context
stringlengths 2.52k
185k
| gt
stringclasses 1
value |
---|---|
//------------------------------------------------------------------------------
// <copyright file="SqlUDTStorage.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">[....]</owner>
// <owner current="true" primary="false">[....]</owner>
// <owner current="false" primary="false">[....]</owner>
//------------------------------------------------------------------------------
namespace System.Data.Common {
using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.Xml;
using System.IO;
using System.Xml.Serialization;
using System.Globalization;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.CompilerServices;
internal sealed class SqlUdtStorage : DataStorage {
private object[] values;
private readonly bool implementsIXmlSerializable = false;
private readonly bool implementsIComparable = false;
private static readonly Dictionary<Type,object> TypeToNull = new Dictionary<Type,object>();
public SqlUdtStorage(DataColumn column, Type type)
: this(column, type, GetStaticNullForUdtType(type)) {
}
private SqlUdtStorage(DataColumn column, Type type, object nullValue)
: base(column, type, nullValue, nullValue, typeof(ICloneable).IsAssignableFrom(type), GetStorageType(type)) {
implementsIXmlSerializable = typeof(IXmlSerializable).IsAssignableFrom(type);
implementsIComparable = typeof(IComparable).IsAssignableFrom(type);
}
// Webdata 104340, to support oracle types and other INUllable types that have static Null as field
internal static object GetStaticNullForUdtType(Type type) {
object value;
if (!TypeToNull.TryGetValue(type, out value)) {
System.Reflection.PropertyInfo propInfo = type.GetProperty("Null", System.Reflection.BindingFlags.Public |System.Reflection.BindingFlags.Static);
if (propInfo != null)
value = propInfo.GetValue(null, null);
else {
System.Reflection.FieldInfo fieldInfo = type.GetField("Null", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static);
if (fieldInfo != null) {
value = fieldInfo.GetValue(null);
}
else {
throw ExceptionBuilder.INullableUDTwithoutStaticNull(type.AssemblyQualifiedName);
}
}
lock(TypeToNull) {
//if(50 < TypeToNull.Count) {
// TypeToNull.Clear();
//}
TypeToNull[type] = value;
}
}
return value;
}
override public bool IsNull(int record) {
return (((INullable)values[record]).IsNull);
}
override public Object Aggregate(int[] records, AggregateType kind) {
throw ExceptionBuilder.AggregateException(kind, DataType);
}
override public int Compare(int recordNo1, int recordNo2) {
return (CompareValueTo(recordNo1, values[recordNo2]));
}
override public int CompareValueTo(int recordNo1, Object value) {
if (DBNull.Value == value) { // it is not meaningful compare UDT with DBNull.Value WebData 113372
value = NullValue;
}
if(implementsIComparable) {
IComparable comparable = (IComparable)values[recordNo1];
return comparable.CompareTo(value);
}
else if (NullValue == value) {
INullable nullableValue = (INullable)values[recordNo1];
return nullableValue.IsNull ? 0 : 1; // left may be null, right is null
}
// else
throw ExceptionBuilder.IComparableNotImplemented(DataType.AssemblyQualifiedName);
}
override public void Copy(int recordNo1, int recordNo2) {
CopyBits(recordNo1, recordNo2);
values[recordNo2] = values[recordNo1];
}
override public Object Get(int recordNo) {
return (values[recordNo]);
}
override public void Set(int recordNo, Object value) {
if (DBNull.Value == value) {
values[recordNo] = NullValue;
SetNullBit(recordNo, true);
}
else if (null == value) {
if (IsValueType) {
throw ExceptionBuilder.StorageSetFailed();
}
else {
values[recordNo] = NullValue;
SetNullBit(recordNo, true);
}
}
else if (!DataType.IsInstanceOfType(value)) {
throw ExceptionBuilder.StorageSetFailed();
}
else { // WebData 113331 do not clone the value
values[recordNo] = value;
SetNullBit(recordNo, false);
}
}
override public void SetCapacity(int capacity) {
object[] newValues = new object[capacity];
if (values != null) {
Array.Copy(values, 0, newValues, 0, Math.Min(capacity, values.Length));
}
values = newValues;
base.SetCapacity(capacity);
}
// Prevent inlining so that reflection calls are not moved to caller that may be in a different assembly that may have a different grant set.
[MethodImpl(MethodImplOptions.NoInlining)]
override public object ConvertXmlToObject(string s) {
if (implementsIXmlSerializable) {
object Obj = System.Activator.CreateInstance (DataType, true);
string tempStr =string.Concat("<col>", s, "</col>"); // this is done since you can give fragmet to reader, bug 98767
StringReader strReader = new StringReader(tempStr);
using (XmlTextReader xmlTextReader = new XmlTextReader(strReader)) {
((IXmlSerializable)Obj).ReadXml(xmlTextReader);
}
return Obj;
}
StringReader strreader = new StringReader(s);
XmlSerializer deserializerWithOutRootAttribute = ObjectStorage.GetXmlSerializer(DataType);
return(deserializerWithOutRootAttribute.Deserialize(strreader));
}
// Prevent inlining so that reflection calls are not moved to caller that may be in a different assembly that may have a different grant set.
[MethodImpl(MethodImplOptions.NoInlining)]
public override object ConvertXmlToObject(XmlReader xmlReader, XmlRootAttribute xmlAttrib) {
if (null == xmlAttrib) {
string typeName = xmlReader.GetAttribute(Keywords.MSD_INSTANCETYPE, Keywords.MSDNS);
if (typeName == null) {
string xsdTypeName = xmlReader.GetAttribute(Keywords.MSD_INSTANCETYPE, Keywords.XSINS); // this xsd type
if (null != xsdTypeName) {
typeName = XSDSchema.XsdtoClr(xsdTypeName).FullName;
}
}
Type type = (typeName == null)? DataType : Type.GetType(typeName);
object Obj = System.Activator.CreateInstance (type, true);
Debug.Assert(xmlReader is DataTextReader, "Invalid DataTextReader is being passed to customer");
((IXmlSerializable)Obj).ReadXml(xmlReader);
return Obj;
}
else{
XmlSerializer deserializerWithRootAttribute = ObjectStorage.GetXmlSerializer(DataType, xmlAttrib);
return(deserializerWithRootAttribute.Deserialize(xmlReader));
}
}
override public string ConvertObjectToXml(object value) {
StringWriter strwriter = new StringWriter(FormatProvider);
if (implementsIXmlSerializable) {
using (XmlTextWriter xmlTextWriter = new XmlTextWriter (strwriter)) {
((IXmlSerializable)value).WriteXml(xmlTextWriter);
}
}
else {
XmlSerializer serializerWithOutRootAttribute = ObjectStorage.GetXmlSerializer(value.GetType());
serializerWithOutRootAttribute.Serialize(strwriter, value);
}
return (strwriter.ToString ());
}
public override void ConvertObjectToXml(object value, XmlWriter xmlWriter, XmlRootAttribute xmlAttrib) {
if (null == xmlAttrib) {
Debug.Assert(xmlWriter is DataTextWriter, "Invalid DataTextWriter is being passed to customer");
((IXmlSerializable)value).WriteXml(xmlWriter);
}
else {
// we support polymorphism only for types that implements IXmlSerializable.
// Assumption: value is the same type as DataType
XmlSerializer serializerWithRootAttribute = ObjectStorage.GetXmlSerializer(DataType, xmlAttrib);
serializerWithRootAttribute.Serialize(xmlWriter, value);
}
}
override protected object GetEmptyStorage(int recordCount) {
return new Object[recordCount];
}
override protected void CopyValue(int record, object store, BitArray nullbits, int storeIndex) {
Object[] typedStore = (Object[]) store;
typedStore[storeIndex] = values[record];
nullbits.Set(storeIndex, IsNull(record));
}
override protected void SetStorage(object store, BitArray nullbits) {
values = (Object[]) store;
//SetNullStorage(nullbits);
}
}
}
| |
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// 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 CommandLine;
using Google.Ads.GoogleAds.Lib;
using Google.Ads.GoogleAds.V10.Common;
using Google.Ads.GoogleAds.V10.Errors;
using Google.Ads.GoogleAds.V10.Resources;
using Google.Ads.GoogleAds.V10.Services;
using Google.Api.Gax;
using Google.LongRunning;
using Google.Protobuf.WellKnownTypes;
using System;
using System.Collections.Generic;
using static Google.Ads.GoogleAds.V10.Enums.AdGroupAdStatusEnum.Types;
using static Google.Ads.GoogleAds.V10.Enums.AdGroupCriterionStatusEnum.Types;
using static Google.Ads.GoogleAds.V10.Enums.AdGroupTypeEnum.Types;
using static Google.Ads.GoogleAds.V10.Enums.AdvertisingChannelTypeEnum.Types;
using static Google.Ads.GoogleAds.V10.Enums.BudgetDeliveryMethodEnum.Types;
using static Google.Ads.GoogleAds.V10.Enums.CampaignStatusEnum.Types;
using static Google.Ads.GoogleAds.V10.Enums.KeywordMatchTypeEnum.Types;
using static Google.Ads.GoogleAds.V10.Resources.BatchJob.Types;
namespace Google.Ads.GoogleAds.Examples.V10
{
/// <summary>
/// This code example adds complete campaigns including campaign budgets, campaigns, ad groups
/// and keywords using BatchJobService.
/// </summary>
public class AddCompleteCampaignsUsingBatchJob : ExampleBase
{
/// <summary>
/// Command line options for running the <see cref="AddCompleteCampaignsUsingBatchJob"/>
/// example.
/// </summary>
public class Options : OptionsBase
{
/// <summary>
/// The Google Ads customer ID for which the call is made.
/// </summary>
[Option("customerId", Required = true, HelpText =
"The Google Ads customer ID for which the call is made.")]
public long CustomerId { get; set; }
}
/// <summary>
/// Main method, to run this code example as a standalone application.
/// </summary>
/// <param name="args">The command line arguments.</param>
public static void Main(string[] args)
{
Options options = new Options();
CommandLine.Parser.Default.ParseArguments<Options>(args).MapResult(
delegate (Options o)
{
options = o;
return 0;
}, delegate (IEnumerable<Error> errors)
{
// The Google Ads customer ID for which the call is made.
options.CustomerId = long.Parse("INSERT_CUSTOMER_ID_HERE");
return 0;
});
AddCompleteCampaignsUsingBatchJob codeExample = new AddCompleteCampaignsUsingBatchJob();
Console.WriteLine(codeExample.Description);
codeExample.Run(new GoogleAdsClient(), options.CustomerId);
}
/// <summary>
/// The number of campaigns to add.
/// </summary>
private const int NUMBER_OF_CAMPAIGNS_TO_ADD = 2;
/// <summary>
/// The number of ad groups per campaign to add.
/// </summary>
private const int NUMBER_OF_AD_GROUPS_TO_ADD = 2;
/// <summary>
/// The number of keywords per ad group to add.
/// </summary>
private const int NUMBER_OF_KEYWORDS_TO_ADD = 4;
/// <summary>
/// The maximum total poll interval in seconds.
/// </summary>
private const int MAX_TOTAL_POLL_INTERVAL_SECONDS = 60;
/// <summary>
/// The page size for retrieving results.
/// </summary>
private const int PAGE_SIZE = 1000;
/// <summary>
/// The negative temporary ID used in batch job operations.
/// </summary>
private static long temporaryId = -1;
/// <summary>
/// Returns a description about the code example.
/// </summary>
public override string Description =>
"This code example adds complete campaigns including campaign budgets, campaigns, " +
"ad groups and keywords using BatchJobService.";
/// <summary>
/// Runs the code example.
/// </summary>
/// <param name="client">The Google Ads client.</param>
/// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
public void Run(GoogleAdsClient client, long customerId)
{
// Gets the BatchJobService.
BatchJobServiceClient batchJobService =
client.GetService(Services.V10.BatchJobService);
try
{
string batchJobResourceName = CreateBatchJob(batchJobService, customerId);
AddAllBatchJobOperations(batchJobService, customerId, batchJobResourceName);
Operation<Empty, BatchJobMetadata> operationResponse =
RunBatchJob(batchJobService, batchJobResourceName);
PollBatchJob(operationResponse);
FetchAndPrintResults(batchJobService, batchJobResourceName);
}
catch (GoogleAdsException e)
{
Console.WriteLine("Failure:");
Console.WriteLine($"Message: {e.Message}");
Console.WriteLine($"Failure: {e.Failure}");
Console.WriteLine($"Request ID: {e.RequestId}");
throw;
}
}
/// <summary>
/// Creates the batch job.
/// </summary>
/// <param name="batchJobService">The batch job service.</param>
/// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
/// <returns>The resource name of the created batch job.</returns>
// [START add_complete_campaigns_using_batch_job]
private static string CreateBatchJob(BatchJobServiceClient batchJobService,
long customerId)
{
BatchJobOperation operation = new BatchJobOperation()
{
Create = new BatchJob()
{
}
};
string batchJobResourceName =
batchJobService.MutateBatchJob(customerId.ToString(), operation)
.Result.ResourceName;
Console.WriteLine($"Created a batch job with resource name: " +
$"'{batchJobResourceName}'.");
return batchJobResourceName;
}
// [END add_complete_campaigns_using_batch_job]
/// <summary>
/// Adds all batch job operations to the batch job. As this is the first time for this
/// batch job, the sequence token is not set. The response will contain the next sequence
/// token that you can use to upload more operations in the future.
/// </summary>
/// <param name="batchJobService">The batch job service.</param>
/// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
/// <param name="batchJobResourceName">The resource name of batch job to which the batch
/// job operations will be added.
/// </param>
// [START add_complete_campaigns_using_batch_job_1]
private static void AddAllBatchJobOperations(BatchJobServiceClient batchJobService,
long customerId, string batchJobResourceName)
{
AddBatchJobOperationsResponse response =
batchJobService.AddBatchJobOperations(
new AddBatchJobOperationsRequest()
{
ResourceName = batchJobResourceName,
MutateOperations = { BuildAllOperations(customerId) }
});
Console.WriteLine($"{response.TotalOperations} mutate operations have been added" +
$" so far.");
// You can use this next sequence token for calling AddBatchJobOperations() next time.
Console.WriteLine($"Next sequence token for adding next operations is " +
$"'{response.NextSequenceToken}'.");
}
// [END add_complete_campaigns_using_batch_job_1]
/// <summary>
/// Requests the API to run the batch job for executing all uploaded batch job
/// operations.
/// </summary>
/// <param name="batchJobService">The batch job service client.</param>
/// <param name="batchJobResourceName">The resource name of batch job to be run.</param>
/// <returns>The operation response from running batch job.</returns>
// [START add_complete_campaigns_using_batch_job_2]
private Operation<Empty, BatchJobMetadata> RunBatchJob(
BatchJobServiceClient batchJobService, string batchJobResourceName)
{
Operation<Empty, BatchJobMetadata> operationResponse =
batchJobService.RunBatchJob(batchJobResourceName);
Console.WriteLine($"Batch job with resource name '{batchJobResourceName}' has been " +
$"executed.");
return operationResponse;
}
// [END add_complete_campaigns_using_batch_job_2]
/// <summary>
/// Polls the server until the batch job execution finishes by setting the total
/// time to wait before time-out.
/// </summary>
/// <param name="operationResponse">The operation response used to poll the server.</param>
// [START add_complete_campaigns_using_batch_job_3]
private static void PollBatchJob(Operation<Empty, BatchJobMetadata> operationResponse)
{
PollSettings pollSettings = new PollSettings(
Expiration.FromTimeout(TimeSpan.FromSeconds(MAX_TOTAL_POLL_INTERVAL_SECONDS)),
TimeSpan.FromSeconds(1));
operationResponse.PollUntilCompleted(pollSettings);
}
// [END add_complete_campaigns_using_batch_job_3]
/// <summary>
/// Fetches and prints all the results from running the batch job.
/// </summary>
/// <param name="batchJobService">The batch job service.</param>
/// <param name="batchJobResourceName">The resource name of batch job to get its results.
/// </param>
// [START add_complete_campaigns_using_batch_job_4]
private static void FetchAndPrintResults(BatchJobServiceClient batchJobService,
string batchJobResourceName)
{
Console.WriteLine($"batch job with resource name '{batchJobResourceName}' has " +
$"finished. Now, printing its results...");
ListBatchJobResultsRequest request = new ListBatchJobResultsRequest()
{
ResourceName = batchJobResourceName,
PageSize = PAGE_SIZE,
};
ListBatchJobResultsResponse resp = new ListBatchJobResultsResponse();
// Gets all the results from running batch job and prints their information.
foreach (BatchJobResult batchJobResult in
batchJobService.ListBatchJobResults(request))
{
if (!batchJobResult.IsFailed)
{
Console.WriteLine($"batch job result #{batchJobResult.OperationIndex} is " +
$"successful and response is of type " +
$"'{batchJobResult.MutateOperationResponse.ResponseCase}'.");
}
else
{
Console.WriteLine($"batch job result #{batchJobResult.OperationIndex} " +
$"failed with error message {batchJobResult.Status.Message}.");
foreach (GoogleAdsError error in batchJobResult.Failure.Errors)
{
Console.WriteLine($"Error found: {error}.");
}
}
}
}
// [END add_complete_campaigns_using_batch_job_4]
/// <summary>
/// Builds all operations for creating a complete campaign and return an array of
/// their corresponding mutate operations.
/// </summary>
/// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
/// <returns>The mutate operations to be added to a batch job.</returns>
private static List<MutateOperation> BuildAllOperations(long customerId)
{
List<MutateOperation> mutateOperations = new List<MutateOperation>();
// Creates a new campaign budget operation and adds it to the array of mutate operations.
CampaignBudgetOperation campaignBudgetOperation =
BuildCampaignBudgetOperation(customerId);
mutateOperations.Add(
new MutateOperation()
{
CampaignBudgetOperation = campaignBudgetOperation
}
);
// Creates new campaign operations and adds them to the array of mutate operations.
List<CampaignOperation> campaignOperations =
BuildCampaignOperations(customerId, campaignBudgetOperation.Create.ResourceName);
foreach (CampaignOperation campaignOperation in campaignOperations)
{
mutateOperations.Add(
new MutateOperation()
{
CampaignOperation = campaignOperation
}
);
}
// Creates new campaign criterion operations and adds them to the array of mutate
// operations.
List<CampaignCriterionOperation> campaignCriterionOperations =
BuildCampaignCriterionOperations(campaignOperations);
foreach (CampaignCriterionOperation campaignCriterionOperation in
campaignCriterionOperations)
{
mutateOperations.Add(
new MutateOperation()
{
CampaignCriterionOperation = campaignCriterionOperation
}
);
}
// Creates new ad group operations and adds them to the array of mutate operations.
List<AdGroupOperation> adGroupOperations = BuildAdGroupOperations(customerId,
campaignOperations);
foreach (AdGroupOperation adGroupOperation in adGroupOperations)
{
mutateOperations.Add(
new MutateOperation()
{
AdGroupOperation = adGroupOperation
}
);
}
// Creates new ad group criterion operations and adds them to the array of mutate
// operations.
List<AdGroupCriterionOperation> adGroupCriterionOperations =
BuildAdGroupCriterionOperations(adGroupOperations);
foreach (AdGroupCriterionOperation adGroupCriterionOperation in
adGroupCriterionOperations)
{
mutateOperations.Add(
new MutateOperation()
{
AdGroupCriterionOperation = adGroupCriterionOperation
}
);
}
// Creates new ad group ad operations and adds them to the array of mutate operations.
List<AdGroupAdOperation> adGroupAdOperations =
BuildAdGroupAdOperations(adGroupOperations);
foreach (AdGroupAdOperation adGroupAdOperation in adGroupAdOperations)
{
mutateOperations.Add(
new MutateOperation()
{
AdGroupAdOperation = adGroupAdOperation
}
);
}
return mutateOperations;
}
/// <summary>
/// Builds a new campaign budget operation for the specified customer ID.
/// </summary>
/// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
/// <returns>The campaign budget operation.</returns>
private static CampaignBudgetOperation BuildCampaignBudgetOperation(long customerId)
{
// Creates a campaign budget.
CampaignBudget budget = new CampaignBudget()
{
ResourceName = ResourceNames.CampaignBudget(customerId, GetNextTemporaryId()),
Name = "batch job Budget #" + ExampleUtilities.GetRandomString(),
DeliveryMethod = BudgetDeliveryMethod.Standard,
AmountMicros = 5_000_000
};
// Creates a campaign budget operation.
return new CampaignBudgetOperation()
{
Create = budget
};
}
/// <summary>
/// Builds new campaign operations for the specified customer ID.
/// </summary>
/// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
/// <param name="campaignBudgetResourceName">The resource name of campaign budget to be
/// used to create campaigns.</param>
/// <returns>The campaign operations.</returns>
private static List<CampaignOperation> BuildCampaignOperations(long customerId,
string campaignBudgetResourceName)
{
List<CampaignOperation> operations = new List<CampaignOperation>();
for (int i = 0; i < NUMBER_OF_CAMPAIGNS_TO_ADD; i++)
{
// Creates a campaign.
long campaignId = GetNextTemporaryId();
Campaign campaign = new Campaign()
{
ResourceName = ResourceNames.Campaign(customerId, campaignId),
Name = "batch job campaign #" + ExampleUtilities.GetRandomString(),
AdvertisingChannelType = AdvertisingChannelType.Search,
// Recommendation: Set the campaign to PAUSED when creating it to prevent
// the ads from immediately serving. Set to ENABLED once you've added
// targeting and the ads are ready to serve.
Status = CampaignStatus.Paused,
// Sets the bidding strategy and budget.
ManualCpc = new ManualCpc(),
CampaignBudget = campaignBudgetResourceName
};
// Creates a campaign operation and adds it to the operations list.
CampaignOperation op = new CampaignOperation()
{
Create = campaign
};
operations.Add(op);
}
return operations;
}
/// <summary>
/// Builds new campaign criterion operations for creating negative campaign criteria
/// (as keywords).
/// </summary>
/// <param name="campaignOperations">The campaign operations to be used to create
/// campaign criteria.</param>
/// <returns>The campaign criterion operations.</returns>
private static List<CampaignCriterionOperation> BuildCampaignCriterionOperations(
List<CampaignOperation> campaignOperations)
{
List<CampaignCriterionOperation> operations =
new List<CampaignCriterionOperation>();
foreach (CampaignOperation campaignOperation in campaignOperations)
{
// Creates a campaign criterion.
CampaignCriterion campaignCriterion = new CampaignCriterion()
{
Keyword = new KeywordInfo()
{
Text = "venus",
MatchType = KeywordMatchType.Broad
},
// Sets the campaign criterion as a negative criterion.
Negative = true,
Campaign = campaignOperation.Create.ResourceName
};
// Creates a campaign criterion operation and adds it to the operations list.
CampaignCriterionOperation op = new CampaignCriterionOperation()
{
Create = campaignCriterion
};
operations.Add(op);
}
return operations;
}
/// <summary>
/// Builds new ad group operations for the specified customer ID.
/// </summary>
/// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
/// <param name="campaignOperations">The campaign operations to be used to create ad
/// groups.</param>
/// <returns>The ad group operations.</returns>
private static List<AdGroupOperation> BuildAdGroupOperations(
long customerId, List<CampaignOperation> campaignOperations)
{
List<AdGroupOperation> operations = new List<AdGroupOperation>();
foreach (CampaignOperation campaignOperation in campaignOperations)
{
for (int i = 0; i < NUMBER_OF_AD_GROUPS_TO_ADD; i++)
{
// Creates an ad group.
long adGroupId = GetNextTemporaryId();
AdGroup adGroup = new AdGroup()
{
ResourceName = ResourceNames.AdGroup(customerId, adGroupId),
Name = "batch job ad group #" + ExampleUtilities.GetShortRandomString(),
Campaign = campaignOperation.Create.ResourceName,
Type = AdGroupType.SearchStandard,
CpcBidMicros = 10_000_000
};
// Creates an ad group operation and adds it to the operations list.
AdGroupOperation op = new AdGroupOperation()
{
Create = adGroup
};
operations.Add(op);
}
}
return operations;
}
/// <summary>
/// Builds new ad group criterion operations for creating keywords. 50% of keywords are
/// created some invalid characters to demonstrate how BatchJobService returns information
/// about such errors.
/// </summary>
/// <param name="adGroupOperations">The ad group operations to be used to create ad group
/// criteria.</param>
/// <returns>The ad group criterion operations.</returns>
private static List<AdGroupCriterionOperation> BuildAdGroupCriterionOperations(
List<AdGroupOperation> adGroupOperations)
{
List<AdGroupCriterionOperation> operations = new List<AdGroupCriterionOperation>();
foreach (AdGroupOperation adGroupOperation in adGroupOperations)
{
for (int i = 0; i < NUMBER_OF_KEYWORDS_TO_ADD; i++)
{
// Creates a keyword text by making 50% of keywords invalid to demonstrate
// error handling.
string keywordText = "mars" + i;
if (i % 2 == 0)
{
keywordText += "!!!";
}
// Creates an ad group criterion using the created keyword text.
AdGroupCriterion adGroupCriterion = new AdGroupCriterion()
{
Keyword = new KeywordInfo()
{
Text = keywordText,
MatchType = KeywordMatchType.Broad,
},
AdGroup = adGroupOperation.Create.ResourceName,
Status = AdGroupCriterionStatus.Paused
};
// Creates an ad group criterion operation and adds it to the operations list.
AdGroupCriterionOperation op = new AdGroupCriterionOperation()
{
Create = adGroupCriterion
};
operations.Add(op);
}
}
return operations;
}
/// <summary>
/// Builds the ad group ad operations.
/// </summary>
/// <param name="adGroupOperations">The ad group operations to be used to create ad
/// group ads.</param>
/// <returns>The ad group ad operations.</returns>
private static List<AdGroupAdOperation> BuildAdGroupAdOperations(
List<AdGroupOperation> adGroupOperations)
{
List<AdGroupAdOperation> operations = new List<AdGroupAdOperation>();
foreach (AdGroupOperation adGroupOperation in adGroupOperations)
{
// Creates an ad group ad.
AdGroupAd adGroupAd = new AdGroupAd()
{
Ad = new Ad
{
FinalUrls = { "http://www.example.com/" },
// Sets the expanded text ad info on an ad.
ExpandedTextAd = new ExpandedTextAdInfo
{
HeadlinePart1 = "Cruise #" + ExampleUtilities.GetShortRandomString() +
" to Mars",
HeadlinePart2 = "Best Space Cruise Line",
Description = "Buy your tickets now!",
},
},
AdGroup = adGroupOperation.Create.ResourceName,
// Optional: Set the status.
Status = AdGroupAdStatus.Paused,
};
// Creates an ad group ad operation and adds it to the operations list.
AdGroupAdOperation op = new AdGroupAdOperation()
{
Create = adGroupAd
};
operations.Add(op);
}
return operations;
}
/// <summary>
/// Returns the next temporary ID and decreases it by one.
/// </summary>
/// <returns>The next temporary ID.</returns>
private static long GetNextTemporaryId()
{
return temporaryId--;
}
}
}
| |
/*
* Copyright (c) Citrix Systems, 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:
*
* 1) Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2) Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using Newtonsoft.Json;
namespace XenAPI
{
/// <summary>
/// LVHD SR specific operations
/// First published in XenServer 7.0.
/// </summary>
public partial class LVHD : XenObject<LVHD>
{
#region Constructors
public LVHD()
{
}
public LVHD(string uuid)
{
this.uuid = uuid;
}
/// <summary>
/// Creates a new LVHD from a Hashtable.
/// Note that the fields not contained in the Hashtable
/// will be created with their default values.
/// </summary>
/// <param name="table"></param>
public LVHD(Hashtable table)
: this()
{
UpdateFrom(table);
}
/// <summary>
/// Creates a new LVHD from a Proxy_LVHD.
/// </summary>
/// <param name="proxy"></param>
public LVHD(Proxy_LVHD proxy)
{
UpdateFrom(proxy);
}
#endregion
/// <summary>
/// Updates each field of this instance with the value of
/// the corresponding field of a given LVHD.
/// </summary>
public override void UpdateFrom(LVHD update)
{
uuid = update.uuid;
}
internal void UpdateFrom(Proxy_LVHD proxy)
{
uuid = proxy.uuid == null ? null : proxy.uuid;
}
public Proxy_LVHD ToProxy()
{
Proxy_LVHD result_ = new Proxy_LVHD();
result_.uuid = uuid ?? "";
return result_;
}
/// <summary>
/// Given a Hashtable with field-value pairs, it updates the fields of this LVHD
/// with the values listed in the Hashtable. Note that only the fields contained
/// in the Hashtable will be updated and the rest will remain the same.
/// </summary>
/// <param name="table"></param>
public void UpdateFrom(Hashtable table)
{
if (table.ContainsKey("uuid"))
uuid = Marshalling.ParseString(table, "uuid");
}
public bool DeepEquals(LVHD other)
{
if (ReferenceEquals(null, other))
return false;
if (ReferenceEquals(this, other))
return true;
return Helper.AreEqual2(this._uuid, other._uuid);
}
internal static List<LVHD> ProxyArrayToObjectList(Proxy_LVHD[] input)
{
var result = new List<LVHD>();
foreach (var item in input)
result.Add(new LVHD(item));
return result;
}
public override string SaveChanges(Session session, string opaqueRef, LVHD server)
{
if (opaqueRef == null)
{
System.Diagnostics.Debug.Assert(false, "Cannot create instances of this type on the server");
return "";
}
else
{
throw new InvalidOperationException("This type has no read/write properties");
}
}
/// <summary>
/// Get a record containing the current state of the given LVHD.
/// First published in XenServer 7.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_lvhd">The opaque_ref of the given lvhd</param>
public static LVHD get_record(Session session, string _lvhd)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.lvhd_get_record(session.opaque_ref, _lvhd);
else
return new LVHD(session.XmlRpcProxy.lvhd_get_record(session.opaque_ref, _lvhd ?? "").parse());
}
/// <summary>
/// Get a reference to the LVHD instance with the specified UUID.
/// First published in XenServer 7.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_uuid">UUID of object to return</param>
public static XenRef<LVHD> get_by_uuid(Session session, string _uuid)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.lvhd_get_by_uuid(session.opaque_ref, _uuid);
else
return XenRef<LVHD>.Create(session.XmlRpcProxy.lvhd_get_by_uuid(session.opaque_ref, _uuid ?? "").parse());
}
/// <summary>
/// Get the uuid field of the given LVHD.
/// First published in XenServer 7.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_lvhd">The opaque_ref of the given lvhd</param>
public static string get_uuid(Session session, string _lvhd)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.lvhd_get_uuid(session.opaque_ref, _lvhd);
else
return session.XmlRpcProxy.lvhd_get_uuid(session.opaque_ref, _lvhd ?? "").parse();
}
/// <summary>
/// Upgrades an LVHD SR to enable thin-provisioning. Future VDIs created in this SR will be thinly-provisioned, although existing VDIs will be left alone. Note that the SR must be attached to the SRmaster for upgrade to work.
/// First published in XenServer 7.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The LVHD Host to upgrade to being thin-provisioned.</param>
/// <param name="_sr">The LVHD SR to upgrade to being thin-provisioned.</param>
/// <param name="_initial_allocation">The initial amount of space to allocate to a newly-created VDI in bytes</param>
/// <param name="_allocation_quantum">The amount of space to allocate to a VDI when it needs to be enlarged in bytes</param>
public static string enable_thin_provisioning(Session session, string _host, string _sr, long _initial_allocation, long _allocation_quantum)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.lvhd_enable_thin_provisioning(session.opaque_ref, _host, _sr, _initial_allocation, _allocation_quantum);
else
return session.XmlRpcProxy.lvhd_enable_thin_provisioning(session.opaque_ref, _host ?? "", _sr ?? "", _initial_allocation.ToString(), _allocation_quantum.ToString()).parse();
}
/// <summary>
/// Upgrades an LVHD SR to enable thin-provisioning. Future VDIs created in this SR will be thinly-provisioned, although existing VDIs will be left alone. Note that the SR must be attached to the SRmaster for upgrade to work.
/// First published in XenServer 7.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The LVHD Host to upgrade to being thin-provisioned.</param>
/// <param name="_sr">The LVHD SR to upgrade to being thin-provisioned.</param>
/// <param name="_initial_allocation">The initial amount of space to allocate to a newly-created VDI in bytes</param>
/// <param name="_allocation_quantum">The amount of space to allocate to a VDI when it needs to be enlarged in bytes</param>
public static XenRef<Task> async_enable_thin_provisioning(Session session, string _host, string _sr, long _initial_allocation, long _allocation_quantum)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_lvhd_enable_thin_provisioning(session.opaque_ref, _host, _sr, _initial_allocation, _allocation_quantum);
else
return XenRef<Task>.Create(session.XmlRpcProxy.async_lvhd_enable_thin_provisioning(session.opaque_ref, _host ?? "", _sr ?? "", _initial_allocation.ToString(), _allocation_quantum.ToString()).parse());
}
/// <summary>
/// Unique identifier/object reference
/// </summary>
public virtual string uuid
{
get { return _uuid; }
set
{
if (!Helper.AreEqual(value, _uuid))
{
_uuid = value;
NotifyPropertyChanged("uuid");
}
}
}
private string _uuid = "";
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
// Used only for WRITE_LOCK_NAME in deprecated create=true case:
using IndexFileNameFilter = Lucene.Net.Index.IndexFileNameFilter;
using IndexWriter = Lucene.Net.Index.IndexWriter;
using Constants = Lucene.Net.Util.Constants;
namespace Lucene.Net.Store
{
/// <summary> <a name="subclasses"/>
/// Base class for Directory implementations that store index
/// files in the file system. There are currently three core
/// subclasses:
///
/// <ul>
///
/// <li> {@link SimpleFSDirectory} is a straightforward
/// implementation using java.io.RandomAccessFile.
/// However, it has poor concurrent performance
/// (multiple threads will bottleneck) as it
/// synchronizes when multiple threads read from the
/// same file.</li>
///
/// <li> {@link NIOFSDirectory} uses java.nio's
/// FileChannel's positional io when reading to avoid
/// synchronization when reading from the same file.
/// Unfortunately, due to a Windows-only <a
/// href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6265734">Sun
/// JRE bug</a> this is a poor choice for Windows, but
/// on all other platforms this is the preferred
/// choice. Applications using {@link Thread#interrupt()} or
/// <code>Future#cancel(boolean)</code> (on Java 1.5) should use
/// {@link SimpleFSDirectory} instead. See {@link NIOFSDirectory} java doc
/// for details.
///
///
///
/// <li> {@link MMapDirectory} uses memory-mapped IO when
/// reading. This is a good choice if you have plenty
/// of virtual memory relative to your index size, eg
/// if you are running on a 64 bit JRE, or you are
/// running on a 32 bit JRE but your index sizes are
/// small enough to fit into the virtual memory space.
/// Java has currently the limitation of not being able to
/// unmap files from user code. The files are unmapped, when GC
/// releases the byte buffers. Due to
/// <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4724038">
/// this bug</a> in Sun's JRE, MMapDirectory's {@link IndexInput#close}
/// is unable to close the underlying OS file handle. Only when
/// GC finally collects the underlying objects, which could be
/// quite some time later, will the file handle be closed.
/// This will consume additional transient disk usage: on Windows,
/// attempts to delete or overwrite the files will result in an
/// exception; on other platforms, which typically have a "delete on
/// last close" semantics, while such operations will succeed, the bytes
/// are still consuming space on disk. For many applications this
/// limitation is not a problem (e.g. if you have plenty of disk space,
/// and you don't rely on overwriting files on Windows) but it's still
/// an important limitation to be aware of. This class supplies a
/// (possibly dangerous) workaround mentioned in the bug report,
/// which may fail on non-Sun JVMs.</li>
///
/// Applications using {@link Thread#interrupt()} or
/// <code>Future#cancel(boolean)</code> (on Java 1.5) should use
/// {@link SimpleFSDirectory} instead. See {@link MMapDirectory}
/// java doc for details.
/// </ul>
///
/// Unfortunately, because of system peculiarities, there is
/// no single overall best implementation. Therefore, we've
/// added the {@link #open} method, to allow Lucene to choose
/// the best FSDirectory implementation given your
/// environment, and the known limitations of each
/// implementation. For users who have no reason to prefer a
/// specific implementation, it's best to simply use {@link
/// #open}. For all others, you should instantiate the
/// desired implementation directly.
///
/// <p/>The locking implementation is by default {@link
/// NativeFSLockFactory}, but can be changed by
/// passing in a custom {@link LockFactory} instance.
/// The deprecated <code>getDirectory</code> methods default to use
/// {@link SimpleFSLockFactory} for backwards compatibility.
/// The system properties
/// <code>org.apache.lucene.store.FSDirectoryLockFactoryClass</code>
/// and <code>org.apache.lucene.FSDirectory.class</code>
/// are deprecated and only used by the deprecated
/// <code>getDirectory</code> methods. The system property
/// <code>org.apache.lucene.lockDir</code> is ignored completely,
/// If you really want to store locks
/// elsewhere, you can create your own {@link
/// SimpleFSLockFactory} (or {@link NativeFSLockFactory},
/// etc.) passing in your preferred lock directory.
///
/// <p/><em>In 3.0 this class will become abstract.</em>
///
/// </summary>
/// <seealso cref="Directory">
/// </seealso>
// TODO: in 3.0 this will become an abstract base class
public class FSDirectory:Directory
{
/// <summary>This cache of directories ensures that there is a unique Directory
/// instance per path, so that synchronization on the Directory can be used to
/// synchronize access between readers and writers. We use
/// refcounts to ensure when the last use of an FSDirectory
/// instance for a given canonical path is closed, we remove the
/// instance from the cache. See LUCENE-776
/// for some relevant discussion.
/// </summary>
/// <deprecated> Not used by any non-deprecated methods anymore
/// </deprecated>
[Obsolete("Not used by any non-deprecated methods anymore")]
private static readonly Dictionary<string, FSDirectory> DIRECTORIES = new Dictionary<string, FSDirectory>();
private static bool disableLocks = false;
// TODO: should this move up to the Directory base class? Also: should we
// make a per-instance (in addition to the static "default") version?
/// <summary> Set whether Lucene's use of lock files is disabled. By default,
/// lock files are enabled. They should only be disabled if the index
/// is on a read-only medium like a CD-ROM.
/// </summary>
/// <deprecated> Use a {@link #open(File, LockFactory)} or a constructor
/// that takes a {@link LockFactory} and supply
/// {@link NoLockFactory#getNoLockFactory}. This setting does not work
/// with {@link #open(File)} only the deprecated <code>getDirectory</code>
/// respect this setting.
/// </deprecated>
[Obsolete("Use a Open(File, LockFactory) or a constructor that takes a LockFactory and supply NoLockFactory.GetNoLockFactory. This setting does not work with Open(File) only the deprecated GetDirectory respect this setting.")]
public static void SetDisableLocks(bool doDisableLocks)
{
FSDirectory.disableLocks = doDisableLocks;
}
/// <summary> Returns whether Lucene's use of lock files is disabled.</summary>
/// <returns> true if locks are disabled, false if locks are enabled.
/// </returns>
/// <seealso cref="setDisableLocks">
/// </seealso>
/// <deprecated> Use a constructor that takes a {@link LockFactory} and
/// supply {@link NoLockFactory#getNoLockFactory}.
/// </deprecated>
[Obsolete("Use a constructor that takes a LockFactory and supply NoLockFactory.GetNoLockFactory.")]
public static bool GetDisableLocks()
{
return FSDirectory.disableLocks;
}
/// <summary> Directory specified by <code>org.apache.lucene.lockDir</code>
/// or <code>java.io.tmpdir</code> system property.
/// </summary>
/// <deprecated> As of 2.1, <code>LOCK_DIR</code> is unused
/// because the write.lock is now stored by default in the
/// index directory. If you really want to store locks
/// elsewhere, you can create your own {@link
/// SimpleFSLockFactory} (or {@link NativeFSLockFactory},
/// etc.) passing in your preferred lock directory. Then,
/// pass this <code>LockFactory</code> instance to one of
/// the <code>open</code> methods that take a
/// <code>lockFactory</code> (for example, {@link #open(File, LockFactory)}).
/// </deprecated>
//[Obsolete("As of 2.1, LOCK_DIR is unused because the write.lock is now stored by default in the index directory. ")]
//public static readonly System.String LOCK_DIR = SupportClass.AppSettings.Get("Lucene.Net.lockDir", System.IO.Path.GetTempPath());
/// <summary>The default class which implements filesystem-based directories. </summary>
// deprecated
[Obsolete]
private static readonly System.Type IMPL = typeof(Lucene.Net.Store.SimpleFSDirectory);
private static System.Security.Cryptography.HashAlgorithm DIGESTER;
/// <summary>A buffer optionally used in renameTo method </summary>
private byte[] buffer = null;
/// <summary>Returns the directory instance for the named location.
///
/// </summary>
/// <deprecated> Use {@link #Open(File)}
///
/// </deprecated>
/// <param name="path">the path to the directory.
/// </param>
/// <returns> the FSDirectory for the named file.
/// </returns>
[Obsolete("Use Open(File)")]
public static FSDirectory GetDirectory(System.String path)
{
return GetDirectory(new System.IO.DirectoryInfo(path), null);
}
/// <summary>Returns the directory instance for the named location.
///
/// </summary>
/// <deprecated> Use {@link #Open(File, LockFactory)}
///
/// </deprecated>
/// <param name="path">the path to the directory.
/// </param>
/// <param name="lockFactory">instance of {@link LockFactory} providing the
/// locking implementation.
/// </param>
/// <returns> the FSDirectory for the named file.
/// </returns>
[Obsolete("Use Open(File, LockFactory)")]
public static FSDirectory GetDirectory(System.String path, LockFactory lockFactory)
{
return GetDirectory(new System.IO.DirectoryInfo(path), lockFactory);
}
/// <summary>Returns the directory instance for the named location.
///
/// </summary>
/// <deprecated> Use {@link #Open(File)}
///
/// </deprecated>
/// <param name="file">the path to the directory.
/// </param>
/// <returns> the FSDirectory for the named file.
/// </returns>
[Obsolete("Use Open(File)")]
public static FSDirectory GetDirectory(System.IO.DirectoryInfo file)
{
return GetDirectory(file, null);
}
/// <summary>Returns the directory instance for the named location.
///
/// </summary>
/// <deprecated> Use {@link #Open(File)}
///
/// </deprecated>
/// <param name="file">the path to the directory.
/// </param>
/// <returns> the FSDirectory for the named file.
/// </returns>
[System.Obsolete("Use the constructor that takes a DirectoryInfo, this will be removed in the 3.0 release")]
public static FSDirectory GetDirectory(System.IO.FileInfo file)
{
return GetDirectory(new System.IO.DirectoryInfo(file.FullName), null);
}
/// <summary>Returns the directory instance for the named location.
///
/// </summary>
/// <deprecated> Use {@link #Open(File, LockFactory)}
///
/// </deprecated>
/// <param name="file">the path to the directory.
/// </param>
/// <param name="lockFactory">instance of {@link LockFactory} providing the
/// locking implementation.
/// </param>
/// <returns> the FSDirectory for the named file.
/// </returns>
[System.Obsolete("Use the constructor that takes a DirectoryInfo, this will be removed in the 3.0 release")]
public static FSDirectory GetDirectory(System.IO.FileInfo file, LockFactory lockFactory)
{
return GetDirectory(new System.IO.DirectoryInfo(file.FullName), lockFactory);
}
/// <summary>Returns the directory instance for the named location.
///
/// </summary>
/// <deprecated> Use {@link #Open(File, LockFactory)}
///
/// </deprecated>
/// <param name="file">the path to the directory.
/// </param>
/// <param name="lockFactory">instance of {@link LockFactory} providing the
/// locking implementation.
/// </param>
/// <returns> the FSDirectory for the named file.
/// </returns>
[Obsolete("Use Open(File, LockFactory)")]
public static FSDirectory GetDirectory(System.IO.DirectoryInfo file, LockFactory lockFactory)
{
FSDirectory dir;
lock (DIRECTORIES)
{
if(!DIRECTORIES.TryGetValue(file.FullName, out dir))
{
try
{
dir = (FSDirectory)System.Activator.CreateInstance(IMPL, true);
}
catch (System.Exception e)
{
throw new System.SystemException("cannot load FSDirectory class: " + e.ToString(), e);
}
dir.Init(file, lockFactory);
DIRECTORIES.Add(file.FullName, dir);
}
else
{
// Catch the case where a Directory is pulled from the cache, but has a
// different LockFactory instance.
if (lockFactory != null && lockFactory != dir.GetLockFactory())
{
throw new System.IO.IOException("Directory was previously created with a different LockFactory instance; please pass null as the lockFactory instance and use setLockFactory to change it");
}
dir.checked_Renamed = false;
}
}
lock (dir)
{
dir.refCount++;
}
return dir;
}
/// <summary>Returns the directory instance for the named location.
///
/// </summary>
/// <deprecated> Use IndexWriter's create flag, instead, to
/// create a new index.
///
/// </deprecated>
/// <param name="path">the path to the directory.
/// </param>
/// <param name="create">if true, create, or erase any existing contents.
/// </param>
/// <returns> the FSDirectory for the named file.
/// </returns>
[Obsolete("Use IndexWriter's create flag, instead, to create a new index.")]
public static FSDirectory GetDirectory(System.String path, bool create)
{
return GetDirectory(new System.IO.DirectoryInfo(path), create);
}
/// <summary>Returns the directory instance for the named location.
///
/// </summary>
/// <deprecated> Use IndexWriter's create flag, instead, to
/// create a new index.
///
/// </deprecated>
/// <param name="file">the path to the directory.
/// </param>
/// <param name="create">if true, create, or erase any existing contents.
/// </param>
/// <returns> the FSDirectory for the named file.
/// </returns>
[System.Obsolete("Use the method that takes a DirectoryInfo, this will be removed in the 3.0 release")]
public static FSDirectory GetDirectory(System.IO.FileInfo file, bool create)
{
return GetDirectory(new System.IO.DirectoryInfo(file.FullName), create);
}
/// <summary>Returns the directory instance for the named location.
///
/// </summary>
/// <deprecated> Use IndexWriter's create flag, instead, to
/// create a new index.
///
/// </deprecated>
/// <param name="file">the path to the directory.
/// </param>
/// <param name="create">if true, create, or erase any existing contents.
/// </param>
/// <returns> the FSDirectory for the named file.
/// </returns>
[Obsolete("Use IndexWriter's create flag, instead, to create a new index.")]
public static FSDirectory GetDirectory(System.IO.DirectoryInfo file, bool create)
{
FSDirectory dir = GetDirectory(file, null);
// This is now deprecated (creation should only be done
// by IndexWriter):
if (create)
{
dir.Create();
}
return dir;
}
/// <deprecated>
/// </deprecated>
[Obsolete]
private void Create()
{
if (directory.Exists)
{
System.String[] files = SupportClass.FileSupport.GetLuceneIndexFiles(directory.FullName, IndexFileNameFilter.GetFilter()); // clear old files
if (files == null)
throw new System.IO.IOException("cannot read directory " + directory.FullName + ": list() returned null");
for (int i = 0; i < files.Length; i++)
{
System.String fileOrDir = System.IO.Path.Combine(directory.FullName, files[i]);
if (System.IO.File.Exists(fileOrDir))
{
System.IO.File.Delete(fileOrDir);
}
else if (System.IO.Directory.Exists(fileOrDir))
{
System.IO.Directory.Delete(fileOrDir);
}
// no need to throw anything - if a delete fails the exc will propogate to the caller
}
}
lockFactory.ClearLock(IndexWriter.WRITE_LOCK_NAME);
}
private bool checked_Renamed;
internal void CreateDir()
{
if (!checked_Renamed)
{
if (!this.directory.Exists)
{
try
{
this.directory.Create();
}
catch (Exception)
{
throw new System.IO.IOException("Cannot create directory: " + directory);
}
this.directory.Refresh(); // need to see the creation
}
checked_Renamed = true;
}
}
/// <summary>Initializes the directory to create a new file with the given name.
/// This method should be used in {@link #createOutput}.
/// </summary>
protected internal void InitOutput(System.String name)
{
EnsureOpen();
CreateDir();
System.IO.FileInfo file = new System.IO.FileInfo(System.IO.Path.Combine(directory.FullName, name));
if (file.Exists) // delete existing, if any
{
try
{
file.Delete();
}
catch (Exception)
{
throw new System.IO.IOException("Cannot overwrite: " + file);
}
}
}
/// <summary>The underlying filesystem directory </summary>
protected internal System.IO.DirectoryInfo directory = null;
/// <deprecated>
/// </deprecated>
[Obsolete]
private int refCount = 0;
/// <deprecated>
/// </deprecated>
[Obsolete]
protected internal FSDirectory()
{
}
// permit subclassing
/// <summary>Create a new FSDirectory for the named location (ctor for subclasses).</summary>
/// <param name="path">the path of the directory
/// </param>
/// <param name="lockFactory">the lock factory to use, or null for the default
/// ({@link NativeFSLockFactory});
/// </param>
/// <throws> IOException </throws>
protected internal FSDirectory(System.IO.DirectoryInfo path, LockFactory lockFactory)
{
// new ctors use always NativeFSLockFactory as default:
if (lockFactory == null)
{
lockFactory = new NativeFSLockFactory();
}
Init(path, lockFactory);
refCount = 1;
}
/// <summary>Creates an FSDirectory instance, trying to pick the
/// best implementation given the current environment.
/// The directory returned uses the {@link NativeFSLockFactory}.
///
/// <p/>Currently this returns {@link SimpleFSDirectory} as
/// NIOFSDirectory is currently not supported.
///
/// <p/>Currently this returns {@link SimpleFSDirectory} as
/// NIOFSDirectory is currently not supported.
///
/// <p/><b>NOTE</b>: this method may suddenly change which
/// implementation is returned from release to release, in
/// the event that higher performance defaults become
/// possible; if the precise implementation is important to
/// your application, please instantiate it directly,
/// instead. On 64 bit systems, it may also good to
/// return {@link MMapDirectory}, but this is disabled
/// because of officially missing unmap support in Java.
/// For optimal performance you should consider using
/// this implementation on 64 bit JVMs.
///
/// <p/>See <a href="#subclasses">above</a>
/// </summary>
[System.Obsolete("Use the method that takes a DirectoryInfo, this will be removed in the 3.0 release")]
public static FSDirectory Open(System.IO.FileInfo path)
{
System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(path.FullName);
return Open(dir, null);
}
/// <summary>Creates an FSDirectory instance, trying to pick the
/// best implementation given the current environment.
/// The directory returned uses the {@link NativeFSLockFactory}.
///
/// <p/>Currently this returns {@link SimpleFSDirectory} as
/// NIOFSDirectory is currently not supported.
///
/// <p/><b>NOTE</b>: this method may suddenly change which
/// implementation is returned from release to release, in
/// the event that higher performance defaults become
/// possible; if the precise implementation is important to
/// your application, please instantiate it directly,
/// instead. On 64 bit systems, it may also good to
/// return {@link MMapDirectory}, but this is disabled
/// because of officially missing unmap support in Java.
/// For optimal performance you should consider using
/// this implementation on 64 bit JVMs.
///
/// <p/>See <a href="#subclasses">above</a>
/// </summary>
public static FSDirectory Open(System.IO.DirectoryInfo path)
{
return Open(path, null);
}
/// <summary>Just like {@link #Open(File)}, but allows you to
/// also specify a custom {@link LockFactory}.
/// </summary>
public static FSDirectory Open(System.IO.DirectoryInfo path, LockFactory lockFactory)
{
/* For testing:
MMapDirectory dir=new MMapDirectory(path, lockFactory);
dir.setUseUnmap(true);
return dir;
*/
if (Constants.WINDOWS)
{
return new SimpleFSDirectory(path, lockFactory);
}
else
{
//NIOFSDirectory is not implemented in Lucene.Net
//return new NIOFSDirectory(path, lockFactory);
return new SimpleFSDirectory(path, lockFactory);
}
}
/* will move to ctor, when reflection is removed in 3.0 */
private void Init(System.IO.DirectoryInfo path, LockFactory lockFactory)
{
// Set up lockFactory with cascaded defaults: if an instance was passed in,
// use that; else if locks are disabled, use NoLockFactory; else if the
// system property Lucene.Net.Store.FSDirectoryLockFactoryClass is set,
// instantiate that; else, use SimpleFSLockFactory:
directory = path;
// due to differences in how Java & .NET refer to files, the checks are a bit different
if (!directory.Exists && System.IO.File.Exists(directory.FullName))
{
throw new NoSuchDirectoryException("file '" + directory.FullName + "' exists but is not a directory");
}
if (lockFactory == null)
{
if (disableLocks)
{
// Locks are disabled:
lockFactory = NoLockFactory.GetNoLockFactory();
}
else
{
System.String lockClassName = SupportClass.AppSettings.Get("Lucene.Net.Store.FSDirectoryLockFactoryClass", "");
if (lockClassName != null && !lockClassName.Equals(""))
{
System.Type c;
try
{
c = System.Type.GetType(lockClassName);
}
catch (System.Exception e)
{
throw new System.IO.IOException("unable to find LockClass " + lockClassName);
}
try
{
lockFactory = (LockFactory) System.Activator.CreateInstance(c, true);
}
catch (System.UnauthorizedAccessException e)
{
throw new System.IO.IOException("IllegalAccessException when instantiating LockClass " + lockClassName);
}
catch (System.InvalidCastException e)
{
throw new System.IO.IOException("unable to cast LockClass " + lockClassName + " instance to a LockFactory");
}
catch (System.Exception e)
{
throw new System.IO.IOException("InstantiationException when instantiating LockClass " + lockClassName);
}
}
else
{
// Our default lock is SimpleFSLockFactory;
// default lockDir is our index directory:
lockFactory = new SimpleFSLockFactory();
}
}
}
SetLockFactory(lockFactory);
// for filesystem based LockFactory, delete the lockPrefix, if the locks are placed
// in index dir. If no index dir is given, set ourselves
if (lockFactory is FSLockFactory)
{
FSLockFactory lf = (FSLockFactory) lockFactory;
System.IO.DirectoryInfo dir = lf.GetLockDir();
// if the lock factory has no lockDir set, use the this directory as lockDir
if (dir == null)
{
lf.SetLockDir(this.directory);
lf.SetLockPrefix(null);
}
else if (dir.FullName.Equals(this.directory.FullName))
{
lf.SetLockPrefix(null);
}
}
}
/// <summary>Lists all files (not subdirectories) in the
/// directory. This method never returns null (throws
/// {@link IOException} instead).
///
/// </summary>
/// <throws> NoSuchDirectoryException if the directory </throws>
/// <summary> does not exist, or does exist but is not a
/// directory.
/// </summary>
/// <throws> IOException if list() returns null </throws>
[System.Obsolete("Use the method that takes a DirectoryInfo, this will be removed in the 3.0 release")]
public static System.String[] ListAll(System.IO.FileInfo dir)
{
return ListAll(new System.IO.DirectoryInfo(dir.FullName));
}
/// <summary>Lists all files (not subdirectories) in the
/// directory. This method never returns null (throws
/// {@link IOException} instead).
///
/// </summary>
/// <throws> NoSuchDirectoryException if the directory </throws>
/// <summary> does not exist, or does exist but is not a
/// directory.
/// </summary>
/// <throws> IOException if list() returns null </throws>
public static System.String[] ListAll(System.IO.DirectoryInfo dir)
{
if (!dir.Exists)
{
throw new NoSuchDirectoryException("directory '" + dir.FullName + "' does not exist");
}
// Exclude subdirs, only the file names, not the paths
System.IO.FileInfo[] files = dir.GetFiles();
System.String[] result = new System.String[files.Length];
for (int i = 0; i < files.Length; i++)
{
result[i] = files[i].Name;
}
// no reason to return null, if the directory cannot be listed, an exception
// will be thrown on the above call to dir.GetFiles()
// use of LINQ to create the return value array may be a bit more efficient
return result;
}
[Obsolete("Lucene.Net-2.9.1. This method overrides obsolete member Lucene.Net.Store.Directory.List()")]
public override System.String[] List()
{
EnsureOpen();
return SupportClass.FileSupport.GetLuceneIndexFiles(directory.FullName, IndexFileNameFilter.GetFilter());
}
/// <summary>Lists all files (not subdirectories) in the
/// directory.
/// </summary>
/// <seealso cref="ListAll(File)">
/// </seealso>
public override System.String[] ListAll()
{
EnsureOpen();
return ListAll(directory);
}
/// <summary>Returns true iff a file with the given name exists. </summary>
public override bool FileExists(System.String name)
{
EnsureOpen();
System.IO.FileInfo file = new System.IO.FileInfo(System.IO.Path.Combine(directory.FullName, name));
return file.Exists;
}
/// <summary>Returns the time the named file was last modified. </summary>
public override long FileModified(System.String name)
{
EnsureOpen();
System.IO.FileInfo file = new System.IO.FileInfo(System.IO.Path.Combine(directory.FullName, name));
return (long)file.LastWriteTime.ToUniversalTime().Subtract(new DateTime(1970, 1, 1, 0, 0, 0)).TotalMilliseconds; //{{LUCENENET-353}}
}
/// <summary>Returns the time the named file was last modified. </summary>
public static long FileModified(System.IO.FileInfo directory, System.String name)
{
System.IO.FileInfo file = new System.IO.FileInfo(System.IO.Path.Combine(directory.FullName, name));
return (long)file.LastWriteTime.ToUniversalTime().Subtract(new DateTime(1970, 1, 1, 0, 0, 0)).TotalMilliseconds; //{{LUCENENET-353}}
}
/// <summary>Set the modified time of an existing file to now. </summary>
public override void TouchFile(System.String name)
{
EnsureOpen();
System.IO.FileInfo file = new System.IO.FileInfo(System.IO.Path.Combine(directory.FullName, name));
file.LastWriteTime = System.DateTime.Now;
}
/// <summary>Returns the length in bytes of a file in the directory. </summary>
public override long FileLength(System.String name)
{
EnsureOpen();
System.IO.FileInfo file = new System.IO.FileInfo(System.IO.Path.Combine(directory.FullName, name));
return file.Exists ? file.Length : 0;
}
/// <summary>Removes an existing file in the directory. </summary>
public override void DeleteFile(System.String name)
{
EnsureOpen();
System.IO.FileInfo file = new System.IO.FileInfo(System.IO.Path.Combine(directory.FullName, name));
try
{
file.Delete();
}
catch (Exception)
{
throw new System.IO.IOException("Cannot delete " + file);
}
}
/// <summary>Renames an existing file in the directory.
/// Warning: This is not atomic.
/// </summary>
/// <deprecated>
/// </deprecated>
[Obsolete]
public override void RenameFile(System.String from, System.String to)
{
lock (this)
{
EnsureOpen();
System.IO.FileInfo old = new System.IO.FileInfo(System.IO.Path.Combine(directory.FullName, from));
try
{
old.MoveTo(System.IO.Path.Combine(directory.FullName, to));
}
catch (System.IO.IOException ioe)
{
System.IO.IOException newExc = new System.IO.IOException("Cannot rename " + old + " to " + directory, ioe);
throw newExc;
}
}
}
/// <summary>Creates an IndexOutput for the file with the given name.
/// <em>In 3.0 this method will become abstract.</em>
/// </summary>
public override IndexOutput CreateOutput(System.String name)
{
InitOutput(name);
return new FSIndexOutput(new System.IO.FileInfo(System.IO.Path.Combine(directory.FullName, name)));
}
public override void Sync(System.String name)
{
EnsureOpen();
System.IO.FileInfo fullFile = new System.IO.FileInfo(System.IO.Path.Combine(directory.FullName, name));
bool success = false;
int retryCount = 0;
System.IO.IOException exc = null;
while (!success && retryCount < 5)
{
retryCount++;
System.IO.FileStream file = null;
try
{
try
{
file = new System.IO.FileStream(fullFile.FullName, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write, System.IO.FileShare.ReadWrite);
SupportClass.FileSupport.Sync(file);
success = true;
}
finally
{
if (file != null)
file.Close();
}
}
catch (System.IO.IOException ioe)
{
if (exc == null)
exc = ioe;
try
{
// Pause 5 msec
System.Threading.Thread.Sleep(new System.TimeSpan((System.Int64) 10000 * 5));
}
catch (System.Threading.ThreadInterruptedException ie)
{
// In 3.0 we will change this to throw
// InterruptedException instead
SupportClass.ThreadClass.Current().Interrupt();
throw new System.SystemException(ie.ToString(), ie);
}
}
}
if (!success)
// Throw original exception
throw exc;
}
// Inherit javadoc
public override IndexInput OpenInput(System.String name)
{
EnsureOpen();
return OpenInput(name, BufferedIndexInput.BUFFER_SIZE);
}
/// <summary>Creates an IndexInput for the file with the given name.
/// <em>In 3.0 this method will become abstract.</em>
/// </summary>
public override IndexInput OpenInput(System.String name, int bufferSize)
{
EnsureOpen();
return new FSIndexInput(new System.IO.FileInfo(System.IO.Path.Combine(directory.FullName, name)), bufferSize);
}
/// <summary> So we can do some byte-to-hexchar conversion below</summary>
private static readonly char[] HEX_DIGITS = new char[]{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
public override System.String GetLockID()
{
EnsureOpen();
System.String dirName; // name to be hashed
try
{
dirName = directory.FullName;
}
catch (System.IO.IOException e)
{
throw new System.SystemException(e.ToString(), e);
}
byte[] digest;
lock (DIGESTER)
{
digest = DIGESTER.ComputeHash(System.Text.Encoding.UTF8.GetBytes(dirName));
}
System.Text.StringBuilder buf = new System.Text.StringBuilder();
buf.Append("lucene-");
for (int i = 0; i < digest.Length; i++)
{
int b = digest[i];
buf.Append(HEX_DIGITS[(b >> 4) & 0xf]);
buf.Append(HEX_DIGITS[b & 0xf]);
}
return buf.ToString();
}
/// <summary>Closes the store to future operations. </summary>
public override void Close()
{
lock (this)
{
if (isOpen && --refCount <= 0)
{
isOpen = false;
lock (DIRECTORIES)
{
DIRECTORIES.Remove(directory.FullName);
}
}
}
}
/// <summary>
/// .NET
/// </summary>
public override void Dispose()
{
Close();
}
[System.Obsolete("A DirectoryInfo is more appropriate, however this is here for backwards compatibility. This will be removed in the 3.0 release")]
public virtual System.IO.FileInfo GetFile()
{
EnsureOpen();
return new System.IO.FileInfo(directory.FullName);
}
// Java Lucene implements GetFile() which returns a FileInfo.
// For Lucene.Net, GetDirectory() is more appropriate
public virtual System.IO.DirectoryInfo GetDirectory()
{
EnsureOpen();
return directory;
}
/// <summary>For debug output. </summary>
public override System.String ToString()
{
return this.GetType().FullName + "@" + directory + " lockFactory=" + GetLockFactory();
}
/// <summary> Default read chunk size. This is a conditional
/// default: on 32bit JVMs, it defaults to 100 MB. On
/// 64bit JVMs, it's <code>Integer.MAX_VALUE</code>.
/// </summary>
/// <seealso cref="setReadChunkSize">
/// </seealso>
public static readonly int DEFAULT_READ_CHUNK_SIZE;
// LUCENE-1566
private int chunkSize = DEFAULT_READ_CHUNK_SIZE;
/// <summary> Sets the maximum number of bytes read at once from the
/// underlying file during {@link IndexInput#readBytes}.
/// The default value is {@link #DEFAULT_READ_CHUNK_SIZE};
///
/// <p/> This was introduced due to <a
/// href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6478546">Sun
/// JVM Bug 6478546</a>, which throws an incorrect
/// OutOfMemoryError when attempting to read too many bytes
/// at once. It only happens on 32bit JVMs with a large
/// maximum heap size.<p/>
///
/// <p/>Changes to this value will not impact any
/// already-opened {@link IndexInput}s. You should call
/// this before attempting to open an index on the
/// directory.<p/>
///
/// <p/> <b>NOTE</b>: This value should be as large as
/// possible to reduce any possible performance impact. If
/// you still encounter an incorrect OutOfMemoryError,
/// trying lowering the chunk size.<p/>
/// </summary>
public void SetReadChunkSize(int chunkSize)
{
// LUCENE-1566
if (chunkSize <= 0)
{
throw new System.ArgumentException("chunkSize must be positive");
}
if (!Constants.JRE_IS_64BIT)
{
this.chunkSize = chunkSize;
}
}
/// <summary> The maximum number of bytes to read at once from the
/// underlying file during {@link IndexInput#readBytes}.
/// </summary>
/// <seealso cref="setReadChunkSize">
/// </seealso>
public int GetReadChunkSize()
{
// LUCENE-1566
return chunkSize;
}
/// <deprecated> Use SimpleFSDirectory.SimpleFSIndexInput instead
/// </deprecated>
[Obsolete("Use SimpleFSDirectory.SimpleFSIndexInput instead ")]
public /*protected internal*/ class FSIndexInput:SimpleFSDirectory.SimpleFSIndexInput
{
/// <deprecated>
/// </deprecated>
[Obsolete]
new protected internal class Descriptor:SimpleFSDirectory.SimpleFSIndexInput.Descriptor
{
/// <deprecated>
/// </deprecated>
[Obsolete]
public Descriptor(/*FSIndexInput enclosingInstance,*/ System.IO.FileInfo file, System.IO.FileAccess mode) : base(file, mode)
{
}
}
/// <deprecated>
/// </deprecated>
[Obsolete]
public FSIndexInput(System.IO.FileInfo path):base(path)
{
}
/// <deprecated>
/// </deprecated>
[Obsolete]
public FSIndexInput(System.IO.FileInfo path, int bufferSize):base(path, bufferSize)
{
}
}
/// <deprecated> Use SimpleFSDirectory.SimpleFSIndexOutput instead
/// </deprecated>
[Obsolete("Use SimpleFSDirectory.SimpleFSIndexOutput instead ")]
protected internal class FSIndexOutput:SimpleFSDirectory.SimpleFSIndexOutput
{
/// <deprecated>
/// </deprecated>
[Obsolete]
public FSIndexOutput(System.IO.FileInfo path):base(path)
{
}
}
static FSDirectory()
{
{
try
{
System.String name = SupportClass.AppSettings.Get("Lucene.Net.FSDirectory.class", typeof(SimpleFSDirectory).FullName);
if (typeof(FSDirectory).FullName.Equals(name))
{
// FSDirectory will be abstract, so we replace it by the correct class
IMPL = typeof(SimpleFSDirectory);
}
else
{
IMPL = System.Type.GetType(name);
}
}
catch (System.Security.SecurityException se)
{
IMPL = typeof(SimpleFSDirectory);
}
catch (System.Exception e)
{
throw new System.SystemException("cannot load FSDirectory class: " + e.ToString(), e);
}
}
{
try
{
DIGESTER = SupportClass.Cryptography.GetHashAlgorithm();
}
catch (System.Exception e)
{
throw new System.SystemException(e.ToString(), e);
}
}
DEFAULT_READ_CHUNK_SIZE = Constants.JRE_IS_64BIT?System.Int32.MaxValue:100 * 1024 * 1024;
}
}
}
| |
#region License
// Copyright 2009 The Sixth Form College Farnborough (http://www.farnborough.ac.uk)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// The latest version of this file can be found at http://github.com/JeremySkinner/SagePayMvc
#endregion
using System;
using System.Collections.Specialized;
using System.Configuration;
using System.Globalization;
using System.Linq.Expressions;
namespace SagePayMvc {
/// <summary>
/// Configuration data
/// </summary>
public class Configuration {
public static CultureInfo CultureForTransactionEncoding = new CultureInfo("en-gb");
public const string ProtocolVersion = "3.0";
public const string DefaultControllerName = "PaymentResponse";
public const string DefaultFailedAction = "Failed";
public const string DefaultSuccessAction = "Success";
public const decimal DefaultVatMultiplier = 1.2m;
public const string DefaultResponseAction = "Index";
public const string LiveUrl = "https://live.sagepay.com/gateway/service/vspserver-register.vsp";
public const string TestUrl = "https://test.sagepay.com/gateway/service/vspserver-register.vsp";
public const string SimulatorUrl = "https://test.sagepay.com/simulator/VSPServerGateway.asp?Service=VendorRegisterTx";
public const string LiveRefundUrl = "https://live.sagepay.com/gateway/service/refund.vsp";
public const string TestRefundUrl = "https://test.sagepay.com/gateway/service/refund.vsp";
public const string SimulatorRefundUrl = "https://test.sagepay.com/simulator/vspserverGateway.asp?Service=VendorRefundTx";
string notificationController = DefaultControllerName;
string notificationAction = DefaultResponseAction;
string successAction = DefaultSuccessAction;
string failedAction = DefaultFailedAction;
string successController = DefaultControllerName;
string failedController = DefaultControllerName;
decimal vatMultiplier = DefaultVatMultiplier;
string protocol = "http";
string vendorName;
string notificationHostName;
/// <summary>
/// The Protocol to use (http or https). Default is http.
/// </summary>
public string Protocol {
get { return protocol; }
set {
if (!string.IsNullOrEmpty(value)) {
if(value != "http" && value != "https")
{
throw new NotSupportedException("Protocol '{0}' is not supported. Allowed values are http or https");
}
protocol = value;
}
}
}
/// <summary>
/// Vendor name. This is required.
/// </summary>
public string VendorName {
get {
if (string.IsNullOrEmpty(vendorName)) {
throw new ArgumentNullException("vendorName", "VendorName must be specified in the configuration.");
}
return vendorName;
}
set {
if (string.IsNullOrEmpty(value)) {
throw new ArgumentNullException("value", "VendorName must be specified in the configuration.");
}
vendorName = value;
}
}
/// <summary>
/// Notification host name. This is required.
/// </summary>
public string NotificationHostName {
get {
if (string.IsNullOrEmpty(notificationHostName)) {
throw new ArgumentNullException("notificationHostName", "NotificationHostName must be specified in the configuration.");
}
return notificationHostName;
}
set {
if (string.IsNullOrEmpty(value)) {
throw new ArgumentNullException("value", "NotificationHostName must be specified in the configuration.");
}
notificationHostName = value;
}
}
/// <summary>
/// Server mode (simulator, test, live)
/// </summary>
public VspServerMode Mode { get; set; }
/// <summary>
/// The controller name to use when when generating the notification url. Default is "PaymentResponse".
/// </summary>
public string NotificationController {
get { return notificationController; }
set {
if (!string.IsNullOrEmpty(value)) {
notificationController = value;
}
}
}
/// <summary>
/// Action name to use when generating the notification url. Default is "Index"
/// </summary>
public string NotificationAction {
get { return notificationAction; }
set {
if (!string.IsNullOrEmpty(value)) {
notificationAction = value;
}
}
}
/// <summary>
/// Action name to use when generating the success URL. Default is "Success"
/// </summary>
public string SuccessAction {
get { return successAction; }
set {
if (!string.IsNullOrEmpty(value))
successAction = value;
}
}
/// <summary>
/// Action name to use when generating the failure url. Defualt is "Failed"
/// </summary>
public string FailedAction {
get { return failedAction; }
set {
if (!string.IsNullOrEmpty(value))
failedAction = value;
}
}
/// <summary>
/// Controller name to use when generating the success URL. Default is "PaymentResponse"
/// </summary>
public string SuccessController {
get { return successController; }
set {
if (!string.IsNullOrEmpty(value))
successController = value;
}
}
/// <summary>
/// Controller name to use when generating the failed URL. Default is "PaymentResponse"
/// </summary>
public string FailedController {
get { return failedController; }
set {
if (!string.IsNullOrEmpty(value))
failedController = value;
}
}
/// <summary>
/// VAT multiplier. Default is 1.15.
/// </summary>
public decimal VatMultiplier {
get { return vatMultiplier; }
set {
if (value > 0) {
vatMultiplier = value;
}
}
}
static Configuration currentConfiguration;
/// <summary>
/// Sets up the configuration using a manually generated Configuration instance rather than using the Web.config file.
/// </summary>
/// <param name="configuration"></param>
public static void Configure(Configuration configuration) {
currentConfiguration = configuration;
}
/// <summary>
/// Gets the current configuration. If none has been specified using Configuration.Configure, it is loaded from the web.config
/// </summary>
public static Configuration Current {
get {
if (currentConfiguration == null) {
currentConfiguration = LoadConfigurationFromConfigFile();
}
return currentConfiguration;
}
}
/// <summary>
/// The registration URL
/// </summary>
public string RegistrationUrl {
get {
switch (Mode) {
case VspServerMode.Simulator:
return SimulatorUrl;
case VspServerMode.Test:
return TestUrl;
case VspServerMode.Live:
return LiveUrl;
}
return null;
}
}
public string RefundUrl {
get {
switch (Mode) {
case VspServerMode.Simulator:
return SimulatorRefundUrl;
case VspServerMode.Test:
return TestRefundUrl;
case VspServerMode.Live:
return LiveRefundUrl;
}
return null;
}
}
static Configuration LoadConfigurationFromConfigFile() {
var section = ConfigurationManager.GetSection("sagePay") as NameValueCollection;
if (section == null) {
return new Configuration();
}
var configuration = new Configuration {
NotificationHostName = GetValue(x => x.NotificationHostName, section),
NotificationController = GetValue(x => x.NotificationController, section),
notificationAction = GetValue(x => x.NotificationAction, section),
SuccessAction = GetValue(x => x.SuccessAction, section),
FailedAction = GetValue(x => x.FailedAction, section),
SuccessController = GetValue(x => x.SuccessController, section),
FailedController = GetValue(x => x.FailedController, section),
Protocol = GetValue(x => x.Protocol, section),
VatMultiplier = Convert.ToDecimal(GetValue(x => x.VatMultiplier, section) ?? "0", CultureInfo.InvariantCulture),
VendorName = GetValue(x => x.VendorName, section),
Mode = (VspServerMode) Enum.Parse(typeof (VspServerMode), (GetValue(x => x.Mode, section) ?? "Simulator"))
};
return configuration;
}
static string GetValue(Expression<Func<Configuration, object>> expression, NameValueCollection collection) {
var body = expression.Body as MemberExpression;
if (body == null && expression.Body is UnaryExpression) {
body = ((UnaryExpression) expression.Body).Operand as MemberExpression;
}
string name = body.Member.Name;
return collection[name];
}
}
}
| |
#region Apache License
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to you under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
// MONO 1.0 Beta mcs does not like #if !A && !B && !C syntax
// .NET Compact Framework 1.0 has no support for EventLog
#if !NETCF
// SSCLI 1.0 has no support for EventLog
#if !SSCLI
using System;
using System.Diagnostics;
using System.Globalization;
using Ctrip.Util;
using Ctrip.Layout;
using Ctrip.Core;
namespace Ctrip.Appender
{
/// <summary>
/// Writes events to the system event log.
/// </summary>
/// <remarks>
/// <para>
/// The appender will fail if you try to write using an event source that doesn't exist unless it is running with local administrator privileges.
/// See also http://logging.apache.org/Ctrip/release/faq.html#trouble-EventLog
/// </para>
/// <para>
/// The <c>EventID</c> of the event log entry can be
/// set using the <c>EventID</c> property (<see cref="LoggingEvent.Properties"/>)
/// on the <see cref="LoggingEvent"/>.
/// </para>
/// <para>
/// The <c>Category</c> of the event log entry can be
/// set using the <c>Category</c> property (<see cref="LoggingEvent.Properties"/>)
/// on the <see cref="LoggingEvent"/>.
/// </para>
/// <para>
/// There is a limit of 32K characters for an event log message
/// </para>
/// <para>
/// When configuring the EventLogAppender a mapping can be
/// specified to map a logging level to an event log entry type. For example:
/// </para>
/// <code lang="XML">
/// <mapping>
/// <level value="ERROR" />
/// <eventLogEntryType value="Error" />
/// </mapping>
/// <mapping>
/// <level value="DEBUG" />
/// <eventLogEntryType value="Information" />
/// </mapping>
/// </code>
/// <para>
/// The Level is the standard Ctrip logging level and eventLogEntryType can be any value
/// from the <see cref="EventLogEntryType"/> enum, i.e.:
/// <list type="bullet">
/// <item><term>Error</term><description>an error event</description></item>
/// <item><term>Warning</term><description>a warning event</description></item>
/// <item><term>Information</term><description>an informational event</description></item>
/// </list>
/// </para>
/// </remarks>
/// <author>Aspi Havewala</author>
/// <author>Douglas de la Torre</author>
/// <author>Nicko Cadell</author>
/// <author>Gert Driesen</author>
/// <author>Thomas Voss</author>
public class EventLogAppender : AppenderSkeleton
{
#region Public Instance Constructors
/// <summary>
/// Initializes a new instance of the <see cref="EventLogAppender" /> class.
/// </summary>
/// <remarks>
/// <para>
/// Default constructor.
/// </para>
/// </remarks>
public EventLogAppender()
{
m_applicationName = System.Threading.Thread.GetDomain().FriendlyName;
m_logName = "Application"; // Defaults to application log
m_machineName = "."; // Only log on the local machine
}
/// <summary>
/// Initializes a new instance of the <see cref="EventLogAppender" /> class
/// with the specified <see cref="ILayout" />.
/// </summary>
/// <param name="layout">The <see cref="ILayout" /> to use with this appender.</param>
/// <remarks>
/// <para>
/// Obsolete constructor.
/// </para>
/// </remarks>
[Obsolete("Instead use the default constructor and set the Layout property")]
public EventLogAppender(ILayout layout) : this()
{
Layout = layout;
}
#endregion // Public Instance Constructors
#region Public Instance Properties
/// <summary>
/// The name of the log where messages will be stored.
/// </summary>
/// <value>
/// The string name of the log where messages will be stored.
/// </value>
/// <remarks>
/// <para>This is the name of the log as it appears in the Event Viewer
/// tree. The default value is to log into the <c>Application</c>
/// log, this is where most applications write their events. However
/// if you need a separate log for your application (or applications)
/// then you should set the <see cref="LogName"/> appropriately.</para>
/// <para>This should not be used to distinguish your event log messages
/// from those of other applications, the <see cref="ApplicationName"/>
/// property should be used to distinguish events. This property should be
/// used to group together events into a single log.
/// </para>
/// </remarks>
public string LogName
{
get { return m_logName; }
set { m_logName = value; }
}
/// <summary>
/// Property used to set the Application name. This appears in the
/// event logs when logging.
/// </summary>
/// <value>
/// The string used to distinguish events from different sources.
/// </value>
/// <remarks>
/// Sets the event log source property.
/// </remarks>
public string ApplicationName
{
get { return m_applicationName; }
set { m_applicationName = value; }
}
/// <summary>
/// This property is used to return the name of the computer to use
/// when accessing the event logs. Currently, this is the current
/// computer, denoted by a dot "."
/// </summary>
/// <value>
/// The string name of the machine holding the event log that
/// will be logged into.
/// </value>
/// <remarks>
/// This property cannot be changed. It is currently set to '.'
/// i.e. the local machine. This may be changed in future.
/// </remarks>
public string MachineName
{
get { return m_machineName; }
set { /* Currently we do not allow the machine name to be changed */; }
}
/// <summary>
/// Add a mapping of level to <see cref="EventLogEntryType"/> - done by the config file
/// </summary>
/// <param name="mapping">The mapping to add</param>
/// <remarks>
/// <para>
/// Add a <see cref="Level2EventLogEntryType"/> mapping to this appender.
/// Each mapping defines the event log entry type for a level.
/// </para>
/// </remarks>
public void AddMapping(Level2EventLogEntryType mapping)
{
m_levelMapping.Add(mapping);
}
/// <summary>
/// Gets or sets the <see cref="SecurityContext"/> used to write to the EventLog.
/// </summary>
/// <value>
/// The <see cref="SecurityContext"/> used to write to the EventLog.
/// </value>
/// <remarks>
/// <para>
/// The system security context used to write to the EventLog.
/// </para>
/// <para>
/// Unless a <see cref="SecurityContext"/> specified here for this appender
/// the <see cref="SecurityContextProvider.DefaultProvider"/> is queried for the
/// security context to use. The default behavior is to use the security context
/// of the current thread.
/// </para>
/// </remarks>
public SecurityContext SecurityContext
{
get { return m_securityContext; }
set { m_securityContext = value; }
}
/// <summary>
/// Gets or sets the <c>EventId</c> to use unless one is explicitly specified via the <c>LoggingEvent</c>'s properties.
/// </summary>
/// <remarks>
/// <para>
/// The <c>EventID</c> of the event log entry will normally be
/// set using the <c>EventID</c> property (<see cref="LoggingEvent.Properties"/>)
/// on the <see cref="LoggingEvent"/>.
/// This property provides the fallback value which defaults to 0.
/// </para>
/// </remarks>
public int EventId {
get { return m_eventId; }
set { m_eventId = value; }
}
/// <summary>
/// Gets or sets the <c>Category</c> to use unless one is explicitly specified via the <c>LoggingEvent</c>'s properties.
/// </summary>
/// <remarks>
/// <para>
/// The <c>Category</c> of the event log entry will normally be
/// set using the <c>Category</c> property (<see cref="LoggingEvent.Properties"/>)
/// on the <see cref="LoggingEvent"/>.
/// This property provides the fallback value which defaults to 0.
/// </para>
/// </remarks>
public short Category
{
get { return m_category; }
set { m_category = value; }
}
#endregion // Public Instance Properties
#region Implementation of IOptionHandler
/// <summary>
/// Initialize the appender based on the options set
/// </summary>
/// <remarks>
/// <para>
/// This is part of the <see cref="IOptionHandler"/> delayed object
/// activation scheme. The <see cref="ActivateOptions"/> method must
/// be called on this object after the configuration properties have
/// been set. Until <see cref="ActivateOptions"/> is called this
/// object is in an undefined state and must not be used.
/// </para>
/// <para>
/// If any of the configuration properties are modified then
/// <see cref="ActivateOptions"/> must be called again.
/// </para>
/// </remarks>
override public void ActivateOptions()
{
try
{
base.ActivateOptions();
if (m_securityContext == null)
{
m_securityContext = SecurityContextProvider.DefaultProvider.CreateSecurityContext(this);
}
bool sourceAlreadyExists = false;
string currentLogName = null;
using (SecurityContext.Impersonate(this))
{
sourceAlreadyExists = EventLog.SourceExists(m_applicationName);
if (sourceAlreadyExists) {
currentLogName = EventLog.LogNameFromSourceName(m_applicationName, m_machineName);
}
}
if (sourceAlreadyExists && currentLogName != m_logName)
{
LogLog.Debug(declaringType, "Changing event source [" + m_applicationName + "] from log [" + currentLogName + "] to log [" + m_logName + "]");
}
else if (!sourceAlreadyExists)
{
LogLog.Debug(declaringType, "Creating event source Source [" + m_applicationName + "] in log " + m_logName + "]");
}
string registeredLogName = null;
using (SecurityContext.Impersonate(this))
{
if (sourceAlreadyExists && currentLogName != m_logName)
{
//
// Re-register this to the current application if the user has changed
// the application / logfile association
//
EventLog.DeleteEventSource(m_applicationName, m_machineName);
CreateEventSource(m_applicationName, m_logName, m_machineName);
registeredLogName = EventLog.LogNameFromSourceName(m_applicationName, m_machineName);
}
else if (!sourceAlreadyExists)
{
CreateEventSource(m_applicationName, m_logName, m_machineName);
registeredLogName = EventLog.LogNameFromSourceName(m_applicationName, m_machineName);
}
}
m_levelMapping.ActivateOptions();
LogLog.Debug(declaringType, "Source [" + m_applicationName + "] is registered to log [" + registeredLogName + "]");
}
catch (System.Security.SecurityException ex)
{
ErrorHandler.Error("Caught a SecurityException trying to access the EventLog. Most likely the event source "
+ m_applicationName
+ " doesn't exist and must be created by a local administrator. Will disable EventLogAppender."
+ " See http://logging.apache.org/Ctrip/release/faq.html#trouble-EventLog",
ex);
Threshold = Level.Off;
}
}
#endregion // Implementation of IOptionHandler
/// <summary>
/// Create an event log source
/// </summary>
/// <remarks>
/// Uses different API calls under NET_2_0
/// </remarks>
private static void CreateEventSource(string source, string logName, string machineName)
{
#if NET_2_0
EventSourceCreationData eventSourceCreationData = new EventSourceCreationData(source, logName);
eventSourceCreationData.MachineName = machineName;
EventLog.CreateEventSource(eventSourceCreationData);
#else
EventLog.CreateEventSource(source, logName, machineName);
#endif
}
#region Override implementation of AppenderSkeleton
/// <summary>
/// This method is called by the <see cref="M:AppenderSkeleton.DoAppend(LoggingEvent)"/>
/// method.
/// </summary>
/// <param name="loggingEvent">the event to log</param>
/// <remarks>
/// <para>Writes the event to the system event log using the
/// <see cref="ApplicationName"/>.</para>
///
/// <para>If the event has an <c>EventID</c> property (see <see cref="LoggingEvent.Properties"/>)
/// set then this integer will be used as the event log event id.</para>
///
/// <para>
/// There is a limit of 32K characters for an event log message
/// </para>
/// </remarks>
override protected void Append(LoggingEvent loggingEvent)
{
//
// Write the resulting string to the event log system
//
int eventID = m_eventId;
// Look for the EventID property
object eventIDPropertyObj = loggingEvent.LookupProperty("EventID");
if (eventIDPropertyObj != null)
{
if (eventIDPropertyObj is int)
{
eventID = (int)eventIDPropertyObj;
}
else
{
string eventIDPropertyString = eventIDPropertyObj as string;
if (eventIDPropertyString == null)
{
eventIDPropertyString = eventIDPropertyObj.ToString();
}
if (eventIDPropertyString != null && eventIDPropertyString.Length > 0)
{
// Read the string property into a number
int intVal;
if (SystemInfo.TryParse(eventIDPropertyString, out intVal))
{
eventID = intVal;
}
else
{
ErrorHandler.Error("Unable to parse event ID property [" + eventIDPropertyString + "].");
}
}
}
}
short category = m_category;
// Look for the Category property
object categoryPropertyObj = loggingEvent.LookupProperty("Category");
if (categoryPropertyObj != null)
{
if (categoryPropertyObj is short)
{
category = (short) categoryPropertyObj;
}
else
{
string categoryPropertyString = categoryPropertyObj as string;
if (categoryPropertyString == null)
{
categoryPropertyString = categoryPropertyObj.ToString();
}
if (categoryPropertyString != null && categoryPropertyString.Length > 0)
{
// Read the string property into a number
short shortVal;
if (SystemInfo.TryParse(categoryPropertyString, out shortVal))
{
category = shortVal;
}
else
{
ErrorHandler.Error("Unable to parse event category property [" + categoryPropertyString + "].");
}
}
}
}
// Write to the event log
try
{
string eventTxt = RenderLoggingEvent(loggingEvent);
// There is a limit of 32K characters for an event log message
if (eventTxt.Length > 32000)
{
eventTxt = eventTxt.Substring(0, 32000);
}
EventLogEntryType entryType = GetEntryType(loggingEvent.Level);
using(SecurityContext.Impersonate(this))
{
EventLog.WriteEntry(m_applicationName, eventTxt, entryType, eventID, category);
}
}
catch(Exception ex)
{
ErrorHandler.Error("Unable to write to event log [" + m_logName + "] using source [" + m_applicationName + "]", ex);
}
}
/// <summary>
/// This appender requires a <see cref="Layout"/> to be set.
/// </summary>
/// <value><c>true</c></value>
/// <remarks>
/// <para>
/// This appender requires a <see cref="Layout"/> to be set.
/// </para>
/// </remarks>
override protected bool RequiresLayout
{
get { return true; }
}
#endregion // Override implementation of AppenderSkeleton
#region Protected Instance Methods
/// <summary>
/// Get the equivalent <see cref="EventLogEntryType"/> for a <see cref="Level"/> <paramref name="level"/>
/// </summary>
/// <param name="level">the Level to convert to an EventLogEntryType</param>
/// <returns>The equivalent <see cref="EventLogEntryType"/> for a <see cref="Level"/> <paramref name="level"/></returns>
/// <remarks>
/// Because there are fewer applicable <see cref="EventLogEntryType"/>
/// values to use in logging levels than there are in the
/// <see cref="Level"/> this is a one way mapping. There is
/// a loss of information during the conversion.
/// </remarks>
virtual protected EventLogEntryType GetEntryType(Level level)
{
// see if there is a specified lookup.
Level2EventLogEntryType entryType = m_levelMapping.Lookup(level) as Level2EventLogEntryType;
if (entryType != null)
{
return entryType.EventLogEntryType;
}
// Use default behavior
if (level >= Level.Error)
{
return EventLogEntryType.Error;
}
else if (level == Level.Warn)
{
return EventLogEntryType.Warning;
}
// Default setting
return EventLogEntryType.Information;
}
#endregion // Protected Instance Methods
#region Private Instance Fields
/// <summary>
/// The log name is the section in the event logs where the messages
/// are stored.
/// </summary>
private string m_logName;
/// <summary>
/// Name of the application to use when logging. This appears in the
/// application column of the event log named by <see cref="m_logName"/>.
/// </summary>
private string m_applicationName;
/// <summary>
/// The name of the machine which holds the event log. This is
/// currently only allowed to be '.' i.e. the current machine.
/// </summary>
private string m_machineName;
/// <summary>
/// Mapping from level object to EventLogEntryType
/// </summary>
private LevelMapping m_levelMapping = new LevelMapping();
/// <summary>
/// The security context to use for privileged calls
/// </summary>
private SecurityContext m_securityContext;
/// <summary>
/// The event ID to use unless one is explicitly specified via the <c>LoggingEvent</c>'s properties.
/// </summary>
private int m_eventId = 0;
/// <summary>
/// The event category to use unless one is explicitly specified via the <c>LoggingEvent</c>'s properties.
/// </summary>
private short m_category = 0;
#endregion // Private Instance Fields
#region Level2EventLogEntryType LevelMapping Entry
/// <summary>
/// A class to act as a mapping between the level that a logging call is made at and
/// the color it should be displayed as.
/// </summary>
/// <remarks>
/// <para>
/// Defines the mapping between a level and its event log entry type.
/// </para>
/// </remarks>
public class Level2EventLogEntryType : LevelMappingEntry
{
private EventLogEntryType m_entryType;
/// <summary>
/// The <see cref="EventLogEntryType"/> for this entry
/// </summary>
/// <remarks>
/// <para>
/// Required property.
/// The <see cref="EventLogEntryType"/> for this entry
/// </para>
/// </remarks>
public EventLogEntryType EventLogEntryType
{
get { return m_entryType; }
set { m_entryType = value; }
}
}
#endregion // LevelColors LevelMapping Entry
#region Private Static Fields
/// <summary>
/// The fully qualified type of the EventLogAppender class.
/// </summary>
/// <remarks>
/// Used by the internal logger to record the Type of the
/// log message.
/// </remarks>
private readonly static Type declaringType = typeof(EventLogAppender);
#endregion Private Static Fields
}
}
#endif // !SSCLI
#endif // !NETCF
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace MultiTenantAccountManager.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
/*
* Copyright (c) 2007-2011 Erin Catto http://www.box2d.org
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
// Limit:
// C = norm(pB - pA) - L
// u = (pB - pA) / norm(pB - pA)
// Cdot = dot(u, vB + cross(wB, rB) - vA - cross(wA, rA))
// J = [-u -cross(rA, u) u cross(rB, u)]
// K = J * invM * JT
// = invMassA + invIA * cross(rA, u)^2 + invMassB + invIB * cross(rB, u)^2
using System;
using System.Diagnostics;
using Box2D.Common;
namespace Box2D.Dynamics.Joints
{
/// A rope joint enforces a maximum distance between two points
/// on two bodies. It has no other effect.
/// Warning: if you attempt to change the maximum length during
/// the simulation you will get some non-physical behavior.
/// A model that would allow you to dynamically modify the length
/// would have some sponginess, so I chose not to implement it
/// that way. See b2DistanceJoint if you want to dynamically
/// control length.
public class b2RopeJoint : b2Joint
{
// Solver shared
protected b2Vec2 m_localAnchorA;
protected b2Vec2 m_localAnchorB;
protected float m_maxLength;
protected float m_length;
protected float m_impulse;
// Solver temp
protected int m_indexA;
protected int m_indexB;
protected b2Vec2 m_u;
protected b2Vec2 m_rA;
protected b2Vec2 m_rB;
protected b2Vec2 m_localCenterA;
protected b2Vec2 m_localCenterB;
protected float m_invMassA;
protected float m_invMassB;
protected float m_invIA;
protected float m_invIB;
protected float m_mass;
protected b2LimitState m_state;
/// The local anchor point relative to bodyA's origin.
public b2Vec2 GetLocalAnchorA() { return m_localAnchorA; }
/// The local anchor point relative to bodyB's origin.
public b2Vec2 GetLocalAnchorB() { return m_localAnchorB; }
/// Set/Get the maximum length of the rope.
public void SetMaxLength(float length) { m_maxLength = length; }
public b2RopeJoint(b2RopeJointDef def)
: base(def)
{
m_localAnchorA = def.localAnchorA;
m_localAnchorB = def.localAnchorB;
m_maxLength = def.maxLength;
m_mass = 0.0f;
m_impulse = 0.0f;
m_state = b2LimitState.e_inactiveLimit;
m_length = 0.0f;
}
public override void InitVelocityConstraints(b2SolverData data)
{
m_indexA = m_bodyA.IslandIndex;
m_indexB = m_bodyB.IslandIndex;
m_localCenterA = m_bodyA.Sweep.localCenter;
m_localCenterB = m_bodyB.Sweep.localCenter;
m_invMassA = m_bodyA.InvertedMass;
m_invMassB = m_bodyB.InvertedMass;
m_invIA = m_bodyA.InvertedI;
m_invIB = m_bodyB.InvertedI;
b2Vec2 cA = m_bodyA.InternalPosition.c;
float aA = m_bodyA.InternalPosition.a;
b2Vec2 vA = m_bodyA.InternalVelocity.v;
float wA = m_bodyA.InternalVelocity.w;
b2Vec2 cB = m_bodyB.InternalPosition.c;
float aB = m_bodyB.InternalPosition.a;
b2Vec2 vB = m_bodyB.InternalVelocity.v;
float wB = m_bodyB.InternalVelocity.w;
b2Rot qA = new b2Rot(aA);
b2Rot qB = new b2Rot(aB);
m_rA = b2Math.b2Mul(qA, m_localAnchorA - m_localCenterA);
m_rB = b2Math.b2Mul(qB, m_localAnchorB - m_localCenterB);
m_u = cB + m_rB - cA - m_rA;
m_length = m_u.Length;
float C = m_length - m_maxLength;
if (C > 0.0f)
{
m_state = b2LimitState.e_atUpperLimit;
}
else
{
m_state = b2LimitState.e_inactiveLimit;
}
if (m_length > b2Settings.b2_linearSlop)
{
m_u *= 1.0f / m_length;
}
else
{
m_u.SetZero();
m_mass = 0.0f;
m_impulse = 0.0f;
return;
}
// Compute effective mass.
float crA = b2Math.b2Cross(m_rA, m_u);
float crB = b2Math.b2Cross(m_rB, m_u);
float invMass = m_invMassA + m_invIA * crA * crA + m_invMassB + m_invIB * crB * crB;
m_mass = invMass != 0.0f ? 1.0f / invMass : 0.0f;
if (data.step.warmStarting)
{
// Scale the impulse to support a variable time step.
m_impulse *= data.step.dtRatio;
b2Vec2 P = m_impulse * m_u;
vA -= m_invMassA * P;
wA -= m_invIA * b2Math.b2Cross(m_rA, P);
vB += m_invMassB * P;
wB += m_invIB * b2Math.b2Cross(m_rB, P);
}
else
{
m_impulse = 0.0f;
}
m_bodyA.InternalVelocity.v = vA;
m_bodyA.InternalVelocity.w = wA;
m_bodyB.InternalVelocity.v = vB;
m_bodyB.InternalVelocity.w = wB;
}
public override void SolveVelocityConstraints(b2SolverData data)
{
b2Vec2 vA = m_bodyA.InternalVelocity.v;
float wA = m_bodyA.InternalVelocity.w;
b2Vec2 vB = m_bodyB.InternalVelocity.v;
float wB = m_bodyB.InternalVelocity.w;
// Cdot = dot(u, v + cross(w, r))
b2Vec2 vpA = vA + b2Math.b2Cross(wA, ref m_rA);
b2Vec2 vpB = vB + b2Math.b2Cross(wB, ref m_rB);
float C = m_length - m_maxLength;
float Cdot = b2Math.b2Dot(m_u, vpB - vpA);
// Predictive constraint.
if (C < 0.0f)
{
Cdot += data.step.inv_dt * C;
}
float impulse = -m_mass * Cdot;
float oldImpulse = m_impulse;
m_impulse = Math.Min(0.0f, m_impulse + impulse);
impulse = m_impulse - oldImpulse;
b2Vec2 P = impulse * m_u;
vA -= m_invMassA * P;
wA -= m_invIA * b2Math.b2Cross(m_rA, P);
vB += m_invMassB * P;
wB += m_invIB * b2Math.b2Cross(m_rB, P);
m_bodyA.InternalVelocity.v = vA;
m_bodyA.InternalVelocity.w = wA;
m_bodyB.InternalVelocity.v = vB;
m_bodyB.InternalVelocity.w = wB;
}
public override bool SolvePositionConstraints(b2SolverData data)
{
b2Vec2 cA = m_bodyA.InternalPosition.c;
float aA = m_bodyA.InternalPosition.a;
b2Vec2 cB = m_bodyB.InternalPosition.c;
float aB = m_bodyB.InternalPosition.a;
b2Rot qA = new b2Rot(aA);
b2Rot qB = new b2Rot(aB);
b2Vec2 rA = b2Math.b2Mul(qA, m_localAnchorA - m_localCenterA);
b2Vec2 rB = b2Math.b2Mul(qB, m_localAnchorB - m_localCenterB);
b2Vec2 u = cB + rB - cA - rA;
float length = u.Normalize();
float C = length - m_maxLength;
C = b2Math.b2Clamp(C, 0.0f, b2Settings.b2_maxLinearCorrection);
float impulse = -m_mass * C;
b2Vec2 P = impulse * u;
cA -= m_invMassA * P;
aA -= m_invIA * b2Math.b2Cross(rA, P);
cB += m_invMassB * P;
aB += m_invIB * b2Math.b2Cross(rB, P);
m_bodyA.InternalPosition.c = cA;
m_bodyA.InternalPosition.a = aA;
m_bodyB.InternalPosition.c = cB;
m_bodyB.InternalPosition.a = aB;
return length - m_maxLength < b2Settings.b2_linearSlop;
}
public override b2Vec2 GetAnchorA()
{
return m_bodyA.GetWorldPoint(m_localAnchorA);
}
public override b2Vec2 GetAnchorB()
{
return m_bodyB.GetWorldPoint(m_localAnchorB);
}
public virtual b2Vec2 GetReactionForce(float inv_dt)
{
b2Vec2 F = (inv_dt * m_impulse) * m_u;
return F;
}
public virtual float GetReactionTorque(float inv_dt)
{
return 0.0f;
}
public virtual float GetMaxLength()
{
return m_maxLength;
}
public virtual b2LimitState GetLimitState()
{
return m_state;
}
public override void Dump()
{
int indexA = m_bodyA.IslandIndex;
int indexB = m_bodyB.IslandIndex;
b2Settings.b2Log(" b2RopeJointDef jd;\n");
b2Settings.b2Log(" jd.bodyA = bodies[{0}];\n", indexA);
b2Settings.b2Log(" jd.bodyB = bodies[{0}];\n", indexB);
b2Settings.b2Log(" jd.collideConnected = bool({0});\n", m_collideConnected);
b2Settings.b2Log(" jd.localAnchorA.Set({0:F5}, {1:F5});\n", m_localAnchorA.x, m_localAnchorA.y);
b2Settings.b2Log(" jd.localAnchorB.Set({0:F5}, {1:F5});\n", m_localAnchorB.x, m_localAnchorB.y);
b2Settings.b2Log(" jd.maxLength = {0:F5};\n", m_maxLength);
b2Settings.b2Log(" joints[{0}] = m_world.CreateJoint(&jd);\n", m_index);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using SteamKit2;
using SteamTrade.Exceptions;
using SteamTrade.TradeWebAPI;
namespace SteamTrade
{
public partial class Trade
{
#region Static Public data
public static Schema CurrentSchema = null;
#endregion
private const int WEB_REQUEST_MAX_RETRIES = 3;
private const int WEB_REQUEST_TIME_BETWEEN_RETRIES_MS = 600;
// list to store all trade events already processed
private readonly List<TradeEvent> eventList;
// current bot's sid
private readonly SteamID mySteamId;
private readonly Dictionary<int, ulong> myOfferedItems;
private readonly List<ulong> steamMyOfferedItems;
private readonly TradeSession session;
private readonly Task<Inventory> myInventoryTask;
private readonly Task<Inventory> otherInventoryTask;
internal Trade(SteamID me, SteamID other, string sessionId, string token, Task<Inventory> myInventoryTask, Task<Inventory> otherInventoryTask)
{
TradeStarted = false;
OtherIsReady = false;
MeIsReady = false;
mySteamId = me;
OtherSID = other;
session = new TradeSession(sessionId, token, other);
this.eventList = new List<TradeEvent>();
OtherOfferedItems = new List<ulong>();
myOfferedItems = new Dictionary<int, ulong>();
steamMyOfferedItems = new List<ulong>();
this.otherInventoryTask = otherInventoryTask;
this.myInventoryTask = myInventoryTask;
}
#region Public Properties
/// <summary>Gets the other user's steam ID.</summary>
public SteamID OtherSID { get; private set; }
/// <summary>
/// Gets the bot's Steam ID.
/// </summary>
public SteamID MySteamId
{
get { return mySteamId; }
}
/// <summary>
/// Gets the inventory of the other user.
/// </summary>
public Inventory OtherInventory
{
get
{
if(otherInventoryTask == null)
return null;
otherInventoryTask.Wait();
return otherInventoryTask.Result;
}
}
/// <summary>
/// Gets the private inventory of the other user.
/// </summary>
public ForeignInventory OtherPrivateInventory { get; private set; }
/// <summary>
/// Gets the inventory of the bot.
/// </summary>
public Inventory MyInventory
{
get
{
if(myInventoryTask == null)
return null;
myInventoryTask.Wait();
return myInventoryTask.Result;
}
}
/// <summary>
/// Gets the items the user has offered, by itemid.
/// </summary>
/// <value>
/// The other offered items.
/// </value>
public List<ulong> OtherOfferedItems { get; private set; }
/// <summary>
/// Gets a value indicating if the other user is ready to trade.
/// </summary>
public bool OtherIsReady { get; private set; }
/// <summary>
/// Gets a value indicating if the bot is ready to trade.
/// </summary>
public bool MeIsReady { get; private set; }
/// <summary>
/// Gets a value indicating if a trade has started.
/// </summary>
public bool TradeStarted { get; private set; }
/// <summary>
/// Gets a value indicating if the remote trading partner cancelled the trade.
/// </summary>
public bool OtherUserCancelled { get; private set; }
/// <summary>
/// Gets a value indicating whether the trade completed normally. This
/// is independent of other flags.
/// </summary>
public bool HasTradeCompletedOk { get; private set; }
/// <summary>
/// Gets a value indicating if the remote trading partner accepted the trade.
/// </summary>
public bool OtherUserAccepted { get; private set; }
#endregion
#region Public Events
public delegate void CloseHandler ();
public delegate void CompleteHandler ();
public delegate void ErrorHandler (string error);
public delegate void TimeoutHandler ();
public delegate void SuccessfulInit ();
public delegate void UserAddItemHandler (Schema.Item schemaItem,Inventory.Item inventoryItem);
public delegate void UserRemoveItemHandler (Schema.Item schemaItem,Inventory.Item inventoryItem);
public delegate void MessageHandler (string msg);
public delegate void UserSetReadyStateHandler (bool ready);
public delegate void UserAcceptHandler ();
/// <summary>
/// When the trade closes, this is called. It doesn't matter
/// whether or not it was a timeout or an error, this is called
/// to close the trade.
/// </summary>
public event CloseHandler OnClose;
/// <summary>
/// Called when the trade completes successfully.
/// </summary>
public event CompleteHandler OnSuccess;
/// <summary>
/// This is for handling errors that may occur, like inventories
/// not loading.
/// </summary>
public event ErrorHandler OnError;
/// <summary>
/// This occurs after Inventories have been loaded.
/// </summary>
public event SuccessfulInit OnAfterInit;
/// <summary>
/// This occurs when the other user adds an item to the trade.
/// </summary>
public event UserAddItemHandler OnUserAddItem;
/// <summary>
/// This occurs when the other user removes an item from the
/// trade.
/// </summary>
public event UserAddItemHandler OnUserRemoveItem;
/// <summary>
/// This occurs when the user sends a message to the bot over
/// trade.
/// </summary>
public event MessageHandler OnMessage;
/// <summary>
/// This occurs when the user sets their ready state to either
/// true or false.
/// </summary>
public event UserSetReadyStateHandler OnUserSetReady;
/// <summary>
/// This occurs when the user accepts the trade.
/// </summary>
public event UserAcceptHandler OnUserAccept;
#endregion
/// <summary>
/// Cancel the trade. This calls the OnClose handler, as well.
/// </summary>
public bool CancelTrade ()
{
return RetryWebRequest(session.CancelTradeWebCmd);
}
/// <summary>
/// Adds a specified TF2 item by its itemid.
/// If the item is not a TF2 item, use the AddItem(ulong itemid, int appid, long contextid) overload
/// </summary>
/// <returns><c>false</c> if the tf2 item was not found in the inventory.</returns>
public bool AddItem (ulong itemid)
{
if (MyInventory.GetItem(itemid) == null)
{
return false;
}
else
{
return AddItem(new TradeUserAssets(){assetid=itemid,appid=440,contextid=2});
}
}
public bool AddItem(ulong itemid, int appid, long contextid)
{
return AddItem(new TradeUserAssets(){assetid=itemid,appid=appid,contextid=contextid});
}
public bool AddItem(TradeUserAssets item)
{
var slot = NextTradeSlot();
bool success = RetryWebRequest(() => session.AddItemWebCmd(item.assetid, slot, item.appid, item.contextid));
if(success)
myOfferedItems[slot] = item.assetid;
return success;
}
/// <summary>
/// Adds a single item by its Defindex.
/// </summary>
/// <returns>
/// <c>true</c> if an item was found with the corresponding
/// defindex, <c>false</c> otherwise.
/// </returns>
public bool AddItemByDefindex (int defindex)
{
List<Inventory.Item> items = MyInventory.GetItemsByDefindex (defindex);
foreach (Inventory.Item item in items)
{
if (item != null && !myOfferedItems.ContainsValue(item.Id) && !item.IsNotTradeable)
{
return AddItem (item.Id);
}
}
return false;
}
/// <summary>
/// Adds an entire set of items by Defindex to each successive
/// slot in the trade.
/// </summary>
/// <param name="defindex">The defindex. (ex. 5022 = crates)</param>
/// <param name="numToAdd">The upper limit on amount of items to add. <c>0</c> to add all items.</param>
/// <returns>Number of items added.</returns>
public uint AddAllItemsByDefindex (int defindex, uint numToAdd = 0)
{
List<Inventory.Item> items = MyInventory.GetItemsByDefindex (defindex);
uint added = 0;
foreach (Inventory.Item item in items)
{
if (item != null && !myOfferedItems.ContainsValue(item.Id) && !item.IsNotTradeable)
{
bool success = AddItem (item.Id);
if (success)
added++;
if (numToAdd > 0 && added >= numToAdd)
return added;
}
}
return added;
}
public bool RemoveItem(TradeUserAssets item)
{
return RemoveItem(item.assetid, item.appid, item.contextid);
}
/// <summary>
/// Removes an item by its itemid.
/// </summary>
/// <returns><c>false</c> the item was not found in the trade.</returns>
public bool RemoveItem (ulong itemid, int appid = 440, long contextid = 2)
{
int? slot = GetItemSlot (itemid);
if (!slot.HasValue)
return false;
bool success = RetryWebRequest(() => session.RemoveItemWebCmd(itemid, slot.Value, appid, contextid));
if(success)
myOfferedItems.Remove (slot.Value);
return success;
}
/// <summary>
/// Removes an item with the given Defindex from the trade.
/// </summary>
/// <returns>
/// Returns <c>true</c> if it found a corresponding item; <c>false</c> otherwise.
/// </returns>
public bool RemoveItemByDefindex (int defindex)
{
foreach (ulong id in myOfferedItems.Values)
{
Inventory.Item item = MyInventory.GetItem (id);
if (item != null && item.Defindex == defindex)
{
return RemoveItem (item.Id);
}
}
return false;
}
/// <summary>
/// Removes an entire set of items by Defindex.
/// </summary>
/// <param name="defindex">The defindex. (ex. 5022 = crates)</param>
/// <param name="numToRemove">The upper limit on amount of items to remove. <c>0</c> to remove all items.</param>
/// <returns>Number of items removed.</returns>
public uint RemoveAllItemsByDefindex (int defindex, uint numToRemove = 0)
{
List<Inventory.Item> items = MyInventory.GetItemsByDefindex (defindex);
uint removed = 0;
foreach (Inventory.Item item in items)
{
if (item != null && myOfferedItems.ContainsValue (item.Id))
{
bool success = RemoveItem (item.Id);
if (success)
removed++;
if (numToRemove > 0 && removed >= numToRemove)
return removed;
}
}
return removed;
}
/// <summary>
/// Removes all offered items from the trade.
/// </summary>
/// <returns>Number of items removed.</returns>
public uint RemoveAllItems()
{
uint numRemoved = 0;
foreach(var id in myOfferedItems.Values.ToList())
{
Inventory.Item item = MyInventory.GetItem(id);
if(item != null)
{
bool wasRemoved = RemoveItem(item.Id);
if(wasRemoved)
numRemoved++;
}
}
return numRemoved;
}
/// <summary>
/// Sends a message to the user over the trade chat.
/// </summary>
public bool SendMessage (string msg)
{
return RetryWebRequest(() => session.SendMessageWebCmd(msg));
}
/// <summary>
/// Sets the bot to a ready status.
/// </summary>
public bool SetReady (bool ready)
{
//If the bot calls SetReady(false) and the call fails, we still want meIsReady to be
//set to false. Otherwise, if the call to SetReady() was a result of a callback
//from Trade.Poll() inside of the OnTradeAccept() handler, the OnTradeAccept()
//handler might think the bot is ready, when really it's not!
if(!ready)
MeIsReady = false;
// testing
ValidateLocalTradeItems ();
return RetryWebRequest(() => session.SetReadyWebCmd(ready));
}
/// <summary>
/// Accepts the trade from the user. Returns a deserialized
/// JSON object.
/// </summary>
public bool AcceptTrade ()
{
ValidateLocalTradeItems ();
return RetryWebRequest(session.AcceptTradeWebCmd);
}
/// <summary>
/// Calls the given function multiple times, until we get a non-null/non-false/non-zero result, or we've made at least
/// WEB_REQUEST_MAX_RETRIES attempts (with WEB_REQUEST_TIME_BETWEEN_RETRIES_MS between attempts)
/// </summary>
/// <returns>The result of the function if it succeeded, or default(T) (null/false/0) otherwise</returns>
private T RetryWebRequest<T>(Func<T> webEvent)
{
for (int i = 0; i < WEB_REQUEST_MAX_RETRIES; i++)
{
//Don't make any more requests if the trade has ended!
if (HasTradeCompletedOk || OtherUserCancelled)
return default(T);
try
{
T result = webEvent();
// if the web request returned some error.
if (!EqualityComparer<T>.Default.Equals(result, default(T)))
return result;
}
catch (Exception ex)
{
// TODO: log to SteamBot.Log but... see issue #394
// realistically we should not throw anymore
Console.WriteLine(ex);
}
if (i != WEB_REQUEST_MAX_RETRIES)
{
//This will cause the bot to stop responding while we wait between web requests. ...Is this really what we want?
Thread.Sleep(WEB_REQUEST_TIME_BETWEEN_RETRIES_MS);
}
}
return default(T);
}
/// <summary>
/// This updates the trade. This is called at an interval of a
/// default of 800ms, not including the execution time of the
/// method itself.
/// </summary>
/// <returns><c>true</c> if the other trade partner performed an action; otherwise <c>false</c>.</returns>
public bool Poll ()
{
bool otherDidSomething = false;
if (!TradeStarted)
{
TradeStarted = true;
// since there is no feedback to let us know that the trade
// is fully initialized we assume that it is when we start polling.
if (OnAfterInit != null)
OnAfterInit ();
}
TradeStatus status = RetryWebRequest(session.GetStatus);
if (status == null)
return false;
switch (status.trade_status)
{
// Nothing happened. i.e. trade hasn't closed yet.
case 0:
break;
// Successful trade
case 1:
HasTradeCompletedOk = true;
return false;
// All other known values (3, 4) correspond to trades closing.
default:
FireOnErrorEvent("Trade was closed by other user. Trade status: " + status.trade_status);
OtherUserCancelled = true;
return false;
}
if (status.newversion)
{
// handle item adding and removing
session.Version = status.version;
HandleTradeVersionChange(status);
return true;
}
else if (status.version > session.Version)
{
// oh crap! we missed a version update abort so we don't get
// scammed. if we could get what steam thinks what's in the
// trade then this wouldn't be an issue. but we can only get
// that when we see newversion == true
throw new TradeException("The trade version does not match. Aborting.");
}
// Update Local Variables
if (status.them != null)
{
OtherIsReady = status.them.ready == 1;
MeIsReady = status.me.ready == 1;
OtherUserAccepted = status.them.confirmed == 1;
}
var events = status.GetAllEvents();
foreach (var tradeEvent in events)
{
if (eventList.Contains(tradeEvent))
continue;
//add event to processed list, as we are taking care of this event now
eventList.Add(tradeEvent);
bool isBot = tradeEvent.steamid == MySteamId.ConvertToUInt64().ToString();
// dont process if this is something the bot did
if (isBot)
continue;
otherDidSomething = true;
switch ((TradeEventType) tradeEvent.action)
{
case TradeEventType.ItemAdded:
FireOnUserAddItem(tradeEvent);
break;
case TradeEventType.ItemRemoved:
FireOnUserRemoveItem(tradeEvent);
break;
case TradeEventType.UserSetReady:
OnUserSetReady(true);
break;
case TradeEventType.UserSetUnReady:
OnUserSetReady(false);
break;
case TradeEventType.UserAccept:
OnUserAccept();
break;
case TradeEventType.UserChat:
OnMessage(tradeEvent.text);
break;
default:
// Todo: add an OnWarning or similar event
FireOnErrorEvent("Unknown Event ID: " + tradeEvent.action);
break;
}
}
if (status.logpos != 0)
{
session.LogPos = status.logpos;
}
return otherDidSomething;
}
private void HandleTradeVersionChange(TradeStatus status)
{
CopyNewAssets(OtherOfferedItems, status.them.GetAssets());
CopyNewAssets(steamMyOfferedItems, status.me.GetAssets());
}
private void CopyNewAssets(List<ulong> dest, IEnumerable<TradeUserAssets> assetList)
{
if (assetList == null)
return;
dest.Clear();
dest.AddRange(assetList.Select(asset => asset.assetid));
}
/// <summary>
/// Gets an item from a TradeEvent, and passes it into the UserHandler's implemented OnUserAddItem([...]) routine.
/// Passes in null items if something went wrong.
/// </summary>
/// <param name="tradeEvent">TradeEvent to get item from</param>
/// <returns></returns>
private void FireOnUserAddItem(TradeEvent tradeEvent)
{
ulong itemID = tradeEvent.assetid;
if (OtherInventory != null)
{
Inventory.Item item = OtherInventory.GetItem(itemID);
if (item != null)
{
Schema.Item schemaItem = CurrentSchema.GetItem(item.Defindex);
if (schemaItem == null)
{
Console.WriteLine("User added an unknown item to the trade.");
}
OnUserAddItem(schemaItem, item);
}
else
{
item = new Inventory.Item
{
Id=itemID,
AppId=tradeEvent.appid,
ContextId=tradeEvent.contextid
};
//Console.WriteLine("User added a non TF2 item to the trade.");
OnUserAddItem(null, item);
}
}
else
{
var schemaItem = GetItemFromPrivateBp(tradeEvent, itemID);
if (schemaItem == null)
{
Console.WriteLine("User added an unknown item to the trade.");
}
OnUserAddItem(schemaItem, null);
// todo: figure out what to send in with Inventory item.....
}
}
private Schema.Item GetItemFromPrivateBp(TradeEvent tradeEvent, ulong itemID)
{
if (OtherPrivateInventory == null)
{
// get the foreign inventory
var f = session.GetForiegnInventory(OtherSID, tradeEvent.contextid, tradeEvent.appid);
OtherPrivateInventory = new ForeignInventory(f);
}
ushort defindex = OtherPrivateInventory.GetDefIndex(itemID);
Schema.Item schemaItem = CurrentSchema.GetItem(defindex);
return schemaItem;
}
/// <summary>
/// Gets an item from a TradeEvent, and passes it into the UserHandler's implemented OnUserRemoveItem([...]) routine.
/// Passes in null items if something went wrong.
/// </summary>
/// <param name="tradeEvent">TradeEvent to get item from</param>
/// <returns></returns>
private void FireOnUserRemoveItem(TradeEvent tradeEvent)
{
ulong itemID = tradeEvent.assetid;
if (OtherInventory != null)
{
Inventory.Item item = OtherInventory.GetItem(itemID);
if (item != null)
{
Schema.Item schemaItem = CurrentSchema.GetItem(item.Defindex);
if (schemaItem == null)
{
// TODO: Add log (counldn't find item in CurrentSchema)
}
OnUserRemoveItem(schemaItem, item);
}
else
{
// TODO: Log this (Couldn't find item in user's inventory can't find item in CurrentSchema
item = new Inventory.Item()
{
Id = itemID,
AppId = tradeEvent.appid,
ContextId = tradeEvent.contextid
};
OnUserRemoveItem(null, item);
}
}
else
{
var schemaItem = GetItemFromPrivateBp(tradeEvent, itemID);
if (schemaItem == null)
{
// TODO: Add log (counldn't find item in CurrentSchema)
}
OnUserRemoveItem(schemaItem, null);
}
}
internal void FireOnSuccessEvent()
{
var onSuccessEvent = OnSuccess;
if (onSuccessEvent != null)
onSuccessEvent();
}
internal void FireOnCloseEvent()
{
var onCloseEvent = OnClose;
if (onCloseEvent != null)
onCloseEvent();
}
internal void FireOnErrorEvent(string errorMessage)
{
var onErrorEvent = OnError;
if(onErrorEvent != null)
onErrorEvent(errorMessage);
}
private int NextTradeSlot()
{
int slot = 0;
while (myOfferedItems.ContainsKey (slot))
{
slot++;
}
return slot;
}
private int? GetItemSlot(ulong itemid)
{
foreach (int slot in myOfferedItems.Keys)
{
if (myOfferedItems [slot] == itemid)
{
return slot;
}
}
return null;
}
private void ValidateLocalTradeItems ()
{
if (myOfferedItems.Count != steamMyOfferedItems.Count)
{
throw new TradeException ("Error validating local copy of items in the trade: Count mismatch");
}
if (myOfferedItems.Values.Any(id => !steamMyOfferedItems.Contains(id)))
{
throw new TradeException ("Error validating local copy of items in the trade: Item was not in the Steam Copy.");
}
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="Column.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Web.UI.WebControls {
using System;
using System.Collections;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
/// <devdoc>
/// Creates a column and is the base class for all <see cref='System.Web.UI.WebControls.DataGrid'/> column types.
/// </devdoc>
[
TypeConverterAttribute(typeof(ExpandableObjectConverter))
]
public abstract class DataGridColumn : IStateManager {
private DataGrid owner;
private TableItemStyle itemStyle;
private TableItemStyle headerStyle;
private TableItemStyle footerStyle;
private StateBag statebag;
private bool marked;
/// <devdoc>
/// <para>Initializes a new instance of the System.Web.UI.WebControls.Column class.</para>
/// </devdoc>
protected DataGridColumn() {
statebag = new StateBag();
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
protected bool DesignMode {
get {
if (owner != null) {
return owner.DesignMode;
}
return false;
}
}
/// <devdoc>
/// <para>Gets the style properties for the footer item.</para>
/// </devdoc>
[
WebCategory("Styles"),
DefaultValue(null),
WebSysDescription(SR.DataGridColumn_FooterStyle),
DesignerSerializationVisibility(DesignerSerializationVisibility.Content),
PersistenceMode(PersistenceMode.InnerProperty)
]
public virtual TableItemStyle FooterStyle {
get {
if (footerStyle == null) {
footerStyle = new TableItemStyle();
if (IsTrackingViewState)
((IStateManager)footerStyle).TrackViewState();
}
return footerStyle;
}
}
/// <devdoc>
/// </devdoc>
internal TableItemStyle FooterStyleInternal {
get {
return footerStyle;
}
}
/// <devdoc>
/// <para> Gets or sets the text displayed in the footer of the
/// System.Web.UI.WebControls.Column.</para>
/// </devdoc>
[
WebCategory("Appearance"),
DefaultValue(""),
WebSysDescription(SR.DataGridColumn_FooterText)
]
public virtual string FooterText {
get {
object o = ViewState["FooterText"];
if (o != null)
return(string)o;
return String.Empty;
}
set {
ViewState["FooterText"] = value;
OnColumnChanged();
}
}
/// <devdoc>
/// <para>Gets or sets the URL reference to an image to display
/// instead of text on the header of this System.Web.UI.WebControls.Column
/// .</para>
/// </devdoc>
[
WebCategory("Appearance"),
DefaultValue(""),
UrlProperty(),
WebSysDescription(SR.DataGridColumn_HeaderImageUrl)
]
public virtual string HeaderImageUrl {
get {
object o = ViewState["HeaderImageUrl"];
if (o != null)
return(string)o;
return String.Empty;
}
set {
ViewState["HeaderImageUrl"] = value;
OnColumnChanged();
}
}
/// <devdoc>
/// <para>Gets the style properties for the header of the System.Web.UI.WebControls.Column. This property is read-only.</para>
/// </devdoc>
[
WebCategory("Styles"),
DefaultValue(null),
WebSysDescription(SR.DataGridColumn_HeaderStyle),
DesignerSerializationVisibility(DesignerSerializationVisibility.Content),
PersistenceMode(PersistenceMode.InnerProperty)
]
public virtual TableItemStyle HeaderStyle {
get {
if (headerStyle == null) {
headerStyle = new TableItemStyle();
if (IsTrackingViewState)
((IStateManager)headerStyle).TrackViewState();
}
return headerStyle;
}
}
/// <devdoc>
/// </devdoc>
internal TableItemStyle HeaderStyleInternal {
get {
return headerStyle;
}
}
/// <devdoc>
/// <para>Gets or sets the text displayed in the header of the
/// System.Web.UI.WebControls.Column.</para>
/// </devdoc>
[
WebCategory("Appearance"),
DefaultValue(""),
WebSysDescription(SR.DataGridColumn_HeaderText)
]
public virtual string HeaderText {
get {
object o = ViewState["HeaderText"];
if (o != null)
return(string)o;
return String.Empty;
}
set {
ViewState["HeaderText"] = value;
OnColumnChanged();
}
}
/// <devdoc>
/// <para>Gets the style properties of an item within the System.Web.UI.WebControls.Column. This property is read-only.</para>
/// </devdoc>
[
WebCategory("Styles"),
DefaultValue(null),
WebSysDescription(SR.DataGridColumn_ItemStyle),
DesignerSerializationVisibility(DesignerSerializationVisibility.Content),
PersistenceMode(PersistenceMode.InnerProperty)
]
public virtual TableItemStyle ItemStyle {
get {
if (itemStyle == null) {
itemStyle = new TableItemStyle();
if (IsTrackingViewState)
((IStateManager)itemStyle).TrackViewState();
}
return itemStyle;
}
}
/// <devdoc>
/// </devdoc>
internal TableItemStyle ItemStyleInternal {
get {
return itemStyle;
}
}
/// <devdoc>
/// <para>Gets the System.Web.UI.WebControls.DataGrid that the System.Web.UI.WebControls.Column is a part of. This property is read-only.</para>
/// </devdoc>
protected DataGrid Owner {
get {
return owner;
}
}
/// <devdoc>
/// <para>Gets or sets the expression used when this column is used to sort the data source> by.</para>
/// </devdoc>
[
WebCategory("Behavior"),
DefaultValue(""),
WebSysDescription(SR.DataGridColumn_SortExpression)
]
public virtual string SortExpression {
get {
object o = ViewState["SortExpression"];
if (o != null)
return(string)o;
return String.Empty;
}
set {
ViewState["SortExpression"] = value;
OnColumnChanged();
}
}
/// <devdoc>
/// <para>Gets the statebag for the System.Web.UI.WebControls.Column. This property is read-only.</para>
/// </devdoc>
protected StateBag ViewState {
get {
return statebag;
}
}
/// <devdoc>
/// <para>Gets or sets a value to indicate whether the System.Web.UI.WebControls.Column is visible.</para>
/// </devdoc>
[
WebCategory("Behavior"),
DefaultValue(true),
WebSysDescription(SR.DataGridColumn_Visible)
]
public bool Visible {
get {
object o = ViewState["Visible"];
if (o != null)
return(bool)o;
return true;
}
set {
ViewState["Visible"] = value;
OnColumnChanged();
}
}
/// <devdoc>
/// </devdoc>
public virtual void Initialize() {
}
/// <devdoc>
/// <para>Initializes a cell in the System.Web.UI.WebControls.Column.</para>
/// </devdoc>
public virtual void InitializeCell(TableCell cell, int columnIndex, ListItemType itemType) {
switch (itemType) {
case ListItemType.Header:
{
WebControl headerControl = null;
bool sortableHeader = true;
string sortExpression = null;
if ((owner != null) && (owner.AllowSorting == false)) {
sortableHeader = false;
}
if (sortableHeader) {
sortExpression = SortExpression;
if (sortExpression.Length == 0)
sortableHeader = false;
}
string headerImageUrl = HeaderImageUrl;
if (headerImageUrl.Length != 0) {
if (sortableHeader) {
ImageButton sortButton = new ImageButton();
sortButton.ImageUrl = HeaderImageUrl;
sortButton.CommandName = DataGrid.SortCommandName;
sortButton.CommandArgument = sortExpression;
sortButton.CausesValidation = false;
headerControl = sortButton;
}
else {
Image headerImage = new Image();
headerImage.ImageUrl = headerImageUrl;
headerControl = headerImage;
}
}
else {
string headerText = HeaderText;
if (sortableHeader) {
LinkButton sortButton = new DataGridLinkButton();
sortButton.Text = headerText;
sortButton.CommandName = DataGrid.SortCommandName;
sortButton.CommandArgument = sortExpression;
sortButton.CausesValidation = false;
headerControl = sortButton;
}
else {
if (headerText.Length == 0) {
// the browser does not render table borders for cells with nothing
// in their content, so we add a non-breaking space.
headerText = " ";
}
cell.Text = headerText;
}
}
if (headerControl != null) {
cell.Controls.Add(headerControl);
}
}
break;
case ListItemType.Footer:
{
string footerText = FooterText;
if (footerText.Length == 0) {
// the browser does not render table borders for cells with nothing
// in their content, so we add a non-breaking space.
footerText = " ";
}
cell.Text = footerText;
}
break;
}
}
/// <devdoc>
/// <para>Determines if the System.Web.UI.WebControls.Column is marked to save its state.</para>
/// </devdoc>
protected bool IsTrackingViewState {
get {
return marked;
}
}
/// <devdoc>
/// <para>Loads the state of the System.Web.UI.WebControls.Column.</para>
/// </devdoc>
protected virtual void LoadViewState(object savedState) {
if (savedState != null) {
object[] myState = (object[])savedState;
if (myState[0] != null)
((IStateManager)ViewState).LoadViewState(myState[0]);
if (myState[1] != null)
((IStateManager)ItemStyle).LoadViewState(myState[1]);
if (myState[2] != null)
((IStateManager)HeaderStyle).LoadViewState(myState[2]);
if (myState[3] != null)
((IStateManager)FooterStyle).LoadViewState(myState[3]);
}
}
/// <devdoc>
/// <para>Marks the starting point to begin tracking and saving changes to the
/// control as part of the control viewstate.</para>
/// </devdoc>
protected virtual void TrackViewState() {
marked = true;
((IStateManager)ViewState).TrackViewState();
if (itemStyle != null)
((IStateManager)itemStyle).TrackViewState();
if (headerStyle != null)
((IStateManager)headerStyle).TrackViewState();
if (footerStyle != null)
((IStateManager)footerStyle).TrackViewState();
}
/// <devdoc>
/// <para>Raises the ColumnChanged event for a System.Web.UI.WebControls.Column.</para>
/// </devdoc>
protected virtual void OnColumnChanged() {
if (owner != null) {
owner.OnColumnsChanged();
}
}
/// <devdoc>
/// <para>Saves the current state of the System.Web.UI.WebControls.Column.</para>
/// </devdoc>
protected virtual object SaveViewState() {
object propState = ((IStateManager)ViewState).SaveViewState();
object itemStyleState = (itemStyle != null) ? ((IStateManager)itemStyle).SaveViewState() : null;
object headerStyleState = (headerStyle != null) ? ((IStateManager)headerStyle).SaveViewState() : null;
object footerStyleState = (footerStyle != null) ? ((IStateManager)footerStyle).SaveViewState() : null;
if ((propState != null) ||
(itemStyleState != null) ||
(headerStyleState != null) ||
(footerStyleState != null)) {
return new object[4] {
propState,
itemStyleState,
headerStyleState,
footerStyleState
};
}
return null;
}
/// <devdoc>
/// </devdoc>
internal void SetOwner(DataGrid owner) {
this.owner = owner;
}
/// <devdoc>
/// <para>Converts the System.Web.UI.WebControls.Column to string.</para>
/// </devdoc>
public override string ToString() {
return String.Empty;
}
/// <internalonly/>
/// <devdoc>
/// Return true if tracking state changes.
/// </devdoc>
bool IStateManager.IsTrackingViewState {
get {
return IsTrackingViewState;
}
}
/// <internalonly/>
/// <devdoc>
/// Load previously saved state.
/// </devdoc>
void IStateManager.LoadViewState(object state) {
LoadViewState(state);
}
/// <internalonly/>
/// <devdoc>
/// Start tracking state changes.
/// </devdoc>
void IStateManager.TrackViewState() {
TrackViewState();
}
/// <internalonly/>
/// <devdoc>
/// Return object containing state changes.
/// </devdoc>
object IStateManager.SaveViewState() {
return SaveViewState();
}
}
}
| |
#region License
/*---------------------------------------------------------------------------------*\
Distributed under the terms of an MIT-style license:
The MIT License
Copyright (c) 2006-2010 Stephen M. McKamey
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
\*---------------------------------------------------------------------------------*/
#endregion License
using System;
using System.Collections.Generic;
using System.Globalization;
using JsonFx.IO;
using JsonFx.Serialization;
namespace JsonFx.Model.Filters
{
/// <summary>
/// Defines a filter for JSON-style serialization of DateTime into ISO-8601 string
/// </summary>
/// <remarks>
/// This is the format used by EcmaScript 5th edition Date.prototype.toJSON(...):
/// http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf
/// http://www.w3.org/TR/NOTE-datetime
/// http://en.wikipedia.org/wiki/ISO_8601
///
/// NOTE: This format limits expressing DateTime as either UTC or Unspecified. Local (i.e. Server Local) is converted to UTC.
/// </remarks>
public class Iso8601DateFilter : ModelFilter<DateTime>
{
#region Precision
/// <summary>
/// Defines the precision of fractional seconds in ISO-8601 dates
/// </summary>
public enum Precision
{
Seconds,
Milliseconds,
Ticks
}
#endregion Precision
#region Constants
private const string ShortFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ssK";
private const string LongFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffK";
private const string FullFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'FFFFFFFK";
#endregion Constants
#region Fields
private string iso8601Format = Iso8601DateFilter.LongFormat;
#endregion Fields
#region Properties
/// <summary>
/// Determines the precision of fractional seconds.
/// Defaults to EcmaScript precision of milliseconds.
/// </summary>
public Precision Format
{
get
{
switch (this.iso8601Format)
{
case ShortFormat:
{
return Precision.Seconds;
}
case LongFormat:
{
return Precision.Milliseconds;
}
default:
case FullFormat:
{
return Precision.Ticks;
}
}
}
set
{
switch (value)
{
case Precision.Seconds:
{
this.iso8601Format = Iso8601DateFilter.ShortFormat;
break;
}
case Precision.Milliseconds:
{
this.iso8601Format = Iso8601DateFilter.LongFormat;
break;
}
default:
case Precision.Ticks:
{
this.iso8601Format = Iso8601DateFilter.FullFormat;
break;
}
}
}
}
#endregion Properties
#region IDataFilter<DataTokenType,DateTime> Members
public override bool TryRead(DataReaderSettings settings, IStream<Token<ModelTokenType>> tokens, out DateTime value)
{
Token<ModelTokenType> token = tokens.Peek();
if (token == null ||
token.TokenType != ModelTokenType.Primitive ||
!(token.Value is string))
{
value = default(DateTime);
return false;
}
if (!Iso8601DateFilter.TryParseIso8601(
token.ValueAsString(),
out value))
{
value = default(DateTime);
return false;
}
tokens.Pop();
return true;
}
public override bool TryWrite(DataWriterSettings settings, DateTime value, out IEnumerable<Token<ModelTokenType>> tokens)
{
tokens = new Token<ModelTokenType>[]
{
ModelGrammar.TokenPrimitive(this.FormatIso8601(value))
};
return true;
}
#endregion IDataFilter<DataTokenType,DateTime> Members
#region Utility Methods
/// <summary>
/// Converts a ISO-8601 string to the corresponding DateTime representation
/// </summary>
/// <param name="date">ISO-8601 conformant date</param>
/// <param name="value">UTC or Unspecified DateTime</param>
/// <returns>true if parsing was successful</returns>
private static bool TryParseIso8601(string date, out DateTime value)
{
if (!DateTime.TryParseExact(date,
Iso8601DateFilter.FullFormat,
CultureInfo.InvariantCulture,
DateTimeStyles.RoundtripKind | DateTimeStyles.AllowWhiteSpaces | DateTimeStyles.NoCurrentDateDefault,
out value))
{
value = default(DateTime);
return false;
}
if (value.Kind == DateTimeKind.Local)
{
value = value.ToUniversalTime();
}
return true;
}
/// <summary>
/// Converts a DateTime to the corresponding ISO-8601 string representation
/// </summary>
/// <param name="value"></param>
/// <returns>ISO-8601 conformant date</returns>
private string FormatIso8601(DateTime value)
{
if (value.Kind == DateTimeKind.Local)
{
value = value.ToUniversalTime();
}
// DateTime in ISO-8601
return value.ToString(this.iso8601Format);
}
#endregion Utility Methods
}
}
| |
// Copyright (c) Microsoft Corporation. All Rights Reserved.
// Licensed under the MIT License.
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Shapes;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Data;
using System.ComponentModel;
namespace InteractiveDataDisplay.WPF
{
/// <summary>Facilitates drawing of vertical or horizontal coordinate axis</summary>
[Description("Vertical or horizontal coordinate axis")]
public class Axis : Panel
{
private ILabelProvider labelProvider;
private TicksProvider ticksProvider;
private Path majorTicksPath;
private Path minorTicksPath;
private FrameworkElement[] labels;
private const int maxTickArrangeIterations = 12;
private int maxTicks = 20;
private const double increaseRatio = 8.0;
private const double decreaseRatio = 8.0;
private const double tickLength = 10;
private bool drawTicks = true;
private bool drawMinorTicks = true;
/// <summary>
/// Initializes a new instance of <see cref="Axis"/> class with double <see cref="LabelProvider"/>
/// and <see cref="TicksProvider"/>.
/// </summary>
public Axis()
{
DataTransform = new IdentityDataTransform();
Ticks = new double[0];
majorTicksPath = new Path();
minorTicksPath = new Path();
Children.Add(majorTicksPath);
Children.Add(minorTicksPath);
BindingOperations.SetBinding(majorTicksPath, Path.StrokeProperty, new Binding("Foreground") { Source = this, Mode = BindingMode.TwoWay });
BindingOperations.SetBinding(minorTicksPath, Path.StrokeProperty, new Binding("Foreground") { Source = this, Mode = BindingMode.TwoWay });
if (labelProvider == null)
this.labelProvider = new LabelProvider();
if (ticksProvider == null)
this.ticksProvider = new TicksProvider();
}
/// <summary>
/// Initializes a new instance of <see cref="Axis"/> class.
/// </summary>
/// <param name="labelProvider">A <see cref="LabelProvider"/> to create labels.</param>
/// <param name="ticksProvider">A <see cref="TicksProvider"/> to create ticks.</param>
public Axis(ILabelProvider labelProvider, TicksProvider ticksProvider)
: this()
{
this.labelProvider = labelProvider;
this.ticksProvider = ticksProvider;
}
/// <summary>
/// Gets or sets a set of double values displayed as axis ticks in data values.
/// </summary>
/// <remarks>
/// Ticks are calculated from current Range of axis in plot coordinates and current DataTransform of axis.
/// Example: for range [-1,1] int plot coordinates and DataTransform as y = 0.001 * x + 0.5 values of Ticks will be in [-1000,1000] range
/// It is not recommended to set this property manually.
/// </remarks>
[Browsable(false)]
public IEnumerable<double> Ticks
{
get { return (IEnumerable<double>)GetValue(TicksProperty); }
set { SetValue(TicksProperty, value); }
}
/// <summary>
/// Identifies the <see cref="Ticks"/> dependency property.
/// </summary>
public static readonly DependencyProperty TicksProperty =
DependencyProperty.Register("Ticks", typeof(IEnumerable<double>), typeof(Axis), new PropertyMetadata(new double[0]));
/// <summary>
/// Gets or sets the range of values on axis in plot coordinates.
/// </summary>
///<remarks>
/// <see cref="Range"/> should be inside Domain of <see cref="DataTransform"/>, otherwise exception will be thrown.
///</remarks>
[Category("InteractiveDataDisplay")]
[Description("Range of values on axis")]
public Range Range
{
get { return (Range)GetValue(RangeProperty); }
set { SetValue(RangeProperty, value); }
}
/// <summary>
/// Identifies the <see cref="Range"/> dependency property.
/// </summary>
public static readonly DependencyProperty RangeProperty =
DependencyProperty.Register("Range", typeof(Range), typeof(Axis), new PropertyMetadata(new Range(0, 1),
(o, e) =>
{
Axis axis = (Axis)o;
if (axis != null)
{
axis.InvalidateMeasure();
}
}));
/// <summary>
/// Gets or sets orientation of the axis and location of labels
/// </summary>
/// <remarks>The default AxisOrientation is AxisOrientation.Bottom</remarks>
[Category("InteractiveDataDisplay")]
[Description("Defines orientation of axis and location of labels")]
public AxisOrientation AxisOrientation
{
get { return (AxisOrientation)GetValue(AxisOrientationProperty); }
set { SetValue(AxisOrientationProperty, value); }
}
/// <summary>
/// Identifies the <see cref="AxisOrientation"/> dependency property.
/// </summary>
public static readonly DependencyProperty AxisOrientationProperty =
DependencyProperty.Register("AxisOrientation", typeof(AxisOrientation), typeof(Axis), new PropertyMetadata(AxisOrientation.Bottom,
(o, e) =>
{
Axis axis = (Axis)o;
if (axis != null)
{
axis.InvalidateMeasure();
}
}));
/// <summary>
/// Gets or sets a flag indicating whether the axis is reversed or not.
/// </summary>
/// <remarks>Axis is not reversed by default.</remarks>
[Category("InteractiveDataDisplay")]
[Description("Defines orientation of axis and location of labels")]
public bool IsReversed
{
get { return (bool)GetValue(IsReversedProperty); }
set { SetValue(IsReversedProperty, value); }
}
/// <summary>
/// Identifies the <see cref="IsReversed"/> dependency property.
/// </summary>
public static readonly DependencyProperty IsReversedProperty =
DependencyProperty.Register("IsReversed", typeof(bool), typeof(Axis), new PropertyMetadata(false,
(o, e) =>
{
Axis axis = (Axis)o;
if (axis != null)
{
axis.InvalidateMeasure();
}
}));
/// <summary>
/// Gets or sets <see cref="DataTransform"/> for an axis.
/// </summary>
/// <remarks>
/// The default transform is <see cref="IdentityDataTransform"/>
/// DataTransform is used for transform plot coordinates from Range property to data values, which will be displayed on ticks
/// </remarks>
[Description("Transform from data to plot coordinates")]
[Category("InteractiveDataDisplay")]
public DataTransform DataTransform
{
get { return (DataTransform)GetValue(DataTransformProperty); }
set { SetValue(DataTransformProperty, value); }
}
/// <summary>
/// Identifies the <see cref="DataTransform"/> dependency property.
/// </summary>
public static readonly DependencyProperty DataTransformProperty =
DependencyProperty.Register("DataTransform", typeof(DataTransform), typeof(Axis), new PropertyMetadata(null,
(o, e) =>
{
Axis axis = (Axis)o;
if (axis != null)
{
axis.InvalidateMeasure();
}
}));
/// <summary>
/// Gets or sets the brush for labels and ticks of axis
/// </summary>
/// <remarks>The default foreground is black</remarks>
[Category("Appearance")]
[Description("Brush for labels and ticks")]
public SolidColorBrush Foreground
{
get { return (SolidColorBrush)GetValue(ForegroundProperty); }
set { SetValue(ForegroundProperty, value); }
}
/// <summary>
/// Identifies the <see cref="Foreground"/> dependency property.
/// </summary>
public static readonly DependencyProperty ForegroundProperty =
DependencyProperty.Register("Foreground", typeof(SolidColorBrush), typeof(Axis), new PropertyMetadata(new SolidColorBrush(Colors.Black)));
/// <summary>
/// Gets or sets the maximum possible count of ticks.
/// </summary>
/// <remarks>The defalut count is 20</remarks>
[Category("InteractiveDataDisplay")]
[Description("Maximum number of major ticks")]
public int MaxTicks
{
set
{
maxTicks = value;
InvalidateMeasure();
}
get
{
return maxTicks;
}
}
/// <summary>
/// Gets or sets a value indicating whether the ticks should be rendered or not.
/// </summary>
/// <remarks>The default value is true.</remarks>
[Category("InteractiveDataDisplay")]
public bool AreTicksVisible
{
set
{
drawTicks = value;
drawMinorTicks = value;
if (drawTicks)
InvalidateMeasure();
}
get { return drawTicks; }
}
/// <summary>
/// Gets or sets a value indicating whether the minor ticks should be rendered or not.
/// </summary>
/// <remarks>The default value is true.</remarks>
[Category("InteractiveDataDisplay")]
public bool AreMinorTicksVisible
{
set
{
drawMinorTicks = value;
if (drawMinorTicks)
InvalidateMeasure();
}
get { return drawMinorTicks; }
}
private void CreateTicks(Size axisSize)
{
Range range = new Range(
DataTransform.PlotToData(Double.IsInfinity(Range.Min) || Double.IsNaN(Range.Min) ? 0 : Range.Min),
DataTransform.PlotToData(Double.IsInfinity(Range.Max) || Double.IsNaN(Range.Max) ? 1 : Range.Max));
// One tick if range is point
if (range.IsPoint)
{
var t = new double[] { range.Min };
Ticks = t;
labels = labelProvider.GetLabels(t);
return;
}
// Do first pass of ticks arrangement
ticksProvider.Range = range;
double[] ticks = ticksProvider.GetTicks();
labels = labelProvider.GetLabels(ticks);
TickChange result;
if (ticks.Length > MaxTicks)
result = TickChange.Decrease;
else if (ticks.Length < 2)
result = TickChange.Increase;
else
result = CheckLabelsArrangement(axisSize, labels, ticks);
int iterations = 0;
int prevLength = ticks.Length;
while (result != TickChange.OK && iterations++ < maxTickArrangeIterations)
{
if (result == TickChange.Increase)
ticksProvider.IncreaseTickCount();
else
ticksProvider.DecreaseTickCount();
double[] newTicks = ticksProvider.GetTicks();
if (newTicks.Length > MaxTicks && result == TickChange.Increase)
{
ticksProvider.DecreaseTickCount(); // Step back and stop to not get more than MaxTicks
break;
}
else if (newTicks.Length < 2 && result == TickChange.Decrease)
{
ticksProvider.IncreaseTickCount(); // Step back and stop to not get less than 2
break;
}
var prevTicks = ticks;
ticks = newTicks;
var prevLabels = labels;
labels = labelProvider.GetLabels(newTicks);
var newResult = CheckLabelsArrangement(axisSize, labels, ticks);
if (newResult == result) // Continue in the same direction
{
prevLength = newTicks.Length;
}
else // Direction changed or layout OK - stop the loop
{
if (newResult != TickChange.OK) // Direction changed - time to stop
{
if (result == TickChange.Decrease)
{
if (prevLength < MaxTicks)
{
ticks = prevTicks;
labels = prevLabels;
ticksProvider.IncreaseTickCount();
}
}
else
{
if (prevLength >= 2)
{
ticks = prevTicks;
labels = prevLabels;
ticksProvider.DecreaseTickCount();
}
}
break;
}
break;
}
}
Ticks = ticks;
}
private void DrawCanvas(Size axisSize, double[] cTicks)
{
double length = IsHorizontal ? axisSize.Width : axisSize.Height;
GeometryGroup majorTicksGeometry = new GeometryGroup();
GeometryGroup minorTicksGeometry = new GeometryGroup();
if (!Double.IsNaN(length) && length != 0)
{
int start = 0;
if (cTicks.Length > 0 && cTicks[0] < Range.Min) start++;
if (Range.IsPoint)
drawMinorTicks = false;
for (int i = start; i < cTicks.Length; i++)
{
LineGeometry line = new LineGeometry();
majorTicksGeometry.Children.Add(line);
if (IsHorizontal)
{
line.StartPoint = new Point(GetCoordinateFromTick(cTicks[i], axisSize), 0);
line.EndPoint = new Point(GetCoordinateFromTick(cTicks[i], axisSize), tickLength);
}
else
{
line.StartPoint = new Point(0, GetCoordinateFromTick(cTicks[i], axisSize));
line.EndPoint = new Point(tickLength, GetCoordinateFromTick(cTicks[i], axisSize));
}
if (labels[i] is TextBlock)
{
(labels[i] as TextBlock).Foreground = Foreground;
}
else if (labels[i] is Control)
{
(labels[i] as Control).Foreground = Foreground;
}
Children.Add(labels[i]);
}
if (drawMinorTicks)
{
double[] minorTicks = ticksProvider.GetMinorTicks(Range);
if (minorTicks != null)
{
for (int j = 0; j < minorTicks.Length; j++)
{
LineGeometry line = new LineGeometry();
minorTicksGeometry.Children.Add(line);
if (IsHorizontal)
{
line.StartPoint = new Point(GetCoordinateFromTick(minorTicks[j], axisSize), 0);
line.EndPoint = new Point(GetCoordinateFromTick(minorTicks[j], axisSize), tickLength / 2.0);
}
else
{
line.StartPoint = new Point(0, GetCoordinateFromTick(minorTicks[j], axisSize));
line.EndPoint = new Point(tickLength / 2.0, GetCoordinateFromTick(minorTicks[j], axisSize));
}
}
}
}
majorTicksPath.Data = majorTicksGeometry;
minorTicksPath.Data = minorTicksGeometry;
if (!drawMinorTicks)
drawMinorTicks = true;
}
}
/// <summary>
/// Positions child elements and determines a size for a Figure.
/// </summary>
/// <param name="finalSize">The final area within the parent that Figure should use to arrange itself and its children.</param>
/// <returns>The actual size used.</returns>
protected override Size ArrangeOverride(Size finalSize)
{
finalSize.Width = Math.Min(DesiredSize.Width, finalSize.Width);
finalSize.Height = Math.Min(DesiredSize.Height, finalSize.Height);
double labelArrangeOriginX = 0;
double labelArrangeOriginY = 0;
switch (AxisOrientation)
{
case AxisOrientation.Top:
majorTicksPath.Arrange(new Rect(0, finalSize.Height - tickLength, finalSize.Width, tickLength));
minorTicksPath.Arrange(new Rect(0, finalSize.Height - tickLength / 2.0, finalSize.Width, tickLength / 2.0));
break;
case AxisOrientation.Bottom:
majorTicksPath.Arrange(new Rect(0, 0, finalSize.Width, tickLength));
minorTicksPath.Arrange(new Rect(0, 0, finalSize.Width, tickLength / 2.0));
break;
case AxisOrientation.Right:
majorTicksPath.Arrange(new Rect(0, 0, tickLength, finalSize.Height));
minorTicksPath.Arrange(new Rect(0, 0, tickLength / 2.0, finalSize.Height));
break;
case AxisOrientation.Left:
majorTicksPath.Arrange(new Rect(Math.Max(0, finalSize.Width - tickLength), 0, tickLength, finalSize.Height));
minorTicksPath.Arrange(new Rect(Math.Max(0, finalSize.Width - tickLength / 2.0), 0, tickLength / 2.0, finalSize.Height));
labelArrangeOriginX = finalSize.Width - tickLength - CalculateMaxLabelWidth();
break;
}
foreach (var label in labels)
{
label.Arrange(new Rect(labelArrangeOriginX, labelArrangeOriginY, label.DesiredSize.Width, label.DesiredSize.Height));
}
return finalSize;
}
/// <summary>
/// Measures the size in layout required for child elements and determines a size for the Figure.
/// </summary>
/// <param name="availableSize">The available size that this element can give to child elements. Infinity can be specified as a value to indicate that the element will size to whatever content is available.</param>
/// <returns>The size that this element determines it needs during layout, based on its calculations of child element sizes.</returns>
protected override Size MeasureOverride(Size availableSize)
{
if (Double.IsInfinity(availableSize.Width))
availableSize.Width = 128;
if (Double.IsInfinity(availableSize.Height))
availableSize.Height = 128;
Size effectiveSize = availableSize;
ClearLabels();
CreateTicks(effectiveSize);
double[] cTicks = Ticks.ToArray();
DrawCanvas(effectiveSize, cTicks);
foreach (UIElement child in Children)
{
child.Measure(availableSize);
}
double maxLabelWidth = CalculateMaxLabelWidth();
double maxLabelHeight = CalculateMaxLabelHeight();
switch (AxisOrientation)
{
case AxisOrientation.Top:
for (int i = 0; i < labels.Length; i++)
{
labels[i].RenderTransform = new TranslateTransform { X = GetCoordinateFromTick(cTicks[i], effectiveSize) - labels[i].DesiredSize.Width / 2, Y = 0 };
}
break;
case AxisOrientation.Bottom:
for (int i = 0; i < labels.Length; i++)
{
labels[i].RenderTransform = new TranslateTransform { X = GetCoordinateFromTick(cTicks[i], effectiveSize) - labels[i].DesiredSize.Width / 2, Y = majorTicksPath.DesiredSize.Height };
}
break;
case AxisOrientation.Right:
for (int i = 0; i < labels.Length; i++)
{
labels[i].RenderTransform = new TranslateTransform { X = majorTicksPath.DesiredSize.Width, Y = GetCoordinateFromTick(cTicks[i], effectiveSize) - labels[i].DesiredSize.Height / 2 };
}
break;
case AxisOrientation.Left:
for (int i = 0; i < labels.Length; i++)
{
labels[i].RenderTransform = new TranslateTransform { X = maxLabelWidth - labels[i].DesiredSize.Width, Y = GetCoordinateFromTick(cTicks[i], effectiveSize) - labels[i].DesiredSize.Height / 2 };
}
break;
}
if (IsHorizontal)
{
availableSize.Height = majorTicksPath.DesiredSize.Height + maxLabelHeight;
}
else
{
availableSize.Width = majorTicksPath.DesiredSize.Width + maxLabelWidth;
}
return availableSize;
}
private void ClearLabels()
{
if (labels != null)
{
foreach (var elt in labels)
{
if (Children.Contains(elt))
Children.Remove(elt);
}
}
}
private double CalculateMaxLabelHeight()
{
if (labels != null)
{
double max = 0;
for (int i = 0; i < labels.Length; i++)
if (Children.Contains(labels[i]) && labels[i].DesiredSize.Height > max)
max = labels[i].DesiredSize.Height;
return max;
}
return 0;
}
private double CalculateMaxLabelWidth()
{
if (labels != null)
{
double max = 0;
for (int i = 0; i < labels.Length; i++)
if (Children.Contains(labels[i]) && labels[i].DesiredSize.Width > max)
max = labels[i].DesiredSize.Width;
return max;
}
return 0;
}
private TickChange CheckLabelsArrangement(Size axisSize, IEnumerable<FrameworkElement> inputLabels, double[] inputTicks)
{
var actualLabels1 = inputLabels.Select((label, i) => new { Label = label, Index = i });
var actualLabels2 = actualLabels1.Where(el => el.Label != null);
var actualLabels3 = actualLabels2.Select(el => new { Label = el.Label, Tick = inputTicks[el.Index] });
var actualLabels = actualLabels3.ToList();
actualLabels.ForEach(item => item.Label.Measure(axisSize));
var sizeInfos = actualLabels.Select(item =>
new { Offset = GetCoordinateFromTick(item.Tick, axisSize), Size = IsHorizontal ? item.Label.DesiredSize.Width : item.Label.DesiredSize.Height })
.OrderBy(item => item.Offset).ToArray();
// If distance between labels if smaller than threshold for any of the labels - decrease
for (int i = 0; i < sizeInfos.Length - 1; i++)
if ((sizeInfos[i].Offset + sizeInfos[i].Size * decreaseRatio / 2) > sizeInfos[i + 1].Offset)
return TickChange.Decrease;
// If distance between labels if larger than threshold for all of the labels - increase
TickChange res = TickChange.Increase;
for (int i = 0; i < sizeInfos.Length - 1; i++)
{
if ((sizeInfos[i].Offset + sizeInfos[i].Size * increaseRatio / 2) > sizeInfos[i + 1].Offset)
{
res = TickChange.OK;
break;
}
}
return res;
}
private double GetCoordinateFromTick(double tick, Size screenSize)
{
return ValueToScreen(DataTransform.DataToPlot(tick), screenSize, Range);
}
private double ValueToScreen(double value, Size screenSize, Range range)
{
double leftBound, rightBound, topBound, bottomBound;
leftBound = bottomBound = IsReversed ? range.Max : range.Min;
rightBound = topBound = IsReversed ? range.Min : range.Max;
if (IsHorizontal)
{
return range.IsPoint ?
(screenSize.Width / 2) :
((value - leftBound) * screenSize.Width / (rightBound - leftBound));
}
else
{
return range.IsPoint ?
(screenSize.Height / 2) :
(screenSize.Height - (value - leftBound) * screenSize.Height / (rightBound - leftBound));
}
}
/// <summary>
/// Gets the value indcating whether the axis is horizontal or not.
/// </summary>
private bool IsHorizontal
{
get
{
return (AxisOrientation == AxisOrientation.Bottom || AxisOrientation == AxisOrientation.Top);
}
}
}
internal enum TickChange
{
Increase = -1,
OK = 0,
Decrease = 1
}
}
| |
using System;
using System.Net;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Shared.Protocol;
using Microsoft.WindowsAzure.Storage.Table.Protocol;
using Orleans.TestingHost.Utils;
using TestExtensions;
using Xunit;
using Orleans.Tests.AzureUtils;
namespace Tester.AzureUtils
{
[TestCategory("Azure"), TestCategory("Storage")]
public class AzureTableDataManagerTests : AzureStorageBasicTests
{
private string PartitionKey;
private UnitTestAzureTableDataManager manager;
private UnitTestAzureTableData GenerateNewData()
{
return new UnitTestAzureTableData("JustData", PartitionKey, "RK-" + Guid.NewGuid());
}
public AzureTableDataManagerTests()
{
TestingUtils.ConfigureThreadPoolSettingsForStorageTests();
// Pre-create table, if required
manager = new UnitTestAzureTableDataManager(TestDefaultConfiguration.DataConnectionString, NullLoggerFactory.Instance);
PartitionKey = "PK-AzureTableDataManagerTests-" + Guid.NewGuid();
}
[SkippableFact, TestCategory("Functional")]
public async Task AzureTableDataManager_CreateTableEntryAsync()
{
var data = GenerateNewData();
await manager.CreateTableEntryAsync(data);
try
{
var data2 = data.Clone();
data2.StringData = "NewData";
await manager.CreateTableEntryAsync(data2);
Assert.True(false, "Should have thrown StorageException.");
}
catch(StorageException exc)
{
Assert.Equal((int)HttpStatusCode.Conflict, exc.RequestInformation.HttpStatusCode); // "Creating an already existing entry."
HttpStatusCode httpStatusCode;
string restStatus;
AzureStorageUtils.EvaluateException(exc, out httpStatusCode, out restStatus, true);
Assert.Equal(HttpStatusCode.Conflict, httpStatusCode);
Assert.Equal("EntityAlreadyExists", restStatus);
}
var tuple = await manager.ReadSingleTableEntryAsync(data.PartitionKey, data.RowKey);
Assert.Equal(data.StringData, tuple.Item1.StringData);
}
[SkippableFact, TestCategory("Functional")]
public async Task AzureTableDataManager_UpsertTableEntryAsync()
{
var data = GenerateNewData();
await manager.UpsertTableEntryAsync(data);
var tuple = await manager.ReadSingleTableEntryAsync(data.PartitionKey, data.RowKey);
Assert.Equal(data.StringData, tuple.Item1.StringData);
var data2 = data.Clone();
data2.StringData = "NewData";
await manager.UpsertTableEntryAsync(data2);
tuple = await manager.ReadSingleTableEntryAsync(data2.PartitionKey, data2.RowKey);
Assert.Equal(data2.StringData, tuple.Item1.StringData);
}
[SkippableFact, TestCategory("Functional")]
public async Task AzureTableDataManager_UpdateTableEntryAsync()
{
var data = GenerateNewData();
try
{
await manager.UpdateTableEntryAsync(data, AzureStorageUtils.ANY_ETAG);
Assert.True(false, "Should have thrown StorageException.");
}
catch(StorageException exc)
{
Assert.Equal((int)HttpStatusCode.NotFound, exc.RequestInformation.HttpStatusCode); // "Update before insert."
HttpStatusCode httpStatusCode;
string restStatus;
AzureStorageUtils.EvaluateException(exc, out httpStatusCode, out restStatus, true);
Assert.Equal(HttpStatusCode.NotFound, httpStatusCode);
Assert.Equal(StorageErrorCodeStrings.ResourceNotFound, restStatus);
}
await manager.UpsertTableEntryAsync(data);
var tuple = await manager.ReadSingleTableEntryAsync(data.PartitionKey, data.RowKey);
Assert.Equal(data.StringData, tuple.Item1.StringData);
var data2 = data.Clone();
data2.StringData = "NewData";
string eTag1 = await manager.UpdateTableEntryAsync(data2, AzureStorageUtils.ANY_ETAG);
tuple = await manager.ReadSingleTableEntryAsync(data2.PartitionKey, data2.RowKey);
Assert.Equal(data2.StringData, tuple.Item1.StringData);
var data3 = data.Clone();
data3.StringData = "EvenNewerData";
string ignoredETag = await manager.UpdateTableEntryAsync(data3, eTag1);
tuple = await manager.ReadSingleTableEntryAsync(data3.PartitionKey, data3.RowKey);
Assert.Equal(data3.StringData, tuple.Item1.StringData);
try
{
string eTag3 = await manager.UpdateTableEntryAsync(data3.Clone(), eTag1);
Assert.True(false, "Should have thrown StorageException.");
}
catch(StorageException exc)
{
Assert.Equal((int)HttpStatusCode.PreconditionFailed, exc.RequestInformation.HttpStatusCode); // "Wrong eTag"
HttpStatusCode httpStatusCode;
string restStatus;
AzureStorageUtils.EvaluateException(exc, out httpStatusCode, out restStatus, true);
Assert.Equal(HttpStatusCode.PreconditionFailed, httpStatusCode);
Assert.True(restStatus == TableErrorCodeStrings.UpdateConditionNotSatisfied
|| restStatus == StorageErrorCodeStrings.ConditionNotMet, restStatus);
}
}
[SkippableFact, TestCategory("Functional")]
public async Task AzureTableDataManager_DeleteTableAsync()
{
var data = GenerateNewData();
try
{
await manager.DeleteTableEntryAsync(data, AzureStorageUtils.ANY_ETAG);
Assert.True(false, "Should have thrown StorageException.");
}
catch(StorageException exc)
{
Assert.Equal((int)HttpStatusCode.NotFound, exc.RequestInformation.HttpStatusCode); // "Delete before create."
HttpStatusCode httpStatusCode;
string restStatus;
AzureStorageUtils.EvaluateException(exc, out httpStatusCode, out restStatus, true);
Assert.Equal(HttpStatusCode.NotFound, httpStatusCode);
Assert.Equal(StorageErrorCodeStrings.ResourceNotFound, restStatus);
}
string eTag1 = await manager.UpsertTableEntryAsync(data);
await manager.DeleteTableEntryAsync(data, eTag1);
try
{
await manager.DeleteTableEntryAsync(data, eTag1);
Assert.True(false, "Should have thrown StorageException.");
}
catch(StorageException exc)
{
Assert.Equal((int)HttpStatusCode.NotFound, exc.RequestInformation.HttpStatusCode); // "Deleting an already deleted item."
HttpStatusCode httpStatusCode;
string restStatus;
AzureStorageUtils.EvaluateException(exc, out httpStatusCode, out restStatus, true);
Assert.Equal(HttpStatusCode.NotFound, httpStatusCode);
Assert.Equal(StorageErrorCodeStrings.ResourceNotFound, restStatus);
}
var tuple = await manager.ReadSingleTableEntryAsync(data.PartitionKey, data.RowKey);
Assert.Null(tuple);
}
[SkippableFact, TestCategory("Functional")]
public async Task AzureTableDataManager_MergeTableAsync()
{
var data = GenerateNewData();
try
{
await manager.MergeTableEntryAsync(data, AzureStorageUtils.ANY_ETAG);
Assert.True(false, "Should have thrown StorageException.");
}
catch(StorageException exc)
{
Assert.Equal((int)HttpStatusCode.NotFound, exc.RequestInformation.HttpStatusCode); // "Merge before create."
HttpStatusCode httpStatusCode;
string restStatus;
AzureStorageUtils.EvaluateException(exc, out httpStatusCode, out restStatus, true);
Assert.Equal(HttpStatusCode.NotFound, httpStatusCode);
Assert.Equal(StorageErrorCodeStrings.ResourceNotFound, restStatus);
}
string eTag1 = await manager.UpsertTableEntryAsync(data);
var data2 = data.Clone();
data2.StringData = "NewData";
await manager.MergeTableEntryAsync(data2, eTag1);
try
{
await manager.MergeTableEntryAsync(data, eTag1);
Assert.True(false, "Should have thrown StorageException.");
}
catch(StorageException exc)
{
Assert.Equal((int)HttpStatusCode.PreconditionFailed, exc.RequestInformation.HttpStatusCode); // "Wrong eTag."
HttpStatusCode httpStatusCode;
string restStatus;
AzureStorageUtils.EvaluateException(exc, out httpStatusCode, out restStatus, true);
Assert.Equal(HttpStatusCode.PreconditionFailed, httpStatusCode);
Assert.True(restStatus == TableErrorCodeStrings.UpdateConditionNotSatisfied
|| restStatus == StorageErrorCodeStrings.ConditionNotMet, restStatus);
}
var tuple = await manager.ReadSingleTableEntryAsync(data.PartitionKey, data.RowKey);
Assert.Equal("NewData", tuple.Item1.StringData);
}
[SkippableFact, TestCategory("Functional")]
public async Task AzureTableDataManager_ReadSingleTableEntryAsync()
{
var data = GenerateNewData();
var tuple = await manager.ReadSingleTableEntryAsync(data.PartitionKey, data.RowKey);
Assert.Null(tuple);
}
[SkippableFact, TestCategory("Functional")]
public async Task AzureTableDataManager_InsertTwoTableEntriesConditionallyAsync()
{
StorageEmulatorUtilities.EnsureEmulatorIsNotUsed();
var data1 = GenerateNewData();
var data2 = GenerateNewData();
try
{
await manager.InsertTwoTableEntriesConditionallyAsync(data1, data2, AzureStorageUtils.ANY_ETAG);
}
catch(StorageException exc)
{
Assert.Equal((int)HttpStatusCode.NotFound, exc.RequestInformation.HttpStatusCode); // "Upadte item 2 before created it."
HttpStatusCode httpStatusCode;
string restStatus;
AzureStorageUtils.EvaluateException(exc, out httpStatusCode, out restStatus, true);
Assert.Equal(HttpStatusCode.NotFound, httpStatusCode);
Assert.Equal(StorageErrorCodeStrings.ResourceNotFound, restStatus);
}
string etag = await manager.CreateTableEntryAsync(data2.Clone());
var tuple = await manager.InsertTwoTableEntriesConditionallyAsync(data1, data2, etag);
try
{
await manager.InsertTwoTableEntriesConditionallyAsync(data1.Clone(), data2.Clone(), tuple.Item2);
Assert.True(false, "Should have thrown StorageException.");
}
catch(StorageException exc)
{
Assert.Equal((int)HttpStatusCode.Conflict, exc.RequestInformation.HttpStatusCode); // "Inserting an already existing item 1."
HttpStatusCode httpStatusCode;
string restStatus;
AzureStorageUtils.EvaluateException(exc, out httpStatusCode, out restStatus, true);
Assert.Equal(HttpStatusCode.Conflict, httpStatusCode);
Assert.Equal("EntityAlreadyExists", restStatus);
}
try
{
await manager.InsertTwoTableEntriesConditionallyAsync(data1.Clone(), data2.Clone(), AzureStorageUtils.ANY_ETAG);
Assert.True(false, "Should have thrown StorageException.");
}
catch(StorageException exc)
{
Assert.Equal((int)HttpStatusCode.Conflict, exc.RequestInformation.HttpStatusCode); // "Inserting an already existing item 1 AND wring eTag"
HttpStatusCode httpStatusCode;
string restStatus;
AzureStorageUtils.EvaluateException(exc, out httpStatusCode, out restStatus, true);
Assert.Equal(HttpStatusCode.Conflict, httpStatusCode);
Assert.Equal("EntityAlreadyExists", restStatus);
};
}
[SkippableFact, TestCategory("Functional")]
public async Task AzureTableDataManager_UpdateTwoTableEntriesConditionallyAsync()
{
StorageEmulatorUtilities.EnsureEmulatorIsNotUsed();
var data1 = GenerateNewData();
var data2 = GenerateNewData();
try
{
await manager.UpdateTwoTableEntriesConditionallyAsync(data1, AzureStorageUtils.ANY_ETAG, data2, AzureStorageUtils.ANY_ETAG);
}
catch(StorageException exc)
{
Assert.Equal((int)HttpStatusCode.NotFound, exc.RequestInformation.HttpStatusCode); // "Update before insert."
HttpStatusCode httpStatusCode;
string restStatus;
AzureStorageUtils.EvaluateException(exc, out httpStatusCode, out restStatus, true);
Assert.Equal(HttpStatusCode.NotFound, httpStatusCode);
Assert.Equal(StorageErrorCodeStrings.ResourceNotFound, restStatus);
}
string etag = await manager.CreateTableEntryAsync(data2.Clone());
var tuple1 = await manager.InsertTwoTableEntriesConditionallyAsync(data1, data2, etag);
var tuple2 = await manager.UpdateTwoTableEntriesConditionallyAsync(data1, tuple1.Item1, data2, tuple1.Item2);
try
{
await manager.UpdateTwoTableEntriesConditionallyAsync(data1, tuple1.Item1, data2, tuple1.Item2);
Assert.True(false, "Should have thrown StorageException.");
}
catch(StorageException exc)
{
Assert.Equal((int)HttpStatusCode.PreconditionFailed, exc.RequestInformation.HttpStatusCode); // "Wrong eTag"
HttpStatusCode httpStatusCode;
string restStatus;
AzureStorageUtils.EvaluateException(exc, out httpStatusCode, out restStatus, true);
Assert.Equal(HttpStatusCode.PreconditionFailed, httpStatusCode);
Assert.True(restStatus == TableErrorCodeStrings.UpdateConditionNotSatisfied
|| restStatus == StorageErrorCodeStrings.ConditionNotMet, restStatus);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using nHydrate.Generator.Common.Util;
namespace nHydrate.DataImport.SqlClient
{
/// <summary>
/// Summary description for DbHelper.
/// </summary>
public class DatabaseHelper : IDatabaseHelper
{
internal DatabaseHelper()
{
}
#region Public Methods
public bool TestConnectionString(string connectString)
{
var valid = false;
var conn = new System.Data.SqlClient.SqlConnection();
try
{
conn.ConnectionString = connectString;
conn.Open();
valid = true;
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.ToString());
valid = false;
}
finally
{
conn.Close();
}
return valid;
}
public DataTable GetStaticData(string connectionString, Entity entity)
{
if (entity == null) return null;
var auditFields = new List<SpecialField>();
var importDomain = new ImportDomain();
var dbEntity = importDomain.Import(connectionString, auditFields).EntityList.FirstOrDefault(x => x.Name == entity.Name);
if (dbEntity == null) return null;
//Get the columns that actually exist in the database
var columnList = dbEntity.FieldList;
var fieldList = entity.FieldList.Where(x => !x.DataType.IsBinaryType() && x.DataType != SqlDbType.Timestamp).ToList();
//Load the static data grid
var sb = new StringBuilder();
sb.Append("SELECT ");
foreach (var field in fieldList)
{
if (columnList.Count(x => x.Name.Match(field.Name)) == 1)
{
sb.Append("[" + field.Name + "]");
}
else
{
sb.Append("'' AS [" + field.Name + "]");
}
if (fieldList.ToList().IndexOf(field) < fieldList.Count - 1) sb.Append(",");
}
sb.AppendLine(" FROM [" + entity.Name + "]");
var ds = DatabaseHelper.ExecuteDataset(connectionString, sb.ToString());
if (ds.Tables.Count == 0) return null;
return ds.Tables[0];
}
#endregion
#region SQL
internal static DataSet ExecuteDataset(string connectionString, string sql)
{
var retVal = new DataSet();
using (var connection = new SqlConnection(connectionString))
{
var command = new SqlCommand();
command.CommandType = CommandType.Text;
command.CommandText = sql;
command.Connection = connection;
command.CommandTimeout = 300;
var da = new SqlDataAdapter();
da.SelectCommand = (SqlCommand)command;
try
{
da.Fill(retVal);
connection.Open();
}
catch (Exception /*ignored*/)
{
throw;
}
finally
{
if (connection.State != ConnectionState.Closed)
{
connection.Close();
}
}
}
return retVal;
}
internal static int ExecuteNonQuery(IDbCommand command)
{
var cmd = (SqlCommand)command;
return cmd.ExecuteNonQuery();
}
internal static IDbConnection GetConnection(string connectionString)
{
//if (sqlConnection == null)
//{
SqlConnection.ClearAllPools(); //If we do NOT do this, sometimes we get pool errors
var sqlConnection = new SqlConnection();
sqlConnection.ConnectionString = connectionString;
//}
return sqlConnection;
}
internal static SqlDataReader ExecuteReader(IDbConnection connection, CommandType cmdType, string stmt)
{
var cmd = GetCommand();
cmd.CommandText = stmt;
cmd.CommandType = cmdType;
cmd.CommandTimeout = 300;
if (connection.State == ConnectionState.Closed)
connection.Open();
cmd.Connection = connection;
return (SqlDataReader)cmd.ExecuteReader();
}
internal static SqlDataReader ExecuteReader(string connectString, CommandType cmdType, string stmt)
{
try
{
var connection = GetConnection(connectString);
connection.Open();
return ExecuteReader(connection, cmdType, stmt);
}
catch (Exception /*ignored*/)
{
throw;
}
}
internal static IDbCommand GetCommand()
{
var cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
return cmd;
}
internal static void Fill(IDbDataAdapter da, DataTable dt)
{
var sqlDa = (SqlDataAdapter)da;
sqlDa.Fill(dt);
}
internal static void Update(IDbDataAdapter da, DataTable dt)
{
var sqlDa = (SqlDataAdapter)da;
if (dt != null && dt.Rows.Count > 0)
{
try
{
sqlDa.Update(dt);
}
catch (Exception ex)
{
Console.Write(ex.ToString());
throw;
}
}
}
internal static void Update(IDbDataAdapter da, DataRow[] rows)
{
var sqlDa = (SqlDataAdapter)da;
if (rows.Length > 0)
{
try
{
sqlDa.Update(rows);
}
catch (Exception ex)
{
Console.Write(ex.ToString());
throw;
}
}
}
#endregion
#region Methods
internal static bool IsValidSQLDataType(nHydrate.DataImport.SqlNativeTypes nativeType)
{
switch (nativeType)
{
case SqlNativeTypes.bigint:
case SqlNativeTypes.binary:
case SqlNativeTypes.bit:
case SqlNativeTypes.@char:
case SqlNativeTypes.date:
case SqlNativeTypes.datetime:
case SqlNativeTypes.datetime2:
case SqlNativeTypes.datetimeoffset:
case SqlNativeTypes.@decimal:
case SqlNativeTypes.@float:
//SqlNativeTypes.geography
//SqlNativeTypes.geometry
//SqlNativeTypes.hierarchyid
case SqlNativeTypes.image:
case SqlNativeTypes.@int:
case SqlNativeTypes.money:
case SqlNativeTypes.nchar:
case SqlNativeTypes.ntext:
case SqlNativeTypes.numeric:
case SqlNativeTypes.nvarchar:
case SqlNativeTypes.real:
case SqlNativeTypes.smalldatetime:
case SqlNativeTypes.smallint:
case SqlNativeTypes.smallmoney:
case SqlNativeTypes.sql_variant:
//SqlNativeTypes.sysname
case SqlNativeTypes.text:
case SqlNativeTypes.time:
case SqlNativeTypes.timestamp:
case SqlNativeTypes.tinyint:
//case SqlNativeTypes.:
case SqlNativeTypes.uniqueidentifier:
case SqlNativeTypes.varbinary:
case SqlNativeTypes.varchar:
//case SqlNativeTypes.:
case SqlNativeTypes.xml:
return true;
default:
return false;
}
}
internal static SqlDbType GetSQLDataType(string type, Dictionary<string, string> udtTypes)
{
// NOTE: highly recommended to use Case insensitive dictionary
// example:
// var caseInsensitiveDictionary = new Dictionary<string, string>( StringComparer.OrdinalIgnoreCase );
if (null != udtTypes && udtTypes.ContainsKey(type))
{
type = udtTypes[type];
}
if (int.TryParse(type, out var xType))
{
return GetSQLDataType((SqlNativeTypes)xType);
}
else if (Enum.TryParse<SqlNativeTypes>(type, out var sType))
{
return GetSQLDataType(sType);
}
throw new Exception("Unknown native SQL type '" + type + "'!");
}
private static SqlDbType GetSQLDataType(nHydrate.DataImport.SqlNativeTypes nativeType)
{
switch (nativeType)
{
case SqlNativeTypes.bigint: return SqlDbType.BigInt;
case SqlNativeTypes.binary: return SqlDbType.Binary;
case SqlNativeTypes.bit: return SqlDbType.Bit;
case SqlNativeTypes.@char: return SqlDbType.Char;
case SqlNativeTypes.date: return SqlDbType.Date;
case SqlNativeTypes.datetime: return SqlDbType.DateTime;
case SqlNativeTypes.datetime2: return SqlDbType.DateTime2;
case SqlNativeTypes.datetimeoffset: return SqlDbType.DateTimeOffset;
case SqlNativeTypes.@decimal: return SqlDbType.Decimal;
case SqlNativeTypes.@float: return SqlDbType.Float;
//SqlNativeTypes.geography
//SqlNativeTypes.geometry
//SqlNativeTypes.hierarchyid
case SqlNativeTypes.image: return SqlDbType.Image;
case SqlNativeTypes.@int: return SqlDbType.Int;
case SqlNativeTypes.money: return SqlDbType.Money;
case SqlNativeTypes.nchar: return SqlDbType.NChar;
case SqlNativeTypes.ntext: return SqlDbType.NText;
case SqlNativeTypes.numeric: return SqlDbType.Decimal;
case SqlNativeTypes.nvarchar: return SqlDbType.NVarChar;
case SqlNativeTypes.real: return SqlDbType.Real;
case SqlNativeTypes.smalldatetime: return SqlDbType.SmallDateTime;
case SqlNativeTypes.smallint: return SqlDbType.SmallInt;
case SqlNativeTypes.smallmoney: return SqlDbType.SmallMoney;
case SqlNativeTypes.sql_variant: return SqlDbType.Structured;
//SqlNativeTypes.sysname
case SqlNativeTypes.text: return SqlDbType.Text;
case SqlNativeTypes.time: return SqlDbType.Time;
case SqlNativeTypes.timestamp: return SqlDbType.Timestamp;
case SqlNativeTypes.tinyint: return SqlDbType.TinyInt;
//case SqlNativeTypes.: return SqlDbType.Udt;
case SqlNativeTypes.uniqueidentifier: return SqlDbType.UniqueIdentifier;
case SqlNativeTypes.varbinary: return SqlDbType.VarBinary;
case SqlNativeTypes.varchar: return SqlDbType.VarChar;
//case SqlNativeTypes.: return SqlDbType.Variant;
case SqlNativeTypes.xml: return SqlDbType.Xml;
default: throw new Exception("Unknown native SQL type '" + nativeType.ToString() + "'!");
}
}
#endregion
}
}
| |
using System;
using NUnit.Framework;
using OpenQA.Selenium.Environment;
namespace OpenQA.Selenium
{
[TestFixture]
public class FrameSwitchingTest : DriverTestFixture
{
// ----------------------------------------------------------------------------------------------
//
// Tests that WebDriver doesn't do anything fishy when it navigates to a page with frames.
//
// ----------------------------------------------------------------------------------------------
[Test]
public void ShouldAlwaysFocusOnTheTopMostFrameAfterANavigationEvent()
{
driver.Url = framesetPage;
IWebElement element = driver.FindElement(By.TagName("frameset"));
Assert.That(element, Is.Not.Null);
}
[Test]
public void ShouldNotAutomaticallySwitchFocusToAnIFrameWhenAPageContainingThemIsLoaded()
{
driver.Url = iframePage;
driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(1);
IWebElement element = driver.FindElement(By.Id("iframe_page_heading"));
driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(0);
Assert.That(element, Is.Not.Null);
}
[Test]
public void ShouldOpenPageWithBrokenFrameset()
{
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("framesetPage3.html");
IWebElement frame1 = driver.FindElement(By.Id("first"));
driver.SwitchTo().Frame(frame1);
driver.SwitchTo().DefaultContent();
IWebElement frame2 = driver.FindElement(By.Id("second"));
try
{
driver.SwitchTo().Frame(frame2);
}
catch (WebDriverException)
{
// IE9 can not switch to this broken frame - it has no window.
}
}
// ----------------------------------------------------------------------------------------------
//
// Tests that WebDriver can switch to frames as expected.
//
// ----------------------------------------------------------------------------------------------
[Test]
public void ShouldBeAbleToSwitchToAFrameByItsIndex()
{
driver.Url = framesetPage;
driver.SwitchTo().Frame(1);
Assert.AreEqual("2", driver.FindElement(By.Id("pageNumber")).Text);
}
[Test]
public void ShouldBeAbleToSwitchToAnIframeByItsIndex()
{
driver.Url = iframePage;
driver.SwitchTo().Frame(0);
Assert.AreEqual("name", driver.FindElement(By.Name("id-name1")).GetAttribute("value"));
}
[Test]
public void ShouldBeAbleToSwitchToAFrameByItsName()
{
driver.Url = framesetPage;
driver.SwitchTo().Frame("fourth");
Assert.AreEqual("child1", driver.FindElement(By.TagName("frame")).GetAttribute("name"));
}
[Test]
public void ShouldBeAbleToSwitchToAnIframeByItsName()
{
driver.Url = iframePage;
driver.SwitchTo().Frame("iframe1-name");
Assert.AreEqual("name", driver.FindElement(By.Name("id-name1")).GetAttribute("value"));
}
[Test]
public void ShouldBeAbleToSwitchToAFrameByItsID()
{
driver.Url = framesetPage;
driver.SwitchTo().Frame("fifth");
Assert.AreEqual("Open new window", driver.FindElement(By.Name("windowOne")).Text);
}
[Test]
public void ShouldBeAbleToSwitchToAnIframeByItsID()
{
driver.Url = iframePage;
driver.SwitchTo().Frame("iframe1");
Assert.AreEqual("name", driver.FindElement(By.Name("id-name1")).GetAttribute("value"));
}
[Test]
public void ShouldBeAbleToSwitchToFrameWithNameContainingDot()
{
driver.Url = framesetPage;
driver.SwitchTo().Frame("sixth.iframe1");
Assert.That(driver.FindElement(By.TagName("body")).Text, Does.Contain("Page number 3"));
}
[Test]
public void ShouldBeAbleToSwitchToAFrameUsingAPreviouslyLocatedWebElement()
{
driver.Url = framesetPage;
IWebElement frame = driver.FindElement(By.TagName("frame"));
driver.SwitchTo().Frame(frame);
Assert.AreEqual("1", driver.FindElement(By.Id("pageNumber")).Text);
}
[Test]
public void ShouldBeAbleToSwitchToAnIFrameUsingAPreviouslyLocatedWebElement()
{
driver.Url = iframePage;
IWebElement frame = driver.FindElement(By.TagName("iframe"));
driver.SwitchTo().Frame(frame);
Assert.AreEqual("name", driver.FindElement(By.Name("id-name1")).GetAttribute("value"));
}
[Test]
public void ShouldEnsureElementIsAFrameBeforeSwitching()
{
driver.Url = framesetPage;
IWebElement frame = driver.FindElement(By.TagName("frameset"));
Assert.That(() => driver.SwitchTo().Frame(frame), Throws.InstanceOf<NoSuchFrameException>());
}
[Test]
public void FrameSearchesShouldBeRelativeToTheCurrentlySelectedFrame()
{
driver.Url = framesetPage;
IWebElement frameElement = WaitFor(() => driver.FindElement(By.Name("second")), "did not find frame");
driver.SwitchTo().Frame(frameElement);
Assert.AreEqual("2", driver.FindElement(By.Id("pageNumber")).Text);
try
{
driver.SwitchTo().Frame("third");
Assert.Fail();
}
catch (NoSuchFrameException)
{
// Do nothing
}
driver.SwitchTo().DefaultContent();
driver.SwitchTo().Frame("third");
try
{
driver.SwitchTo().Frame("second");
Assert.Fail();
}
catch (NoSuchFrameException)
{
// Do nothing
}
driver.SwitchTo().DefaultContent();
driver.SwitchTo().Frame("second");
Assert.AreEqual("2", driver.FindElement(By.Id("pageNumber")).Text);
}
[Test]
public void ShouldSelectChildFramesByChainedCalls()
{
driver.Url = framesetPage;
driver.SwitchTo().Frame("fourth").SwitchTo().Frame("child2");
Assert.AreEqual("11", driver.FindElement(By.Id("pageNumber")).Text);
}
[Test]
public void ShouldThrowFrameNotFoundExceptionLookingUpSubFramesWithSuperFrameNames()
{
driver.Url = framesetPage;
driver.SwitchTo().Frame("fourth");
Assert.That(() => driver.SwitchTo().Frame("second"), Throws.InstanceOf<NoSuchFrameException>());
}
[Test]
public void ShouldThrowAnExceptionWhenAFrameCannotBeFound()
{
driver.Url = xhtmlTestPage;
Assert.That(() => driver.SwitchTo().Frame("Nothing here"), Throws.InstanceOf<NoSuchFrameException>());
}
[Test]
public void ShouldThrowAnExceptionWhenAFrameCannotBeFoundByIndex()
{
driver.Url = xhtmlTestPage;
Assert.That(() => driver.SwitchTo().Frame(27), Throws.InstanceOf<NoSuchFrameException>());
}
[Test]
[IgnoreBrowser(Browser.Opera, "Browser does not support parent frame navigation")]
public void ShouldBeAbleToSwitchToParentFrame()
{
driver.Url = framesetPage;
driver.SwitchTo().Frame("fourth").SwitchTo().ParentFrame().SwitchTo().Frame("first");
Assert.AreEqual("1", driver.FindElement(By.Id("pageNumber")).Text);
}
[Test]
[IgnoreBrowser(Browser.Opera, "Browser does not support parent frame navigation")]
public void ShouldBeAbleToSwitchToParentFrameFromASecondLevelFrame()
{
driver.Url = framesetPage;
driver.SwitchTo().Frame("fourth").SwitchTo().Frame("child1").SwitchTo().ParentFrame().SwitchTo().Frame("child2");
Assert.AreEqual("11", driver.FindElement(By.Id("pageNumber")).Text);
}
[Test]
[IgnoreBrowser(Browser.Opera, "Browser does not support parent frame navigation")]
public void SwitchingToParentFrameFromDefaultContextIsNoOp()
{
driver.Url = xhtmlTestPage;
driver.SwitchTo().ParentFrame();
Assert.AreEqual("XHTML Test Page", driver.Title);
}
[Test]
[IgnoreBrowser(Browser.Opera, "Browser does not support parent frame navigation")]
public void ShouldBeAbleToSwitchToParentFromAnIframe()
{
driver.Url = iframePage;
driver.SwitchTo().Frame(0);
driver.SwitchTo().ParentFrame();
driver.FindElement(By.Id("iframe_page_heading"));
}
// ----------------------------------------------------------------------------------------------
//
// General frame handling behavior tests
//
// ----------------------------------------------------------------------------------------------
[Test]
public void ShouldContinueToReferToTheSameFrameOnceItHasBeenSelected()
{
driver.Url = framesetPage;
driver.SwitchTo().Frame(2);
IWebElement checkbox = driver.FindElement(By.XPath("//input[@name='checky']"));
checkbox.Click();
checkbox.Submit();
Assert.AreEqual("Success!", driver.FindElement(By.XPath("//p")).Text);
}
[Test]
public void ShouldFocusOnTheReplacementWhenAFrameFollowsALinkToA_TopTargettedPage()
{
driver.Url = framesetPage;
driver.SwitchTo().Frame(0);
driver.FindElement(By.LinkText("top")).Click();
// TODO(simon): Avoid going too fast when native events are there.
System.Threading.Thread.Sleep(1000);
Assert.AreEqual("XHTML Test Page", driver.Title);
}
[Test]
public void ShouldAllowAUserToSwitchFromAnIframeBackToTheMainContentOfThePage()
{
driver.Url = iframePage;
driver.SwitchTo().Frame(0);
driver.SwitchTo().DefaultContent();
driver.FindElement(By.Id("iframe_page_heading"));
}
[Test]
public void ShouldAllowTheUserToSwitchToAnIFrameAndRemainFocusedOnIt()
{
driver.Url = iframePage;
driver.SwitchTo().Frame(0);
driver.FindElement(By.Id("submitButton")).Click();
string hello = GetTextOfGreetingElement();
Assert.AreEqual(hello, "Success!");
}
[Test]
public void ShouldBeAbleToClickInAFrame()
{
driver.Url = framesetPage;
driver.SwitchTo().Frame("third");
// This should replace frame "third" ...
driver.FindElement(By.Id("submitButton")).Click();
// driver should still be focused on frame "third" ...
Assert.AreEqual("Success!", GetTextOfGreetingElement());
// Make sure it was really frame "third" which was replaced ...
driver.SwitchTo().DefaultContent().SwitchTo().Frame("third");
Assert.AreEqual("Success!", GetTextOfGreetingElement());
}
[Test]
public void ShouldBeAbleToClickInAFrameThatRewritesTopWindowLocation()
{
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("click_tests/issue5237.html");
driver.SwitchTo().Frame("search");
driver.FindElement(By.Id("submit")).Click();
driver.SwitchTo().DefaultContent();
WaitFor(() => { return driver.Title == "Target page for issue 5237"; }, "Browser title was not 'Target page for issue 5237'");
}
[Test]
public void ShouldBeAbleToClickInASubFrame()
{
driver.Url = framesetPage;
driver.SwitchTo().Frame("sixth").SwitchTo().Frame("iframe1");
// This should replaxe frame "iframe1" inside frame "sixth" ...
driver.FindElement(By.Id("submitButton")).Click();
// driver should still be focused on frame "iframe1" inside frame "sixth" ...
Assert.AreEqual("Success!", GetTextOfGreetingElement());
// Make sure it was really frame "iframe1" inside frame "sixth" which was replaced ...
driver.SwitchTo().DefaultContent().SwitchTo().Frame("sixth").SwitchTo().Frame("iframe1");
Assert.AreEqual("Success!", driver.FindElement(By.Id("greeting")).Text);
}
[Test]
public void ShouldBeAbleToFindElementsInIframesByXPath()
{
driver.Url = iframePage;
driver.SwitchTo().Frame("iframe1");
IWebElement element = driver.FindElement(By.XPath("//*[@id = 'changeme']"));
Assert.That(element, Is.Not.Null);
}
[Test]
public void GetCurrentUrlShouldReturnTopLevelBrowsingContextUrl()
{
driver.Url = framesetPage;
Assert.AreEqual(framesetPage, driver.Url);
driver.SwitchTo().Frame("second");
Assert.AreEqual(framesetPage, driver.Url);
}
[Test]
public void GetCurrentUrlShouldReturnTopLevelBrowsingContextUrlForIframes()
{
driver.Url = iframePage;
Assert.AreEqual(iframePage, driver.Url);
driver.SwitchTo().Frame("iframe1");
Assert.AreEqual(iframePage, driver.Url);
}
[Test]
public void ShouldBeAbleToSwitchToTheTopIfTheFrameIsDeletedFromUnderUs()
{
driver.Url = deletingFrame;
driver.SwitchTo().Frame("iframe1");
IWebElement killIframe = driver.FindElement(By.Id("killIframe"));
killIframe.Click();
driver.SwitchTo().DefaultContent();
AssertFrameNotPresent("iframe1");
IWebElement addIFrame = driver.FindElement(By.Id("addBackFrame"));
addIFrame.Click();
WaitFor(() => driver.FindElement(By.Id("iframe1")), "Did not find frame element");
driver.SwitchTo().Frame("iframe1");
WaitFor(() => driver.FindElement(By.Id("success")), "Did not find element in frame");
}
[Test]
public void ShouldBeAbleToSwitchToTheTopIfTheFrameIsDeletedFromUnderUsWithFrameIndex()
{
driver.Url = deletingFrame;
int iframe = 0;
WaitFor(() => FrameExistsAndSwitchedTo(iframe), "Did not switch to frame");
// we should be in the frame now
IWebElement killIframe = driver.FindElement(By.Id("killIframe"));
killIframe.Click();
driver.SwitchTo().DefaultContent();
IWebElement addIFrame = driver.FindElement(By.Id("addBackFrame"));
addIFrame.Click();
WaitFor(() => FrameExistsAndSwitchedTo(iframe), "Did not switch to frame");
WaitFor(() => driver.FindElement(By.Id("success")), "Did not find element in frame");
}
[Test]
public void ShouldBeAbleToSwitchToTheTopIfTheFrameIsDeletedFromUnderUsWithWebelement()
{
driver.Url = deletingFrame;
IWebElement iframe = driver.FindElement(By.Id("iframe1"));
WaitFor(() => FrameExistsAndSwitchedTo(iframe), "Did not switch to frame");
// we should be in the frame now
IWebElement killIframe = driver.FindElement(By.Id("killIframe"));
killIframe.Click();
driver.SwitchTo().DefaultContent();
IWebElement addIFrame = driver.FindElement(By.Id("addBackFrame"));
addIFrame.Click();
iframe = driver.FindElement(By.Id("iframe1"));
WaitFor(() => FrameExistsAndSwitchedTo(iframe), "Did not switch to frame");
WaitFor(() => driver.FindElement(By.Id("success")), "Did not find element in frame");
}
[Test]
[IgnoreBrowser(Browser.Chrome, "Chrome driver throws NoSuchElementException, spec is unclear")]
[IgnoreBrowser(Browser.IE, "IE driver throws NoSuchElementException, spec is unclear")]
public void ShouldNotBeAbleToDoAnythingTheFrameIsDeletedFromUnderUs()
{
driver.Url = deletingFrame;
driver.SwitchTo().Frame("iframe1");
IWebElement killIframe = driver.FindElement(By.Id("killIframe"));
killIframe.Click();
Assert.That(() => driver.FindElement(By.Id("killIframe")), Throws.InstanceOf<NoSuchFrameException>());
}
[Test]
public void ShouldReturnWindowTitleInAFrameset()
{
driver.Url = framesetPage;
driver.SwitchTo().Frame("third");
Assert.AreEqual("Unique title", driver.Title);
}
[Test]
public void JavaScriptShouldExecuteInTheContextOfTheCurrentFrame()
{
IJavaScriptExecutor executor = driver as IJavaScriptExecutor;
driver.Url = framesetPage;
Assert.That((bool)executor.ExecuteScript("return window == window.top"), Is.True);
driver.SwitchTo().Frame("third");
Assert.That((bool)executor.ExecuteScript("return window != window.top"), Is.True);
}
[Test]
[IgnoreBrowser(Browser.Safari, "Not yet implemented")]
public void ShouldNotSwitchMagicallyToTheTopWindow()
{
string baseUrl = EnvironmentManager.Instance.UrlBuilder.WhereIs("frame_switching_tests/");
driver.Url = baseUrl + "bug4876.html";
driver.SwitchTo().Frame(0);
WaitFor(() => driver.FindElement(By.Id("inputText")), "Could not find element");
for (int i = 0; i < 20; i++)
{
try
{
IWebElement input = WaitFor(() => driver.FindElement(By.Id("inputText")), "Did not find element");
IWebElement submit = WaitFor(() => driver.FindElement(By.Id("submitButton")), "Did not find input element");
input.Clear();
input.SendKeys("rand" + new Random().Next());
submit.Click();
}
finally
{
string url = (string)((IJavaScriptExecutor)driver).ExecuteScript("return window.location.href");
// IE6 and Chrome add "?"-symbol to the end of the URL
if (url.EndsWith("?"))
{
url = url.Substring(0, url.Length - 1);
}
Assert.AreEqual(baseUrl + "bug4876_iframe.html", url);
}
}
}
[Test]
[NeedsFreshDriver(IsCreatedAfterTest = true)]
public void GetShouldSwitchToDefaultContext()
{
driver.Url = iframePage;
driver.SwitchTo().Frame(driver.FindElement(By.Id("iframe1")));
driver.FindElement(By.Id("cheese")); // Found on formPage.html but not on iframes.html.
driver.Url = iframePage; // This must effectively switchTo().defaultContent(), too.
driver.FindElement(By.Id("iframe1"));
}
// ----------------------------------------------------------------------------------------------
//
// Frame handling behavior tests not included in Java tests
//
// ----------------------------------------------------------------------------------------------
[Test]
public void ShouldBeAbleToFlipToAFrameIdentifiedByItsId()
{
driver.Url = framesetPage;
driver.SwitchTo().Frame("fifth");
driver.FindElement(By.Id("username"));
}
[Test]
public void ShouldBeAbleToSelectAFrameByName()
{
driver.Url = framesetPage;
driver.SwitchTo().Frame("second");
Assert.AreEqual(driver.FindElement(By.Id("pageNumber")).Text, "2");
driver.SwitchTo().DefaultContent().SwitchTo().Frame("third");
driver.FindElement(By.Id("changeme")).Click();
driver.SwitchTo().DefaultContent().SwitchTo().Frame("second");
Assert.AreEqual(driver.FindElement(By.Id("pageNumber")).Text, "2");
}
[Test]
public void ShouldBeAbleToFindElementsInIframesByName()
{
driver.Url = iframePage;
driver.SwitchTo().Frame("iframe1");
IWebElement element = driver.FindElement(By.Name("id-name1"));
Assert.That(element, Is.Not.Null);
}
private string GetTextOfGreetingElement()
{
string text = string.Empty;
DateTime end = DateTime.Now.Add(TimeSpan.FromMilliseconds(3000));
while (DateTime.Now < end)
{
try
{
IWebElement element = driver.FindElement(By.Id("greeting"));
text = element.Text;
break;
}
catch (NoSuchElementException)
{
}
}
return text;
}
private void AssertFrameNotPresent(string locator)
{
driver.SwitchTo().DefaultContent();
WaitFor(() => !FrameExistsAndSwitchedTo(locator), "Frame still present after timeout");
driver.SwitchTo().DefaultContent();
}
private bool FrameExistsAndSwitchedTo(string locator)
{
try
{
driver.SwitchTo().Frame(locator);
return true;
}
catch (NoSuchFrameException)
{
}
return false;
}
private bool FrameExistsAndSwitchedTo(int index)
{
try
{
driver.SwitchTo().Frame(index);
return true;
}
catch (NoSuchFrameException)
{
}
return false;
}
private bool FrameExistsAndSwitchedTo(IWebElement frameElement)
{
try
{
driver.SwitchTo().Frame(frameElement);
return true;
}
catch (NoSuchFrameException)
{
}
return false;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Runtime.Serialization.Formatters.Tests;
using Xunit;
namespace System.Text.Tests
{
public partial class EncodingTest : IClassFixture<CultureSetup>
{
public EncodingTest(CultureSetup setup)
{
// Setting up the culture happens externally, and only once, which is what we want.
// xUnit will keep track of it, do nothing.
}
public static IEnumerable<object[]> CodePageInfo()
{
// The layout is code page, IANA(web) name, and query string.
// Query strings may be undocumented, and IANA names will be returned from Encoding objects.
// Entries are sorted by code page.
yield return new object[] { 37, "ibm037", "ibm037" };
yield return new object[] { 37, "ibm037", "cp037" };
yield return new object[] { 37, "ibm037", "csibm037" };
yield return new object[] { 37, "ibm037", "ebcdic-cp-ca" };
yield return new object[] { 37, "ibm037", "ebcdic-cp-nl" };
yield return new object[] { 37, "ibm037", "ebcdic-cp-us" };
yield return new object[] { 37, "ibm037", "ebcdic-cp-wt" };
yield return new object[] { 437, "ibm437", "ibm437" };
yield return new object[] { 437, "ibm437", "437" };
yield return new object[] { 437, "ibm437", "cp437" };
yield return new object[] { 437, "ibm437", "cspc8codepage437" };
yield return new object[] { 500, "ibm500", "ibm500" };
yield return new object[] { 500, "ibm500", "cp500" };
yield return new object[] { 500, "ibm500", "csibm500" };
yield return new object[] { 500, "ibm500", "ebcdic-cp-be" };
yield return new object[] { 500, "ibm500", "ebcdic-cp-ch" };
yield return new object[] { 708, "asmo-708", "asmo-708" };
yield return new object[] { 720, "dos-720", "dos-720" };
yield return new object[] { 737, "ibm737", "ibm737" };
yield return new object[] { 775, "ibm775", "ibm775" };
yield return new object[] { 850, "ibm850", "ibm850" };
yield return new object[] { 850, "ibm850", "cp850" };
yield return new object[] { 852, "ibm852", "ibm852" };
yield return new object[] { 852, "ibm852", "cp852" };
yield return new object[] { 855, "ibm855", "ibm855" };
yield return new object[] { 855, "ibm855", "cp855" };
yield return new object[] { 857, "ibm857", "ibm857" };
yield return new object[] { 857, "ibm857", "cp857" };
yield return new object[] { 858, "ibm00858", "ibm00858" };
yield return new object[] { 858, "ibm00858", "ccsid00858" };
yield return new object[] { 858, "ibm00858", "cp00858" };
yield return new object[] { 858, "ibm00858", "cp858" };
yield return new object[] { 858, "ibm00858", "pc-multilingual-850+euro" };
yield return new object[] { 860, "ibm860", "ibm860" };
yield return new object[] { 860, "ibm860", "cp860" };
yield return new object[] { 861, "ibm861", "ibm861" };
yield return new object[] { 861, "ibm861", "cp861" };
yield return new object[] { 862, "dos-862", "dos-862" };
yield return new object[] { 862, "dos-862", "cp862" };
yield return new object[] { 862, "dos-862", "ibm862" };
yield return new object[] { 863, "ibm863", "ibm863" };
yield return new object[] { 863, "ibm863", "cp863" };
yield return new object[] { 864, "ibm864", "ibm864" };
yield return new object[] { 864, "ibm864", "cp864" };
yield return new object[] { 865, "ibm865", "ibm865" };
yield return new object[] { 865, "ibm865", "cp865" };
yield return new object[] { 866, "cp866", "cp866" };
yield return new object[] { 866, "cp866", "ibm866" };
yield return new object[] { 869, "ibm869", "ibm869" };
yield return new object[] { 869, "ibm869", "cp869" };
yield return new object[] { 870, "ibm870", "ibm870" };
yield return new object[] { 870, "ibm870", "cp870" };
yield return new object[] { 870, "ibm870", "csibm870" };
yield return new object[] { 870, "ibm870", "ebcdic-cp-roece" };
yield return new object[] { 870, "ibm870", "ebcdic-cp-yu" };
yield return new object[] { 874, "windows-874", "windows-874" };
yield return new object[] { 874, "windows-874", "dos-874" };
yield return new object[] { 874, "windows-874", "iso-8859-11" };
yield return new object[] { 874, "windows-874", "tis-620" };
yield return new object[] { 875, "cp875", "cp875" };
yield return new object[] { 932, "shift_jis", "shift_jis" };
yield return new object[] { 932, "shift_jis", "csshiftjis" };
yield return new object[] { 932, "shift_jis", "cswindows31j" };
yield return new object[] { 932, "shift_jis", "ms_kanji" };
yield return new object[] { 932, "shift_jis", "shift-jis" };
yield return new object[] { 932, "shift_jis", "sjis" };
yield return new object[] { 932, "shift_jis", "x-ms-cp932" };
yield return new object[] { 932, "shift_jis", "x-sjis" };
yield return new object[] { 936, "gb2312", "gb2312" };
yield return new object[] { 936, "gb2312", "chinese" };
yield return new object[] { 936, "gb2312", "cn-gb" };
yield return new object[] { 936, "gb2312", "csgb2312" };
yield return new object[] { 936, "gb2312", "csgb231280" };
yield return new object[] { 936, "gb2312", "csiso58gb231280" };
yield return new object[] { 936, "gb2312", "gb_2312-80" };
yield return new object[] { 936, "gb2312", "gb231280" };
yield return new object[] { 936, "gb2312", "gb2312-80" };
yield return new object[] { 936, "gb2312", "gbk" };
yield return new object[] { 936, "gb2312", "iso-ir-58" };
yield return new object[] { 949, "ks_c_5601-1987", "ks_c_5601-1987" };
yield return new object[] { 949, "ks_c_5601-1987", "csksc56011987" };
yield return new object[] { 949, "ks_c_5601-1987", "iso-ir-149" };
yield return new object[] { 949, "ks_c_5601-1987", "korean" };
yield return new object[] { 949, "ks_c_5601-1987", "ks_c_5601" };
yield return new object[] { 949, "ks_c_5601-1987", "ks_c_5601_1987" };
yield return new object[] { 949, "ks_c_5601-1987", "ks_c_5601-1989" };
yield return new object[] { 949, "ks_c_5601-1987", "ksc_5601" };
yield return new object[] { 949, "ks_c_5601-1987", "ksc5601" };
yield return new object[] { 949, "ks_c_5601-1987", "ks-c5601" };
yield return new object[] { 949, "ks_c_5601-1987", "ks-c-5601" };
yield return new object[] { 950, "big5", "big5" };
yield return new object[] { 950, "big5", "big5-hkscs" };
yield return new object[] { 950, "big5", "cn-big5" };
yield return new object[] { 950, "big5", "csbig5" };
yield return new object[] { 950, "big5", "x-x-big5" };
yield return new object[] { 1026, "ibm1026", "ibm1026" };
yield return new object[] { 1026, "ibm1026", "cp1026" };
yield return new object[] { 1026, "ibm1026", "csibm1026" };
yield return new object[] { 1047, "ibm01047", "ibm01047" };
yield return new object[] { 1140, "ibm01140", "ibm01140" };
yield return new object[] { 1140, "ibm01140", "ccsid01140" };
yield return new object[] { 1140, "ibm01140", "cp01140" };
yield return new object[] { 1140, "ibm01140", "ebcdic-us-37+euro" };
yield return new object[] { 1141, "ibm01141", "ibm01141" };
yield return new object[] { 1141, "ibm01141", "ccsid01141" };
yield return new object[] { 1141, "ibm01141", "cp01141" };
yield return new object[] { 1141, "ibm01141", "ebcdic-de-273+euro" };
yield return new object[] { 1142, "ibm01142", "ibm01142" };
yield return new object[] { 1142, "ibm01142", "ccsid01142" };
yield return new object[] { 1142, "ibm01142", "cp01142" };
yield return new object[] { 1142, "ibm01142", "ebcdic-dk-277+euro" };
yield return new object[] { 1142, "ibm01142", "ebcdic-no-277+euro" };
yield return new object[] { 1143, "ibm01143", "ibm01143" };
yield return new object[] { 1143, "ibm01143", "ccsid01143" };
yield return new object[] { 1143, "ibm01143", "cp01143" };
yield return new object[] { 1143, "ibm01143", "ebcdic-fi-278+euro" };
yield return new object[] { 1143, "ibm01143", "ebcdic-se-278+euro" };
yield return new object[] { 1144, "ibm01144", "ibm01144" };
yield return new object[] { 1144, "ibm01144", "ccsid01144" };
yield return new object[] { 1144, "ibm01144", "cp01144" };
yield return new object[] { 1144, "ibm01144", "ebcdic-it-280+euro" };
yield return new object[] { 1145, "ibm01145", "ibm01145" };
yield return new object[] { 1145, "ibm01145", "ccsid01145" };
yield return new object[] { 1145, "ibm01145", "cp01145" };
yield return new object[] { 1145, "ibm01145", "ebcdic-es-284+euro" };
yield return new object[] { 1146, "ibm01146", "ibm01146" };
yield return new object[] { 1146, "ibm01146", "ccsid01146" };
yield return new object[] { 1146, "ibm01146", "cp01146" };
yield return new object[] { 1146, "ibm01146", "ebcdic-gb-285+euro" };
yield return new object[] { 1147, "ibm01147", "ibm01147" };
yield return new object[] { 1147, "ibm01147", "ccsid01147" };
yield return new object[] { 1147, "ibm01147", "cp01147" };
yield return new object[] { 1147, "ibm01147", "ebcdic-fr-297+euro" };
yield return new object[] { 1148, "ibm01148", "ibm01148" };
yield return new object[] { 1148, "ibm01148", "ccsid01148" };
yield return new object[] { 1148, "ibm01148", "cp01148" };
yield return new object[] { 1148, "ibm01148", "ebcdic-international-500+euro" };
yield return new object[] { 1149, "ibm01149", "ibm01149" };
yield return new object[] { 1149, "ibm01149", "ccsid01149" };
yield return new object[] { 1149, "ibm01149", "cp01149" };
yield return new object[] { 1149, "ibm01149", "ebcdic-is-871+euro" };
yield return new object[] { 1250, "windows-1250", "windows-1250" };
yield return new object[] { 1250, "windows-1250", "x-cp1250" };
yield return new object[] { 1251, "windows-1251", "windows-1251" };
yield return new object[] { 1251, "windows-1251", "x-cp1251" };
yield return new object[] { 1252, "windows-1252", "windows-1252" };
yield return new object[] { 1252, "windows-1252", "x-ansi" };
yield return new object[] { 1253, "windows-1253", "windows-1253" };
yield return new object[] { 1254, "windows-1254", "windows-1254" };
yield return new object[] { 1255, "windows-1255", "windows-1255" };
yield return new object[] { 1256, "windows-1256", "windows-1256" };
yield return new object[] { 1256, "windows-1256", "cp1256" };
yield return new object[] { 1257, "windows-1257", "windows-1257" };
yield return new object[] { 1258, "windows-1258", "windows-1258" };
yield return new object[] { 1361, "johab", "johab" };
yield return new object[] { 10000, "macintosh", "macintosh" };
yield return new object[] { 10001, "x-mac-japanese", "x-mac-japanese" };
yield return new object[] { 10002, "x-mac-chinesetrad", "x-mac-chinesetrad" };
yield return new object[] { 10003, "x-mac-korean", "x-mac-korean" };
yield return new object[] { 10004, "x-mac-arabic", "x-mac-arabic" };
yield return new object[] { 10005, "x-mac-hebrew", "x-mac-hebrew" };
yield return new object[] { 10006, "x-mac-greek", "x-mac-greek" };
yield return new object[] { 10007, "x-mac-cyrillic", "x-mac-cyrillic" };
yield return new object[] { 10008, "x-mac-chinesesimp", "x-mac-chinesesimp" };
yield return new object[] { 10010, "x-mac-romanian", "x-mac-romanian" };
yield return new object[] { 10017, "x-mac-ukrainian", "x-mac-ukrainian" };
yield return new object[] { 10021, "x-mac-thai", "x-mac-thai" };
yield return new object[] { 10029, "x-mac-ce", "x-mac-ce" };
yield return new object[] { 10079, "x-mac-icelandic", "x-mac-icelandic" };
yield return new object[] { 10081, "x-mac-turkish", "x-mac-turkish" };
yield return new object[] { 10082, "x-mac-croatian", "x-mac-croatian" };
yield return new object[] { 20000, "x-chinese-cns", "x-chinese-cns" };
yield return new object[] { 20001, "x-cp20001", "x-cp20001" };
yield return new object[] { 20002, "x-chinese-eten", "x-chinese-eten" };
yield return new object[] { 20003, "x-cp20003", "x-cp20003" };
yield return new object[] { 20004, "x-cp20004", "x-cp20004" };
yield return new object[] { 20005, "x-cp20005", "x-cp20005" };
yield return new object[] { 20105, "x-ia5", "x-ia5" };
yield return new object[] { 20105, "x-ia5", "irv" };
yield return new object[] { 20106, "x-ia5-german", "x-ia5-german" };
yield return new object[] { 20106, "x-ia5-german", "din_66003" };
yield return new object[] { 20106, "x-ia5-german", "german" };
yield return new object[] { 20107, "x-ia5-swedish", "x-ia5-swedish" };
yield return new object[] { 20107, "x-ia5-swedish", "sen_850200_b" };
yield return new object[] { 20107, "x-ia5-swedish", "swedish" };
yield return new object[] { 20108, "x-ia5-norwegian", "x-ia5-norwegian" };
yield return new object[] { 20108, "x-ia5-norwegian", "norwegian" };
yield return new object[] { 20108, "x-ia5-norwegian", "ns_4551-1" };
yield return new object[] { 20261, "x-cp20261", "x-cp20261" };
yield return new object[] { 20269, "x-cp20269", "x-cp20269" };
yield return new object[] { 20273, "ibm273", "ibm273" };
yield return new object[] { 20273, "ibm273", "cp273" };
yield return new object[] { 20273, "ibm273", "csibm273" };
yield return new object[] { 20277, "ibm277", "ibm277" };
yield return new object[] { 20277, "ibm277", "csibm277" };
yield return new object[] { 20277, "ibm277", "ebcdic-cp-dk" };
yield return new object[] { 20277, "ibm277", "ebcdic-cp-no" };
yield return new object[] { 20278, "ibm278", "ibm278" };
yield return new object[] { 20278, "ibm278", "cp278" };
yield return new object[] { 20278, "ibm278", "csibm278" };
yield return new object[] { 20278, "ibm278", "ebcdic-cp-fi" };
yield return new object[] { 20278, "ibm278", "ebcdic-cp-se" };
yield return new object[] { 20280, "ibm280", "ibm280" };
yield return new object[] { 20280, "ibm280", "cp280" };
yield return new object[] { 20280, "ibm280", "csibm280" };
yield return new object[] { 20280, "ibm280", "ebcdic-cp-it" };
yield return new object[] { 20284, "ibm284", "ibm284" };
yield return new object[] { 20284, "ibm284", "cp284" };
yield return new object[] { 20284, "ibm284", "csibm284" };
yield return new object[] { 20284, "ibm284", "ebcdic-cp-es" };
yield return new object[] { 20285, "ibm285", "ibm285" };
yield return new object[] { 20285, "ibm285", "cp285" };
yield return new object[] { 20285, "ibm285", "csibm285" };
yield return new object[] { 20285, "ibm285", "ebcdic-cp-gb" };
yield return new object[] { 20290, "ibm290", "ibm290" };
yield return new object[] { 20290, "ibm290", "cp290" };
yield return new object[] { 20290, "ibm290", "csibm290" };
yield return new object[] { 20290, "ibm290", "ebcdic-jp-kana" };
yield return new object[] { 20297, "ibm297", "ibm297" };
yield return new object[] { 20297, "ibm297", "cp297" };
yield return new object[] { 20297, "ibm297", "csibm297" };
yield return new object[] { 20297, "ibm297", "ebcdic-cp-fr" };
yield return new object[] { 20420, "ibm420", "ibm420" };
yield return new object[] { 20420, "ibm420", "cp420" };
yield return new object[] { 20420, "ibm420", "csibm420" };
yield return new object[] { 20420, "ibm420", "ebcdic-cp-ar1" };
yield return new object[] { 20423, "ibm423", "ibm423" };
yield return new object[] { 20423, "ibm423", "cp423" };
yield return new object[] { 20423, "ibm423", "csibm423" };
yield return new object[] { 20423, "ibm423", "ebcdic-cp-gr" };
yield return new object[] { 20424, "ibm424", "ibm424" };
yield return new object[] { 20424, "ibm424", "cp424" };
yield return new object[] { 20424, "ibm424", "csibm424" };
yield return new object[] { 20424, "ibm424", "ebcdic-cp-he" };
yield return new object[] { 20833, "x-ebcdic-koreanextended", "x-ebcdic-koreanextended" };
yield return new object[] { 20838, "ibm-thai", "ibm-thai" };
yield return new object[] { 20838, "ibm-thai", "csibmthai" };
yield return new object[] { 20866, "koi8-r", "koi8-r" };
yield return new object[] { 20866, "koi8-r", "cskoi8r" };
yield return new object[] { 20866, "koi8-r", "koi" };
yield return new object[] { 20866, "koi8-r", "koi8" };
yield return new object[] { 20866, "koi8-r", "koi8r" };
yield return new object[] { 20871, "ibm871", "ibm871" };
yield return new object[] { 20871, "ibm871", "cp871" };
yield return new object[] { 20871, "ibm871", "csibm871" };
yield return new object[] { 20871, "ibm871", "ebcdic-cp-is" };
yield return new object[] { 20880, "ibm880", "ibm880" };
yield return new object[] { 20880, "ibm880", "cp880" };
yield return new object[] { 20880, "ibm880", "csibm880" };
yield return new object[] { 20880, "ibm880", "ebcdic-cyrillic" };
yield return new object[] { 20905, "ibm905", "ibm905" };
yield return new object[] { 20905, "ibm905", "cp905" };
yield return new object[] { 20905, "ibm905", "csibm905" };
yield return new object[] { 20905, "ibm905", "ebcdic-cp-tr" };
yield return new object[] { 20924, "ibm00924", "ibm00924" };
yield return new object[] { 20924, "ibm00924", "ccsid00924" };
yield return new object[] { 20924, "ibm00924", "cp00924" };
yield return new object[] { 20924, "ibm00924", "ebcdic-latin9--euro" };
yield return new object[] { 20932, "euc-jp", "euc-jp" };
yield return new object[] { 20936, "x-cp20936", "x-cp20936" };
yield return new object[] { 20949, "x-cp20949", "x-cp20949" };
yield return new object[] { 21025, "cp1025", "cp1025" };
yield return new object[] { 21866, "koi8-u", "koi8-u" };
yield return new object[] { 21866, "koi8-u", "koi8-ru" };
yield return new object[] { 28592, "iso-8859-2", "iso-8859-2" };
yield return new object[] { 28592, "iso-8859-2", "csisolatin2" };
yield return new object[] { 28592, "iso-8859-2", "iso_8859-2" };
yield return new object[] { 28592, "iso-8859-2", "iso_8859-2:1987" };
yield return new object[] { 28592, "iso-8859-2", "iso8859-2" };
yield return new object[] { 28592, "iso-8859-2", "iso-ir-101" };
yield return new object[] { 28592, "iso-8859-2", "l2" };
yield return new object[] { 28592, "iso-8859-2", "latin2" };
yield return new object[] { 28593, "iso-8859-3", "iso-8859-3" };
yield return new object[] { 28593, "iso-8859-3", "csisolatin3" };
yield return new object[] { 28593, "iso-8859-3", "iso_8859-3" };
yield return new object[] { 28593, "iso-8859-3", "iso_8859-3:1988" };
yield return new object[] { 28593, "iso-8859-3", "iso-ir-109" };
yield return new object[] { 28593, "iso-8859-3", "l3" };
yield return new object[] { 28593, "iso-8859-3", "latin3" };
yield return new object[] { 28594, "iso-8859-4", "iso-8859-4" };
yield return new object[] { 28594, "iso-8859-4", "csisolatin4" };
yield return new object[] { 28594, "iso-8859-4", "iso_8859-4" };
yield return new object[] { 28594, "iso-8859-4", "iso_8859-4:1988" };
yield return new object[] { 28594, "iso-8859-4", "iso-ir-110" };
yield return new object[] { 28594, "iso-8859-4", "l4" };
yield return new object[] { 28594, "iso-8859-4", "latin4" };
yield return new object[] { 28595, "iso-8859-5", "iso-8859-5" };
yield return new object[] { 28595, "iso-8859-5", "csisolatincyrillic" };
yield return new object[] { 28595, "iso-8859-5", "cyrillic" };
yield return new object[] { 28595, "iso-8859-5", "iso_8859-5" };
yield return new object[] { 28595, "iso-8859-5", "iso_8859-5:1988" };
yield return new object[] { 28595, "iso-8859-5", "iso-ir-144" };
yield return new object[] { 28596, "iso-8859-6", "iso-8859-6" };
yield return new object[] { 28596, "iso-8859-6", "arabic" };
yield return new object[] { 28596, "iso-8859-6", "csisolatinarabic" };
yield return new object[] { 28596, "iso-8859-6", "ecma-114" };
yield return new object[] { 28596, "iso-8859-6", "iso_8859-6" };
yield return new object[] { 28596, "iso-8859-6", "iso_8859-6:1987" };
yield return new object[] { 28596, "iso-8859-6", "iso-ir-127" };
yield return new object[] { 28597, "iso-8859-7", "iso-8859-7" };
yield return new object[] { 28597, "iso-8859-7", "csisolatingreek" };
yield return new object[] { 28597, "iso-8859-7", "ecma-118" };
yield return new object[] { 28597, "iso-8859-7", "elot_928" };
yield return new object[] { 28597, "iso-8859-7", "greek" };
yield return new object[] { 28597, "iso-8859-7", "greek8" };
yield return new object[] { 28597, "iso-8859-7", "iso_8859-7" };
yield return new object[] { 28597, "iso-8859-7", "iso_8859-7:1987" };
yield return new object[] { 28597, "iso-8859-7", "iso-ir-126" };
yield return new object[] { 28598, "iso-8859-8", "iso-8859-8" };
yield return new object[] { 28598, "iso-8859-8", "csisolatinhebrew" };
yield return new object[] { 28598, "iso-8859-8", "hebrew" };
yield return new object[] { 28598, "iso-8859-8", "iso_8859-8" };
yield return new object[] { 28598, "iso-8859-8", "iso_8859-8:1988" };
yield return new object[] { 28598, "iso-8859-8", "iso-8859-8 visual" };
yield return new object[] { 28598, "iso-8859-8", "iso-ir-138" };
yield return new object[] { 28598, "iso-8859-8", "logical" };
yield return new object[] { 28598, "iso-8859-8", "visual" };
yield return new object[] { 28599, "iso-8859-9", "iso-8859-9" };
yield return new object[] { 28599, "iso-8859-9", "csisolatin5" };
yield return new object[] { 28599, "iso-8859-9", "iso_8859-9" };
yield return new object[] { 28599, "iso-8859-9", "iso_8859-9:1989" };
yield return new object[] { 28599, "iso-8859-9", "iso-ir-148" };
yield return new object[] { 28599, "iso-8859-9", "l5" };
yield return new object[] { 28599, "iso-8859-9", "latin5" };
yield return new object[] { 28603, "iso-8859-13", "iso-8859-13" };
yield return new object[] { 28605, "iso-8859-15", "iso-8859-15" };
yield return new object[] { 28605, "iso-8859-15", "csisolatin9" };
yield return new object[] { 28605, "iso-8859-15", "iso_8859-15" };
yield return new object[] { 28605, "iso-8859-15", "l9" };
yield return new object[] { 28605, "iso-8859-15", "latin9" };
yield return new object[] { 29001, "x-europa", "x-europa" };
yield return new object[] { 38598, "iso-8859-8-i", "iso-8859-8-i" };
yield return new object[] { 50220, "iso-2022-jp", "iso-2022-jp" };
yield return new object[] { 50221, "csiso2022jp", "csiso2022jp" };
yield return new object[] { 50222, "iso-2022-jp", "iso-2022-jp" };
yield return new object[] { 50225, "iso-2022-kr", "iso-2022-kr" };
yield return new object[] { 50225, "iso-2022-kr", "csiso2022kr" };
yield return new object[] { 50225, "iso-2022-kr", "iso-2022-kr-7" };
yield return new object[] { 50225, "iso-2022-kr", "iso-2022-kr-7bit" };
yield return new object[] { 50227, "x-cp50227", "x-cp50227" };
yield return new object[] { 50227, "x-cp50227", "cp50227" };
yield return new object[] { 51932, "euc-jp", "euc-jp" };
yield return new object[] { 51932, "euc-jp", "cseucpkdfmtjapanese" };
yield return new object[] { 51932, "euc-jp", "extended_unix_code_packed_format_for_japanese" };
yield return new object[] { 51932, "euc-jp", "iso-2022-jpeuc" };
yield return new object[] { 51932, "euc-jp", "x-euc" };
yield return new object[] { 51932, "euc-jp", "x-euc-jp" };
yield return new object[] { 51936, "euc-cn", "euc-cn" };
yield return new object[] { 51936, "euc-cn", "x-euc-cn" };
yield return new object[] { 51949, "euc-kr", "euc-kr" };
yield return new object[] { 51949, "euc-kr", "cseuckr" };
yield return new object[] { 51949, "euc-kr", "iso-2022-kr-8" };
yield return new object[] { 51949, "euc-kr", "iso-2022-kr-8bit" };
yield return new object[] { 52936, "hz-gb-2312", "hz-gb-2312" };
yield return new object[] { 54936, "gb18030", "gb18030" };
yield return new object[] { 57002, "x-iscii-de", "x-iscii-de" };
yield return new object[] { 57003, "x-iscii-be", "x-iscii-be" };
yield return new object[] { 57004, "x-iscii-ta", "x-iscii-ta" };
yield return new object[] { 57005, "x-iscii-te", "x-iscii-te" };
yield return new object[] { 57006, "x-iscii-as", "x-iscii-as" };
yield return new object[] { 57007, "x-iscii-or", "x-iscii-or" };
yield return new object[] { 57008, "x-iscii-ka", "x-iscii-ka" };
yield return new object[] { 57009, "x-iscii-ma", "x-iscii-ma" };
yield return new object[] { 57010, "x-iscii-gu", "x-iscii-gu" };
yield return new object[] { 57011, "x-iscii-pa", "x-iscii-pa" };
}
public static IEnumerable<object[]> SpecificCodepageEncodings()
{
// Layout is codepage encoding, bytes, and matching unicode string.
yield return new object[] { "Windows-1256", new byte[] { 0xC7, 0xE1, 0xE1, 0xE5, 0x20, 0xC7, 0xCD, 0xCF }, "\x0627\x0644\x0644\x0647\x0020\x0627\x062D\x062F" };
yield return new object[] {"Windows-1252", new byte[] { 0xD0, 0xD1, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0xD7, 0xD8, 0xD9, 0xDA, 0xDB, 0xDC, 0xDD, 0xDE, 0xDF } ,
"\x00D0\x00D1\x00D2\x00D3\x00D4\x00D5\x00D6\x00D7\x00D8\x00D9\x00DA\x00DB\x00DC\x00DD\x00DE\x00DF"};
yield return new object[] { "GB2312", new byte[] { 0xCD, 0xE2, 0xCD, 0xE3, 0xCD, 0xE4 }, "\x5916\x8C4C\x5F2F" };
yield return new object[] {"GB18030", new byte[] { 0x81, 0x30, 0x89, 0x37, 0x81, 0x30, 0x89, 0x38, 0xA8, 0xA4, 0xA8, 0xA2, 0x81, 0x30, 0x89, 0x39, 0x81, 0x30, 0x8A, 0x30 } ,
"\x00DE\x00DF\x00E0\x00E1\x00E2\x00E3"};
}
public static IEnumerable<object[]> MultibyteCharacterEncodings()
{
// Layout is the encoding, bytes, and expected result.
yield return new object[] { "iso-2022-jp",
new byte[] { 0xA,
0x1B, 0x24, 0x42, 0x25, 0x4A, 0x25, 0x4A,
0x1B, 0x28, 0x42,
0x1B, 0x24, 0x42, 0x25, 0x4A,
0x1B, 0x28, 0x42,
0x1B, 0x24, 0x42, 0x25, 0x4A,
0x1B, 0x28, 0x42,
0x1B, 0x1, 0x2, 0x3, 0x4,
0x1B, 0x24, 0x42, 0x25, 0x4A, 0x0E, 0x25, 0x4A,
0x1B, 0x28, 0x42, 0x41, 0x42, 0x0E, 0x25, 0x0F, 0x43 },
new int[] { 0xA, 0x30CA, 0x30CA, 0x30CA, 0x30CA, 0x1B, 0x1, 0x2, 0x3, 0x4,
0x30CA, 0xFF65, 0xFF8A, 0x41, 0x42, 0xFF65, 0x43}
};
yield return new object[] { "GB18030",
new byte[] { 0x41, 0x42, 0x43, 0x81, 0x40, 0x82, 0x80, 0x81, 0x30, 0x82, 0x31, 0x81, 0x20 },
new int[] { 0x41, 0x42, 0x43, 0x4E02, 0x500B, 0x8B, 0x3F, 0x20 }
};
yield return new object[] { "shift_jis",
new byte[] { 0x41, 0x42, 0x43, 0x81, 0x42, 0xE0, 0x43, 0x44, 0x45 },
new int[] { 0x41, 0x42, 0x43, 0x3002, 0x6F86, 0x44, 0x45 }
};
yield return new object[] { "iso-2022-kr",
new byte[] { 0x0E, 0x21, 0x7E, 0x1B, 0x24, 0x29, 0x43, 0x21, 0x7E, 0x0F, 0x21, 0x7E, 0x1B, 0x24, 0x29, 0x43, 0x21, 0x7E },
new int[] { 0xFFE2, 0xFFE2, 0x21, 0x7E, 0x21, 0x7E }
};
yield return new object[] { "hz-gb-2312",
new byte[] { 0x7E, 0x42, 0x7E, 0x7E, 0x7E, 0x7B, 0x21, 0x7E, 0x7E, 0x7D, 0x42, 0x42, 0x7E, 0xA, 0x43, 0x43 },
new int[] { 0x7E, 0x42, 0x7E, 0x3013, 0x42, 0x42, 0x43, 0x43, }
};
}
private static IEnumerable<KeyValuePair<int, string>> CrossplatformDefaultEncodings()
{
yield return Map(1200, "utf-16");
yield return Map(12000, "utf-32");
yield return Map(20127, "us-ascii");
yield return Map(65000, "utf-7");
yield return Map(65001, "utf-8");
}
private static KeyValuePair<int, string> Map(int codePage, string webName)
{
return new KeyValuePair<int, string>(codePage, webName);
}
[Fact]
public static void TestDefaultEncodings()
{
ValidateDefaultEncodings();
// The default encoding should be something from the known list.
Encoding defaultEncoding = Encoding.GetEncoding(0);
Assert.NotNull(defaultEncoding);
KeyValuePair<int, string> mappedEncoding = Map(defaultEncoding.CodePage, defaultEncoding.WebName);
if (defaultEncoding.CodePage == Encoding.UTF8.CodePage)
{
// if the default encoding is not UTF8 that means either we are running on the full framework
// or the encoding provider is registered throw the call Encoding.RegisterProvider.
// at that time we shouldn't expect exceptions when creating the following encodings.
foreach (object[] mapping in CodePageInfo())
{
Assert.Throws<NotSupportedException>(() => Encoding.GetEncoding((int)mapping[0]));
Assert.Throws<ArgumentException>(() => Encoding.GetEncoding((string)mapping[2]));
}
// Currently the class EncodingInfo isn't present in corefx, so this checks none of the code pages are present.
// When it is, comment out this line and remove the previous foreach/assert.
// Assert.Equal(CrossplatformDefaultEncodings, Encoding.GetEncodings().OrderBy(i => i.CodePage).Select(i => Map(i.CodePage, i.WebName)));
Assert.Contains(mappedEncoding, CrossplatformDefaultEncodings());
}
// Add the code page provider.
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
// Make sure added code pages are identical between the provider and the Encoding class.
foreach (object[] mapping in CodePageInfo())
{
Encoding encoding = Encoding.GetEncoding((int)mapping[0]);
Encoding codePageEncoding = CodePagesEncodingProvider.Instance.GetEncoding((int)mapping[0]);
Assert.Equal(encoding, codePageEncoding);
Assert.Equal(encoding.CodePage, (int)mapping[0]);
Assert.Equal(encoding.WebName, (string)mapping[1]);
// Get encoding via query string.
Assert.Equal(Encoding.GetEncoding((string)mapping[2]), CodePagesEncodingProvider.Instance.GetEncoding((string)mapping[2]));
}
// Adding the code page provider should keep the originals, too.
ValidateDefaultEncodings();
// Currently the class EncodingInfo isn't present in corefx, so this checks the complete list
// When it is, comment out this line and remove the previous foreach/assert.
// Assert.Equal(CrossplatformDefaultEncodings().Union(CodePageInfo().Select(i => Map((int)i[0], (string)i[1])).OrderBy(i => i.Key)),
// Encoding.GetEncodings().OrderBy(i => i.CodePage).Select(i => Map(i.CodePage, i.WebName)));
// Default encoding may have changed, should still be something on the combined list.
defaultEncoding = Encoding.GetEncoding(0);
Assert.NotNull(defaultEncoding);
mappedEncoding = Map(defaultEncoding.CodePage, defaultEncoding.WebName);
Assert.Contains(mappedEncoding, CrossplatformDefaultEncodings().Union(CodePageInfo().Select(i => Map((int)i[0], (string)i[1]))));
TestRegister1252();
}
private static void ValidateDefaultEncodings()
{
foreach (var mapping in CrossplatformDefaultEncodings())
{
Encoding encoding = Encoding.GetEncoding(mapping.Key);
Assert.NotNull(encoding);
Assert.Equal(encoding, Encoding.GetEncoding(mapping.Value));
Assert.Equal(mapping.Value, encoding.WebName);
}
}
[Theory]
[MemberData(nameof(SpecificCodepageEncodings))]
public static void TestRoundtrippingSpecificCodepageEncoding(string encodingName, byte[] bytes, string expected)
{
Encoding encoding = CodePagesEncodingProvider.Instance.GetEncoding(encodingName);
string encoded = encoding.GetString(bytes, 0, bytes.Length);
Assert.Equal(expected, encoded);
Assert.Equal(bytes, encoding.GetBytes(encoded));
byte[] resultBytes = encoding.GetBytes(encoded);
}
[Theory]
[MemberData(nameof(CodePageInfo))]
public static void TestCodepageEncoding(int codePage, string webName, string queryString)
{
Encoding encoding;
// There are two names that have duplicate associated CodePages. For those two names,
// we have to test with the expectation that querying the name will always return the
// same codepage.
if (codePage != 20932 && codePage != 50222)
{
encoding = CodePagesEncodingProvider.Instance.GetEncoding(queryString);
Assert.Equal(encoding, CodePagesEncodingProvider.Instance.GetEncoding(codePage));
Assert.Equal(encoding, CodePagesEncodingProvider.Instance.GetEncoding(webName));
}
else
{
encoding = CodePagesEncodingProvider.Instance.GetEncoding(codePage);
Assert.NotEqual(encoding, CodePagesEncodingProvider.Instance.GetEncoding(queryString));
Assert.NotEqual(encoding, CodePagesEncodingProvider.Instance.GetEncoding(webName));
}
Assert.NotNull(encoding);
Assert.Equal(codePage, encoding.CodePage);
Assert.Equal(webName, encoding.WebName);
// Small round-trip for ASCII alphanumeric range (some code pages use different punctuation!)
// Start with space.
string asciiPrintable = " 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
char[] traveled = encoding.GetChars(encoding.GetBytes(asciiPrintable));
Assert.Equal(asciiPrintable.ToCharArray(), traveled);
}
[Theory]
[MemberData(nameof(MultibyteCharacterEncodings))]
public static void TestSpecificMultibyteCharacterEncodings(string codepageName, byte[] bytes, int[] expected)
{
Decoder decoder = CodePagesEncodingProvider.Instance.GetEncoding(codepageName).GetDecoder();
char[] buffer = new char[expected.Length];
for (int byteIndex = 0, charIndex = 0, charCount = 0; byteIndex < bytes.Length; byteIndex++, charIndex += charCount)
{
charCount = decoder.GetChars(bytes, byteIndex, 1, buffer, charIndex);
}
Assert.Equal(expected, buffer.Select(c => (int)c));
}
[Theory]
[MemberData(nameof(CodePageInfo))]
public static void TestEncodingDisplayNames(int codePage, string webName, string queryString)
{
var encoding = CodePagesEncodingProvider.Instance.GetEncoding(codePage);
string name = encoding.EncodingName;
// Names can't be empty, and must be printable characters.
Assert.False(string.IsNullOrWhiteSpace(name));
Assert.All(name, c => Assert.True(c >= ' ' && c < '~' + 1, "Name: " + name + " contains character: " + c));
}
// This test is run as part of the default mappings test, since it modifies global state which that test
// depends on.
public static void TestRegister1252()
{
// This test case ensure we can map all 1252 codepage codepoints without any exception.
string s1252Result =
"\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\u0008\u0009\u000a\u000b\u000c\u000d\u000e\u000f" +
"\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f" +
"\u0020\u0021\u0022\u0023\u0024\u0025\u0026\u0027\u0028\u0029\u002a\u002b\u002c\u002d\u002e\u002f" +
"\u0030\u0031\u0032\u0033\u0034\u0035\u0036\u0037\u0038\u0039\u003a\u003b\u003c\u003d\u003e\u003f" +
"\u0040\u0041\u0042\u0043\u0044\u0045\u0046\u0047\u0048\u0049\u004a\u004b\u004c\u004d\u004e\u004f" +
"\u0050\u0051\u0052\u0053\u0054\u0055\u0056\u0057\u0058\u0059\u005a\u005b\u005c\u005d\u005e\u005f" +
"\u0060\u0061\u0062\u0063\u0064\u0065\u0066\u0067\u0068\u0069\u006a\u006b\u006c\u006d\u006e\u006f" +
"\u0070\u0071\u0072\u0073\u0074\u0075\u0076\u0077\u0078\u0079\u007a\u007b\u007c\u007d\u007e\u007f" +
"\u20ac\u0081\u201a\u0192\u201e\u2026\u2020\u2021\u02c6\u2030\u0160\u2039\u0152\u008d\u017d\u008f" +
"\u0090\u2018\u2019\u201c\u201d\u2022\u2013\u2014\u02dc\u2122\u0161\u203a\u0153\u009d\u017e\u0178" +
"\u00a0\u00a1\u00a2\u00a3\u00a4\u00a5\u00a6\u00a7\u00a8\u00a9\u00aa\u00ab\u00ac\u00ad\u00ae\u00af" +
"\u00b0\u00b1\u00b2\u00b3\u00b4\u00b5\u00b6\u00b7\u00b8\u00b9\u00ba\u00bb\u00bc\u00bd\u00be\u00bf" +
"\u00c0\u00c1\u00c2\u00c3\u00c4\u00c5\u00c6\u00c7\u00c8\u00c9\u00ca\u00cb\u00cc\u00cd\u00ce\u00cf" +
"\u00d0\u00d1\u00d2\u00d3\u00d4\u00d5\u00d6\u00d7\u00d8\u00d9\u00da\u00db\u00dc\u00dd\u00de\u00df" +
"\u00e0\u00e1\u00e2\u00e3\u00e4\u00e5\u00e6\u00e7\u00e8\u00e9\u00ea\u00eb\u00ec\u00ed\u00ee\u00ef" +
"\u00f0\u00f1\u00f2\u00f3\u00f4\u00f5\u00f6\u00f7\u00f8\u00f9\u00fa\u00fb\u00fc\u00fd\u00fe\u00ff";
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
Encoding win1252 = Encoding.GetEncoding("windows-1252", EncoderFallback.ExceptionFallback, DecoderFallback.ExceptionFallback);
byte[] enc = new byte[256];
for (int j = 0; j < 256; j++)
{
enc[j] = (byte)j;
}
Assert.Equal(s1252Result, win1252.GetString(enc));
}
}
public class CultureSetup : IDisposable
{
private readonly CultureInfo _originalUICulture;
public CultureSetup()
{
_originalUICulture = CultureInfo.CurrentUICulture;
CultureInfo.CurrentUICulture = new CultureInfo("en-US");
}
public void Dispose()
{
CultureInfo.CurrentUICulture = _originalUICulture;
}
}
}
| |
using System;
using System.Xml.Serialization;
using System.Xml;
namespace GPX
{
/// <summary>
///This represents a waypoint, point of interest, or named feature on a map.
/// </summary>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.42")]
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://www.topografix.com/GPX/1/1")]
public class WayPoint
{
#region Variables
private decimal eleField;
private bool eleFieldSpecified;
private const int _EleDecimals = 2;
private System.DateTime timeField;
private bool timeFieldSpecified;
private decimal magvarField;
private bool magvarFieldSpecified;
private decimal geoidheightField;
private bool geoidheightFieldSpecified;
private string nameField;
private string cmtField;
private string descField;
private string srcField;
private Link[] linkField;
private string symField;
private string typeField;
private Fix fixField;
private bool fixFieldSpecified;
private string satField;
private decimal hdopField;
private bool hdopFieldSpecified;
private decimal vdopField;
private bool vdopFieldSpecified;
private decimal pdopField;
private bool pdopFieldSpecified;
private decimal ageofdgpsdataField;
private bool ageofdgpsdataFieldSpecified;
private string dgpsidField;
private Extensions extensionsField;
private decimal latField;
private decimal lonField;
private int _LatLonDecimals = 6;
#endregion Variables
public WayPoint() { }
/// <summary>
/// Elevation (in meters) of the point.
/// </summary>
[System.Xml.Serialization.XmlElementAttribute("ele")]
public decimal Elevation
{
get
{
return this.eleField;
}
set
{
this.eleField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool eleSpecified
{
get
{
return this.eleFieldSpecified;
}
set
{
this.eleFieldSpecified = value;
}
}
/// <summary>
/// Creation/modification timestamp for element.
/// </summary>
/// <remarks>Date and time in are in Univeral Coordinated Time (UTC), not local time! Conforms to ISO 8601 specification for date/time representation. Fractional seconds are allowed for millisecond timing in tracklogs.</remarks>
[System.Xml.Serialization.XmlElementAttribute("time")]
public System.DateTime Time
{
get
{
return this.timeField;
}
set
{
this.timeField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool timeSpecified
{
get
{
return this.timeFieldSpecified;
}
set
{
this.timeFieldSpecified = value;
}
}
/// <summary>
/// Magnetic variation (in degrees) at the point.
/// </summary>
/// <remarks>For writing the XML file, magvar property is used.</remarks>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public decimal MagneticVariation
{
get
{
return this.magvarField;
}
set
{
this.magvarField = value;
}
}
/// <summary>
/// Is MagneticVariation property.
/// </summary>
public decimal magvar
{
get
{
return this.magvarField;
}
set
{
this.magvarField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool magvarSpecified
{
get
{
return this.magvarFieldSpecified;
}
set
{
this.magvarFieldSpecified = value;
}
}
/// <summary>
/// Height (in meters) of geoid (mean sea level) above WGS84 earth ellipsoid. As defined in NMEA GGA message.
/// </summary>
[System.Xml.Serialization.XmlElementAttribute("geoidheight")]
public decimal geoidheight
{
get
{
return this.geoidheightField;
}
set
{
this.geoidheightField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool geoidheightSpecified
{
get
{
return this.geoidheightFieldSpecified;
}
set
{
this.geoidheightFieldSpecified = value;
}
}
/// <summary>
/// The GPS name of the waypoint.
/// </summary>
/// <remarks>This field will be transferred to and from the GPS. GPX does not place restrictions on the length of this field or the characters contained in it. It is up to the receiving application to validate the field before sending it to the GPS.</remarks>
[System.Xml.Serialization.XmlElementAttribute("name")]
public string Name
{
get
{
return this.nameField;
}
set
{
this.nameField = value;
}
}
/// <summary>
/// GPS waypoint comment. Sent to GPS as comment.
/// </summary>
[System.Xml.Serialization.XmlElementAttribute("cmt")]
public string Comment
{
get
{
return this.cmtField;
}
set
{
this.cmtField = value;
}
}
/// <summary>
/// A text description of the element. Holds additional information about the element intended for the user, not the GPS.
/// </summary>
[System.Xml.Serialization.XmlElementAttribute("desc")]
public string Description
{
get
{
return this.descField;
}
set
{
this.descField = value;
}
}
/// <summary>
/// Source of data. Included to give user some idea of reliability and accuracy of data.
/// </summary>
/// <example>"Garmin eTrex", "USGS quad Boston North"</example>
[System.Xml.Serialization.XmlElementAttribute("src")]
public string SourceOfData
{
get
{
return this.srcField;
}
set
{
this.srcField = value;
}
}
/// <summary>
/// Link to additional information about the waypoint.
/// </summary>
[System.Xml.Serialization.XmlElementAttribute("link")]
public Link[] Link
{
get
{
return this.linkField;
}
set
{
this.linkField = value;
}
}
/// <summary>
/// Text of GPS symbol name. For interchange with other programs, use the exact spelling of the symbol as displayed on the GPS. If the GPS abbreviates words, spell them out.
/// </summary>
[System.Xml.Serialization.XmlElementAttribute("sym")]
public string Symbol
{
get
{
return this.symField;
}
set
{
this.symField = value;
}
}
/// <summary>
/// Type (classification) of the waypoint.
/// </summary>
[System.Xml.Serialization.XmlElementAttribute("type")]
public string Classification
{
get
{
return this.typeField;
}
set
{
this.typeField = value;
}
}
/// <summary>
/// Type of GPX fix.
/// </summary>
public Fix fix
{
get
{
return this.fixField;
}
set
{
this.fixField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool fixSpecified
{
get
{
return this.fixFieldSpecified;
}
set
{
this.fixFieldSpecified = value;
}
}
/// <summary>
/// Number of satellites used to calculate the GPX fix.
/// </summary>
[System.Xml.Serialization.XmlElementAttribute(ElementName = "sat", DataType = "nonNegativeInteger")]
public string NumberOfSatellites
{
get
{
return this.satField;
}
set
{
this.satField = value;
}
}
/// <summary>
/// Horizontal dilution of precision.
/// </summary>
[System.Xml.Serialization.XmlElementAttribute("hdop")]
public decimal hdop
{
get
{
return this.hdopField;
}
set
{
this.hdopField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool hdopSpecified
{
get
{
return this.hdopFieldSpecified;
}
set
{
this.hdopFieldSpecified = value;
}
}
/// <summary>
/// Vertical dilution of precision.
/// </summary>
[System.Xml.Serialization.XmlElementAttribute("vdop")]
public decimal vdop
{
get
{
return this.vdopField;
}
set
{
this.vdopField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool vdopSpecified
{
get
{
return this.vdopFieldSpecified;
}
set
{
this.vdopFieldSpecified = value;
}
}
/// <summary>
/// Position dilution of precision.
/// </summary>
[System.Xml.Serialization.XmlElementAttribute("pdop")]
public decimal pdop
{
get
{
return this.pdopField;
}
set
{
this.pdopField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool pdopSpecified
{
get
{
return this.pdopFieldSpecified;
}
set
{
this.pdopFieldSpecified = value;
}
}
/// <summary>
/// Number of seconds since last DGPS update.
/// </summary>
[System.Xml.Serialization.XmlElementAttribute("ageofdgpsdata")]
public decimal ageofdgpsdata
{
get
{
return this.ageofdgpsdataField;
}
set
{
this.ageofdgpsdataField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool ageofdgpsdataSpecified
{
get
{
return this.ageofdgpsdataFieldSpecified;
}
set
{
this.ageofdgpsdataFieldSpecified = value;
}
}
/// <summary>
/// ID of DGPS station used in differential correction.
/// </summary>
[System.Xml.Serialization.XmlElementAttribute(ElementName = "dgpsid", DataType = "integer")]
public string dgpsid
{
get
{
return this.dgpsidField;
}
set
{
this.dgpsidField = value;
}
}
/// <summary>
/// You can add extend GPX by adding your own elements from another schema here.
/// </summary>
//[System.Xml.Serialization.XmlAttributeAttribute("extensions")]
public Extensions extensions
{
get
{
return this.extensionsField;
}
set
{
this.extensionsField = value;
}
}
/// <summary>
/// The latitude of the point. Decimal degrees, WGS84 datum.
/// </summary>
[System.Xml.Serialization.XmlAttributeAttribute("lat")]
public decimal Latitude
{
get
{
return this.latField;
}
set
{
this.latField = value;
TransformCoordinates();
}
}
/// <summary>
/// The longitude of the point. Decimal degrees, WGS84 datum.
/// </summary>
[System.Xml.Serialization.XmlAttributeAttribute("lon")]
public decimal Longitude
{
get
{
return this.lonField;
}
set
{
this.lonField = value;
TransformCoordinates();
}
}
private double _Temperature;
[XmlIgnoreAttribute()]
public double Temperature
{
get { return _Temperature; }
set { _Temperature = value; }
}
private double _WaterTemperature;
[XmlIgnoreAttribute()]
public double WaterTemperature
{
get { return _WaterTemperature; }
set { _WaterTemperature = value; }
}
private double _Depth;
[XmlIgnoreAttribute()]
public double Depth
{
get { return _Depth; }
set { _Depth = value; }
}
private int _Heartrate;
[XmlIgnoreAttribute()]
public int Heartreate
{
get { return _Heartrate; }
set { _Heartrate = value; }
}
private int _Cadence;
[XmlIgnoreAttribute()]
public int Cadence
{
get { return _Cadence; }
set { _Cadence = value; }
}
#region Extensions
public void SetLongitudeLatitude(decimal longitude, decimal latitude)
{
this.lonField = longitude;
this.latField = latitude;
TransformCoordinates();
}
private double _LatitudeKm;
private double _LongitudeKm;
private void TransformCoordinates()
{
_LatitudeKm = GPXUtils.KmPerDegree * Convert.ToDouble(this.latField);
_LongitudeKm = GPXUtils.KmPerDegreeAtLatitude(this.latField) * Convert.ToDouble(this.lonField);
}
/// <summary>
/// Latitude converted to km.
/// </summary>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public double LatitudeKm
{
get { return _LatitudeKm; }
}
//public double GetLatitudeKm()
//{
// return GPXUtils.KmPerDegree * Convert.ToDouble(this.latField);
//}
/// <summary>
/// Longitude converted to km.
/// </summary>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public double LongitudeKm
{
get { return _LongitudeKm; }
}
//public double GetLongitudeKm()
//{
// return GPXUtils.KmPerDegreeAtLatitude(this.latField) * Convert.ToDouble(this.lonField);
//}
private WayPoint _PreviousWaypoint;
[System.Xml.Serialization.XmlIgnoreAttribute()]
public WayPoint PreviousWaypoint
{
get { return _PreviousWaypoint; }
internal set { _PreviousWaypoint = value; }
}
private WayPoint _NextWaypoint;
[System.Xml.Serialization.XmlIgnoreAttribute()]
public WayPoint NextWaypoint
{
get { return _NextWaypoint; }
internal set { _NextWaypoint = value; }
}
private GPXVector _SpeedVector;
/// <summary>
/// Speed differentiated per direction
/// </summary>
public GPXVector GetSpeedVector()
{
return _SpeedVector * _SpeedUnitFactor;
}
private static double _SpeedUnitFactor = 1.0;
public static double GetSpeedUnitFactor()
{
return _SpeedUnitFactor;
}
public static void SetSpeedUnitFactor(double value)
{
_SpeedUnitFactor = value;
}
private double _Speed;
/// <summary>
/// Speed in meter per second * unit factor
/// </summary>
public double GetSpeed()
{
return _Speed * _SpeedUnitFactor;
}
private GPXVector _DistanceVector;
/// <summary>
/// Distance from Previos WayPoint differntiated per direction
/// </summary>
public GPXVector GetDistanceVector()
{
return _DistanceVector;
}
private double _Distance;
/// <summary>
/// Absolute Distance from Previous WayPoint in meter.
/// </summary>
public double GetDistance()
{
return _Distance;
}
private GPXVector _DirectionVector;
/// <summary>
/// Indicates the direction from Previous WayPoint.
/// </summary>
/// <remarks>Caculated by dividing the <see cref="GetDistanceVector()">DistanceVector</see> by the <see cref="GetDistance()">Distance</see>.</remarks>
public GPXVector GetDirectionVector()
{
return _DirectionVector;
}
/// <summary>
/// Returns the change in direction at this WayPoint.
/// </summary>
/// <remarks>Calculated by Subtracting the <see cref="GetDirectionVector()">DirectionVector</see> of this WayPoint from the DirectionVector of the next WayPoint.</remarks>
public GPXVector GetDirectionChange()
{
if ((_PreviousWaypoint == null) || (_NextWaypoint == null))
return new GPXVector();
else
return _NextWaypoint.GetDirectionVector() - this.GetDirectionVector();
}
public double GetAscent()
{
if (_PreviousWaypoint == null)
return 0.0;
else
return Convert.ToDouble(this.Elevation - _PreviousWaypoint.Elevation) / GetDistance();
}
/// <summary>
/// Returns the Distance of two WayPoints (differentiated by direction).
/// </summary>
public static GPXVector operator -(WayPoint wp1, WayPoint wp2)
{
double deltaLat = Convert.ToDouble(wp1.latField - wp2.latField);
double deltaLong = Convert.ToDouble(wp1.lonField - wp2.lonField);
double deltaEle = 0;
//if ((wp1.eleFieldSpecified)&&(wp2.eleFieldSpecified))
deltaEle = Convert.ToDouble(wp1.eleField - wp2.eleField);
return new GPXVector(deltaLat, deltaLong, deltaEle);
}
private GPXVector _DistanceFromStart;
/// <summary>
/// Returns the distance from the segment start differentiated by direction.
/// </summary>
public GPXVector GetDistanceFromStart()
{
return _DistanceFromStart;
}
public double GetDistanceFrom(WayPoint pt)
{
return (this - pt).GetLength(Latitude);
}
private TimeSpan _TimeSinceStart;
/// <summary>
/// Returns the time since segment start.
/// </summary>
public TimeSpan GetTimeSinceStart()
{
return _TimeSinceStart;
}
/// <summary>
/// Returns the time since segment start in seconds.
/// </summary>
public double GetTimeSinceStartSeconds()
{
return _TimeSinceStart.Ticks / GPXUtils.TicksPerSecond;
}
private double _TrackDistanceFromStart;
/// <summary>
/// Returns the distance from start along the track.
/// </summary>
public double GetTrackDistanceFromStart()
{
return _TrackDistanceFromStart;
}
private int _Index;
/// <summary>
/// Index of the point in this track segment.
/// </summary>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public int Index
{
get { return _Index; }
internal set { _Index = value; }
}
internal void RelateToStartPoint(ref WayPoint start) //, out GPXVector distanceVector, out double time)
{
_DistanceFromStart = this - start;
_TimeSinceStart = this.Time.Subtract(start.Time);
}
internal void Recalculate()
{
TransformCoordinates();
_SpeedVector = new GPXVector();
_Speed = 0;
_DirectionVector = new GPXVector();
if (_PreviousWaypoint == null)
{
_DistanceVector = new GPXVector();
_Distance = 0;
_TrackDistanceFromStart = 0;
}
else
{
_DistanceVector = this - _PreviousWaypoint;
_Distance = _DistanceVector.GetLength(this.latField);
_TrackDistanceFromStart = _PreviousWaypoint.GetTrackDistanceFromStart() + _Distance;
if (_Distance > 0.01)
_DirectionVector = _DistanceVector / _Distance;
else
_DirectionVector = new GPXVector();
//if ((this.timeFieldSpecified) && (_PreviousWaypoint.timeFieldSpecified))
//{
TimeSpan ts = this.Time.Subtract(_PreviousWaypoint.Time);
double timeDiff = ts.Ticks / 10000000;
if (timeDiff != 0)
{
_SpeedVector = _DistanceVector / timeDiff;
_Speed = _SpeedVector.GetLength(this.latField);
}
//}
}
}
public void AdjustPoint(double deltaLongitude, double deltaLatitude, double deltaElevation)
{
eleField = Convert.ToDecimal(Math.Round(Convert.ToDouble(eleField) + deltaElevation, _EleDecimals));
latField = Convert.ToDecimal(Math.Round(Convert.ToDouble(latField) + deltaLatitude, _LatLonDecimals));
lonField = Convert.ToDecimal(Math.Round(Convert.ToDouble(lonField) + deltaLongitude, _LatLonDecimals));
TransformCoordinates();
}
public void AdjustPoint(GPXVector vector)
{
AdjustPoint(vector.DeltaLongitude, vector.DeltaLatitude, vector.DeltaElevation);
}
public WayPoint (Gpx.GpxPoint pt)
{
ageofdgpsdata = (pt.AgeOfData != null) ? (decimal)pt.AgeOfData : 0;
ageofdgpsdataSpecified = pt.AgeOfData != null;
Comment = pt.Comment;
Description = pt.Description;
dgpsid = pt.DgpsId.ToString();
Elevation = (pt.Elevation != null) ? (decimal)pt.Elevation : 0;
fix = (pt.FixType != null) ? (Fix)Enum.Parse(typeof(Fix), pt.FixType) : Fix.none;
geoidheight = (pt.GeoidHeight != null) ? (decimal)pt.GeoidHeight : 0;
hdop = (pt.Hdop != null) ? (decimal)pt.Hdop : 0;
Latitude = (decimal)pt.Latitude;
Longitude = (decimal)pt.Longitude;
MagneticVariation = (pt.MagneticVar != null) ? (decimal)pt.MagneticVar: 0;
Name = pt.Name;
pdop = (pt.Pdop != null) ? (decimal)pt.Pdop : 0;
NumberOfSatellites = pt.Satelites.ToString();
SourceOfData = pt.Source;
Symbol = pt.Symbol;
Time = (pt.Time != null) ? (DateTime)pt.Time : DateTime.Now;
Classification = pt.Type;
}
public WayPoint Copy()
{
WayPoint retVal = new WayPoint();
retVal.ageofdgpsdata = this.ageofdgpsdata;
retVal.ageofdgpsdataSpecified = this.ageofdgpsdataSpecified;
retVal.Comment = this.Comment;
retVal.Description = this.descField;
retVal.dgpsid = this.dgpsid;
retVal.Elevation = this.eleField;
retVal.fix = (Fix)this.fix;
retVal.geoidheight = this.geoidheight;
retVal.hdop = this.hdop;
//retVal.Latitude = this.lat;
//retVal.Longitude = this.lon;
retVal.SetLongitudeLatitude(this.lonField, this.latField);
retVal.MagneticVariation = this.magvar;
retVal.Name = this.nameField;
retVal.pdop = this.pdop;
retVal.NumberOfSatellites = this.satField;
retVal.SourceOfData = this.srcField;
retVal.Symbol = this.symField;
retVal.Time = this.timeField;
retVal.Classification = this.typeField;
return retVal;
}
#endregion Extensions
internal void CleanupExtension()
{
if (this.extensions != null)
{
XmlElement[] any = this.extensions.Any;
foreach (XmlElement element in any)
{
try
{
XmlNode inner = element.FirstChild;
string name = inner.LocalName;
string val = inner.InnerText;
switch (name)
{
case "hr":
this.Heartreate = Convert.ToInt32(val);
break;
case "cad":
this.Cadence = Convert.ToInt32(val);
break;
case "atemp":
this.Temperature = Convert.ToDouble(val);
break;
case "wtemp":
this.WaterTemperature = Convert.ToDouble(val);
break;
case "depth":
this.Depth = Convert.ToDouble(val);
break;
}
}
catch (Exception)
{
//hmpf.
}
}
}
}
}
}
| |
// Copyright (c) 2008-2018, Hazelcast, Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Hazelcast.Client.Protocol;
using Hazelcast.Client.Protocol.Codec;
using Hazelcast.Core;
using Hazelcast.IO.Serialization;
using Hazelcast.Partition.Strategy;
using Hazelcast.Util;
#pragma warning disable CS1591
namespace Hazelcast.Client.Spi
{
internal abstract class ClientProxy : IDistributedObject
{
private readonly string _objectName;
private readonly string _serviceName;
private volatile ClientContext _context;
protected ClientProxy(string serviceName, string objectName)
{
_serviceName = serviceName;
_objectName = objectName;
}
public string GetPartitionKey()
{
return StringPartitioningStrategy.GetPartitionKey(GetName());
}
public string GetName()
{
return _objectName;
}
public string GetServiceName()
{
return _serviceName;
}
protected virtual Task<T> InvokeAsync<T>(IClientMessage request, object key, Func<IClientMessage, T> decodeResponse)
{
var future = GetContext().GetInvocationService().InvokeOnKeyOwner(request, key);
var continueTask = future.ToTask().ContinueWith(t =>
{
if (t.IsFaulted)
{
// ReSharper disable once PossibleNullReferenceException
throw t.Exception.Flatten().InnerExceptions.First();
}
var clientMessage = ThreadUtil.GetResult(t);
return decodeResponse(clientMessage);
});
return continueTask;
}
protected virtual IData ToData(object Object)
{
return GetContext().GetSerializationService().ToData(Object);
}
protected virtual T ToObject<T>(object Object)
{
return GetContext().GetSerializationService().ToObject<T>(Object);
}
protected ClientContext GetContext()
{
var ctx = _context;
if (ctx == null)
{
throw new HazelcastInstanceNotActiveException();
}
return ctx;
}
internal void SetContext(ClientContext context)
{
_context = context;
}
protected virtual ISet<KeyValuePair<TKey, TValue>> ToEntrySet<TKey, TValue>(
ICollection<KeyValuePair<IData, IData>> entryCollection)
{
ISet<KeyValuePair<TKey, TValue>> entrySet = new HashSet<KeyValuePair<TKey, TValue>>();
foreach (var entry in entryCollection)
{
var key = ToObject<TKey>(entry.Key);
var val = ToObject<TValue>(entry.Value);
entrySet.Add(new KeyValuePair<TKey, TValue>(key, val));
}
return entrySet;
}
protected virtual IList<T> ToList<T>(ICollection<IData> dataList)
{
var list = new List<T>(dataList.Count);
foreach (var data in dataList)
{
list.Add(ToObject<T>(data));
}
return list;
}
protected internal virtual ISet<T> ToSet<T>(ICollection<IData> dataList)
{
var set = new HashSet<T>();
foreach (var data in dataList)
{
set.Add(ToObject<T>(data));
}
return set;
}
protected IList<IData> ToDataList<T>(ICollection<T> c)
{
ValidationUtil.ThrowExceptionIfNull(c, "Collection cannot be null.");
var values = new List<IData>(c.Count);
foreach (var o in c)
{
ValidationUtil.ThrowExceptionIfNull(o, "Collection cannot contain null items.");
values.Add(ToData(o));
}
return values;
}
protected IDictionary<TKey, object> DeserializeEntries<TKey>(IList<KeyValuePair<IData, IData>> entries)
{
if (entries.Count == 0)
{
return new Dictionary<TKey, object>();
}
var result = new Dictionary<TKey, object>();
foreach (var entry in entries)
{
var key = (TKey) ToObject<object>(entry.Key);
result.Add(key, ToObject<object>(entry.Value));
}
return result;
}
protected ISet<IData> ToDataSet<T>(ICollection<T> c)
{
ValidationUtil.ThrowExceptionIfNull(c);
var valueSet = new HashSet<IData>();
foreach (var o in c)
{
ValidationUtil.ThrowExceptionIfNull(o);
valueSet.Add(ToData(o));
}
return valueSet;
}
protected virtual IClientMessage Invoke(IClientMessage request, object key)
{
try
{
var task = GetContext().GetInvocationService().InvokeOnKeyOwner(request, key);
return ThreadUtil.GetResult(task);
}
catch (Exception e)
{
throw ExceptionUtil.Rethrow(e);
}
}
protected T Invoke<T>(IClientMessage request, object key, Func<IClientMessage, T> decodeResponse)
{
var response = Invoke(request, key);
return decodeResponse(response);
}
protected T InvokeOnPartition<T>(IClientMessage request, int partitionId, Func<IClientMessage, T> decodeResponse)
{
var response = InvokeOnPartition(request, partitionId);
return decodeResponse(response);
}
protected IClientMessage InvokeOnPartition(IClientMessage request, int partitionId)
{
try
{
var task = GetContext().GetInvocationService().InvokeOnPartition(request, partitionId);
return ThreadUtil.GetResult(task);
}
catch (Exception e)
{
throw ExceptionUtil.Rethrow(e);
}
}
protected virtual IClientMessage Invoke(IClientMessage request)
{
try
{
var task = GetContext().GetInvocationService().InvokeOnRandomTarget(request);
return ThreadUtil.GetResult(task);
}
catch (Exception e)
{
throw ExceptionUtil.Rethrow(e);
}
}
protected virtual T Invoke<T>(IClientMessage request, Func<IClientMessage, T> decodeResponse)
{
var response = Invoke(request);
return decodeResponse(response);
}
protected virtual string RegisterListener(IClientMessage registrationMessage, DecodeRegisterResponse responseDecoder,
EncodeDeregisterRequest encodeDeregisterRequest, DistributedEventHandler eventHandler)
{
return _context.GetListenerService()
.RegisterListener(registrationMessage, responseDecoder, encodeDeregisterRequest, eventHandler);
}
protected virtual bool DeregisterListener(string userRegistrationId)
{
return _context.GetListenerService().DeregisterListener(userRegistrationId);
}
protected virtual bool IsSmart()
{
return _context.GetClientConfig().GetNetworkConfig().IsSmartRouting();
}
public void Destroy()
{
OnDestroy();
_context.RemoveProxy(this);
var request = ClientDestroyProxyCodec.EncodeRequest(_objectName, GetServiceName());
Invoke(request);
PostDestroy();
_context = null;
}
internal void Init()
{
OnInitialize();
}
protected virtual void OnInitialize()
{
}
protected virtual void OnDestroy()
{
}
protected internal virtual void OnShutdown()
{
}
protected virtual void PostDestroy()
{
}
}
}
| |
/*
* Copyright (c) Contributors, http://aurora-sim.org/, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Aurora-Sim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Net;
using System.Reflection;
using System.Text;
using System.Web;
using Griffin.Networking;
using Griffin.Networking.Http.Protocol;
namespace Aurora.Framework.Servers.HttpServer
{
public class OSHttpRequest : IDisposable
{
private readonly Hashtable _query;
private readonly NameValueCollection _queryString;
private IPEndPoint _remoteIPEndPoint;
private Dictionary<string, HttpFile> _files = new Dictionary<string, HttpFile>();
private NameValueCollection _form = new NameValueCollection();
protected IRequest _httpRequest;
protected IPipelineHandlerContext _httpContext;
public OSHttpRequest()
{
}
public OSHttpRequest(IPipelineHandlerContext context, IRequest req)
{
_httpContext = context;
_httpRequest = req;
_queryString = new NameValueCollection();
_query = new Hashtable();
try
{
foreach (var item in req.QueryString)
{
try
{
_queryString.Add(item.Name, item.Value);
_query[item.Name] = item.Value;
}
catch (InvalidCastException)
{
MainConsole.Instance.DebugFormat("[OSHttpRequest]: error parsing {0} query item, skipping it", item.Name);
continue;
}
}
}
catch (Exception)
{
MainConsole.Instance.ErrorFormat("[OSHttpRequest]: Error parsing querystring");
}
foreach (var header in _httpRequest.Files)
_files[header.Name] = new HttpFile
{
ContentType = header.ContentType,
Name = header.Name,
OriginalFileName = header.OriginalFileName,
TempFileName = header.TempFileName
};
foreach (var header in _httpRequest.Form)
_form.Add(header.Name, header.Value);
// Form = new Hashtable();
// foreach (HttpInputItem item in req.Form)
// {
// MainConsole.Instance.DebugFormat("[OSHttpRequest]: Got form item {0}={1}", item.Name, item.Value);
// Form.Add(item.Name, item.Value);
// }
}
public string[] AcceptTypes
{
get { return new string[0]; }
}
public Encoding ContentEncoding
{
get { return _httpRequest.ContentEncoding; }
}
public long ContentLength
{
get { return _httpRequest.ContentLength; }
}
public string ContentType
{
get { return _httpRequest.ContentType; }
}
public HttpCookieCollection Cookies
{
get
{
var cookies = _httpRequest.Cookies;
HttpCookieCollection httpCookies = new HttpCookieCollection();
foreach (var cookie in cookies)
httpCookies.Add(new HttpCookie(cookie.Name, cookie.Value));
return httpCookies;
}
}
public bool HasEntityBody
{
get { return _httpRequest.ContentLength != 0; }
}
public NameValueCollection Headers
{
get
{
NameValueCollection nvc = new NameValueCollection();
foreach (var header in _httpRequest.Headers)
nvc.Add(header.Name, header.Value);
return nvc;
}
}
public NameValueCollection Form
{
get { return _form; }
set { _form = value; }
}
public class HttpFile : IDisposable
{
/// <summary>
/// Gets or sets form element name
/// </summary>
public string Name { get; set; }
/// <summary>
/// Gets or sets client side file name
/// </summary>
public string OriginalFileName { get; set; }
/// <summary>
/// Gets or sets mime content type
/// </summary>
public string ContentType { get; set; }
/// <summary>
/// Gets or sets full path to local file
/// </summary>
public string TempFileName { get; set; }
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
/// <filterpriority>2</filterpriority>
public void Dispose()
{
File.Delete(TempFileName);
}
}
public Dictionary<string, HttpFile> Files
{
get { return _files; }
set { _files = value; }
}
public string HttpMethod
{
get { return _httpRequest.Method; }
}
public Stream InputStream
{
get { return _httpRequest.Body; }
set { _httpRequest.Body = value; }
}
public bool KeepAlive
{
get { return _httpRequest.KeepAlive; }
}
public NameValueCollection QueryString
{
get { return _queryString; }
}
public Hashtable Query
{
get { return _query; }
}
/// <value>
/// POST request values, if applicable
/// </value>
// public Hashtable Form { get; private set; }
public string RawUrl
{
get { return _httpRequest.Uri.AbsolutePath; }
}
public IPEndPoint RemoteIPEndPoint
{
get
{
if (_remoteIPEndPoint == null)
{
if (_httpRequest.Headers["Host"].Value.Split(':').Length == 1)
_remoteIPEndPoint = NetworkUtils.ResolveEndPoint(_httpRequest.Headers["Host"].Value.Split(':')[0], 80);
else
_remoteIPEndPoint = NetworkUtils.ResolveEndPoint(_httpRequest.Headers["Host"].Value.Split(':')[0], int.Parse(_httpRequest.Headers["Host"].Value.Split(':')[1]));
}
return _remoteIPEndPoint;
}
}
public Uri Url
{
get { return _httpRequest.Uri; }
}
public override string ToString()
{
StringBuilder me = new StringBuilder();
me.Append(String.Format("OSHttpRequest: {0} {1}\n", HttpMethod, RawUrl));
foreach (string k in Headers.AllKeys)
{
me.Append(String.Format(" {0}: {1}\n", k, Headers[k]));
}
if (null != RemoteIPEndPoint)
{
me.Append(String.Format(" IP: {0}\n", RemoteIPEndPoint));
}
return me.ToString();
}
internal OSHttpResponse MakeResponse(HttpStatusCode code, string reason)
{
return new OSHttpResponse(_httpContext, _httpRequest, _httpRequest.CreateResponse(code, reason));
}
#region Implementation of IDisposable
public void Dispose()
{
_query.Clear();
_queryString.Clear();
_remoteIPEndPoint = null;
_httpRequest.Body = null;
_httpRequest = null;
_httpContext = null;
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using Android.Runtime;
namespace Org.Achartengine.Model {
// Metadata.xml XPath class reference: path="/api/package[@name='org.achartengine.model']/class[@name='MultipleCategorySeries']"
[global::Android.Runtime.Register ("org/achartengine/model/MultipleCategorySeries", DoNotGenerateAcw=true)]
public partial class MultipleCategorySeries : global::Java.Lang.Object, global::Java.IO.ISerializable {
internal static IntPtr java_class_handle;
internal static IntPtr class_ref {
get {
return JNIEnv.FindClass ("org/achartengine/model/MultipleCategorySeries", ref java_class_handle);
}
}
protected override IntPtr ThresholdClass {
get { return class_ref; }
}
protected override global::System.Type ThresholdType {
get { return typeof (MultipleCategorySeries); }
}
protected MultipleCategorySeries (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {}
static IntPtr id_ctor_Ljava_lang_String_;
// Metadata.xml XPath constructor reference: path="/api/package[@name='org.achartengine.model']/class[@name='MultipleCategorySeries']/constructor[@name='MultipleCategorySeries' and count(parameter)=1 and parameter[1][@type='java.lang.String']]"
[Register (".ctor", "(Ljava/lang/String;)V", "")]
public MultipleCategorySeries (string p0) : base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer)
{
if (Handle != IntPtr.Zero)
return;
IntPtr native_p0 = JNIEnv.NewString (p0);;
if (GetType () != typeof (MultipleCategorySeries)) {
SetHandle (
global::Android.Runtime.JNIEnv.StartCreateInstance (GetType (), "(Ljava/lang/String;)V", new JValue (native_p0)),
JniHandleOwnership.TransferLocalRef);
global::Android.Runtime.JNIEnv.FinishCreateInstance (Handle, "(Ljava/lang/String;)V", new JValue (native_p0));
JNIEnv.DeleteLocalRef (native_p0);
return;
}
if (id_ctor_Ljava_lang_String_ == IntPtr.Zero)
id_ctor_Ljava_lang_String_ = JNIEnv.GetMethodID (class_ref, "<init>", "(Ljava/lang/String;)V");
SetHandle (
global::Android.Runtime.JNIEnv.StartCreateInstance (class_ref, id_ctor_Ljava_lang_String_, new JValue (native_p0)),
JniHandleOwnership.TransferLocalRef);
JNIEnv.FinishCreateInstance (Handle, class_ref, id_ctor_Ljava_lang_String_, new JValue (native_p0));
JNIEnv.DeleteLocalRef (native_p0);
}
static Delegate cb_getCategoriesCount;
#pragma warning disable 0169
static Delegate GetGetCategoriesCountHandler ()
{
if (cb_getCategoriesCount == null)
cb_getCategoriesCount = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, int>) n_GetCategoriesCount);
return cb_getCategoriesCount;
}
static int n_GetCategoriesCount (IntPtr jnienv, IntPtr native__this)
{
global::Org.Achartengine.Model.MultipleCategorySeries __this = global::Java.Lang.Object.GetObject<global::Org.Achartengine.Model.MultipleCategorySeries> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
return __this.CategoriesCount;
}
#pragma warning restore 0169
static IntPtr id_getCategoriesCount;
public virtual int CategoriesCount {
// Metadata.xml XPath method reference: path="/api/package[@name='org.achartengine.model']/class[@name='MultipleCategorySeries']/method[@name='getCategoriesCount' and count(parameter)=0]"
[Register ("getCategoriesCount", "()I", "GetGetCategoriesCountHandler")]
get {
if (id_getCategoriesCount == IntPtr.Zero)
id_getCategoriesCount = JNIEnv.GetMethodID (class_ref, "getCategoriesCount", "()I");
if (GetType () == ThresholdType)
return JNIEnv.CallIntMethod (Handle, id_getCategoriesCount);
else
return JNIEnv.CallNonvirtualIntMethod (Handle, ThresholdClass, id_getCategoriesCount);
}
}
static Delegate cb_add_Ljava_lang_String_arrayLjava_lang_String_arrayD;
#pragma warning disable 0169
static Delegate GetAdd_Ljava_lang_String_arrayLjava_lang_String_arrayDHandler ()
{
if (cb_add_Ljava_lang_String_arrayLjava_lang_String_arrayD == null)
cb_add_Ljava_lang_String_arrayLjava_lang_String_arrayD = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, IntPtr, IntPtr, IntPtr>) n_Add_Ljava_lang_String_arrayLjava_lang_String_arrayD);
return cb_add_Ljava_lang_String_arrayLjava_lang_String_arrayD;
}
static void n_Add_Ljava_lang_String_arrayLjava_lang_String_arrayD (IntPtr jnienv, IntPtr native__this, IntPtr native_p0, IntPtr native_p1, IntPtr native_p2)
{
global::Org.Achartengine.Model.MultipleCategorySeries __this = global::Java.Lang.Object.GetObject<global::Org.Achartengine.Model.MultipleCategorySeries> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
string p0 = JNIEnv.GetString (native_p0, JniHandleOwnership.DoNotTransfer);
string[] p1 = (string[]) JNIEnv.GetArray (native_p1, JniHandleOwnership.DoNotTransfer, typeof (string));
double[] p2 = (double[]) JNIEnv.GetArray (native_p2, JniHandleOwnership.DoNotTransfer, typeof (double));
__this.Add (p0, p1, p2);
if (p1 != null)
JNIEnv.CopyArray (p1, native_p1);
if (p2 != null)
JNIEnv.CopyArray (p2, native_p2);
}
#pragma warning restore 0169
static IntPtr id_add_Ljava_lang_String_arrayLjava_lang_String_arrayD;
// Metadata.xml XPath method reference: path="/api/package[@name='org.achartengine.model']/class[@name='MultipleCategorySeries']/method[@name='add' and count(parameter)=3 and parameter[1][@type='java.lang.String'] and parameter[2][@type='java.lang.String[]'] and parameter[3][@type='double[]']]"
[Register ("add", "(Ljava/lang/String;[Ljava/lang/String;[D)V", "GetAdd_Ljava_lang_String_arrayLjava_lang_String_arrayDHandler")]
public virtual void Add (string p0, string[] p1, double[] p2)
{
if (id_add_Ljava_lang_String_arrayLjava_lang_String_arrayD == IntPtr.Zero)
id_add_Ljava_lang_String_arrayLjava_lang_String_arrayD = JNIEnv.GetMethodID (class_ref, "add", "(Ljava/lang/String;[Ljava/lang/String;[D)V");
IntPtr native_p0 = JNIEnv.NewString (p0);
IntPtr native_p1 = JNIEnv.NewArray (p1);
IntPtr native_p2 = JNIEnv.NewArray (p2);
if (GetType () == ThresholdType)
JNIEnv.CallVoidMethod (Handle, id_add_Ljava_lang_String_arrayLjava_lang_String_arrayD, new JValue (native_p0), new JValue (native_p1), new JValue (native_p2));
else
JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, id_add_Ljava_lang_String_arrayLjava_lang_String_arrayD, new JValue (native_p0), new JValue (native_p1), new JValue (native_p2));
JNIEnv.DeleteLocalRef (native_p0);
if (p1 != null) {
JNIEnv.CopyArray (native_p1, p1);
JNIEnv.DeleteLocalRef (native_p1);
}
if (p2 != null) {
JNIEnv.CopyArray (native_p2, p2);
JNIEnv.DeleteLocalRef (native_p2);
}
}
static Delegate cb_add_arrayLjava_lang_String_arrayD;
#pragma warning disable 0169
static Delegate GetAdd_arrayLjava_lang_String_arrayDHandler ()
{
if (cb_add_arrayLjava_lang_String_arrayD == null)
cb_add_arrayLjava_lang_String_arrayD = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, IntPtr, IntPtr>) n_Add_arrayLjava_lang_String_arrayD);
return cb_add_arrayLjava_lang_String_arrayD;
}
static void n_Add_arrayLjava_lang_String_arrayD (IntPtr jnienv, IntPtr native__this, IntPtr native_p0, IntPtr native_p1)
{
global::Org.Achartengine.Model.MultipleCategorySeries __this = global::Java.Lang.Object.GetObject<global::Org.Achartengine.Model.MultipleCategorySeries> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
string[] p0 = (string[]) JNIEnv.GetArray (native_p0, JniHandleOwnership.DoNotTransfer, typeof (string));
double[] p1 = (double[]) JNIEnv.GetArray (native_p1, JniHandleOwnership.DoNotTransfer, typeof (double));
__this.Add (p0, p1);
if (p0 != null)
JNIEnv.CopyArray (p0, native_p0);
if (p1 != null)
JNIEnv.CopyArray (p1, native_p1);
}
#pragma warning restore 0169
static IntPtr id_add_arrayLjava_lang_String_arrayD;
// Metadata.xml XPath method reference: path="/api/package[@name='org.achartengine.model']/class[@name='MultipleCategorySeries']/method[@name='add' and count(parameter)=2 and parameter[1][@type='java.lang.String[]'] and parameter[2][@type='double[]']]"
[Register ("add", "([Ljava/lang/String;[D)V", "GetAdd_arrayLjava_lang_String_arrayDHandler")]
public virtual void Add (string[] p0, double[] p1)
{
if (id_add_arrayLjava_lang_String_arrayD == IntPtr.Zero)
id_add_arrayLjava_lang_String_arrayD = JNIEnv.GetMethodID (class_ref, "add", "([Ljava/lang/String;[D)V");
IntPtr native_p0 = JNIEnv.NewArray (p0);
IntPtr native_p1 = JNIEnv.NewArray (p1);
if (GetType () == ThresholdType)
JNIEnv.CallVoidMethod (Handle, id_add_arrayLjava_lang_String_arrayD, new JValue (native_p0), new JValue (native_p1));
else
JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, id_add_arrayLjava_lang_String_arrayD, new JValue (native_p0), new JValue (native_p1));
if (p0 != null) {
JNIEnv.CopyArray (native_p0, p0);
JNIEnv.DeleteLocalRef (native_p0);
}
if (p1 != null) {
JNIEnv.CopyArray (native_p1, p1);
JNIEnv.DeleteLocalRef (native_p1);
}
}
static Delegate cb_clear;
#pragma warning disable 0169
static Delegate GetClearHandler ()
{
if (cb_clear == null)
cb_clear = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr>) n_Clear);
return cb_clear;
}
static void n_Clear (IntPtr jnienv, IntPtr native__this)
{
global::Org.Achartengine.Model.MultipleCategorySeries __this = global::Java.Lang.Object.GetObject<global::Org.Achartengine.Model.MultipleCategorySeries> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
__this.Clear ();
}
#pragma warning restore 0169
static IntPtr id_clear;
// Metadata.xml XPath method reference: path="/api/package[@name='org.achartengine.model']/class[@name='MultipleCategorySeries']/method[@name='clear' and count(parameter)=0]"
[Register ("clear", "()V", "GetClearHandler")]
public virtual void Clear ()
{
if (id_clear == IntPtr.Zero)
id_clear = JNIEnv.GetMethodID (class_ref, "clear", "()V");
if (GetType () == ThresholdType)
JNIEnv.CallVoidMethod (Handle, id_clear);
else
JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, id_clear);
}
static Delegate cb_getCategory_I;
#pragma warning disable 0169
static Delegate GetGetCategory_IHandler ()
{
if (cb_getCategory_I == null)
cb_getCategory_I = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, int, IntPtr>) n_GetCategory_I);
return cb_getCategory_I;
}
static IntPtr n_GetCategory_I (IntPtr jnienv, IntPtr native__this, int p0)
{
global::Org.Achartengine.Model.MultipleCategorySeries __this = global::Java.Lang.Object.GetObject<global::Org.Achartengine.Model.MultipleCategorySeries> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
return JNIEnv.NewString (__this.GetCategory (p0));
}
#pragma warning restore 0169
static IntPtr id_getCategory_I;
// Metadata.xml XPath method reference: path="/api/package[@name='org.achartengine.model']/class[@name='MultipleCategorySeries']/method[@name='getCategory' and count(parameter)=1 and parameter[1][@type='int']]"
[Register ("getCategory", "(I)Ljava/lang/String;", "GetGetCategory_IHandler")]
public virtual string GetCategory (int p0)
{
if (id_getCategory_I == IntPtr.Zero)
id_getCategory_I = JNIEnv.GetMethodID (class_ref, "getCategory", "(I)Ljava/lang/String;");
if (GetType () == ThresholdType)
return JNIEnv.GetString (JNIEnv.CallObjectMethod (Handle, id_getCategory_I, new JValue (p0)), JniHandleOwnership.TransferLocalRef);
else
return JNIEnv.GetString (JNIEnv.CallNonvirtualObjectMethod (Handle, ThresholdClass, id_getCategory_I, new JValue (p0)), JniHandleOwnership.TransferLocalRef);
}
static Delegate cb_getItemCount_I;
#pragma warning disable 0169
static Delegate GetGetItemCount_IHandler ()
{
if (cb_getItemCount_I == null)
cb_getItemCount_I = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, int, int>) n_GetItemCount_I);
return cb_getItemCount_I;
}
static int n_GetItemCount_I (IntPtr jnienv, IntPtr native__this, int p0)
{
global::Org.Achartengine.Model.MultipleCategorySeries __this = global::Java.Lang.Object.GetObject<global::Org.Achartengine.Model.MultipleCategorySeries> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
return __this.GetItemCount (p0);
}
#pragma warning restore 0169
static IntPtr id_getItemCount_I;
// Metadata.xml XPath method reference: path="/api/package[@name='org.achartengine.model']/class[@name='MultipleCategorySeries']/method[@name='getItemCount' and count(parameter)=1 and parameter[1][@type='int']]"
[Register ("getItemCount", "(I)I", "GetGetItemCount_IHandler")]
public virtual int GetItemCount (int p0)
{
if (id_getItemCount_I == IntPtr.Zero)
id_getItemCount_I = JNIEnv.GetMethodID (class_ref, "getItemCount", "(I)I");
if (GetType () == ThresholdType)
return JNIEnv.CallIntMethod (Handle, id_getItemCount_I, new JValue (p0));
else
return JNIEnv.CallNonvirtualIntMethod (Handle, ThresholdClass, id_getItemCount_I, new JValue (p0));
}
static Delegate cb_getTitles_I;
#pragma warning disable 0169
static Delegate GetGetTitles_IHandler ()
{
if (cb_getTitles_I == null)
cb_getTitles_I = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, int, IntPtr>) n_GetTitles_I);
return cb_getTitles_I;
}
static IntPtr n_GetTitles_I (IntPtr jnienv, IntPtr native__this, int p0)
{
global::Org.Achartengine.Model.MultipleCategorySeries __this = global::Java.Lang.Object.GetObject<global::Org.Achartengine.Model.MultipleCategorySeries> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
return JNIEnv.NewArray (__this.GetTitles (p0));
}
#pragma warning restore 0169
static IntPtr id_getTitles_I;
// Metadata.xml XPath method reference: path="/api/package[@name='org.achartengine.model']/class[@name='MultipleCategorySeries']/method[@name='getTitles' and count(parameter)=1 and parameter[1][@type='int']]"
[Register ("getTitles", "(I)[Ljava/lang/String;", "GetGetTitles_IHandler")]
public virtual string[] GetTitles (int p0)
{
if (id_getTitles_I == IntPtr.Zero)
id_getTitles_I = JNIEnv.GetMethodID (class_ref, "getTitles", "(I)[Ljava/lang/String;");
if (GetType () == ThresholdType)
return (string[]) JNIEnv.GetArray (JNIEnv.CallObjectMethod (Handle, id_getTitles_I, new JValue (p0)), JniHandleOwnership.TransferLocalRef, typeof (string));
else
return (string[]) JNIEnv.GetArray (JNIEnv.CallNonvirtualObjectMethod (Handle, ThresholdClass, id_getTitles_I, new JValue (p0)), JniHandleOwnership.TransferLocalRef, typeof (string));
}
static Delegate cb_getValues_I;
#pragma warning disable 0169
static Delegate GetGetValues_IHandler ()
{
if (cb_getValues_I == null)
cb_getValues_I = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, int, IntPtr>) n_GetValues_I);
return cb_getValues_I;
}
static IntPtr n_GetValues_I (IntPtr jnienv, IntPtr native__this, int p0)
{
global::Org.Achartengine.Model.MultipleCategorySeries __this = global::Java.Lang.Object.GetObject<global::Org.Achartengine.Model.MultipleCategorySeries> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
return JNIEnv.NewArray (__this.GetValues (p0));
}
#pragma warning restore 0169
static IntPtr id_getValues_I;
// Metadata.xml XPath method reference: path="/api/package[@name='org.achartengine.model']/class[@name='MultipleCategorySeries']/method[@name='getValues' and count(parameter)=1 and parameter[1][@type='int']]"
[Register ("getValues", "(I)[D", "GetGetValues_IHandler")]
public virtual double[] GetValues (int p0)
{
if (id_getValues_I == IntPtr.Zero)
id_getValues_I = JNIEnv.GetMethodID (class_ref, "getValues", "(I)[D");
if (GetType () == ThresholdType)
return (double[]) JNIEnv.GetArray (JNIEnv.CallObjectMethod (Handle, id_getValues_I, new JValue (p0)), JniHandleOwnership.TransferLocalRef, typeof (double));
else
return (double[]) JNIEnv.GetArray (JNIEnv.CallNonvirtualObjectMethod (Handle, ThresholdClass, id_getValues_I, new JValue (p0)), JniHandleOwnership.TransferLocalRef, typeof (double));
}
static Delegate cb_remove_I;
#pragma warning disable 0169
static Delegate GetRemove_IHandler ()
{
if (cb_remove_I == null)
cb_remove_I = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, int>) n_Remove_I);
return cb_remove_I;
}
static void n_Remove_I (IntPtr jnienv, IntPtr native__this, int p0)
{
global::Org.Achartengine.Model.MultipleCategorySeries __this = global::Java.Lang.Object.GetObject<global::Org.Achartengine.Model.MultipleCategorySeries> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
__this.Remove (p0);
}
#pragma warning restore 0169
static IntPtr id_remove_I;
// Metadata.xml XPath method reference: path="/api/package[@name='org.achartengine.model']/class[@name='MultipleCategorySeries']/method[@name='remove' and count(parameter)=1 and parameter[1][@type='int']]"
[Register ("remove", "(I)V", "GetRemove_IHandler")]
public virtual void Remove (int p0)
{
if (id_remove_I == IntPtr.Zero)
id_remove_I = JNIEnv.GetMethodID (class_ref, "remove", "(I)V");
if (GetType () == ThresholdType)
JNIEnv.CallVoidMethod (Handle, id_remove_I, new JValue (p0));
else
JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, id_remove_I, new JValue (p0));
}
static Delegate cb_toXYSeries;
#pragma warning disable 0169
static Delegate GetToXYSeriesHandler ()
{
if (cb_toXYSeries == null)
cb_toXYSeries = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr>) n_ToXYSeries);
return cb_toXYSeries;
}
static IntPtr n_ToXYSeries (IntPtr jnienv, IntPtr native__this)
{
global::Org.Achartengine.Model.MultipleCategorySeries __this = global::Java.Lang.Object.GetObject<global::Org.Achartengine.Model.MultipleCategorySeries> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
return JNIEnv.ToLocalJniHandle (__this.ToXYSeries ());
}
#pragma warning restore 0169
static IntPtr id_toXYSeries;
// Metadata.xml XPath method reference: path="/api/package[@name='org.achartengine.model']/class[@name='MultipleCategorySeries']/method[@name='toXYSeries' and count(parameter)=0]"
[Register ("toXYSeries", "()Lorg/achartengine/model/XYSeries;", "GetToXYSeriesHandler")]
public virtual global::Org.Achartengine.Model.XYSeries ToXYSeries ()
{
if (id_toXYSeries == IntPtr.Zero)
id_toXYSeries = JNIEnv.GetMethodID (class_ref, "toXYSeries", "()Lorg/achartengine/model/XYSeries;");
if (GetType () == ThresholdType)
return global::Java.Lang.Object.GetObject<global::Org.Achartengine.Model.XYSeries> (JNIEnv.CallObjectMethod (Handle, id_toXYSeries), JniHandleOwnership.TransferLocalRef);
else
return global::Java.Lang.Object.GetObject<global::Org.Achartengine.Model.XYSeries> (JNIEnv.CallNonvirtualObjectMethod (Handle, ThresholdClass, id_toXYSeries), JniHandleOwnership.TransferLocalRef);
}
}
}
| |
//
// AddinView.cs
//
// Author:
// Aaron Bockover <[email protected]>
//
// Copyright (C) 2008 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using Gtk;
using Mono.Addins;
namespace Banshee.Addins.Gui
{
public class AddinView : EventBox
{
private List<AddinTile> tiles = new List<AddinTile> ();
private VBox box = new VBox ();
private int selected_index = -1;
public AddinView ()
{
CanFocus = true;
VisibleWindow = false;
box.Show ();
Add (box);
LoadAddins ();
}
private void LoadAddins ()
{
foreach (Addin addin in AddinManager.Registry.GetAddins ()) {
if (addin.Name != addin.Id && addin.Description != null &&
addin.Description.Category != null && !addin.Description.Category.StartsWith ("required:") &&
(!addin.Description.Category.Contains ("Debug") || Banshee.Base.ApplicationContext.Debugging)) {
AppendAddin (addin);
}
}
if (tiles.Count > 0) {
tiles[tiles.Count - 1].Last = true;
}
}
private bool changing_styles = false;
protected override void OnStyleSet (Style previous_style)
{
if (changing_styles) {
return;
}
changing_styles = true;
base.OnStyleSet (previous_style);
Parent.ModifyBg (StateType.Normal, Style.Base (StateType.Normal));
changing_styles = false;
}
private void AppendAddin (Addin addin)
{
AddinTile tile = new AddinTile (addin);
tile.ActiveChanged += OnAddinActiveChanged;
tile.SizeAllocated += OnAddinSizeAllocated;
tile.Show ();
tiles.Add (tile);
box.PackStart (tile, false, false, 0);
}
private void OnAddinActiveChanged (object o, EventArgs args)
{
foreach (AddinTile tile in tiles) {
tile.UpdateState ();
}
}
private void OnAddinSizeAllocated (object o, SizeAllocatedArgs args)
{
ScrolledWindow scroll;
if (Parent == null || (scroll = Parent.Parent as ScrolledWindow) == null) {
return;
}
AddinTile tile = (AddinTile)o;
if (tiles.IndexOf (tile) != selected_index) {
return;
}
Gdk.Rectangle ta = ((AddinTile)o).Allocation;
Gdk.Rectangle va = new Gdk.Rectangle (0, (int)scroll.Vadjustment.Value,
Allocation.Width, Parent.Allocation.Height);
if (!va.Contains (ta)) {
double delta = 0.0;
if (ta.Bottom > va.Bottom) {
delta = ta.Bottom - va.Bottom;
} else if (ta.Top < va.Top) {
delta = ta.Top - va.Top;
}
scroll.Vadjustment.Value += delta;
QueueDraw();
}
}
protected override bool OnButtonPressEvent (Gdk.EventButton evnt)
{
HasFocus = true;
ClearSelection ();
for (int i = 0; i < tiles.Count; i++) {
if (tiles[i].Allocation.Contains ((int)evnt.X, (int)evnt.Y)) {
Select (i);
break;
}
}
QueueDraw ();
return base.OnButtonPressEvent (evnt);
}
protected override bool OnKeyPressEvent (Gdk.EventKey evnt)
{
int index = selected_index;
switch (evnt.Key) {
case Gdk.Key.Up:
case Gdk.Key.uparrow:
index--;
if (index < 0) {
index = 0;
}
break;
case Gdk.Key.Down:
case Gdk.Key.downarrow:
index++;
if (index > tiles.Count - 1) {
index = tiles.Count - 1;
}
break;
}
if (index != selected_index) {
ClearSelection ();
Select (index);
return true;
}
return base.OnKeyPressEvent (evnt);
}
private void Select (int index)
{
if (index >= 0 && index < tiles.Count) {
selected_index = index;
tiles[index].Select (true);
} else {
ClearSelection ();
}
if (Parent != null && Parent.IsRealized) {
Parent.GdkWindow.InvalidateRect (Parent.Allocation, true);
}
QueueResize ();
}
private void ClearSelection ()
{
if (selected_index >= 0 && selected_index < tiles.Count) {
tiles[selected_index].Select (false);
}
selected_index = -1;
}
}
}
| |
//
// 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.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.Management.Rdfe.Models;
namespace Microsoft.Azure.Management.Rdfe
{
/// <summary>
/// The Service Management API provides programmatic access to much of the
/// functionality available through the Management Portal. The Service
/// Management API is a REST API. All API operations are performed over
/// SSL and are mutually authenticated using X.509 v3 certificates. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/ee460799.aspx for
/// more information)
/// </summary>
public static partial class SubscriptionOperationsExtensions
{
/// <summary>
/// The Get Subscription operation returns account and resource
/// allocation information for the specified subscription. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/hh403995.aspx
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Rdfe.ISubscriptionOperations.
/// </param>
/// <returns>
/// The Get Subscription operation response.
/// </returns>
public static SubscriptionGetResponse Get(this ISubscriptionOperations operations)
{
return Task.Factory.StartNew((object s) =>
{
return ((ISubscriptionOperations)s).GetAsync();
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The Get Subscription operation returns account and resource
/// allocation information for the specified subscription. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/hh403995.aspx
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Rdfe.ISubscriptionOperations.
/// </param>
/// <returns>
/// The Get Subscription operation response.
/// </returns>
public static Task<SubscriptionGetResponse> GetAsync(this ISubscriptionOperations operations)
{
return operations.GetAsync(CancellationToken.None);
}
/// <summary>
/// The List Subscription Operations operation returns a list of
/// create, update, and delete operations that were performed on a
/// subscription during the specified timeframe. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/gg715318.aspx
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Rdfe.ISubscriptionOperations.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the List Subscription Operations
/// operation.
/// </param>
/// <returns>
/// The List Subscription Operations operation response.
/// </returns>
public static SubscriptionListOperationsResponse ListOperations(this ISubscriptionOperations operations, SubscriptionListOperationsParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((ISubscriptionOperations)s).ListOperationsAsync(parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The List Subscription Operations operation returns a list of
/// create, update, and delete operations that were performed on a
/// subscription during the specified timeframe. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/gg715318.aspx
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Rdfe.ISubscriptionOperations.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the List Subscription Operations
/// operation.
/// </param>
/// <returns>
/// The List Subscription Operations operation response.
/// </returns>
public static Task<SubscriptionListOperationsResponse> ListOperationsAsync(this ISubscriptionOperations operations, SubscriptionListOperationsParameters parameters)
{
return operations.ListOperationsAsync(parameters, CancellationToken.None);
}
/// <summary>
/// Register a resource with your subscription.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Rdfe.ISubscriptionOperations.
/// </param>
/// <param name='resourceName'>
/// Required. Name of the resource to register.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static AzureOperationResponse RegisterResource(this ISubscriptionOperations operations, string resourceName)
{
return Task.Factory.StartNew((object s) =>
{
return ((ISubscriptionOperations)s).RegisterResourceAsync(resourceName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Register a resource with your subscription.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Rdfe.ISubscriptionOperations.
/// </param>
/// <param name='resourceName'>
/// Required. Name of the resource to register.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static Task<AzureOperationResponse> RegisterResourceAsync(this ISubscriptionOperations operations, string resourceName)
{
return operations.RegisterResourceAsync(resourceName, CancellationToken.None);
}
/// <summary>
/// Unregister a resource with your subscription.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Rdfe.ISubscriptionOperations.
/// </param>
/// <param name='resourceName'>
/// Required. Name of the resource to unregister.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static AzureOperationResponse UnregisterResource(this ISubscriptionOperations operations, string resourceName)
{
return Task.Factory.StartNew((object s) =>
{
return ((ISubscriptionOperations)s).UnregisterResourceAsync(resourceName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Unregister a resource with your subscription.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Rdfe.ISubscriptionOperations.
/// </param>
/// <param name='resourceName'>
/// Required. Name of the resource to unregister.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static Task<AzureOperationResponse> UnregisterResourceAsync(this ISubscriptionOperations operations, string resourceName)
{
return operations.UnregisterResourceAsync(resourceName, CancellationToken.None);
}
}
}
| |
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Semmle.Extraction.Kinds;
namespace Semmle.Extraction.CSharp.Entities.Expressions
{
internal static class Factory
{
internal static Expression Create(ExpressionNodeInfo info)
{
// Some expressions can be extremely deep (e.g. string + string + string ...)
// to the extent that the stack has been known to overflow.
using (info.Context.StackGuard)
{
if (info.Node is null)
{
info.Context.ModelError(info.Location, "Attempt to create a null expression");
return new Unknown(info);
}
switch (info.Node.Kind())
{
case SyntaxKind.AddExpression:
case SyntaxKind.SubtractExpression:
case SyntaxKind.LessThanExpression:
case SyntaxKind.LessThanOrEqualExpression:
case SyntaxKind.GreaterThanExpression:
case SyntaxKind.GreaterThanOrEqualExpression:
case SyntaxKind.MultiplyExpression:
case SyntaxKind.LogicalAndExpression:
case SyntaxKind.EqualsExpression:
case SyntaxKind.ModuloExpression:
case SyntaxKind.BitwiseAndExpression:
case SyntaxKind.BitwiseOrExpression:
case SyntaxKind.DivideExpression:
case SyntaxKind.NotEqualsExpression:
case SyntaxKind.LogicalOrExpression:
case SyntaxKind.IsExpression:
case SyntaxKind.AsExpression:
case SyntaxKind.RightShiftExpression:
case SyntaxKind.LeftShiftExpression:
case SyntaxKind.ExclusiveOrExpression:
case SyntaxKind.CoalesceExpression:
return Binary.Create(info);
case SyntaxKind.FalseLiteralExpression:
case SyntaxKind.TrueLiteralExpression:
case SyntaxKind.StringLiteralExpression:
case SyntaxKind.NullLiteralExpression:
case SyntaxKind.NumericLiteralExpression:
case SyntaxKind.CharacterLiteralExpression:
case SyntaxKind.DefaultLiteralExpression:
return Literal.Create(info);
case SyntaxKind.InvocationExpression:
return Invocation.Create(info);
case SyntaxKind.PostIncrementExpression:
return PostfixUnary.Create(info.SetKind(ExprKind.POST_INCR), ((PostfixUnaryExpressionSyntax)info.Node).Operand);
case SyntaxKind.PostDecrementExpression:
return PostfixUnary.Create(info.SetKind(ExprKind.POST_DECR), ((PostfixUnaryExpressionSyntax)info.Node).Operand);
case SyntaxKind.AwaitExpression:
return Await.Create(info);
case SyntaxKind.ElementAccessExpression:
return NormalElementAccess.Create(info);
case SyntaxKind.SimpleAssignmentExpression:
case SyntaxKind.OrAssignmentExpression:
case SyntaxKind.AndAssignmentExpression:
case SyntaxKind.SubtractAssignmentExpression:
case SyntaxKind.AddAssignmentExpression:
case SyntaxKind.MultiplyAssignmentExpression:
case SyntaxKind.ExclusiveOrAssignmentExpression:
case SyntaxKind.LeftShiftAssignmentExpression:
case SyntaxKind.RightShiftAssignmentExpression:
case SyntaxKind.DivideAssignmentExpression:
case SyntaxKind.ModuloAssignmentExpression:
case SyntaxKind.CoalesceAssignmentExpression:
return Assignment.Create(info);
case SyntaxKind.ObjectCreationExpression:
return ExplicitObjectCreation.Create(info);
case SyntaxKind.ImplicitObjectCreationExpression:
return ImplicitObjectCreation.Create(info);
case SyntaxKind.ArrayCreationExpression:
return NormalArrayCreation.Create(info);
case SyntaxKind.ObjectInitializerExpression:
return ObjectInitializer.Create(info);
case SyntaxKind.ArrayInitializerExpression:
return ImplicitArrayInitializer.Create(info);
case SyntaxKind.CollectionInitializerExpression:
return CollectionInitializer.Create(info);
case SyntaxKind.ConditionalAccessExpression:
return MemberAccess.Create(info, (ConditionalAccessExpressionSyntax)info.Node);
case SyntaxKind.SimpleMemberAccessExpression:
return MemberAccess.Create(info, (MemberAccessExpressionSyntax)info.Node);
case SyntaxKind.UnaryMinusExpression:
return Unary.Create(info.SetKind(ExprKind.MINUS));
case SyntaxKind.UnaryPlusExpression:
return Unary.Create(info.SetKind(ExprKind.PLUS));
case SyntaxKind.SimpleLambdaExpression:
return Lambda.Create(info, (SimpleLambdaExpressionSyntax)info.Node);
case SyntaxKind.ParenthesizedLambdaExpression:
return Lambda.Create(info, (ParenthesizedLambdaExpressionSyntax)info.Node);
case SyntaxKind.ConditionalExpression:
return Conditional.Create(info);
case SyntaxKind.CastExpression:
return Cast.Create(info);
case SyntaxKind.ParenthesizedExpression:
return Create(info.SetNode(((ParenthesizedExpressionSyntax)info.Node).Expression));
case SyntaxKind.PointerType:
case SyntaxKind.ArrayType:
case SyntaxKind.PredefinedType:
case SyntaxKind.NullableType:
case SyntaxKind.TupleType:
return TypeAccess.Create(info);
case SyntaxKind.TypeOfExpression:
return TypeOf.Create(info);
case SyntaxKind.QualifiedName:
case SyntaxKind.IdentifierName:
case SyntaxKind.AliasQualifiedName:
case SyntaxKind.GenericName:
return Name.Create(info);
case SyntaxKind.LogicalNotExpression:
return Unary.Create(info.SetKind(ExprKind.LOG_NOT));
case SyntaxKind.BitwiseNotExpression:
return Unary.Create(info.SetKind(ExprKind.BIT_NOT));
case SyntaxKind.PreIncrementExpression:
return Unary.Create(info.SetKind(ExprKind.PRE_INCR));
case SyntaxKind.PreDecrementExpression:
return Unary.Create(info.SetKind(ExprKind.PRE_DECR));
case SyntaxKind.ThisExpression:
return This.CreateExplicit(info);
case SyntaxKind.AddressOfExpression:
return Unary.Create(info.SetKind(ExprKind.ADDRESS_OF));
case SyntaxKind.PointerIndirectionExpression:
return Unary.Create(info.SetKind(ExprKind.POINTER_INDIRECTION));
case SyntaxKind.DefaultExpression:
return Default.Create(info);
case SyntaxKind.CheckedExpression:
return Checked.Create(info);
case SyntaxKind.UncheckedExpression:
return Unchecked.Create(info);
case SyntaxKind.BaseExpression:
return Base.Create(info);
case SyntaxKind.AnonymousMethodExpression:
return Lambda.Create(info, (AnonymousMethodExpressionSyntax)info.Node);
case SyntaxKind.ImplicitArrayCreationExpression:
return ImplicitArrayCreation.Create(info);
case SyntaxKind.AnonymousObjectCreationExpression:
return AnonymousObjectCreation.Create(info);
case SyntaxKind.ComplexElementInitializerExpression:
return CollectionInitializer.Create(info);
case SyntaxKind.SizeOfExpression:
return SizeOf.Create(info);
case SyntaxKind.PointerMemberAccessExpression:
return PointerMemberAccess.Create(info);
case SyntaxKind.QueryExpression:
return Query.Create(info);
case SyntaxKind.InterpolatedStringExpression:
return InterpolatedString.Create(info);
case SyntaxKind.MemberBindingExpression:
return MemberAccess.Create(info, (MemberBindingExpressionSyntax)info.Node);
case SyntaxKind.ElementBindingExpression:
return BindingElementAccess.Create(info);
case SyntaxKind.StackAllocArrayCreationExpression:
return StackAllocArrayCreation.Create(info);
case SyntaxKind.ImplicitStackAllocArrayCreationExpression:
return ImplicitStackAllocArrayCreation.Create(info);
case SyntaxKind.ArgListExpression:
return ArgList.Create(info);
case SyntaxKind.RefTypeExpression:
return RefType.Create(info);
case SyntaxKind.RefValueExpression:
return RefValue.Create(info);
case SyntaxKind.MakeRefExpression:
return MakeRef.Create(info);
case SyntaxKind.ThrowExpression:
return Throw.Create(info);
case SyntaxKind.DeclarationExpression:
return VariableDeclaration.Create(info.Context, (DeclarationExpressionSyntax)info.Node, info.Parent, info.Child);
case SyntaxKind.TupleExpression:
return Tuple.Create(info);
case SyntaxKind.RefExpression:
return Ref.Create(info);
case SyntaxKind.IsPatternExpression:
return IsPattern.Create(info);
case SyntaxKind.RangeExpression:
return RangeExpression.Create(info);
case SyntaxKind.IndexExpression:
return Unary.Create(info.SetKind(ExprKind.INDEX));
case SyntaxKind.SwitchExpression:
return Switch.Create(info);
case SyntaxKind.SuppressNullableWarningExpression:
return PostfixUnary.Create(info.SetKind(ExprKind.SUPPRESS_NULLABLE_WARNING), ((PostfixUnaryExpressionSyntax)info.Node).Operand);
case SyntaxKind.WithExpression:
return WithExpression.Create(info);
default:
info.Context.ModelError(info.Node, $"Unhandled expression '{info.Node}' of kind '{info.Node.Kind()}'");
return new Unknown(info);
}
}
}
}
}
| |
//
// Copyright (c) 2004-2011 Jaroslaw Kowalski <[email protected]>
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
using System.Runtime.CompilerServices;
namespace NLog.UnitTests
{
using System;
using NLog.Common;
using System.IO;
using System.Text;
using NLog.Layouts;
using NLog.Config;
using Xunit;
#if SILVERLIGHT
using System.Xml.Linq;
#else
using System.Xml;
using System.IO.Compression;
using System.Security.Permissions;
#endif
public abstract class NLogTestBase
{
protected NLogTestBase()
{
InternalLogger.LogToConsole = false;
InternalLogger.LogToConsoleError = false;
LogManager.ThrowExceptions = false;
}
public void AssertDebugCounter(string targetName, int val)
{
Assert.Equal(val, GetDebugTarget(targetName).Counter);
}
public void AssertDebugLastMessage(string targetName, string msg)
{
Assert.Equal(msg, GetDebugLastMessage(targetName));
}
public void AssertDebugLastMessageContains(string targetName, string msg)
{
string debugLastMessage = GetDebugLastMessage(targetName);
Assert.True(debugLastMessage.Contains(msg),
string.Format("Expected to find '{0}' in last message value on '{1}', but found '{2}'", msg, targetName, debugLastMessage));
}
public string GetDebugLastMessage(string targetName)
{
return GetDebugLastMessage(targetName, LogManager.Configuration);
}
public string GetDebugLastMessage(string targetName, LoggingConfiguration configuration)
{
return GetDebugTarget(targetName, configuration).LastMessage;
}
public NLog.Targets.DebugTarget GetDebugTarget(string targetName)
{
return GetDebugTarget(targetName, LogManager.Configuration);
}
public NLog.Targets.DebugTarget GetDebugTarget(string targetName, LoggingConfiguration configuration)
{
var debugTarget = (NLog.Targets.DebugTarget)configuration.FindTargetByName(targetName);
Assert.NotNull(debugTarget);
return debugTarget;
}
public void AssertFileContentsStartsWith(string fileName, string contents, Encoding encoding)
{
FileInfo fi = new FileInfo(fileName);
if (!fi.Exists)
Assert.True(true, "File '" + fileName + "' doesn't exist.");
byte[] encodedBuf = encoding.GetBytes(contents);
Assert.True(encodedBuf.Length <= fi.Length);
byte[] buf = new byte[encodedBuf.Length];
using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read))
{
fs.Read(buf, 0, buf.Length);
}
for (int i = 0; i < buf.Length; ++i)
{
Assert.Equal(encodedBuf[i], buf[i]);
}
}
public void AssertFileSize(string filename, long expectedSize)
{
var fi = new FileInfo(filename);
if (!fi.Exists)
{
Assert.True(true, string.Format("File \"{0}\" doesn't exist.", filename));
}
if (fi.Length != expectedSize)
{
Assert.True(true, string.Format("Filesize of \"{0}\" unequals {1}.", filename, expectedSize));
}
}
#if NET4_5
public void AssertZipFileContents(string fileName, string contents, Encoding encoding)
{
FileInfo fi = new FileInfo(fileName);
if (!fi.Exists)
Assert.True(true, "File '" + fileName + "' doesn't exist.");
byte[] encodedBuf = encoding.GetBytes(contents);
using (var stream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read))
using (var zip = new ZipArchive(stream, ZipArchiveMode.Read))
{
Assert.Equal(1, zip.Entries.Count);
Assert.Equal(encodedBuf.Length, zip.Entries[0].Length);
byte[] buf = new byte[(int)zip.Entries[0].Length];
using (var fs = zip.Entries[0].Open())
{
fs.Read(buf, 0, buf.Length);
}
for (int i = 0; i < buf.Length; ++i)
{
Assert.Equal(encodedBuf[i], buf[i]);
}
}
}
#endif
public void AssertFileContents(string fileName, string contents, Encoding encoding)
{
FileInfo fi = new FileInfo(fileName);
if (!fi.Exists)
Assert.True(true, "File '" + fileName + "' doesn't exist.");
byte[] encodedBuf = encoding.GetBytes(contents);
Assert.Equal(encodedBuf.Length, fi.Length);
byte[] buf = new byte[(int)fi.Length];
using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read))
{
fs.Read(buf, 0, buf.Length);
}
for (int i = 0; i < buf.Length; ++i)
{
Assert.Equal(encodedBuf[i], buf[i]);
}
}
public string StringRepeat(int times, string s)
{
StringBuilder sb = new StringBuilder(s.Length * times);
for (int i = 0; i < times; ++i)
sb.Append(s);
return sb.ToString();
}
protected void AssertLayoutRendererOutput(Layout l, string expected)
{
l.Initialize(null);
string actual = l.Render(LogEventInfo.Create(LogLevel.Info, "loggername", "message"));
l.Close();
Assert.Equal(expected, actual);
}
#if MONO || NET4_5
/// <summary>
/// Get line number of previous line.
/// </summary>
protected int GetPrevLineNumber([CallerLineNumber] int callingFileLineNumber = 0)
{
return callingFileLineNumber-1;
}
#else
/// <summary>
/// Get line number of previous line.
/// </summary>
protected int GetPrevLineNumber()
{
//fixed value set with #line 100000
return 100001;
}
#endif
protected XmlLoggingConfiguration CreateConfigurationFromString(string configXml)
{
#if SILVERLIGHT
XElement element = XElement.Parse(configXml);
return new XmlLoggingConfiguration(element.CreateReader(), null);
#else
XmlDocument doc = new XmlDocument();
doc.LoadXml(configXml);
return new XmlLoggingConfiguration(doc.DocumentElement, Environment.CurrentDirectory);
#endif
}
protected string RunAndCaptureInternalLog(SyncAction action, LogLevel internalLogLevel)
{
var stringWriter = new StringWriter();
var oldWriter = InternalLogger.LogWriter;
var oldLevel = InternalLogger.LogLevel;
var oldIncludeTimestamp = InternalLogger.IncludeTimestamp;
try
{
InternalLogger.LogWriter = stringWriter;
InternalLogger.LogLevel = LogLevel.Trace;
InternalLogger.IncludeTimestamp = false;
action();
return stringWriter.ToString();
}
finally
{
InternalLogger.LogWriter = oldWriter;
InternalLogger.LogLevel = oldLevel;
InternalLogger.IncludeTimestamp = oldIncludeTimestamp;
}
}
public delegate void SyncAction();
public class InternalLoggerScope : IDisposable
{
private readonly string logFile;
private readonly LogLevel logLevel;
private readonly bool logToConsole;
private readonly bool includeTimestamp;
private readonly bool logToConsoleError;
private readonly LogLevel globalThreshold;
private readonly bool throwExceptions;
public InternalLoggerScope()
{
this.logFile = InternalLogger.LogFile;
this.logLevel = InternalLogger.LogLevel;
this.logToConsole = InternalLogger.LogToConsole;
this.includeTimestamp = InternalLogger.IncludeTimestamp;
this.logToConsoleError = InternalLogger.LogToConsoleError;
this.globalThreshold = LogManager.GlobalThreshold;
this.throwExceptions = LogManager.ThrowExceptions;
}
public void Dispose()
{
InternalLogger.LogFile = this.logFile;
InternalLogger.LogLevel = this.logLevel;
InternalLogger.LogToConsole = this.logToConsole;
InternalLogger.IncludeTimestamp = this.includeTimestamp;
InternalLogger.LogToConsoleError = this.logToConsoleError;
LogManager.GlobalThreshold = this.globalThreshold;
LogManager.ThrowExceptions = this.throwExceptions;
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.IO;
using System.IO.Compression;
using System.Net;
using System.Net.Http;
using System.Runtime.InteropServices;
using System.Security.Authentication;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace System.Net.Http.WinHttpHandlerUnitTests
{
public class WinHttpHandlerTest : IDisposable
{
private const string FakeProxy = "http://proxy.contoso.com";
public WinHttpHandlerTest()
{
TestControl.ResetAll();
}
public void Dispose()
{
TestControl.ResponseDelayCompletedEvent.WaitOne();
}
[Fact]
public void AutomaticRedirection_CtorAndGet_DefaultValueIsTrue()
{
var handler = new WinHttpHandler();
Assert.True(handler.AutomaticRedirection);
}
[Fact]
public void AutomaticRedirection_SetFalseAndGet_ValueIsFalse()
{
var handler = new WinHttpHandler();
handler.AutomaticRedirection = false;
Assert.False(handler.AutomaticRedirection);
}
[Fact]
public void AutomaticRedirection_SetTrue_ExpectedWinHttpHandleSettings()
{
var handler = new WinHttpHandler();
SendRequestHelper.Send(
handler,
delegate { handler.AutomaticRedirection = true; });
Assert.Equal(
Interop.WinHttp.WINHTTP_OPTION_REDIRECT_POLICY_DISALLOW_HTTPS_TO_HTTP,
APICallHistory.WinHttpOptionRedirectPolicy);
}
[Fact]
public void AutomaticRedirection_SetFalse_ExpectedWinHttpHandleSettings()
{
var handler = new WinHttpHandler();
SendRequestHelper.Send(
handler,
delegate { handler.AutomaticRedirection = false; });
Assert.Equal(
Interop.WinHttp.WINHTTP_OPTION_REDIRECT_POLICY_NEVER,
APICallHistory.WinHttpOptionRedirectPolicy);
}
[Fact]
public void CheckCertificateRevocationList_SetTrue_ExpectedWinHttpHandleSettings()
{
var handler = new WinHttpHandler();
SendRequestHelper.Send(handler, delegate { handler.CheckCertificateRevocationList = true; });
Assert.True(APICallHistory.WinHttpOptionEnableSslRevocation.Value);
}
[Fact]
public void CheckCertificateRevocationList_SetFalse_ExpectedWinHttpHandleSettings()
{
var handler = new WinHttpHandler();
SendRequestHelper.Send(handler, delegate { handler.CheckCertificateRevocationList = false; });
Assert.Equal(false, APICallHistory.WinHttpOptionEnableSslRevocation.HasValue);
}
[Fact]
public void ConnectTimeout_SetNegativeValue_ThrowsArgumentOutOfRangeException()
{
var handler = new WinHttpHandler();
Assert.Throws<ArgumentOutOfRangeException>(() => { handler.ConnectTimeout = TimeSpan.FromMinutes(-10); });
}
[Fact]
public void ConnectTimeout_SetTooLargeValue_ThrowsArgumentOutOfRangeException()
{
var handler = new WinHttpHandler();
Assert.Throws<ArgumentOutOfRangeException>(
() => { handler.ConnectTimeout = TimeSpan.FromMilliseconds(int.MaxValue + 1.0); });
}
[Fact]
public void ConnectTimeout_SetZeroValue_ThrowsArgumentOutOfRangeException()
{
var handler = new WinHttpHandler();
Assert.Throws<ArgumentOutOfRangeException>(() => { handler.ConnectTimeout = TimeSpan.FromSeconds(0); });
}
[Fact]
public void ConnectTimeout_SetInfiniteValue_NoExceptionThrown()
{
var handler = new WinHttpHandler();
handler.ConnectTimeout = Timeout.InfiniteTimeSpan;
}
[Fact]
public void CookieContainer_WhenCreated_ReturnsNull()
{
var handler = new WinHttpHandler();
Assert.Null(handler.CookieContainer);
}
[Fact]
public async Task CookieUsePolicy_UseSpecifiedCookieContainerAndNullContainer_ThrowsInvalidOperationException()
{
var handler = new WinHttpHandler();
Assert.Null(handler.CookieContainer);
handler.CookieUsePolicy = CookieUsePolicy.UseSpecifiedCookieContainer;
var client = new HttpClient(handler);
TestServer.SetResponse(DecompressionMethods.None, TestServer.ExpectedResponseBody);
var request = new HttpRequestMessage(HttpMethod.Post, TestServer.FakeServerEndpoint);
await Assert.ThrowsAsync<InvalidOperationException>(() => client.SendAsync(request));
}
[Fact]
public void CookieUsePolicy_SetUsingInvalidEnum_ThrowsArgumentOutOfRangeException()
{
var handler = new WinHttpHandler();
Assert.Throws<ArgumentOutOfRangeException>(() => { handler.CookieUsePolicy = (CookieUsePolicy)100; });
}
[Fact]
public void CookieUsePolicy_WhenCreated_ReturnsUseInternalCookieStoreOnly()
{
var handler = new WinHttpHandler();
Assert.Equal(CookieUsePolicy.UseInternalCookieStoreOnly, handler.CookieUsePolicy);
}
[Fact]
public void CookieUsePolicy_SetIgnoreCookies_NoExceptionThrown()
{
var handler = new WinHttpHandler();
handler.CookieUsePolicy = CookieUsePolicy.IgnoreCookies;
}
[Fact]
public void CookieUsePolicy_SetUseInternalCookieStoreOnly_NoExceptionThrown()
{
var handler = new WinHttpHandler();
handler.CookieUsePolicy = CookieUsePolicy.UseInternalCookieStoreOnly;
}
[Fact]
public void CookieUsePolicy_SetUseSpecifiedCookieContainer_NoExceptionThrown()
{
var handler = new WinHttpHandler();
handler.CookieUsePolicy = CookieUsePolicy.UseSpecifiedCookieContainer;
}
[Fact]
public void CookieUsePolicy_SetIgnoreCookies_ExpectedWinHttpHandleSettings()
{
var handler = new WinHttpHandler();
SendRequestHelper.Send(handler, delegate { handler.CookieUsePolicy = CookieUsePolicy.IgnoreCookies; });
Assert.True(APICallHistory.WinHttpOptionDisableCookies.Value);
}
[Fact]
public void CookieUsePolicy_SetUseInternalCookieStoreOnly_ExpectedWinHttpHandleSettings()
{
var handler = new WinHttpHandler();
SendRequestHelper.Send(
handler,
delegate { handler.CookieUsePolicy = CookieUsePolicy.UseInternalCookieStoreOnly; });
Assert.Equal(false, APICallHistory.WinHttpOptionDisableCookies.HasValue);
}
[Fact]
[ActiveIssue(2165, PlatformID.AnyUnix)]
public void CookieUsePolicy_SetUseSpecifiedCookieContainerAndContainer_ExpectedWinHttpHandleSettings()
{
var handler = new WinHttpHandler();
SendRequestHelper.Send(
handler,
delegate {
handler.CookieUsePolicy = CookieUsePolicy.UseSpecifiedCookieContainer;
handler.CookieContainer = new CookieContainer();
});
Assert.Equal(true, APICallHistory.WinHttpOptionDisableCookies.HasValue);
}
[Fact]
public void WindowsProxyUsePolicy_SetUsingInvalidEnum_ThrowArgumentOutOfRangeException()
{
var handler = new WinHttpHandler();
Assert.Throws<ArgumentOutOfRangeException>(
() => { handler.WindowsProxyUsePolicy = (WindowsProxyUsePolicy)100; });
}
[Fact]
public void WindowsProxyUsePolicy_SetDoNotUseProxy_NoExceptionThrown()
{
var handler = new WinHttpHandler();
handler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.DoNotUseProxy;
}
[Fact]
public void WindowsProxyUsePolicy_SetUseWinHttpProxy_NoExceptionThrown()
{
var handler = new WinHttpHandler();
handler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseWinHttpProxy;
}
[Fact]
public void WindowsProxyUsePolicy_SetUseWinWinInetProxy_NoExceptionThrown()
{
var handler = new WinHttpHandler();
handler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseWinInetProxy;
}
[Fact]
public void WindowsProxyUsePolicy_SetUseCustomProxy_NoExceptionThrown()
{
var handler = new WinHttpHandler();
handler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseCustomProxy;
}
[Fact]
public async Task WindowsProxyUsePolicy_UseNonNullProxyAndIncorrectWindowsProxyUsePolicy_ThrowsInvalidOperationException()
{
var handler = new WinHttpHandler();
handler.Proxy = new CustomProxy(false);
handler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.DoNotUseProxy;
var client = new HttpClient(handler);
TestServer.SetResponse(DecompressionMethods.None, TestServer.ExpectedResponseBody);
var request = new HttpRequestMessage(HttpMethod.Post, TestServer.FakeServerEndpoint);
await Assert.ThrowsAsync<InvalidOperationException>(() => client.SendAsync(request));
}
[Fact]
public async Task WindowsProxyUsePolicy_UseCustomProxyAndNullProxy_ThrowsInvalidOperationException()
{
var handler = new WinHttpHandler();
handler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseCustomProxy;
handler.Proxy = null;
var client = new HttpClient(handler);
TestServer.SetResponse(DecompressionMethods.None, TestServer.ExpectedResponseBody);
var request = new HttpRequestMessage(HttpMethod.Post, TestServer.FakeServerEndpoint);
await Assert.ThrowsAsync<InvalidOperationException>(() => client.SendAsync(request));
}
[Fact]
public void MaxAutomaticRedirections_SetZero_ThrowsArgumentOutOfRangeException()
{
var handler = new WinHttpHandler();
Assert.Throws<ArgumentOutOfRangeException>(() => { handler.MaxAutomaticRedirections = 0; });
}
[Fact]
public void MaxAutomaticRedirections_SetNegativeValue_ThrowsArgumentOutOfRangeException()
{
var handler = new WinHttpHandler();
Assert.Throws<ArgumentOutOfRangeException>(() => { handler.MaxAutomaticRedirections = -1; });
}
[Fact]
public void MaxAutomaticRedirections_SetValidValue_ExpectedWinHttpHandleSettings()
{
var handler = new WinHttpHandler();
int redirections = 35;
SendRequestHelper.Send(handler, delegate { handler.MaxAutomaticRedirections = redirections; });
Assert.Equal((uint)redirections, APICallHistory.WinHttpOptionMaxHttpAutomaticRedirects);
}
[Fact]
public void MaxConnectionsPerServer_SetZero_ThrowsArgumentOutOfRangeException()
{
var handler = new WinHttpHandler();
Assert.Throws<ArgumentOutOfRangeException>(() => { handler.MaxConnectionsPerServer = 0; });
}
[Fact]
public void MaxConnectionsPerServer_SetNegativeValue_ThrowsArgumentOutOfRangeException()
{
var handler = new WinHttpHandler();
Assert.Throws<ArgumentOutOfRangeException>(() => { handler.MaxConnectionsPerServer = -1; });
}
[Fact]
public void MaxConnectionsPerServer_SetPositiveValue_Success()
{
var handler = new WinHttpHandler();
handler.MaxConnectionsPerServer = 1;
}
[Fact]
public void ReceiveDataTimeout_SetNegativeValue_ThrowsArgumentOutOfRangeException()
{
var handler = new WinHttpHandler();
Assert.Throws<ArgumentOutOfRangeException>(
() => { handler.ReceiveDataTimeout = TimeSpan.FromMinutes(-10); });
}
[Fact]
public void ReceiveDataTimeout_SetTooLargeValue_ThrowsArgumentOutOfRangeException()
{
var handler = new WinHttpHandler();
Assert.Throws<ArgumentOutOfRangeException>(
() => { handler.ReceiveDataTimeout = TimeSpan.FromMilliseconds(int.MaxValue + 1.0); });
}
[Fact]
public void ReceiveDataTimeout_SetZeroValue_ThrowsArgumentOutOfRangeException()
{
var handler = new WinHttpHandler();
Assert.Throws<ArgumentOutOfRangeException>(() => { handler.ReceiveDataTimeout = TimeSpan.FromSeconds(0); });
}
[Fact]
public void ReceiveDataTimeout_SetInfiniteValue_NoExceptionThrown()
{
var handler = new WinHttpHandler();
handler.ReceiveDataTimeout = Timeout.InfiniteTimeSpan;
}
[Fact]
public void ReceiveHeadersTimeout_SetNegativeValue_ThrowsArgumentOutOfRangeException()
{
var handler = new WinHttpHandler();
Assert.Throws<ArgumentOutOfRangeException>(
() => { handler.ReceiveHeadersTimeout = TimeSpan.FromMinutes(-10); });
}
[Fact]
public void ReceiveHeadersTimeout_SetTooLargeValue_ThrowsArgumentOutOfRangeException()
{
var handler = new WinHttpHandler();
Assert.Throws<ArgumentOutOfRangeException>(
() => { handler.ReceiveHeadersTimeout = TimeSpan.FromMilliseconds(int.MaxValue + 1.0); });
}
[Fact]
public void ReceiveHeadersTimeout_SetZeroValue_ThrowsArgumentOutOfRangeException()
{
var handler = new WinHttpHandler();
Assert.Throws<ArgumentOutOfRangeException>(
() => { handler.ReceiveHeadersTimeout = TimeSpan.FromSeconds(0); });
}
[Fact]
public void ReceiveHeadersTimeout_SetInfiniteValue_NoExceptionThrown()
{
var handler = new WinHttpHandler();
handler.ConnectTimeout = Timeout.InfiniteTimeSpan;
}
[Fact]
public void SslProtocols_SetUsingSsl2_ThrowsArgumentOutOfRangeException()
{
var handler = new WinHttpHandler();
Assert.Throws<ArgumentOutOfRangeException>(() => { handler.SslProtocols = SslProtocols.Ssl2; });
}
[Fact]
public void SslProtocols_SetUsingSsl3_ThrowsArgumentOutOfRangeException()
{
var handler = new WinHttpHandler();
Assert.Throws<ArgumentOutOfRangeException>(() => { handler.SslProtocols = SslProtocols.Ssl3; });
}
[Fact]
public void SslProtocols_SetUsingNone_ThrowsArgumentOutOfRangeException()
{
var handler = new WinHttpHandler();
Assert.Throws<ArgumentOutOfRangeException>(() => { handler.SslProtocols = SslProtocols.None; });
}
[Fact]
public void SslProtocols_SetUsingInvalidEnum_ThrowsArgumentOutOfRangeException()
{
var handler = new WinHttpHandler();
Assert.Throws<ArgumentOutOfRangeException>(() => { handler.SslProtocols = (SslProtocols)4096; });
}
[Fact]
public void SslProtocols_SetUsingValidEnums_ExpectedWinHttpHandleSettings()
{
var handler = new WinHttpHandler();
SendRequestHelper.Send(
handler,
delegate
{
handler.SslProtocols =
SslProtocols.Tls |
SslProtocols.Tls11 |
SslProtocols.Tls12;
});
uint expectedProtocols =
Interop.WinHttp.WINHTTP_FLAG_SECURE_PROTOCOL_TLS1 |
Interop.WinHttp.WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_1 |
Interop.WinHttp.WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_2;
Assert.Equal(expectedProtocols, APICallHistory.WinHttpOptionSecureProtocols);
}
[Fact]
public async Task GetAsync_MultipleRequestsReusingSameClient_Success()
{
var handler = new WinHttpHandler();
var client = new HttpClient(handler);
TestServer.SetResponse(DecompressionMethods.None, TestServer.ExpectedResponseBody);
HttpResponseMessage response = await client.GetAsync(TestServer.FakeServerEndpoint);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
response = await client.GetAsync(TestServer.FakeServerEndpoint);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
response = await client.GetAsync(TestServer.FakeServerEndpoint);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
client.Dispose();
}
[Fact]
public async Task SendAsync_PostContentWithContentLengthAndChunkedEncodingHeaders_Success()
{
var handler = new WinHttpHandler();
var client = new HttpClient(handler);
client.DefaultRequestHeaders.TransferEncodingChunked = true;
TestServer.SetResponse(DecompressionMethods.None, TestServer.ExpectedResponseBody);
var content = new StringContent(TestServer.ExpectedResponseBody);
Assert.True(content.Headers.ContentLength.HasValue);
var request = new HttpRequestMessage(HttpMethod.Post, TestServer.FakeServerEndpoint);
request.Content = content;
HttpResponseMessage response = await client.SendAsync(request);
}
[Fact]
public async Task SendAsync_PostNoContentObjectWithChunkedEncodingHeader_ExpectInvalidOperationException()
{
var handler = new WinHttpHandler();
var client = new HttpClient(handler);
client.DefaultRequestHeaders.TransferEncodingChunked = true;
TestServer.SetResponse(DecompressionMethods.None, TestServer.ExpectedResponseBody);
var request = new HttpRequestMessage(HttpMethod.Post, TestServer.FakeServerEndpoint);
await Assert.ThrowsAsync<InvalidOperationException>(() => client.SendAsync(request));
}
// TODO: Need to skip this test due to missing native dependency clrcompression.dll.
// https://github.com/dotnet/corefx/issues/1298
[Fact]
[ActiveIssue(1298)]
public async Task SendAsync_NoWinHttpDecompressionSupportAndResponseBodyIsDeflateCompressed_ExpectedResponse()
{
TestControl.WinHttpDecompressionSupport = false;
var handler = new WinHttpHandler();
HttpResponseMessage response = SendRequestHelper.Send(
handler,
delegate
{
handler.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
TestServer.SetResponse(DecompressionMethods.Deflate, TestServer.ExpectedResponseBody);
});
Assert.Null(response.Content.Headers.ContentLength);
string responseBody = await response.Content.ReadAsStringAsync();
Assert.Equal(0, response.Content.Headers.ContentEncoding.Count);
Assert.Equal(TestServer.ExpectedResponseBody, responseBody);
}
// TODO: Need to skip this test due to missing native dependency clrcompression.dll.
// https://github.com/dotnet/corefx/issues/1298
[Fact]
[ActiveIssue(1298)]
public async Task SendAsync_NoWinHttpDecompressionSupportAndResponseBodyIsGZipCompressed_ExpectedResponse()
{
TestControl.WinHttpDecompressionSupport = false;
var handler = new WinHttpHandler();
HttpResponseMessage response = SendRequestHelper.Send(
handler,
delegate
{
handler.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
TestServer.SetResponse(DecompressionMethods.GZip, TestServer.ExpectedResponseBody);
});
Assert.Null(response.Content.Headers.ContentLength);
string responseBody = await response.Content.ReadAsStringAsync();
Assert.Equal(0, response.Content.Headers.ContentEncoding.Count);
Assert.Equal(TestServer.ExpectedResponseBody, responseBody);
}
[Fact]
public async Task SendAsync_NoWinHttpDecompressionSupportAndResponseBodyIsNotCompressed_ExpectedResponse()
{
TestControl.WinHttpDecompressionSupport = false;
var handler = new WinHttpHandler();
HttpResponseMessage response = SendRequestHelper.Send(
handler,
delegate
{
handler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseWinInetProxy;
});
Assert.NotNull(response.Content.Headers.ContentLength);
string responseBody = await response.Content.ReadAsStringAsync();
Assert.Equal(TestServer.ExpectedResponseBody, responseBody);
}
[Fact]
public void SendAsync_AutomaticProxySupportAndUseWinInetSettings_ExpectedWinHttpSessionProxySettings()
{
TestControl.WinHttpAutomaticProxySupport = true;
var handler = new WinHttpHandler();
SendRequestHelper.Send(
handler,
delegate
{
handler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseWinInetProxy;
});
Assert.Equal(Interop.WinHttp.WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY, APICallHistory.SessionProxySettings.AccessType);
}
[Fact]
public void SendAsync_NoAutomaticProxySupportAndUseWinInetSettingsWithAutoDetectSetting_ExpectedWinHttpProxySettings()
{
TestControl.WinHttpAutomaticProxySupport = false;
FakeRegistry.WinInetProxySettings.AutoDetect = true;
var handler = new WinHttpHandler();
SendRequestHelper.Send(
handler,
delegate
{
handler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseWinInetProxy;
});
Assert.Equal(Interop.WinHttp.WINHTTP_ACCESS_TYPE_NO_PROXY, APICallHistory.SessionProxySettings.AccessType);
Assert.Equal(Interop.WinHttp.WINHTTP_ACCESS_TYPE_NAMED_PROXY, APICallHistory.RequestProxySettings.AccessType);
}
[Fact]
public void SendAsync_NoAutomaticProxySupportAndUseWinInetSettingsWithEmptySettings_ExpectedWinHttpProxySettings()
{
TestControl.WinHttpAutomaticProxySupport = false;
var handler = new WinHttpHandler();
SendRequestHelper.Send(
handler,
delegate
{
handler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseWinInetProxy;
});
Assert.Equal(Interop.WinHttp.WINHTTP_ACCESS_TYPE_NO_PROXY, APICallHistory.SessionProxySettings.AccessType);
Assert.Equal(false, APICallHistory.RequestProxySettings.AccessType.HasValue);
}
[Fact]
public void SendAsync_NoAutomaticProxySupportAndUseWinInetSettingsWithManualSettingsOnly_ExpectedWinHttpProxySettings()
{
TestControl.WinHttpAutomaticProxySupport = false;
FakeRegistry.WinInetProxySettings.Proxy = FakeProxy;
var handler = new WinHttpHandler();
SendRequestHelper.Send(
handler,
delegate
{
handler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseWinInetProxy;
});
Assert.Equal(Interop.WinHttp.WINHTTP_ACCESS_TYPE_NAMED_PROXY, APICallHistory.SessionProxySettings.AccessType);
Assert.Equal(false, APICallHistory.RequestProxySettings.AccessType.HasValue);
}
[Fact]
public void SendAsync_NoAutomaticProxySupportAndUseWinInetSettingsWithMissingRegistrySettings_ExpectedWinHttpProxySettings()
{
TestControl.WinHttpAutomaticProxySupport = false;
FakeRegistry.WinInetProxySettings.RegistryKeyMissing = true;
var handler = new WinHttpHandler();
SendRequestHelper.Send(
handler,
delegate
{
handler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseWinInetProxy;
});
Assert.Equal(Interop.WinHttp.WINHTTP_ACCESS_TYPE_NO_PROXY, APICallHistory.SessionProxySettings.AccessType);
Assert.Equal(false, APICallHistory.RequestProxySettings.AccessType.HasValue);
}
[Fact]
public void SendAsync_NoAutomaticProxySupportAndUseWinInetSettingsWithAutoDetectButPACFileNotDetectedOnNetwork_ExpectedWinHttpProxySettings()
{
TestControl.WinHttpAutomaticProxySupport = false;
TestControl.PACFileNotDetectedOnNetwork = true;
FakeRegistry.WinInetProxySettings.AutoDetect = true;
var handler = new WinHttpHandler();
SendRequestHelper.Send(
handler,
delegate
{
handler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseWinInetProxy;
});
Assert.Equal(Interop.WinHttp.WINHTTP_ACCESS_TYPE_NO_PROXY, APICallHistory.SessionProxySettings.AccessType);
Assert.Equal(Interop.WinHttp.WINHTTP_ACCESS_TYPE_NO_PROXY, APICallHistory.RequestProxySettings.AccessType);
}
[Fact]
public void SendAsync_NoAutomaticProxySupportAndUseWinInetSettingsWithAutoDetectSettingAndManualSettingButPACFileNotFoundOnNetwork_ExpectedWinHttpProxySettings()
{
const string manualProxy = FakeProxy;
TestControl.WinHttpAutomaticProxySupport = false;
FakeRegistry.WinInetProxySettings.AutoDetect = true;
FakeRegistry.WinInetProxySettings.Proxy = manualProxy;
TestControl.PACFileNotDetectedOnNetwork = true;
var handler = new WinHttpHandler();
SendRequestHelper.Send(
handler,
delegate
{
handler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseWinInetProxy;
});
// Both AutoDetect and manual proxy are specified. If AutoDetect fails to find
// the PAC file on the network, then we should fall back to manual setting.
Assert.Equal(Interop.WinHttp.WINHTTP_ACCESS_TYPE_NO_PROXY, APICallHistory.SessionProxySettings.AccessType);
Assert.Equal(Interop.WinHttp.WINHTTP_ACCESS_TYPE_NAMED_PROXY, APICallHistory.RequestProxySettings.AccessType);
Assert.Equal(manualProxy, APICallHistory.RequestProxySettings.Proxy);
}
[Fact]
public void SendAsync_UseNoProxy_ExpectedWinHttpProxySettings()
{
var handler = new WinHttpHandler();
SendRequestHelper.Send(handler, delegate { handler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.DoNotUseProxy; });
Assert.Equal(Interop.WinHttp.WINHTTP_ACCESS_TYPE_NO_PROXY, APICallHistory.SessionProxySettings.AccessType);
}
[Fact]
public void SendAsync_UseCustomProxyWithNoBypass_ExpectedWinHttpProxySettings()
{
var handler = new WinHttpHandler();
var customProxy = new CustomProxy(false);
SendRequestHelper.Send(
handler,
delegate
{
handler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseCustomProxy;
handler.Proxy = customProxy;
});
Assert.Equal(Interop.WinHttp.WINHTTP_ACCESS_TYPE_NO_PROXY, APICallHistory.SessionProxySettings.AccessType);
Assert.Equal(Interop.WinHttp.WINHTTP_ACCESS_TYPE_NAMED_PROXY, APICallHistory.RequestProxySettings.AccessType);
Assert.Equal(FakeProxy, APICallHistory.RequestProxySettings.Proxy);
}
[Fact]
public void SendAsync_UseCustomProxyWithBypass_ExpectedWinHttpProxySettings()
{
var handler = new WinHttpHandler();
var customProxy = new CustomProxy(true);
SendRequestHelper.Send(
handler,
delegate
{
handler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseCustomProxy;
handler.Proxy = customProxy;
});
Assert.Equal(Interop.WinHttp.WINHTTP_ACCESS_TYPE_NO_PROXY, APICallHistory.SessionProxySettings.AccessType);
Assert.Equal(Interop.WinHttp.WINHTTP_ACCESS_TYPE_NO_PROXY, APICallHistory.RequestProxySettings.AccessType);
}
[Fact]
public void SendAsync_AutomaticProxySupportAndUseDefaultWebProxy_ExpectedWinHttpSessionProxySettings()
{
TestControl.WinHttpAutomaticProxySupport = true;
var handler = new WinHttpHandler();
SendRequestHelper.Send(
handler,
delegate
{
handler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseCustomProxy;
handler.Proxy = new FakeDefaultWebProxy();
});
Assert.Equal(Interop.WinHttp.WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY, APICallHistory.SessionProxySettings.AccessType);
}
[Fact]
public async Task SendAsync_SlowPostRequestWithTimedCancellation_ExpectTaskCanceledException()
{
var handler = new WinHttpHandler();
TestControl.ResponseDelayTime = 500;
CancellationTokenSource cts = new CancellationTokenSource(100);
var client = new HttpClient(handler);
var request = new HttpRequestMessage(HttpMethod.Post, TestServer.FakeServerEndpoint);
var content = new StringContent(new String('a', 1000));
request.Content = content;
await Assert.ThrowsAsync<TaskCanceledException>(() =>
client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cts.Token));
}
[Fact]
public async Task SendAsync_SlowGetRequestWithTimedCancellation_ExpectTaskCanceledException()
{
var handler = new WinHttpHandler();
TestControl.ResponseDelayTime = 500;
CancellationTokenSource cts = new CancellationTokenSource(100);
var client = new HttpClient(handler);
var request = new HttpRequestMessage(HttpMethod.Get, TestServer.FakeServerEndpoint);
await Assert.ThrowsAsync<TaskCanceledException>(() =>
client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cts.Token));
}
[Fact]
public async Task SendAsync_RequestWithCanceledToken_ExpectTaskCanceledException()
{
var handler = new WinHttpHandler();
CancellationTokenSource cts = new CancellationTokenSource();
cts.Cancel();
var client = new HttpClient(handler);
var request = new HttpRequestMessage(HttpMethod.Get, TestServer.FakeServerEndpoint);
await Assert.ThrowsAsync<TaskCanceledException>(() =>
client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cts.Token));
}
[Fact]
public async Task SendAsync_WinHttpOpenReturnsError_ExpectHttpRequestException()
{
var handler = new WinHttpHandler();
var client = new HttpClient(handler);
var request = new HttpRequestMessage(HttpMethod.Get, TestServer.FakeServerEndpoint);
TestControl.Fail.WinHttpOpen = true;
Exception ex = await Assert.ThrowsAsync<HttpRequestException>(() => client.SendAsync(request));
Assert.Equal(typeof(WinHttpException), ex.InnerException.GetType());
}
[Fact]
public void SendAsync_MultipleCallsWithDispose_NoHandleLeaksManuallyVerifiedUsingLogging()
{
WinHttpHandler handler;
HttpResponseMessage response;
for (int i = 0; i < 50; i++)
{
handler = new WinHttpHandler();
response = SendRequestHelper.Send(handler, () => { });
response.Dispose();
handler.Dispose();
}
}
[Fact]
public void SendAsync_MultipleCallsWithoutDispose_NoHandleLeaksManuallyVerifiedUsingLogging()
{
WinHttpHandler handler;
HttpResponseMessage response;
for (int i = 0; i < 50; i++)
{
handler = new WinHttpHandler();
response = SendRequestHelper.Send(handler, () => { });
}
}
public class CustomProxy : IWebProxy
{
private const string DefaultDomain = "domain";
private const string DefaultUsername = "username";
private const string DefaultPassword = "password";
private bool bypassAll;
private NetworkCredential networkCredential;
public CustomProxy(bool bypassAll)
{
this.bypassAll = bypassAll;
this.networkCredential = new NetworkCredential(CustomProxy.DefaultUsername, CustomProxy.DefaultPassword, CustomProxy.DefaultDomain);
}
public string UsernameWithDomain
{
get
{
return CustomProxy.DefaultDomain + "\\" + CustomProxy.DefaultUsername;
}
}
public string Password
{
get
{
return CustomProxy.DefaultPassword;
}
}
public NetworkCredential NetworkCredential
{
get
{
return this.networkCredential;
}
}
ICredentials IWebProxy.Credentials
{
get
{
return this.networkCredential;
}
set
{
}
}
Uri IWebProxy.GetProxy(Uri destination)
{
return new Uri(FakeProxy);
}
bool IWebProxy.IsBypassed(Uri host)
{
return this.bypassAll;
}
}
public class FakeDefaultWebProxy : IWebProxy
{
private ICredentials _credentials = null;
public FakeDefaultWebProxy()
{
}
public ICredentials Credentials
{
get
{
return _credentials;
}
set
{
_credentials = value;
}
}
// This is a sentinel object representing the internal default system proxy that a developer would
// use when accessing the System.Net.WebRequest.DefaultWebProxy property (from the System.Net.Requests
// package). It can't support the GetProxy or IsBypassed methods. WinHttpHandler will handle this
// exception and use the appropriate system default proxy.
public Uri GetProxy(Uri destination)
{
throw new PlatformNotSupportedException();
}
public bool IsBypassed(Uri host)
{
throw new PlatformNotSupportedException();
}
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using OpenMetaverse;
using System;
using System.Collections;
using System.Globalization;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using System.Xml;
namespace OpenSim.Framework.Capabilities
{
/// <summary>
/// Borrowed from (a older version of) libsl for now, as their new llsd code doesn't work we our decoding code.
/// </summary>
public static class LLSD
{
/// <summary>
///
/// </summary>
public class LLSDParseException : Exception
{
public LLSDParseException(string message) : base(message)
{
}
}
/// <summary>
///
/// </summary>
public class LLSDSerializeException : Exception
{
public LLSDSerializeException(string message) : base(message)
{
}
}
/// <summary>
///
/// </summary>
/// <param name="b"></param>
/// <returns></returns>
public static object LLSDDeserialize(byte[] b)
{
using (MemoryStream ms = new MemoryStream(b, false))
{
return LLSDDeserialize(ms);
}
}
/// <summary>
///
/// </summary>
/// <param name="st"></param>
/// <returns></returns>
public static object LLSDDeserialize(Stream st)
{
using (XmlTextReader reader = new XmlTextReader(st))
{
reader.Read();
SkipWS(reader);
if (reader.NodeType != XmlNodeType.Element || reader.LocalName != "llsd")
throw new LLSDParseException("Expected <llsd>");
reader.Read();
object ret = LLSDParseOne(reader);
SkipWS(reader);
if (reader.NodeType != XmlNodeType.EndElement || reader.LocalName != "llsd")
throw new LLSDParseException("Expected </llsd>");
return ret;
}
}
/// <summary>
///
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public static byte[] LLSDSerialize(object obj)
{
StringWriter sw = new StringWriter();
XmlTextWriter writer = new XmlTextWriter(sw);
writer.Formatting = Formatting.None;
writer.WriteStartElement(String.Empty, "llsd", String.Empty);
LLSDWriteOne(writer, obj);
writer.WriteEndElement();
writer.Close();
return Util.UTF8.GetBytes(sw.ToString());
}
/// <summary>
///
/// </summary>
/// <param name="writer"></param>
/// <param name="obj"></param>
public static void LLSDWriteOne(XmlTextWriter writer, object obj)
{
if (obj == null)
{
writer.WriteStartElement(String.Empty, "undef", String.Empty);
writer.WriteEndElement();
return;
}
if (obj is string)
{
writer.WriteStartElement(String.Empty, "string", String.Empty);
writer.WriteString((string) obj);
writer.WriteEndElement();
}
else if (obj is int)
{
writer.WriteStartElement(String.Empty, "integer", String.Empty);
writer.WriteString(obj.ToString());
writer.WriteEndElement();
}
else if (obj is double)
{
writer.WriteStartElement(String.Empty, "real", String.Empty);
writer.WriteString(obj.ToString());
writer.WriteEndElement();
}
else if (obj is bool)
{
bool b = (bool) obj;
writer.WriteStartElement(String.Empty, "boolean", String.Empty);
writer.WriteString(b ? "1" : "0");
writer.WriteEndElement();
}
else if (obj is ulong)
{
throw new Exception("ulong in LLSD is currently not implemented, fix me!");
}
else if (obj is UUID)
{
UUID u = (UUID) obj;
writer.WriteStartElement(String.Empty, "uuid", String.Empty);
writer.WriteString(u.ToString());
writer.WriteEndElement();
}
else if (obj is Hashtable)
{
Hashtable h = obj as Hashtable;
writer.WriteStartElement(String.Empty, "map", String.Empty);
foreach (string key in h.Keys)
{
writer.WriteStartElement(String.Empty, "key", String.Empty);
writer.WriteString(key);
writer.WriteEndElement();
LLSDWriteOne(writer, h[key]);
}
writer.WriteEndElement();
}
else if (obj is ArrayList)
{
ArrayList a = obj as ArrayList;
writer.WriteStartElement(String.Empty, "array", String.Empty);
foreach (object item in a)
{
LLSDWriteOne(writer, item);
}
writer.WriteEndElement();
}
else if (obj is byte[])
{
byte[] b = obj as byte[];
writer.WriteStartElement(String.Empty, "binary", String.Empty);
writer.WriteStartAttribute(String.Empty, "encoding", String.Empty);
writer.WriteString("base64");
writer.WriteEndAttribute();
//// Calculate the length of the base64 output
//long length = (long)(4.0d * b.Length / 3.0d);
//if (length % 4 != 0) length += 4 - (length % 4);
//// Create the char[] for base64 output and fill it
//char[] tmp = new char[length];
//int i = Convert.ToBase64CharArray(b, 0, b.Length, tmp, 0);
//writer.WriteString(new String(tmp));
writer.WriteString(Convert.ToBase64String(b));
writer.WriteEndElement();
}
else
{
throw new LLSDSerializeException("Unknown type " + obj.GetType().Name);
}
}
/// <summary>
///
/// </summary>
/// <param name="reader"></param>
/// <returns></returns>
public static object LLSDParseOne(XmlTextReader reader)
{
SkipWS(reader);
if (reader.NodeType != XmlNodeType.Element)
throw new LLSDParseException("Expected an element");
string dtype = reader.LocalName;
object ret = null;
switch (dtype)
{
case "undef":
{
if (reader.IsEmptyElement)
{
reader.Read();
return null;
}
reader.Read();
SkipWS(reader);
ret = null;
break;
}
case "boolean":
{
if (reader.IsEmptyElement)
{
reader.Read();
return false;
}
reader.Read();
string s = reader.ReadString().Trim();
if (s == String.Empty || s == "false" || s == "0")
ret = false;
else if (s == "true" || s == "1")
ret = true;
else
throw new LLSDParseException("Bad boolean value " + s);
break;
}
case "integer":
{
if (reader.IsEmptyElement)
{
reader.Read();
return 0;
}
reader.Read();
ret = Convert.ToInt32(reader.ReadString().Trim());
break;
}
case "real":
{
if (reader.IsEmptyElement)
{
reader.Read();
return 0.0f;
}
reader.Read();
ret = Convert.ToDouble(reader.ReadString().Trim());
break;
}
case "uuid":
{
if (reader.IsEmptyElement)
{
reader.Read();
return UUID.Zero;
}
reader.Read();
ret = new UUID(reader.ReadString().Trim());
break;
}
case "string":
{
if (reader.IsEmptyElement)
{
reader.Read();
return String.Empty;
}
reader.Read();
ret = reader.ReadString();
break;
}
case "binary":
{
if (reader.IsEmptyElement)
{
reader.Read();
return new byte[0];
}
if (reader.GetAttribute("encoding") != null &&
reader.GetAttribute("encoding") != "base64")
{
throw new LLSDParseException("Unknown encoding: " + reader.GetAttribute("encoding"));
}
reader.Read();
FromBase64Transform b64 = new FromBase64Transform(FromBase64TransformMode.IgnoreWhiteSpaces);
byte[] inp = Util.UTF8.GetBytes(reader.ReadString());
ret = b64.TransformFinalBlock(inp, 0, inp.Length);
break;
}
case "date":
{
reader.Read();
throw new Exception("LLSD TODO: date");
}
case "map":
{
return LLSDParseMap(reader);
}
case "array":
{
return LLSDParseArray(reader);
}
default:
throw new LLSDParseException("Unknown element <" + dtype + ">");
}
if (reader.NodeType != XmlNodeType.EndElement || reader.LocalName != dtype)
{
throw new LLSDParseException("Expected </" + dtype + ">");
}
reader.Read();
return ret;
}
/// <summary>
///
/// </summary>
/// <param name="reader"></param>
/// <returns></returns>
public static Hashtable LLSDParseMap(XmlTextReader reader)
{
Hashtable ret = new Hashtable();
if (reader.NodeType != XmlNodeType.Element || reader.LocalName != "map")
throw new LLSDParseException("Expected <map>");
if (reader.IsEmptyElement)
{
reader.Read();
return ret;
}
reader.Read();
while (true)
{
SkipWS(reader);
if (reader.NodeType == XmlNodeType.EndElement && reader.LocalName == "map")
{
reader.Read();
break;
}
if (reader.NodeType != XmlNodeType.Element || reader.LocalName != "key")
throw new LLSDParseException("Expected <key>");
string key = reader.ReadString();
if (reader.NodeType != XmlNodeType.EndElement || reader.LocalName != "key")
throw new LLSDParseException("Expected </key>");
reader.Read();
object val = LLSDParseOne(reader);
ret[key] = val;
}
return ret; // TODO
}
/// <summary>
///
/// </summary>
/// <param name="reader"></param>
/// <returns></returns>
public static ArrayList LLSDParseArray(XmlTextReader reader)
{
ArrayList ret = new ArrayList();
if (reader.NodeType != XmlNodeType.Element || reader.LocalName != "array")
throw new LLSDParseException("Expected <array>");
if (reader.IsEmptyElement)
{
reader.Read();
return ret;
}
reader.Read();
while (true)
{
SkipWS(reader);
if (reader.NodeType == XmlNodeType.EndElement && reader.LocalName == "array")
{
reader.Read();
break;
}
ret.Insert(ret.Count, LLSDParseOne(reader));
}
return ret; // TODO
}
/// <summary>
///
/// </summary>
/// <param name="count"></param>
/// <returns></returns>
private static string GetSpaces(int count)
{
StringBuilder b = new StringBuilder();
for (int i = 0; i < count; i++) b.Append(" ");
return b.ToString();
}
/// <summary>
///
/// </summary>
/// <param name="obj"></param>
/// <param name="indent"></param>
/// <returns></returns>
public static String LLSDDump(object obj, int indent)
{
if (obj == null)
{
return GetSpaces(indent) + "- undef\n";
}
else if (obj is string)
{
return GetSpaces(indent) + "- string \"" + (string) obj + "\"\n";
}
else if (obj is int)
{
return GetSpaces(indent) + "- integer " + obj.ToString() + "\n";
}
else if (obj is double)
{
return GetSpaces(indent) + "- float " + obj.ToString() + "\n";
}
else if (obj is UUID)
{
return GetSpaces(indent) + "- uuid " + ((UUID) obj).ToString() + Environment.NewLine;
}
else if (obj is Hashtable)
{
StringBuilder ret = new StringBuilder();
ret.Append(GetSpaces(indent) + "- map" + Environment.NewLine);
Hashtable map = (Hashtable) obj;
foreach (string key in map.Keys)
{
ret.Append(GetSpaces(indent + 2) + "- key \"" + key + "\"" + Environment.NewLine);
ret.Append(LLSDDump(map[key], indent + 3));
}
return ret.ToString();
}
else if (obj is ArrayList)
{
StringBuilder ret = new StringBuilder();
ret.Append(GetSpaces(indent) + "- array\n");
ArrayList list = (ArrayList) obj;
foreach (object item in list)
{
ret.Append(LLSDDump(item, indent + 2));
}
return ret.ToString();
}
else if (obj is byte[])
{
return GetSpaces(indent) + "- binary\n" + Utils.BytesToHexString((byte[]) obj, GetSpaces(indent)) +
Environment.NewLine;
}
else
{
return GetSpaces(indent) + "- unknown type " + obj.GetType().Name + Environment.NewLine;
}
}
public static object ParseTerseLLSD(string llsd)
{
int notused;
return ParseTerseLLSD(llsd, out notused);
}
public static object ParseTerseLLSD(string llsd, out int endPos)
{
if (llsd.Length == 0)
{
endPos = 0;
return null;
}
// Identify what type of object this is
switch (llsd[0])
{
case '!':
throw new LLSDParseException("Undefined value type encountered");
case '1':
endPos = 1;
return true;
case '0':
endPos = 1;
return false;
case 'i':
{
if (llsd.Length < 2) throw new LLSDParseException("Integer value type with no value");
int value;
endPos = FindEnd(llsd, 1);
if (Int32.TryParse(llsd.Substring(1, endPos - 1), out value))
return value;
else
throw new LLSDParseException("Failed to parse integer value type");
}
case 'r':
{
if (llsd.Length < 2) throw new LLSDParseException("Real value type with no value");
double value;
endPos = FindEnd(llsd, 1);
if (Double.TryParse(llsd.Substring(1, endPos - 1), NumberStyles.Float,
Utils.EnUsCulture.NumberFormat, out value))
return value;
else
throw new LLSDParseException("Failed to parse double value type");
}
case 'u':
{
if (llsd.Length < 17) throw new LLSDParseException("UUID value type with no value");
UUID value;
endPos = FindEnd(llsd, 1);
if (UUID.TryParse(llsd.Substring(1, endPos - 1), out value))
return value;
else
throw new LLSDParseException("Failed to parse UUID value type");
}
case 'b':
//byte[] value = new byte[llsd.Length - 1];
// This isn't the actual binary LLSD format, just the terse format sent
// at login so I don't even know if there is a binary type
throw new LLSDParseException("Binary value type is unimplemented");
case 's':
case 'l':
if (llsd.Length < 2) throw new LLSDParseException("String value type with no value");
endPos = FindEnd(llsd, 1);
return llsd.Substring(1, endPos - 1);
case 'd':
// Never seen one before, don't know what the format is
throw new LLSDParseException("Date value type is unimplemented");
case '[':
{
if (llsd.IndexOf(']') == -1) throw new LLSDParseException("Invalid array");
int pos = 0;
ArrayList array = new ArrayList();
while (llsd[pos] != ']')
{
++pos;
// Advance past comma if need be
if (llsd[pos] == ',') ++pos;
// Allow a single whitespace character
if (pos < llsd.Length && llsd[pos] == ' ') ++pos;
int end;
array.Add(ParseTerseLLSD(llsd.Substring(pos), out end));
pos += end;
}
endPos = pos + 1;
return array;
}
case '{':
{
if (llsd.IndexOf('}') == -1) throw new LLSDParseException("Invalid map");
int pos = 0;
Hashtable hashtable = new Hashtable();
while (llsd[pos] != '}')
{
++pos;
// Advance past comma if need be
if (llsd[pos] == ',') ++pos;
// Allow a single whitespace character
if (pos < llsd.Length && llsd[pos] == ' ') ++pos;
if (llsd[pos] != '\'') throw new LLSDParseException("Expected a map key");
int endquote = llsd.IndexOf('\'', pos + 1);
if (endquote == -1 || (endquote + 1) >= llsd.Length || llsd[endquote + 1] != ':')
throw new LLSDParseException("Invalid map format");
string key = llsd.Substring(pos, endquote - pos);
key = key.Replace("'", String.Empty);
pos += (endquote - pos) + 2;
int end;
hashtable.Add(key, ParseTerseLLSD(llsd.Substring(pos), out end));
pos += end;
}
endPos = pos + 1;
return hashtable;
}
default:
throw new Exception("Unknown value type");
}
}
private static int FindEnd(string llsd, int start)
{
int end = llsd.IndexOfAny(new char[] {',', ']', '}'});
if (end == -1) end = llsd.Length - 1;
return end;
}
/// <summary>
///
/// </summary>
/// <param name="reader"></param>
private static void SkipWS(XmlTextReader reader)
{
while (
reader.NodeType == XmlNodeType.Comment ||
reader.NodeType == XmlNodeType.Whitespace ||
reader.NodeType == XmlNodeType.SignificantWhitespace ||
reader.NodeType == XmlNodeType.XmlDeclaration)
{
reader.Read();
}
}
}
}
| |
// 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.ComponentModel;
using System.Security.Principal;
using System.Security.AccessControl;
namespace System.DirectoryServices
{
[Flags]
public enum ActiveDirectoryRights
{
Delete = 0x10000,
ReadControl = 0x20000,
WriteDacl = 0x40000,
WriteOwner = 0x80000,
Synchronize = 0x100000,
AccessSystemSecurity = 0x1000000,
GenericRead = ReadControl | ListChildren | ReadProperty | ListObject,
GenericWrite = ReadControl | Self | WriteProperty,
GenericExecute = ReadControl | ListChildren,
GenericAll = Delete | ReadControl | WriteDacl | WriteOwner | CreateChild | DeleteChild | ListChildren | Self | ReadProperty | WriteProperty | DeleteTree | ListObject | ExtendedRight,
CreateChild = 0x1,
DeleteChild = 0x2,
ListChildren = 0x4,
Self = 0x8,
ReadProperty = 0x10,
WriteProperty = 0x20,
DeleteTree = 0x40,
ListObject = 0x80,
ExtendedRight = 0x100
}
public enum ActiveDirectorySecurityInheritance
{
None = 0,
All = 1,
Descendents = 2,
SelfAndChildren = 3,
Children = 4
}
public enum PropertyAccess
{
Read = 0,
Write = 1
}
public class ActiveDirectorySecurity : DirectoryObjectSecurity
{
private readonly SecurityMasks _securityMaskUsedInRetrieval = SecurityMasks.Owner | SecurityMasks.Group | SecurityMasks.Dacl | SecurityMasks.Sacl;
#region Constructors
public ActiveDirectorySecurity()
{
}
internal ActiveDirectorySecurity(byte[] sdBinaryForm, SecurityMasks securityMask)
: base(new CommonSecurityDescriptor(true, true, sdBinaryForm, 0))
{
_securityMaskUsedInRetrieval = securityMask;
}
#endregion
#region Public methods
//
// DiscretionaryAcl related methods
//
public void AddAccessRule(ActiveDirectoryAccessRule rule)
{
if (!DaclRetrieved())
{
throw new InvalidOperationException(SR.CannotModifyDacl);
}
base.AddAccessRule(rule);
}
public void SetAccessRule(ActiveDirectoryAccessRule rule)
{
if (!DaclRetrieved())
{
throw new InvalidOperationException(SR.CannotModifyDacl);
}
base.SetAccessRule(rule);
}
public void ResetAccessRule(ActiveDirectoryAccessRule rule)
{
if (!DaclRetrieved())
{
throw new InvalidOperationException(SR.CannotModifyDacl);
}
base.ResetAccessRule(rule);
}
public void RemoveAccess(IdentityReference identity, AccessControlType type)
{
if (!DaclRetrieved())
{
throw new InvalidOperationException(SR.CannotModifyDacl);
}
//
// Create a new rule
//
ActiveDirectoryAccessRule rule = new ActiveDirectoryAccessRule(
identity,
ActiveDirectoryRights.GenericRead, // will be ignored
type,
ActiveDirectorySecurityInheritance.None);
base.RemoveAccessRuleAll(rule);
}
public bool RemoveAccessRule(ActiveDirectoryAccessRule rule)
{
if (!DaclRetrieved())
{
throw new InvalidOperationException(SR.CannotModifyDacl);
}
return base.RemoveAccessRule(rule);
}
public void RemoveAccessRuleSpecific(ActiveDirectoryAccessRule rule)
{
if (!DaclRetrieved())
{
throw new InvalidOperationException(SR.CannotModifyDacl);
}
base.RemoveAccessRuleSpecific(rule);
}
public override bool ModifyAccessRule(AccessControlModification modification, AccessRule rule, out bool modified)
{
if (!DaclRetrieved())
{
throw new InvalidOperationException(SR.CannotModifyDacl);
}
return base.ModifyAccessRule(modification, rule, out modified);
}
public override void PurgeAccessRules(IdentityReference identity)
{
if (!DaclRetrieved())
{
throw new InvalidOperationException(SR.CannotModifyDacl);
}
base.PurgeAccessRules(identity);
}
//
// SystemAcl related methods
//
public void AddAuditRule(ActiveDirectoryAuditRule rule)
{
if (!SaclRetrieved())
{
throw new InvalidOperationException(SR.CannotModifySacl);
}
base.AddAuditRule(rule);
}
public void SetAuditRule(ActiveDirectoryAuditRule rule)
{
if (!SaclRetrieved())
{
throw new InvalidOperationException(SR.CannotModifySacl);
}
base.SetAuditRule(rule);
}
public void RemoveAudit(IdentityReference identity)
{
if (!SaclRetrieved())
{
throw new InvalidOperationException(SR.CannotModifySacl);
}
//
// Create a new rule
//
ActiveDirectoryAuditRule rule = new ActiveDirectoryAuditRule(
identity,
ActiveDirectoryRights.GenericRead, // will be ignored
AuditFlags.Success | AuditFlags.Failure,
ActiveDirectorySecurityInheritance.None);
base.RemoveAuditRuleAll(rule);
}
public bool RemoveAuditRule(ActiveDirectoryAuditRule rule)
{
if (!SaclRetrieved())
{
throw new InvalidOperationException(SR.CannotModifySacl);
}
return base.RemoveAuditRule(rule);
}
public void RemoveAuditRuleSpecific(ActiveDirectoryAuditRule rule)
{
if (!SaclRetrieved())
{
throw new InvalidOperationException(SR.CannotModifySacl);
}
base.RemoveAuditRuleSpecific(rule);
}
public override bool ModifyAuditRule(AccessControlModification modification, AuditRule rule, out bool modified)
{
if (!SaclRetrieved())
{
throw new InvalidOperationException(SR.CannotModifySacl);
}
return base.ModifyAuditRule(modification, rule, out modified);
}
public override void PurgeAuditRules(IdentityReference identity)
{
if (!SaclRetrieved())
{
throw new InvalidOperationException(SR.CannotModifySacl);
}
base.PurgeAuditRules(identity);
}
#endregion
#region Factories
public sealed override AccessRule AccessRuleFactory(
IdentityReference identityReference,
int accessMask,
bool isInherited,
InheritanceFlags inheritanceFlags,
PropagationFlags propagationFlags,
AccessControlType type)
{
return new ActiveDirectoryAccessRule(
identityReference,
accessMask,
type,
Guid.Empty,
isInherited,
inheritanceFlags,
propagationFlags,
Guid.Empty);
}
public sealed override AccessRule AccessRuleFactory(
IdentityReference identityReference,
int accessMask,
bool isInherited,
InheritanceFlags inheritanceFlags,
PropagationFlags propagationFlags,
AccessControlType type,
Guid objectGuid,
Guid inheritedObjectGuid)
{
return new ActiveDirectoryAccessRule(
identityReference,
accessMask,
type,
objectGuid,
isInherited,
inheritanceFlags,
propagationFlags,
inheritedObjectGuid);
}
public sealed override AuditRule AuditRuleFactory(
IdentityReference identityReference,
int accessMask,
bool isInherited,
InheritanceFlags inheritanceFlags,
PropagationFlags propagationFlags,
AuditFlags flags)
{
return new ActiveDirectoryAuditRule(
identityReference,
accessMask,
flags,
Guid.Empty,
isInherited,
inheritanceFlags,
propagationFlags,
Guid.Empty);
}
public sealed override AuditRule AuditRuleFactory(
IdentityReference identityReference,
int accessMask,
bool isInherited,
InheritanceFlags inheritanceFlags,
PropagationFlags propagationFlags,
AuditFlags flags,
Guid objectGuid,
Guid inheritedObjectGuid)
{
return new ActiveDirectoryAuditRule(
identityReference,
accessMask,
flags,
objectGuid,
isInherited,
inheritanceFlags,
propagationFlags,
inheritedObjectGuid);
}
internal bool IsModified()
{
ReadLock();
try
{
return (OwnerModified || GroupModified || AccessRulesModified || AuditRulesModified);
}
finally
{
ReadUnlock();
}
}
private bool DaclRetrieved()
{
return ((_securityMaskUsedInRetrieval & SecurityMasks.Dacl) != 0);
}
private bool SaclRetrieved()
{
return ((_securityMaskUsedInRetrieval & SecurityMasks.Sacl) != 0);
}
#endregion
#region some overrides
public override Type AccessRightType => typeof(ActiveDirectoryRights);
public override Type AccessRuleType => typeof(ActiveDirectoryAccessRule);
public override Type AuditRuleType => typeof(ActiveDirectoryAuditRule);
#endregion
}
internal sealed class ActiveDirectoryRightsTranslator
{
#region Access mask to rights translation
internal static int AccessMaskFromRights(ActiveDirectoryRights adRights) => (int)adRights;
internal static ActiveDirectoryRights RightsFromAccessMask(int accessMask)
{
return (ActiveDirectoryRights)accessMask;
}
#endregion
}
internal sealed class PropertyAccessTranslator
{
#region PropertyAccess to access mask translation
internal static int AccessMaskFromPropertyAccess(PropertyAccess access)
{
int accessMask = 0;
if (access < PropertyAccess.Read || access > PropertyAccess.Write)
{
throw new InvalidEnumArgumentException(nameof(access), (int)access, typeof(PropertyAccess));
}
switch (access)
{
case PropertyAccess.Read:
{
accessMask = ActiveDirectoryRightsTranslator.AccessMaskFromRights(ActiveDirectoryRights.ReadProperty);
break;
}
case PropertyAccess.Write:
{
accessMask = ActiveDirectoryRightsTranslator.AccessMaskFromRights(ActiveDirectoryRights.WriteProperty);
break;
}
default:
//
// This should not happen. Indicates a problem with the
// internal logic.
//
Debug.Fail("Invalid PropertyAccess value");
throw new ArgumentException(nameof(access));
}
return accessMask;
}
#endregion
}
internal sealed class ActiveDirectoryInheritanceTranslator
{
#region ActiveDirectorySecurityInheritance to Inheritance/Propagation flags translation
//
// InheritanceType InheritanceFlags PropagationFlags
// ------------------------------------------------------------------------------
// None None None
// All ContainerInherit None
// Descendents ContainerInherit InheritOnly
// SelfAndChildren ContainerInherit NoPropogateInherit
// Children ContainerInherit InheritOnly | NoPropagateInherit
//
internal static InheritanceFlags[] ITToIF = new InheritanceFlags[] {
InheritanceFlags.None,
InheritanceFlags.ContainerInherit,
InheritanceFlags.ContainerInherit,
InheritanceFlags.ContainerInherit,
InheritanceFlags.ContainerInherit
};
internal static PropagationFlags[] ITToPF = new PropagationFlags[] {
PropagationFlags.None,
PropagationFlags.None,
PropagationFlags.InheritOnly,
PropagationFlags.NoPropagateInherit,
PropagationFlags.InheritOnly | PropagationFlags.NoPropagateInherit
};
internal static InheritanceFlags GetInheritanceFlags(ActiveDirectorySecurityInheritance inheritanceType)
{
if (inheritanceType < ActiveDirectorySecurityInheritance.None || inheritanceType > ActiveDirectorySecurityInheritance.Children)
{
throw new InvalidEnumArgumentException(nameof(inheritanceType), (int)inheritanceType, typeof(ActiveDirectorySecurityInheritance));
}
return ITToIF[(int)inheritanceType];
}
internal static PropagationFlags GetPropagationFlags(ActiveDirectorySecurityInheritance inheritanceType)
{
if (inheritanceType < ActiveDirectorySecurityInheritance.None || inheritanceType > ActiveDirectorySecurityInheritance.Children)
{
throw new InvalidEnumArgumentException(nameof(inheritanceType), (int)inheritanceType, typeof(ActiveDirectorySecurityInheritance));
}
return ITToPF[(int)inheritanceType];
}
internal static ActiveDirectorySecurityInheritance GetEffectiveInheritanceFlags(InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags)
{
ActiveDirectorySecurityInheritance inheritanceType = ActiveDirectorySecurityInheritance.None;
if ((inheritanceFlags & InheritanceFlags.ContainerInherit) != 0)
{
switch (propagationFlags)
{
case PropagationFlags.None:
{
inheritanceType = ActiveDirectorySecurityInheritance.All;
break;
}
case PropagationFlags.InheritOnly:
{
inheritanceType = ActiveDirectorySecurityInheritance.Descendents;
break;
}
case PropagationFlags.NoPropagateInherit:
{
inheritanceType = ActiveDirectorySecurityInheritance.SelfAndChildren;
break;
}
case PropagationFlags.InheritOnly | PropagationFlags.NoPropagateInherit:
{
inheritanceType = ActiveDirectorySecurityInheritance.Children;
break;
}
default:
//
// This should not happen. Indicates a problem with the
// internal logic.
//
Debug.Fail("Invalid PropagationFlags value");
throw new ArgumentException(nameof(propagationFlags));
}
}
return inheritanceType;
}
#endregion
}
public class ActiveDirectoryAccessRule : ObjectAccessRule
{
#region Constructors
public ActiveDirectoryAccessRule(
IdentityReference identity,
ActiveDirectoryRights adRights,
AccessControlType type)
: this(
identity,
ActiveDirectoryRightsTranslator.AccessMaskFromRights(adRights),
type,
Guid.Empty,
false,
InheritanceFlags.None,
PropagationFlags.None,
Guid.Empty
)
{
}
public ActiveDirectoryAccessRule(
IdentityReference identity,
ActiveDirectoryRights adRights,
AccessControlType type,
Guid objectType)
: this(
identity,
ActiveDirectoryRightsTranslator.AccessMaskFromRights(adRights),
type,
objectType,
false,
InheritanceFlags.None,
PropagationFlags.None,
Guid.Empty)
{
}
public ActiveDirectoryAccessRule(
IdentityReference identity,
ActiveDirectoryRights adRights,
AccessControlType type,
ActiveDirectorySecurityInheritance inheritanceType)
: this(
identity,
ActiveDirectoryRightsTranslator.AccessMaskFromRights(adRights),
type,
Guid.Empty,
false,
ActiveDirectoryInheritanceTranslator.GetInheritanceFlags(inheritanceType),
ActiveDirectoryInheritanceTranslator.GetPropagationFlags(inheritanceType),
Guid.Empty)
{
}
public ActiveDirectoryAccessRule(
IdentityReference identity,
ActiveDirectoryRights adRights,
AccessControlType type,
Guid objectType,
ActiveDirectorySecurityInheritance inheritanceType)
: this(
identity,
ActiveDirectoryRightsTranslator.AccessMaskFromRights(adRights),
type,
objectType,
false,
ActiveDirectoryInheritanceTranslator.GetInheritanceFlags(inheritanceType),
ActiveDirectoryInheritanceTranslator.GetPropagationFlags(inheritanceType),
Guid.Empty)
{
}
public ActiveDirectoryAccessRule(
IdentityReference identity,
ActiveDirectoryRights adRights,
AccessControlType type,
ActiveDirectorySecurityInheritance inheritanceType,
Guid inheritedObjectType)
: this(
identity,
ActiveDirectoryRightsTranslator.AccessMaskFromRights(adRights),
type,
Guid.Empty,
false,
ActiveDirectoryInheritanceTranslator.GetInheritanceFlags(inheritanceType),
ActiveDirectoryInheritanceTranslator.GetPropagationFlags(inheritanceType),
inheritedObjectType)
{
}
public ActiveDirectoryAccessRule(
IdentityReference identity,
ActiveDirectoryRights adRights,
AccessControlType type,
Guid objectType,
ActiveDirectorySecurityInheritance inheritanceType,
Guid inheritedObjectType)
: this(
identity,
ActiveDirectoryRightsTranslator.AccessMaskFromRights(adRights),
type,
objectType,
false,
ActiveDirectoryInheritanceTranslator.GetInheritanceFlags(inheritanceType),
ActiveDirectoryInheritanceTranslator.GetPropagationFlags(inheritanceType),
inheritedObjectType)
{
}
internal ActiveDirectoryAccessRule(
IdentityReference identity,
int accessMask,
AccessControlType type,
Guid objectType,
bool isInherited,
InheritanceFlags inheritanceFlags,
PropagationFlags propagationFlags,
Guid inheritedObjectType
)
: base(identity,
accessMask,
isInherited,
inheritanceFlags,
propagationFlags,
objectType,
inheritedObjectType,
type)
{
}
#endregion constructors
#region Public properties
public ActiveDirectoryRights ActiveDirectoryRights
{
get => ActiveDirectoryRightsTranslator.RightsFromAccessMask(base.AccessMask);
}
public ActiveDirectorySecurityInheritance InheritanceType
{
get => ActiveDirectoryInheritanceTranslator.GetEffectiveInheritanceFlags(InheritanceFlags, PropagationFlags);
}
#endregion
}
public sealed class ListChildrenAccessRule : ActiveDirectoryAccessRule
{
#region Constructors
public ListChildrenAccessRule(
IdentityReference identity,
AccessControlType type)
: base(
identity,
(int)ActiveDirectoryRights.ListChildren,
type,
Guid.Empty,
false,
InheritanceFlags.None,
PropagationFlags.None,
Guid.Empty
)
{
}
public ListChildrenAccessRule(
IdentityReference identity,
AccessControlType type,
ActiveDirectorySecurityInheritance inheritanceType)
: base(
identity,
(int)ActiveDirectoryRights.ListChildren,
type,
Guid.Empty,
false,
ActiveDirectoryInheritanceTranslator.GetInheritanceFlags(inheritanceType),
ActiveDirectoryInheritanceTranslator.GetPropagationFlags(inheritanceType),
Guid.Empty)
{
}
public ListChildrenAccessRule(
IdentityReference identity,
AccessControlType type,
ActiveDirectorySecurityInheritance inheritanceType,
Guid inheritedObjectType)
: base(
identity,
(int)ActiveDirectoryRights.ListChildren,
type,
Guid.Empty,
false,
ActiveDirectoryInheritanceTranslator.GetInheritanceFlags(inheritanceType),
ActiveDirectoryInheritanceTranslator.GetPropagationFlags(inheritanceType),
inheritedObjectType)
{
}
#endregion constructors
}
public sealed class CreateChildAccessRule : ActiveDirectoryAccessRule
{
#region Constructors
public CreateChildAccessRule(
IdentityReference identity,
AccessControlType type)
: base(
identity,
(int)ActiveDirectoryRights.CreateChild,
type,
Guid.Empty, // all child objects
false,
InheritanceFlags.None,
PropagationFlags.None,
Guid.Empty)
{
}
public CreateChildAccessRule(
IdentityReference identity,
AccessControlType type,
Guid childType)
: base(
identity,
(int)ActiveDirectoryRights.CreateChild,
type,
childType,
false,
InheritanceFlags.None,
PropagationFlags.None,
Guid.Empty)
{
}
public CreateChildAccessRule(
IdentityReference identity,
AccessControlType type,
ActiveDirectorySecurityInheritance inheritanceType)
: base(
identity,
(int)ActiveDirectoryRights.CreateChild,
type,
Guid.Empty, // all child objects
false,
ActiveDirectoryInheritanceTranslator.GetInheritanceFlags(inheritanceType),
ActiveDirectoryInheritanceTranslator.GetPropagationFlags(inheritanceType),
Guid.Empty)
{
}
public CreateChildAccessRule(
IdentityReference identity,
AccessControlType type,
Guid childType,
ActiveDirectorySecurityInheritance inheritanceType)
: base(
identity,
(int)ActiveDirectoryRights.CreateChild,
type,
childType,
false,
ActiveDirectoryInheritanceTranslator.GetInheritanceFlags(inheritanceType),
ActiveDirectoryInheritanceTranslator.GetPropagationFlags(inheritanceType),
Guid.Empty)
{
}
public CreateChildAccessRule(
IdentityReference identity,
AccessControlType type,
ActiveDirectorySecurityInheritance inheritanceType,
Guid inheritedObjectType)
: base(
identity,
(int)ActiveDirectoryRights.CreateChild,
type,
Guid.Empty, // all child objects
false,
ActiveDirectoryInheritanceTranslator.GetInheritanceFlags(inheritanceType),
ActiveDirectoryInheritanceTranslator.GetPropagationFlags(inheritanceType),
inheritedObjectType)
{
}
public CreateChildAccessRule(
IdentityReference identity, AccessControlType type,
Guid childType,
ActiveDirectorySecurityInheritance inheritanceType,
Guid inheritedObjectType)
: base(
identity,
(int)ActiveDirectoryRights.CreateChild,
type,
childType,
false,
ActiveDirectoryInheritanceTranslator.GetInheritanceFlags(inheritanceType),
ActiveDirectoryInheritanceTranslator.GetPropagationFlags(inheritanceType),
inheritedObjectType)
{
}
#endregion constructors
}
public sealed class DeleteChildAccessRule : ActiveDirectoryAccessRule
{
#region Constructors
public DeleteChildAccessRule(
IdentityReference identity,
AccessControlType type)
: base(
identity,
(int)ActiveDirectoryRights.DeleteChild,
type,
Guid.Empty, // all child objects
false,
InheritanceFlags.None,
PropagationFlags.None,
Guid.Empty)
{
}
public DeleteChildAccessRule(
IdentityReference identity,
AccessControlType type,
Guid childType)
: base(
identity,
(int)ActiveDirectoryRights.DeleteChild,
type,
childType,
false,
InheritanceFlags.None,
PropagationFlags.None,
Guid.Empty)
{
}
public DeleteChildAccessRule(
IdentityReference identity,
AccessControlType type,
ActiveDirectorySecurityInheritance inheritanceType)
: base(
identity,
(int)ActiveDirectoryRights.DeleteChild,
type,
Guid.Empty, // all child objects
false,
ActiveDirectoryInheritanceTranslator.GetInheritanceFlags(inheritanceType),
ActiveDirectoryInheritanceTranslator.GetPropagationFlags(inheritanceType),
Guid.Empty)
{
}
public DeleteChildAccessRule(
IdentityReference identity,
AccessControlType type,
Guid childType,
ActiveDirectorySecurityInheritance inheritanceType)
: base(
identity,
(int)ActiveDirectoryRights.DeleteChild,
type,
childType,
false,
ActiveDirectoryInheritanceTranslator.GetInheritanceFlags(inheritanceType),
ActiveDirectoryInheritanceTranslator.GetPropagationFlags(inheritanceType),
Guid.Empty)
{
}
public DeleteChildAccessRule(
IdentityReference identity,
AccessControlType type,
ActiveDirectorySecurityInheritance inheritanceType,
Guid inheritedObjectType)
: base(
identity,
(int)ActiveDirectoryRights.DeleteChild,
type,
Guid.Empty, // all child objects
false,
ActiveDirectoryInheritanceTranslator.GetInheritanceFlags(inheritanceType),
ActiveDirectoryInheritanceTranslator.GetPropagationFlags(inheritanceType),
inheritedObjectType)
{
}
public DeleteChildAccessRule(
IdentityReference identity, AccessControlType type,
Guid childType,
ActiveDirectorySecurityInheritance inheritanceType,
Guid inheritedObjectType)
: base(
identity,
(int)ActiveDirectoryRights.DeleteChild,
type,
childType,
false,
ActiveDirectoryInheritanceTranslator.GetInheritanceFlags(inheritanceType),
ActiveDirectoryInheritanceTranslator.GetPropagationFlags(inheritanceType),
inheritedObjectType)
{
}
#endregion constructors
}
public sealed class PropertyAccessRule : ActiveDirectoryAccessRule
{
#region Constructors
public PropertyAccessRule(
IdentityReference identity,
AccessControlType type,
PropertyAccess access)
: base(
identity,
(int)PropertyAccessTranslator.AccessMaskFromPropertyAccess(access),
type,
Guid.Empty, // all properties
false,
InheritanceFlags.None,
PropagationFlags.None,
Guid.Empty)
{
}
public PropertyAccessRule(
IdentityReference identity,
AccessControlType type,
PropertyAccess access,
Guid propertyType)
: base(
identity,
(int)PropertyAccessTranslator.AccessMaskFromPropertyAccess(access),
type,
propertyType,
false,
InheritanceFlags.None,
PropagationFlags.None,
Guid.Empty)
{
}
public PropertyAccessRule(
IdentityReference identity,
AccessControlType type,
PropertyAccess access,
ActiveDirectorySecurityInheritance inheritanceType)
: base(
identity,
(int)PropertyAccessTranslator.AccessMaskFromPropertyAccess(access),
type,
Guid.Empty, // all properties
false,
ActiveDirectoryInheritanceTranslator.GetInheritanceFlags(inheritanceType),
ActiveDirectoryInheritanceTranslator.GetPropagationFlags(inheritanceType),
Guid.Empty)
{
}
public PropertyAccessRule(
IdentityReference identity,
AccessControlType type,
PropertyAccess access,
Guid propertyType,
ActiveDirectorySecurityInheritance inheritanceType)
: base(
identity,
(int)PropertyAccessTranslator.AccessMaskFromPropertyAccess(access),
type,
propertyType,
false,
ActiveDirectoryInheritanceTranslator.GetInheritanceFlags(inheritanceType),
ActiveDirectoryInheritanceTranslator.GetPropagationFlags(inheritanceType),
Guid.Empty)
{
}
public PropertyAccessRule(
IdentityReference identity,
AccessControlType type,
PropertyAccess access,
ActiveDirectorySecurityInheritance inheritanceType,
Guid inheritedObjectType)
: base(
identity,
(int)PropertyAccessTranslator.AccessMaskFromPropertyAccess(access),
type,
Guid.Empty, // all properties
false,
ActiveDirectoryInheritanceTranslator.GetInheritanceFlags(inheritanceType),
ActiveDirectoryInheritanceTranslator.GetPropagationFlags(inheritanceType),
inheritedObjectType)
{
}
public PropertyAccessRule(
IdentityReference identity,
AccessControlType type,
PropertyAccess access,
Guid propertyType,
ActiveDirectorySecurityInheritance inheritanceType,
Guid inheritedObjectType)
: base(
identity,
(int)PropertyAccessTranslator.AccessMaskFromPropertyAccess(access),
type,
propertyType,
false,
ActiveDirectoryInheritanceTranslator.GetInheritanceFlags(inheritanceType),
ActiveDirectoryInheritanceTranslator.GetPropagationFlags(inheritanceType),
inheritedObjectType)
{
}
#endregion constructors
}
public sealed class PropertySetAccessRule : ActiveDirectoryAccessRule
{
#region Constructors
public PropertySetAccessRule(
IdentityReference identity,
AccessControlType type,
PropertyAccess access,
Guid propertySetType)
: base(
identity,
(int)PropertyAccessTranslator.AccessMaskFromPropertyAccess(access),
type,
propertySetType,
false,
InheritanceFlags.None,
PropagationFlags.None,
Guid.Empty)
{
}
public PropertySetAccessRule(
IdentityReference identity,
AccessControlType type,
PropertyAccess access,
Guid propertySetType,
ActiveDirectorySecurityInheritance inheritanceType)
: base(
identity,
(int)PropertyAccessTranslator.AccessMaskFromPropertyAccess(access),
type,
propertySetType,
false,
ActiveDirectoryInheritanceTranslator.GetInheritanceFlags(inheritanceType),
ActiveDirectoryInheritanceTranslator.GetPropagationFlags(inheritanceType),
Guid.Empty)
{
}
public PropertySetAccessRule(IdentityReference identity,
AccessControlType type,
PropertyAccess access,
Guid propertySetType,
ActiveDirectorySecurityInheritance inheritanceType,
Guid inheritedObjectType)
: base(
identity,
(int)PropertyAccessTranslator.AccessMaskFromPropertyAccess(access),
type,
propertySetType,
false,
ActiveDirectoryInheritanceTranslator.GetInheritanceFlags(inheritanceType),
ActiveDirectoryInheritanceTranslator.GetPropagationFlags(inheritanceType),
inheritedObjectType)
{
}
#endregion constructors
}
public sealed class ExtendedRightAccessRule : ActiveDirectoryAccessRule
{
#region Constructors
public ExtendedRightAccessRule(
IdentityReference identity,
AccessControlType type)
: base(
identity,
(int)ActiveDirectoryRights.ExtendedRight,
type,
Guid.Empty, // all extended rights
false,
InheritanceFlags.None,
PropagationFlags.None,
Guid.Empty)
{
}
public ExtendedRightAccessRule(
IdentityReference identity,
AccessControlType type,
Guid extendedRightType)
: base(
identity,
(int)ActiveDirectoryRights.ExtendedRight,
type,
extendedRightType,
false,
InheritanceFlags.None,
PropagationFlags.None,
Guid.Empty)
{
}
public ExtendedRightAccessRule(
IdentityReference identity,
AccessControlType type,
ActiveDirectorySecurityInheritance inheritanceType)
: base(
identity,
(int)ActiveDirectoryRights.ExtendedRight,
type,
Guid.Empty, // all extended rights
false,
ActiveDirectoryInheritanceTranslator.GetInheritanceFlags(inheritanceType),
ActiveDirectoryInheritanceTranslator.GetPropagationFlags(inheritanceType),
Guid.Empty)
{
}
public ExtendedRightAccessRule(
IdentityReference identity,
AccessControlType type,
Guid extendedRightType,
ActiveDirectorySecurityInheritance inheritanceType)
: base(
identity,
(int)ActiveDirectoryRights.ExtendedRight,
type,
extendedRightType,
false,
ActiveDirectoryInheritanceTranslator.GetInheritanceFlags(inheritanceType),
ActiveDirectoryInheritanceTranslator.GetPropagationFlags(inheritanceType),
Guid.Empty)
{
}
public ExtendedRightAccessRule(
IdentityReference identity,
AccessControlType type,
ActiveDirectorySecurityInheritance inheritanceType,
Guid inheritedObjectType)
: base(
identity,
(int)ActiveDirectoryRights.ExtendedRight,
type,
Guid.Empty, // all extended rights
false,
ActiveDirectoryInheritanceTranslator.GetInheritanceFlags(inheritanceType),
ActiveDirectoryInheritanceTranslator.GetPropagationFlags(inheritanceType),
inheritedObjectType)
{
}
public ExtendedRightAccessRule(IdentityReference identity,
AccessControlType type,
Guid extendedRightType,
ActiveDirectorySecurityInheritance inheritanceType,
Guid inheritedObjectType)
: base(
identity,
(int)ActiveDirectoryRights.ExtendedRight,
type,
extendedRightType,
false,
ActiveDirectoryInheritanceTranslator.GetInheritanceFlags(inheritanceType),
ActiveDirectoryInheritanceTranslator.GetPropagationFlags(inheritanceType),
inheritedObjectType)
{
}
#endregion constructors
}
public sealed class DeleteTreeAccessRule : ActiveDirectoryAccessRule
{
#region Constructors
public DeleteTreeAccessRule(
IdentityReference identity,
AccessControlType type)
: base(
identity,
(int)ActiveDirectoryRights.DeleteTree,
type,
Guid.Empty,
false,
InheritanceFlags.None,
PropagationFlags.None,
Guid.Empty)
{
}
public DeleteTreeAccessRule(
IdentityReference identity,
AccessControlType type,
ActiveDirectorySecurityInheritance inheritanceType)
: base(
identity,
(int)ActiveDirectoryRights.DeleteTree,
type,
Guid.Empty,
false,
ActiveDirectoryInheritanceTranslator.GetInheritanceFlags(inheritanceType),
ActiveDirectoryInheritanceTranslator.GetPropagationFlags(inheritanceType),
Guid.Empty)
{
}
public DeleteTreeAccessRule(
IdentityReference identity,
AccessControlType type,
ActiveDirectorySecurityInheritance inheritanceType,
Guid inheritedObjectType)
: base(
identity,
(int)ActiveDirectoryRights.DeleteTree,
type,
Guid.Empty,
false,
ActiveDirectoryInheritanceTranslator.GetInheritanceFlags(inheritanceType),
ActiveDirectoryInheritanceTranslator.GetPropagationFlags(inheritanceType),
inheritedObjectType)
{
}
#endregion constructors
}
public class ActiveDirectoryAuditRule : ObjectAuditRule
{
#region Constructors
public ActiveDirectoryAuditRule(
IdentityReference identity,
ActiveDirectoryRights adRights,
AuditFlags auditFlags)
: this(
identity,
ActiveDirectoryRightsTranslator.AccessMaskFromRights(adRights),
auditFlags,
Guid.Empty,
false,
InheritanceFlags.None,
PropagationFlags.None,
Guid.Empty
)
{
}
public ActiveDirectoryAuditRule(
IdentityReference identity,
ActiveDirectoryRights adRights,
AuditFlags auditFlags,
Guid objectType)
: this(
identity,
ActiveDirectoryRightsTranslator.AccessMaskFromRights(adRights),
auditFlags,
objectType,
false,
InheritanceFlags.None,
PropagationFlags.None,
Guid.Empty)
{
}
public ActiveDirectoryAuditRule(
IdentityReference identity,
ActiveDirectoryRights adRights,
AuditFlags auditFlags,
ActiveDirectorySecurityInheritance inheritanceType)
: this(
identity,
ActiveDirectoryRightsTranslator.AccessMaskFromRights(adRights),
auditFlags,
Guid.Empty,
false,
ActiveDirectoryInheritanceTranslator.GetInheritanceFlags(inheritanceType),
ActiveDirectoryInheritanceTranslator.GetPropagationFlags(inheritanceType),
Guid.Empty)
{
}
public ActiveDirectoryAuditRule(
IdentityReference identity,
ActiveDirectoryRights adRights,
AuditFlags auditFlags,
Guid objectType,
ActiveDirectorySecurityInheritance inheritanceType)
: this(
identity,
ActiveDirectoryRightsTranslator.AccessMaskFromRights(adRights),
auditFlags,
objectType,
false,
ActiveDirectoryInheritanceTranslator.GetInheritanceFlags(inheritanceType),
ActiveDirectoryInheritanceTranslator.GetPropagationFlags(inheritanceType),
Guid.Empty)
{
}
public ActiveDirectoryAuditRule(
IdentityReference identity,
ActiveDirectoryRights adRights,
AuditFlags auditFlags,
ActiveDirectorySecurityInheritance inheritanceType,
Guid inheritedObjectType)
: this(
identity,
ActiveDirectoryRightsTranslator.AccessMaskFromRights(adRights),
auditFlags,
Guid.Empty,
false,
ActiveDirectoryInheritanceTranslator.GetInheritanceFlags(inheritanceType),
ActiveDirectoryInheritanceTranslator.GetPropagationFlags(inheritanceType),
inheritedObjectType)
{
}
public ActiveDirectoryAuditRule(
IdentityReference identity,
ActiveDirectoryRights adRights,
AuditFlags auditFlags,
Guid objectType,
ActiveDirectorySecurityInheritance inheritanceType,
Guid inheritedObjectType)
: this(
identity,
ActiveDirectoryRightsTranslator.AccessMaskFromRights(adRights),
auditFlags,
objectType,
false,
ActiveDirectoryInheritanceTranslator.GetInheritanceFlags(inheritanceType),
ActiveDirectoryInheritanceTranslator.GetPropagationFlags(inheritanceType),
inheritedObjectType)
{
}
internal ActiveDirectoryAuditRule(
IdentityReference identity,
int accessMask,
AuditFlags auditFlags,
Guid objectGuid,
bool isInherited,
InheritanceFlags inheritanceFlags,
PropagationFlags propagationFlags,
Guid inheritedObjectType
)
: base(identity,
accessMask,
isInherited,
inheritanceFlags,
propagationFlags,
objectGuid,
inheritedObjectType,
auditFlags)
{
}
#endregion constructors
#region Public properties
public ActiveDirectoryRights ActiveDirectoryRights
{
get => ActiveDirectoryRightsTranslator.RightsFromAccessMask(AccessMask);
}
public ActiveDirectorySecurityInheritance InheritanceType
{
get => ActiveDirectoryInheritanceTranslator.GetEffectiveInheritanceFlags(InheritanceFlags, PropagationFlags);
}
#endregion
}
}
| |
namespace PeregrineDb.Tests.Dialects
{
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Data;
using System.Diagnostics.CodeAnalysis;
using FluentAssertions;
using Moq;
using Pagination;
using PeregrineDb;
using PeregrineDb.Dialects;
using PeregrineDb.Dialects.SqlServer2012;
using PeregrineDb.Schema;
using PeregrineDb.Tests.ExampleEntities;
using PeregrineDb.Tests.Utils;
using Xunit;
[SuppressMessage("ReSharper", "ConvertToConstant.Local")]
public class SqlServer2012DialectTests
{
private PeregrineConfig config = PeregrineConfig.SqlServer2012;
private IDialect Sut => this.config.Dialect;
private TableSchema GetTableSchema<T>()
{
return this.GetTableSchema(typeof(T));
}
private TableSchema GetTableSchema(Type type)
{
return this.config.SchemaFactory.GetTableSchema(type);
}
private ImmutableArray<ConditionColumnSchema> GetConditionsSchema<T>(object conditions)
{
var entityType = typeof(T);
var tableSchema = this.GetTableSchema(entityType);
return this.config.SchemaFactory.GetConditionsSchema(entityType, tableSchema, conditions.GetType());
}
public class MakeCountStatement
: SqlServer2012DialectTests
{
[Fact]
public void Selects_from_given_table()
{
// Act
var command = this.Sut.MakeCountCommand(null, null, this.GetTableSchema<Dog>());
// Assert
var expected = new SqlCommand(@"
SELECT COUNT(*)
FROM [Dogs]");
command.Should().Be(expected);
}
[Fact]
public void Adds_conditions()
{
// Act
var command = this.Sut.MakeCountCommand("WHERE Foo IS NOT NULL", null, this.GetTableSchema<Dog>());
// Assert
var expected = new SqlCommand(@"
SELECT COUNT(*)
FROM [Dogs]
WHERE Foo IS NOT NULL");
command.Should().Be(expected);
}
}
public class MakeFindStatement
: SqlServer2012DialectTests
{
[Fact]
public void Errors_when_id_is_null()
{
// Act
Action act = () => this.Sut.MakeFindCommand(null, this.GetTableSchema<Dog>());
// Assert
act.Should().Throw<ArgumentNullException>();
}
[Fact]
public void Selects_from_given_table()
{
// Act
var command = this.Sut.MakeFindCommand(5, this.GetTableSchema<Dog>());
// Assert
var expected = new SqlCommand(@"
SELECT [Id], [Name], [Age]
FROM [Dogs]
WHERE [Id] = @Id",
new Dictionary<string, object>
{
["Id"] = 5
});
command.Should().Be(expected);
}
[Fact]
public void Uses_non_default_primary_key_name()
{
// Act
var command = this.Sut.MakeFindCommand(5, this.GetTableSchema<KeyExplicit>());
// Assert
var expected = new SqlCommand(@"
SELECT [Key], [Name]
FROM [KeyExplicit]
WHERE [Key] = @Key",
new Dictionary<string, object>
{
["Key"] = 5
});
command.Should().Be(expected);
}
[Fact]
public void Uses_each_key_in_composite_key()
{
// Act
var command = this.Sut.MakeFindCommand(new { key1 = 2, key2 = 3 }, this.GetTableSchema<CompositeKeys>());
// Assert
var expected = new SqlCommand(@"
SELECT [Key1], [Key2], [Name]
FROM [CompositeKeys]
WHERE [Key1] = @Key1 AND [Key2] = @Key2",
new { key1 = 2, key2 = 3 });
command.Should().Be(expected);
}
[Fact]
public void Adds_alias_when_primary_key_is_aliased()
{
// Act
var command = this.Sut.MakeFindCommand(5, this.GetTableSchema<KeyAlias>());
// Assert
var expected = new SqlCommand(@"
SELECT [Key] AS [Id], [Name]
FROM [KeyAlias]
WHERE [Key] = @Id",
new Dictionary<string, object>
{
["Id"] = 5
});
command.Should().Be(expected);
}
[Fact]
public void Adds_alias_when_column_name_is_aliased()
{
// Act
var command = this.Sut.MakeFindCommand(5, this.GetTableSchema<PropertyAlias>());
// Assert
var expected = new SqlCommand(@"
SELECT [Id], [YearsOld] AS [Age]
FROM [PropertyAlias]
WHERE [Id] = @Id",
new Dictionary<string, object>
{
["Id"] = 5
});
command.Should().Be(expected);
}
}
public class MakeGetRangeStatement
: SqlServer2012DialectTests
{
[Fact]
public void Selects_from_given_table()
{
// Act
var command = this.Sut.MakeGetRangeCommand(null, null, this.GetTableSchema<Dog>());
// Assert
var expected = new SqlCommand(@"
SELECT [Id], [Name], [Age]
FROM [Dogs]");
command.Should().Be(expected);
}
[Fact]
public void Adds_conditions_clause()
{
// Act
var command = this.Sut.MakeGetRangeCommand("WHERE Age > @Age", new { Age = 10 }, this.GetTableSchema<Dog>());
// Assert
var expected = new SqlCommand(@"
SELECT [Id], [Name], [Age]
FROM [Dogs]
WHERE Age > @Age",
new { Age = 10 });
command.Should().Be(expected);
}
[Fact]
public void Uses_explicit_primary_key_name()
{
// Act
var command = this.Sut.MakeGetRangeCommand(null, null, this.GetTableSchema<KeyExplicit>());
// Assert
var expected = new SqlCommand(@"
SELECT [Key], [Name]
FROM [KeyExplicit]");
command.Should().Be(expected);
}
[Fact]
public void Adds_alias_when_primary_key_is_aliased()
{
// Act
var command = this.Sut.MakeGetRangeCommand(null, null, this.GetTableSchema<KeyAlias>());
// Assert
var expected = new SqlCommand(@"
SELECT [Key] AS [Id], [Name]
FROM [KeyAlias]");
command.Should().Be(expected);
}
[Fact]
public void Adds_alias_when_column_name_is_aliased()
{
// Act
var command = this.Sut.MakeGetRangeCommand(null, null, this.GetTableSchema<PropertyAlias>());
// Assert
var expected = new SqlCommand(@"
SELECT [Id], [YearsOld] AS [Age]
FROM [PropertyAlias]");
command.Should().Be(expected);
}
}
public class MakeGetFirstNCommand
: SqlServer2012DialectTests
{
[Fact]
public void Adds_conditions_clause()
{
// Act
var command = this.Sut.MakeGetFirstNCommand(1, "WHERE Name LIKE @Name", new { Name = "Foo%" }, "Name", this.GetTableSchema<Dog>());
// Assert
var expected = new SqlCommand(@"
SELECT TOP 1 [Id], [Name], [Age]
FROM [Dogs]
WHERE Name LIKE @Name
ORDER BY Name",
new { Name = "Foo%" });
command.Should().Be(expected);
}
[Fact]
public void Adds_alias_when_column_name_is_aliased()
{
// Act
var command = this.Sut.MakeGetFirstNCommand(1, "WHERE Name LIKE @p0", new { p0 = "Foo%" }, "Name", this.GetTableSchema<PropertyAlias>());
// Assert
var expected = new SqlCommand(@"
SELECT TOP 1 [Id], [YearsOld] AS [Age]
FROM [PropertyAlias]
WHERE Name LIKE @p0
ORDER BY Name",
new { p0 = "Foo%" });
command.Should().Be(expected);
}
[Theory]
[InlineData(null)]
[InlineData("")]
[InlineData(" ")]
public void Does_not_order_when_no_orderby_given(string orderBy)
{
// Act
var command = this.Sut.MakeGetFirstNCommand(1, "WHERE Name LIKE @p0", new { p0 = "Foo%" }, orderBy, this.GetTableSchema<Dog>());
// Assert
var expected = new SqlCommand(@"
SELECT TOP 1 [Id], [Name], [Age]
FROM [Dogs]
WHERE Name LIKE @p0",
new { p0 = "Foo%" });
command.Should().Be(expected);
}
}
public class MakeGetPageStatement
: SqlServer2012DialectTests
{
[Theory]
[InlineData(null)]
[InlineData("")]
[InlineData(" ")]
public void Throws_exception_when_order_by_is_empty(string orderBy)
{
// Act / Assert
Assert.Throws<ArgumentException>(() => this.Sut.MakeGetPageCommand(new Page(1, 10, true, 0, 9), null, null, orderBy, this.GetTableSchema<Dog>()));
}
[Fact]
public void Selects_from_given_table()
{
// Act
var command = this.Sut.MakeGetPageCommand(new Page(1, 10, true, 0, 9), null, null, "Name", this.GetTableSchema<Dog>());
// Assert
var expected = new SqlCommand(@"
SELECT [Id], [Name], [Age]
FROM [Dogs]
ORDER BY Name
OFFSET 0 ROWS FETCH NEXT 10 ROWS ONLY");
command.Should().Be(expected);
}
[Fact]
public void Adds_conditions_clause()
{
// Act
var command = this.Sut.MakeGetPageCommand(new Page(1, 10, true, 0, 9), "WHERE Name LIKE @Name", new { Name = "Foo%" }, "Name", this.GetTableSchema<Dog>());
// Assert
var expected = new SqlCommand(@"
SELECT [Id], [Name], [Age]
FROM [Dogs]
WHERE Name LIKE @Name
ORDER BY Name
OFFSET 0 ROWS FETCH NEXT 10 ROWS ONLY",
new { Name = "Foo%" });
command.Should().Be(expected);
}
[Fact]
public void Adds_alias_when_column_name_is_aliased()
{
// Act
var command = this.Sut.MakeGetPageCommand(new Page(1, 10, true, 0, 9), null, null, "Name", this.GetTableSchema<PropertyAlias>());
// Assert
var expected = new SqlCommand(@"
SELECT [Id], [YearsOld] AS [Age]
FROM [PropertyAlias]
ORDER BY Name
OFFSET 0 ROWS FETCH NEXT 10 ROWS ONLY");
command.Should().Be(expected);
}
[Fact]
public void Selects_second_page()
{
// Act
var command = this.Sut.MakeGetPageCommand(new Page(2, 10, true, 10, 19), null, null, "Name", this.GetTableSchema<Dog>());
// Assert
var expected = new SqlCommand(@"
SELECT [Id], [Name], [Age]
FROM [Dogs]
ORDER BY Name
OFFSET 10 ROWS FETCH NEXT 10 ROWS ONLY");
command.Should().Be(expected);
}
[Fact]
public void Selects_appropriate_number_of_rows()
{
// Act
var command = this.Sut.MakeGetPageCommand(new Page(2, 5, true, 5, 9), null, null, "Name", this.GetTableSchema<Dog>());
// Assert
var expected = new SqlCommand(@"
SELECT [Id], [Name], [Age]
FROM [Dogs]
ORDER BY Name
OFFSET 5 ROWS FETCH NEXT 5 ROWS ONLY");
command.Should().Be(expected);
}
}
public class MakeInsertStatement
: SqlServer2012DialectTests
{
[Fact]
public void Inserts_into_given_table()
{
// Act
object entity = new Dog { Name = "Foo", Age = 10 };
var command = this.Sut.MakeInsertCommand(entity, this.GetTableSchema(entity.GetType()));
// Assert
var expected = new SqlCommand(@"
INSERT INTO [Dogs] ([Name], [Age])
VALUES (@Name, @Age);",
new Dog { Name = "Foo", Age = 10 });
command.Should().Be(expected);
}
[Fact]
public void Adds_primary_key_if_its_not_generated_by_database()
{
// Act
object entity = new KeyNotGenerated { Id = 6, Name = "Foo" };
var command = this.Sut.MakeInsertCommand(entity, this.GetTableSchema<KeyNotGenerated>());
// Assert
var expected = new SqlCommand(@"
INSERT INTO [KeyNotGenerated] ([Id], [Name])
VALUES (@Id, @Name);",
new KeyNotGenerated { Id = 6, Name = "Foo" });
command.Should().Be(expected);
}
[Fact]
public void Does_not_include_computed_columns()
{
// Act
object entity = new PropertyComputed { Name = "Foo" };
var command = this.Sut.MakeInsertCommand(entity, this.GetTableSchema<PropertyComputed>());
// Assert
var expected = new SqlCommand(@"
INSERT INTO [PropertyComputed] ([Name])
VALUES (@Name);",
new PropertyComputed { Name = "Foo" });
command.Should().Be(expected);
}
[Fact]
public void Does_not_include_generated_columns()
{
// Act
object entity = new PropertyGenerated { Name = "Foo" };
var command = this.Sut.MakeInsertCommand(entity, this.GetTableSchema<PropertyGenerated>());
// Assert
var expected = new SqlCommand(@"
INSERT INTO [PropertyGenerated] ([Name])
VALUES (@Name);",
new PropertyGenerated { Name = "Foo" });
command.Should().Be(expected);
}
}
public class MakeInsertReturningIdentityStatement
: SqlServer2012DialectTests
{
[Fact]
public void Inserts_into_given_table()
{
// Act
var command = this.Sut.MakeInsertReturningPrimaryKeyCommand(new Dog { Name = "Foo", Age = 10 }, this.GetTableSchema<Dog>());
// Assert
var expected = new SqlCommand(@"
INSERT INTO [Dogs] ([Name], [Age])
VALUES (@Name, @Age);
SELECT CAST(SCOPE_IDENTITY() AS BIGINT) AS [id]",
new Dog { Name = "Foo", Age = 10 });
command.Should().Be(expected);
}
[Fact]
public void Adds_primary_key_if_its_not_generated_by_database()
{
// Act
var command = this.Sut.MakeInsertReturningPrimaryKeyCommand(new KeyNotGenerated { Id = 10, Name = "Foo" }, this.GetTableSchema<KeyNotGenerated>());
// Assert
var expected = new SqlCommand(@"
INSERT INTO [KeyNotGenerated] ([Id], [Name])
VALUES (@Id, @Name);
SELECT CAST(SCOPE_IDENTITY() AS BIGINT) AS [id]",
new KeyNotGenerated { Id = 10, Name = "Foo" });
command.Should().Be(expected);
}
[Fact]
public void Does_not_include_computed_columns()
{
// Act
var command = this.Sut.MakeInsertReturningPrimaryKeyCommand(new PropertyComputed { Name = "Foo" }, this.GetTableSchema<PropertyComputed>());
// Assert
var expected = new SqlCommand(@"
INSERT INTO [PropertyComputed] ([Name])
VALUES (@Name);
SELECT CAST(SCOPE_IDENTITY() AS BIGINT) AS [id]",
new PropertyComputed { Name = "Foo" });
command.Should().Be(expected);
}
[Fact]
public void Does_not_include_generated_columns()
{
// Act
var command = this.Sut.MakeInsertReturningPrimaryKeyCommand(new PropertyGenerated { Name = "Foo" }, this.GetTableSchema<PropertyGenerated>());
// Assert
var expected = new SqlCommand(@"
INSERT INTO [PropertyGenerated] ([Name])
VALUES (@Name);
SELECT CAST(SCOPE_IDENTITY() AS BIGINT) AS [id]",
new PropertyGenerated { Name = "Foo" });
command.Should().Be(expected);
}
}
public class MakeUpdateStatement
: SqlServer2012DialectTests
{
[Fact]
public void Updates_given_table()
{
// Act
var command = this.Sut.MakeUpdateCommand(new Dog { Id = 5, Name = "Foo", Age = 10 }, this.GetTableSchema<Dog>());
// Assert
var expected = new SqlCommand(@"
UPDATE [Dogs]
SET [Name] = @Name, [Age] = @Age
WHERE [Id] = @Id",
new Dog { Id = 5, Name = "Foo", Age = 10 });
command.Should().Be(expected);
}
[Fact]
public void Uses_each_key_in_composite_key()
{
// Act
var command = this.Sut.MakeUpdateCommand(new CompositeKeys { Key1 = 7, Key2 = 8, Name = "Foo" }, this.GetTableSchema<CompositeKeys>());
// Assert
var expected = new SqlCommand(@"
UPDATE [CompositeKeys]
SET [Name] = @Name
WHERE [Key1] = @Key1 AND [Key2] = @Key2",
new CompositeKeys { Key1 = 7, Key2 = 8, Name = "Foo" });
command.Should().Be(expected);
}
[Fact]
public void Does_not_update_primary_key_even_if_its_not_auto_generated()
{
// Act
var command = this.Sut.MakeUpdateCommand(new KeyNotGenerated { Id = 7, Name = "Foo" }, this.GetTableSchema<KeyNotGenerated>());
// Assert
var expected = new SqlCommand(@"
UPDATE [KeyNotGenerated]
SET [Name] = @Name
WHERE [Id] = @Id",
new KeyNotGenerated { Id = 7, Name = "Foo" });
command.Should().Be(expected);
}
[Fact]
public void Uses_aliased_property_names()
{
// Act
var command = this.Sut.MakeUpdateCommand(new PropertyAlias { Id = 5, Age = 10 }, this.GetTableSchema<PropertyAlias>());
// Assert
var expected = new SqlCommand(@"
UPDATE [PropertyAlias]
SET [YearsOld] = @Age
WHERE [Id] = @Id",
new PropertyAlias { Id = 5, Age = 10 });
command.Should().Be(expected);
}
[Fact]
public void Uses_aliased_key_name()
{
// Act
var command = this.Sut.MakeUpdateCommand(new KeyAlias { Name = "Foo", Id = 10 }, this.GetTableSchema<KeyAlias>());
// Assert
var expected = new SqlCommand(@"
UPDATE [KeyAlias]
SET [Name] = @Name
WHERE [Key] = @Id",
new KeyAlias { Name = "Foo", Id = 10 });
command.Should().Be(expected);
}
[Fact]
public void Uses_explicit_key_name()
{
// Act
var command = this.Sut.MakeUpdateCommand(new KeyExplicit { Name = "Foo", Key = 10 }, this.GetTableSchema<KeyExplicit>());
// Assert
var expected = new SqlCommand(@"
UPDATE [KeyExplicit]
SET [Name] = @Name
WHERE [Key] = @Key",
new KeyExplicit
{
Key = 10,
Name = "Foo"
});
command.Should().Be(expected);
}
[Fact]
public void Does_not_include_computed_columns()
{
// Act
var command = this.Sut.MakeUpdateCommand(new PropertyComputed { Name = "Foo", Id = 10 }, this.GetTableSchema<PropertyComputed>());
// Assert
var expected = new SqlCommand(@"
UPDATE [PropertyComputed]
SET [Name] = @Name
WHERE [Id] = @Id",
new PropertyComputed { Name = "Foo", Id = 10 });
command.Should().Be(expected);
}
[Fact]
public void Includes_generated_columns()
{
// Act
var command = this.Sut.MakeUpdateCommand(new PropertyGenerated { Id = 5, Name = "Foo", Created = new DateTime(2018, 4, 1) }, this.GetTableSchema<PropertyGenerated>());
// Assert
var expected = new SqlCommand(@"
UPDATE [PropertyGenerated]
SET [Name] = @Name, [Created] = @Created
WHERE [Id] = @Id",
new PropertyGenerated { Id = 5, Name = "Foo", Created = new DateTime(2018, 4, 1) });
command.Should().Be(expected);
}
}
public class MakeDeleteByPrimaryKeyStatement
: SqlServer2012DialectTests
{
[Fact]
public void Deletes_from_given_table()
{
// Act
var command = this.Sut.MakeDeleteByPrimaryKeyCommand(5, this.GetTableSchema<Dog>());
// Assert
var expected = new SqlCommand(@"
DELETE FROM [Dogs]
WHERE [Id] = @Id",
new Dictionary<string, object>
{
["Id"] = 5
});
command.Should().Be(expected);
}
[Fact]
public void Uses_each_key_in_composite_key()
{
// Act
var command = this.Sut.MakeDeleteByPrimaryKeyCommand(new { Key1 = 1, Key2 = 2 }, this.GetTableSchema<CompositeKeys>());
// Assert
var expected = new SqlCommand(@"
DELETE FROM [CompositeKeys]
WHERE [Key1] = @Key1 AND [Key2] = @Key2",
new { Key1 = 1, Key2 = 2 });
command.Should().Be(expected);
}
[Fact]
public void Uses_primary_key_even_if_its_not_auto_generated()
{
// Act
var command = this.Sut.MakeDeleteByPrimaryKeyCommand(5, this.GetTableSchema<KeyNotGenerated>());
// Assert
var expected = new SqlCommand(@"
DELETE FROM [KeyNotGenerated]
WHERE [Id] = @Id",
new Dictionary<string, object>
{
["Id"] = 5
});
command.Should().Be(expected);
}
[Fact]
public void Uses_aliased_key_name()
{
// Act
var command = this.Sut.MakeDeleteByPrimaryKeyCommand(5, this.GetTableSchema<KeyAlias>());
// Assert
var expected = new SqlCommand(@"
DELETE FROM [KeyAlias]
WHERE [Key] = @Id",
new Dictionary<string, object>
{
["Id"] = 5
});
command.Should().Be(expected);
}
[Fact]
public void Uses_explicit_key_name()
{
// Act
var command = this.Sut.MakeDeleteByPrimaryKeyCommand(5, this.GetTableSchema<KeyExplicit>());
// Assert
var expected = new SqlCommand(@"
DELETE FROM [KeyExplicit]
WHERE [Key] = @Key",
new Dictionary<string, object>
{
["Key"] = 5
});
command.Should().Be(expected);
}
}
public class MakeDeleteRangeStatement
: SqlServer2012DialectTests
{
[Fact]
public void Deletes_from_given_table()
{
// Act
var command = this.Sut.MakeDeleteRangeCommand("WHERE [Age] > @Age", new { Age = 10 }, this.GetTableSchema<Dog>());
// Assert
var expected = new SqlCommand(@"
DELETE FROM [Dogs]
WHERE [Age] > @Age",
new { Age = 10 });
command.Should().Be(expected);
}
}
public class MakeCreateTempTableStatement
: SqlServer2012DialectTests
{
private readonly Mock<ITableNameConvention> tableNameFactory;
public MakeCreateTempTableStatement()
{
this.tableNameFactory = new Mock<ITableNameConvention>();
var defaultTableNameFactory = new AtttributeTableNameConvention(new SqlServer2012NameEscaper());
this.tableNameFactory.Setup(f => f.GetTableName(It.IsAny<Type>()))
.Returns((Type type) => "[#" + defaultTableNameFactory.GetTableName(type).Substring(1));
this.config = this.config.AddSqlTypeMapping(typeof(DateTime), DbType.DateTime2).WithTableNameConvention(this.tableNameFactory.Object);
}
[Fact]
public void Throws_exception_when_tablename_doesnt_begin_with_a_hash()
{
// Arrange
this.tableNameFactory.Setup(f => f.GetTableName(It.IsAny<Type>()))
.Returns((Type type) => "table");
// Act
Assert.Throws<ArgumentException>(() => this.Sut.MakeCreateTempTableCommand(this.GetTableSchema<Dog>()));
}
[Fact]
public void Throws_exception_if_there_are_no_columns()
{
// Act
Assert.Throws<ArgumentException>(() => this.Sut.MakeCreateTempTableCommand(this.GetTableSchema<NoColumns>()));
}
}
public class MakeWhereClause
: SqlServer2012DialectTests
{
[Fact]
public void Returns_empty_string_when_conditions_is_empty()
{
// Arrange
var conditions = new { };
var conditionsSchema = this.GetConditionsSchema<Dog>(conditions);
// Act
var clause = this.Sut.MakeWhereClause(conditionsSchema, conditions);
// Assert
clause.Should().BeEmpty();
}
[Fact]
public void Selects_from_given_table()
{
// Arrange
var conditions = new { Name = "Fido" };
var conditionsSchema = this.GetConditionsSchema<Dog>(conditions);
// Act
var clause = this.Sut.MakeWhereClause(conditionsSchema, conditions);
// Assert
clause.Should().Be("WHERE [Name] = @Name");
}
[Fact]
public void Adds_alias_when_column_name_is_aliased()
{
// Arrange
var conditions = new { Age = 15 };
var conditionsSchema = this.GetConditionsSchema<PropertyAlias>(conditions);
// Act
var clause = this.Sut.MakeWhereClause(conditionsSchema, conditions);
// Assert
clause.Should().Be("WHERE [YearsOld] = @Age");
}
[Fact]
public void Checks_multiple_properties()
{
// Arrange
var conditions = new { Name = "Fido", Age = 15 };
var conditionsSchema = this.GetConditionsSchema<Dog>(conditions);
// Act
var clause = this.Sut.MakeWhereClause(conditionsSchema, conditions);
// Assert
clause.Should().Be("WHERE [Name] = @Name AND [Age] = @Age");
}
[Fact]
public void Checks_for_null_properly()
{
// Arrange
var conditions = new { Name = (string)null };
var conditionsSchema = this.GetConditionsSchema<Dog>(conditions);
// Act
var clause = this.Sut.MakeWhereClause(conditionsSchema, conditions);
// Assert
clause.Should().Be("WHERE [Name] IS NULL");
}
[Fact]
public void Checks_for_null_properly_with_multiple_properties()
{
// Arrange
var conditions = new { Name = (string)null, age = (int?)null };
var conditionsSchema = this.GetConditionsSchema<Dog>(conditions);
// Act
var clause = this.Sut.MakeWhereClause(conditionsSchema, conditions);
// Assert
clause.Should().Be("WHERE [Name] IS NULL AND [Age] IS NULL");
}
}
}
}
| |
/* Copyright (c) Citrix Systems 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
using System;
using System.ComponentModel;
using System.Drawing;
using XenAdmin.Controls;
using XenAdmin.Core;
using XenAPI;
using XenAdmin.Actions;
namespace XenAdmin.Dialogs
{
public partial class AttachDiskDialog : XenDialogBase
{
private readonly VM TheVM;
private DiskListVdiItem oldSelected = null;
private bool oldROState = false;
private readonly CollectionChangeEventHandler SR_CollectionChangedWithInvoke;
public AttachDiskDialog(VM vm) : base(vm.Connection)
{
TheVM = vm;
InitializeComponent();
DiskListTreeView.ShowCheckboxes = false;
DiskListTreeView.ShowDescription = true;
DiskListTreeView.ShowImages = true;
DiskListTreeView.SelectedIndexChanged += DiskListTreeView_SelectedIndexChanged;
SR_CollectionChangedWithInvoke = Program.ProgramInvokeHandler(SR_CollectionChanged);
connection.Cache.RegisterCollectionChanged<SR>(SR_CollectionChangedWithInvoke);
Pool poolofone = Helpers.GetPoolOfOne(connection);
if (poolofone != null)
poolofone.PropertyChanged += Server_Changed;
readonlyCheckboxToolTipContainer.SuppressTooltip = false;
DeactivateControlsForHvmVm();
BuildList();
DiskListTreeView_SelectedIndexChanged(null, null);
}
void SR_CollectionChanged(object sender, CollectionChangeEventArgs e)
{
Program.Invoke(this, BuildList);
}
private bool skipSelectedIndexChanged;
void DiskListTreeView_SelectedIndexChanged(object sender, EventArgs e)
{
if(skipSelectedIndexChanged)
return;
if (DiskListTreeView.SelectedItem is DiskListSrItem || DiskListTreeView.SelectedItem == null)
{
//As we're changing the index below - stall the SelectedIndexChanged event until we're done
skipSelectedIndexChanged = true;
try
{
DiskListTreeView.SelectedItem = oldSelected;
OkBtn.Enabled = DiskListTreeView.SelectedItem != null;
DeactivateAttachButtonIfHvm();
}
finally
{
//Ensure the lock is released
skipSelectedIndexChanged = false;
}
return;
}
DiskListVdiItem item = DiskListTreeView.SelectedItem as DiskListVdiItem;
ReadOnlyCheckBox.Enabled = !item.ForceReadOnly;
ReadOnlyCheckBox.Checked = item.ForceReadOnly ? true : oldROState;
OkBtn.Enabled = true;
oldSelected = item;
DeactivateControlsForHvmVm();
}
private void DeactivateControlsForHvmVm()
{
DeactivateReadOnlyCheckBoxForHvmVm();
DeactivateAttachButtonIfHvm();
}
private void DeactivateAttachButtonIfHvm()
{
if (!TheVM.IsHVM)
return;
DiskListVdiItem vdiItem = DiskListTreeView.SelectedItem as DiskListVdiItem;
if (vdiItem != null && vdiItem.ForceReadOnly)
OkBtn.Enabled = false;
}
private void DeactivateReadOnlyCheckBoxForHvmVm()
{
if (!TheVM.IsHVM)
return;
readonlyCheckboxToolTipContainer.SetToolTip(Messages.ATTACH_DISK_DIALOG_READONLY_DISABLED_FOR_HVM);
ReadOnlyCheckBox.Enabled = false;
}
private void BuildList()
{
Program.AssertOnEventThread();
DiskListVdiItem lastSelected = DiskListTreeView.SelectedItem as DiskListVdiItem;
String oldRef = "";
if (lastSelected != null)
oldRef = lastSelected.TheVDI.opaque_ref;
DiskListTreeView.BeginUpdate();
try
{
DiskListTreeView.ClearAllNodes();
foreach (SR sr in connection.Cache.SRs)
{
DiskListSrItem item = new DiskListSrItem(sr, TheVM);
if (item.Show)
{
DiskListTreeView.AddNode(item);
foreach (VDI TheVDI in sr.Connection.ResolveAllShownXenModelObjects(sr.VDIs, Properties.Settings.Default.ShowHiddenVMs))
{
DiskListVdiItem VDIitem = new DiskListVdiItem(TheVDI);
if (VDIitem.Show)
DiskListTreeView.AddChildNode(item, VDIitem);
TheVDI.PropertyChanged -= new PropertyChangedEventHandler(Server_Changed);
TheVDI.PropertyChanged += new PropertyChangedEventHandler(Server_Changed);
}
}
sr.PropertyChanged -= new PropertyChangedEventHandler(Server_Changed);
sr.PropertyChanged += new PropertyChangedEventHandler(Server_Changed);
}
}
finally
{
DiskListTreeView.EndUpdate();
DiskListTreeView.SelectedItem = SelectByRef(oldRef);
}
}
private object SelectByRef(string oldRef)
{
for (int i = 0; i < DiskListTreeView.Items.Count; i++)
{
DiskListVdiItem item = DiskListTreeView.Items[i] as DiskListVdiItem;
if (item == null)
continue;
else if (item.TheVDI.opaque_ref == oldRef)
return item;
}
return null;
}
private void Server_Changed(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "name_label" || e.PropertyName == "VDIs" || e.PropertyName == "VBDs" || e.PropertyName == "default_SR")
{
Program.Invoke(this, BuildList);
}
}
private void ReadOnlyCheckBox_CheckedChanged(object sender, EventArgs e)
{
if (ReadOnlyCheckBox.Enabled)
oldROState = ReadOnlyCheckBox.Checked;
}
private void OkBtn_Click(object sender, EventArgs e)
{
DiskListVdiItem item = DiskListTreeView.SelectedItem as DiskListVdiItem;
if (item == null)
return;
VDI TheVDI = item.TheVDI;
// Run this stuff off the event thread, since it involves a server call
System.Threading.ThreadPool.QueueUserWorkItem((System.Threading.WaitCallback)delegate(object o)
{
// Get a spare userdevice
string[] uds = VM.get_allowed_VBD_devices(connection.DuplicateSession(), TheVM.opaque_ref);
if (uds.Length == 0)
{
Program.Invoke(Program.MainWindow, delegate()
{
new ThreeButtonDialog(
new ThreeButtonDialog.Details(
SystemIcons.Error,
FriendlyErrorNames.VBDS_MAX_ALLOWED, Messages.DISK_ATTACH)).ShowDialog(Program.MainWindow);
});
// Give up
return;
}
string ud = uds[0];
VBD vbd = new VBD();
vbd.VDI = new XenRef<VDI>(TheVDI);
vbd.VM = new XenRef<VM>(TheVM);
vbd.bootable = ud == "0";
vbd.device = "";
vbd.IsOwner = TheVDI.VBDs.Count == 0;
vbd.empty = false;
vbd.userdevice = ud;
vbd.type = vbd_type.Disk;
vbd.mode = ReadOnlyCheckBox.Checked ? vbd_mode.RO : vbd_mode.RW;
vbd.unpluggable = true;
// Try to hot plug the VBD.
new VbdSaveAndPlugAction(TheVM, vbd, TheVDI.Name, null, false,NewDiskDialog.ShowMustRebootBoxCD,NewDiskDialog.ShowVBDWarningBox).RunAsync();
});
Close();
}
private void CancelBtn_Click(object sender, EventArgs e)
{
Close();
}
}
public class DiskListSrItem : CustomTreeNode
{
public enum DisabledReason { None, Broken, NotSeen };
public SR TheSR;
public VM TheVM;
public bool Show = false;
public DisabledReason Reason;
public DiskListSrItem(SR sr, VM vm)
: base(false)
{
TheSR = sr;
TheVM = vm;
Update();
}
private void Update()
{
Text = TheSR.NameWithoutHost;
Image = Images.GetImage16For(TheSR.GetIcon);
Host affinity = TheVM.Connection.Resolve<Host>(TheVM.affinity);
Host activeHost = TheVM.Connection.Resolve<Host>(TheVM.resident_on);
if (TheSR.content_type != SR.Content_Type_ISO && !((affinity != null && !TheSR.CanBeSeenFrom(affinity)) || (activeHost != null && TheVM.power_state == vm_power_state.Running && !TheSR.CanBeSeenFrom(activeHost)) || TheSR.IsBroken(false) || TheSR.PBDs.Count < 1))
{
Description = "";
Enabled = true;
Show = true;
Reason = DisabledReason.None;
}
else if (((affinity != null && !TheSR.CanBeSeenFrom(affinity)) || (activeHost != null && TheVM.power_state == vm_power_state.Running
&& !TheSR.CanBeSeenFrom(activeHost))) && !TheSR.IsBroken(false) && TheSR.PBDs.Count < 1)
{
Description = string.Format(Messages.SR_CANNOT_BE_SEEN, Helpers.GetName(affinity));
Enabled = false;
Show = true;
Reason = DisabledReason.NotSeen;
}
else if (TheSR.IsBroken(false) && TheSR.PBDs.Count >= 1)
{
Description = Messages.SR_IS_BROKEN;
Enabled = false;
Show = true;
Reason = DisabledReason.Broken;
}
else
{
Show = false;
}
}
protected override int SameLevelSortOrder(CustomTreeNode other)
{
DiskListSrItem otherItem = other as DiskListSrItem;
if (otherItem == null) //shouldnt ever happen!!!
return -1;
int rank = this.SrRank() - otherItem.SrRank();
if (rank == 0)
return base.SameLevelSortOrder(other);
else
return rank;
}
public int SrRank()
{
if (Enabled && TheSR.VDIs.Count > 0)
return 0;
else
return 1 + (int)Reason;
}
}
public class DiskListVdiItem : CustomTreeNode, IEquatable<DiskListVdiItem>
{
public VDI TheVDI;
public bool Show = false;
public bool ForceReadOnly = false;
public DiskListVdiItem(VDI vdi)
{
TheVDI = vdi;
Update();
}
private void Update()
{
if (TheVDI.type == vdi_type.crashdump || TheVDI.type == vdi_type.ephemeral || TheVDI.type == vdi_type.suspend)
Show = false;
else if ((TheVDI.VBDs.Count > 0 && !TheVDI.sharable))
{
bool allRO = true;
foreach (VBD vbd in TheVDI.Connection.ResolveAll<VBD>(TheVDI.VBDs))
{
if (!vbd.read_only&&vbd.currently_attached)
{
allRO = false;
break;
}
}
Show = allRO;
if (Show)
{
ForceReadOnly = true;
Text = String.IsNullOrEmpty(TheVDI.Name) ? Messages.NO_NAME : TheVDI.Name;
if (!string.IsNullOrEmpty(TheVDI.Description))
Description = string.Format(Messages.ATTACHDISK_SIZE_DESCRIPTION, TheVDI.Description, Util.DiskSizeString(TheVDI.virtual_size));
else
Description = Util.DiskSizeString(TheVDI.virtual_size);
Image = Properties.Resources._000_VirtualStorage_h32bit_16;
}
}
else
{
Show = true;
ForceReadOnly = TheVDI.read_only;
Text = String.IsNullOrEmpty(TheVDI.Name) ? Messages.NO_NAME : TheVDI.Name;
if (!string.IsNullOrEmpty(TheVDI.Description))
Description = string.Format(Messages.ATTACHDISK_SIZE_DESCRIPTION, TheVDI.Description, Util.DiskSizeString(TheVDI.virtual_size));
else
Description = Util.DiskSizeString(TheVDI.virtual_size);
Image = Properties.Resources._000_VirtualStorage_h32bit_16;
}
}
public bool Equals(DiskListVdiItem other)
{
return this.TheVDI.opaque_ref == other.TheVDI.opaque_ref;
}
}
}
| |
// Copyright (c) 2006-2007 Frank Laub
// 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.Collections.Generic;
using System.Text;
using System.IO;
using OpenSSL.Crypto;
namespace OpenSSL.Core
{
/// <summary>
/// Encapsulates the BIO_* functions.
/// </summary>
public class BIO : Base
{
#region Initialization
internal BIO(IntPtr ptr, bool owner) : base(ptr, owner) { }
/// <summary>
/// Calls BIO_new_mem_buf() from the specified buffer.
/// </summary>
/// <param name="buf"></param>
public BIO(byte[] buf)
: base(Native.ExpectNonNull(Native.BIO_new_mem_buf(buf, buf.Length)), true)
{
}
/// <summary>
/// Calls BIO_new_mem_buf() from the specified string.
/// </summary>
/// <param name="str"></param>
public BIO(string str)
: this(Encoding.ASCII.GetBytes(str))
{
}
/// <summary>
/// Calls BIO_new(BIO_s_mem())
/// </summary>
/// <param name="takeOwnership"></param>
/// <returns></returns>
public static BIO MemoryBuffer(bool takeOwnership)
{
IntPtr ptr = Native.ExpectNonNull(Native.BIO_new(Native.BIO_s_mem()));
return new BIO(ptr, takeOwnership);
}
/// <summary>
/// Factory method that calls BIO_new() with BIO_s_mem()
/// </summary>
/// <returns></returns>
public static BIO MemoryBuffer()
{
return MemoryBuffer(true);
}
/// <summary>
/// Factory method that calls BIO_new_file()
/// </summary>
/// <param name="filename"></param>
/// <param name="mode"></param>
/// <returns></returns>
public static BIO File(string filename, string mode)
{
IntPtr ptr = Native.ExpectNonNull(Native.BIO_new_file(filename, mode));
return new BIO(ptr, true);
}
private const int FD_STDIN = 0;
private const int FD_STDOUT = 1;
private const int FD_STDERR = 2;
/// <summary>
/// Factory method that calls BIO_new() with BIO_f_md()
/// </summary>
/// <param name="md"></param>
/// <returns></returns>
public static BIO MessageDigest(MessageDigest md)
{
IntPtr ptr = Native.ExpectNonNull(Native.BIO_new(Native.BIO_f_md()));
Native.BIO_set_md(ptr, md.Handle);
return new BIO(ptr, true);
}
//public static BIO MessageDigestContext(MessageDigestContext ctx)
//{
// IntPtr ptr = Native.ExpectNonNull(Native.BIO_new(Native.BIO_f_md()));
// //IntPtr ptr = Native.ExpectNonNull(Native.BIO_new(Native.BIO_f_null()));
// Native.BIO_set_md_ctx(ptr, ctx.Handle);
// return new BIO(ptr);
//}
#endregion
#region Properties
/// <summary>
/// Returns BIO_number_read()
/// </summary>
public uint NumberRead
{
get { return Native.BIO_number_read(this.Handle); }
}
/// <summary>
/// Returns BIO_number_written()
/// </summary>
public uint NumberWritten
{
get { return Native.BIO_number_written(this.Handle); }
}
/// <summary>
/// Returns number of bytes buffered in the BIO - calls BIO_ctrl_pending
/// </summary>
public uint BytesPending
{
get { return Native.BIO_ctrl_pending(this.Handle); }
}
#endregion
#region Methods
/// <summary>
/// BIO Close Options
/// </summary>
public enum CloseOption
{
/// <summary>
/// Don't close on free
/// </summary>
NoClose = 0,
/// <summary>
/// Close on freee
/// </summary>
Close = 1
}
/// <summary>
/// Calls BIO_set_close()
/// </summary>
/// <param name="opt"></param>
public void SetClose(CloseOption opt)
{
Native.BIO_set_close(this.ptr, (int)opt);
}
/// <summary>
/// Calls BIO_push()
/// </summary>
/// <param name="bio"></param>
public void Push(BIO bio)
{
Native.ExpectNonNull(Native.BIO_push(this.ptr, bio.Handle));
}
/// <summary>
/// Calls BIO_write()
/// </summary>
/// <param name="buf"></param>
public void Write(byte[] buf)
{
if (Native.BIO_write(this.ptr, buf, buf.Length) != buf.Length)
throw new OpenSslException();
}
/// <summary>
/// Calls BIO_write()
/// </summary>
/// <param name="buf"></param>
/// <param name="len"></param>
public void Write(byte[] buf, int len)
{
if (Native.BIO_write(this.ptr, buf, len) != len)
throw new OpenSslException();
}
/// <summary>
/// Calls BIO_write()
/// </summary>
/// <param name="value"></param>
public void Write(byte value)
{
byte[] buf = new byte[1];
buf[0] = value;
Write(buf);
}
/// <summary>
/// Calls BIO_write()
/// </summary>
/// <param name="value"></param>
public void Write(ushort value)
{
MemoryStream ms = new MemoryStream();
BinaryWriter br = new BinaryWriter(ms);
br.Write(value);
byte[] buf = ms.ToArray();
Write(buf);
}
/// <summary>
/// Calls BIO_write()
/// </summary>
/// <param name="value"></param>
public void Write(uint value)
{
MemoryStream ms = new MemoryStream();
BinaryWriter br = new BinaryWriter(ms);
br.Write(value);
byte[] buf = ms.ToArray();
Write(buf);
}
/// <summary>
/// Calls BIO_puts()
/// </summary>
/// <param name="str"></param>
public void Write(string str)
{
byte[] buf = Encoding.ASCII.GetBytes(str);
if (Native.BIO_puts(this.ptr, buf) != buf.Length)
throw new OpenSslException();
}
/// <summary>
/// Calls BIO_read()
/// </summary>
/// <param name="count"></param>
/// <returns></returns>
public ArraySegment<byte> ReadBytes(int count)
{
byte[] buf = new byte[count];
int ret = Native.BIO_read(this.ptr, buf, buf.Length);
if (ret < 0)
throw new OpenSslException();
return new ArraySegment<byte>(buf, 0, ret);
}
/// <summary>
/// Calls BIO_gets()
/// </summary>
/// <returns></returns>
public string ReadString()
{
StringBuilder sb = new StringBuilder();
const int BLOCK_SIZE = 64;
byte[] buf = new byte[BLOCK_SIZE];
int ret = 0;
while (true)
{
ret = Native.BIO_gets(this.ptr, buf, buf.Length);
if (ret == 0)
break;
if (ret < 0)
throw new OpenSslException();
sb.Append(Encoding.ASCII.GetString(buf, 0, ret));
}
return sb.ToString();
}
/// <summary>
/// Returns the MessageDigestContext if this BIO's type if BIO_f_md()
/// </summary>
/// <returns></returns>
public MessageDigestContext GetMessageDigestContext()
{
return new MessageDigestContext(this);
}
#endregion
#region Overrides
/// <summary>
/// Calls BIO_free()
/// </summary>
protected override void OnDispose()
{
Native.BIO_free(this.ptr);
}
#endregion
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Data;
using System.Reflection;
using log4net;
using RegionFlags = OpenSim.Framework.RegionFlags;
namespace OpenSim.Data.Null
{
public class NullRegionData : IRegionData
{
private static NullRegionData Instance = null;
/// <summary>
/// Should we use the static instance for all invocations?
/// </summary>
private bool m_useStaticInstance = true;
// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
Dictionary<UUID, RegionData> m_regionData = new Dictionary<UUID, RegionData>();
public NullRegionData(string connectionString, string realm)
{
// m_log.DebugFormat(
// "[NULL REGION DATA]: Constructor got connectionString {0}, realm {1}", connectionString, realm);
// The !static connection string is a hack so that regression tests can use this module without a high degree of fragility
// in having to deal with the static reference in the once-loaded NullRegionData class.
//
// In standalone operation, we have to use only one instance of this class since the login service and
// simulator have no other way of using a common data store.
if (connectionString == "!static")
m_useStaticInstance = false;
else if (Instance == null)
Instance = this;
}
private delegate bool Matcher(string value);
public List<RegionData> Get(string regionName, UUID scopeID)
{
if (m_useStaticInstance && Instance != this)
return Instance.Get(regionName, scopeID);
// m_log.DebugFormat("[NULL REGION DATA]: Getting region {0}, scope {1}", regionName, scopeID);
string cleanName = regionName.ToLower();
// Handle SQL wildcards
const string wildcard = "%";
bool wildcardPrefix = false;
bool wildcardSuffix = false;
if (cleanName.Equals(wildcard))
{
wildcardPrefix = wildcardSuffix = true;
cleanName = string.Empty;
}
else
{
if (cleanName.StartsWith(wildcard))
{
wildcardPrefix = true;
cleanName = cleanName.Substring(1);
}
if (regionName.EndsWith(wildcard))
{
wildcardSuffix = true;
cleanName = cleanName.Remove(cleanName.Length - 1);
}
}
Matcher queryMatch;
if (wildcardPrefix && wildcardSuffix)
queryMatch = delegate(string s) { return s.Contains(cleanName); };
else if (wildcardSuffix)
queryMatch = delegate(string s) { return s.StartsWith(cleanName); };
else if (wildcardPrefix)
queryMatch = delegate(string s) { return s.EndsWith(cleanName); };
else
queryMatch = delegate(string s) { return s.Equals(cleanName); };
// Find region data
List<RegionData> ret = new List<RegionData>();
lock (m_regionData)
{
foreach (RegionData r in m_regionData.Values)
{
// m_log.DebugFormat("[NULL REGION DATA]: comparing {0} to {1}", cleanName, r.RegionName.ToLower());
if (queryMatch(r.RegionName.ToLower()))
ret.Add(r);
}
}
if (ret.Count > 0)
return ret;
return null;
}
public RegionData Get(int posX, int posY, UUID scopeID)
{
if (m_useStaticInstance && Instance != this)
return Instance.Get(posX, posY, scopeID);
List<RegionData> ret = new List<RegionData>();
lock (m_regionData)
{
foreach (RegionData r in m_regionData.Values)
{
if (r.posX == posX && r.posY == posY)
ret.Add(r);
}
}
if (ret.Count > 0)
return ret[0];
return null;
}
public RegionData Get(UUID regionID, UUID scopeID)
{
if (m_useStaticInstance && Instance != this)
return Instance.Get(regionID, scopeID);
lock (m_regionData)
{
if (m_regionData.ContainsKey(regionID))
return m_regionData[regionID];
}
return null;
}
public List<RegionData> Get(int startX, int startY, int endX, int endY, UUID scopeID)
{
if (m_useStaticInstance && Instance != this)
return Instance.Get(startX, startY, endX, endY, scopeID);
List<RegionData> ret = new List<RegionData>();
lock (m_regionData)
{
foreach (RegionData r in m_regionData.Values)
{
if (r.posX >= startX && r.posX <= endX && r.posY >= startY && r.posY <= endY)
ret.Add(r);
}
}
return ret;
}
public bool Store(RegionData data)
{
if (m_useStaticInstance && Instance != this)
return Instance.Store(data);
// m_log.DebugFormat(
// "[NULL REGION DATA]: Storing region {0} {1}, scope {2}", data.RegionName, data.RegionID, data.ScopeID);
lock (m_regionData)
{
m_regionData[data.RegionID] = data;
}
return true;
}
public bool SetDataItem(UUID regionID, string item, string value)
{
if (m_useStaticInstance && Instance != this)
return Instance.SetDataItem(regionID, item, value);
lock (m_regionData)
{
if (!m_regionData.ContainsKey(regionID))
return false;
m_regionData[regionID].Data[item] = value;
}
return true;
}
public bool Delete(UUID regionID)
{
if (m_useStaticInstance && Instance != this)
return Instance.Delete(regionID);
// m_log.DebugFormat("[NULL REGION DATA]: Deleting region {0}", regionID);
lock (m_regionData)
{
if (!m_regionData.ContainsKey(regionID))
return false;
m_regionData.Remove(regionID);
}
return true;
}
public List<RegionData> GetDefaultRegions(UUID scopeID)
{
return Get((int)RegionFlags.DefaultRegion, scopeID);
}
public List<RegionData> GetFallbackRegions(UUID scopeID, int x, int y)
{
List<RegionData> regions = Get((int)RegionFlags.FallbackRegion, scopeID);
RegionDataDistanceCompare distanceComparer = new RegionDataDistanceCompare(x, y);
regions.Sort(distanceComparer);
return regions;
}
public List<RegionData> GetHyperlinks(UUID scopeID)
{
return Get((int)RegionFlags.Hyperlink, scopeID);
}
private List<RegionData> Get(int regionFlags, UUID scopeID)
{
if (Instance != this)
return Instance.Get(regionFlags, scopeID);
List<RegionData> ret = new List<RegionData>();
lock (m_regionData)
{
foreach (RegionData r in m_regionData.Values)
{
if ((Convert.ToInt32(r.Data["flags"]) & regionFlags) != 0)
ret.Add(r);
}
}
return ret;
}
}
}
| |
//
// X509CertificateBuilder.cs: Handles building of X.509 certificates.
//
// Author:
// Sebastien Pouliot <[email protected]>
//
// (C) 2003 Motus Technologies Inc. (http://www.motus.com)
// (C) 2004 Novell (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.Security.Cryptography;
namespace Mono.Security.X509 {
// From RFC3280
/*
* Certificate ::= SEQUENCE {
* tbsCertificate TBSCertificate,
* signatureAlgorithm AlgorithmIdentifier,
* signature BIT STRING
* }
* TBSCertificate ::= SEQUENCE {
* version [0] Version DEFAULT v1,
* serialNumber CertificateSerialNumber,
* signature AlgorithmIdentifier,
* issuer Name,
* validity Validity,
* subject Name,
* subjectPublicKeyInfo SubjectPublicKeyInfo,
* issuerUniqueID [1] IMPLICIT UniqueIdentifier OPTIONAL,
* -- If present, version MUST be v2 or v3
* subjectUniqueID [2] IMPLICIT UniqueIdentifier OPTIONAL,
* -- If present, version MUST be v2 or v3
* extensions [3] Extensions OPTIONAL
* -- If present, version MUST be v3 --
* }
* Version ::= INTEGER { v1(0), v2(1), v3(2) }
* CertificateSerialNumber ::= INTEGER
* Validity ::= SEQUENCE {
* notBefore Time,
* notAfter Time
* }
* Time ::= CHOICE {
* utcTime UTCTime,
* generalTime GeneralizedTime
* }
*/
public class X509CertificateBuilder : X509Builder {
private byte version;
private byte[] sn;
private string issuer;
private DateTime notBefore;
private DateTime notAfter;
private string subject;
private AsymmetricAlgorithm aa;
private byte[] issuerUniqueID;
private byte[] subjectUniqueID;
private X509ExtensionCollection extensions;
public X509CertificateBuilder () : this (3) {}
public X509CertificateBuilder (byte version)
{
if (version > 3)
throw new ArgumentException ("Invalid certificate version");
this.version = version;
extensions = new X509ExtensionCollection ();
}
public byte Version {
get { return version; }
set { version = value; }
}
public byte[] SerialNumber {
get { return sn; }
set { sn = value; }
}
public string IssuerName {
get { return issuer; }
set { issuer = value; }
}
public DateTime NotBefore {
get { return notBefore; }
set { notBefore = value; }
}
public DateTime NotAfter {
get { return notAfter; }
set { notAfter = value; }
}
public string SubjectName {
get { return subject; }
set { subject = value; }
}
public AsymmetricAlgorithm SubjectPublicKey {
get { return aa; }
set { aa = value; }
}
public byte[] IssuerUniqueId {
get { return issuerUniqueID; }
set { issuerUniqueID = value; }
}
public byte[] SubjectUniqueId {
get { return subjectUniqueID; }
set { subjectUniqueID = value; }
}
public X509ExtensionCollection Extensions {
get { return extensions; }
}
/* SubjectPublicKeyInfo ::= SEQUENCE {
* algorithm AlgorithmIdentifier,
* subjectPublicKey BIT STRING }
*/
private ASN1 SubjectPublicKeyInfo ()
{
ASN1 keyInfo = new ASN1 (0x30);
if (aa is RSA) {
keyInfo.Add (PKCS7.AlgorithmIdentifier ("1.2.840.113549.1.1.1"));
RSAParameters p = (aa as RSA).ExportParameters (false);
/* RSAPublicKey ::= SEQUENCE {
* modulus INTEGER, -- n
* publicExponent INTEGER } -- e
*/
ASN1 key = new ASN1 (0x30);
key.Add (ASN1Convert.FromUnsignedBigInteger (p.Modulus));
key.Add (ASN1Convert.FromUnsignedBigInteger (p.Exponent));
keyInfo.Add (new ASN1 (UniqueIdentifier (key.GetBytes ())));
}
else if (aa is DSA) {
DSAParameters p = (aa as DSA).ExportParameters (false);
/* Dss-Parms ::= SEQUENCE {
* p INTEGER,
* q INTEGER,
* g INTEGER }
*/
ASN1 param = new ASN1 (0x30);
param.Add (ASN1Convert.FromUnsignedBigInteger (p.P));
param.Add (ASN1Convert.FromUnsignedBigInteger (p.Q));
param.Add (ASN1Convert.FromUnsignedBigInteger (p.G));
keyInfo.Add (PKCS7.AlgorithmIdentifier ("1.2.840.10040.4.1", param));
ASN1 key = keyInfo.Add (new ASN1 (0x03));
// DSAPublicKey ::= INTEGER -- public key, y
key.Add (ASN1Convert.FromUnsignedBigInteger (p.Y));
}
else
throw new NotSupportedException ("Unknown Asymmetric Algorithm " + aa.ToString ());
return keyInfo;
}
private byte[] UniqueIdentifier (byte[] id)
{
// UniqueIdentifier ::= BIT STRING
ASN1 uid = new ASN1 (0x03);
// first byte in a BITSTRING is the number of unused bits in the first byte
byte[] v = new byte [id.Length + 1];
Buffer.BlockCopy (id, 0, v, 1, id.Length);
uid.Value = v;
return uid.GetBytes ();
}
protected override ASN1 ToBeSigned (string oid)
{
// TBSCertificate
ASN1 tbsCert = new ASN1 (0x30);
if (version > 1) {
// TBSCertificate / [0] Version DEFAULT v1,
byte[] ver = { (byte)(version - 1) };
ASN1 v = tbsCert.Add (new ASN1 (0xA0));
v.Add (new ASN1 (0x02, ver));
}
// TBSCertificate / CertificateSerialNumber,
tbsCert.Add (new ASN1 (0x02, sn));
// TBSCertificate / AlgorithmIdentifier,
tbsCert.Add (PKCS7.AlgorithmIdentifier (oid));
// TBSCertificate / Name
tbsCert.Add (X501.FromString (issuer));
// TBSCertificate / Validity
ASN1 validity = tbsCert.Add (new ASN1 (0x30));
// TBSCertificate / Validity / Time
validity.Add (ASN1Convert.FromDateTime (notBefore));
// TBSCertificate / Validity / Time
validity.Add (ASN1Convert.FromDateTime (notAfter));
// TBSCertificate / Name
tbsCert.Add (X501.FromString (subject));
// TBSCertificate / SubjectPublicKeyInfo
tbsCert.Add (SubjectPublicKeyInfo ());
if (version > 1) {
// TBSCertificate / [1] IMPLICIT UniqueIdentifier OPTIONAL
if (issuerUniqueID != null)
tbsCert.Add (new ASN1 (0xA1, UniqueIdentifier (issuerUniqueID)));
// TBSCertificate / [2] IMPLICIT UniqueIdentifier OPTIONAL
if (subjectUniqueID != null)
tbsCert.Add (new ASN1 (0xA1, UniqueIdentifier (subjectUniqueID)));
// TBSCertificate / [3] Extensions OPTIONAL
if ((version > 2) && (extensions.Count > 0))
tbsCert.Add (new ASN1 (0xA3, extensions.GetBytes ()));
}
return tbsCert;
}
}
}
| |
using System.Diagnostics;
using Microsoft.Msagl.Core.Geometry.Curves;
namespace Microsoft.Msagl.Core.Geometry {
/// <summary>
/// Clusters can (optionally) have a rectangular border which is respected by overlap avoidance.
/// Currently, this is controlled by FastIncrementalLayoutSettings.RectangularClusters.
/// If FastIncrementalLayoutSettings.RectangularClusters is true, then the
/// FastIncrementalLayout constructor will create a RectangularBoundary in each cluster.
/// Otherwise it will be null.
/// </summary>
public class RectangularClusterBoundary {
/// <summary>
/// Set margins to zero which also initializes other members.
/// </summary>
public RectangularClusterBoundary() {
this.LeftBorderInfo = new BorderInfo(0.0);
this.RightBorderInfo = new BorderInfo(0.0);
this.TopBorderInfo = new BorderInfo(0.0);
this.BottomBorderInfo = new BorderInfo(0.0);
}
internal Rectangle rectangle; // Used only for RectangularHull
internal OverlapRemovalCluster olapCluster; // For use with RectangularHull only, and only valid during verletIntegration()
/// <summary>
/// Left margin of this cluster (additional space inside the cluster border).
/// </summary>
public double LeftMargin {
get { return this.LeftBorderInfo.InnerMargin; }
set { this.LeftBorderInfo = new BorderInfo(value, this.LeftBorderInfo.FixedPosition, this.LeftBorderInfo.Weight); }
}
/// <summary>
/// Right margin of this cluster (additional space inside the cluster border).
/// </summary>
public double RightMargin {
get { return this.RightBorderInfo.InnerMargin; }
set { this.RightBorderInfo = new BorderInfo(value, this.RightBorderInfo.FixedPosition, this.RightBorderInfo.Weight); }
}
/// <summary>
/// Top margin of this cluster (additional space inside the cluster border).
/// </summary>
public double TopMargin {
get { return this.TopBorderInfo.InnerMargin; }
set { this.TopBorderInfo = new BorderInfo(value, this.TopBorderInfo.FixedPosition, this.TopBorderInfo.Weight); }
}
/// <summary>
/// Bottom margin of this cluster (additional space inside the cluster border).
/// </summary>
public double BottomMargin {
get { return this.BottomBorderInfo.InnerMargin; }
set { this.BottomBorderInfo = new BorderInfo(value, this.BottomBorderInfo.FixedPosition, this.BottomBorderInfo.Weight); }
}
/// <summary>
/// Information for the Left border of the cluster.
/// </summary>
public BorderInfo LeftBorderInfo { get; set; }
/// <summary>
/// Information for the Right border of the cluster.
/// </summary>
public BorderInfo RightBorderInfo { get; set; }
/// <summary>
/// Information for the Top border of the cluster.
/// </summary>
public BorderInfo TopBorderInfo { get; set; }
/// <summary>
/// Information for the Bottom border of the cluster.
/// </summary>
public BorderInfo BottomBorderInfo { get; set; }
/// <summary>
/// When this is set, the OverlapRemovalCluster will generate equality constraints rather than inequalities
/// to keep its children within its bounds.
/// </summary>
public bool GenerateFixedConstraints
{
get;
set;
}
bool generateFixedConstraintsDefault;
/// <summary>
/// The default value that GenerateFixedConstraints will be reverted to when a lock is released
/// </summary>
public bool GenerateFixedConstraintsDefault
{
get
{
return generateFixedConstraintsDefault;
}
set
{
GenerateFixedConstraints = generateFixedConstraintsDefault = value;
}
}
/// <summary>
/// The rectangular hull of all the points of all the nodes in the cluster, as set by
/// ProjectionSolver.Solve().
/// Note: This rectangle may not originate at the barycenter. Drawing uses only the results
/// of this function; the barycenter is used only for gravity computations.
/// </summary>
/// <returns></returns>
public ICurve RectangularHull() {
Debug.Assert(rectangle.Bottom <= rectangle.Top);
if (RadiusX > 0 || RadiusY > 0)
{
return CurveFactory.CreateRectangleWithRoundedCorners(rectangle.Width, rectangle.Height, RadiusX, RadiusY, rectangle.Center);
}
else
{
return CurveFactory.CreateRectangle(rectangle.Width, rectangle.Height, rectangle.Center);
}
}
/// <summary>
/// Will only return something useful if FastIncrementalLayoutSettings.AvoidOverlaps is true.
/// </summary>
public Rectangle Rect {
get {
return rectangle;
}
set
{
rectangle = value;
}
}
/// <summary>
/// Returns (bounding) Rect with margins subtracted
/// </summary>
public Rectangle InnerRect
{
get
{
var outer = Rect;
var inner = new Rectangle(outer.Left + LeftMargin, outer.Bottom + BottomMargin,
outer.Right - RightMargin, outer.Top - TopMargin);
return inner;
}
}
class Margin
{
public double Left;
public double Right;
public double Top;
public double Bottom;
}
Margin defaultMargin;
internal bool DefaultMarginIsSet {
get { return defaultMargin!=null; }
}
/// <summary>
/// The default margin stored by StoreDefaultMargin
/// </summary>
public double DefaultLeftMargin
{
get
{
return defaultMargin.Left;
}
}
/// <summary>
/// The default margin stored by StoreDefaultMargin
/// </summary>
public double DefaultTopMargin
{
get
{
return defaultMargin.Top;
}
}
/// <summary>
/// The default margin stored by StoreDefaultMargin
/// </summary>
public double DefaultRightMargin
{
get
{
return defaultMargin.Right;
}
}
/// <summary>
/// The default margin stored by StoreDefaultMargin
/// </summary>
public double DefaultBottomMargin
{
get
{
return defaultMargin.Bottom;
}
}
/// <summary>
/// store a the current margin as the default which we can revert to later with the RestoreDefaultMargin
/// </summary>
public void StoreDefaultMargin()
{
defaultMargin = new Margin { Left = LeftMargin, Right = RightMargin, Bottom = BottomMargin, Top = TopMargin };
}
/// <summary>
/// store a default margin which we can revert to later with the RestoreDefaultMargin
/// </summary>
public void StoreDefaultMargin(double left, double right, double bottom, double top)
{
defaultMargin = new Margin { Left = left, Right = right, Bottom = bottom, Top = top };
}
/// <summary>
/// revert to a previously stored default margin
/// </summary>
public void RestoreDefaultMargin()
{
if (defaultMargin != null)
{
LeftMargin = defaultMargin.Left;
RightMargin = defaultMargin.Right;
TopMargin = defaultMargin.Top;
BottomMargin = defaultMargin.Bottom;
}
}
/// <summary>
/// Move the bounding box by delta
/// </summary>
/// <param name="delta"></param>
public void TranslateRectangle(Point delta)
{
rectangle = new Rectangle(rectangle.Left + delta.X, rectangle.Bottom + delta.Y, new Point(rectangle.Width, rectangle.Height));
}
/// <summary>
/// Radius on the X axis
/// </summary>
public double RadiusX { get; set; }
/// <summary>
/// Radius on the Y axis
/// </summary>
public double RadiusY { get; set; }
/// <summary>
/// Creates a lock on all four borders
/// </summary>
/// <param name="left"></param>
/// <param name="right"></param>
/// <param name="top"></param>
/// <param name="bottom"></param>
public void Lock(double left, double right, double top, double bottom) {
double weight = 1e4;
LeftBorderInfo = new BorderInfo(LeftBorderInfo.InnerMargin, left, weight);
RightBorderInfo = new BorderInfo(RightBorderInfo.InnerMargin, right, weight);
TopBorderInfo = new BorderInfo(TopBorderInfo.InnerMargin, top, weight);
BottomBorderInfo = new BorderInfo(BottomBorderInfo.InnerMargin, bottom, weight);
}
/// <summary>
/// Releases the lock on all four borders
/// </summary>
public void Unlock() {
LeftBorderInfo = new BorderInfo(LeftBorderInfo.InnerMargin);
RightBorderInfo = new BorderInfo(RightBorderInfo.InnerMargin);
TopBorderInfo = new BorderInfo(TopBorderInfo.InnerMargin);
BottomBorderInfo = new BorderInfo(BottomBorderInfo.InnerMargin);
}
/// <summary>
/// Locks all four borders at their current positions
/// </summary>
public void Lock() {
Lock(rectangle.Left, rectangle.Right, rectangle.Top, rectangle.Bottom);
}
/// <summary>
/// boundary can shrink no more than this
/// </summary>
public double MinWidth
{
get;
set;
}
/// <summary>
/// boundary can shrink no more than this
/// </summary>
public double MinHeight
{
get;
set;
}
}
}
| |
//*********************************************************//
// Copyright (c) Microsoft. All rights reserved.
//
// Apache 2.0 License
//
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
// implied. See the License for the specific language governing
// permissions and limitations under the License.
//
//*********************************************************//
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
using Microsoft.VisualStudio.Shell.Interop;
using VSLangProj;
using ErrorHandler = Microsoft.VisualStudio.ErrorHandler;
namespace Microsoft.VisualStudioTools.Project.Automation
{
/// <summary>
/// Represents the automation object for the equivalent ReferenceContainerNode object
/// </summary>
[ComVisible(true)]
public class OAReferences : ConnectionPointContainer,
IEventSource<_dispReferencesEvents>,
References,
ReferencesEvents
{
private readonly ProjectNode _project;
private ReferenceContainerNode _container;
/// <summary>
/// Creates a new automation references object. If the project type doesn't
/// support references containerNode is null.
/// </summary>
/// <param name="containerNode"></param>
/// <param name="project"></param>
internal OAReferences(ReferenceContainerNode containerNode, ProjectNode project)
{
_container = containerNode;
_project = project;
AddEventSource<_dispReferencesEvents>(this as IEventSource<_dispReferencesEvents>);
if (_container != null) {
_container.OnChildAdded += new EventHandler<HierarchyNodeEventArgs>(OnReferenceAdded);
_container.OnChildRemoved += new EventHandler<HierarchyNodeEventArgs>(OnReferenceRemoved);
}
}
#region Private Members
private Reference AddFromSelectorData(VSCOMPONENTSELECTORDATA selector)
{
if (_container == null) {
return null;
}
ReferenceNode refNode = _container.AddReferenceFromSelectorData(selector);
if (null == refNode)
{
return null;
}
return refNode.Object as Reference;
}
private Reference FindByName(string stringIndex)
{
foreach (Reference refNode in this)
{
if (0 == string.Compare(refNode.Name, stringIndex, StringComparison.Ordinal))
{
return refNode;
}
}
return null;
}
#endregion
#region References Members
public Reference Add(string bstrPath)
{
// ignore requests from the designer which are framework assemblies and start w/ a *.
if (string.IsNullOrEmpty(bstrPath) || bstrPath.StartsWith("*"))
{
return null;
}
VSCOMPONENTSELECTORDATA selector = new VSCOMPONENTSELECTORDATA();
selector.type = VSCOMPONENTTYPE.VSCOMPONENTTYPE_File;
selector.bstrFile = bstrPath;
return AddFromSelectorData(selector);
}
public Reference AddActiveX(string bstrTypeLibGuid, int lMajorVer, int lMinorVer, int lLocaleId, string bstrWrapperTool)
{
VSCOMPONENTSELECTORDATA selector = new VSCOMPONENTSELECTORDATA();
selector.type = VSCOMPONENTTYPE.VSCOMPONENTTYPE_Com2;
selector.guidTypeLibrary = new Guid(bstrTypeLibGuid);
selector.lcidTypeLibrary = (uint)lLocaleId;
selector.wTypeLibraryMajorVersion = (ushort)lMajorVer;
selector.wTypeLibraryMinorVersion = (ushort)lMinorVer;
return AddFromSelectorData(selector);
}
public Reference AddProject(EnvDTE.Project project)
{
if (null == project || _container == null)
{
return null;
}
// Get the soulution.
IVsSolution solution = _container.ProjectMgr.Site.GetService(typeof(SVsSolution)) as IVsSolution;
if (null == solution)
{
return null;
}
// Get the hierarchy for this project.
IVsHierarchy projectHierarchy;
ErrorHandler.ThrowOnFailure(solution.GetProjectOfUniqueName(project.UniqueName, out projectHierarchy));
// Create the selector data.
VSCOMPONENTSELECTORDATA selector = new VSCOMPONENTSELECTORDATA();
selector.type = VSCOMPONENTTYPE.VSCOMPONENTTYPE_Project;
// Get the project reference string.
ErrorHandler.ThrowOnFailure(solution.GetProjrefOfProject(projectHierarchy, out selector.bstrProjRef));
selector.bstrTitle = project.Name;
selector.bstrFile = System.IO.Path.GetDirectoryName(project.FullName);
return AddFromSelectorData(selector);
}
public EnvDTE.Project ContainingProject
{
get
{
return _project.GetAutomationObject() as EnvDTE.Project;
}
}
public int Count
{
get
{
if (_container == null)
{
return 0;
}
return _container.EnumReferences().Count;
}
}
public EnvDTE.DTE DTE
{
get
{
return _project.Site.GetService(typeof(EnvDTE.DTE)) as EnvDTE.DTE;
}
}
public Reference Find(string bstrIdentity)
{
if (string.IsNullOrEmpty(bstrIdentity))
{
return null;
}
foreach (Reference refNode in this)
{
if (null != refNode)
{
if (0 == string.Compare(bstrIdentity, refNode.Identity, StringComparison.Ordinal))
{
return refNode;
}
}
}
return null;
}
public IEnumerator GetEnumerator()
{
if (_container == null) {
return new List<Reference>().GetEnumerator();
}
List<Reference> references = new List<Reference>();
IEnumerator baseEnum = _container.EnumReferences().GetEnumerator();
if (null == baseEnum)
{
return references.GetEnumerator();
}
while (baseEnum.MoveNext())
{
ReferenceNode refNode = baseEnum.Current as ReferenceNode;
if (null == refNode)
{
continue;
}
Reference reference = refNode.Object as Reference;
if (null != reference)
{
references.Add(reference);
}
}
return references.GetEnumerator();
}
public Reference Item(object index)
{
if (_container == null)
{
throw new ArgumentOutOfRangeException("index");
}
string stringIndex = index as string;
if (null != stringIndex)
{
return FindByName(stringIndex);
}
// Note that this cast will throw if the index is not convertible to int.
int intIndex = (int)index;
IList<ReferenceNode> refs = _container.EnumReferences();
if (null == refs)
{
throw new ArgumentOutOfRangeException("index");
}
if ((intIndex <= 0) || (intIndex > refs.Count))
{
throw new ArgumentOutOfRangeException("index");
}
// Let the implementation of IList<> throw in case of index not correct.
return refs[intIndex - 1].Object as Reference;
}
public object Parent
{
get
{
if (_container == null)
{
return _project.Object;
}
return _container.Parent.Object;
}
}
#endregion
#region _dispReferencesEvents_Event Members
public event _dispReferencesEvents_ReferenceAddedEventHandler ReferenceAdded;
public event _dispReferencesEvents_ReferenceChangedEventHandler ReferenceChanged {
add { }
remove { }
}
public event _dispReferencesEvents_ReferenceRemovedEventHandler ReferenceRemoved;
#endregion
#region Callbacks for the HierarchyNode events
private void OnReferenceAdded(object sender, HierarchyNodeEventArgs args)
{
// Validate the parameters.
if ((_container != sender as ReferenceContainerNode) ||
(null == args) || (null == args.Child))
{
return;
}
// Check if there is any sink for this event.
if (null == ReferenceAdded)
{
return;
}
// Check that the removed item implements the Reference interface.
Reference reference = args.Child.Object as Reference;
if (null != reference)
{
ReferenceAdded(reference);
}
}
private void OnReferenceRemoved(object sender, HierarchyNodeEventArgs args)
{
// Validate the parameters.
if ((_container != sender as ReferenceContainerNode) ||
(null == args) || (null == args.Child))
{
return;
}
// Check if there is any sink for this event.
if (null == ReferenceRemoved)
{
return;
}
// Check that the removed item implements the Reference interface.
Reference reference = args.Child.Object as Reference;
if (null != reference)
{
ReferenceRemoved(reference);
}
}
#endregion
#region IEventSource<_dispReferencesEvents> Members
void IEventSource<_dispReferencesEvents>.OnSinkAdded(_dispReferencesEvents sink)
{
ReferenceAdded += new _dispReferencesEvents_ReferenceAddedEventHandler(sink.ReferenceAdded);
ReferenceChanged += new _dispReferencesEvents_ReferenceChangedEventHandler(sink.ReferenceChanged);
ReferenceRemoved += new _dispReferencesEvents_ReferenceRemovedEventHandler(sink.ReferenceRemoved);
}
void IEventSource<_dispReferencesEvents>.OnSinkRemoved(_dispReferencesEvents sink)
{
ReferenceAdded -= new _dispReferencesEvents_ReferenceAddedEventHandler(sink.ReferenceAdded);
ReferenceChanged -= new _dispReferencesEvents_ReferenceChangedEventHandler(sink.ReferenceChanged);
ReferenceRemoved -= new _dispReferencesEvents_ReferenceRemovedEventHandler(sink.ReferenceRemoved);
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Build.Framework;
using Microsoft.Build.BackEnd;
using Microsoft.Build.Collections;
using Microsoft.Build.Execution;
using Microsoft.Build.Shared;
using System.Xml;
using System.Threading;
using System.Diagnostics;
using Xunit;
namespace Microsoft.Build.UnitTests.BackEnd
{
public class Lookup_Tests
{
/// <summary>
/// Primary group contains an item for a type and secondary does;
/// primary item should be returned instead of the secondary item.
/// </summary>
[Fact]
public void SecondaryItemShadowedByPrimaryItem()
{
ProjectInstance project = ProjectHelpers.CreateEmptyProjectInstance();
ItemDictionary<ProjectItemInstance> table1 = new ItemDictionary<ProjectItemInstance>();
table1.Add(new ProjectItemInstance(project, "i1", "a1", project.FullPath));
table1.Add(new ProjectItemInstance(project, "i2", "a%3b1", project.FullPath));
Lookup lookup = LookupHelpers.CreateLookup(table1);
lookup.EnterScope("x");
lookup.PopulateWithItem(new ProjectItemInstance(project, "i1", "a2", project.FullPath));
lookup.PopulateWithItem(new ProjectItemInstance(project, "i2", "a%282", project.FullPath));
// Should return the item from the primary, not the secondary table
Assert.Equal("a2", lookup.GetItems("i1").First().EvaluatedInclude);
Assert.Equal("a(2", lookup.GetItems("i2").First().EvaluatedInclude);
}
/// <summary>
/// Primary group does not contain an item for a type but secondary does;
/// secondary item should be returned.
/// </summary>
[Fact]
public void SecondaryItemNotShadowedByPrimaryItem()
{
ProjectInstance project = ProjectHelpers.CreateEmptyProjectInstance();
ItemDictionary<ProjectItemInstance> table1 = new ItemDictionary<ProjectItemInstance>();
table1.Add(new ProjectItemInstance(project, "i1", "a1", project.FullPath));
table1.Add(new ProjectItemInstance(project, "i2", "a%3b1", project.FullPath));
Lookup lookup = LookupHelpers.CreateLookup(table1);
lookup.EnterScope("x");
// Should return item from the secondary table.
Assert.Equal("a1", lookup.GetItems("i1").First().EvaluatedInclude);
Assert.Equal("a;1", lookup.GetItems("i2").First().EvaluatedInclude);
}
/// <summary>
/// No items of that type: should return empty group rather than null
/// </summary>
[Fact]
public void UnknownItemType()
{
Lookup lookup = LookupHelpers.CreateEmptyLookup();
lookup.EnterScope("x"); // Doesn't matter really
Assert.Empty(lookup.GetItems("i1"));
}
/// <summary>
/// Adds accumulate as we lookup in the tables
/// </summary>
[Fact]
public void AddsAreCombinedWithPopulates()
{
ProjectInstance project = ProjectHelpers.CreateEmptyProjectInstance();
// One item in the project
ItemDictionary<ProjectItemInstance> table1 = new ItemDictionary<ProjectItemInstance>();
table1.Add(new ProjectItemInstance(project, "i1", "a1", project.FullPath));
Lookup lookup = LookupHelpers.CreateLookup(table1);
// We see the one item
Assert.Equal("a1", lookup.GetItems("i1").First().EvaluatedInclude);
Assert.Single(lookup.GetItems("i1"));
// One item in the project
Assert.Equal("a1", table1["i1"].First().EvaluatedInclude);
Assert.Single(table1["i1"]);
// Start a target
Lookup.Scope enteredScope = lookup.EnterScope("x");
// We see the one item
Assert.Equal("a1", lookup.GetItems("i1").First().EvaluatedInclude);
Assert.Single(lookup.GetItems("i1"));
// One item in the project
Assert.Equal("a1", table1["i1"].First().EvaluatedInclude);
Assert.Single(table1["i1"]);
// Start a task (eg) and add a new item
Lookup.Scope enteredScope2 = lookup.EnterScope("x");
lookup.AddNewItem(new ProjectItemInstance(project, "i1", "a2", project.FullPath));
// Now we see two items
Assert.Equal("a1", lookup.GetItems("i1").First().EvaluatedInclude);
Assert.Equal("a2", lookup.GetItems("i1").ElementAt(1).EvaluatedInclude);
Assert.Equal(2, lookup.GetItems("i1").Count);
// But there's still one item in the project
Assert.Equal("a1", table1["i1"].First().EvaluatedInclude);
Assert.Single(table1["i1"]);
// Finish the task
enteredScope2.LeaveScope();
// We still see two items
Assert.Equal("a1", lookup.GetItems("i1").First().EvaluatedInclude);
Assert.Equal("a2", lookup.GetItems("i1").ElementAt(1).EvaluatedInclude);
Assert.Equal(2, lookup.GetItems("i1").Count);
// But there's still one item in the project
Assert.Equal("a1", table1["i1"].First().EvaluatedInclude);
Assert.Single(table1["i1"]);
// Finish the target
enteredScope.LeaveScope();
// We still see two items
Assert.Equal("a1", lookup.GetItems("i1").First().EvaluatedInclude);
Assert.Equal("a2", lookup.GetItems("i1").ElementAt(1).EvaluatedInclude);
Assert.Equal(2, lookup.GetItems("i1").Count);
// And now the items have gotten put into the global group
Assert.Equal("a1", table1["i1"].First().EvaluatedInclude);
Assert.Equal("a2", table1["i1"].ElementAt(1).EvaluatedInclude);
Assert.Equal(2, table1["i1"].Count);
}
/// <summary>
/// Adds when duplicate removal is enabled removes only duplicates. Tests only item specs, not metadata differences
/// </summary>
[Fact]
public void AddsWithDuplicateRemovalItemSpecsOnly()
{
ProjectInstance project = ProjectHelpers.CreateEmptyProjectInstance();
// One item in the project
ItemDictionary<ProjectItemInstance> table1 = new ItemDictionary<ProjectItemInstance>();
table1.Add(new ProjectItemInstance(project, "i1", "a1", project.FullPath));
// Add an existing duplicate
table1.Add(new ProjectItemInstance(project, "i1", "a1", project.FullPath));
Lookup lookup = LookupHelpers.CreateLookup(table1);
var scope = lookup.EnterScope("test");
// This one should not get added
ProjectItemInstance[] newItems = new ProjectItemInstance[]
{
new ProjectItemInstance(project, "i1", "a1", project.FullPath), // Should not get added
new ProjectItemInstance(project, "i1", "a2", project.FullPath), // Should get added
};
// Perform the addition
lookup.AddNewItemsOfItemType("i1", newItems, doNotAddDuplicates: true);
var group = lookup.GetItems("i1");
// We should have the original two duplicates plus one new addition.
Assert.Equal(3, group.Count);
// Only two of the items should have the 'a1' include.
Assert.Equal(2, group.Where(item => item.EvaluatedInclude == "a1").Count());
// And ensure the other item got added.
Assert.Single(group.Where(item => item.EvaluatedInclude == "a2"));
scope.LeaveScope();
group = lookup.GetItems("i1");
// We should have the original two duplicates plus one new addition.
Assert.Equal(3, group.Count);
// Only two of the items should have the 'a1' include.
Assert.Equal(2, group.Where(item => item.EvaluatedInclude == "a1").Count());
// And ensure the other item got added.
Assert.Single(group.Where(item => item.EvaluatedInclude == "a2"));
}
/// <summary>
/// Adds when duplicate removal is enabled removes only duplicates. Tests only item specs, not metadata differences
/// </summary>
[Fact]
public void AddsWithDuplicateRemovalWithMetadata()
{
ProjectInstance project = ProjectHelpers.CreateEmptyProjectInstance();
ItemDictionary<ProjectItemInstance> table1 = new ItemDictionary<ProjectItemInstance>();
// Two items, differ only by metadata
table1.Add(new ProjectItemInstance(project, "i1", "a1", new KeyValuePair<string, string>[] { new KeyValuePair<string, string>("m1", "m1") }, project.FullPath));
table1.Add(new ProjectItemInstance(project, "i1", "a1", new KeyValuePair<string, string>[] { new KeyValuePair<string, string>("m1", "m2") }, project.FullPath));
Lookup lookup = LookupHelpers.CreateLookup(table1);
var scope = lookup.EnterScope("test");
// This one should not get added
ProjectItemInstance[] newItems = new ProjectItemInstance[]
{
new ProjectItemInstance(project, "i1", "a1", project.FullPath), // Should get added
new ProjectItemInstance(project, "i1", "a2", new KeyValuePair<string, string>[] { new KeyValuePair<string, string>( "m1", "m1" ) }, project.FullPath), // Should get added
new ProjectItemInstance(project, "i1", "a1", new KeyValuePair<string, string>[] { new KeyValuePair<string, string>( "m1", "m1" ) }, project.FullPath), // Should not get added
new ProjectItemInstance(project, "i1", "a1", new KeyValuePair<string, string>[] { new KeyValuePair<string, string>( "m1", "m3" ) }, project.FullPath), // Should get added
};
// Perform the addition
lookup.AddNewItemsOfItemType("i1", newItems, doNotAddDuplicates: true);
var group = lookup.GetItems("i1");
// We should have the original two duplicates plus one new addition.
Assert.Equal(5, group.Count);
// Four of the items will have the a1 include
Assert.Equal(4, group.Where(item => item.EvaluatedInclude == "a1").Count());
// One item will have the a2 include
Assert.Single(group.Where(item => item.EvaluatedInclude == "a2"));
scope.LeaveScope();
group = lookup.GetItems("i1");
// We should have the original two duplicates plus one new addition.
Assert.Equal(5, group.Count);
// Four of the items will have the a1 include
Assert.Equal(4, group.Where(item => item.EvaluatedInclude == "a1").Count());
// One item will have the a2 include
Assert.Single(group.Where(item => item.EvaluatedInclude == "a2"));
}
[Fact]
public void Removes()
{
ProjectInstance project = ProjectHelpers.CreateEmptyProjectInstance();
// One item in the project
ItemDictionary<ProjectItemInstance> table1 = new ItemDictionary<ProjectItemInstance>();
ProjectItemInstance item1 = new ProjectItemInstance(project, "i1", "a1", project.FullPath);
table1.Add(item1);
Lookup lookup = LookupHelpers.CreateLookup(table1);
// Start a target
Lookup.Scope enteredScope = lookup.EnterScope("x");
// Start a task (eg) and add a new item
Lookup.Scope enteredScope2 = lookup.EnterScope("x");
ProjectItemInstance item2 = new ProjectItemInstance(project, "i1", "a2", project.FullPath);
lookup.AddNewItem(item2);
// Remove one item
lookup.RemoveItem(item1);
// We see one item
Assert.Single(lookup.GetItems("i1"));
Assert.Equal("a2", lookup.GetItems("i1").First().EvaluatedInclude);
// Remove the other item
lookup.RemoveItem(item2);
// We see no items
Assert.Empty(lookup.GetItems("i1"));
// Finish the task
enteredScope2.LeaveScope();
// We still see no items
Assert.Empty(lookup.GetItems("i1"));
// But there's still one item in the project
Assert.Equal("a1", table1["i1"].First().EvaluatedInclude);
Assert.Single(table1["i1"]);
// Finish the target
enteredScope.LeaveScope();
// We still see no items
Assert.Empty(lookup.GetItems("i1"));
// And now there are no items in the project either
Assert.Empty(table1["i1"]);
}
[Fact]
public void RemoveItemPopulatedInLowerScope()
{
ProjectInstance project = ProjectHelpers.CreateEmptyProjectInstance();
ItemDictionary<ProjectItemInstance> table1 = new ItemDictionary<ProjectItemInstance>();
Lookup lookup = LookupHelpers.CreateLookup(table1);
ProjectItemInstance item1 = new ProjectItemInstance(project, "i1", "a2", project.FullPath);
// Start a target
Lookup.Scope enteredScope = lookup.EnterScope("x");
// There's one item in this batch
lookup.PopulateWithItem(item1);
// We see it
Assert.Single(lookup.GetItems("i1"));
// Make a clone so we can keep an eye on that item
Lookup lookup2 = lookup.Clone();
// We can see the item in the clone
Assert.Single(lookup2.GetItems("i1"));
// Start a task (eg)
Lookup.Scope enteredScope2 = lookup.EnterScope("x");
// We see the item below
Assert.Single(lookup.GetItems("i1"));
// Remove that item
lookup.RemoveItem(item1);
// We see no items
Assert.Empty(lookup.GetItems("i1"));
// The clone is unaffected so far
Assert.Single(lookup2.GetItems("i1"));
// Finish the task
enteredScope2.LeaveScope();
// We still see no items
Assert.Empty(lookup.GetItems("i1"));
// But now the clone doesn't either
Assert.Empty(lookup2.GetItems("i1"));
// Finish the target
enteredScope.LeaveScope();
// We still see no items
Assert.Empty(lookup.GetItems("i1"));
Assert.Empty(lookup2.GetItems("i1"));
}
[Fact]
public void RemoveItemAddedInLowerScope()
{
ProjectInstance project = ProjectHelpers.CreateEmptyProjectInstance();
ItemDictionary<ProjectItemInstance> table1 = new ItemDictionary<ProjectItemInstance>();
Lookup lookup = LookupHelpers.CreateLookup(table1);
// Start a target
Lookup.Scope enteredScope = lookup.EnterScope("x");
// Add an item
ProjectItemInstance item1 = new ProjectItemInstance(project, "i1", "a2", project.FullPath);
lookup.AddNewItem(item1);
// Start a task (eg)
Lookup.Scope enteredScope2 = lookup.EnterScope("x");
// We see the item below
Assert.Single(lookup.GetItems("i1"));
// Remove that item
lookup.RemoveItem(item1);
// We see no items
Assert.Empty(lookup.GetItems("i1"));
// Finish the task
enteredScope2.LeaveScope();
// We still see no items
Assert.Empty(lookup.GetItems("i1"));
// Finish the target
enteredScope.LeaveScope();
// We still see no items
Assert.Empty(lookup.GetItems("i1"));
}
/// <summary>
/// Ensure that once keepOnlySpecified is set to true, it remains in effect.
/// </summary>
[Fact]
public void KeepMetadataOnlySpecifiedPropagate1()
{
ProjectInstance project = ProjectHelpers.CreateEmptyProjectInstance();
ItemDictionary<ProjectItemInstance> table1 = new ItemDictionary<ProjectItemInstance>();
Lookup lookup = LookupHelpers.CreateLookup(table1);
Lookup.Scope enteredScope = lookup.EnterScope("x");
// Add an item with m=m1
ProjectItemInstance item1 = new ProjectItemInstance(project, "i1", "a2", project.FullPath);
item1.SetMetadata("m1", "m1");
item1.SetMetadata("m2", "m2");
lookup.AddNewItem(item1);
Lookup.Scope enteredScope2 = lookup.EnterScope("x");
// Get rid of all of the metadata.
Lookup.MetadataModifications newMetadata = new Lookup.MetadataModifications(keepOnlySpecified: true);
ICollection<ProjectItemInstance> group = lookup.GetItems(item1.ItemType);
lookup.ModifyItems(item1.ItemType, group, newMetadata);
group = lookup.GetItems("i1");
Assert.Single(group);
// m1 and m2 are gone.
Assert.Equal(String.Empty, group.First().GetMetadataValue("m1"));
Assert.Equal(String.Empty, group.First().GetMetadataValue("m2"));
enteredScope2.LeaveScope();
// Add metadata m3.
Lookup.MetadataModifications newMetadata2 = new Lookup.MetadataModifications(keepOnlySpecified: false);
newMetadata2.Add("m3", "m3");
group = lookup.GetItems(item1.ItemType);
lookup.ModifyItems(item1.ItemType, group, newMetadata2);
group = lookup.GetItems("i1");
Assert.Single(group);
// m1 and m2 are gone
Assert.Equal(String.Empty, group.First().GetMetadataValue("m1"));
Assert.Equal(String.Empty, group.First().GetMetadataValue("m2"));
// m3 is still there.
Assert.Equal("m3", group.First().GetMetadataValue("m3"));
enteredScope.LeaveScope();
group = lookup.GetItems("i1");
Assert.Single(group);
// m1 and m2 are gone
Assert.Equal(String.Empty, group.First().GetMetadataValue("m1"));
Assert.Equal(String.Empty, group.First().GetMetadataValue("m2"));
// m3 is still there.
Assert.Equal("m3", group.First().GetMetadataValue("m3"));
}
/// <summary>
/// Ensure that if keepOnlySpecified is specified after some metadata have been set in a higher scope that it will
/// eliminate that metadata are the current scope and beyond.
/// </summary>
[Fact]
public void KeepMetadataOnlySpecifiedPropagate2()
{
ProjectInstance project = ProjectHelpers.CreateEmptyProjectInstance();
ItemDictionary<ProjectItemInstance> table1 = new ItemDictionary<ProjectItemInstance>();
Lookup lookup = LookupHelpers.CreateLookup(table1);
Lookup.Scope enteredScope = lookup.EnterScope("x");
// Add an item with m=m1
ProjectItemInstance item1 = new ProjectItemInstance(project, "i1", "a2", project.FullPath);
item1.SetMetadata("m1", "m1");
item1.SetMetadata("m2", "m2");
lookup.AddNewItem(item1);
Lookup.Scope enteredScope2 = lookup.EnterScope("x");
// Add m3 metadata
Lookup.MetadataModifications newMetadata = new Lookup.MetadataModifications(keepOnlySpecified: false);
newMetadata.Add("m3", "m3");
ICollection<ProjectItemInstance> group = lookup.GetItems(item1.ItemType);
lookup.ModifyItems(item1.ItemType, group, newMetadata);
group = lookup.GetItems("i1");
Assert.Single(group);
// All metadata are present
Assert.Equal("m1", group.First().GetMetadataValue("m1"));
Assert.Equal("m2", group.First().GetMetadataValue("m2"));
Assert.Equal("m3", group.First().GetMetadataValue("m3"));
enteredScope2.LeaveScope();
// Now clear metadata
Lookup.MetadataModifications newMetadata2 = new Lookup.MetadataModifications(keepOnlySpecified: true);
group = lookup.GetItems(item1.ItemType);
lookup.ModifyItems(item1.ItemType, group, newMetadata2);
group = lookup.GetItems("i1");
Assert.Single(group);
// All metadata are gone
Assert.Equal(String.Empty, group.First().GetMetadataValue("m1"));
Assert.Equal(String.Empty, group.First().GetMetadataValue("m2"));
Assert.Equal(String.Empty, group.First().GetMetadataValue("m3"));
enteredScope.LeaveScope();
group = lookup.GetItems("i1");
Assert.Single(group);
// All metadata are gone
Assert.Equal(String.Empty, group.First().GetMetadataValue("m1"));
Assert.Equal(String.Empty, group.First().GetMetadataValue("m2"));
Assert.Equal(String.Empty, group.First().GetMetadataValue("m3"));
}
/// <summary>
/// Ensure that once keepOnlySpecified is set to true, it remains in effect, but that metadata explicitly added at subsequent levels is still retained.
/// </summary>
[Fact]
public void KeepMetadataOnlySpecifiedPropagate3()
{
ProjectInstance project = ProjectHelpers.CreateEmptyProjectInstance();
ItemDictionary<ProjectItemInstance> table1 = new ItemDictionary<ProjectItemInstance>();
Lookup lookup = LookupHelpers.CreateLookup(table1);
Lookup.Scope enteredScope = lookup.EnterScope("x");
// Add an item with m=m1
ProjectItemInstance item1 = new ProjectItemInstance(project, "i1", "a2", project.FullPath);
item1.SetMetadata("m1", "m1");
item1.SetMetadata("m2", "m2");
lookup.AddNewItem(item1);
Lookup.Scope enteredScope2 = lookup.EnterScope("x");
// Get rid of all of the metadata, then add m3
Lookup.MetadataModifications newMetadata = new Lookup.MetadataModifications(keepOnlySpecified: true);
newMetadata.Add("m3", "m3");
ICollection<ProjectItemInstance> group = lookup.GetItems(item1.ItemType);
lookup.ModifyItems(item1.ItemType, group, newMetadata);
group = lookup.GetItems("i1");
Assert.Single(group);
// m1 and m2 are gone.
Assert.Equal(String.Empty, group.First().GetMetadataValue("m1"));
Assert.Equal(String.Empty, group.First().GetMetadataValue("m2"));
// m3 is still there.
Assert.Equal("m3", group.First().GetMetadataValue("m3"));
enteredScope2.LeaveScope();
// Add metadata m4.
Lookup.MetadataModifications newMetadata2 = new Lookup.MetadataModifications(keepOnlySpecified: true);
newMetadata2.Add("m4", "m4");
group = lookup.GetItems(item1.ItemType);
lookup.ModifyItems(item1.ItemType, group, newMetadata2);
group = lookup.GetItems("i1");
Assert.Single(group);
// m1, m2 and m3 are gone
Assert.Equal(String.Empty, group.First().GetMetadataValue("m1"));
Assert.Equal(String.Empty, group.First().GetMetadataValue("m2"));
Assert.Equal(String.Empty, group.First().GetMetadataValue("m3"));
// m4 is still there.
Assert.Equal("m4", group.First().GetMetadataValue("m4"));
enteredScope.LeaveScope();
group = lookup.GetItems("i1");
Assert.Single(group);
// m1, m2 and m3 are gone
Assert.Equal(String.Empty, group.First().GetMetadataValue("m1"));
Assert.Equal(String.Empty, group.First().GetMetadataValue("m2"));
Assert.Equal(String.Empty, group.First().GetMetadataValue("m3"));
// m4 is still there.
Assert.Equal("m4", group.First().GetMetadataValue("m4"));
}
/// <summary>
/// Ensure that once keepOnlySpecified is set to true, it remains in effect, and that if a metadata modification is declared as 'keep value' that
/// the value as lower scopes is retained.
/// </summary>
[Fact]
public void KeepMetadataOnlySpecifiedPropagate4()
{
ProjectInstance project = ProjectHelpers.CreateEmptyProjectInstance();
ItemDictionary<ProjectItemInstance> table1 = new ItemDictionary<ProjectItemInstance>();
Lookup lookup = LookupHelpers.CreateLookup(table1);
Lookup.Scope enteredScope = lookup.EnterScope("x");
// Add an item with m=m1
ProjectItemInstance item1 = new ProjectItemInstance(project, "i1", "a2", project.FullPath);
item1.SetMetadata("m1", "m1");
item1.SetMetadata("m2", "m2");
lookup.AddNewItem(item1);
Lookup.Scope enteredScope2 = lookup.EnterScope("x");
// Get rid of all of the metadata, then add m3
Lookup.MetadataModifications newMetadata = new Lookup.MetadataModifications(keepOnlySpecified: true);
newMetadata.Add("m3", "m3");
ICollection<ProjectItemInstance> group = lookup.GetItems(item1.ItemType);
lookup.ModifyItems(item1.ItemType, group, newMetadata);
group = lookup.GetItems("i1");
Assert.Single(group);
// m1 and m2 are gone.
Assert.Equal(String.Empty, group.First().GetMetadataValue("m1"));
Assert.Equal(String.Empty, group.First().GetMetadataValue("m2"));
// m3 is still there.
Assert.Equal("m3", group.First().GetMetadataValue("m3"));
enteredScope2.LeaveScope();
// Keep m3.
Lookup.MetadataModifications newMetadata2 = new Lookup.MetadataModifications(keepOnlySpecified: true);
newMetadata2["m3"] = Lookup.MetadataModification.CreateFromNoChange();
group = lookup.GetItems(item1.ItemType);
lookup.ModifyItems(item1.ItemType, group, newMetadata2);
group = lookup.GetItems("i1");
Assert.Single(group);
// m1 and m2 are gone
Assert.Equal(String.Empty, group.First().GetMetadataValue("m1"));
Assert.Equal(String.Empty, group.First().GetMetadataValue("m2"));
// m3 is still there
Assert.Equal("m3", group.First().GetMetadataValue("m3"));
enteredScope.LeaveScope();
group = lookup.GetItems("i1");
Assert.Single(group);
// m1 and m2 are gone
Assert.Equal(String.Empty, group.First().GetMetadataValue("m1"));
Assert.Equal(String.Empty, group.First().GetMetadataValue("m2"));
// m3 is still there.
Assert.Equal("m3", group.First().GetMetadataValue("m3"));
}
/// <summary>
/// Ensure that when keepOnlySpecified is true, we will clear all metadata unless it is retained using the 'NoChange' modification type.
/// </summary>
[Fact]
public void KeepMetadataOnlySpecified()
{
ProjectInstance project = ProjectHelpers.CreateEmptyProjectInstance();
ItemDictionary<ProjectItemInstance> table1 = new ItemDictionary<ProjectItemInstance>();
Lookup lookup = LookupHelpers.CreateLookup(table1);
Lookup.Scope enteredScope = lookup.EnterScope("x");
// Add an item with m=m1
ProjectItemInstance item1 = new ProjectItemInstance(project, "i1", "a2", project.FullPath);
item1.SetMetadata("m1", "m1");
item1.SetMetadata("m2", "m2");
lookup.AddNewItem(item1);
Lookup.Scope enteredScope2 = lookup.EnterScope("x");
// Test keeping only specified metadata
Lookup.MetadataModifications newMetadata = new Lookup.MetadataModifications(keepOnlySpecified: true);
newMetadata["m1"] = Lookup.MetadataModification.CreateFromNoChange();
ICollection<ProjectItemInstance> group = lookup.GetItems(item1.ItemType);
lookup.ModifyItems(item1.ItemType, group, newMetadata);
group = lookup.GetItems("i1");
Assert.Single(group);
// m1 is still here.
Assert.Equal("m1", group.First().GetMetadataValue("m1"));
// m2 is gone
Assert.Equal(String.Empty, group.First().GetMetadataValue("m2"));
enteredScope2.LeaveScope();
group = lookup.GetItems("i1");
Assert.Single(group);
// m1 should still be here
Assert.Equal("m1", group.First().GetMetadataValue("m1"));
// m2 is gone.
Assert.Equal(String.Empty, group.First().GetMetadataValue("m2"));
enteredScope.LeaveScope();
group = lookup.GetItems("i1");
Assert.Single(group);
// m1 should still be here
Assert.Equal("m1", group.First().GetMetadataValue("m1"));
// m2 should not persist here either
Assert.Equal(String.Empty, group.First().GetMetadataValue("m2"));
}
[Fact]
public void KeepMetadataOnlySpecifiedNoneSpecified()
{
ProjectInstance project = ProjectHelpers.CreateEmptyProjectInstance();
ItemDictionary<ProjectItemInstance> table1 = new ItemDictionary<ProjectItemInstance>();
Lookup lookup = LookupHelpers.CreateLookup(table1);
Lookup.Scope enteredScope = lookup.EnterScope("x");
// Add an item with m=m1
ProjectItemInstance item1 = new ProjectItemInstance(project, "i1", "a2", project.FullPath);
item1.SetMetadata("m1", "m1");
item1.SetMetadata("m2", "m2");
lookup.AddNewItem(item1);
Lookup.Scope enteredScope2 = lookup.EnterScope("x");
// Test keeping only specified metadata
Lookup.MetadataModifications newMetadata = new Lookup.MetadataModifications(keepOnlySpecified: true);
ICollection<ProjectItemInstance> group = lookup.GetItems(item1.ItemType);
lookup.ModifyItems(item1.ItemType, group, newMetadata);
group = lookup.GetItems("i1");
Assert.Single(group);
// m1 and m2 are gone.
Assert.Equal(String.Empty, group.First().GetMetadataValue("m1"));
Assert.Equal(String.Empty, group.First().GetMetadataValue("m2"));
enteredScope2.LeaveScope();
group = lookup.GetItems("i1");
Assert.Single(group);
// m1 and m2 are gone.
Assert.Equal(String.Empty, group.First().GetMetadataValue("m1"));
Assert.Equal(String.Empty, group.First().GetMetadataValue("m2"));
enteredScope.LeaveScope();
group = lookup.GetItems("i1");
Assert.Single(group);
// m1 and m2 are gone.
Assert.Equal(String.Empty, group.First().GetMetadataValue("m1"));
Assert.Equal(String.Empty, group.First().GetMetadataValue("m2"));
}
[Fact]
public void ModifyItem()
{
ProjectInstance project = ProjectHelpers.CreateEmptyProjectInstance();
ItemDictionary<ProjectItemInstance> table1 = new ItemDictionary<ProjectItemInstance>();
Lookup lookup = LookupHelpers.CreateLookup(table1);
Lookup.Scope enteredScope = lookup.EnterScope("x");
// Add an item with m=m1
ProjectItemInstance item1 = new ProjectItemInstance(project, "i1", "a2", project.FullPath);
item1.SetMetadata("m", "m1");
lookup.AddNewItem(item1);
Lookup.Scope enteredScope2 = lookup.EnterScope("x");
// Change the item to be m=m2
Lookup.MetadataModifications newMetadata = new Lookup.MetadataModifications(keepOnlySpecified: false);
newMetadata.Add("m", "m2");
ICollection<ProjectItemInstance> group = new List<ProjectItemInstance>();
group.Add(item1);
lookup.ModifyItems(item1.ItemType, group, newMetadata);
// Now it has m=m2
group = lookup.GetItems("i1");
Assert.Single(group);
Assert.Equal("m2", group.First().GetMetadataValue("m"));
// But the original item hasn't changed yet
Assert.Equal("m1", item1.GetMetadataValue("m"));
enteredScope2.LeaveScope();
// It still has m=m2
group = lookup.GetItems("i1");
Assert.Single(group);
Assert.Equal("m2", group.First().GetMetadataValue("m"));
// The original item still hasn't changed
// even though it was added in this scope
Assert.Equal("m1", item1.GetMetadataValue("m"));
enteredScope.LeaveScope();
// It still has m=m2
group = lookup.GetItems("i1");
Assert.Single(group);
Assert.Equal("m2", group.First().GetMetadataValue("m"));
// But now the original item has changed
Assert.Equal("m2", item1.GetMetadataValue("m"));
}
/// <summary>
/// Modifications should be merged
/// </summary>
[Fact]
public void ModifyItemModifiedInPreviousScope()
{
ProjectInstance project = ProjectHelpers.CreateEmptyProjectInstance();
ItemDictionary<ProjectItemInstance> table1 = new ItemDictionary<ProjectItemInstance>();
Lookup lookup = LookupHelpers.CreateLookup(table1);
// Add an item with m=m1 and n=n1
ProjectItemInstance item1 = new ProjectItemInstance(project, "i1", "a2", project.FullPath);
item1.SetMetadata("m", "m1");
lookup.PopulateWithItem(item1);
lookup.EnterScope("x");
// Make a modification to the item to be m=m2
Lookup.MetadataModifications newMetadata = new Lookup.MetadataModifications(keepOnlySpecified: false);
newMetadata.Add("m", "m2");
newMetadata.Add("n", "n2");
ICollection<ProjectItemInstance> group = new List<ProjectItemInstance>();
group.Add(item1);
lookup.ModifyItems(item1.ItemType, group, newMetadata);
lookup.EnterScope("x");
// Make another modification to the item
newMetadata = new Lookup.MetadataModifications(keepOnlySpecified: false);
newMetadata.Add("m", "m3");
newMetadata.Add("o", "o3");
lookup.ModifyItems(item1.ItemType, group, newMetadata);
// It's now m=m3, n=n2, o=o3
group = lookup.GetItems("i1");
Assert.Single(group);
Assert.Equal("m3", group.First().GetMetadataValue("m"));
Assert.Equal("n2", group.First().GetMetadataValue("n"));
Assert.Equal("o3", group.First().GetMetadataValue("o"));
}
/// <summary>
/// Modifications should be merged
/// </summary>
[Fact]
public void ModifyItemTwiceInSameScope1()
{
ProjectInstance project = ProjectHelpers.CreateEmptyProjectInstance();
ItemDictionary<ProjectItemInstance> table1 = new ItemDictionary<ProjectItemInstance>();
Lookup lookup = LookupHelpers.CreateLookup(table1);
// Add an item with m=m1 and n=n1
ProjectItemInstance item1 = new ProjectItemInstance(project, "i1", "a2", project.FullPath);
item1.SetMetadata("m", "m1");
lookup.PopulateWithItem(item1);
lookup.EnterScope("x");
// Make a modification to the item to be m=m2
Lookup.MetadataModifications newMetadata = new Lookup.MetadataModifications(keepOnlySpecified: false);
newMetadata.Add("m", "m2");
ICollection<ProjectItemInstance> group = new List<ProjectItemInstance>();
group.Add(item1);
lookup.ModifyItems(item1.ItemType, group, newMetadata);
// Make an unrelated modification to the item
newMetadata = new Lookup.MetadataModifications(keepOnlySpecified: false);
newMetadata.Add("n", "n1");
lookup.ModifyItems(item1.ItemType, group, newMetadata);
// It's now m=m2
group = lookup.GetItems("i1");
Assert.Single(group);
Assert.Equal("m2", group.First().GetMetadataValue("m"));
}
/// <summary>
/// Modifications should be merged
/// </summary>
[Fact]
public void ModifyItemTwiceInSameScope2()
{
ProjectInstance project = ProjectHelpers.CreateEmptyProjectInstance();
ItemDictionary<ProjectItemInstance> table1 = new ItemDictionary<ProjectItemInstance>();
Lookup lookup = LookupHelpers.CreateLookup(table1);
// Add an item with m=m1 and n=n1 and o=o1
ProjectItemInstance item1 = new ProjectItemInstance(project, "i1", "a2", project.FullPath);
item1.SetMetadata("m", "m1");
item1.SetMetadata("n", "n1");
item1.SetMetadata("o", "o1");
lookup.PopulateWithItem(item1);
Lookup.Scope enteredScope = lookup.EnterScope("x");
// It's still m=m1, n=n1, o=o1
ICollection<ProjectItemInstance> group = lookup.GetItems("i1");
Assert.Single(group);
Assert.Equal("m1", group.First().GetMetadataValue("m"));
Assert.Equal("n1", group.First().GetMetadataValue("n"));
Assert.Equal("o1", group.First().GetMetadataValue("o"));
// Make a modification to the item to be m=m2 and n=n2
Lookup.MetadataModifications newMetadata = new Lookup.MetadataModifications(keepOnlySpecified: false);
newMetadata.Add("m", "m2");
newMetadata.Add("n", "n2");
group = new List<ProjectItemInstance>();
group.Add(item1);
lookup.ModifyItems("i1", group, newMetadata);
// It's now m=m2, n=n2, o=o1
ICollection<ProjectItemInstance> foundGroup = lookup.GetItems("i1");
Assert.Single(foundGroup);
Assert.Equal("m2", foundGroup.First().GetMetadataValue("m"));
Assert.Equal("n2", foundGroup.First().GetMetadataValue("n"));
Assert.Equal("o1", foundGroup.First().GetMetadataValue("o"));
// Make a modification to the item to be n=n3
newMetadata = new Lookup.MetadataModifications(keepOnlySpecified: false);
newMetadata.Add("n", "n3");
lookup.ModifyItems("i1", group, newMetadata);
// It's now m=m2, n=n3, o=o1
foundGroup = lookup.GetItems("i1");
Assert.Single(foundGroup);
Assert.Equal("m2", foundGroup.First().GetMetadataValue("m"));
Assert.Equal("n3", foundGroup.First().GetMetadataValue("n"));
Assert.Equal("o1", foundGroup.First().GetMetadataValue("o"));
// But the original item hasn't changed yet
Assert.Equal("m1", item1.GetMetadataValue("m"));
Assert.Equal("n1", item1.GetMetadataValue("n"));
Assert.Equal("o1", item1.GetMetadataValue("o"));
enteredScope.LeaveScope();
// It's still m=m2, n=n3, o=o1
foundGroup = lookup.GetItems("i1");
Assert.Single(foundGroup);
Assert.Equal("m2", foundGroup.First().GetMetadataValue("m"));
Assert.Equal("n3", foundGroup.First().GetMetadataValue("n"));
Assert.Equal("o1", foundGroup.First().GetMetadataValue("o"));
// And the original item has changed
Assert.Equal("m2", item1.GetMetadataValue("m"));
Assert.Equal("n3", item1.GetMetadataValue("n"));
Assert.Equal("o1", item1.GetMetadataValue("o"));
}
[Fact]
public void ModifyItemThatWasAddedInSameScope()
{
ProjectInstance project = ProjectHelpers.CreateEmptyProjectInstance();
ItemDictionary<ProjectItemInstance> table1 = new ItemDictionary<ProjectItemInstance>();
Lookup lookup = LookupHelpers.CreateLookup(table1);
Lookup.Scope enteredScope = lookup.EnterScope("x");
// Add an item with m=m1
ProjectItemInstance item1 = new ProjectItemInstance(project, "i1", "a2", project.FullPath);
item1.SetMetadata("m", "m1");
lookup.AddNewItem(item1);
// Change the item to be m=m2
Lookup.MetadataModifications newMetadata = new Lookup.MetadataModifications(keepOnlySpecified: false);
newMetadata.Add("m", "m2");
ICollection<ProjectItemInstance> group = new List<ProjectItemInstance>();
group.Add(item1);
lookup.ModifyItems(item1.ItemType, group, newMetadata);
// Now it has m=m2
group = lookup.GetItems("i1");
Assert.Single(group);
Assert.Equal("m2", group.First().GetMetadataValue("m"));
// But the original item hasn't changed yet
Assert.Equal("m1", item1.GetMetadataValue("m"));
enteredScope.LeaveScope();
// It still has m=m2
group = lookup.GetItems("i1");
Assert.Single(group);
Assert.Equal("m2", group.First().GetMetadataValue("m"));
// But now the original item has changed as well
Assert.Equal("m2", item1.GetMetadataValue("m"));
}
/// <summary>
/// Modifying an item in the outside scope is prohibited-
/// purely because we don't need to do it in our code
/// </summary>
[Fact]
public void ModifyItemInOutsideScope()
{
Assert.Throws<InternalErrorException>(() =>
{
ProjectInstance project = ProjectHelpers.CreateEmptyProjectInstance();
Lookup lookup = LookupHelpers.CreateLookup(new ItemDictionary<ProjectItemInstance>());
lookup.AddNewItem(new ProjectItemInstance(project, "x", "y", project.FullPath));
}
);
}
/// <summary>
/// After modification, should be able to GetItem and then modify it again
/// </summary>
[Fact]
public void ModifyItemPreviouslyModifiedAndGottenThroughGetItem()
{
ProjectInstance project = ProjectHelpers.CreateEmptyProjectInstance();
ItemDictionary<ProjectItemInstance> table1 = new ItemDictionary<ProjectItemInstance>();
Lookup lookup = LookupHelpers.CreateLookup(table1);
// Add an item with m=m1 and n=n1
ProjectItemInstance item1 = new ProjectItemInstance(project, "i1", "a2", project.FullPath);
item1.SetMetadata("m", "m1");
lookup.PopulateWithItem(item1);
Lookup.Scope enteredScope = lookup.EnterScope("x");
// Make a modification to the item to be m=m2
Lookup.MetadataModifications newMetadata = new Lookup.MetadataModifications(keepOnlySpecified: false);
newMetadata.Add("m", "m2");
ICollection<ProjectItemInstance> group = new List<ProjectItemInstance>();
group.Add(item1);
lookup.ModifyItems(item1.ItemType, group, newMetadata);
// Get the item (under the covers, it cloned it in order to apply the modification)
ICollection<ProjectItemInstance> group2 = lookup.GetItems(item1.ItemType);
Assert.Single(group2);
ProjectItemInstance item1b = group2.First();
// Modify to m=m3
Lookup.MetadataModifications newMetadata2 = new Lookup.MetadataModifications(keepOnlySpecified: false);
newMetadata2.Add("m", "m3");
ICollection<ProjectItemInstance> group3 = new List<ProjectItemInstance>();
group3.Add(item1b);
lookup.ModifyItems(item1b.ItemType, group3, newMetadata2);
// Modifications are visible
ICollection<ProjectItemInstance> group4 = lookup.GetItems(item1b.ItemType);
Assert.Single(group4);
Assert.Equal("m3", group4.First().GetMetadataValue("m"));
// Leave scope
enteredScope.LeaveScope();
// Still visible
ICollection<ProjectItemInstance> group5 = lookup.GetItems(item1b.ItemType);
Assert.Single(group5);
Assert.Equal("m3", group5.First().GetMetadataValue("m"));
}
/// <summary>
/// After modification, should be able to GetItem and then modify it again
/// </summary>
[Fact]
public void ModifyItemInProjectPreviouslyModifiedAndGottenThroughGetItem()
{
ProjectInstance project = ProjectHelpers.CreateEmptyProjectInstance();
// Create some project state with an item with m=m1 and n=n1
ItemDictionary<ProjectItemInstance> table1 = new ItemDictionary<ProjectItemInstance>();
ProjectItemInstance item1 = new ProjectItemInstance(project, "i1", "a2", project.FullPath);
item1.SetMetadata("m", "m1");
table1.Add(item1);
Lookup lookup = LookupHelpers.CreateLookup(table1);
Lookup.Scope enteredScope = lookup.EnterScope("x");
// Make a modification to the item to be m=m2
Lookup.MetadataModifications newMetadata = new Lookup.MetadataModifications(keepOnlySpecified: false);
newMetadata.Add("m", "m2");
List<ProjectItemInstance> group = new List<ProjectItemInstance>();
group.Add(item1);
lookup.ModifyItems(item1.ItemType, group, newMetadata);
// Get the item (under the covers, it cloned it in order to apply the modification)
ICollection<ProjectItemInstance> group2 = lookup.GetItems(item1.ItemType);
Assert.Single(group2);
ProjectItemInstance item1b = group2.First();
// Modify to m=m3
Lookup.MetadataModifications newMetadata2 = new Lookup.MetadataModifications(keepOnlySpecified: false);
newMetadata2.Add("m", "m3");
List<ProjectItemInstance> group3 = new List<ProjectItemInstance>();
group3.Add(item1b);
lookup.ModifyItems(item1b.ItemType, group3, newMetadata2);
// Modifications are visible
ICollection<ProjectItemInstance> group4 = lookup.GetItems(item1b.ItemType);
Assert.Single(group4);
Assert.Equal("m3", group4.First().GetMetadataValue("m"));
// Leave scope
enteredScope.LeaveScope();
// Still visible
ICollection<ProjectItemInstance> group5 = lookup.GetItems(item1b.ItemType);
Assert.Single(group5);
Assert.Equal("m3", group5.First().GetMetadataValue("m"));
// And the one in the project is changed
Assert.Equal("m3", item1.GetMetadataValue("m"));
}
/// <summary>
/// After modification, should be able to GetItem and then remove it
/// </summary>
[Fact]
public void RemoveItemPreviouslyModifiedAndGottenThroughGetItem()
{
ProjectInstance project = ProjectHelpers.CreateEmptyProjectInstance();
ItemDictionary<ProjectItemInstance> table1 = new ItemDictionary<ProjectItemInstance>();
Lookup lookup = LookupHelpers.CreateLookup(table1);
// Add an item with m=m1 and n=n1
ProjectItemInstance item1 = new ProjectItemInstance(project, "i1", "a2", project.FullPath);
item1.SetMetadata("m", "m1");
lookup.PopulateWithItem(item1);
lookup.EnterScope("x");
// Make a modification to the item to be m=m2
Lookup.MetadataModifications newMetadata = new Lookup.MetadataModifications(keepOnlySpecified: false);
newMetadata.Add("m", "m2");
List<ProjectItemInstance> group = new List<ProjectItemInstance>();
group.Add(item1);
lookup.ModifyItems(item1.ItemType, group, newMetadata);
// Get the item (under the covers, it cloned it in order to apply the modification)
ICollection<ProjectItemInstance> group2 = lookup.GetItems(item1.ItemType);
Assert.Single(group2);
ProjectItemInstance item1b = group2.First();
// Remove the item
lookup.RemoveItem(item1b);
// There's now no items at all
ICollection<ProjectItemInstance> group3 = lookup.GetItems(item1.ItemType);
Assert.Empty(group3);
}
/// <summary>
/// After modification, should be able to GetItem and then remove it
/// </summary>
[Fact]
public void RemoveItemFromProjectPreviouslyModifiedAndGottenThroughGetItem()
{
ProjectInstance project = ProjectHelpers.CreateEmptyProjectInstance();
// Create some project state with an item with m=m1 and n=n1
ItemDictionary<ProjectItemInstance> table1 = new ItemDictionary<ProjectItemInstance>();
ProjectItemInstance item1 = new ProjectItemInstance(project, "i1", "a2", project.FullPath);
item1.SetMetadata("m", "m1");
table1.Add(item1);
Lookup lookup = LookupHelpers.CreateLookup(table1);
Lookup.Scope enteredScope = lookup.EnterScope("x");
// Make a modification to the item to be m=m2
Lookup.MetadataModifications newMetadata = new Lookup.MetadataModifications(keepOnlySpecified: false);
newMetadata.Add("m", "m2");
List<ProjectItemInstance> group = new List<ProjectItemInstance>();
group.Add(item1);
lookup.ModifyItems(item1.ItemType, group, newMetadata);
// Get the item (under the covers, it cloned it in order to apply the modification)
ICollection<ProjectItemInstance> group2 = lookup.GetItems(item1.ItemType);
Assert.Single(group2);
ProjectItemInstance item1b = group2.First();
// Remove the item
lookup.RemoveItem(item1b);
// There's now no items at all
ICollection<ProjectItemInstance> group3 = lookup.GetItems(item1.ItemType);
Assert.Empty(group3);
// Leave scope
enteredScope.LeaveScope();
// And now none left in the project either
Assert.Empty(table1["i1"]);
}
/// <summary>
/// If the property isn't modified, the initial property
/// should be returned
/// </summary>
[Fact]
public void UnmodifiedProperty()
{
PropertyDictionary<ProjectPropertyInstance> group = new PropertyDictionary<ProjectPropertyInstance>();
ProjectPropertyInstance property = ProjectPropertyInstance.Create("p1", "v1");
group.Set(property);
Lookup lookup = LookupHelpers.CreateLookup(group);
Assert.Equal(property, lookup.GetProperty("p1"));
lookup.EnterScope("x");
Assert.Equal(property, lookup.GetProperty("p1"));
}
/// <summary>
/// If the property isn't found, should return null
/// </summary>
[Fact]
public void NonexistentProperty()
{
PropertyDictionary<ProjectPropertyInstance> group = new PropertyDictionary<ProjectPropertyInstance>();
Lookup lookup = LookupHelpers.CreateLookup(group);
Assert.Null(lookup.GetProperty("p1"));
lookup.EnterScope("x");
Assert.Null(lookup.GetProperty("p1"));
}
/// <summary>
/// If the property is modified, the updated value should be returned,
/// both before and after leaving scope.
/// </summary>
[Fact]
public void ModifiedProperty()
{
PropertyDictionary<ProjectPropertyInstance> group = new PropertyDictionary<ProjectPropertyInstance>();
group.Set(ProjectPropertyInstance.Create("p1", "v1"));
Lookup lookup = LookupHelpers.CreateLookup(group);
// Enter scope so that property sets are allowed on it
Lookup.Scope enteredScope = lookup.EnterScope("x");
// Change the property value
lookup.SetProperty(ProjectPropertyInstance.Create("p1", "v2"));
// Lookup is updated, but not original item group
Assert.Equal("v2", lookup.GetProperty("p1").EvaluatedValue);
Assert.Equal("v1", group["p1"].EvaluatedValue);
Lookup.Scope enteredScope2 = lookup.EnterScope("x");
// Change the value again in the new scope
lookup.SetProperty(ProjectPropertyInstance.Create("p1", "v3"));
// Lookup is updated, but not the original item group
Assert.Equal("v3", lookup.GetProperty("p1").EvaluatedValue);
Assert.Equal("v1", group["p1"].EvaluatedValue);
Lookup.Scope enteredScope3 = lookup.EnterScope("x");
// Change the value again in the new scope
lookup.SetProperty(ProjectPropertyInstance.Create("p1", "v4"));
Assert.Equal("v4", lookup.GetProperty("p1").EvaluatedValue);
enteredScope3.LeaveScope();
Assert.Equal("v4", lookup.GetProperty("p1").EvaluatedValue);
// Leave to the outer scope
enteredScope2.LeaveScope();
enteredScope.LeaveScope();
// Now the lookup and original group are updated
Assert.Equal("v4", lookup.GetProperty("p1").EvaluatedValue);
Assert.Equal("v4", group["p1"].EvaluatedValue);
}
}
internal class LookupHelpers
{
internal static Lookup CreateEmptyLookup()
{
Lookup lookup = new Lookup(new ItemDictionary<ProjectItemInstance>(), new PropertyDictionary<ProjectPropertyInstance>());
return lookup;
}
internal static Lookup CreateLookup(ItemDictionary<ProjectItemInstance> items)
{
Lookup lookup = new Lookup(items, new PropertyDictionary<ProjectPropertyInstance>());
return lookup;
}
internal static Lookup CreateLookup(PropertyDictionary<ProjectPropertyInstance> properties)
{
Lookup lookup = new Lookup(new ItemDictionary<ProjectItemInstance>(), properties);
return lookup;
}
internal static Lookup CreateLookup(PropertyDictionary<ProjectPropertyInstance> properties, ItemDictionary<ProjectItemInstance> items)
{
Lookup lookup = new Lookup(items, properties);
return lookup;
}
}
}
| |
using Apache.NMS.Util;
using System;
using System.Diagnostics;
using System.Threading;
using Lucene.Net.Documents;
namespace Lucene.Net.Index
{
using Lucene.Net.Randomized.Generators;
using Lucene.Net.Support;
using NUnit.Framework;
using System.IO;
using Directory = Lucene.Net.Store.Directory;
using Document = Documents.Document;
using Field = Field;
using Lucene41PostingsFormat = Lucene.Net.Codecs.Lucene41.Lucene41PostingsFormat;
using LuceneTestCase = Lucene.Net.Util.LuceneTestCase;
/*
* 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 MockAnalyzer = Lucene.Net.Analysis.MockAnalyzer;
using MockDirectoryWrapper = Lucene.Net.Store.MockDirectoryWrapper;
using OpenMode_e = Lucene.Net.Index.IndexWriterConfig.OpenMode_e;
using StringField = StringField;
using TestUtil = Lucene.Net.Util.TestUtil;
using TextField = TextField;
[TestFixture]
public class TestConcurrentMergeScheduler : LuceneTestCase
{
private class FailOnlyOnFlush : MockDirectoryWrapper.Failure
{
private readonly TestConcurrentMergeScheduler OuterInstance;
public FailOnlyOnFlush(TestConcurrentMergeScheduler outerInstance)
{
this.OuterInstance = outerInstance;
}
internal bool DoFail;
internal bool HitExc;
public override void SetDoFail()
{
this.DoFail = true;
HitExc = false;
}
public override void ClearDoFail()
{
this.DoFail = false;
}
public override void Eval(MockDirectoryWrapper dir)
{
if (DoFail && TestThread())
{
bool isDoFlush = false;
bool isClose = false;
var trace = new StackTrace();
foreach (var frame in trace.GetFrames())
{
var method = frame.GetMethod();
if (isDoFlush && isClose)
{
break;
}
if ("flush".Equals(method.Name))
{
isDoFlush = true;
}
if ("close".Equals(method.Name))
{
isClose = true;
}
}
if (isDoFlush && !isClose && Random().NextBoolean())
{
HitExc = true;
throw new IOException(Thread.CurrentThread.Name + ": now failing during flush");
}
}
}
}
// Make sure running BG merges still work fine even when
// we are hitting exceptions during flushing.
[Ignore]
[Test]
public virtual void TestFlushExceptions()
{
MockDirectoryWrapper directory = NewMockDirectory();
FailOnlyOnFlush failure = new FailOnlyOnFlush(this);
directory.FailOn(failure);
IndexWriter writer = new IndexWriter(directory, (IndexWriterConfig)NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetMaxBufferedDocs(2));
Document doc = new Document();
Field idField = NewStringField("id", "", Field.Store.YES);
doc.Add(idField);
int extraCount = 0;
for (int i = 0; i < 10; i++)
{
if (VERBOSE)
{
Console.WriteLine("TEST: iter=" + i);
}
for (int j = 0; j < 20; j++)
{
idField.StringValue = Convert.ToString(i * 20 + j);
writer.AddDocument(doc);
}
// must cycle here because sometimes the merge flushes
// the doc we just added and so there's nothing to
// flush, and we don't hit the exception
while (true)
{
writer.AddDocument(doc);
failure.SetDoFail();
try
{
writer.Flush(true, true);
if (failure.HitExc)
{
Assert.Fail("failed to hit IOException");
}
extraCount++;
}
catch (IOException ioe)
{
if (VERBOSE)
{
Console.WriteLine(ioe.StackTrace);
}
failure.ClearDoFail();
break;
}
}
Assert.AreEqual(20 * (i + 1) + extraCount, writer.NumDocs());
}
writer.Dispose();
IndexReader reader = DirectoryReader.Open(directory);
Assert.AreEqual(200 + extraCount, reader.NumDocs);
reader.Dispose();
directory.Dispose();
}
// Test that deletes committed after a merge started and
// before it finishes, are correctly merged back:
[Test]
public virtual void TestDeleteMerging()
{
Directory directory = NewDirectory();
LogDocMergePolicy mp = new LogDocMergePolicy();
// Force degenerate merging so we can get a mix of
// merging of segments with and without deletes at the
// start:
mp.MinMergeDocs = 1000;
IndexWriter writer = new IndexWriter(directory, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetMergePolicy(mp));
Document doc = new Document();
Field idField = NewStringField("id", "", Field.Store.YES);
doc.Add(idField);
for (int i = 0; i < 10; i++)
{
if (VERBOSE)
{
Console.WriteLine("\nTEST: cycle");
}
for (int j = 0; j < 100; j++)
{
idField.StringValue = Convert.ToString(i * 100 + j);
writer.AddDocument(doc);
}
int delID = i;
while (delID < 100 * (1 + i))
{
if (VERBOSE)
{
Console.WriteLine("TEST: del " + delID);
}
writer.DeleteDocuments(new Term("id", "" + delID));
delID += 10;
}
writer.Commit();
}
writer.Dispose();
IndexReader reader = DirectoryReader.Open(directory);
// Verify that we did not lose any deletes...
Assert.AreEqual(450, reader.NumDocs);
reader.Dispose();
directory.Dispose();
}
[Test, Timeout(300000)]
public virtual void TestNoExtraFiles()
{
Directory directory = NewDirectory();
IndexWriter writer = new IndexWriter(directory, (IndexWriterConfig)NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetMaxBufferedDocs(2));
for (int iter = 0; iter < 7; iter++)
{
if (VERBOSE)
{
Console.WriteLine("TEST: iter=" + iter);
}
for (int j = 0; j < 21; j++)
{
Document doc = new Document();
doc.Add(NewTextField("content", "a b c", Field.Store.NO));
writer.AddDocument(doc);
}
writer.Dispose();
TestIndexWriter.AssertNoUnreferencedFiles(directory, "testNoExtraFiles");
// Reopen
writer = new IndexWriter(directory, (IndexWriterConfig)NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetOpenMode(OpenMode_e.APPEND).SetMaxBufferedDocs(2));
}
writer.Dispose();
directory.Dispose();
}
[Test, Timeout(300000)]
public virtual void TestNoWaitClose()
{
Directory directory = NewDirectory();
Document doc = new Document();
Field idField = NewStringField("id", "", Field.Store.YES);
doc.Add(idField);
IndexWriter writer = new IndexWriter(directory, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetMaxBufferedDocs(2).SetMergePolicy(NewLogMergePolicy(100)));
for (int iter = 0; iter < 10; iter++)
{
for (int j = 0; j < 201; j++)
{
idField.StringValue = Convert.ToString(iter * 201 + j);
writer.AddDocument(doc);
}
int delID = iter * 201;
for (int j = 0; j < 20; j++)
{
writer.DeleteDocuments(new Term("id", Convert.ToString(delID)));
delID += 5;
}
// Force a bunch of merge threads to kick off so we
// stress out aborting them on close:
((LogMergePolicy)writer.Config.MergePolicy).MergeFactor = 3;
writer.AddDocument(doc);
writer.Commit();
writer.Dispose(false);
IndexReader reader = DirectoryReader.Open(directory);
Assert.AreEqual((1 + iter) * 182, reader.NumDocs);
reader.Dispose();
// Reopen
writer = new IndexWriter(directory, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetOpenMode(OpenMode_e.APPEND).SetMergePolicy(NewLogMergePolicy(100)));
}
writer.Dispose();
directory.Dispose();
}
// LUCENE-4544
[Test]
public virtual void TestMaxMergeCount()
{
Directory dir = NewDirectory();
IndexWriterConfig iwc = new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random()));
int maxMergeCount = TestUtil.NextInt(Random(), 1, 5);
int maxMergeThreads = TestUtil.NextInt(Random(), 1, maxMergeCount);
CountDownLatch enoughMergesWaiting = new CountDownLatch(maxMergeCount);
AtomicInteger runningMergeCount = new AtomicInteger(0);
AtomicBoolean failed = new AtomicBoolean();
if (VERBOSE)
{
Console.WriteLine("TEST: maxMergeCount=" + maxMergeCount + " maxMergeThreads=" + maxMergeThreads);
}
ConcurrentMergeScheduler cms = new ConcurrentMergeSchedulerAnonymousInnerClassHelper(this, maxMergeCount, enoughMergesWaiting, runningMergeCount, failed);
cms.SetMaxMergesAndThreads(maxMergeCount, maxMergeThreads);
iwc.SetMergeScheduler(cms);
iwc.SetMaxBufferedDocs(2);
TieredMergePolicy tmp = new TieredMergePolicy();
iwc.SetMergePolicy(tmp);
tmp.MaxMergeAtOnce = 2;
tmp.SegmentsPerTier = 2;
IndexWriter w = new IndexWriter(dir, iwc);
Document doc = new Document();
doc.Add(NewField("field", "field", TextField.TYPE_NOT_STORED));
while (enoughMergesWaiting.Remaining != 0 && !failed.Get())
{
for (int i = 0; i < 10; i++)
{
w.AddDocument(doc);
}
}
w.Dispose(false);
dir.Dispose();
}
private class ConcurrentMergeSchedulerAnonymousInnerClassHelper : ConcurrentMergeScheduler
{
private readonly TestConcurrentMergeScheduler OuterInstance;
private int MaxMergeCount;
private CountDownLatch EnoughMergesWaiting;
private AtomicInteger RunningMergeCount;
private AtomicBoolean Failed;
public ConcurrentMergeSchedulerAnonymousInnerClassHelper(TestConcurrentMergeScheduler outerInstance, int maxMergeCount, CountDownLatch enoughMergesWaiting, AtomicInteger runningMergeCount, AtomicBoolean failed)
{
this.OuterInstance = outerInstance;
this.MaxMergeCount = maxMergeCount;
this.EnoughMergesWaiting = enoughMergesWaiting;
this.RunningMergeCount = runningMergeCount;
this.Failed = failed;
}
protected override void DoMerge(MergePolicy.OneMerge merge)
{
try
{
// Stall all incoming merges until we see
// maxMergeCount:
int count = RunningMergeCount.IncrementAndGet();
try
{
Assert.IsTrue(count <= MaxMergeCount, "count=" + count + " vs maxMergeCount=" + MaxMergeCount);
EnoughMergesWaiting.countDown();
// Stall this merge until we see exactly
// maxMergeCount merges waiting
while (true)
{
// wait for 10 milliseconds
if (EnoughMergesWaiting.@await(new TimeSpan(0, 0, 0, 0, 10)) || Failed.Get())
{
break;
}
}
// Then sleep a bit to give a chance for the bug
// (too many pending merges) to appear:
Thread.Sleep(20);
base.DoMerge(merge);
}
finally
{
RunningMergeCount.DecrementAndGet();
}
}
catch (Exception t)
{
Failed.Set(true);
Writer.MergeFinish(merge);
throw new Exception(t.Message, t);
}
}
}
private class TrackingCMS : ConcurrentMergeScheduler
{
internal long TotMergedBytes;
public TrackingCMS()
{
SetMaxMergesAndThreads(5, 5);
}
protected override void DoMerge(MergePolicy.OneMerge merge)
{
TotMergedBytes += merge.TotalBytesSize();
base.DoMerge(merge);
}
}
[Test, Timeout(300000)]
public virtual void TestTotalBytesSize()
{
Directory d = NewDirectory();
if (d is MockDirectoryWrapper)
{
((MockDirectoryWrapper)d).Throttling = MockDirectoryWrapper.Throttling_e.NEVER;
}
IndexWriterConfig iwc = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random()));
iwc.SetMaxBufferedDocs(5);
iwc.SetMergeScheduler(new TrackingCMS());
if (TestUtil.GetPostingsFormat("id").Equals("SimpleText"))
{
// no
iwc.SetCodec(TestUtil.AlwaysPostingsFormat(new Lucene41PostingsFormat()));
}
RandomIndexWriter w = new RandomIndexWriter(Random(), d, iwc);
for (int i = 0; i < 1000; i++)
{
Document doc = new Document();
doc.Add(new StringField("id", "" + i, Field.Store.NO));
w.AddDocument(doc);
if (Random().NextBoolean())
{
w.DeleteDocuments(new Term("id", "" + Random().Next(i + 1)));
}
}
Assert.IsTrue(((TrackingCMS)w.w.Config.MergeScheduler).TotMergedBytes != 0);
w.Dispose();
d.Dispose();
}
}
}
| |
// Author: abi
// Project: DungeonQuest
// Path: C:\code\Xna\DungeonQuest\GameLogic
// Creation date: 28.03.2007 01:01
// Last modified: 31.07.2007 04:39
#region Using directives
using System;
using System.Collections.Generic;
using System.Text;
using DungeonQuest.Shaders;
using DungeonQuest.Graphics;
using DungeonQuest.Helpers;
using DungeonQuest.GameScreens;
using DungeonQuest.Game;
using Material = DungeonQuest.Graphics.Material;
using Microsoft.Xna.Framework;
using DungeonQuest.Sounds;
using DungeonQuest.Collision;
#endregion
namespace DungeonQuest.Game
{
/// <summary>
/// Unit values, used for both the GameAsteroidManager to keep all
/// enemy units in the current level and in UnitManager for all active
/// units we are currently rendering.
/// </summary>
public class Projectile
{
#region Variables
/// <summary>
/// Damage this unit currently does. Copied from unit settings,
/// but increase as the level advances.
/// </summary>
public float damage = 5;
/// <summary>
/// Helper for plasma and fireball effects, rotation is calculated
/// once in constructor and used for the effects.
/// </summary>
public float effectRotation;
/// <summary>
/// Max speed for this unit (calculated from unit settings, increased
/// a little for each level). Any movement is limited by this value.
/// Units don't have to fly as fast as this value, this is just the limit.
/// </summary>
public float maxSpeed;
/// <summary>
/// Current position of this unit, will be updated each frame.
/// Absolute position in 3d space.
/// </summary>
public Vector3 position;
/// <summary>
/// Move direction, not used for plasma projectiles, but fireballs will
/// be moving towards the player (but not change direction during flight).
/// Rockets on the other hand will slowly adjust to the player position.
/// </summary>
public Vector3 moveDirection;
/// <summary>
/// Own projectile? Then it flys up and damages enemies, else it
/// is an enemy projectile!
/// </summary>
public bool ownProjectile = false;
/// <summary>
/// Life time of this projectile, will die after 6 seconds!
/// </summary>
private float lifeTimeMs = 0;
#endregion
#region Constructor
/// <summary>
/// Create unit of specific type at specific location.
/// </summary>
/// <param name="setType">Set type</param>
/// <param name="setPosition">Set position</param>
public Projectile(//WeaponTypes setType,
Vector3 setPosition)//,
//bool setOwnProjectile)
{
//obs: weaponType = setType;
position = setPosition;
//obs: ownProjectile = setOwnProjectile;
// 300 dmg for plasma, 1000 for rockets
//see above: damage = weaponType == WeaponTypes.Plasma ? 300 : 1000;
/*
if (ownProjectile == false)
{
if (weaponType == WeaponTypes.Fireball)
{
*/
Vector3 distVec = BaseGame.camera.PlayerPos - position;
moveDirection = Vector3.Normalize(
BaseGame.camera.PlayerPos +
//new Vector3(0, distVec.Length() / 3, 0) -
new Vector3(0, 0, 1.25f) -
position);
//see above: damage = 70;// 75;
/*
} // if
else if (weaponType == WeaponTypes.Rocket)
{
moveDirection = new Vector3(0, -1, 0);
damage = 110;// 125;
} // else if
} // if
*/
/*tst
if (weaponType == WeaponTypes.Rocket)
maxSpeed = 30;//80;
else if (weaponType == WeaponTypes.Plasma)
maxSpeed = 75;//150;
else if (weaponType == WeaponTypes.Fireball)
*/
maxSpeed = 8;// 20;//45;
//if (weaponType == WeaponTypes.Plasma ||
// weaponType == WeaponTypes.Fireball)
effectRotation = RandomHelper.GetRandomFloat(
0, (float)Math.PI * 2.0f);
} // Unit(setType, setPosition, setLevel)
#endregion
#region Get rotation angle
private float GetRotationAngle(Vector3 pos1, Vector3 pos2)
{
// See http://en.wikipedia.org/wiki/Vector_(spatial)
// for help and check out the Dot Product section ^^
// Both vectors are normalized so we can save deviding through the
// lengths.
Vector3 vec1 = new Vector3(0, 1, 0);
Vector3 vec2 = pos1 - pos2;
vec2.Normalize();
return (float)Math.Acos(Vector3.Dot(vec1, vec2));
} // GetRotationAngle(pos1, pos2)
private float GetRotationAngle(Vector3 vec)
{
return (float)Math.Atan2(vec.Y, vec.X);
} // GetRotationAngle(pos1, pos2)
#endregion
#region Render
/// <summary>
/// Render projectile, returns false if we are done with it.
/// Has to be removed then. Else it updates just position.
/// </summary>
/// <returns>True if done, false otherwise</returns>
public bool Render()
{
#region Update movement
lifeTimeMs += BaseGame.ElapsedTimeThisFrameInMs;
float moveSpeed = BaseGame.MoveFactorPerSecond;
if (Player.GameOver)
moveSpeed = 0;
/*
switch (weaponType)
{
case WeaponTypes.Fireball:
*/
Vector3 oldPosition = position;
position += moveDirection * maxSpeed * moveSpeed;
/*
break;
case WeaponTypes.Rocket:
if (ownProjectile)
position += new Vector3(0, +1, 0) * maxSpeed * moveSpeed * 1.1f;
else
{
// Fly to player
Vector3 targetMovement = Player.shipPos - position;
targetMovement.Normalize();
moveDirection = moveDirection * 0.95f + targetMovement * 0.05f;
moveDirection.Normalize();
position += moveDirection * maxSpeed * moveSpeed;
} // else
break;
case WeaponTypes.Plasma:
if (ownProjectile)
position += new Vector3(0, +1, 0) * maxSpeed * moveSpeed * 1.25f;
else
position += new Vector3(0, -1, 0) * maxSpeed * moveSpeed;
break;
// Rest are items, they just stay around
} // switch(movementPattern)
*/
#endregion
#region Skip if out of visible range
float distance = (position - BaseGame.camera.PlayerPos).Length();
const float MaxUnitDistance = BaseGame.FarPlane;
// Remove unit if it is out of visible range!
if (distance > MaxUnitDistance)/*tst ||
distance < -MaxUnitDistance * 2 ||
position.Z < 0 ||
lifeTimeMs > 6000)*/
return true;
// Also check if fireball is hitting a wall
Vector3 newPosition = position;
Vector3 newVelocity = moveDirection * maxSpeed * moveSpeed;
Vector3 polyPoint;
CaveCollision.caveCollision.PointMove(
oldPosition, position, 0.0f, 1.0f, 3,
out newPosition, ref newVelocity, out polyPoint);
if (Vector3.Distance(newPosition, position) > 0.01f)
return true;
#endregion
#region Render
/*
switch (weaponType)
{
case WeaponTypes.Rocket:
float rocketRotation = MathHelper.Pi;
if (ownProjectile == false)
rocketRotation = MathHelper.PiOver2 + GetRotationAngle(moveDirection);
mission.AddModelToRender(
mission.shipModels[(int)Mission.ShipModelTypes.Rocket],
Matrix.CreateScale(
(ownProjectile ? 1.25f : 0.75f) *
Mission.ShipModelSize[(int)Mission.ShipModelTypes.Rocket]) *
Matrix.CreateRotationZ(rocketRotation) *
Matrix.CreateTranslation(position));
// Add rocket smoke
EffectManager.AddRocketOrShipFlareAndSmoke(position, 1.5f, 6 * maxSpeed);
break;
case WeaponTypes.Plasma:
EffectManager.AddPlasmaEffect(position, effectRotation, 1.25f);
break;
case WeaponTypes.Fireball:
*/
EffectManager.AddFireBallEffect(position, effectRotation, 0.25f);
/* break;
} // switch
*/
#endregion
#region Explode if hitting unit
/*
// Own projectile?
if (ownProjectile)
{
// Hit enemy units, check all of them
for (int num = 0; num < Mission.units.Count; num++)
{
Unit enemyUnit = Mission.units[num];
// Near enough to enemy ship?
Vector2 distVec =
new Vector2(enemyUnit.position.X, enemyUnit.position.Y) -
new Vector2(position.X, position.Y);
if (distVec.Length() < 7 &&
(enemyUnit.position.Y - Player.shipPos.Y) < 60)
{
// Explode and do damage!
EffectManager.AddFlameExplosion(position);
Player.score += (int)enemyUnit.hitpoints / 10;
enemyUnit.hitpoints -= damage;
return true;
} // if
} // for
} // if
// Else this is an enemy projectile?
else
{
*/
// Near enough to our player?
Vector2 distVec =
new Vector2(BaseGame.camera.PlayerPos.X, BaseGame.camera.PlayerPos.Y) -
new Vector2(position.X, position.Y);
if (distVec.Length() < 0.275f)//0.25f)
{
// Explode and do damage!
EffectManager.AddFlameExplosion(position);
Player.health -= 10+Player.level/2-Player.defenseIncrease;//14;
Sound.Play(Sound.Sounds.PlayerWasHit);
return true;
} // if
//} // else
#endregion
// Don't remove unit from units list
return false;
} // Render()
#endregion
} // class Unit
} // namespace DungeonQuest.Game
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Signum.Engine.Basics;
using Signum.Engine.Templating;
using Signum.Entities;
using Signum.Entities.Basics;
using Signum.Entities.DynamicQuery;
using Signum.Entities.Mailing;
using Signum.Entities.UserQueries;
using Signum.Utilities;
namespace Signum.Engine.Mailing
{
class EmailMessageBuilder
{
EmailTemplateEntity template;
Entity? entity;
IEmailModel? model;
object queryName;
QueryDescription qd;
EmailSenderConfigurationEntity? smtpConfig;
CultureInfo? cultureInfo;
public EmailMessageBuilder(EmailTemplateEntity template, Entity? entity, IEmailModel? systemEmail, CultureInfo? cultureInfo)
{
this.template = template;
this.entity = entity;
this.model = systemEmail;
this.queryName = QueryLogic.ToQueryName(template.Query.Key);
this.qd = QueryLogic.Queries.QueryDescription(queryName);
this.smtpConfig = EmailTemplateLogic.GetSmtpConfiguration?.Invoke(template, (systemEmail?.UntypedEntity as Entity)?.ToLiteFat(), null);
this.cultureInfo = cultureInfo;
}
ResultTable table = null!;
Dictionary<QueryToken, ResultColumn> dicTokenColumn = null!;
IEnumerable<ResultRow> currentRows = null!;
public IEnumerable<EmailMessageEntity> CreateEmailMessageInternal()
{
ExecuteQuery();
foreach (EmailFromEmbedded from in GetFrom())
{
foreach (List<EmailOwnerRecipientData> recipients in GetRecipients())
{
EmailMessageEntity email = CreateEmailMessageInternal(from, recipients);
yield return email;
}
}
}
private EmailMessageEntity CreateEmailMessageInternal(EmailFromEmbedded from, List<EmailOwnerRecipientData> recipients)
{
EmailMessageEntity email;
try
{
var ci = this.cultureInfo ??
EmailTemplateLogic.GetCultureInfo?.Invoke(entity ?? model?.UntypedEntity as Entity) ??
recipients.Where(a => a.Kind == EmailRecipientKind.To).Select(a => a.OwnerData.CultureInfo).FirstOrDefault()?.ToCultureInfo() ??
EmailLogic.Configuration.DefaultCulture.ToCultureInfo();
email = new EmailMessageEntity
{
Target = entity?.ToLite() ?? (this.model!.UntypedEntity as Entity)?.ToLite(),
Recipients = recipients.Select(r => new EmailRecipientEmbedded(r.OwnerData) { Kind = r.Kind }).ToMList(),
From = from,
IsBodyHtml = template.IsBodyHtml,
EditableMessage = template.EditableMessage,
Template = template.ToLite(),
Attachments = template.Attachments.SelectMany(g => EmailTemplateLogic.GenerateAttachment.Invoke(g,
new EmailTemplateLogic.GenerateAttachmentContext(this.qd, template, dicTokenColumn, currentRows, ci)
{
ModelType = template.Model?.ToType(),
Model = model,
Entity = entity,
})).ToMList()
};
EmailTemplateMessageEmbedded? message =
template.GetCultureMessage(ci) ??
template.GetCultureMessage(ci.Parent) ??
template.GetCultureMessage(EmailLogic.Configuration.DefaultCulture.ToCultureInfo()) ??
template.GetCultureMessage(EmailLogic.Configuration.DefaultCulture.ToCultureInfo().Parent);
if (message == null)
throw new InvalidOperationException("Message {0} does not have a message for CultureInfo {1} (or Default)".FormatWith(template, ci));
using (CultureInfoUtils.ChangeBothCultures(ci))
{
email.Subject = SubjectNode(message).Print(
new TextTemplateParameters(entity, ci, dicTokenColumn, currentRows)
{
IsHtml = false,
Model = model
});
email.Body = new BigStringEmbedded(TextNode(message).Print(
new TextTemplateParameters(entity, ci, dicTokenColumn, currentRows)
{
IsHtml = template.IsBodyHtml,
Model = model,
}));
}
}
catch (Exception ex)
{
ex.Data["Template"] = this.template.ToLite();
ex.Data["Model"] = this.model;
ex.Data["Entity"] = this.entity;
throw;
}
return email;
}
TextTemplateParser.BlockNode TextNode(EmailTemplateMessageEmbedded message)
{
if (message.TextParsedNode == null)
{
string body = message.Text;
if (template.MasterTemplate != null)
{
var emt = template.MasterTemplate.RetrieveAndRemember();
var emtm =
emt.GetCultureMessage(message.CultureInfo.ToCultureInfo()) ??
emt.GetCultureMessage(message.CultureInfo.ToCultureInfo().Parent) ??
emt.GetCultureMessage(EmailLogic.Configuration.DefaultCulture.ToCultureInfo()) ??
emt.GetCultureMessage(EmailLogic.Configuration.DefaultCulture.ToCultureInfo().Parent);
if (emtm != null)
body = EmailMasterTemplateEntity.MasterTemplateContentRegex.Replace(emtm.Text, m => body);
}
message.TextParsedNode = TextTemplateParser.Parse(body, qd, template.Model?.ToType());
}
return (TextTemplateParser.BlockNode)message.TextParsedNode;
}
TextTemplateParser.BlockNode SubjectNode(EmailTemplateMessageEmbedded message)
{
if (message.SubjectParsedNode == null)
message.SubjectParsedNode = TextTemplateParser.Parse(message.Subject, qd, template.Model?.ToType());
return (TextTemplateParser.BlockNode)message.SubjectParsedNode;
}
IEnumerable<EmailFromEmbedded> GetFrom()
{
if (template.From != null)
{
if (template.From.Token != null)
{
ResultColumn owner = dicTokenColumn.GetOrThrow(template.From.Token.Token);
var groups = currentRows.GroupBy(r => (EmailOwnerData)r[owner]!).ToList();
var groupsWithEmail = groups.Where(a => a.Key.Email.HasText()).ToList();
if (groupsWithEmail.IsEmpty())
{
switch (template.From.WhenNone)
{
case WhenNoneFromBehaviour.ThrowException:
if (groups.Count() == 0)
throw new InvalidOperationException($"Impossible to send {this.template} because From Token ({template.From.Token}) returned no result");
else
throw new InvalidOperationException($"Impossible to send {this.template} because From Token ({template.From.Token}) returned results without Email addresses");
case WhenNoneFromBehaviour.NoMessage:
yield break;
case WhenNoneFromBehaviour.DefaultFrom:
if (smtpConfig != null && smtpConfig.DefaultFrom != null)
yield return smtpConfig.DefaultFrom.Clone();
else
throw new InvalidOperationException("Not Default From found");
break;
default:
throw new UnexpectedValueException(template.From.WhenNone);
}
}
else
{
if (template.From.WhenMany == WhenManyFromBehaviour.FistResult)
groupsWithEmail = groupsWithEmail.Take(1).ToList();
foreach (var gr in groupsWithEmail)
{
var old = currentRows;
currentRows = gr;
yield return new EmailFromEmbedded(gr.Key);
currentRows = old;
}
}
}
else
{
yield return new EmailFromEmbedded
{
EmailOwner = null,
EmailAddress = template.From.EmailAddress!,
DisplayName = template.From.DisplayName,
AzureUserId = template.From.AzureUserId,
};
}
}
else
{
if (smtpConfig != null && smtpConfig.DefaultFrom != null)
{
yield return smtpConfig.DefaultFrom.Clone();
}
else
{
throw new InvalidOperationException("Not Default From found");
}
}
}
IEnumerable<List<EmailOwnerRecipientData>> GetRecipients()
{
foreach (List<EmailOwnerRecipientData> recipients in TokenRecipientsCrossProduct(template.Recipients.Where(a => a.Token != null).ToList(), 0))
{
recipients.AddRange(template.Recipients.Where(a => a.Token == null).Select(tr => new EmailOwnerRecipientData(new EmailOwnerData
{
CultureInfo = null,
Email = tr.EmailAddress!,
DisplayName = tr.DisplayName
})
{ Kind = tr.Kind }));
if (model != null)
recipients.AddRange(model.GetRecipients());
if (smtpConfig != null)
{
recipients.AddRange(smtpConfig.AdditionalRecipients.Where(a => a.EmailOwner == null).Select(r =>
new EmailOwnerRecipientData(new EmailOwnerData { CultureInfo = null, DisplayName = r.DisplayName, Email = r.EmailAddress, Owner = r.EmailOwner }) { Kind = r.Kind }));
}
if (recipients.Where(r => r.OwnerData.Email.HasText()).Any())
yield return recipients;
}
}
private IEnumerable<List<EmailOwnerRecipientData>> TokenRecipientsCrossProduct(List<EmailTemplateRecipientEmbedded> tokenRecipients, int pos)
{
if (tokenRecipients.Count == pos)
yield return new List<EmailOwnerRecipientData>();
else
{
EmailTemplateRecipientEmbedded tr = tokenRecipients[pos];
ResultColumn owner = dicTokenColumn.GetOrThrow(tr.Token!.Token);
var groups = currentRows.GroupBy(r => (EmailOwnerData)r[owner]!).ToList();
var groupsWithEmail = groups.Where(a => a.Key.Email.HasText()).ToList();
if (groupsWithEmail.IsEmpty())
{
switch (tr.WhenNone)
{
case WhenNoneRecipientsBehaviour.ThrowException:
if (groups.Count() == 0)
throw new InvalidOperationException($"Impossible to send {this.template} because {tr.Kind} Token ({tr.Token}) returned no result");
else
throw new InvalidOperationException($"Impossible to send {this.template} because {tr.Kind} Token ({tr.Token}) returned results without Email addresses");
case WhenNoneRecipientsBehaviour.NoMessage:
yield break;
case WhenNoneRecipientsBehaviour.NoRecipients:
foreach (var item in TokenRecipientsCrossProduct(tokenRecipients, pos + 1))
{
yield return item;
}
break;
default:
throw new UnexpectedValueException(tr.WhenNone);
}
}
else
{
if (tr.WhenMany == WhenManyRecipiensBehaviour.SplitMessages)
{
foreach (var gr in groupsWithEmail)
{
var rec = new EmailOwnerRecipientData(gr.Key) { Kind = tr.Kind };
var old = currentRows;
currentRows = gr;
foreach (var list in TokenRecipientsCrossProduct(tokenRecipients, pos + 1))
{
var result = list.ToList();
result.Insert(0, rec);
yield return result;
}
currentRows = old;
}
}
else if (tr.WhenMany == WhenManyRecipiensBehaviour.KeepOneMessageWithManyRecipients)
{
var recipients = groupsWithEmail.Select(g => new EmailOwnerRecipientData(g.Key) { Kind = tr.Kind }).ToList();
foreach (var list in TokenRecipientsCrossProduct(tokenRecipients, pos + 1))
{
var result = list.ToList();
result.InsertRange(0, recipients);
yield return result;
}
}
else
{
throw new UnexpectedValueException(tr.WhenMany);
}
}
}
}
void ExecuteQuery()
{
using (this.template.DisableAuthorization ? ExecutionMode.Global() : null)
{
List<QueryToken> tokens = new List<QueryToken>();
if (template.From != null && template.From.Token != null)
tokens.Add(template.From.Token.Token);
foreach (var tr in template.Recipients.Where(r => r.Token != null))
tokens.Add(tr.Token!.Token);
foreach (var t in template.Messages)
{
TextNode(t).FillQueryTokens(tokens);
SubjectNode(t).FillQueryTokens(tokens);
}
foreach (var a in template.Attachments)
{
EmailTemplateLogic.FillAttachmentTokens.Invoke(a, new EmailTemplateLogic.FillAttachmentTokenContext(qd, tokens)
{
ModelType = template.Model?.ToType(),
});
}
var columns = tokens.Distinct().Select(qt => new Column(qt, null)).ToList();
var filters = model != null ? model.GetFilters(qd) :
entity != null ? new List<Filter> { new FilterCondition(QueryUtils.Parse("Entity", qd, 0), FilterOperation.EqualTo, entity!.ToLite()) } :
throw new InvalidOperationException($"Impossible to create a Word report if '{nameof(entity)}' and '{nameof(model)}' are both null");
filters.AddRange(template.Filters.ToFilterList());
var orders = model?.GetOrders(qd) ?? new List<Order>();
orders.AddRange(template.Orders.Select(qo => new Order(qo.Token.Token, qo.OrderType)).ToList());
this.table = QueryLogic.Queries.ExecuteQuery(new QueryRequest
{
QueryName = queryName,
GroupResults = template.GroupResults,
Columns = columns,
Pagination = model?.GetPagination() ?? new Pagination.All(),
Filters = filters,
Orders = orders,
});
this.dicTokenColumn = table.Columns.ToDictionary(rc => rc.Column.Token);
this.currentRows = table.Rows;
}
}
}
}
| |
// TypeTest.cs - NUnit Test Cases for the System.Type class
//
// Authors:
// Zoltan Varga ([email protected])
// Patrik Torstensson
//
// (C) 2003 Ximian, Inc. http://www.ximian.com
//
using NUnit.Framework;
using System;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
class NoNamespaceClass {
}
namespace MonoTests.System
{
class Super : ICloneable {
public virtual object Clone () {
return null;
}
}
class Duper: Super {
}
interface IFace1 {
void foo ();
}
interface IFace2 : IFace1 {
void bar ();
}
interface IFace3 : IFace2 {
}
enum TheEnum { A, B, C };
abstract class Base {
public int level;
public abstract int this [byte i] { get; }
public abstract int this [int i] { get; }
public abstract void TestVoid();
public abstract void TestInt(int i);
}
class DeriveVTable : Base {
public override int this [byte i] { get { return 1; } }
public override int this [int i] { get { return 1; } }
public override void TestVoid() { level = 1; }
public override void TestInt(int i) { level = 1; }
}
class NewVTable : DeriveVTable {
public new int this [byte i] { get { return 2; } }
public new int this [int i] { get { return 2; } }
public new void TestVoid() { level = 2; }
public new void TestInt(int i) { level = 2; }
public void Overload () { }
public void Overload (int i) { }
public NewVTable (out int i) {
i = 0;
}
public void byref_method (out int i) {
i = 0;
}
}
class Base1 {
public virtual int Foo {
get {
return 1;
}
set {
}
}
}
class Derived1 : Base1 {
public override int Foo {
set {
}
}
}
[TestFixture]
public class TypeTest : Assertion
{
private void ByrefMethod (ref int i, ref Derived1 j, ref Base1 k) {
}
[Test]
public void TestIsAssignableFrom () {
// Simple tests for inheritance
AssertEquals ("#01", typeof (Super).IsAssignableFrom (typeof (Duper)) , true);
AssertEquals ("#02", typeof (Duper).IsAssignableFrom (typeof (Duper)) , true);
AssertEquals ("#03", typeof (Object).IsAssignableFrom (typeof (Duper)) , true);
AssertEquals ("#04", typeof (ICloneable).IsAssignableFrom (typeof (Duper)) , true);
// Tests for arrays
AssertEquals ("#05", typeof (Super[]).IsAssignableFrom (typeof (Duper[])) , true);
AssertEquals ("#06", typeof (Duper[]).IsAssignableFrom (typeof (Super[])) , false);
AssertEquals ("#07", typeof (Object[]).IsAssignableFrom (typeof (Duper[])) , true);
AssertEquals ("#08", typeof (ICloneable[]).IsAssignableFrom (typeof (Duper[])) , true);
// Tests for multiple dimensional arrays
AssertEquals ("#09", typeof (Super[][]).IsAssignableFrom (typeof (Duper[][])) , true);
AssertEquals ("#10", typeof (Duper[][]).IsAssignableFrom (typeof (Super[][])) , false);
AssertEquals ("#11", typeof (Object[][]).IsAssignableFrom (typeof (Duper[][])) , true);
AssertEquals ("#12", typeof (ICloneable[][]).IsAssignableFrom (typeof (Duper[][])) , true);
// Tests for vectors<->one dimensional arrays */
Array arr1 = Array.CreateInstance (typeof (int), new int[] {1}, new int[] {0});
Array arr2 = Array.CreateInstance (typeof (int), new int[] {1}, new int[] {10});
AssertEquals ("#13", typeof (int[]).IsAssignableFrom (arr1.GetType ()), true);
AssertEquals ("#14", typeof (int[]).IsAssignableFrom (arr2.GetType ()), false);
// Test that arrays of enums can be cast to their base types
AssertEquals ("#15", typeof (int[]).IsAssignableFrom (typeof (TypeCode[])) , true);
// Test that arrays of valuetypes can't be cast to arrays of
// references
AssertEquals ("#16", typeof (object[]).IsAssignableFrom (typeof (TypeCode[])) , false);
AssertEquals ("#17", typeof (ValueType[]).IsAssignableFrom (typeof (TypeCode[])) , false);
AssertEquals ("#18", typeof (Enum[]).IsAssignableFrom (typeof (TypeCode[])) , false);
// Test that arrays of enums can't be cast to arrays of references
AssertEquals ("#19", typeof (object[]).IsAssignableFrom (typeof (TheEnum[])) , false);
AssertEquals ("#20", typeof (ValueType[]).IsAssignableFrom (typeof (TheEnum[])) , false);
AssertEquals ("#21", typeof (Enum[]).IsAssignableFrom (typeof (TheEnum[])) , false);
// Check that ValueType and Enum are recognized as reference types
AssertEquals ("#22", typeof (object).IsAssignableFrom (typeof (ValueType)) , true);
AssertEquals ("#23", typeof (object).IsAssignableFrom (typeof (Enum)) , true);
AssertEquals ("#24", typeof (ValueType).IsAssignableFrom (typeof (Enum)) , true);
AssertEquals ("#25", typeof (object[]).IsAssignableFrom (typeof (ValueType[])) , true);
AssertEquals ("#26", typeof (ValueType[]).IsAssignableFrom (typeof (ValueType[])) , true);
AssertEquals ("#27", typeof (Enum[]).IsAssignableFrom (typeof (ValueType[])) , false);
AssertEquals ("#28", typeof (object[]).IsAssignableFrom (typeof (Enum[])) , true);
AssertEquals ("#29", typeof (ValueType[]).IsAssignableFrom (typeof (Enum[])) , true);
AssertEquals ("#30", typeof (Enum[]).IsAssignableFrom (typeof (Enum[])) , true);
// Tests for byref types
MethodInfo mi = typeof (TypeTest).GetMethod ("ByrefMethod", BindingFlags.Instance|BindingFlags.NonPublic);
Assert (mi.GetParameters ()[2].ParameterType.IsAssignableFrom (mi.GetParameters ()[1].ParameterType));
Assert (mi.GetParameters ()[1].ParameterType.IsAssignableFrom (mi.GetParameters ()[1].ParameterType));
}
[Test]
public void TestIsSubclassOf () {
Assert ("#01", typeof (ICloneable).IsSubclassOf (typeof (object)));
// Tests for byref types
Type paramType = typeof (TypeTest).GetMethod ("ByrefMethod", BindingFlags.Instance|BindingFlags.NonPublic).GetParameters () [0].ParameterType;
Assert ("#02", !paramType.IsSubclassOf (typeof (ValueType)));
//Assert ("#03", paramType.IsSubclassOf (typeof (Object)));
Assert ("#04", !paramType.IsSubclassOf (paramType));
}
[Test]
public void TestGetMethodImpl() {
// Test binding of new slot methods (using no types)
AssertEquals("#01", typeof (Base), typeof (Base).GetMethod("TestVoid").DeclaringType);
AssertEquals("#02", typeof (NewVTable), typeof (NewVTable).GetMethod("TestVoid").DeclaringType);
// Test binding of new slot methods (using types)
AssertEquals("#03", typeof (Base), typeof (Base).GetMethod("TestInt", new Type [] { typeof(int) }).DeclaringType);
AssertEquals("#04", typeof (NewVTable), typeof (NewVTable).GetMethod("TestInt", new Type [] { typeof(int) }).DeclaringType);
// Test overload resolution
AssertEquals ("#05", 0, typeof (NewVTable).GetMethod ("Overload", new Type [0]).GetParameters ().Length);
// Test byref parameters
AssertEquals ("#06", null, typeof (NewVTable).GetMethod ("byref_method", new Type [] { typeof (int) }));
Type byrefInt = typeof (NewVTable).GetMethod ("byref_method").GetParameters ()[0].ParameterType;
AssertNotNull ("#07", typeof (NewVTable).GetMethod ("byref_method", new Type [] { byrefInt }));
}
[Test]
public void TestGetPropertyImpl() {
// Test getting property that is exact
AssertEquals("#01", typeof (NewVTable), typeof (NewVTable).GetProperty("Item", new Type[1] { typeof(Int32) }).DeclaringType);
// Test getting property that is not exact
AssertEquals("#02", typeof (NewVTable), typeof (NewVTable).GetProperty("Item", new Type[1] { typeof(Int16) }).DeclaringType);
// Test overriding of properties when only the set accessor is overriden
AssertEquals ("#03", 1, typeof (Derived1).GetProperties ().Length);
}
[StructLayout(LayoutKind.Explicit, Pack = 4, Size = 64)]
public class Class1 {
}
[StructLayout(LayoutKind.Explicit, CharSet=CharSet.Unicode)]
public class Class2 {
}
#if NET_2_0
[Test]
public void StructLayoutAttribute () {
StructLayoutAttribute attr1 = typeof (TypeTest).StructLayoutAttribute;
AssertEquals (LayoutKind.Auto, attr1.Value);
StructLayoutAttribute attr2 = typeof (Class1).StructLayoutAttribute;
AssertEquals (LayoutKind.Explicit, attr2.Value);
AssertEquals (4, attr2.Pack);
AssertEquals (64, attr2.Size);
StructLayoutAttribute attr3 = typeof (Class2).StructLayoutAttribute;
AssertEquals (LayoutKind.Explicit, attr3.Value);
AssertEquals (CharSet.Unicode, attr3.CharSet);
}
#endif
[Test]
public void Namespace () {
AssertEquals (null, typeof (NoNamespaceClass).Namespace);
}
[Test]
public void GetInterfaces () {
Type[] t = typeof (Duper).GetInterfaces ();
AssertEquals (1, t.Length);
AssertEquals (typeof (ICloneable), t [0]);
Type[] t2 = typeof (IFace3).GetInterfaces ();
AssertEquals (2, t2.Length);
}
public int AField;
[Test]
public void GetFieldIgnoreCase () {
AssertNotNull (typeof (TypeTest).GetField ("afield", BindingFlags.Instance|BindingFlags.Public|BindingFlags.IgnoreCase));
}
#if NET_2_0
public int Count {
internal get {
return 0;
}
set {
}
}
[Test]
public void GetPropertyAccessorModifiers () {
AssertNotNull (typeof (TypeTest).GetProperty ("Count", BindingFlags.Instance | BindingFlags.Public));
AssertNull (typeof (TypeTest).GetProperty ("Count", BindingFlags.Instance | BindingFlags.NonPublic));
}
#endif
[Test]
public void IsPrimitive () {
Assert (typeof (IntPtr).IsPrimitive);
}
[Test]
[Category("NotDotNet")]
// Depends on the GAC working, which it doesn't durring make distcheck.
[Category ("NotWorking")]
public void GetTypeWithWhitespace () {
AssertNotNull (Type.GetType
(@"System.Configuration.NameValueSectionHandler,
System,
Version=1.0.5000.0,
Culture=neutral
,
PublicKeyToken=b77a5c561934e089"));
}
[Test]
public void ExerciseFilterName() {
MemberInfo[] mi = typeof(Base).FindMembers(
MemberTypes.Method,
BindingFlags.Public | BindingFlags.Static | BindingFlags.NonPublic |
BindingFlags.Instance | BindingFlags.DeclaredOnly,
Type.FilterName, "*");
AssertEquals(4, mi.Length);
mi = typeof(Base).FindMembers(
MemberTypes.Method,
BindingFlags.Public | BindingFlags.Static | BindingFlags.NonPublic |
BindingFlags.Instance | BindingFlags.DeclaredOnly,
Type.FilterName, "Test*");
AssertEquals(2, mi.Length);
mi = typeof(Base).FindMembers(
MemberTypes.Method,
BindingFlags.Public | BindingFlags.Static | BindingFlags.NonPublic |
BindingFlags.Instance | BindingFlags.DeclaredOnly,
Type.FilterName, "TestVoid");
AssertEquals(1, mi.Length);
mi = typeof(Base).FindMembers(
MemberTypes.Method,
BindingFlags.Public | BindingFlags.Static | BindingFlags.NonPublic |
BindingFlags.Instance | BindingFlags.DeclaredOnly,
Type.FilterName, "NonExistingMethod");
AssertEquals(0, mi.Length);
}
[Test]
public void ExerciseFilterNameIgnoreCase() {
MemberInfo[] mi = typeof(Base).FindMembers(
MemberTypes.Method,
BindingFlags.Public | BindingFlags.Static | BindingFlags.NonPublic |
BindingFlags.Instance | BindingFlags.DeclaredOnly,
Type.FilterNameIgnoreCase, "*");
AssertEquals(4, mi.Length);
mi = typeof(Base).FindMembers(
MemberTypes.Method,
BindingFlags.Public | BindingFlags.Static | BindingFlags.NonPublic |
BindingFlags.Instance | BindingFlags.DeclaredOnly,
Type.FilterNameIgnoreCase, "test*");
AssertEquals(2, mi.Length);
mi = typeof(Base).FindMembers(
MemberTypes.Method,
BindingFlags.Public | BindingFlags.Static | BindingFlags.NonPublic |
BindingFlags.Instance | BindingFlags.DeclaredOnly,
Type.FilterNameIgnoreCase, "TESTVOID");
AssertEquals(1, mi.Length);
mi = typeof(Base).FindMembers(
MemberTypes.Method,
BindingFlags.Public | BindingFlags.Static | BindingFlags.NonPublic |
BindingFlags.Instance | BindingFlags.DeclaredOnly,
Type.FilterNameIgnoreCase, "NonExistingMethod");
AssertEquals(0, mi.Length);
}
public int byref_field;
public int byref_property {
get {
return 0;
}
}
[Test]
public void ByrefTypes ()
{
Type t = Type.GetType ("MonoTests.System.TypeTest&");
AssertEquals (0, t.GetMethods (BindingFlags.Public|BindingFlags.Instance).Length);
AssertEquals (0, t.GetConstructors (BindingFlags.Public|BindingFlags.Instance).Length);
AssertEquals (0, t.GetEvents (BindingFlags.Public|BindingFlags.Instance).Length);
AssertEquals (0, t.GetProperties (BindingFlags.Public|BindingFlags.Instance).Length);
AssertNull (t.GetMethod ("ByrefTypes"));
AssertNull (t.GetField ("byref_field"));
AssertNull (t.GetProperty ("byref_property"));
}
struct B
{
int value;
}
[Test]
public void CreateValueTypeNoCtor () {
typeof(B).InvokeMember ("", BindingFlags.CreateInstance, null, null, null);
}
[Test]
[ExpectedException (typeof (MissingMethodException))]
public void CreateValueTypeNoCtorArgs () {
typeof(B).InvokeMember ("", BindingFlags.CreateInstance, null, null, new object [] { 1 });
}
class TakesInt {
public TakesInt (int x) {}
}
class TakesObject {
public TakesObject (object x) {}
}
[Test]
[Category ("NotWorking")] // Filed as bug #75241
public void GetConstructoNullInTypes ()
{
// This ends up calling type.GetConstructor ()
Activator.CreateInstance (typeof (TakesInt), new object [] { null });
Activator.CreateInstance (typeof (TakesObject), new object [] { null });
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Windows.Media;
using Microsoft.VisualStudio.Imaging;
using Microsoft.VisualStudio.Imaging.Interop;
using Microsoft.VisualStudio.Language.Intellisense;
namespace Microsoft.CodeAnalysis.Editor.Shared.Extensions
{
internal static class GlyphExtensions
{
public static StandardGlyphGroup GetStandardGlyphGroup(this Glyph glyph)
{
switch (glyph)
{
case Glyph.Assembly:
return StandardGlyphGroup.GlyphAssembly;
case Glyph.BasicFile:
case Glyph.BasicProject:
return StandardGlyphGroup.GlyphVBProject;
case Glyph.ClassPublic:
case Glyph.ClassProtected:
case Glyph.ClassPrivate:
case Glyph.ClassInternal:
return StandardGlyphGroup.GlyphGroupClass;
case Glyph.ConstantPublic:
case Glyph.ConstantProtected:
case Glyph.ConstantPrivate:
case Glyph.ConstantInternal:
return StandardGlyphGroup.GlyphGroupConstant;
case Glyph.CSharpFile:
return StandardGlyphGroup.GlyphCSharpFile;
case Glyph.CSharpProject:
return StandardGlyphGroup.GlyphCoolProject;
case Glyph.DelegatePublic:
case Glyph.DelegateProtected:
case Glyph.DelegatePrivate:
case Glyph.DelegateInternal:
return StandardGlyphGroup.GlyphGroupDelegate;
case Glyph.EnumPublic:
case Glyph.EnumProtected:
case Glyph.EnumPrivate:
case Glyph.EnumInternal:
return StandardGlyphGroup.GlyphGroupEnum;
case Glyph.EnumMember:
return StandardGlyphGroup.GlyphGroupEnumMember;
case Glyph.Error:
return StandardGlyphGroup.GlyphGroupError;
case Glyph.ExtensionMethodPublic:
return StandardGlyphGroup.GlyphExtensionMethod;
case Glyph.ExtensionMethodProtected:
return StandardGlyphGroup.GlyphExtensionMethodProtected;
case Glyph.ExtensionMethodPrivate:
return StandardGlyphGroup.GlyphExtensionMethodPrivate;
case Glyph.ExtensionMethodInternal:
return StandardGlyphGroup.GlyphExtensionMethodInternal;
case Glyph.EventPublic:
case Glyph.EventProtected:
case Glyph.EventPrivate:
case Glyph.EventInternal:
return StandardGlyphGroup.GlyphGroupEvent;
case Glyph.FieldPublic:
case Glyph.FieldProtected:
case Glyph.FieldPrivate:
case Glyph.FieldInternal:
return StandardGlyphGroup.GlyphGroupField;
case Glyph.InterfacePublic:
case Glyph.InterfaceProtected:
case Glyph.InterfacePrivate:
case Glyph.InterfaceInternal:
return StandardGlyphGroup.GlyphGroupInterface;
case Glyph.Intrinsic:
return StandardGlyphGroup.GlyphGroupIntrinsic;
case Glyph.Keyword:
return StandardGlyphGroup.GlyphKeyword;
case Glyph.Label:
return StandardGlyphGroup.GlyphGroupIntrinsic;
case Glyph.Local:
return StandardGlyphGroup.GlyphGroupVariable;
case Glyph.Namespace:
return StandardGlyphGroup.GlyphGroupNamespace;
case Glyph.MethodPublic:
case Glyph.MethodProtected:
case Glyph.MethodPrivate:
case Glyph.MethodInternal:
return StandardGlyphGroup.GlyphGroupMethod;
case Glyph.ModulePublic:
case Glyph.ModuleProtected:
case Glyph.ModulePrivate:
case Glyph.ModuleInternal:
return StandardGlyphGroup.GlyphGroupModule;
case Glyph.OpenFolder:
return StandardGlyphGroup.GlyphOpenFolder;
case Glyph.Operator:
return StandardGlyphGroup.GlyphGroupOperator;
case Glyph.Parameter:
return StandardGlyphGroup.GlyphGroupVariable;
case Glyph.PropertyPublic:
case Glyph.PropertyProtected:
case Glyph.PropertyPrivate:
case Glyph.PropertyInternal:
return StandardGlyphGroup.GlyphGroupProperty;
case Glyph.RangeVariable:
return StandardGlyphGroup.GlyphGroupVariable;
case Glyph.Reference:
return StandardGlyphGroup.GlyphReference;
case Glyph.StructurePublic:
case Glyph.StructureProtected:
case Glyph.StructurePrivate:
case Glyph.StructureInternal:
return StandardGlyphGroup.GlyphGroupStruct;
case Glyph.TypeParameter:
return StandardGlyphGroup.GlyphGroupType;
case Glyph.Snippet:
return StandardGlyphGroup.GlyphCSharpExpansion;
case Glyph.CompletionWarning:
return StandardGlyphGroup.GlyphCompletionWarning;
default:
throw new ArgumentException("glyph");
}
}
public static StandardGlyphItem GetStandardGlyphItem(this Glyph icon)
{
switch (icon)
{
case Glyph.ClassProtected:
case Glyph.ConstantProtected:
case Glyph.DelegateProtected:
case Glyph.EnumProtected:
case Glyph.EventProtected:
case Glyph.FieldProtected:
case Glyph.InterfaceProtected:
case Glyph.MethodProtected:
case Glyph.ModuleProtected:
case Glyph.PropertyProtected:
case Glyph.StructureProtected:
return StandardGlyphItem.GlyphItemProtected;
case Glyph.ClassPrivate:
case Glyph.ConstantPrivate:
case Glyph.DelegatePrivate:
case Glyph.EnumPrivate:
case Glyph.EventPrivate:
case Glyph.FieldPrivate:
case Glyph.InterfacePrivate:
case Glyph.MethodPrivate:
case Glyph.ModulePrivate:
case Glyph.PropertyPrivate:
case Glyph.StructurePrivate:
return StandardGlyphItem.GlyphItemPrivate;
case Glyph.ClassInternal:
case Glyph.ConstantInternal:
case Glyph.DelegateInternal:
case Glyph.EnumInternal:
case Glyph.EventInternal:
case Glyph.FieldInternal:
case Glyph.InterfaceInternal:
case Glyph.MethodInternal:
case Glyph.ModuleInternal:
case Glyph.PropertyInternal:
case Glyph.StructureInternal:
return StandardGlyphItem.GlyphItemFriend;
default:
// We don't want any overlays
return StandardGlyphItem.GlyphItemPublic;
}
}
public static ImageSource GetImageSource(this Glyph? glyph, IGlyphService glyphService)
{
return glyph.HasValue ? glyph.Value.GetImageSource(glyphService) : null;
}
public static ImageSource GetImageSource(this Glyph glyph, IGlyphService glyphService)
{
return glyphService.GetGlyph(glyph.GetStandardGlyphGroup(), glyph.GetStandardGlyphItem());
}
public static ImageMoniker GetImageMoniker(this Glyph glyph)
{
switch (glyph)
{
case Glyph.Assembly:
return KnownMonikers.Assembly;
case Glyph.BasicFile:
return KnownMonikers.VBFileNode;
case Glyph.BasicProject:
return KnownMonikers.VBProjectNode;
case Glyph.ClassPublic:
return KnownMonikers.ClassPublic;
case Glyph.ClassProtected:
return KnownMonikers.ClassProtected;
case Glyph.ClassPrivate:
return KnownMonikers.ClassPrivate;
case Glyph.ClassInternal:
return KnownMonikers.ClassInternal;
case Glyph.CSharpFile:
return KnownMonikers.CSFileNode;
case Glyph.CSharpProject:
return KnownMonikers.CSProjectNode;
case Glyph.ConstantPublic:
return KnownMonikers.ConstantPublic;
case Glyph.ConstantProtected:
return KnownMonikers.ConstantProtected;
case Glyph.ConstantPrivate:
return KnownMonikers.ConstantPrivate;
case Glyph.ConstantInternal:
return KnownMonikers.ConstantInternal;
case Glyph.DelegatePublic:
return KnownMonikers.DelegatePublic;
case Glyph.DelegateProtected:
return KnownMonikers.DelegateProtected;
case Glyph.DelegatePrivate:
return KnownMonikers.DelegatePrivate;
case Glyph.DelegateInternal:
return KnownMonikers.DelegateInternal;
case Glyph.EnumPublic:
return KnownMonikers.EnumerationPublic;
case Glyph.EnumProtected:
return KnownMonikers.EnumerationProtected;
case Glyph.EnumPrivate:
return KnownMonikers.EnumerationPrivate;
case Glyph.EnumInternal:
return KnownMonikers.EnumerationInternal;
case Glyph.EnumMember:
return KnownMonikers.EnumerationItemPublic;
case Glyph.Error:
return KnownMonikers.StatusError;
case Glyph.EventPublic:
return KnownMonikers.EventPublic;
case Glyph.EventProtected:
return KnownMonikers.EventProtected;
case Glyph.EventPrivate:
return KnownMonikers.EventPrivate;
case Glyph.EventInternal:
return KnownMonikers.EventInternal;
// Extension methods have the same glyph regardless of accessibility.
case Glyph.ExtensionMethodPublic:
case Glyph.ExtensionMethodProtected:
case Glyph.ExtensionMethodPrivate:
case Glyph.ExtensionMethodInternal:
return KnownMonikers.ExtensionMethod;
case Glyph.FieldPublic:
return KnownMonikers.FieldPublic;
case Glyph.FieldProtected:
return KnownMonikers.FieldProtected;
case Glyph.FieldPrivate:
return KnownMonikers.FieldPrivate;
case Glyph.FieldInternal:
return KnownMonikers.FieldInternal;
case Glyph.InterfacePublic:
return KnownMonikers.InterfacePublic;
case Glyph.InterfaceProtected:
return KnownMonikers.InterfaceProtected;
case Glyph.InterfacePrivate:
return KnownMonikers.InterfacePrivate;
case Glyph.InterfaceInternal:
return KnownMonikers.InterfaceInternal;
// TODO: Figure out the right thing to return here.
case Glyph.Intrinsic:
return KnownMonikers.Type;
case Glyph.Keyword:
return KnownMonikers.IntellisenseKeyword;
case Glyph.Label:
return KnownMonikers.Label;
case Glyph.Local:
return KnownMonikers.FieldPublic;
case Glyph.Namespace:
return KnownMonikers.Namespace;
case Glyph.MethodPublic:
return KnownMonikers.MethodPublic;
case Glyph.MethodProtected:
return KnownMonikers.MethodProtected;
case Glyph.MethodPrivate:
return KnownMonikers.MethodPrivate;
case Glyph.MethodInternal:
return KnownMonikers.MethodInternal;
case Glyph.ModulePublic:
return KnownMonikers.ModulePublic;
case Glyph.ModuleProtected:
return KnownMonikers.ModuleProtected;
case Glyph.ModulePrivate:
return KnownMonikers.ModulePrivate;
case Glyph.ModuleInternal:
return KnownMonikers.ModuleInternal;
case Glyph.OpenFolder:
return KnownMonikers.OpenFolder;
case Glyph.Operator:
return KnownMonikers.Operator;
case Glyph.Parameter:
return KnownMonikers.FieldPublic;
case Glyph.PropertyPublic:
return KnownMonikers.PropertyPublic;
case Glyph.PropertyProtected:
return KnownMonikers.PropertyProtected;
case Glyph.PropertyPrivate:
return KnownMonikers.PropertyPrivate;
case Glyph.PropertyInternal:
return KnownMonikers.PropertyInternal;
case Glyph.RangeVariable:
return KnownMonikers.FieldPublic;
case Glyph.Reference:
return KnownMonikers.Reference;
case Glyph.StructurePublic:
return KnownMonikers.ValueTypePublic;
case Glyph.StructureProtected:
return KnownMonikers.ValueTypeProtected;
case Glyph.StructurePrivate:
return KnownMonikers.ValueTypePrivate;
case Glyph.StructureInternal:
return KnownMonikers.ValueTypeInternal;
case Glyph.TypeParameter:
return KnownMonikers.Type;
case Glyph.Snippet:
return KnownMonikers.Snippet;
case Glyph.CompletionWarning:
return KnownMonikers.IntellisenseWarning;
default:
throw new ArgumentException("glyph");
}
}
}
}
| |
/*
* 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.
*/
#pragma warning disable 618 // Ignore obsolete, we still need to test them.
namespace Apache.Ignite.Core.Tests
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using Apache.Ignite.Core.Binary;
using Apache.Ignite.Core.Cache.Affinity.Rendezvous;
using Apache.Ignite.Core.Cache.Configuration;
using Apache.Ignite.Core.Cache.Eviction;
using Apache.Ignite.Core.Client;
using Apache.Ignite.Core.Client.Cache;
using Apache.Ignite.Core.Common;
using Apache.Ignite.Core.Communication.Tcp;
using Apache.Ignite.Core.Configuration;
using Apache.Ignite.Core.DataStructures.Configuration;
using Apache.Ignite.Core.Discovery.Tcp;
using Apache.Ignite.Core.Discovery.Tcp.Multicast;
using Apache.Ignite.Core.Discovery.Tcp.Static;
using Apache.Ignite.Core.Encryption.Keystore;
using Apache.Ignite.Core.Events;
using Apache.Ignite.Core.Impl.Common;
using Apache.Ignite.Core.PersistentStore;
using Apache.Ignite.Core.Tests.Plugin;
using Apache.Ignite.Core.Transactions;
using NUnit.Framework;
using WalMode = Apache.Ignite.Core.PersistentStore.WalMode;
/// <summary>
/// Tests code-based configuration.
/// </summary>
public class IgniteConfigurationTest
{
/// <summary>
/// Fixture tear down.
/// </summary>
[TestFixtureSetUp]
public void FixtureTearDown()
{
Ignition.StopAll(true);
}
/// <summary>
/// Tests the default configuration properties.
/// </summary>
[Test]
public void TestDefaultConfigurationProperties()
{
CheckDefaultProperties(new IgniteConfiguration());
CheckDefaultProperties(new PersistentStoreConfiguration());
CheckDefaultProperties(new DataStorageConfiguration());
CheckDefaultProperties(new DataRegionConfiguration());
CheckDefaultProperties(new ClientConnectorConfiguration());
CheckDefaultProperties(new SqlConnectorConfiguration());
}
/// <summary>
/// Tests the default value attributes.
/// </summary>
[Test]
public void TestDefaultValueAttributes()
{
CheckDefaultValueAttributes(new IgniteConfiguration());
CheckDefaultValueAttributes(new BinaryConfiguration());
CheckDefaultValueAttributes(new TcpDiscoverySpi());
CheckDefaultValueAttributes(new KeystoreEncryptionSpi());
CheckDefaultValueAttributes(new CacheConfiguration());
CheckDefaultValueAttributes(new TcpDiscoveryMulticastIpFinder());
CheckDefaultValueAttributes(new TcpCommunicationSpi());
CheckDefaultValueAttributes(new RendezvousAffinityFunction());
CheckDefaultValueAttributes(new NearCacheConfiguration());
CheckDefaultValueAttributes(new FifoEvictionPolicy());
CheckDefaultValueAttributes(new LruEvictionPolicy());
CheckDefaultValueAttributes(new AtomicConfiguration());
CheckDefaultValueAttributes(new TransactionConfiguration());
CheckDefaultValueAttributes(new MemoryEventStorageSpi());
CheckDefaultValueAttributes(new MemoryConfiguration());
CheckDefaultValueAttributes(new MemoryPolicyConfiguration());
CheckDefaultValueAttributes(new SqlConnectorConfiguration());
CheckDefaultValueAttributes(new ClientConnectorConfiguration());
CheckDefaultValueAttributes(new PersistentStoreConfiguration());
CheckDefaultValueAttributes(new IgniteClientConfiguration());
CheckDefaultValueAttributes(new QueryIndex());
CheckDefaultValueAttributes(new DataStorageConfiguration());
CheckDefaultValueAttributes(new DataRegionConfiguration());
CheckDefaultValueAttributes(new CacheClientConfiguration());
}
/// <summary>
/// Tests all configuration properties.
/// </summary>
[Test]
public void TestAllConfigurationProperties()
{
var cfg = new IgniteConfiguration(GetCustomConfig());
using (var ignite = Ignition.Start(cfg))
{
var resCfg = ignite.GetConfiguration();
var disco = (TcpDiscoverySpi) cfg.DiscoverySpi;
var resDisco = (TcpDiscoverySpi) resCfg.DiscoverySpi;
Assert.AreEqual(disco.NetworkTimeout, resDisco.NetworkTimeout);
Assert.AreEqual(disco.AckTimeout, resDisco.AckTimeout);
Assert.AreEqual(disco.MaxAckTimeout, resDisco.MaxAckTimeout);
Assert.AreEqual(disco.SocketTimeout, resDisco.SocketTimeout);
Assert.AreEqual(disco.JoinTimeout, resDisco.JoinTimeout);
Assert.AreEqual(disco.LocalAddress, resDisco.LocalAddress);
Assert.AreEqual(disco.LocalPort, resDisco.LocalPort);
Assert.AreEqual(disco.LocalPortRange, resDisco.LocalPortRange);
Assert.AreEqual(disco.ReconnectCount, resDisco.ReconnectCount);
Assert.AreEqual(disco.StatisticsPrintFrequency, resDisco.StatisticsPrintFrequency);
Assert.AreEqual(disco.ThreadPriority, resDisco.ThreadPriority);
Assert.AreEqual(disco.TopologyHistorySize, resDisco.TopologyHistorySize);
var enc = (KeystoreEncryptionSpi) cfg.EncryptionSpi;
var resEnc = (KeystoreEncryptionSpi) resCfg.EncryptionSpi;
Assert.AreEqual(enc.MasterKeyName, resEnc.MasterKeyName);
Assert.AreEqual(enc.KeySize, resEnc.KeySize);
Assert.AreEqual(enc.KeyStorePath, resEnc.KeyStorePath);
Assert.AreEqual(enc.KeyStorePassword, resEnc.KeyStorePassword);
var ip = (TcpDiscoveryStaticIpFinder) disco.IpFinder;
var resIp = (TcpDiscoveryStaticIpFinder) resDisco.IpFinder;
// There can be extra IPv6 endpoints
Assert.AreEqual(ip.Endpoints, resIp.Endpoints.Take(2).Select(x => x.Trim('/')).ToArray());
Assert.AreEqual(cfg.IgniteInstanceName, resCfg.IgniteInstanceName);
Assert.AreEqual(cfg.IgniteHome, resCfg.IgniteHome);
Assert.AreEqual(cfg.IncludedEventTypes, resCfg.IncludedEventTypes);
Assert.AreEqual(cfg.MetricsExpireTime, resCfg.MetricsExpireTime);
Assert.AreEqual(cfg.MetricsHistorySize, resCfg.MetricsHistorySize);
Assert.AreEqual(cfg.MetricsLogFrequency, resCfg.MetricsLogFrequency);
Assert.AreEqual(cfg.MetricsUpdateFrequency, resCfg.MetricsUpdateFrequency);
Assert.AreEqual(cfg.NetworkSendRetryCount, resCfg.NetworkSendRetryCount);
Assert.AreEqual(cfg.NetworkTimeout, resCfg.NetworkTimeout);
Assert.AreEqual(cfg.NetworkSendRetryDelay, resCfg.NetworkSendRetryDelay);
Assert.AreEqual(cfg.WorkDirectory.Trim(Path.DirectorySeparatorChar),
resCfg.WorkDirectory.Trim(Path.DirectorySeparatorChar));
Assert.AreEqual(cfg.JvmClasspath, resCfg.JvmClasspath);
Assert.AreEqual(cfg.JvmOptions, resCfg.JvmOptions);
Assert.AreEqual(cfg.JvmDllPath, resCfg.JvmDllPath);
Assert.AreEqual(cfg.Localhost, resCfg.Localhost);
Assert.AreEqual(cfg.IsDaemon, resCfg.IsDaemon);
Assert.AreEqual(IgniteConfiguration.DefaultIsLateAffinityAssignment, resCfg.IsLateAffinityAssignment);
Assert.AreEqual(cfg.UserAttributes, resCfg.UserAttributes);
var atm = cfg.AtomicConfiguration;
var resAtm = resCfg.AtomicConfiguration;
Assert.AreEqual(atm.AtomicSequenceReserveSize, resAtm.AtomicSequenceReserveSize);
Assert.AreEqual(atm.Backups, resAtm.Backups);
Assert.AreEqual(atm.CacheMode, resAtm.CacheMode);
var tx = cfg.TransactionConfiguration;
var resTx = resCfg.TransactionConfiguration;
Assert.AreEqual(tx.DefaultTimeout, resTx.DefaultTimeout);
Assert.AreEqual(tx.DefaultTransactionConcurrency, resTx.DefaultTransactionConcurrency);
Assert.AreEqual(tx.DefaultTransactionIsolation, resTx.DefaultTransactionIsolation);
Assert.AreEqual(tx.PessimisticTransactionLogLinger, resTx.PessimisticTransactionLogLinger);
Assert.AreEqual(tx.PessimisticTransactionLogSize, resTx.PessimisticTransactionLogSize);
Assert.AreEqual(tx.DefaultTimeoutOnPartitionMapExchange, resTx.DefaultTimeoutOnPartitionMapExchange);
var com = (TcpCommunicationSpi) cfg.CommunicationSpi;
var resCom = (TcpCommunicationSpi) resCfg.CommunicationSpi;
Assert.AreEqual(com.AckSendThreshold, resCom.AckSendThreshold);
Assert.AreEqual(com.ConnectionsPerNode, resCom.ConnectionsPerNode);
Assert.AreEqual(com.ConnectTimeout, resCom.ConnectTimeout);
Assert.AreEqual(com.DirectBuffer, resCom.DirectBuffer);
Assert.AreEqual(com.DirectSendBuffer, resCom.DirectSendBuffer);
Assert.AreEqual(com.FilterReachableAddresses, resCom.FilterReachableAddresses);
Assert.AreEqual(com.IdleConnectionTimeout, resCom.IdleConnectionTimeout);
Assert.AreEqual(com.LocalAddress, resCom.LocalAddress);
Assert.AreEqual(com.LocalPort, resCom.LocalPort);
Assert.AreEqual(com.LocalPortRange, resCom.LocalPortRange);
Assert.AreEqual(com.MaxConnectTimeout, resCom.MaxConnectTimeout);
Assert.AreEqual(com.MessageQueueLimit, resCom.MessageQueueLimit);
Assert.AreEqual(com.ReconnectCount, resCom.ReconnectCount);
Assert.AreEqual(com.SelectorsCount, resCom.SelectorsCount);
Assert.AreEqual(com.SelectorSpins, resCom.SelectorSpins);
Assert.AreEqual(com.SharedMemoryPort, resCom.SharedMemoryPort);
Assert.AreEqual(com.SlowClientQueueLimit, resCom.SlowClientQueueLimit);
Assert.AreEqual(com.SocketReceiveBufferSize, resCom.SocketReceiveBufferSize);
Assert.AreEqual(com.SocketSendBufferSize, resCom.SocketSendBufferSize);
Assert.AreEqual(com.SocketWriteTimeout, resCom.SocketWriteTimeout);
Assert.AreEqual(com.TcpNoDelay, resCom.TcpNoDelay);
Assert.AreEqual(com.UnacknowledgedMessagesBufferSize, resCom.UnacknowledgedMessagesBufferSize);
Assert.AreEqual(com.UsePairedConnections, resCom.UsePairedConnections);
Assert.AreEqual(cfg.FailureDetectionTimeout, resCfg.FailureDetectionTimeout);
Assert.AreEqual(cfg.SystemWorkerBlockedTimeout, resCfg.SystemWorkerBlockedTimeout);
Assert.AreEqual(cfg.ClientFailureDetectionTimeout, resCfg.ClientFailureDetectionTimeout);
Assert.AreEqual(cfg.LongQueryWarningTimeout, resCfg.LongQueryWarningTimeout);
Assert.AreEqual(cfg.PublicThreadPoolSize, resCfg.PublicThreadPoolSize);
Assert.AreEqual(cfg.StripedThreadPoolSize, resCfg.StripedThreadPoolSize);
Assert.AreEqual(cfg.ServiceThreadPoolSize, resCfg.ServiceThreadPoolSize);
Assert.AreEqual(cfg.SystemThreadPoolSize, resCfg.SystemThreadPoolSize);
Assert.AreEqual(cfg.AsyncCallbackThreadPoolSize, resCfg.AsyncCallbackThreadPoolSize);
Assert.AreEqual(cfg.ManagementThreadPoolSize, resCfg.ManagementThreadPoolSize);
Assert.AreEqual(cfg.DataStreamerThreadPoolSize, resCfg.DataStreamerThreadPoolSize);
Assert.AreEqual(cfg.UtilityCacheThreadPoolSize, resCfg.UtilityCacheThreadPoolSize);
Assert.AreEqual(cfg.QueryThreadPoolSize, resCfg.QueryThreadPoolSize);
Assert.AreEqual(cfg.ConsistentId, resCfg.ConsistentId);
var binCfg = cfg.BinaryConfiguration;
Assert.IsFalse(binCfg.CompactFooter);
var typ = binCfg.TypeConfigurations.Single();
Assert.AreEqual("myType", typ.TypeName);
Assert.IsTrue(typ.IsEnum);
Assert.AreEqual("affKey", typ.AffinityKeyFieldName);
Assert.AreEqual(false, typ.KeepDeserialized);
Assert.IsNotNull(resCfg.PluginConfigurations);
Assert.AreEqual(cfg.PluginConfigurations, resCfg.PluginConfigurations);
var eventCfg = cfg.EventStorageSpi as MemoryEventStorageSpi;
var resEventCfg = resCfg.EventStorageSpi as MemoryEventStorageSpi;
Assert.IsNotNull(eventCfg);
Assert.IsNotNull(resEventCfg);
Assert.AreEqual(eventCfg.ExpirationTimeout, resEventCfg.ExpirationTimeout);
Assert.AreEqual(eventCfg.MaxEventCount, resEventCfg.MaxEventCount);
var sql = cfg.SqlConnectorConfiguration;
var resSql = resCfg.SqlConnectorConfiguration;
Assert.AreEqual(sql.Host, resSql.Host);
Assert.AreEqual(sql.Port, resSql.Port);
Assert.AreEqual(sql.PortRange, resSql.PortRange);
Assert.AreEqual(sql.MaxOpenCursorsPerConnection, resSql.MaxOpenCursorsPerConnection);
Assert.AreEqual(sql.SocketReceiveBufferSize, resSql.SocketReceiveBufferSize);
Assert.AreEqual(sql.SocketSendBufferSize, resSql.SocketSendBufferSize);
Assert.AreEqual(sql.TcpNoDelay, resSql.TcpNoDelay);
Assert.AreEqual(sql.ThreadPoolSize, resSql.ThreadPoolSize);
AssertExtensions.ReflectionEqual(cfg.DataStorageConfiguration, resCfg.DataStorageConfiguration);
Assert.AreEqual(cfg.MvccVacuumFrequency, resCfg.MvccVacuumFrequency);
Assert.AreEqual(cfg.MvccVacuumThreadCount, resCfg.MvccVacuumThreadCount);
Assert.AreEqual(cfg.SqlQueryHistorySize, resCfg.SqlQueryHistorySize);
Assert.IsNotNull(resCfg.SqlSchemas);
Assert.AreEqual(2, resCfg.SqlSchemas.Count);
Assert.IsTrue(resCfg.SqlSchemas.Contains("SCHEMA_3"));
Assert.IsTrue(resCfg.SqlSchemas.Contains("schema_4"));
}
}
/// <summary>
/// Tests the spring XML.
/// </summary>
[Test]
public void TestSpringXml()
{
// When Spring XML is used, .NET overrides Spring.
var cfg = new IgniteConfiguration(TestUtils.GetTestConfiguration())
{
DataStorageConfiguration = null,
SpringConfigUrl = Path.Combine("Config", "spring-test.xml"),
NetworkSendRetryDelay = TimeSpan.FromSeconds(45),
MetricsHistorySize = 57
};
using (var ignite = Ignition.Start(cfg))
{
var resCfg = ignite.GetConfiguration();
Assert.AreEqual(45, resCfg.NetworkSendRetryDelay.TotalSeconds); // .NET overrides XML
Assert.AreEqual(2999, resCfg.NetworkTimeout.TotalMilliseconds); // Not set in .NET -> comes from XML
Assert.AreEqual(57, resCfg.MetricsHistorySize); // Only set in .NET
var disco = resCfg.DiscoverySpi as TcpDiscoverySpi;
Assert.IsNotNull(disco);
Assert.AreEqual(TimeSpan.FromMilliseconds(300), disco.SocketTimeout);
// DataStorage defaults.
CheckDefaultProperties(resCfg.DataStorageConfiguration);
CheckDefaultProperties(resCfg.DataStorageConfiguration.DefaultDataRegionConfiguration);
// Connector defaults.
CheckDefaultProperties(resCfg.ClientConnectorConfiguration);
}
}
/// <summary>
/// Tests the client mode.
/// </summary>
[Test]
public void TestClientMode()
{
using (var ignite = Ignition.Start(new IgniteConfiguration
{
Localhost = "127.0.0.1",
DiscoverySpi = TestUtils.GetStaticDiscovery()
}))
using (var ignite2 = Ignition.Start(new IgniteConfiguration
{
Localhost = "127.0.0.1",
DiscoverySpi = TestUtils.GetStaticDiscovery(),
IgniteInstanceName = "client",
ClientMode = true
}))
{
const string cacheName = "cache";
ignite.CreateCache<int, int>(cacheName);
Assert.AreEqual(2, ignite2.GetCluster().GetNodes().Count);
Assert.AreEqual(1, ignite.GetCluster().ForCacheNodes(cacheName).GetNodes().Count);
Assert.AreEqual(false, ignite.GetConfiguration().ClientMode);
Assert.AreEqual(true, ignite2.GetConfiguration().ClientMode);
}
}
/// <summary>
/// Tests the default spi.
/// </summary>
[Test]
public void TestDefaultSpi()
{
var cfg = new IgniteConfiguration(TestUtils.GetTestConfiguration())
{
DiscoverySpi =
new TcpDiscoverySpi
{
AckTimeout = TimeSpan.FromDays(2),
MaxAckTimeout = TimeSpan.MaxValue,
JoinTimeout = TimeSpan.MaxValue,
NetworkTimeout = TimeSpan.MaxValue,
SocketTimeout = TimeSpan.MaxValue
}
};
using (var ignite = Ignition.Start(cfg))
{
cfg.IgniteInstanceName = "ignite2";
using (var ignite2 = Ignition.Start(cfg))
{
Assert.AreEqual(2, ignite.GetCluster().GetNodes().Count);
Assert.AreEqual(2, ignite2.GetCluster().GetNodes().Count);
}
}
}
/// <summary>
/// Tests the invalid timeouts.
/// </summary>
[Test]
public void TestInvalidTimeouts()
{
var cfg = new IgniteConfiguration(TestUtils.GetTestConfiguration())
{
DiscoverySpi =
new TcpDiscoverySpi
{
AckTimeout = TimeSpan.FromMilliseconds(-5),
JoinTimeout = TimeSpan.MinValue
}
};
Assert.Throws<IgniteException>(() => Ignition.Start(cfg));
}
/// <summary>
/// Tests the static ip finder.
/// </summary>
[Test]
public void TestStaticIpFinder()
{
TestIpFinders(new TcpDiscoveryStaticIpFinder
{
Endpoints = new[] {"127.0.0.1:47500"}
}, new TcpDiscoveryStaticIpFinder
{
Endpoints = new[] {"127.0.0.1:47501"}
});
}
/// <summary>
/// Tests the multicast ip finder.
/// </summary>
[Test]
public void TestMulticastIpFinder()
{
TestIpFinders(
new TcpDiscoveryMulticastIpFinder {MulticastGroup = "228.111.111.222", MulticastPort = 54522},
new TcpDiscoveryMulticastIpFinder {MulticastGroup = "228.111.111.223", MulticastPort = 54522});
}
/// <summary>
/// Tests the work directory.
/// </summary>
[Test]
public void TestWorkDirectory()
{
var cfg = new IgniteConfiguration(TestUtils.GetTestConfiguration())
{
WorkDirectory = TestUtils.GetTempDirectoryName()
};
using (Ignition.Start(cfg))
{
var marshDir = Path.Combine(cfg.WorkDirectory, "marshaller");
Assert.IsTrue(Directory.Exists(marshDir));
}
Directory.Delete(cfg.WorkDirectory, true);
}
/// <summary>
/// Tests the consistent id.
/// </summary>
[Test]
[NUnit.Framework.Category(TestUtils.CategoryIntensive)]
public void TestConsistentId()
{
var ids = new object[]
{
null, new MyConsistentId {Data = "foo"}, "str", 1, 1.1, DateTime.Now, Guid.NewGuid()
};
var cfg = TestUtils.GetTestConfiguration();
foreach (var id in ids)
{
cfg.ConsistentId = id;
using (var ignite = Ignition.Start(cfg))
{
Assert.AreEqual(id, ignite.GetConfiguration().ConsistentId);
Assert.AreEqual(id ?? "127.0.0.1:47500", ignite.GetCluster().GetLocalNode().ConsistentId);
}
}
}
/// <summary>
/// Tests the ip finders.
/// </summary>
/// <param name="ipFinder">The ip finder.</param>
/// <param name="ipFinder2">The ip finder2.</param>
private static void TestIpFinders(TcpDiscoveryIpFinderBase ipFinder, TcpDiscoveryIpFinderBase ipFinder2)
{
var cfg = new IgniteConfiguration(TestUtils.GetTestConfiguration())
{
DiscoverySpi =
new TcpDiscoverySpi
{
IpFinder = ipFinder
}
};
using (var ignite = Ignition.Start(cfg))
{
// Start with the same endpoint
cfg.IgniteInstanceName = "ignite2";
using (var ignite2 = Ignition.Start(cfg))
{
Assert.AreEqual(2, ignite.GetCluster().GetNodes().Count);
Assert.AreEqual(2, ignite2.GetCluster().GetNodes().Count);
}
// Start with incompatible endpoint and check that there are 2 topologies
((TcpDiscoverySpi) cfg.DiscoverySpi).IpFinder = ipFinder2;
using (var ignite2 = Ignition.Start(cfg))
{
Assert.AreEqual(1, ignite.GetCluster().GetNodes().Count);
Assert.AreEqual(1, ignite2.GetCluster().GetNodes().Count);
}
}
}
/// <summary>
/// Checks the default properties.
/// </summary>
/// <param name="cfg">The CFG.</param>
private static void CheckDefaultProperties(IgniteConfiguration cfg)
{
Assert.AreEqual(IgniteConfiguration.DefaultMetricsExpireTime, cfg.MetricsExpireTime);
Assert.AreEqual(IgniteConfiguration.DefaultMetricsHistorySize, cfg.MetricsHistorySize);
Assert.AreEqual(IgniteConfiguration.DefaultMetricsLogFrequency, cfg.MetricsLogFrequency);
Assert.AreEqual(IgniteConfiguration.DefaultMetricsUpdateFrequency, cfg.MetricsUpdateFrequency);
Assert.AreEqual(IgniteConfiguration.DefaultNetworkTimeout, cfg.NetworkTimeout);
Assert.AreEqual(IgniteConfiguration.DefaultNetworkSendRetryCount, cfg.NetworkSendRetryCount);
Assert.AreEqual(IgniteConfiguration.DefaultNetworkSendRetryDelay, cfg.NetworkSendRetryDelay);
Assert.AreEqual(IgniteConfiguration.DefaultFailureDetectionTimeout, cfg.FailureDetectionTimeout);
Assert.AreEqual(IgniteConfiguration.DefaultClientFailureDetectionTimeout,
cfg.ClientFailureDetectionTimeout);
Assert.AreEqual(IgniteConfiguration.DefaultLongQueryWarningTimeout, cfg.LongQueryWarningTimeout);
Assert.AreEqual(IgniteConfiguration.DefaultIsLateAffinityAssignment, cfg.IsLateAffinityAssignment);
Assert.AreEqual(IgniteConfiguration.DefaultIsActiveOnStart, cfg.IsActiveOnStart);
Assert.AreEqual(IgniteConfiguration.DefaultClientConnectorConfigurationEnabled,
cfg.ClientConnectorConfigurationEnabled);
Assert.AreEqual(IgniteConfiguration.DefaultRedirectJavaConsoleOutput, cfg.RedirectJavaConsoleOutput);
Assert.AreEqual(IgniteConfiguration.DefaultAuthenticationEnabled, cfg.AuthenticationEnabled);
Assert.AreEqual(IgniteConfiguration.DefaultMvccVacuumFrequency, cfg.MvccVacuumFrequency);
Assert.AreEqual(IgniteConfiguration.DefaultMvccVacuumThreadCount, cfg.MvccVacuumThreadCount);
// Thread pools.
Assert.AreEqual(IgniteConfiguration.DefaultManagementThreadPoolSize, cfg.ManagementThreadPoolSize);
Assert.AreEqual(IgniteConfiguration.DefaultThreadPoolSize, cfg.PublicThreadPoolSize);
Assert.AreEqual(IgniteConfiguration.DefaultThreadPoolSize, cfg.StripedThreadPoolSize);
Assert.AreEqual(IgniteConfiguration.DefaultThreadPoolSize, cfg.ServiceThreadPoolSize);
Assert.AreEqual(IgniteConfiguration.DefaultThreadPoolSize, cfg.SystemThreadPoolSize);
Assert.AreEqual(IgniteConfiguration.DefaultThreadPoolSize, cfg.AsyncCallbackThreadPoolSize);
Assert.AreEqual(IgniteConfiguration.DefaultThreadPoolSize, cfg.DataStreamerThreadPoolSize);
Assert.AreEqual(IgniteConfiguration.DefaultThreadPoolSize, cfg.UtilityCacheThreadPoolSize);
Assert.AreEqual(IgniteConfiguration.DefaultThreadPoolSize, cfg.QueryThreadPoolSize);
}
/// <summary>
/// Checks the default properties.
/// </summary>
/// <param name="cfg">Config.</param>
private static void CheckDefaultProperties(PersistentStoreConfiguration cfg)
{
Assert.AreEqual(PersistentStoreConfiguration.DefaultTlbSize, cfg.TlbSize);
Assert.AreEqual(PersistentStoreConfiguration.DefaultCheckpointingFrequency, cfg.CheckpointingFrequency);
Assert.AreEqual(PersistentStoreConfiguration.DefaultCheckpointingThreads, cfg.CheckpointingThreads);
Assert.AreEqual(default(long), cfg.CheckpointingPageBufferSize);
Assert.AreEqual(PersistentStoreConfiguration.DefaultLockWaitTime, cfg.LockWaitTime);
Assert.AreEqual(PersistentStoreConfiguration.DefaultWalFlushFrequency, cfg.WalFlushFrequency);
Assert.AreEqual(PersistentStoreConfiguration.DefaultWalFsyncDelayNanos, cfg.WalFsyncDelayNanos);
Assert.AreEqual(PersistentStoreConfiguration.DefaultWalHistorySize, cfg.WalHistorySize);
Assert.AreEqual(PersistentStoreConfiguration.DefaultWalRecordIteratorBufferSize,
cfg.WalRecordIteratorBufferSize);
Assert.AreEqual(PersistentStoreConfiguration.DefaultWalSegmentSize, cfg.WalSegmentSize);
Assert.AreEqual(PersistentStoreConfiguration.DefaultWalSegments, cfg.WalSegments);
Assert.AreEqual(WalMode.Default, cfg.WalMode);
Assert.IsFalse(cfg.MetricsEnabled);
Assert.AreEqual(PersistentStoreConfiguration.DefaultSubIntervals, cfg.SubIntervals);
Assert.AreEqual(PersistentStoreConfiguration.DefaultRateTimeInterval, cfg.RateTimeInterval);
Assert.AreEqual(PersistentStoreConfiguration.DefaultWalStorePath, cfg.WalStorePath);
Assert.AreEqual(PersistentStoreConfiguration.DefaultWalArchivePath, cfg.WalArchivePath);
Assert.AreEqual(PersistentStoreConfiguration.DefaultCheckpointWriteOrder, cfg.CheckpointWriteOrder);
Assert.AreEqual(PersistentStoreConfiguration.DefaultWriteThrottlingEnabled, cfg.WriteThrottlingEnabled);
}
/// <summary>
/// Checks the default properties.
/// </summary>
/// <param name="cfg">Config.</param>
private static void CheckDefaultProperties(DataStorageConfiguration cfg)
{
Assert.AreEqual(DataStorageConfiguration.DefaultTlbSize, cfg.WalThreadLocalBufferSize);
Assert.AreEqual(DataStorageConfiguration.DefaultCheckpointFrequency, cfg.CheckpointFrequency);
Assert.AreEqual(DataStorageConfiguration.DefaultCheckpointThreads, cfg.CheckpointThreads);
Assert.AreEqual(DataStorageConfiguration.DefaultLockWaitTime, cfg.LockWaitTime);
Assert.AreEqual(DataStorageConfiguration.DefaultWalFlushFrequency, cfg.WalFlushFrequency);
Assert.AreEqual(DataStorageConfiguration.DefaultWalFsyncDelayNanos, cfg.WalFsyncDelayNanos);
Assert.AreEqual(DataStorageConfiguration.DefaultWalHistorySize, cfg.WalHistorySize);
Assert.AreEqual(DataStorageConfiguration.DefaultWalRecordIteratorBufferSize,
cfg.WalRecordIteratorBufferSize);
Assert.AreEqual(DataStorageConfiguration.DefaultWalSegmentSize, cfg.WalSegmentSize);
Assert.AreEqual(DataStorageConfiguration.DefaultWalSegments, cfg.WalSegments);
Assert.AreEqual(DataStorageConfiguration.DefaultWalMode, cfg.WalMode);
Assert.IsFalse(cfg.MetricsEnabled);
Assert.AreEqual(DataStorageConfiguration.DefaultMetricsSubIntervalCount, cfg.MetricsSubIntervalCount);
Assert.AreEqual(DataStorageConfiguration.DefaultMetricsRateTimeInterval, cfg.MetricsRateTimeInterval);
Assert.AreEqual(DataStorageConfiguration.DefaultWalPath, cfg.WalPath);
Assert.AreEqual(DataStorageConfiguration.DefaultWalArchivePath, cfg.WalArchivePath);
Assert.AreEqual(DataStorageConfiguration.DefaultCheckpointWriteOrder, cfg.CheckpointWriteOrder);
Assert.AreEqual(DataStorageConfiguration.DefaultWriteThrottlingEnabled, cfg.WriteThrottlingEnabled);
Assert.AreEqual(DataStorageConfiguration.DefaultSystemRegionInitialSize, cfg.SystemRegionInitialSize);
Assert.AreEqual(DataStorageConfiguration.DefaultSystemRegionMaxSize, cfg.SystemRegionMaxSize);
Assert.AreEqual(DataStorageConfiguration.DefaultPageSize, cfg.PageSize);
Assert.AreEqual(DataStorageConfiguration.DefaultConcurrencyLevel, cfg.ConcurrencyLevel);
Assert.AreEqual(DataStorageConfiguration.DefaultWalAutoArchiveAfterInactivity,
cfg.WalAutoArchiveAfterInactivity);
}
/// <summary>
/// Checks the default properties.
/// </summary>
/// <param name="cfg">Config.</param>
private static void CheckDefaultProperties(DataRegionConfiguration cfg)
{
Assert.AreEqual(DataRegionConfiguration.DefaultEmptyPagesPoolSize, cfg.EmptyPagesPoolSize);
Assert.AreEqual(DataRegionConfiguration.DefaultEvictionThreshold, cfg.EvictionThreshold);
Assert.AreEqual(DataRegionConfiguration.DefaultInitialSize, cfg.InitialSize);
Assert.AreEqual(DataRegionConfiguration.DefaultMaxSize, cfg.MaxSize);
Assert.AreEqual(DataRegionConfiguration.DefaultPersistenceEnabled, cfg.PersistenceEnabled);
Assert.AreEqual(DataRegionConfiguration.DefaultMetricsRateTimeInterval, cfg.MetricsRateTimeInterval);
Assert.AreEqual(DataRegionConfiguration.DefaultMetricsSubIntervalCount, cfg.MetricsSubIntervalCount);
Assert.AreEqual(default(long), cfg.CheckpointPageBufferSize);
}
/// <summary>
/// Checks the default properties.
/// </summary>
/// <param name="cfg">Config.</param>
private static void CheckDefaultProperties(ClientConnectorConfiguration cfg)
{
Assert.AreEqual(ClientConnectorConfiguration.DefaultPort, cfg.Port);
Assert.AreEqual(ClientConnectorConfiguration.DefaultPortRange, cfg.PortRange);
Assert.AreEqual(ClientConnectorConfiguration.DefaultMaxOpenCursorsPerConnection,
cfg.MaxOpenCursorsPerConnection);
Assert.AreEqual(ClientConnectorConfiguration.DefaultSocketBufferSize, cfg.SocketReceiveBufferSize);
Assert.AreEqual(ClientConnectorConfiguration.DefaultSocketBufferSize, cfg.SocketSendBufferSize);
Assert.AreEqual(ClientConnectorConfiguration.DefaultTcpNoDelay, cfg.TcpNoDelay);
Assert.AreEqual(ClientConnectorConfiguration.DefaultThreadPoolSize, cfg.ThreadPoolSize);
Assert.AreEqual(ClientConnectorConfiguration.DefaultIdleTimeout, cfg.IdleTimeout);
Assert.AreEqual(ClientConnectorConfiguration.DefaultThinClientEnabled, cfg.ThinClientEnabled);
Assert.AreEqual(ClientConnectorConfiguration.DefaultJdbcEnabled, cfg.JdbcEnabled);
Assert.AreEqual(ClientConnectorConfiguration.DefaultOdbcEnabled, cfg.OdbcEnabled);
}
/// <summary>
/// Checks the default properties.
/// </summary>
/// <param name="cfg">Config.</param>
private static void CheckDefaultProperties(SqlConnectorConfiguration cfg)
{
Assert.AreEqual(ClientConnectorConfiguration.DefaultPort, cfg.Port);
Assert.AreEqual(ClientConnectorConfiguration.DefaultPortRange, cfg.PortRange);
Assert.AreEqual(ClientConnectorConfiguration.DefaultMaxOpenCursorsPerConnection,
cfg.MaxOpenCursorsPerConnection);
Assert.AreEqual(ClientConnectorConfiguration.DefaultSocketBufferSize, cfg.SocketReceiveBufferSize);
Assert.AreEqual(ClientConnectorConfiguration.DefaultSocketBufferSize, cfg.SocketSendBufferSize);
Assert.AreEqual(ClientConnectorConfiguration.DefaultTcpNoDelay, cfg.TcpNoDelay);
Assert.AreEqual(ClientConnectorConfiguration.DefaultThreadPoolSize, cfg.ThreadPoolSize);
}
/// <summary>
/// Checks the default value attributes.
/// </summary>
/// <param name="obj">The object.</param>
private static void CheckDefaultValueAttributes(object obj)
{
var props = obj.GetType().GetProperties();
foreach (var prop in props.Where(p => p.Name != "SelectorsCount" && p.Name != "ReadStripesNumber" &&
!p.Name.Contains("ThreadPoolSize") &&
p.Name != "MaxSize"))
{
var attr = prop.GetCustomAttributes(true).OfType<DefaultValueAttribute>().FirstOrDefault();
var propValue = prop.GetValue(obj, null);
if (attr != null)
Assert.AreEqual(attr.Value, propValue, string.Format("{0}.{1}", obj.GetType(), prop.Name));
else if (prop.PropertyType.IsValueType)
Assert.AreEqual(Activator.CreateInstance(prop.PropertyType), propValue, prop.Name);
else
Assert.IsNull(propValue);
}
}
/// <summary>
/// Gets the custom configuration.
/// </summary>
private static IgniteConfiguration GetCustomConfig()
{
// CacheConfiguration is not tested here - see CacheConfigurationTest
return new IgniteConfiguration(TestUtils.GetTestConfiguration())
{
DiscoverySpi = new TcpDiscoverySpi
{
NetworkTimeout = TimeSpan.FromSeconds(1),
AckTimeout = TimeSpan.FromSeconds(2),
MaxAckTimeout = TimeSpan.FromSeconds(3),
SocketTimeout = TimeSpan.FromSeconds(4),
JoinTimeout = TimeSpan.FromSeconds(5),
IpFinder = new TcpDiscoveryStaticIpFinder
{
Endpoints = new[] {"127.0.0.1:49900", "127.0.0.1:49901"}
},
ClientReconnectDisabled = true,
ForceServerMode = true,
IpFinderCleanFrequency = TimeSpan.FromMinutes(7),
LocalAddress = "127.0.0.1",
LocalPort = 49900,
LocalPortRange = 13,
ReconnectCount = 11,
StatisticsPrintFrequency = TimeSpan.FromSeconds(20),
ThreadPriority = 6,
TopologyHistorySize = 1234567
},
EncryptionSpi = new KeystoreEncryptionSpi()
{
KeySize = 192,
KeyStorePassword = "love_sex_god",
KeyStorePath = "tde.jks",
MasterKeyName = KeystoreEncryptionSpi.DefaultMasterKeyName
},
IgniteInstanceName = "gridName1",
IgniteHome = IgniteHome.Resolve(null),
IncludedEventTypes = EventType.DiscoveryAll,
MetricsExpireTime = TimeSpan.FromMinutes(7),
MetricsHistorySize = 125,
MetricsLogFrequency = TimeSpan.FromMinutes(8),
MetricsUpdateFrequency = TimeSpan.FromMinutes(9),
NetworkSendRetryCount = 54,
NetworkTimeout = TimeSpan.FromMinutes(10),
NetworkSendRetryDelay = TimeSpan.FromMinutes(11),
WorkDirectory = Path.GetTempPath(),
Localhost = "127.0.0.1",
IsDaemon = false,
IsLateAffinityAssignment = false,
UserAttributes = Enumerable.Range(1, 10).ToDictionary(x => x.ToString(), x => (object) x),
AtomicConfiguration = new AtomicConfiguration
{
CacheMode = CacheMode.Replicated,
Backups = 2,
AtomicSequenceReserveSize = 200
},
TransactionConfiguration = new TransactionConfiguration
{
DefaultTransactionConcurrency = TransactionConcurrency.Optimistic,
DefaultTimeout = TimeSpan.FromSeconds(25),
DefaultTransactionIsolation = TransactionIsolation.Serializable,
PessimisticTransactionLogLinger = TimeSpan.FromHours(1),
PessimisticTransactionLogSize = 240,
DefaultTimeoutOnPartitionMapExchange = TimeSpan.FromSeconds(25)
},
CommunicationSpi = new TcpCommunicationSpi
{
LocalPort = 47501,
MaxConnectTimeout = TimeSpan.FromSeconds(34),
MessageQueueLimit = 15,
ConnectTimeout = TimeSpan.FromSeconds(17),
IdleConnectionTimeout = TimeSpan.FromSeconds(19),
SelectorsCount = 8,
ReconnectCount = 33,
SocketReceiveBufferSize = 512,
AckSendThreshold = 99,
DirectBuffer = false,
DirectSendBuffer = true,
LocalPortRange = 45,
LocalAddress = "127.0.0.1",
TcpNoDelay = false,
SlowClientQueueLimit = 98,
SocketSendBufferSize = 2045,
UnacknowledgedMessagesBufferSize = 3450,
ConnectionsPerNode = 12,
UsePairedConnections = true,
SharedMemoryPort = 1234,
SocketWriteTimeout = 2222,
SelectorSpins = 12,
FilterReachableAddresses = true
},
FailureDetectionTimeout = TimeSpan.FromSeconds(3.5),
SystemWorkerBlockedTimeout = TimeSpan.FromSeconds(8.5),
ClientFailureDetectionTimeout = TimeSpan.FromMinutes(12.3),
LongQueryWarningTimeout = TimeSpan.FromMinutes(1.23),
IsActiveOnStart = true,
BinaryConfiguration = new BinaryConfiguration
{
CompactFooter = false,
TypeConfigurations = new[]
{
new BinaryTypeConfiguration
{
TypeName = "myType",
IsEnum = true,
AffinityKeyFieldName = "affKey",
KeepDeserialized = false
}
}
},
// Skip cache check because with persistence the grid is not active by default.
PluginConfigurations = new[] {new TestIgnitePluginConfiguration {SkipCacheCheck = true}},
EventStorageSpi = new MemoryEventStorageSpi
{
ExpirationTimeout = TimeSpan.FromSeconds(5),
MaxEventCount = 10
},
PublicThreadPoolSize = 3,
StripedThreadPoolSize = 5,
ServiceThreadPoolSize = 6,
SystemThreadPoolSize = 7,
AsyncCallbackThreadPoolSize = 8,
ManagementThreadPoolSize = 9,
DataStreamerThreadPoolSize = 10,
UtilityCacheThreadPoolSize = 11,
QueryThreadPoolSize = 12,
SqlConnectorConfiguration = new SqlConnectorConfiguration
{
Host = "127.0.0.2",
Port = 1081,
PortRange = 3,
SocketReceiveBufferSize = 2048,
MaxOpenCursorsPerConnection = 5,
ThreadPoolSize = 4,
TcpNoDelay = false,
SocketSendBufferSize = 4096
},
ConsistentId = new MyConsistentId {Data = "abc"},
DataStorageConfiguration = new DataStorageConfiguration
{
AlwaysWriteFullPages = true,
CheckpointFrequency = TimeSpan.FromSeconds(25),
CheckpointThreads = 2,
LockWaitTime = TimeSpan.FromSeconds(5),
StoragePath = Path.GetTempPath(),
WalThreadLocalBufferSize = 64 * 1024,
WalArchivePath = Path.GetTempPath(),
WalFlushFrequency = TimeSpan.FromSeconds(3),
WalFsyncDelayNanos = 3,
WalHistorySize = 10,
WalMode = Configuration.WalMode.LogOnly,
WalRecordIteratorBufferSize = 32 * 1024 * 1024,
WalSegments = 6,
WalSegmentSize = 5 * 1024 * 1024,
WalPath = Path.GetTempPath(),
MetricsEnabled = true,
MetricsSubIntervalCount = 7,
MetricsRateTimeInterval = TimeSpan.FromSeconds(9),
CheckpointWriteOrder = Configuration.CheckpointWriteOrder.Random,
WriteThrottlingEnabled = true,
SystemRegionInitialSize = 64 * 1024 * 1024,
SystemRegionMaxSize = 128 * 1024 * 1024,
ConcurrencyLevel = 1,
PageSize = 8 * 1024,
WalAutoArchiveAfterInactivity = TimeSpan.FromMinutes(5),
CheckpointReadLockTimeout = TimeSpan.FromSeconds(9.5),
DefaultDataRegionConfiguration = new DataRegionConfiguration
{
Name = "reg1",
EmptyPagesPoolSize = 50,
EvictionThreshold = 0.8,
InitialSize = 100 * 1024 * 1024,
MaxSize = 150 * 1024 * 1024,
MetricsEnabled = true,
PageEvictionMode = Configuration.DataPageEvictionMode.Random2Lru,
PersistenceEnabled = false,
MetricsRateTimeInterval = TimeSpan.FromMinutes(2),
MetricsSubIntervalCount = 6,
SwapPath = TestUtils.GetTempDirectoryName(),
CheckpointPageBufferSize = 28 * 1024 * 1024
},
DataRegionConfigurations = new[]
{
new DataRegionConfiguration
{
Name = "reg2",
EmptyPagesPoolSize = 51,
EvictionThreshold = 0.7,
InitialSize = 101 * 1024 * 1024,
MaxSize = 151 * 1024 * 1024,
MetricsEnabled = false,
PageEvictionMode = Configuration.DataPageEvictionMode.RandomLru,
PersistenceEnabled = false,
MetricsRateTimeInterval = TimeSpan.FromMinutes(3),
MetricsSubIntervalCount = 7,
SwapPath = TestUtils.GetTempDirectoryName()
}
}
},
AuthenticationEnabled = false,
MvccVacuumFrequency = 20000,
MvccVacuumThreadCount = 8,
SqlQueryHistorySize = 99,
SqlSchemas = new List<string> { "SCHEMA_3", "schema_4" }
};
}
private class MyConsistentId
{
public string Data { get; set; }
private bool Equals(MyConsistentId other)
{
return string.Equals(Data, other.Data);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != GetType()) return false;
return Equals((MyConsistentId) obj);
}
public override int GetHashCode()
{
return (Data != null ? Data.GetHashCode() : 0);
}
public static bool operator ==(MyConsistentId left, MyConsistentId right)
{
return Equals(left, right);
}
public static bool operator !=(MyConsistentId left, MyConsistentId right)
{
return !Equals(left, right);
}
}
}
}
| |
// Copyright 2018 Esri.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
// You may obtain a copy of the License at: http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific
// language governing permissions and limitations under the License.
using Esri.ArcGISRuntime.Geometry;
using Esri.ArcGISRuntime.Mapping;
using Esri.ArcGISRuntime.Symbology;
using Esri.ArcGISRuntime.UI;
using Esri.ArcGISRuntime.UI.Controls;
using Foundation;
using System;
using System.Collections.Generic;
using System.Linq;
using UIKit;
namespace ArcGISRuntime.Samples.ConvexHull
{
[Register("ConvexHull")]
[ArcGISRuntime.Samples.Shared.Attributes.Sample(
name: "Convex hull",
category: "Geometry",
description: "Create a convex hull for a given set of points. The convex hull is a polygon with shortest perimeter that encloses a set of points. As a visual analogy, consider a set of points as nails in a board. The convex hull of the points would be like a rubber band stretched around the outermost nails.",
instructions: "Tap on the map to add points. Tap the \"Create Convex Hull\" button to generate the convex hull of those points. Tap the \"Reset\" button to start over.",
tags: new[] { "convex hull", "geometry", "spatial analysis" })]
public class ConvexHull : UIViewController
{
// Hold references to UI controls.
private MapView _myMapView;
private UIBarButtonItem _createHullButton;
private UIBarButtonItem _helpButton;
private UIBarButtonItem _resetButton;
// Graphics overlay to display the graphics.
private GraphicsOverlay _graphicsOverlay;
// List of geometry values (MapPoints in this case) that will be used by the GeometryEngine.ConvexHull operation.
private readonly PointCollection _inputPointCollection = new PointCollection(SpatialReferences.WebMercator);
public ConvexHull()
{
Title = "Convex hull";
}
private void Initialize()
{
// Create and show a map with a topographic basemap.
_myMapView.Map = new Map(BasemapStyle.ArcGISTopographic);
// Create an overlay to hold the lines of the hull.
_graphicsOverlay = new GraphicsOverlay();
// Add the created graphics overlay to the MapView.
_myMapView.GraphicsOverlays.Add(_graphicsOverlay);
}
private void MyMapView_GeoViewTapped(object sender, GeoViewInputEventArgs e)
{
try
{
// Normalize the tapped point.
var centralizedPoint = (MapPoint)GeometryEngine.NormalizeCentralMeridian(e.Location);
// Add the map point to the list that will be used by the GeometryEngine.ConvexHull operation.
_inputPointCollection.Add(centralizedPoint);
// Check if there are at least three points.
if (_inputPointCollection.Count > 2)
{
// Enable the button for creating hulls.
_createHullButton.Enabled = true;
}
// Create a simple marker symbol to display where the user tapped/clicked on the map. The marker symbol
// will be a solid, red circle.
SimpleMarkerSymbol userTappedSimpleMarkerSymbol = new SimpleMarkerSymbol(SimpleMarkerSymbolStyle.Circle, System.Drawing.Color.Red, 10);
// Create a new graphic for the spot where the user clicked on the map using the simple marker symbol.
Graphic userTappedGraphic = new Graphic(e.Location, new Dictionary<string, object> { { "Type", "Point" } }, userTappedSimpleMarkerSymbol)
{
// Set the Z index for the user tapped graphic so that it appears above the convex hull graphic(s) added later.
ZIndex = 1
};
// Add the user tapped/clicked map point graphic to the graphic overlay.
_graphicsOverlay.Graphics.Add(userTappedGraphic);
}
catch (Exception ex)
{
// Display an error message if there is a problem adding user tapped graphics.
UIAlertController alertController = UIAlertController.Create("Can't add user-tapped graphic.", ex.Message, UIAlertControllerStyle.Alert);
alertController.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null));
PresentViewController(alertController, true, null);
}
}
private void ConvexHullButton_Click(object sender, EventArgs e)
{
try
{
// Create a multi-point geometry from the user tapped input map points.
Multipoint inputMultipoint = new Multipoint(_inputPointCollection);
// Get the returned result from the convex hull operation.
Geometry convexHullGeometry = GeometryEngine.ConvexHull(inputMultipoint);
// Create a simple line symbol for the outline of the convex hull graphic(s).
SimpleLineSymbol convexHullSimpleLineSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, System.Drawing.Color.Blue, 4);
// Create the simple fill symbol for the convex hull graphic(s) - comprised of a fill style, fill
// color and outline. It will be a hollow (i.e.. see-through) polygon graphic with a thick red outline.
SimpleFillSymbol convexHullSimpleFillSymbol = new SimpleFillSymbol(SimpleFillSymbolStyle.Null, System.Drawing.Color.Red, convexHullSimpleLineSymbol);
// Create the graphic for the convex hull - comprised of a polygon shape and fill symbol.
Graphic convexHullGraphic = new Graphic(convexHullGeometry, new Dictionary<string, object>() { { "Type", "Hull" } }, convexHullSimpleFillSymbol)
{
// Set the Z index for the convex hull graphic so that it appears below the initial input user tapped map point graphics added earlier.
ZIndex = 0
};
// Remove any existing convex hull graphics from the overlay.
foreach (Graphic g in _graphicsOverlay.Graphics.ToList())
if ((string)g.Attributes["Type"] == "Hull")
_graphicsOverlay.Graphics.Remove(g);
// Add the convex hull graphic to the graphics overlay collection.
_graphicsOverlay.Graphics.Add(convexHullGraphic);
// Disable the button after has been used.
_createHullButton.Enabled = false;
}
catch (Exception ex)
{
// Display an error message if there is a problem generating convex hull operation.
UIAlertController alertController = UIAlertController.Create("Geometry Engine Failed!", ex.Message, UIAlertControllerStyle.Alert);
alertController.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null));
PresentViewController(alertController, true, null);
}
}
private void ResetButton_Click(object sender, EventArgs e)
{
// Clear the existing points and graphics.
_inputPointCollection.Clear();
_graphicsOverlay.Graphics.Clear();
// Disable the convex hull button.
_createHullButton.Enabled = false;
}
private void HelpButton_Click(object sender, EventArgs e)
{
UIAlertController unionAlert = UIAlertController.Create("Create a convex hull", "Tap the map in several places, then use the buttons to create or reset the convex hull.", UIAlertControllerStyle.Alert);
unionAlert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null));
PresentViewController(unionAlert, true, null);
}
public override void ViewDidLoad()
{
base.ViewDidLoad();
Initialize();
}
public override void LoadView()
{
// Create the views.
View = new UIView { BackgroundColor = ApplicationTheme.BackgroundColor };
_myMapView = new MapView();
_myMapView.TranslatesAutoresizingMaskIntoConstraints = false;
_createHullButton = new UIBarButtonItem();
_createHullButton.Title = "Create convex hull";
_createHullButton.Enabled = false;
_helpButton = new UIBarButtonItem();
_helpButton.Title = "Help";
_resetButton = new UIBarButtonItem();
_resetButton.Title = "Reset";
UIToolbar toolbar = new UIToolbar();
toolbar.TranslatesAutoresizingMaskIntoConstraints = false;
toolbar.Items = new[]
{
_helpButton,
_resetButton,
new UIBarButtonItem(UIBarButtonSystemItem.FlexibleSpace),
_createHullButton
};
// Add the views.
View.AddSubviews(_myMapView, toolbar);
// Lay out the views.
NSLayoutConstraint.ActivateConstraints(new[]
{
_myMapView.TopAnchor.ConstraintEqualTo(View.SafeAreaLayoutGuide.TopAnchor),
_myMapView.LeadingAnchor.ConstraintEqualTo(View.LeadingAnchor),
_myMapView.TrailingAnchor.ConstraintEqualTo(View.TrailingAnchor),
_myMapView.BottomAnchor.ConstraintEqualTo(toolbar.TopAnchor),
toolbar.BottomAnchor.ConstraintEqualTo(View.SafeAreaLayoutGuide.BottomAnchor),
toolbar.LeadingAnchor.ConstraintEqualTo(View.LeadingAnchor),
toolbar.TrailingAnchor.ConstraintEqualTo(View.TrailingAnchor),
});
}
public override void ViewWillAppear(bool animated)
{
base.ViewWillAppear(animated);
// Subscribe to events.
_myMapView.GeoViewTapped += MyMapView_GeoViewTapped;
_helpButton.Clicked += HelpButton_Click;
_resetButton.Clicked += ResetButton_Click;
_createHullButton.Clicked += ConvexHullButton_Click;
}
public override void ViewDidDisappear(bool animated)
{
base.ViewDidDisappear(animated);
// Unsubscribe from events, per best practice.
_myMapView.GeoViewTapped -= MyMapView_GeoViewTapped;
_helpButton.Clicked -= HelpButton_Click;
_resetButton.Clicked -= ResetButton_Click;
_createHullButton.Clicked -= ConvexHullButton_Click;
}
}
}
| |
using System;
using System.Collections.Generic;
namespace NQuery.Compilation
{
internal sealed class SelectionPusher : StandardVisitor
{
#region Helpers
private static FilterAlgebraNode GetFilterFromAndParts(IList<ExpressionNode> andParts, AlgebraNode input)
{
FilterAlgebraNode filterAlgebraNode = new FilterAlgebraNode();
filterAlgebraNode.Input = input;
filterAlgebraNode.Predicate = AstUtil.CombineConditions(LogicalOperator.And, andParts);
return filterAlgebraNode;
}
private AlgebraNode PushOverUnary(FilterAlgebraNode node)
{
UnaryAlgebraNode inputNode = (UnaryAlgebraNode) node.Input;
node.Input = inputNode.Input;
inputNode.Input = VisitAlgebraNode(node);
return inputNode;
}
private AlgebraNode PushOverValueDefininingUnary(IEnumerable<ValueDefinition> definedValues, FilterAlgebraNode node)
{
UnaryAlgebraNode inputNode = (UnaryAlgebraNode)node.Input;
List<ExpressionNode> nonDependingAndParts = new List<ExpressionNode>();
List<ExpressionNode> dependingAndParts = new List<ExpressionNode>();
foreach (ExpressionNode andPart in AstUtil.SplitCondition(LogicalOperator.And, node.Predicate))
{
RowBufferEntry[] rowBufferEntries = AstUtil.GetRowBufferEntryReferences(andPart);
bool dependsOnDefinedValue = false;
foreach (ValueDefinition definedValue in definedValues)
{
if (ArrayHelpers.Contains(rowBufferEntries, definedValue.Target))
{
dependsOnDefinedValue = true;
break;
}
}
if (dependsOnDefinedValue)
dependingAndParts.Add(andPart);
else
nonDependingAndParts.Add(andPart);
}
if (nonDependingAndParts.Count > 0)
{
node.Predicate = AstUtil.CombineConditions(LogicalOperator.And, dependingAndParts);
inputNode.Input = GetFilterFromAndParts(nonDependingAndParts, inputNode.Input);
if (node.Predicate == null)
{
node.Input = inputNode.Input;
inputNode.Input = VisitAlgebraNode(node);
return inputNode;
}
}
node.Input = VisitAlgebraNode(node.Input);
return node;
}
private AlgebraNode MergeWithFilter(FilterAlgebraNode node)
{
// The input is also a filter, so we can merge this predicate with
// the input filter.
FilterAlgebraNode inputNode = (FilterAlgebraNode) node.Input;
inputNode.Predicate = AstUtil.CombineConditions(LogicalOperator.And, inputNode.Predicate, node.Predicate);
return VisitAlgebraNode(inputNode);
}
private AlgebraNode PushOverComputeScalar(FilterAlgebraNode node)
{
// Predicates can be pushed over a compute scalar if it does not contain any row buffer entries
// that are defined by the compute scalar node.
ComputeScalarAlgebraNode inputNode = (ComputeScalarAlgebraNode) node.Input;
return PushOverValueDefininingUnary(inputNode.DefinedValues, node);
}
private AlgebraNode PushOverAggregate(FilterAlgebraNode node)
{
// TODO: It is not that easy.
// For example this condition can be pushed 'GroupCol = Value' while this can't: 'GroupCol = Value OR Func(const) = const'
// Formally, a predicate can be pushed over an aggregate if and only if all disjuncts of the predicate's CNF do reference
// at least one grouping column.
// Since this requires cloning of the predicate and heavy rewriting this is not done (yet).
return base.VisitFilterAlgebraNode(node);
/*
// Predicates can be pushed over an aggregation if it does not contain any aggregate function.
AggregateAlgebraNode inputNode = (AggregateAlgebraNode)node.Input;
return PushOverValueDefininingUnary(inputNode.DefinedValues, node);
*/
}
private AlgebraNode PushOverJoin(FilterAlgebraNode node)
{
JoinAlgebraNode inputNode = (JoinAlgebraNode) node.Input;
// Get declared tables of left and right
RowBufferEntry[] leftDefinedValues = AstUtil.GetDefinedValueEntries(inputNode.Left);
RowBufferEntry[] rightDefinedValues = AstUtil.GetDefinedValueEntries(inputNode.Right);
// Obviously, we cannot merge the filter with the join if the join is an outer join
// (since it would change the join's semantics).
//
// Another less obvious restriction is that we cannot merge a filter with the join if
// the join has a passthru predicate. In case the passthru predicte evaluates to true
// the filter would not be applied. However, we are allowed to push the filter the over
// join.
bool canMerge = inputNode.Op != JoinAlgebraNode.JoinOperator.FullOuterJoin &&
inputNode.Op != JoinAlgebraNode.JoinOperator.LeftOuterJoin &&
inputNode.Op != JoinAlgebraNode.JoinOperator.RightOuterJoin &&
inputNode.PassthruPredicate == null;
if (canMerge)
{
// We can merge the filter with the condition of the join.
//
// However, we have to make sure that the predicate does not reference the probe column.
// Since not having a probe column is the most common case, we don't always split the
// predicate into conjuncts.
if (inputNode.ProbeBufferEntry == null || !ArrayHelpers.Contains(AstUtil.GetRowBufferEntryReferences(node.Predicate), inputNode.ProbeBufferEntry))
{
// Either there is no probe column defined or the filter does not reference it. That means
// no splitting necessary, we can just merge the whole predicate with the join predicate.
inputNode.Predicate = AstUtil.CombineConditions(LogicalOperator.And, inputNode.Predicate, node.Predicate);
return VisitAlgebraNode(inputNode);
}
else
{
// Unfortunately, the filter references the probe column. Now let's check whether we can merge
// conjuncts of the predicate.
List<ExpressionNode> remainingAndParts = new List<ExpressionNode>();
List<ExpressionNode> mergableAndParts = new List<ExpressionNode>();
foreach (ExpressionNode andPart in AstUtil.SplitCondition(LogicalOperator.And, node.Predicate))
{
bool andPartReferencesProbeColumn = ArrayHelpers.Contains(AstUtil.GetRowBufferEntryReferences(andPart), inputNode.ProbeBufferEntry);
if (andPartReferencesProbeColumn)
remainingAndParts.Add(andPart);
else
mergableAndParts.Add(andPart);
}
if (mergableAndParts.Count > 0)
{
ExpressionNode combinedMergableAndParts = AstUtil.CombineConditions(LogicalOperator.And, mergableAndParts.ToArray());
inputNode.Predicate = AstUtil.CombineConditions(LogicalOperator.And, inputNode.Predicate, combinedMergableAndParts);
node.Predicate = AstUtil.CombineConditions(LogicalOperator.And, remainingAndParts);
if (node.Predicate == null)
return VisitAlgebraNode(inputNode);
}
}
}
else
{
// The condition cannot be merged. Now we try to push AND-parts over the join.
List<ExpressionNode> leftAndParts = new List<ExpressionNode>();
List<ExpressionNode> rightAndParts = new List<ExpressionNode>();
List<ExpressionNode> remainingAndParts = new List<ExpressionNode>();
foreach (ExpressionNode andPart in AstUtil.SplitCondition(LogicalOperator.And, node.Predicate))
{
bool andPartReferencesProbeColumn = inputNode.ProbeBufferEntry != null &&
ArrayHelpers.Contains(AstUtil.GetRowBufferEntryReferences(andPart), inputNode.ProbeBufferEntry);
if (!andPartReferencesProbeColumn && AstUtil.AllowsLeftPushOver(inputNode.Op) && AstUtil.ExpressionDoesNotReference(andPart, rightDefinedValues))
{
// The AND-part depends only on the LHS and the join is inner/left.
// So we are allowed to push this AND-part down.
leftAndParts.Add(andPart);
}
else if (!andPartReferencesProbeColumn && AstUtil.AllowsRightPushOver(inputNode.Op) && AstUtil.ExpressionDoesNotReference(andPart, leftDefinedValues))
{
// The AND-part depends only on the RHS and the join is inner/right.
// So we are allowed to push this AND-part down.
rightAndParts.Add(andPart);
}
else
{
remainingAndParts.Add(andPart);
}
}
if (leftAndParts.Count > 0)
{
inputNode.Left = GetFilterFromAndParts(leftAndParts, inputNode.Left);
}
if (rightAndParts.Count > 0)
{
inputNode.Right = GetFilterFromAndParts(rightAndParts, inputNode.Right);
}
node.Predicate = AstUtil.CombineConditions(LogicalOperator.And, remainingAndParts);
if (node.Predicate == null)
return VisitAlgebraNode(inputNode);
}
node.Input = VisitAlgebraNode(node.Input);
return node;
}
private AlgebraNode PushOverConcat(FilterAlgebraNode node)
{
ConcatAlgebraNode inputNode = (ConcatAlgebraNode) node.Input;
for (int i = 0; i < inputNode.Inputs.Length; i++)
{
ExpressionNode predicate = (ExpressionNode)node.Predicate.Clone();
ConcatRowBufferEntryReplacer concatRowBufferEntryReplacer = new ConcatRowBufferEntryReplacer(inputNode.DefinedValues, i);
predicate = concatRowBufferEntryReplacer.VisitExpression(predicate);
FilterAlgebraNode filterAlgebraNode = new FilterAlgebraNode();
filterAlgebraNode.Input = inputNode.Inputs[i];
filterAlgebraNode.Predicate = predicate;
inputNode.Inputs[i] = VisitAlgebraNode(filterAlgebraNode);
}
return inputNode;
}
private sealed class ConcatRowBufferEntryReplacer : StandardVisitor
{
private UnitedValueDefinition[] _unitedValues;
private int _inputIndex;
public ConcatRowBufferEntryReplacer(UnitedValueDefinition[] unitedValues, int inputIndex)
{
_unitedValues = unitedValues;
_inputIndex = inputIndex;
}
public override ExpressionNode VisitRowBufferEntryExpression(RowBufferEntryExpression expression)
{
foreach (UnitedValueDefinition unitedValue in _unitedValues)
{
if (expression.RowBufferEntry == unitedValue.Target)
expression.RowBufferEntry = unitedValue.DependendEntries[_inputIndex];
}
return expression;
}
}
#endregion
public override AlgebraNode VisitFilterAlgebraNode(FilterAlgebraNode node)
{
switch (node.Input.NodeType)
{
case AstNodeType.SortAlgebraNode:
case AstNodeType.ResultAlgebraNode:
case AstNodeType.TopAlgebraNode:
return PushOverUnary(node);
case AstNodeType.FilterAlgebraNode:
return MergeWithFilter(node);
case AstNodeType.ComputeScalarAlgebraNode:
return PushOverComputeScalar(node);
case AstNodeType.AggregateAlgebraNode:
return PushOverAggregate(node);
case AstNodeType.JoinAlgebraNode:
return PushOverJoin(node);
case AstNodeType.ConcatAlgebraNode:
return PushOverConcat(node);
default:
return base.VisitFilterAlgebraNode(node);
}
}
public override AlgebraNode VisitJoinAlgebraNode(JoinAlgebraNode node)
{
// Get declared tables of left and right
RowBufferEntry[] leftDefinedValues = AstUtil.GetDefinedValueEntries(node.Left);
RowBufferEntry[] rightDefinedValues = AstUtil.GetDefinedValueEntries(node.Right);
// Analyze AND-parts of Condition
if (node.Predicate != null)
{
List<ExpressionNode> leftAndParts = new List<ExpressionNode>();
List<ExpressionNode> rightAndParts = new List<ExpressionNode>();
List<ExpressionNode> remainingAndParts = new List<ExpressionNode>();
foreach (ExpressionNode andPart in AstUtil.SplitCondition(LogicalOperator.And, node.Predicate))
{
// Check if we can push this AND-part down.
if (AstUtil.AllowsLeftPushDown(node.Op) && AstUtil.ExpressionDoesNotReference(andPart, rightDefinedValues))
{
leftAndParts.Add(andPart);
}
else if (AstUtil.AllowsRightPushDown(node.Op) && AstUtil.ExpressionDoesNotReference(andPart, leftDefinedValues))
{
rightAndParts.Add(andPart);
}
else
{
remainingAndParts.Add(andPart);
}
}
if (leftAndParts.Count > 0)
{
node.Left = GetFilterFromAndParts(leftAndParts, node.Left);
}
if (rightAndParts.Count > 0)
{
node.Right = GetFilterFromAndParts(rightAndParts, node.Right);
}
node.Predicate = AstUtil.CombineConditions(LogicalOperator.And, remainingAndParts);
}
// Visit children
node.Left = VisitAlgebraNode(node.Left);
node.Right = VisitAlgebraNode(node.Right);
return node;
}
}
}
| |
// Outline Object Copy|Highlighters|40030
namespace VRTK.Highlighters
{
using UnityEngine;
using System;
using System.Collections.Generic;
/// <summary>
/// The Outline Object Copy Highlighter works by making a copy of a mesh and adding an outline shader to it and toggling the appearance of the highlighted object.
/// </summary>
/// <example>
/// `VRTK/Examples/005_Controller_BasicObjectGrabbing` demonstrates the outline highlighting on the green sphere when the controller touches it.
///
/// `VRTK/Examples/035_Controller_OpacityAndHighlighting` demonstrates the outline highlighting if the left controller collides with the green box.
/// </example>
public class VRTK_OutlineObjectCopyHighlighter : VRTK_BaseHighlighter
{
[Tooltip("The thickness of the outline effect")]
public float thickness = 1f;
[Tooltip("The GameObjects to use as the model to outline. If one isn't provided then the first GameObject with a valid Renderer in the current GameObject hierarchy will be used.")]
public GameObject[] customOutlineModels;
[Tooltip("A path to a GameObject to find at runtime, if the GameObject doesn't exist at edit time.")]
public string[] customOutlineModelPaths;
[Tooltip("If the mesh has multiple sub-meshes to highlight then this should be checked, otherwise only the first mesh will be highlighted.")]
public bool enableSubmeshHighlight = false;
protected Material stencilOutline;
protected GameObject[] highlightModels;
protected string[] copyComponents = new string[] { "UnityEngine.MeshFilter", "UnityEngine.MeshRenderer" };
/// <summary>
/// The Initialise method sets up the highlighter for use.
/// </summary>
/// <param name="color">Not used.</param>
/// <param name="options">A dictionary array containing the highlighter options:\r * `<'thickness', float>` - Same as `thickness` inspector parameter.\r * `<'customOutlineModels', GameObject[]>` - Same as `customOutlineModels` inspector parameter.\r * `<'customOutlineModelPaths', string[]>` - Same as `customOutlineModelPaths` inspector parameter.</param>
public override void Initialise(Color? color = null, Dictionary<string, object> options = null)
{
usesClonedObject = true;
if (stencilOutline == null)
{
stencilOutline = Instantiate((Material)Resources.Load("OutlineBasic"));
}
SetOptions(options);
ResetHighlighter();
}
/// <summary>
/// The ResetHighlighter method creates the additional model to use as the outline highlighted object.
/// </summary>
public override void ResetHighlighter()
{
DeleteExistingHighlightModels();
//First try and use the paths if they have been set
ResetHighlighterWithCustomModelPaths();
//If the custom models have been set then use these to override any set paths.
ResetHighlighterWithCustomModels();
//if no highlights set then try falling back
ResetHighlightersWithCurrentGameObject();
}
/// <summary>
/// The Highlight method initiates the outline object to be enabled and display the outline colour.
/// </summary>
/// <param name="color">The colour to outline with.</param>
/// <param name="duration">Not used.</param>
public override void Highlight(Color? color, float duration = 0f)
{
if (highlightModels != null && highlightModels.Length > 0)
{
stencilOutline.SetFloat("_Thickness", thickness);
stencilOutline.SetColor("_OutlineColor", (Color)color);
for (int i = 0; i < highlightModels.Length; i++)
{
if (highlightModels[i])
{
highlightModels[i].SetActive(true);
}
}
}
}
/// <summary>
/// The Unhighlight method hides the outline object and removes the outline colour.
/// </summary>
/// <param name="color">Not used.</param>
/// <param name="duration">Not used.</param>
public override void Unhighlight(Color? color = null, float duration = 0f)
{
if (highlightModels != null)
{
for (int i = 0; i < highlightModels.Length; i++)
{
if (highlightModels[i])
{
highlightModels[i].SetActive(false);
}
}
}
}
protected virtual void OnEnable()
{
if (customOutlineModels == null)
{
customOutlineModels = new GameObject[0];
}
if (customOutlineModelPaths == null)
{
customOutlineModelPaths = new string[0];
}
}
protected virtual void OnDestroy()
{
if (highlightModels != null)
{
for (int i = 0; i < highlightModels.Length; i++)
{
if (highlightModels[i])
{
Destroy(highlightModels[i]);
}
}
}
Destroy(stencilOutline);
}
protected virtual void ResetHighlighterWithCustomModels()
{
if (customOutlineModels != null && customOutlineModels.Length > 0)
{
highlightModels = new GameObject[customOutlineModels.Length];
for (int i = 0; i < customOutlineModels.Length; i++)
{
highlightModels[i] = CreateHighlightModel(customOutlineModels[i], "");
}
}
}
protected virtual void ResetHighlighterWithCustomModelPaths()
{
if (customOutlineModelPaths != null && customOutlineModelPaths.Length > 0)
{
highlightModels = new GameObject[customOutlineModels.Length];
for (int i = 0; i < customOutlineModelPaths.Length; i++)
{
highlightModels[i] = CreateHighlightModel(null, customOutlineModelPaths[i]);
}
}
}
protected virtual void ResetHighlightersWithCurrentGameObject()
{
if (highlightModels == null || highlightModels.Length == 0)
{
highlightModels = new GameObject[1];
highlightModels[0] = CreateHighlightModel(null, "");
}
}
protected virtual void SetOptions(Dictionary<string, object> options = null)
{
var tmpThickness = GetOption<float>(options, "thickness");
if (tmpThickness > 0f)
{
thickness = tmpThickness;
}
var tmpCustomModels = GetOption<GameObject[]>(options, "customOutlineModels");
if (tmpCustomModels != null)
{
customOutlineModels = tmpCustomModels;
}
var tmpCustomModelPaths = GetOption<string[]>(options, "customOutlineModelPaths");
if (tmpCustomModelPaths != null)
{
customOutlineModelPaths = tmpCustomModelPaths;
}
}
protected virtual void DeleteExistingHighlightModels()
{
var existingHighlighterObjects = GetComponentsInChildren<VRTK_PlayerObject>(true);
for (int i = 0; i < existingHighlighterObjects.Length; i++)
{
if (existingHighlighterObjects[i].objectType == VRTK_PlayerObject.ObjectTypes.Highlighter)
{
Destroy(existingHighlighterObjects[i].gameObject);
}
}
}
protected virtual GameObject CreateHighlightModel(GameObject givenOutlineModel, string givenOutlineModelPath)
{
if (givenOutlineModel != null)
{
givenOutlineModel = (givenOutlineModel.GetComponent<Renderer>() ? givenOutlineModel : givenOutlineModel.GetComponentInChildren<Renderer>().gameObject);
}
else if (givenOutlineModelPath != "")
{
var getChildModel = transform.FindChild(givenOutlineModelPath);
givenOutlineModel = (getChildModel ? getChildModel.gameObject : null);
}
GameObject copyModel = givenOutlineModel;
if (copyModel == null)
{
copyModel = (GetComponent<Renderer>() ? gameObject : GetComponentInChildren<Renderer>().gameObject);
}
if (copyModel == null)
{
Debug.LogError("No Renderer has been found on the model to add highlighting to");
return null;
}
GameObject highlightModel = new GameObject(name + "_HighlightModel");
highlightModel.transform.SetParent(copyModel.transform.parent, false);
highlightModel.transform.localPosition = copyModel.transform.localPosition;
highlightModel.transform.localRotation = copyModel.transform.localRotation;
highlightModel.transform.localScale = copyModel.transform.localScale;
highlightModel.transform.SetParent(transform);
foreach (var component in copyModel.GetComponents<Component>())
{
if (Array.IndexOf(copyComponents, component.GetType().ToString()) >= 0)
{
VRTK_SharedMethods.CloneComponent(component, highlightModel);
}
}
var copyMesh = copyModel.GetComponent<MeshFilter>();
var highlightMesh = highlightModel.GetComponent<MeshFilter>();
if (highlightMesh)
{
if (enableSubmeshHighlight)
{
List<CombineInstance> combine = new List<CombineInstance>();
for (int i = 0; i < copyMesh.mesh.subMeshCount; i++)
{
CombineInstance ci = new CombineInstance();
ci.mesh = copyMesh.mesh;
ci.subMeshIndex = i;
ci.transform = copyMesh.transform.localToWorldMatrix;
combine.Add(ci);
}
highlightMesh.mesh = new Mesh();
highlightMesh.mesh.CombineMeshes(combine.ToArray(), true, false);
}
else
{
highlightMesh.mesh = copyMesh.mesh;
}
highlightModel.GetComponent<Renderer>().material = stencilOutline;
}
highlightModel.SetActive(false);
VRTK_PlayerObject.SetPlayerObject(highlightModel, VRTK_PlayerObject.ObjectTypes.Highlighter);
return highlightModel;
}
}
}
| |
using System;
using System.IO;
using System.Runtime.CompilerServices;
using System.Threading;
using Tamir.SharpSsh.java.io;
namespace Tamir.Streams
{
/*
* @(#)PipedInputStream.java 1.35 03/12/19
*
* Copyright 2004 Sun Microsystems, Inc. All rights reserved.
* SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
/**
* A piped input stream should be connected
* to a piped output stream; the piped input
* stream then provides whatever data bytes
* are written to the piped output stream.
* Typically, data is read from a <code>PipedInputStream</code>
* object by one thread and data is written
* to the corresponding <code>PipedOutputStream</code>
* by some other thread. Attempting to use
* both objects from a single thread is not
* recommended, as it may deadlock the thread.
* The piped input stream contains a buffer,
* decoupling read operations from write operations,
* within limits.
*
* @author James Gosling
* @version 1.35, 12/19/03
* @see java.io.PipedOutputStream
* @since JDK1.0
*/
public class PipedInputStream : InputStream
{
internal bool closedByWriter = false;
internal volatile bool closedByReader = false;
internal bool connected = false;
/* REMIND: identification of the read and write sides needs to be
more sophisticated. Either using thread groups (but what about
pipes within a thread?) or using finalization (but it may be a
long time until the next GC). */
internal Thread readSide;
internal Thread writeSide;
/**
* The size of the pipe's circular input buffer.
* @since JDK1.1
*/
internal const int PIPE_SIZE = 1024;
/**
* The circular buffer into which incoming data is placed.
* @since JDK1.1
*/
internal byte[] buffer = new byte[PIPE_SIZE];
/**
* The index of the position in the circular buffer at which the
* next byte of data will be stored when received from the connected
* piped output stream. <code>in<0</code> implies the buffer is empty,
* <code>in==out</code> implies the buffer is full
* @since JDK1.1
*/
internal int m_in = -1;
/**
* The index of the position in the circular buffer at which the next
* byte of data will be read by this piped input stream.
* @since JDK1.1
*/
internal int m_out = 0;
/**
* Creates a <code>PipedInputStream</code> so
* that it is connected to the piped output
* stream <code>src</code>. Data bytes written
* to <code>src</code> will then be available
* as input from this stream.
*
* @param src the stream to connect to.
* @exception IOException if an I/O error occurs.
*/
public PipedInputStream(PipedOutputStream src)
{
connect(src);
}
/**
* Creates a <code>PipedInputStream</code> so
* that it is not yet connected. It must be
* connected to a <code>PipedOutputStream</code>
* before being used.
*
* @see java.io.PipedInputStream#connect(java.io.PipedOutputStream)
* @see java.io.PipedOutputStream#connect(java.io.PipedInputStream)
*/
public PipedInputStream()
{
}
/**
* Causes this piped input stream to be connected
* to the piped output stream <code>src</code>.
* If this object is already connected to some
* other piped output stream, an <code>IOException</code>
* is thrown.
* <p>
* If <code>src</code> is an
* unconnected piped output stream and <code>snk</code>
* is an unconnected piped input stream, they
* may be connected by either the call:
* <p>
* <pre><code>snk.connect(src)</code> </pre>
* <p>
* or the call:
* <p>
* <pre><code>src.connect(snk)</code> </pre>
* <p>
* The two
* calls have the same effect.
*
* @param src The piped output stream to connect to.
* @exception IOException if an I/O error occurs.
*/
public virtual void connect(PipedOutputStream src)
{
src.connect(this);
}
/**
* Receives a byte of data. This method will block if no input is
* available.
* @param b the byte being received
* @exception IOException If the pipe is broken.
* @since JDK1.1
*/
[MethodImpl(MethodImplOptions.Synchronized)]
internal void receive(int b)
{
checkStateForReceive();
writeSide = Thread.CurrentThread;
if (m_in == m_out)
awaitSpace();
if (m_in < 0)
{
m_in = 0;
m_out = 0;
}
buffer[m_in++] = (byte)(b & 0xFF);
if (m_in >= buffer.Length)
{
m_in = 0;
}
}
/**
* Receives data into an array of bytes. This method will
* block until some input is available.
* @param b the buffer into which the data is received
* @param off the start offset of the data
* @param len the maximum number of bytes received
* @exception IOException If an I/O error has occurred.
*/
[MethodImpl(MethodImplOptions.Synchronized)]
internal void receive(byte[] b, int off, int len)
{
checkStateForReceive();
writeSide = Thread.CurrentThread;
int bytesToTransfer = len;
while (bytesToTransfer > 0)
{
if (m_in == m_out)
awaitSpace();
int nextTransferAmount = 0;
if (m_out < m_in)
{
nextTransferAmount = buffer.Length - m_in;
}
else if (m_in < m_out)
{
if (m_in == -1)
{
m_in = m_out = 0;
nextTransferAmount = buffer.Length - m_in;
}
else
{
nextTransferAmount = m_out - m_in;
}
}
if (nextTransferAmount > bytesToTransfer)
nextTransferAmount = bytesToTransfer;
assert(nextTransferAmount > 0);
Array.Copy(b, off, buffer, m_in, nextTransferAmount);
bytesToTransfer -= nextTransferAmount;
off += nextTransferAmount;
m_in += nextTransferAmount;
if (m_in >= buffer.Length)
{
m_in = 0;
}
}
}
private void checkStateForReceive()
{
if (!connected)
{
throw new IOException("Pipe not connected");
}
else if (closedByWriter || closedByReader)
{
throw new IOException("Pipe closed");
}
else if (readSide != null && !readSide.IsAlive)
{
throw new IOException("Read end dead");
}
}
private void awaitSpace()
{
while (m_in == m_out)
{
if ((readSide != null) && !readSide.IsAlive)
{
throw new IOException("Pipe broken");
}
/* full: kick any waiting readers */
//java: notifyAll();
Monitor.PulseAll(this);
try
{
//java: wait(1000);
Monitor.Wait(this, 1000);
}
catch (ThreadInterruptedException ex)
{
throw ex;
}
}
}
/**
* Notifies all waiting threads that the last byte of data has been
* received.
*/
[MethodImpl(MethodImplOptions.Synchronized)]
internal void receivedLast()
{
closedByWriter = true;
//notifyAll();
Monitor.PulseAll(this);
}
/**
* Reads the next byte of data from this piped input stream. The
* value byte is returned as an <code>int</code> in the range
* <code>0</code> to <code>255</code>. If no byte is available
* because the end of the stream has been reached, the value
* <code>-1</code> is returned. This method blocks until input data
* is available, the end of the stream is detected, or an exception
* is thrown.
* If a thread was providing data bytes
* to the connected piped output stream, but
* the thread is no longer alive, then an
* <code>IOException</code> is thrown.
*
* @return the next byte of data, or <code>-1</code> if the end of the
* stream is reached.
* @exception IOException if the pipe is broken.
*/
[MethodImpl(MethodImplOptions.Synchronized)]
public virtual new int read()
{
if (!connected)
{
throw new IOException("Pipe not connected");
}
else if (closedByReader)
{
throw new IOException("Pipe closed");
}
else if (writeSide != null && !writeSide.IsAlive
&& !closedByWriter && (m_in < 0))
{
throw new IOException("Write end dead");
}
readSide = Thread.CurrentThread;
int trials = 2;
while (m_in < 0)
{
if (closedByWriter)
{
/* closed by writer, return EOF */
return -1;
}
if ((writeSide != null) && (!writeSide.IsAlive) && (--trials < 0))
{
throw new IOException("Pipe broken");
}
/* might be a writer waiting */
Monitor.PulseAll(this);
Monitor.Wait(this, 1000);
}
int ret = buffer[m_out++] & 0xFF;
if (m_out >= buffer.Length)
{
m_out = 0;
}
if (m_in == m_out)
{
/* now empty */
m_in = -1;
}
return ret;
}
/**
* Reads up to <code>len</code> bytes of data from this piped input
* stream into an array of bytes. Less than <code>len</code> bytes
* will be read if the end of the data stream is reached. This method
* blocks until at least one byte of input is available.
* If a thread was providing data bytes
* to the connected piped output stream, but
* the thread is no longer alive, then an
* <code>IOException</code> is thrown.
*
* @param b the buffer into which the data is read.
* @param off the start offset of the data.
* @param len the maximum number of bytes read.
* @return the total number of bytes read into the buffer, or
* <code>-1</code> if there is no more data because the end of
* the stream has been reached.
* @exception IOException if an I/O error occurs.
*/
[MethodImpl(MethodImplOptions.Synchronized)]
public override int Read(byte[] b, int off, int len)
{
if (b == null)
{
throw new NullReferenceException();
}
else if ((off < 0) || (off > b.Length) || (len < 0) ||
((off + len) > b.Length) || ((off + len) < 0))
{
throw new IndexOutOfRangeException();
}
else if (len == 0)
{
return 0;
}
/* possibly wait on the first character */
int c = read();
if (c < 0)
{
return -1;
}
b[off] = (byte)c;
int rlen = 1;
while ((m_in >= 0) && (--len > 0))
{
b[off + rlen] = buffer[m_out++];
rlen++;
if (m_out >= buffer.Length)
{
m_out = 0;
}
if (m_in == m_out)
{
/* now empty */
m_in = -1;
}
}
return rlen;
}
/**
* Returns the number of bytes that can be read from this input
* stream without blocking. This method overrides the <code>available</code>
* method of the parent class.
*
* @return the number of bytes that can be read from this input stream
* without blocking.
* @exception IOException if an I/O error occurs.
* @since JDK1.0.2
*/
[MethodImpl(MethodImplOptions.Synchronized)]
public virtual int available()
{
if (m_in < 0)
return 0;
else if (m_in == m_out)
return buffer.Length;
else if (m_in > m_out)
return m_in - m_out;
else
return m_in + buffer.Length - m_out;
}
/**
* Closes this piped input stream and releases any system resources
* associated with the stream.
*
* @exception IOException if an I/O error occurs.
*/
public override void close()
{
closedByReader = true;
lock (this)
{
m_in = -1;
}
}
private void assert(bool exp)
{
if (!exp)
throw new Exception("Assertion failed!");
}
///////////////////////////////////////
public override int ReadByte()
{
return this.read();
}
public override void WriteByte(byte value)
{
}
public override void Write(byte[] buffer, int offset, int count)
{
}
public override void Close()
{
base.Close();
this.close();
}
public override bool CanRead
{
get { return true; }
}
public override bool CanWrite
{
get { return false; }
}
public override bool CanSeek
{
get { return false; }
}
public override void Flush()
{
}
public override long Length
{
get
{
if (m_in > m_out)
return (m_in - m_out);
else
{
return (buffer.Length - m_out + m_in);
}
}
}
public override long Position
{
get { return m_out; }
set { throw new IOException("Setting the position of this stream is not supported"); }
}
public override void SetLength(long value)
{
throw new IOException("Setting the length of this stream is not supported");
}
public override long Seek(long offset, SeekOrigin origin)
{
return 0;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using System.Collections.Generic;
using System.Threading;
using System.Runtime;
using System.Threading.Tasks;
using Xunit;
namespace System.Tests
{
public class GCExtendedTests : RemoteExecutorTestBase
{
private const int TimeoutMilliseconds = 10 * 30 * 1000; //if full GC is triggered it may take a while
[Fact]
[OuterLoop]
public static void GetGeneration_WeakReference()
{
RemoteInvokeOptions options = new RemoteInvokeOptions();
options.TimeOut = TimeoutMilliseconds;
RemoteInvoke(() =>
{
Func<WeakReference> getweakref = delegate ()
{
Version myobj = new Version();
var wkref = new WeakReference(myobj);
Assert.True(GC.TryStartNoGCRegion(1024));
Assert.True(GC.GetGeneration(wkref) >= 0);
Assert.Equal(GC.GetGeneration(wkref), GC.GetGeneration(myobj));
GC.EndNoGCRegion();
myobj = null;
return wkref;
};
WeakReference weakref = getweakref();
Assert.True(weakref != null);
#if !DEBUG
GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced, true, true);
Assert.Throws<ArgumentNullException>(() => GC.GetGeneration(weakref));
#endif
return SuccessExitCode;
}, options).Dispose();
}
[Fact]
public static void GCNotificationNegTests()
{
Assert.Throws<ArgumentOutOfRangeException>(() => GC.RegisterForFullGCNotification(-1, -1));
Assert.Throws<ArgumentOutOfRangeException>(() => GC.RegisterForFullGCNotification(100, -1));
Assert.Throws<ArgumentOutOfRangeException>(() => GC.RegisterForFullGCNotification(-1, 100));
Assert.Throws<ArgumentOutOfRangeException>(() => GC.RegisterForFullGCNotification(10, -1));
Assert.Throws<ArgumentOutOfRangeException>(() => GC.RegisterForFullGCNotification(-1, 10));
Assert.Throws<ArgumentOutOfRangeException>(() => GC.RegisterForFullGCNotification(100, 10));
Assert.Throws<ArgumentOutOfRangeException>(() => GC.RegisterForFullGCNotification(10, 100));
Assert.Throws<ArgumentOutOfRangeException>(() => GC.WaitForFullGCApproach(-2));
Assert.Throws<ArgumentOutOfRangeException>(() => GC.WaitForFullGCComplete(-2));
}
[Theory]
[InlineData(true, -1)]
[InlineData(false, -1)]
[InlineData(true, 0)]
[InlineData(false, 0)]
[InlineData(true, 100)]
[InlineData(false, 100)]
[InlineData(true, int.MaxValue)]
[InlineData(false, int.MaxValue)]
[OuterLoop]
public static void GCNotificationTests(bool approach, int timeout)
{
RemoteInvokeOptions options = new RemoteInvokeOptions();
options.TimeOut = TimeoutMilliseconds;
RemoteInvoke(() =>
{
TestWait(approach, timeout);
return SuccessExitCode;
}, options).Dispose();
}
[Fact]
[OuterLoop]
public static void TryStartNoGCRegion_EndNoGCRegion_ThrowsInvalidOperationException()
{
RemoteInvokeOptions options = new RemoteInvokeOptions();
options.TimeOut = TimeoutMilliseconds;
RemoteInvoke(() =>
{
Assert.Throws<InvalidOperationException>(() => GC.EndNoGCRegion());
return SuccessExitCode;
}, options).Dispose();
}
[Fact]
[OuterLoop]
public static void TryStartNoGCRegion_StartWhileInNoGCRegion()
{
RemoteInvokeOptions options = new RemoteInvokeOptions();
options.TimeOut = TimeoutMilliseconds;
RemoteInvoke(() =>
{
Assert.True(GC.TryStartNoGCRegion(1024));
Assert.Throws<InvalidOperationException>(() => GC.TryStartNoGCRegion(1024));
Assert.Throws<InvalidOperationException>(() => GC.EndNoGCRegion());
return SuccessExitCode;
}, options).Dispose();
}
[Fact]
[OuterLoop]
public static void TryStartNoGCRegion_StartWhileInNoGCRegion_BlockingCollection()
{
RemoteInvokeOptions options = new RemoteInvokeOptions();
options.TimeOut = TimeoutMilliseconds;
RemoteInvoke(() =>
{
Assert.True(GC.TryStartNoGCRegion(1024, true));
Assert.Throws<InvalidOperationException>(() => GC.TryStartNoGCRegion(1024, true));
Assert.Throws<InvalidOperationException>(() => GC.EndNoGCRegion());
return SuccessExitCode;
}, options).Dispose();
}
[Fact]
[OuterLoop]
public static void TryStartNoGCRegion_StartWhileInNoGCRegion_LargeObjectHeapSize()
{
RemoteInvokeOptions options = new RemoteInvokeOptions();
options.TimeOut = TimeoutMilliseconds;
RemoteInvoke(() =>
{
Assert.True(GC.TryStartNoGCRegion(1024, 1024));
Assert.Throws<InvalidOperationException>(() => GC.TryStartNoGCRegion(1024, 1024));
Assert.Throws<InvalidOperationException>(() => GC.EndNoGCRegion());
return SuccessExitCode;
}, options).Dispose();
}
[Fact]
[OuterLoop]
public static void TryStartNoGCRegion_StartWhileInNoGCRegion_BlockingCollectionAndLOH()
{
RemoteInvokeOptions options = new RemoteInvokeOptions();
options.TimeOut = TimeoutMilliseconds;
RemoteInvoke(() =>
{
Assert.True(GC.TryStartNoGCRegion(1024, 1024, true));
Assert.Throws<InvalidOperationException>(() => GC.TryStartNoGCRegion(1024, 1024, true));
Assert.Throws<InvalidOperationException>(() => GC.EndNoGCRegion());
return SuccessExitCode;
}, options).Dispose();
}
[Fact]
[OuterLoop]
public static void TryStartNoGCRegion_SettingLatencyMode_ThrowsInvalidOperationException()
{
RemoteInvokeOptions options = new RemoteInvokeOptions();
options.TimeOut = TimeoutMilliseconds;
RemoteInvoke(() =>
{
Assert.True(GC.TryStartNoGCRegion(1024, true));
Assert.Equal(GCSettings.LatencyMode, GCLatencyMode.NoGCRegion);
Assert.Throws<InvalidOperationException>(() => GCSettings.LatencyMode = GCLatencyMode.LowLatency);
GC.EndNoGCRegion();
return SuccessExitCode;
}, options).Dispose();
}
[Fact]
[OuterLoop]
public static void TryStartNoGCRegion_SOHSize()
{
RemoteInvokeOptions options = new RemoteInvokeOptions();
options.TimeOut = TimeoutMilliseconds;
RemoteInvoke(() =>
{
Assert.True(GC.TryStartNoGCRegion(1024));
Assert.Equal(GCSettings.LatencyMode, GCLatencyMode.NoGCRegion);
GC.EndNoGCRegion();
return SuccessExitCode;
}, options).Dispose();
}
[Fact]
[OuterLoop]
public static void TryStartNoGCRegion_SOHSize_BlockingCollection()
{
RemoteInvokeOptions options = new RemoteInvokeOptions();
options.TimeOut = TimeoutMilliseconds;
RemoteInvoke(() =>
{
Assert.True(GC.TryStartNoGCRegion(1024, true));
Assert.Equal(GCSettings.LatencyMode, GCLatencyMode.NoGCRegion);
GC.EndNoGCRegion();
return SuccessExitCode;
}, options).Dispose();
}
[Fact]
[OuterLoop]
public static void TryStartNoGCRegion_SOHSize_LOHSize()
{
RemoteInvokeOptions options = new RemoteInvokeOptions();
options.TimeOut = TimeoutMilliseconds;
RemoteInvoke(() =>
{
Assert.True(GC.TryStartNoGCRegion(1024, 1024));
Assert.Equal(GCSettings.LatencyMode, GCLatencyMode.NoGCRegion);
GC.EndNoGCRegion();
return SuccessExitCode;
}, options).Dispose();
}
[Fact]
[OuterLoop]
public static void TryStartNoGCRegion_SOHSize_LOHSize_BlockingCollection()
{
RemoteInvokeOptions options = new RemoteInvokeOptions();
options.TimeOut = TimeoutMilliseconds;
RemoteInvoke(() =>
{
Assert.True(GC.TryStartNoGCRegion(1024, 1024, true));
Assert.Equal(GCSettings.LatencyMode, GCLatencyMode.NoGCRegion);
GC.EndNoGCRegion();
return SuccessExitCode;
}, options).Dispose();
}
public static void TestWait(bool approach, int timeout)
{
GCNotificationStatus result = GCNotificationStatus.Failed;
Thread cancelProc = null;
// Since we need to test an infinite (or very large) wait but the API won't return, spawn off a thread which
// will cancel the wait after a few seconds
//
bool cancelTimeout = (timeout == -1) || (timeout > 10000);
GC.RegisterForFullGCNotification(20, 20);
try
{
if (cancelTimeout)
{
cancelProc = new Thread(new ThreadStart(CancelProc));
cancelProc.Start();
}
if (approach)
result = GC.WaitForFullGCApproach(timeout);
else
result = GC.WaitForFullGCComplete(timeout);
}
catch (Exception e)
{
Assert.True(false, $"({approach}, {timeout}) Error - Unexpected exception received: {e.ToString()}");
}
finally
{
if (cancelProc != null)
cancelProc.Join();
}
if (cancelTimeout)
{
Assert.True(result == GCNotificationStatus.Canceled, $"({approach}, {timeout}) Error - WaitForFullGCApproach result not Cancelled");
}
else
{
Assert.True(result == GCNotificationStatus.Timeout, $"({approach}, {timeout}) Error - WaitForFullGCApproach result not Timeout");
}
}
public static void CancelProc()
{
Thread.Sleep(500);
GC.CancelFullGCNotification();
}
}
}
| |
/*
Copyright (c) 2004-2009 Krzysztof Ostrowski. All rights reserved.
Redistribution and use in source and binary forms,
with or without modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
THIS SOFTWARE IS PROVIDED "AS IS" BY THE ABOVE COPYRIGHT HOLDER(S)
AND ALL OTHER CONTRIBUTORS AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE ABOVE COPYRIGHT HOLDER(S) OR ANY OTHER
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
*/
using System;
/// <summary>
/// This namespace contains all of QuickSilver code.
/// </summary>
namespace QS
{
/// <summary>
/// This enumeration holds identifiers of the serializable classes built into QuickSilver.
/// </summary>
public enum ClassID : ushort
{
/// <summary>
/// None of the classes should have this identifier; if encountered at runtime, it represents a bug or an uninitialized field.
/// </summary>
UnknownThing = 0,
/// <summary>
/// Represents an empty portion of data.
/// </summary>
Nothing = 1,
// Krzys's infrastructure components
AnyMessage = 1000,
BinaryMessage,
NetworkAddress,
ObjectAddress,
EmptyObject,
BaseSender_OurMessage,
CryptographicSender_OurMessage,
DirectIPMCSender_OurMessage,
//SimpleSender4_OurMessage,
//SimpleSender5_OurMessage,
RPCServerRequest,
RPCServerResponse,
Collections_Hashtable,
FBCASTSender_OurMessage,
FBCASTSender_AckMessage,
ReliableSender_OurMessage,
ReliableSender_AckMessage,
SimpleFlushingDevice,
VSSender_Message,
VSSender_Acknowledgement,
SimpleMulticastingSender_Message,
FlushingReport,
ReceiverReport,
ForwardingRequest_ForwardedMessage,
XmlMessage,
BlockOfData,
OutgoingVector,
AccumulatingBufferController_OutgoingBuffer,
SplittingBuffer,
VirtualCommunicationSubsystem_WrappedData,
GenericVSSender_MessageWrapper,
CMSWrapper_WrappedMessage,
Sequencer_Wrapper,
Sequencer_Wrapper_SeqNo,
Base2_XmlObject,
Base2_StringWrapper,
Multicasting2_SimpleMulticastingSender_Multicast,
Multicasting2_SimpleMulticastingSender_Acknowledgement,
VSMessage,
VSMessageID,
ViewController,
VS5_VC2_OutgoingRequest,
VS5_VC2_IncomingRequest,
GenericRCCDescriptor,
GenericVSMPPMID,
AddressedObject,
WrappedIO,
WrappedRPCCall,
NullObject,
AtomicScatterer_Wrapper,
AtomicScatterer_MessageID,
SimpleRS_Message,
SimpleRS_Ack,
AccumulatingController_MessageCollection,
Base3_RegionID,
Base3_GroupID,
Base3_Region,
Base3_Group,
Interoperability_Remoting_HeaderWrapper,
Interoperability_Remoting_RequestWrapper,
RPC3_SimpleCaller_Request,
RPC3_SimpleCaller_Response,
Base3_Message,
Base3_Result,
InstanceID,
FailureDetector_Beacon,
Membership2_Protocol_Notification,
RegionSig,
MembershipChangeRequest,
Senders3_ReliableSender_Message,
Senders3_ReliableSender_Ack,
Multicasting3_MessageID,
Multicasting3_MulticastMessage,
Aggregation_SimpleController_Message,
AggregationID,
Base3_Segments,
ChoppingSender_Chunk,
GroupID,
ViewID,
Aggregation3_ChannelID,
Aggregation3_Agent_Message,
Message,
CompressedObject,
Double,
Multicasting3_Minimum,
RegionMin,
Aggregation_ControllerMessage,
Aggregation4_AggregationController1_Notification,
Aggregation4_Agent_Message,
Aggregation4_AggregationController2_Notification,
Base3_Bytes,
Base3_SerializableObject,
Senders3_ReliableSender2_Message,
Senders3_ReliableSender2_Command,
Senders5_ReliableSink_Message,
Senders5_ReliableSink_Command,
FailureDetection_Centralized_Server_HeartbeatMessage,
Senders6_InstanceSender_Message,
Senders6_ReliableSender_Message,
FailureDetection_Change,
Multicasting5_Message,
Multicasting5_Acknowledgement,
Gossiping2_RegionalAgent_IntraregionalMessage,
Gossiping2_RegionalAgent_InterregionalMessage,
Gossiping2_RingMessageContainer,
Gossiping2_ChannelID,
Gossiping2_GossipAdapter_ChannelDic,
Gossiping2_RegionAggregated,
Components2_SeqContainer1,
Components2_SeqContainer2,
Multicasting5_MessageRV,
Multicasting5_CompressedAckSet,
Gossiping2_Shipment,
Gossiping2_ShipmentCollection,
Components2_MessageCollection,
Multicasting5_AcknowledgementRV,
Rings4_Token,
Rings4_TokenCollection,
Multicasting5_ForwardingRV,
Rings4_ObjectRV,
Rings4_ControlReq,
Ring4_Receiver_Control,
Ring4_NAKs,
Connections_Message,
Connections_MethodCall,
Base3_XmlObject,
Base3_BinaryObject,
Rings5_Request,
Rings5_Response,
Rings5_RingAgent_Token,
Rings6_ReceivingAgent1_InterPartitionToken,
Rings6_ReceivingAgent1_IntraPartitionToken,
Rings6_ReceivingAgent1_Receiver_InterPartitionToken,
Rings6_ReceivingAgent1_Receiver_IntraPartitionToken,
Rings6_ReceivingAgent_Agent_Receiver_Pull,
Rings6_ReceivingAgent_Agent_Receiver_Ack,
Rings6_ReceivingAgent_Agent_Receiver_Forward,
SequenceNo,
TMS_Data_DataSeries,
TMS_Data_XYSeries,
TMS_Data_MultiSeries,
Attribute,
AttributeSet,
TMS_Data_Data1D,
TMS_Data_Data2D,
TMS_Data_DataCo,
TMS_Data_Axis,
Senders11_InstanceMessage,
Receivers5_InstanceAck,
Int32x2,
Now,
Embeddings2_Types_Interface,
Embeddings2_Types_Method,
Embeddings2_Types_Parameter,
Embeddings2_Types_ReferencedType,
Embeddings2_ReplicationGroupType,
Embeddings2_MethodCallRequest,
Embeddings2_MethodCallResponse,
Membership3_Expressions_Group,
Membership3_Expressions_Intersection,
Membership3_Expressions_Union,
Membership3_Expressions_Minus,
Membership3_Requests_Open,
Membership3_Requests_Close,
Membership3_Requests_Crash,
Membership3_Requests_Resync,
Embeddings2_ReplicationGroupType2,
Membership3_Notifications_Notification,
Membership3_Responses_Opened,
Membership3_Responses_Succeeded,
Membership3_Responses_Exception,
Membership3_Notifications_CreateGroup,
Membership3_Notifications_CreateRegion,
Membership3_Notifications_CreateGroupView,
Membership3_Notifications_CreateRegionView,
Membership3_Notifications_CreateGroupViewRevision,
Membership3_Notifications_CreateRegionViewRevision,
Membership3_Notifications_CreateLocalView,
Membership3_Notifications_CreateGlobalView,
Membership3_Notifications_CreateIncomingView,
Membership3_Notifications_CreateSession,
Membership3_Notifications_CreateSessionView,
Membership3_Notifications_CreateClientView,
Membership3_Notifications_CreateMetaNode,
Membership3_Notifications_CreateMetaNodeRevision,
Infrastructure_Components_GVID,
Infrastructure2_Embeddings_ReplicatedObjects_MethodCall,
Infrastructure2_Embeddings_ReplicatedObjects_Response,
Fx_Services_Base_Message,
Fx_Services_Base_Response,
QS_TMS_Data_Series,
Rings6_ReceivingAgent_Agent_Receiver_PartitionAcknowledgement,
Batching_Unpacker_Request,
SimpleChoppingSender_Chunk,
Multicasting7_MessageRV2,
Rings6_ReceivingAgent_Agent_Receiver_Ack2,
Fx_Machine_Components_ReplicaPersistentState,
Fx_Machine_Components_ReplicaPersistentState_Operation,
Fx_Collections_Key,
Fx_Collections_Key_Operation,
Fx_Collections_Key_Value,
Fx_Collections_Key_Collection,
Fx_Machine_Base_MembershipView,
Fx_Base_ServiceID,
Fx_Machine_Base_MemberInfo,
Fx_Base_ID,
Fx_Base_Incarnation,
Fx_Base_Address,
Fx_Machine_Components_ReplicaPersistentState_Operation_SetReplicaName,
Fx_Machine_Components_ReplicaPersistentState_Operation_SetReplicaIncarnation,
Fx_Machine_Components_ReplicaPersistentState_Operation_SetMachineName,
Fx_Machine_Components_ReplicaPersistentState_Operation_SetMachineIncarnation,
Fx_Machine_Components_ReplicaPersistentState_Operation_SetMembershipView,
Fx_Machine_Components_ReplicaPersistentState_Operation_SetReplicaAddress,
Fx_Machine_Components_ReplicaPersistentState_Operation_ModifyDiscoveryAddresses,
Fx_Machine_Components_Hello,
Fx_Machine_Components_ReplicaPersistentState_Operation_SetDisseminationAddress,
Fx_Machine_Components_ServiceControllerOperation,
Fx_Machine_Components_Append,
Fx_Machine_Components_ReplicaPersistentState_Operation_AddSuspectedInView,
Fx_Machine_Components_Token,
Fx_Machine_Components_PeerInfo,
Fx_Machine_Components_ReplicaNonpersistentState,
Fx_Machine_Components_ReplicaPersistentState_Operation_AddServiceControllerOperations,
Fx_Machine_Base_Components_ServiceControllerState,
Fx_Machine_Base_Components_ServiceControllerPersistentState,
Fx_Machine_Base_Components_ServiceControllerNonpersistentState,
Fx_Machine_Applications_Test_Counter,
Fx_Machine_Applications_Test_IncrementCounter,
Fx_Machine_ServiceControl_ServiceClass,
Fx_Base_QualifiedID,
Fx_Backbone_Node_Open,
Fx_Backbone_Node_Close,
Fx_Backbone_Node_Sync,
Fx_Backbone_Node_Message,
Fx_Backbone_Node_Acknowledgement,
Fx_Backbone_Controller_ProviderUpdate,
Fx_Backbone_Controller_TopicUpdate,
Fx_Backbone_Controller_Update,
Fx_Backbone_Controller_Register,
Fx_Backbone_Scope_MembershipID,
Fx_Unmanaged_Msg,
Fx_Base_AgentID,
Fx_Agents_Components_Driver1_Token,
Fx_Agents_Components_Driver2_Token,
Fx_Base_AgentIncarnation,
Fx_Agents_Base_AggregationToken,
Fx_Agents_Base_DisseminationToken,
Fx_Base_SessionID,
Fx_Agents_Base_Plan_Info,
Fx_Protocols_Simple2PC_AggregationToken,
Fx_Protocols_Simple2PC_DisseminationToken,
Fx_Runtime_UIntSet,
Fx_Runtime_Version,
Fx_Runtime_Versioned,
Fx_Agents_Base_ParentInfo,
Fx_Runtime_UInt,
Fx_Protocols_Cleanup_AggregationToken,
Fx_Protocols_Cleanup_DisseminationToken,
Fx_Protocols_Protocol_AggregationToken,
Fx_Protocols_Protocol_DisseminationToken,
Fx_Protocols_CoordinatedPhases_AggregationToken,
Fx_Protocols_CoordinatedPhases_DisseminationToken,
Machine_Persisted,
Machine_Persisted_Operation,
Machine_Persisted_Operation_SetMachineID,
Machine_MemberInfo,
Machine_MembershipView,
Framework2_Message,
Fx_Protocols_Generated_AggregationToken,
Fx_Protocols_Generated_DisseminationToken,
Fx_Runtime_Bool,
Fx_Runtime_Void,
Fx_Object_ObjectId,
Fx_Live_InterfaceID,
UnicodeText,
Centralized_CC_Message,
Centralized_CC_Metadata,
Fx_Channel_Message_Coordinates,
Fx_Channel_Message_Color,
Fx_Channel_Message_Desktop_State,
Fx_Channel_Message_Desktop_Object,
Fx_Channel_Message_Desktop_Operation_Add,
Fx_Channel_Message_Desktop_Operation_Move,
Fx_Channel_Message_Folder_State,
Fx_Channel_Message_Folder_Object,
Fx_Channel_Message_Folder_Operation_Add,
Fx_Channel_Message_Folder_Operation_Remove,
Fx_Channel_Message_Folder_Operation_Rename,
Fx_Channel_Message_Video_Frame,
QsmControl,
QsmObject,
QsmMetadata,
ChannelObject,
UplinkObject,
Properties_Control,
Properties_Message,
Fx_Base_Unsigned_32,
Fx_Base_Unsigned_64,
Fx_Base_Unsigned_128,
MembershipChannel_Member_,
MembershipChannel_Membership_,
Token_,
MessageToken_,
IdToken_,
OrderToken_,
Array_,
TokenArray_,
MsgsForEpochToken,
ReliableMsgSetToken,
AggregateToken_,
KVToken_,
KVSetToken_,
DataFlowToken_,
Identifier,
MessageIdentifier,
Incarnation,
Name,
Address,
Index,
Round_,
MulticastClient_Checkpoint_,
MulticastClient_Message_,
PropertyVersion,
PropertyValue,
PropertyValues,
DelegationControl_,
PropertyControl,
PropertiesControl,
Experiment_Component_Worker,
Runtime_Result,
Runtime_Ready,
Experiment_Component_WordCount,
Experiment_Component_ReverseIndex,
Experiment_Component_ReplicatedDictionary,
Experiment_Component_WebCrawler,
Experiment_Component_StringMatch,
Experiment_Component_KMeans,
Experiment_Component_SplayTreeDictionary,
Experiment_Component_EmptyDictionary,
SwitchMessage_,
TransportMessage_,
TransportMessage_1,
Benchmark_01,
Benchmark_02,
Benchmark_03,
Benchmark_04,
Benchmark_05,
PriorityQueue_1,
PriorityQueue_2,
PriorityQueue_3,
Benchmark_06,
Benchmark_07,
Benchmark_08,
Benchmark_09,
Benchmark_10,
Benchmark_11,
Benchmark_12,
Benchmark_13,
Benchmark_14,
Benchmark_15,
Experiment_Component_Membership,
Experiment_Component_Serializer,
Fx_Experiment_Benchmark_9_Item,
WorkerMessage_,
// Krzys's unit tests and other apps
CMSTest001 = 2000,
CMSTest002,
Fx_App3_State,
Fx_App3_State_Operation,
// Common
// Qi's
STUNAddress = 3000,
BounceMessage,
PubSubData,
BootstrapMin = 3010,
BootstrapJoin,
BootstrapAlive,
BootstrapLeave,
BootstrapMember,
BootstrapMembership,
BootstrapMax = 3049,
EUID = 3050,
TransmitterMsg,
PatchInfo,
HeatbeatMember = 3099,
OmniMin = 3100,
OmniJoin,
OmniRedirect,
OmniAck,
OmniMaintain,
OmniMaintainAck,
OmniData,
OmniMax = 3149,
IpmcMin = 3150,
IpmcData,
IpmcGossip,
IpmcAcclaim,
IpmcMax = 3199,
DonetMin = 3200,
DonetMembership,
DonetBuffermap,
DonetRequest,
DonetData,
DonetMax = 3249,
GradientMin = 3300,
GradientData,
GradientReport,
//Gradient
GradientMax = 3399,
// Mahesh's
Mahesh1_AVeryNiceMessage = 4000,
Mahesh_CSGMSJoinMessage,
Mahesh_CSGMSLeaveMessage,
Mahesh_CSGMSAddUpdateMessage,
Mahesh_CSGMSRemoveUpdateMessage,
Mahesh_CSGMSHeartBeatMessage,
Mahesh_CSGMSHeartBeatResponseMessage,
Mahesh_CSGMSFailureNotificationMessage,
Mahesh_CSGMSWholeViewMessage,
Mahesh_CSGMSImmutableView,
Mahesh_CSGMSImmutableSubView,
// Stefan's
Stefan1_AVeryNiceMessage = 5000,
Stefan_QsInfoObjectLight,
// Matt's
Matt_TimedMessage = 6000,
// User applications
/// <summary>
/// The smallest unique class identifier that can be used by the user's application.
/// </summary>
UserMin = 10000,
/// <summary>
/// The largest unique class identifier that can be used by the user's application.
/// </summary>
UserMax = ushort.MaxValue
}
}
| |
#region File Description
//-----------------------------------------------------------------------------
// LevelUpScreen.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#endregion
#region Using Statements
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Content;
using RolePlayingGameData;
#endregion
namespace RolePlaying
{
/// <summary>
/// Displays all the players that have leveled up
/// </summary>
class LevelUpScreen : GameScreen
{
private int index;
private List<Player> leveledUpPlayers;
private List<Spell> spellList = new List<Spell>();
#region Graphics content
private Texture2D backTexture;
private Texture2D selectIconTexture;
private Texture2D portraitBackTexture;
private Texture2D headerTexture;
private Texture2D lineTexture;
private Texture2D scrollUpTexture;
private Texture2D scrollDownTexture;
private Texture2D fadeTexture;
private Color color;
private Color colorName = new Color(241, 173, 10);
private Color colorClass = new Color(207, 130, 42);
private Color colorText = new Color(76, 49, 8);
#endregion
#region Positions
private Vector2 backgroundPosition;
private Vector2 textPosition;
private Vector2 levelPosition;
private Vector2 iconPosition;
private Vector2 linePosition;
private Vector2 selectPosition;
private Vector2 selectIconPosition;
private Vector2 screenSize;
private Vector2 titlePosition;
private Vector2 scrollUpPosition;
private Vector2 scrollDownPosition;
private Vector2 spellUpgradePosition;
private Vector2 portraitPosition;
private Vector2 playerNamePosition;
private Vector2 playerLvlPosition;
private Vector2 playerClassPosition;
private Vector2 topLinePosition;
private Vector2 playerDamagePosition;
private Vector2 headerPosition;
private Vector2 backPosition;
private Rectangle fadeDest;
#endregion
#region Dialog Strings
private readonly string titleText = "Level Up";
private readonly string selectString = "Continue";
#endregion
#region Scrolling Text Navigation
private int startIndex;
private int endIndex;
private const int maxLines = 3;
private const int lineSpacing = 74;
#endregion
#region Initialization
/// <summary>
/// Constructs a new LevelUpScreen object.
/// </summary>
/// <param name="leveledUpPlayers"></param>
public LevelUpScreen(List<Player> leveledUpPlayers)
{
if ((leveledUpPlayers == null) || (leveledUpPlayers.Count <= 0))
{
throw new ArgumentNullException("leveledUpPlayers");
}
this.IsPopup = true;
this.leveledUpPlayers = leveledUpPlayers;
index = 0;
GetSpellList();
AudioManager.PushMusic("LevelUp");
this.Exiting += new EventHandler(LevelUpScreen_Exiting);
}
void LevelUpScreen_Exiting(object sender, EventArgs e)
{
AudioManager.PopMusic();
}
/// <summary>
/// Load the graphics content
/// </summary>
/// <param name="sprite">SpriteBatch</param>
/// <param name="screenWidth">Width of the screen</param>
/// <param name="screenHeight">Height of the screen</param>
public override void LoadContent()
{
ContentManager content = ScreenManager.Game.Content;
backTexture =
content.Load<Texture2D>(@"Textures\GameScreens\PopupScreen");
selectIconTexture =
content.Load<Texture2D>(@"Textures\Buttons\AButton");
portraitBackTexture =
content.Load<Texture2D>(@"Textures\GameScreens\PlayerSelected");
headerTexture =
content.Load<Texture2D>(@"Textures\GameScreens\Caption");
lineTexture =
content.Load<Texture2D>(@"Textures\GameScreens\SeparationLine");
scrollUpTexture =
content.Load<Texture2D>(@"Textures\GameScreens\ScrollUp");
scrollDownTexture =
content.Load<Texture2D>(@"Textures\GameScreens\ScrollDown");
fadeTexture =
content.Load<Texture2D>(@"Textures\GameScreens\FadeScreen");
Viewport viewport = ScreenManager.GraphicsDevice.Viewport;
backgroundPosition.X = (viewport.Width - backTexture.Width) / 2;
backgroundPosition.Y = (viewport.Height - backTexture.Height) / 2;
screenSize = new Vector2(viewport.Width, viewport.Height);
fadeDest = new Rectangle(0, 0, viewport.Width, viewport.Height);
titlePosition.X = (screenSize.X -
Fonts.HeaderFont.MeasureString(titleText).X) / 2;
titlePosition.Y = backgroundPosition.Y + lineSpacing;
selectIconPosition.X = screenSize.X / 2 + 260;
selectIconPosition.Y = backgroundPosition.Y + 530f;
selectPosition.X = selectIconPosition.X -
Fonts.ButtonNamesFont.MeasureString(selectString).X - 10f;
selectPosition.Y = selectIconPosition.Y;
portraitPosition = backgroundPosition + new Vector2(143f, 155f);
backPosition = backgroundPosition + new Vector2(140f, 135f);
playerNamePosition = backgroundPosition + new Vector2(230f, 160f);
playerClassPosition = backgroundPosition + new Vector2(230f, 185f);
playerLvlPosition = backgroundPosition + new Vector2(230f, 205f);
topLinePosition = backgroundPosition + new Vector2(380f, 160f);
textPosition = backgroundPosition + new Vector2(335f, 320f);
levelPosition = backgroundPosition + new Vector2(540f, 320f);
iconPosition = backgroundPosition + new Vector2(155f, 303f);
linePosition = backgroundPosition + new Vector2(142f, 285f);
scrollUpPosition = backgroundPosition + new Vector2(810f, 300f);
scrollDownPosition = backgroundPosition + new Vector2(810f, 480f);
playerDamagePosition = backgroundPosition + new Vector2(560f, 160f);
spellUpgradePosition = backgroundPosition + new Vector2(380f, 265f);
headerPosition = backgroundPosition + new Vector2(120f, 248f);
}
#endregion
#region Updating
/// <summary>
/// Handles user input.
/// </summary>
public override void HandleInput()
{
// exit without bothering to see the rest
if (InputManager.IsActionTriggered(InputManager.Action.Back))
{
ExitScreen();
}
// advance to the next player to have leveled up
else if (InputManager.IsActionTriggered(InputManager.Action.Ok))
{
if (leveledUpPlayers.Count <= 0)
{
// no players at all
ExitScreen();
return;
}
if (index < leveledUpPlayers.Count - 1)
{
// move to the next player
index++;
GetSpellList();
}
else
{
// no more players
ExitScreen();
return;
}
}
// Scroll up
else if (InputManager.IsActionTriggered(InputManager.Action.CursorUp))
{
if (startIndex > 0)
{
startIndex--;
endIndex--;
}
}
// Scroll down
else if (InputManager.IsActionTriggered(InputManager.Action.CursorDown))
{
if (startIndex < spellList.Count - maxLines)
{
endIndex++;
startIndex++;
}
}
}
/// <summary>
/// Get the spell list
/// </summary>
private void GetSpellList()
{
spellList.Clear();
if ((leveledUpPlayers.Count > 0) &&
(leveledUpPlayers[index].CharacterLevel <=
leveledUpPlayers[index].CharacterClass.LevelEntries.Count))
{
List<Spell> newSpells =
leveledUpPlayers[index].CharacterClass.LevelEntries[
leveledUpPlayers[index].CharacterLevel - 1].Spells;
if ((newSpells == null) || (newSpells.Count <= 0))
{
startIndex = 0;
endIndex = 0;
}
else
{
spellList.AddRange(leveledUpPlayers[index].Spells);
spellList.RemoveAll(delegate(Spell spell)
{
return !newSpells.Exists(delegate(Spell newSpell)
{
return spell.AssetName == newSpell.AssetName;
});
});
startIndex = 0;
endIndex = Math.Min(maxLines, spellList.Count);
}
}
else
{
startIndex = 0;
endIndex = 0;
}
}
#endregion
#region Drawing
/// <summary>
/// Draw the screen.
/// </summary>
public override void Draw(GameTime gameTime)
{
Vector2 currentTextPosition = textPosition;
Vector2 currentIconPosition = iconPosition;
Vector2 currentLinePosition = linePosition;
Vector2 currentLevelPosition = levelPosition;
SpriteBatch spriteBatch = ScreenManager.SpriteBatch;
spriteBatch.Begin();
// Draw the fading screen
spriteBatch.Draw(fadeTexture, fadeDest, Color.White);
// Draw the popup background
spriteBatch.Draw(backTexture, backgroundPosition, Color.White);
// Draw the title
spriteBatch.DrawString(Fonts.HeaderFont, titleText, titlePosition,
Fonts.TitleColor);
DrawPlayerStats();
// Draw the spell upgrades caption
spriteBatch.Draw(headerTexture, headerPosition, Color.White);
spriteBatch.DrawString(Fonts.PlayerNameFont, "Spell Upgrades",
spellUpgradePosition, colorClass);
// Draw the horizontal separating lines
for (int i = 0; i <= maxLines - 1; i++)
{
currentLinePosition.Y += lineSpacing;
spriteBatch.Draw(lineTexture, currentLinePosition, Color.White);
}
// Draw the spell upgrade details
for (int i = startIndex; i < endIndex; i++)
{
// Draw the spell icon
spriteBatch.Draw(spellList[i].IconTexture, currentIconPosition,
Color.White);
// Draw the spell name
spriteBatch.DrawString(Fonts.GearInfoFont, spellList[i].Name,
currentTextPosition, Fonts.CountColor);
// Draw the spell level
spriteBatch.DrawString(Fonts.GearInfoFont, "Spell Level " +
spellList[i].Level.ToString(),
currentLevelPosition, Fonts.CountColor);
// Increment to next line position
currentTextPosition.Y += lineSpacing;
currentLevelPosition.Y += lineSpacing;
currentIconPosition.Y += lineSpacing;
}
// Draw the scroll bars
spriteBatch.Draw(scrollUpTexture, scrollUpPosition, Color.White);
spriteBatch.Draw(scrollDownTexture, scrollDownPosition, Color.White);
// Draw the select button and its corresponding text
spriteBatch.DrawString(Fonts.ButtonNamesFont, selectString, selectPosition,
Color.White);
spriteBatch.Draw(selectIconTexture, selectIconPosition, Color.White);
spriteBatch.End();
}
/// <summary>
/// Draw the player stats here
/// </summary>
private void DrawPlayerStats()
{
Vector2 position = topLinePosition;
Vector2 posDamage = playerDamagePosition;
Player player = leveledUpPlayers[index];
int level = player.CharacterLevel;
CharacterLevelingStatistics levelingStatistics =
player.CharacterClass.LevelingStatistics;
SpriteBatch spriteBatch = ScreenManager.SpriteBatch;
// Draw the portrait
spriteBatch.Draw(portraitBackTexture, backPosition, Color.White);
spriteBatch.Draw(player.ActivePortraitTexture, portraitPosition,
Color.White);
// Print the character name
spriteBatch.DrawString(Fonts.PlayerNameFont,
player.Name, playerNamePosition, colorName);
// Draw the Class Name
spriteBatch.DrawString(Fonts.PlayerNameFont,
player.CharacterClass.Name, playerClassPosition, colorClass);
// Draw the character level
spriteBatch.DrawString(Fonts.PlayerNameFont, "LEVEL: " +
level.ToString(), playerLvlPosition, Color.Gray);
// Draw the character Health Points
SetColor(levelingStatistics.LevelsPerHealthPointsIncrease == 0 ? 0 :
(level % levelingStatistics.LevelsPerHealthPointsIncrease) *
levelingStatistics.HealthPointsIncrease);
spriteBatch.DrawString(Fonts.PlayerStatisticsFont, "HP: " +
player.CurrentStatistics.HealthPoints + "/" +
player.CharacterStatistics.HealthPoints,
position, color);
// Draw the character Mana Points
position.Y += Fonts.GearInfoFont.LineSpacing;
SetColor(levelingStatistics.LevelsPerMagicPointsIncrease == 0 ? 0 :
(level % levelingStatistics.LevelsPerMagicPointsIncrease) *
levelingStatistics.MagicPointsIncrease);
spriteBatch.DrawString(Fonts.PlayerStatisticsFont, "MP: " +
player.CurrentStatistics.MagicPoints + "/" +
player.CharacterStatistics.MagicPoints,
position, color);
// Draw the physical offense
SetColor(levelingStatistics.LevelsPerPhysicalOffenseIncrease == 0 ? 0 :
(level % levelingStatistics.LevelsPerPhysicalOffenseIncrease) *
levelingStatistics.PhysicalOffenseIncrease);
spriteBatch.DrawString(Fonts.PlayerStatisticsFont, "PO: " +
player.CurrentStatistics.PhysicalOffense, posDamage, color);
// Draw the physical defense
posDamage.Y += Fonts.PlayerStatisticsFont.LineSpacing;
SetColor(levelingStatistics.LevelsPerPhysicalDefenseIncrease == 0 ? 0 :
(level % levelingStatistics.LevelsPerPhysicalDefenseIncrease) *
levelingStatistics.PhysicalDefenseIncrease);
spriteBatch.DrawString(Fonts.PlayerStatisticsFont, "PD: " +
player.CurrentStatistics.PhysicalDefense, posDamage, color);
// Draw the Magic offense
posDamage.Y += Fonts.PlayerStatisticsFont.LineSpacing;
SetColor(levelingStatistics.LevelsPerMagicalOffenseIncrease == 0 ? 0 :
(level % levelingStatistics.LevelsPerMagicalOffenseIncrease) *
levelingStatistics.MagicalOffenseIncrease);
spriteBatch.DrawString(Fonts.PlayerStatisticsFont, "MO: " +
player.CurrentStatistics.MagicalOffense, posDamage, color);
// Draw the Magical defense
posDamage.Y += Fonts.PlayerStatisticsFont.LineSpacing;
SetColor(levelingStatistics.LevelsPerMagicalDefenseIncrease == 0 ? 0 :
(level % levelingStatistics.LevelsPerMagicalDefenseIncrease) *
levelingStatistics.MagicalDefenseIncrease);
spriteBatch.DrawString(Fonts.PlayerStatisticsFont, "MD: " +
player.CurrentStatistics.MagicalDefense, posDamage, color);
}
/// <summary>
/// Set the current color based on whether the value has changed.
/// </summary>
/// <param name="change">State of levelled up values</param>
public void SetColor(int value)
{
if (value > 0)
{
color = Color.Green;
}
else if (value < 0)
{
color = Color.Red;
}
else
{
color = colorText;
}
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Reflection;
using Xunit;
namespace System.Linq.Expressions.Tests
{
public static class LiftedModuloNullableTests
{
#region Test methods
[Fact]
public static void CheckLiftedModuloNullableByteTest()
{
byte?[] values = new byte?[] { null, 0, 1, byte.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyModuloNullableByte(values[i], values[j]);
}
}
}
[Fact]
public static void CheckLiftedModuloNullableCharTest()
{
char?[] values = new char?[] { null, '\0', '\b', 'A', '\uffff' };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyModuloNullableChar(values[i], values[j]);
}
}
}
[Fact]
public static void CheckLiftedModuloNullableDecimalTest()
{
decimal?[] values = new decimal?[] { null, decimal.Zero, decimal.One, decimal.MinusOne, decimal.MinValue, decimal.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyModuloNullableDecimal(values[i], values[j]);
}
}
}
[Fact]
public static void CheckLiftedModuloNullableDoubleTest()
{
double?[] values = new double?[] { null, 0, 1, -1, double.MinValue, double.MaxValue, double.Epsilon, double.NegativeInfinity, double.PositiveInfinity, double.NaN };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyModuloNullableDouble(values[i], values[j]);
}
}
}
[Fact]
public static void CheckLiftedModuloNullableFloatTest()
{
float?[] values = new float?[] { null, 0, 1, -1, float.MinValue, float.MaxValue, float.Epsilon, float.NegativeInfinity, float.PositiveInfinity, float.NaN };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyModuloNullableFloat(values[i], values[j]);
}
}
}
[Fact]
public static void CheckLiftedModuloNullableIntTest()
{
int?[] values = new int?[] { null, 0, 1, -1, int.MinValue, int.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyModuloNullableInt(values[i], values[j]);
}
}
}
[Fact]
public static void CheckLiftedModuloNullableLongTest()
{
long?[] values = new long?[] { null, 0, 1, -1, long.MinValue, long.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyModuloNullableLong(values[i], values[j]);
}
}
}
[Fact]
public static void CheckLiftedModuloNullableSByteTest()
{
sbyte?[] values = new sbyte?[] { null, 0, 1, -1, sbyte.MinValue, sbyte.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyModuloNullableSByte(values[i], values[j]);
}
}
}
[Fact]
public static void CheckLiftedModuloNullableShortTest()
{
short?[] values = new short?[] { null, 0, 1, -1, short.MinValue, short.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyModuloNullableShort(values[i], values[j]);
}
}
}
[Fact]
public static void CheckLiftedModuloNullableUIntTest()
{
uint?[] values = new uint?[] { null, 0, 1, uint.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyModuloNullableUInt(values[i], values[j]);
}
}
}
[Fact]
public static void CheckLiftedModuloNullableULongTest()
{
ulong?[] values = new ulong?[] { null, 0, 1, ulong.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyModuloNullableULong(values[i], values[j]);
}
}
}
[Fact]
public static void CheckLiftedModuloNullableUShortTest()
{
ushort?[] values = new ushort?[] { null, 0, 1, ushort.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyModuloNullableUShort(values[i], values[j]);
}
}
}
#endregion
#region Helpers
public static byte ModuloNullableByte(byte a, byte b)
{
return (byte)(a % b);
}
public static char ModuloNullableChar(char a, char b)
{
return (char)(a % b);
}
public static decimal ModuloNullableDecimal(decimal a, decimal b)
{
return (decimal)(a % b);
}
public static double ModuloNullableDouble(double a, double b)
{
return (double)(a % b);
}
public static float ModuloNullableFloat(float a, float b)
{
return (float)(a % b);
}
public static int ModuloNullableInt(int a, int b)
{
return (int)(a % b);
}
public static long ModuloNullableLong(long a, long b)
{
return (long)(a % b);
}
public static sbyte ModuloNullableSByte(sbyte a, sbyte b)
{
return (sbyte)(a % b);
}
public static short ModuloNullableShort(short a, short b)
{
return (short)(a % b);
}
public static uint ModuloNullableUInt(uint a, uint b)
{
return (uint)(a % b);
}
public static ulong ModuloNullableULong(ulong a, ulong b)
{
return (ulong)(a % b);
}
public static ushort ModuloNullableUShort(ushort a, ushort b)
{
return (ushort)(a % b);
}
#endregion
#region Test verifiers
private static void VerifyModuloNullableByte(byte? a, byte? b)
{
Expression<Func<byte?>> e =
Expression.Lambda<Func<byte?>>(
Expression.Modulo(
Expression.Constant(a, typeof(byte?)),
Expression.Constant(b, typeof(byte?)),
typeof(LiftedModuloNullableTests).GetTypeInfo().GetDeclaredMethod("ModuloNullableByte")));
Func<byte?> f = e.Compile();
byte? result = default(byte);
Exception fEx = null;
try
{
result = f();
}
catch (Exception ex)
{
fEx = ex;
}
byte? expected = default(byte);
Exception csEx = null;
try
{
expected = (byte?)(a % b);
}
catch (Exception ex)
{
csEx = ex;
}
if (fEx != null || csEx != null)
{
Assert.NotNull(fEx);
Assert.NotNull(csEx);
Assert.Equal(csEx.GetType(), fEx.GetType());
}
else
{
Assert.Equal(expected, result);
}
}
private static void VerifyModuloNullableChar(char? a, char? b)
{
Expression<Func<char?>> e =
Expression.Lambda<Func<char?>>(
Expression.Modulo(
Expression.Constant(a, typeof(char?)),
Expression.Constant(b, typeof(char?)),
typeof(LiftedModuloNullableTests).GetTypeInfo().GetDeclaredMethod("ModuloNullableChar")));
Func<char?> f = e.Compile();
char? result = default(char);
Exception fEx = null;
try
{
result = f();
}
catch (Exception ex)
{
fEx = ex;
}
char? expected = default(char);
Exception csEx = null;
try
{
expected = (char?)(a % b);
}
catch (Exception ex)
{
csEx = ex;
}
if (fEx != null || csEx != null)
{
Assert.NotNull(fEx);
Assert.NotNull(csEx);
Assert.Equal(csEx.GetType(), fEx.GetType());
}
else
{
Assert.Equal(expected, result);
}
}
private static void VerifyModuloNullableDecimal(decimal? a, decimal? b)
{
Expression<Func<decimal?>> e =
Expression.Lambda<Func<decimal?>>(
Expression.Modulo(
Expression.Constant(a, typeof(decimal?)),
Expression.Constant(b, typeof(decimal?)),
typeof(LiftedModuloNullableTests).GetTypeInfo().GetDeclaredMethod("ModuloNullableDecimal")));
Func<decimal?> f = e.Compile();
decimal? result = default(decimal);
Exception fEx = null;
try
{
result = f();
}
catch (Exception ex)
{
fEx = ex;
}
decimal? expected = default(decimal);
Exception csEx = null;
try
{
expected = (decimal?)(a % b);
}
catch (Exception ex)
{
csEx = ex;
}
if (fEx != null || csEx != null)
{
Assert.NotNull(fEx);
Assert.NotNull(csEx);
Assert.Equal(csEx.GetType(), fEx.GetType());
}
else
{
Assert.Equal(expected, result);
}
}
private static void VerifyModuloNullableDouble(double? a, double? b)
{
Expression<Func<double?>> e =
Expression.Lambda<Func<double?>>(
Expression.Modulo(
Expression.Constant(a, typeof(double?)),
Expression.Constant(b, typeof(double?)),
typeof(LiftedModuloNullableTests).GetTypeInfo().GetDeclaredMethod("ModuloNullableDouble")));
Func<double?> f = e.Compile();
double? result = default(double);
Exception fEx = null;
try
{
result = f();
}
catch (Exception ex)
{
fEx = ex;
}
double? expected = default(double);
Exception csEx = null;
try
{
expected = (double?)(a % b);
}
catch (Exception ex)
{
csEx = ex;
}
if (fEx != null || csEx != null)
{
Assert.NotNull(fEx);
Assert.NotNull(csEx);
Assert.Equal(csEx.GetType(), fEx.GetType());
}
else
{
Assert.Equal(expected, result);
}
}
private static void VerifyModuloNullableFloat(float? a, float? b)
{
Expression<Func<float?>> e =
Expression.Lambda<Func<float?>>(
Expression.Modulo(
Expression.Constant(a, typeof(float?)),
Expression.Constant(b, typeof(float?)),
typeof(LiftedModuloNullableTests).GetTypeInfo().GetDeclaredMethod("ModuloNullableFloat")));
Func<float?> f = e.Compile();
float? result = default(float);
Exception fEx = null;
try
{
result = f();
}
catch (Exception ex)
{
fEx = ex;
}
float? expected = default(float);
Exception csEx = null;
try
{
expected = (float?)(a % b);
}
catch (Exception ex)
{
csEx = ex;
}
if (fEx != null || csEx != null)
{
Assert.NotNull(fEx);
Assert.NotNull(csEx);
Assert.Equal(csEx.GetType(), fEx.GetType());
}
else
{
Assert.Equal(expected, result);
}
}
private static void VerifyModuloNullableInt(int? a, int? b)
{
Expression<Func<int?>> e =
Expression.Lambda<Func<int?>>(
Expression.Modulo(
Expression.Constant(a, typeof(int?)),
Expression.Constant(b, typeof(int?)),
typeof(LiftedModuloNullableTests).GetTypeInfo().GetDeclaredMethod("ModuloNullableInt")));
Func<int?> f = e.Compile();
int? result = default(int);
Exception fEx = null;
try
{
result = f();
}
catch (Exception ex)
{
fEx = ex;
}
int? expected = default(int);
Exception csEx = null;
try
{
expected = (int?)(a % b);
}
catch (Exception ex)
{
csEx = ex;
}
if (fEx != null || csEx != null)
{
Assert.NotNull(fEx);
Assert.NotNull(csEx);
Assert.Equal(csEx.GetType(), fEx.GetType());
}
else
{
Assert.Equal(expected, result);
}
}
private static void VerifyModuloNullableLong(long? a, long? b)
{
Expression<Func<long?>> e =
Expression.Lambda<Func<long?>>(
Expression.Modulo(
Expression.Constant(a, typeof(long?)),
Expression.Constant(b, typeof(long?)),
typeof(LiftedModuloNullableTests).GetTypeInfo().GetDeclaredMethod("ModuloNullableLong")));
Func<long?> f = e.Compile();
long? result = default(long);
Exception fEx = null;
try
{
result = f();
}
catch (Exception ex)
{
fEx = ex;
}
long? expected = default(long);
Exception csEx = null;
try
{
expected = (long?)(a % b);
}
catch (Exception ex)
{
csEx = ex;
}
if (fEx != null || csEx != null)
{
Assert.NotNull(fEx);
Assert.NotNull(csEx);
Assert.Equal(csEx.GetType(), fEx.GetType());
}
else
{
Assert.Equal(expected, result);
}
}
private static void VerifyModuloNullableSByte(sbyte? a, sbyte? b)
{
Expression<Func<sbyte?>> e =
Expression.Lambda<Func<sbyte?>>(
Expression.Modulo(
Expression.Constant(a, typeof(sbyte?)),
Expression.Constant(b, typeof(sbyte?)),
typeof(LiftedModuloNullableTests).GetTypeInfo().GetDeclaredMethod("ModuloNullableSByte")));
Func<sbyte?> f = e.Compile();
sbyte? result = default(sbyte);
Exception fEx = null;
try
{
result = f();
}
catch (Exception ex)
{
fEx = ex;
}
sbyte? expected = default(sbyte);
Exception csEx = null;
try
{
expected = (sbyte?)(a % b);
}
catch (Exception ex)
{
csEx = ex;
}
if (fEx != null || csEx != null)
{
Assert.NotNull(fEx);
Assert.NotNull(csEx);
Assert.Equal(csEx.GetType(), fEx.GetType());
}
else
{
Assert.Equal(expected, result);
}
}
private static void VerifyModuloNullableShort(short? a, short? b)
{
Expression<Func<short?>> e =
Expression.Lambda<Func<short?>>(
Expression.Modulo(
Expression.Constant(a, typeof(short?)),
Expression.Constant(b, typeof(short?)),
typeof(LiftedModuloNullableTests).GetTypeInfo().GetDeclaredMethod("ModuloNullableShort")));
Func<short?> f = e.Compile();
short? result = default(short);
Exception fEx = null;
try
{
result = f();
}
catch (Exception ex)
{
fEx = ex;
}
short? expected = default(short);
Exception csEx = null;
try
{
expected = (short?)(a % b);
}
catch (Exception ex)
{
csEx = ex;
}
if (fEx != null || csEx != null)
{
Assert.NotNull(fEx);
Assert.NotNull(csEx);
Assert.Equal(csEx.GetType(), fEx.GetType());
}
else
{
Assert.Equal(expected, result);
}
}
private static void VerifyModuloNullableUInt(uint? a, uint? b)
{
Expression<Func<uint?>> e =
Expression.Lambda<Func<uint?>>(
Expression.Modulo(
Expression.Constant(a, typeof(uint?)),
Expression.Constant(b, typeof(uint?)),
typeof(LiftedModuloNullableTests).GetTypeInfo().GetDeclaredMethod("ModuloNullableUInt")));
Func<uint?> f = e.Compile();
uint? result = default(uint);
Exception fEx = null;
try
{
result = f();
}
catch (Exception ex)
{
fEx = ex;
}
uint? expected = default(uint);
Exception csEx = null;
try
{
expected = (uint?)(a % b);
}
catch (Exception ex)
{
csEx = ex;
}
if (fEx != null || csEx != null)
{
Assert.NotNull(fEx);
Assert.NotNull(csEx);
Assert.Equal(csEx.GetType(), fEx.GetType());
}
else
{
Assert.Equal(expected, result);
}
}
private static void VerifyModuloNullableULong(ulong? a, ulong? b)
{
Expression<Func<ulong?>> e =
Expression.Lambda<Func<ulong?>>(
Expression.Modulo(
Expression.Constant(a, typeof(ulong?)),
Expression.Constant(b, typeof(ulong?)),
typeof(LiftedModuloNullableTests).GetTypeInfo().GetDeclaredMethod("ModuloNullableULong")));
Func<ulong?> f = e.Compile();
ulong? result = default(ulong);
Exception fEx = null;
try
{
result = f();
}
catch (Exception ex)
{
fEx = ex;
}
ulong? expected = default(ulong);
Exception csEx = null;
try
{
expected = (ulong?)(a % b);
}
catch (Exception ex)
{
csEx = ex;
}
if (fEx != null || csEx != null)
{
Assert.NotNull(fEx);
Assert.NotNull(csEx);
Assert.Equal(csEx.GetType(), fEx.GetType());
}
else
{
Assert.Equal(expected, result);
}
}
private static void VerifyModuloNullableUShort(ushort? a, ushort? b)
{
Expression<Func<ushort?>> e =
Expression.Lambda<Func<ushort?>>(
Expression.Modulo(
Expression.Constant(a, typeof(ushort?)),
Expression.Constant(b, typeof(ushort?)),
typeof(LiftedModuloNullableTests).GetTypeInfo().GetDeclaredMethod("ModuloNullableUShort")));
Func<ushort?> f = e.Compile();
ushort? result = default(ushort);
Exception fEx = null;
try
{
result = f();
}
catch (Exception ex)
{
fEx = ex;
}
ushort? expected = default(ushort);
Exception csEx = null;
try
{
expected = (ushort?)(a % b);
}
catch (Exception ex)
{
csEx = ex;
}
if (fEx != null || csEx != null)
{
Assert.NotNull(fEx);
Assert.NotNull(csEx);
Assert.Equal(csEx.GetType(), fEx.GetType());
}
else
{
Assert.Equal(expected, result);
}
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using Microsoft.Build.Collections;
using System;
using Microsoft.Build.Evaluation;
using System.Collections;
using System.Linq;
using Microsoft.Build.Execution;
using Microsoft.Build.Shared;
using Microsoft.Build.UnitTests.BackEnd;
using Shouldly;
using ObjectModel = System.Collections.ObjectModel;
using Xunit;
using Microsoft.Build.BackEnd;
namespace Microsoft.Build.UnitTests.OM.Collections
{
/// <summary>
/// Tests for several of the collections classes
/// </summary>
public class OMcollections_Tests
{
/// <summary>
/// End to end test of PropertyDictionary
/// </summary>
[Fact]
public void BasicPropertyDictionary()
{
PropertyDictionary<ProjectPropertyInstance> properties = new PropertyDictionary<ProjectPropertyInstance>();
ProjectPropertyInstance p1 = GetPropertyInstance("p1", "v1");
ProjectPropertyInstance p2 = GetPropertyInstance("p2", "v2");
ProjectPropertyInstance p3 = GetPropertyInstance("p1", "v1");
ProjectPropertyInstance p4 = GetPropertyInstance("p2", "v3");
properties.Set(p1);
properties.Set(p2);
properties.Set(p3);
properties.Set(p1);
properties.Set(p4);
Assert.Equal(2, properties.Count);
Assert.Equal("v1", properties["p1"].EvaluatedValue);
Assert.Equal("v3", properties["p2"].EvaluatedValue);
Assert.True(properties.Remove("p1"));
Assert.Null(properties["p1"]);
Assert.False(properties.Remove("x"));
properties.Clear();
Assert.Empty(properties);
}
/// <summary>
/// Test dictionary serialization with properties
/// </summary>
[Fact]
public void PropertyDictionarySerialization()
{
PropertyDictionary<ProjectPropertyInstance> properties = new PropertyDictionary<ProjectPropertyInstance>();
ProjectPropertyInstance p1 = GetPropertyInstance("p1", "v1");
ProjectPropertyInstance p2 = GetPropertyInstance("p2", "v2");
ProjectPropertyInstance p3 = GetPropertyInstance("p1", "v1");
ProjectPropertyInstance p4 = GetPropertyInstance("p2", "v3");
properties.Set(p1);
properties.Set(p2);
properties.Set(p3);
properties.Set(p1);
properties.Set(p4);
TranslationHelpers.GetWriteTranslator().TranslateDictionary<PropertyDictionary<ProjectPropertyInstance>, ProjectPropertyInstance>(ref properties, ProjectPropertyInstance.FactoryForDeserialization);
PropertyDictionary<ProjectPropertyInstance> deserializedProperties = null;
TranslationHelpers.GetReadTranslator().TranslateDictionary<PropertyDictionary<ProjectPropertyInstance>, ProjectPropertyInstance>(ref deserializedProperties, ProjectPropertyInstance.FactoryForDeserialization);
Assert.Equal(properties, deserializedProperties);
}
/// <summary>
/// Test dictionary serialization with no properties
/// </summary>
[Fact]
public void PropertyDictionarySerializationEmpty()
{
PropertyDictionary<ProjectPropertyInstance> properties = new PropertyDictionary<ProjectPropertyInstance>();
TranslationHelpers.GetWriteTranslator().TranslateDictionary<PropertyDictionary<ProjectPropertyInstance>, ProjectPropertyInstance>(ref properties, ProjectPropertyInstance.FactoryForDeserialization);
PropertyDictionary<ProjectPropertyInstance> deserializedProperties = null;
TranslationHelpers.GetReadTranslator().TranslateDictionary<PropertyDictionary<ProjectPropertyInstance>, ProjectPropertyInstance>(ref deserializedProperties, ProjectPropertyInstance.FactoryForDeserialization);
Assert.Equal(properties, deserializedProperties);
}
/// <summary>
/// End to end test of ItemDictionary
/// </summary>
[Fact]
public void BasicItemDictionary()
{
ItemDictionary<ProjectItemInstance> items = new ItemDictionary<ProjectItemInstance>();
// Clearing empty collection
items.Clear();
// Enumeration of empty collection
using (IEnumerator<ProjectItemInstance> enumerator = items.GetEnumerator())
{
enumerator.MoveNext().ShouldBeFalse();
Should.Throw<InvalidOperationException>(() =>
{
object o = ((IEnumerator) enumerator).Current;
});
enumerator.Current.ShouldBeNull();
}
List<ProjectItemInstance> list = new List<ProjectItemInstance>();
foreach (ProjectItemInstance item in items)
{
list.Add(item);
}
Assert.Empty(list);
// Cause an empty list for type 'x' to be added
ICollection<ProjectItemInstance> itemList = items["x"];
// Enumerate empty collection, with an empty list in it
foreach (ProjectItemInstance item in items)
{
list.Add(item);
}
Assert.Empty(list);
// Add and remove some items
ProjectItemInstance item1 = GetItemInstance("i", "i1");
Assert.False(items.Remove(item1));
Assert.Empty(items["j"]);
items.Add(item1);
Assert.Single(items["i"]);
Assert.Equal(item1, items["i"].First());
ProjectItemInstance item2 = GetItemInstance("i", "i2");
items.Add(item2);
ProjectItemInstance item3 = GetItemInstance("j", "j1");
items.Add(item3);
// Enumerate to verify contents
list = new List<ProjectItemInstance>();
foreach (ProjectItemInstance item in items)
{
list.Add(item);
}
list.Sort(ProjectItemInstanceComparer);
Assert.Equal(item1, list[0]);
Assert.Equal(item2, list[1]);
Assert.Equal(item3, list[2]);
// Direct operations on the enumerator
using (IEnumerator<ProjectItemInstance> enumerator = items.GetEnumerator())
{
Assert.Null(enumerator.Current);
Assert.True(enumerator.MoveNext());
Assert.NotNull(enumerator.Current);
enumerator.Reset();
Assert.Null(enumerator.Current);
Assert.True(enumerator.MoveNext());
Assert.NotNull(enumerator.Current);
}
}
/// <summary>
/// Null backing collection should be like empty collection
/// </summary>
[Fact]
public void ReadOnlyDictionaryNullBackingClone()
{
var dictionary = CreateCloneDictionary<string>(null, StringComparer.OrdinalIgnoreCase);
Assert.Empty(dictionary);
}
/// <summary>
/// Null backing collection should be like empty collection
/// </summary>
[Fact]
public void ReadOnlyDictionaryNullBackingWrapper()
{
var dictionary = new ObjectModel.ReadOnlyDictionary<string, string>(new Dictionary<string, string>(0));
Assert.Empty(dictionary);
}
/// <summary>
/// Cloning constructor should not see subsequent changes
/// </summary>
[Fact]
public void ReadOnlyDictionaryClone()
{
var dictionary = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
dictionary.Add("p", "v");
var readOnlyDictionary = CreateCloneDictionary(dictionary, StringComparer.OrdinalIgnoreCase);
dictionary.Add("p2", "v2");
Assert.Single(readOnlyDictionary);
Assert.True(readOnlyDictionary.ContainsKey("P"));
Assert.False(readOnlyDictionary.ContainsKey("p2"));
}
/// <summary>
/// Wrapping constructor should be "live"
/// </summary>
[Fact]
public void ReadOnlyDictionaryWrapper()
{
var dictionary = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
dictionary.Add("p", "v");
var readOnlyDictionary = new ObjectModel.ReadOnlyDictionary<string, string>(dictionary);
dictionary.Add("p2", "v2");
Assert.Equal(2, dictionary.Count);
Assert.True(dictionary.ContainsKey("p2"));
}
/// <summary>
/// Null backing collection should be an error
/// </summary>
[Fact]
public void ReadOnlyCollectionNullBacking()
{
Assert.Throws<InternalErrorException>(() =>
{
new ReadOnlyCollection<string>(null);
}
);
}
/// <summary>
/// Verify non generic enumeration does not recurse
/// ie., GetEnumerator() does not call itself
/// </summary>
[Fact]
public void ReadOnlyDictionaryNonGenericEnumeration()
{
var backing = new Dictionary<string, string>();
var collection = new ObjectModel.ReadOnlyDictionary<string, string>(backing);
IEnumerable enumerable = (IEnumerable)collection;
// Does not overflow stack:
foreach (object o in enumerable)
{
}
}
/// <summary>
/// Verify that the converting dictionary functions.
/// </summary>
[Fact]
public void ReadOnlyConvertingDictionary()
{
Dictionary<string, string> values = new Dictionary<string, string>();
values["one"] = "1";
values["two"] = "2";
values["three"] = "3";
Dictionary<string, int> convertedValues = new Dictionary<string, int>();
convertedValues["one"] = 1;
convertedValues["two"] = 2;
convertedValues["three"] = 3;
ReadOnlyConvertingDictionary<string, string, int> convertingCollection = new ReadOnlyConvertingDictionary<string, string, int>(values, delegate (string x) { return Convert.ToInt32(x); });
Assert.Equal(3, convertingCollection.Count);
Assert.True(convertingCollection.IsReadOnly);
foreach (KeyValuePair<string, int> value in convertingCollection)
{
Assert.Equal(convertedValues[value.Key], value.Value);
}
}
/// <summary>
/// Verify non generic enumeration does not recurse
/// ie., GetEnumerator() does not call itself
/// </summary>
[Fact]
public void ReadOnlyCollectionNonGenericEnumeration()
{
var backing = new List<string>();
var collection = new ReadOnlyCollection<string>(backing);
IEnumerable enumerable = (IEnumerable)collection;
// Does not overflow stack:
foreach (object o in enumerable)
{
}
}
/// <summary>
/// Helper to make a ProjectPropertyInstance.
/// </summary>
private static ProjectPropertyInstance GetPropertyInstance(string name, string value)
{
Project project = new Project();
ProjectInstance projectInstance = project.CreateProjectInstance();
ProjectPropertyInstance property = projectInstance.SetProperty(name, value);
return property;
}
/// <summary>
/// Helper to make a ProjectItemInstance.
/// </summary>
private static ProjectItemInstance GetItemInstance(string itemType, string evaluatedInclude)
{
Project project = new Project();
ProjectInstance projectInstance = project.CreateProjectInstance();
ProjectItemInstance item = projectInstance.AddItem(itemType, evaluatedInclude);
return item;
}
/// <summary>
/// Creates a copy of a dictionary and returns a read-only dictionary around the results.
/// </summary>
/// <typeparam name="TValue">The value stored in the dictionary</typeparam>
/// <param name="dictionary">Dictionary to clone.</param>
private static ObjectModel.ReadOnlyDictionary<string, TValue> CreateCloneDictionary<TValue>(IDictionary<string, TValue> dictionary, StringComparer strComparer)
{
Dictionary<string, TValue> clone;
if (dictionary == null)
{
clone = new Dictionary<string, TValue>(0);
}
else
{
clone = new Dictionary<string, TValue>(dictionary, strComparer);
}
return new ObjectModel.ReadOnlyDictionary<string, TValue>(clone);
}
/// <summary>
/// Simple comparer for ProjectItemInstances. Ought to compare metadata etc.
/// </summary>
private int ProjectItemInstanceComparer(ProjectItemInstance one, ProjectItemInstance two)
{
return String.Compare(one.EvaluatedInclude, two.EvaluatedInclude);
}
}
}
| |
/////////////////////////////////////////////////////////////////////////////////
// Paint.NET //
// Copyright (C) dotPDN LLC, Rick Brewster, Tom Jackson, and contributors. //
// Portions Copyright (C) Microsoft Corporation. All Rights Reserved. //
// See license-pdn.txt for full licensing and attribution details. //
/////////////////////////////////////////////////////////////////////////////////
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Cairo;
using Rectangle = Gdk.Rectangle;
namespace Pinta.Core
{
public abstract class GradientRenderer
{
private BinaryPixelOp normalBlendOp;
private ColorBgra startColor;
private ColorBgra endColor;
private PointD startPoint;
private PointD endPoint;
private bool alphaBlending;
private bool alphaOnly;
private bool lerpCacheIsValid = false;
private byte[] lerpAlphas;
private ColorBgra[] lerpColors;
public ColorBgra StartColor {
get { return this.startColor; }
set {
if (this.startColor != value) {
this.startColor = value;
this.lerpCacheIsValid = false;
}
}
}
public ColorBgra EndColor {
get { return this.endColor; }
set {
if (this.endColor != value) {
this.endColor = value;
this.lerpCacheIsValid = false;
}
}
}
public PointD StartPoint {
get { return this.startPoint; }
set { this.startPoint = value; }
}
public PointD EndPoint {
get { return this.endPoint; }
set { this.endPoint = value; }
}
public bool AlphaBlending {
get { return this.alphaBlending; }
set { this.alphaBlending = value; }
}
public bool AlphaOnly {
get { return this.alphaOnly; }
set { this.alphaOnly = value; }
}
public virtual void BeforeRender ()
{
if (!this.lerpCacheIsValid) {
byte startAlpha;
byte endAlpha;
if (this.alphaOnly) {
ComputeAlphaOnlyValuesFromColors (this.startColor, this.endColor, out startAlpha, out endAlpha);
} else {
startAlpha = this.startColor.A;
endAlpha = this.endColor.A;
}
this.lerpAlphas = new byte[256];
this.lerpColors = new ColorBgra[256];
for (int i = 0; i < 256; ++i) {
byte a = (byte)i;
this.lerpColors[a] = ColorBgra.Blend (this.startColor, this.endColor, a);
this.lerpAlphas[a] = (byte)(startAlpha + ((endAlpha - startAlpha) * a) / 255);
}
this.lerpCacheIsValid = true;
}
}
public abstract byte ComputeByteLerp(int x, int y);
public virtual void AfterRender ()
{
}
private static void ComputeAlphaOnlyValuesFromColors (ColorBgra startColor, ColorBgra endColor, out byte startAlpha, out byte endAlpha)
{
startAlpha = startColor.A;
endAlpha = (byte)(255 - endColor.A);
}
unsafe public void Render (ImageSurface surface, Gdk.Rectangle[] rois)
{
byte startAlpha;
byte endAlpha;
if (this.alphaOnly) {
ComputeAlphaOnlyValuesFromColors (this.startColor, this.endColor, out startAlpha, out endAlpha);
} else {
startAlpha = this.startColor.A;
endAlpha = this.endColor.A;
}
surface.Flush ();
ColorBgra* src_data_ptr = (ColorBgra*)surface.DataPtr;
int src_width = surface.Width;
for (int ri = 0; ri < rois.Length; ++ri) {
Gdk.Rectangle rect = rois[ri];
if (this.startPoint.X == this.endPoint.X && this.startPoint.Y == this.endPoint.Y) {
// Start and End point are the same ... fill with solid color.
for (int y = rect.Top; y <= rect.GetBottom (); ++y) {
ColorBgra* pixelPtr = surface.GetPointAddress(rect.Left, y);
for (int x = rect.Left; x <= rect.GetRight (); ++x) {
ColorBgra result;
if (this.alphaOnly && this.alphaBlending) {
byte resultAlpha = (byte)Utility.FastDivideShortByByte ((ushort)(pixelPtr->A * endAlpha), 255);
result = *pixelPtr;
result.A = resultAlpha;
} else if (this.alphaOnly && !this.alphaBlending) {
result = *pixelPtr;
result.A = endAlpha;
} else if (!this.alphaOnly && this.alphaBlending) {
result = this.normalBlendOp.Apply (*pixelPtr, this.endColor);
//if (!this.alphaOnly && !this.alphaBlending)
} else {
result = this.endColor;
}
*pixelPtr = result;
++pixelPtr;
}
}
} else {
var mainrect = rect;
Parallel.ForEach(Enumerable.Range (rect.Top, rect.Height),
(y) => ProcessGradientLine(startAlpha, endAlpha, y, mainrect, surface, src_data_ptr, src_width));
}
}
surface.MarkDirty ();
AfterRender ();
}
private unsafe bool ProcessGradientLine (byte startAlpha, byte endAlpha, int y, Rectangle rect, ImageSurface surface, ColorBgra* src_data_ptr, int src_width)
{
var pixelPtr = surface.GetPointAddressUnchecked(src_data_ptr, src_width, rect.Left, y);
var right = rect.GetRight ();
if (alphaOnly && alphaBlending)
{
for (var x = rect.Left; x <= right; ++x)
{
var lerpByte = ComputeByteLerp(x, y);
var lerpAlpha = lerpAlphas[lerpByte];
var resultAlpha = Utility.FastScaleByteByByte(pixelPtr->A, lerpAlpha);
pixelPtr->A = resultAlpha;
++pixelPtr;
}
}
else if (alphaOnly && !alphaBlending)
{
for (var x = rect.Left; x <= right; ++x)
{
var lerpByte = ComputeByteLerp(x, y);
var lerpAlpha = lerpAlphas[lerpByte];
pixelPtr->A = lerpAlpha;
++pixelPtr;
}
}
else if (!alphaOnly && (alphaBlending && (startAlpha != 255 || endAlpha != 255)))
{
// If we're doing all color channels, and we're doing alpha blending, and if alpha blending is necessary
for (var x = rect.Left; x <= right; ++x)
{
var lerpByte = ComputeByteLerp(x, y);
var lerpColor = lerpColors[lerpByte];
var result = normalBlendOp.Apply(*pixelPtr, lerpColor);
*pixelPtr = result;
++pixelPtr;
}
//if (!this.alphaOnly && !this.alphaBlending) // or sC.A == 255 && eC.A == 255
}
else
{
for (var x = rect.Left; x <= right; ++x)
{
var lerpByte = ComputeByteLerp(x, y);
var lerpColor = lerpColors[lerpByte];
*pixelPtr = lerpColor;
++pixelPtr;
}
}
return true;
}
protected internal GradientRenderer (bool alphaOnly, BinaryPixelOp normalBlendOp)
{
this.normalBlendOp = normalBlendOp;
this.alphaOnly = alphaOnly;
}
}
}
| |
//---------------------------------------------------------------------
// File: StreamHelper.cs
//
// Summary:
//
// Author: Kevin B. Smith
//
//---------------------------------------------------------------------
// Copyright (c) 2004-2017, Kevin B. Smith. All rights reserved.
//
// THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
// KIND, WHETHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR
// PURPOSE.
//---------------------------------------------------------------------
using System;
using System.Xml;
using System.Text;
using System.IO;
using BizUnit.Core.TestBuilder;
namespace BizUnit.TestSteps.Common
{
/// <summary>
/// Helper class for stream opperations
/// </summary>
public class StreamHelper
{
/// <summary>
/// Performs a binary comparison between two streams
/// </summary>
/// <param name="s1">The 1st stream to compare aginst the 2nd</param>
/// <param name="s2">The 2nd stream to compare aginst the 1st</param>
static public void CompareStreams(Stream s1, Stream s2)
{
var buff1 = new byte[4096];
var buff2 = new byte[4096];
int read1;
do
{
read1 = s1.Read(buff1, 0, 4096);
int read2 = s2.Read(buff2, 0, 4096);
if ( read1 != read2 )
{
throw new ApplicationException( String.Format( "Streams do not contain identical data!" ) );
}
if ( 0 == read1 )
{
break;
}
for ( int c = 0; c < read1; c++ )
{
if ( buff1[c] != buff2[c] )
{
throw new ApplicationException( String.Format( "Streams do not contain identical data!" ) );
}
}
} while( read1 > 0 );
}
/// <summary>
/// Helper method to load a disc FILE into a MemoryStream
/// </summary>
/// <param name="filePath">The path to the FILE containing the data</param>
/// <param name="timeout">The timeout afterwhich if the FILE is not found the method will fail</param>
/// <returns>MemoryStream containing the data in the FILE</returns>
public static MemoryStream LoadFileToStream(string filePath, double timeout)
{
MemoryStream ms = null;
bool loaded = false;
DateTime now = DateTime.Now;
do
{
try
{
ms = LoadFileToStream(filePath);
loaded = true;
break;
}
catch(Exception)
{
if ( DateTime.Now < now.AddMilliseconds(timeout) )
{
System.Threading.Thread.Sleep(500);
}
}
} while ( DateTime.Now < now.AddMilliseconds(timeout) );
if ( !loaded )
{
throw new ApplicationException( string.Format( "The file: {0} was not found within the timeout period!", filePath ) );
}
return ms;
}
/// <summary>
/// Helper method to load a disc FILE into a MemoryStream
/// </summary>
/// <param name="filePath">The path to the FILE containing the data</param>
/// <returns>MemoryStream containing the data in the FILE</returns>
public static MemoryStream LoadFileToStream(string filePath)
{
FileStream fs = null;
MemoryStream s;
try
{
// Get the match data...
fs = System.IO.File.OpenRead(filePath);
s = new MemoryStream();
var buff = new byte[1024];
int read = fs.Read(buff, 0, 1024);
while ( 0 < read )
{
s.Write(buff, 0, read);
read = fs.Read(buff, 0, 1024);
}
s.Flush();
s.Seek(0, SeekOrigin.Begin);
}
finally
{
if ( null != fs )
{
fs.Close();
}
}
return s;
}
/// <summary>
/// Helper method to write the data in a stream to the console
/// </summary>
/// <param name="description">The description text that will be written before the stream data</param>
/// <param name="ms">Stream containing the data to write</param>
/// <param name="context">The BizUnit context object which holds state and is passed between test steps</param>
public static void WriteStreamToConsole(
string description,
MemoryStream ms,
Context context)
{
ms.Seek(0, SeekOrigin.Begin);
var sr = new StreamReader(ms);
context.LogData( description, sr.ReadToEnd() );
ms.Seek(0, SeekOrigin.Begin);
}
/// <summary>
/// Helper method to load a forward only stream into a seekable MemoryStream
/// </summary>
/// <param name="s">The forward only stream to read the data from</param>
/// <returns>MemoryStream containg the data as read from s</returns>
public static MemoryStream LoadMemoryStream(Stream s)
{
var ms = new MemoryStream();
var buff = new byte[1024];
int read = s.Read(buff, 0, 1024);
while ( 0 < read )
{
ms.Write(buff, 0, read);
read = s.Read(buff, 0, 1024);
}
ms.Flush();
ms.Seek(0, SeekOrigin.Begin);
return ms;
}
/// <summary>
/// Helper method to load a string into a MemoryStream
/// </summary>
/// <param name="s">The string containing the data that will be loaded into the stream</param>
/// <returns>MemoryStream containg the data read from the string</returns>
public static MemoryStream LoadMemoryStream(string s)
{
Encoding utf8 = Encoding.UTF8;
byte[] bytes = utf8.GetBytes(s);
var ms = new MemoryStream(bytes);
ms.Flush();
ms.Seek(0, SeekOrigin.Begin);
return ms;
}
/// <summary>
/// Helper method to compare two Xml documents from streams
/// </summary>
/// <param name="s1">Stream containing the 1st Xml document</param>
/// <param name="s2">Stream containing the 2nd Xml document</param>
/// <param name="context">The BizUnit context object which holds state and is passed between test steps</param>
public static void CompareXmlDocs(Stream s1, Stream s2, Context context)
{
var doc = new XmlDocument();
doc.Load(new XmlTextReader(s1));
XmlElement root = doc.DocumentElement;
string data1 = root.OuterXml;
doc = new XmlDocument();
doc.Load(new XmlTextReader(s2));
root = doc.DocumentElement;
string data2 = root.OuterXml;
context.LogInfo("About to compare the following Xml documents:\r\nDocument1: {0},\r\nDocument2: {1}", data1, data2);
CompareStreams( LoadMemoryStream(data1), LoadMemoryStream(data2) );
}
/// <summary>
/// Helper method to encode a stream
/// </summary>
/// <param name="rawData">Stream containing data to be encoded</param>
/// <param name="encoding">The encoding to be used for the data</param>
/// <returns>Encoded MemoryStream</returns>
public static Stream EncodeStream(Stream rawData, Encoding encoding)
{
rawData.Seek(0, SeekOrigin.Begin);
var sr = new StreamReader(rawData);
string data = sr.ReadToEnd();
Encoding e = encoding;
byte[] bytes = e.GetBytes(data);
return new MemoryStream(bytes);
}
}
}
| |
//#define PACKETDUMP
//#define PROMISEDUMP
using System;
using System.Collections.Generic;
using System.Text;
namespace ICSimulator
{
/*
A node can contain the following:
* CPU and CoherentCache (work as a unit)
* coherence directory
* shared cache (only allowed if dir present, and home node must match)
* memory controller
The cache hierarchy is modeled as two levels, the coherent level
(L1 and, in private-cache systems, L2) and the (optional) shared
cache, on top of a collection of memory controllers. Coherence
happens between coherent-level caches, and misses in the
coherent caches go either to the shared cache (if configured) or
directly to memory. The system is thus flexible enough to
support both private and shared cache designs.
*/
public class Node
{
Coord m_coord;
NodeMapping m_mapping;
public Coord coord { get { return m_coord; } }
public NodeMapping mapping { get { return m_mapping; } }
public Router router { get { return m_router; } }
public MemCtlr mem { get { return m_mem; } }
public CPU cpu { get { return m_cpu; } }
private CPU m_cpu;
private MemCtlr m_mem;
private Router m_router;
private IPrioPktPool m_inj_pool;
private Queue<Flit> m_injQueue_flit, m_injQueue_evict;
public Queue<Packet> m_local;
public int RequestQueueLen { get { return m_inj_pool.FlitCount + m_injQueue_flit.Count; } }
RxBufNaive m_rxbuf_naive;
public Node(NodeMapping mapping, Coord c)
{
m_coord = c;
m_mapping = mapping;
if (mapping.hasCPU(c.ID))
{
m_cpu = new CPU(this);
}
if (mapping.hasMem(c.ID))
{
m_mem = new MemCtlr(this);
}
m_inj_pool = Simulator.controller.newPrioPktPool(m_coord.ID);
Simulator.controller.setInjPool(m_coord.ID, m_inj_pool);
m_injQueue_flit = new Queue<Flit>();
m_injQueue_evict = new Queue<Flit>();
m_local = new Queue<Packet>();
m_rxbuf_naive = new RxBufNaive(this,
delegate(Flit f) { m_injQueue_evict.Enqueue(f); },
delegate(Packet p) { receivePacket(p); });
}
public void setRouter(Router r)
{
m_router = r;
}
void synthGen(double rate)
{
if (Simulator.rand.NextDouble() < rate)
{
if (m_inj_pool.Count > Config.synthQueueLimit)
Simulator.stats.synth_queue_limit_drop.Add();
else
{
int dest = m_coord.ID;
Coord c = new Coord(dest);
switch (Config.synthPattern) {
case SynthTrafficPattern.UR:
dest = Simulator.rand.Next(Config.N);
c = new Coord(dest);
break;
case SynthTrafficPattern.BC:
dest = ~dest & (Config.N - 1);
c = new Coord(dest);
break;
case SynthTrafficPattern.TR:
c = new Coord(m_coord.y, m_coord.x);
break;
}
SynthPacket p = new SynthPacket(m_coord, c);
queuePacket(p);
}
}
}
public void doStep()
{
if (Config.synthGen)
{
synthGen(Config.synthRate);
}
while (m_local.Count > 0 &&
m_local.Peek().creationTime < Simulator.CurrentRound)
{
receivePacket(m_local.Dequeue());
}
if (m_cpu != null)
m_cpu.doStep();
if (m_mem != null)
m_mem.doStep();
Packet p = m_inj_pool.next();
if (p != null)
{
foreach (Flit f in p.flits)
m_injQueue_flit.Enqueue(f);
}
if (m_injQueue_evict.Count > 0 && m_router.canInjectFlit(m_injQueue_evict.Peek()))
{
Flit f = m_injQueue_evict.Dequeue();
m_router.InjectFlit(f);
}
else if (m_injQueue_flit.Count > 0 && m_router.canInjectFlit(m_injQueue_flit.Peek()))
{
Flit f = m_injQueue_flit.Dequeue();
#if PACKETDUMP
if (f.flitNr == 0)
if (m_coord.ID == 0)
Console.WriteLine("start to inject packet {0} at node {1} (cyc {2})",
f.packet, coord, Simulator.CurrentRound);
#endif
m_router.InjectFlit(f);
}
}
public virtual void receiveFlit(Flit f)
{
if (Config.naive_rx_buf)
m_rxbuf_naive.acceptFlit(f);
else
receiveFlit_noBuf(f);
}
void receiveFlit_noBuf(Flit f)
{
f.packet.nrOfArrivedFlits++;
if (f.packet.nrOfArrivedFlits == f.packet.nrOfFlits)
receivePacket(f.packet);
}
public void evictFlit(Flit f)
{
m_injQueue_evict.Enqueue(f);
}
public void receivePacket(Packet p)
{
#if PACKETDUMP
if (m_coord.ID == 0)
Console.WriteLine("receive packet {0} at node {1} (cyc {2}) (age {3})",
p, coord, Simulator.CurrentRound, Simulator.CurrentRound - p.creationTime);
#endif
if (p is RetxPacket)
{
p.retx_count++;
p.flow_open = false;
p.flow_close = false;
queuePacket( ((RetxPacket)p).pkt );
}
else if (p is CachePacket)
{
CachePacket cp = p as CachePacket;
m_cpu.receivePacket(cp);
}
}
public void queuePacket(Packet p)
{
#if PACKETDUMP
if (m_coord.ID == 0)
Console.WriteLine("queuePacket {0} at node {1} (cyc {2}) (queue len {3})",
p, coord, Simulator.CurrentRound, RequestQueueLen);
#endif
//if (Config.synthGen && !(p is SynthPacket))
// throw new Exception("non-synthetic packet generated in synthetic run!");
if (p.dest.ID == m_coord.ID) // local traffic: do not go to net (will confuse router)
{
m_local.Enqueue(p);
return;
}
if (Config.idealnet) // ideal network: deliver immediately to dest
Simulator.network.nodes[p.dest.ID].m_local.Enqueue(p);
else // otherwise: enqueue on injection queue
{
m_inj_pool.addPacket(p);
}
}
public void sendRetx(Packet p)
{
p.nrOfArrivedFlits = 0;
RetxPacket pkt = new RetxPacket(p.dest, p.src, p);
queuePacket(pkt);
}
public bool Finished
{ get { return (m_cpu != null) ? m_cpu.Finished : false; } }
public bool Livelocked
{ get { return (m_cpu != null) ? m_cpu.Livelocked : false; } }
public void visitFlits(Flit.Visitor fv)
{
// visit in-buffer (inj and reassembly) flits too?
}
}
}
| |
using System;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Text;
using System.Text.RegularExpressions;
using System.IO;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
namespace BePoE
{
public enum ColorPlace : int
{
ForeUnsel = 0,
BackUnsel = 1,
ForeSel = 2,
BackSel = 3,
}
public enum ColorEnviro : int
{
Untranslated = 0,
Translated = 1,
Removed = 2,
}
[Serializable]
public struct ColorEnviroPlace
{
public ColorEnviro Enviro;
public ColorPlace Place;
public ColorEnviroPlace(ColorEnviro enviro, ColorPlace place)
{
this.Enviro = enviro;
this.Place = place;
}
public static ColorEnviroPlace Get(ColorEnviro enviro, ColorPlace place)
{
return new ColorEnviroPlace(enviro, place);
}
}
public class Vars : ApplicationSettingsBase
{
private static bool? _osIsCaseSensitive = null;
public static bool OsIsCaseSensitive
{
get
{
if (!Vars._osIsCaseSensitive.HasValue)
{
string tempFolder = Path.GetTempPath();
string testFileNameLC, testFileNameUC;
for (int i = 0; ; i++)
{
string lc = string.Format("tst{0}", i);
testFileNameLC = Path.Combine(tempFolder, lc);
testFileNameUC = Path.Combine(tempFolder, lc.ToUpper());
if (!(File.Exists(testFileNameLC) || File.Exists(testFileNameUC) || Directory.Exists(testFileNameLC) || Directory.Exists(testFileNameUC)))
break;
}
bool created = false;
try
{
using (FileStream fs = new FileStream(testFileNameLC, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.Read))
{
created = true;
fs.WriteByte(32);
fs.Flush();
}
Vars._osIsCaseSensitive = !File.Exists(testFileNameUC);
}
finally
{
if (created)
{
try
{ File.Delete(testFileNameLC); }
catch
{ }
}
}
}
return Vars._osIsCaseSensitive.Value;
}
}
public static bool IsPosix
{
get
{
const int PLATFORMID_MACOSX = 6;
switch (Environment.OSVersion.Platform)
{
case (PlatformID)PLATFORMID_MACOSX:
case PlatformID.Unix:
return true;
default:
switch ((int)Environment.OSVersion.Platform)
{
case 128:
return true;
default:
return false;
}
}
}
}
[UserScopedSetting]
public string[] LastFiles
{
get
{
string[] ris = this["LastFiles"] as string[];
return (ris == null) ? new string[] { } : ris;
}
set
{
this["LastFiles"] = (value == null) ? new string[] { } : value;
}
}
public List<string> RemoveLastFile(string fileName, bool save)
{
List<string> list = new List<string>(this.LastFiles);
for (int i = list.Count - 1; i >= 0; i--)
{
if (fileName.Equals(list[i], Vars.OsIsCaseSensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase))
list.RemoveAt(i);
}
if (save)
{
this.LastFiles = list.ToArray();
this.Save();
}
return list;
}
public void AddLastFile(string fileName)
{
List<string> list = this.RemoveLastFile(fileName, false);
list.Insert(0, fileName);
this.LastFiles = list.ToArray();
this.Save();
}
public void RemoveLastFile(string fileName)
{
this.RemoveLastFile(fileName, true);
}
[UserScopedSetting]
public string[] FlattenColors
{
get
{
return this["FlattenColors"] as string[];
}
set
{
this["FlattenColors"] = value;
}
}
[UserScopedSetting]
public string FlattenSpecialChars
{
get
{
return this["FlattenSpecialChars"] as string;
}
set
{
this["FlattenSpecialChars"] = value;
}
}
[UserScopedSetting]
public Font SourceFont
{
get
{
if ((this["SourceFont"] as Font) == null)
this["SourceFont"] = Vars.GetStandardSourceFont();
return (Font)this["SourceFont"];
}
set
{
this["SourceFont"] = value;
}
}
public static Font GetStandardTranslatedFont()
{
try
{ return new Font("Courier New", 10f); }
catch
{
return new Font(FontFamily.GenericMonospace, 10f);
}
}
[UserScopedSetting]
public Font TranslatedFont
{
get
{
if ((this["TranslatedFont"] as Font) == null)
this["TranslatedFont"] = Vars.GetStandardTranslatedFont();
return (Font)this["TranslatedFont"];
}
set
{
this["TranslatedFont"] = value;
}
}
public static Font GetStandardSourceFont()
{
try
{ return new Font("Courier New", 10f); }
catch
{
return new Font(FontFamily.GenericMonospace, 10f);
}
}
[UserScopedSetting, DefaultSettingValue("")]
public string ViewerPath
{
get
{
string s = this["ViewerPath"] as string;
return (s == null) ? "" : s;
}
set
{
this["ViewerPath"] = (value == null) ? "" : value;
}
}
[UserScopedSetting, DefaultSettingValue("")]
public string ViewerParameters
{
get
{
string s = this["ViewerParameters"] as string;
return (s == null) ? "" : s;
}
set
{
this["ViewerParameters"] = (value == null) ? "" : value;
}
}
[UserScopedSetting]
public bool CompileOnSave
{
get
{
object o = this["CompileOnSave"];
return ((o == null) || (o.GetType() != typeof(bool))) ? false : (bool)o;
}
set
{
this["CompileOnSave"] = value;
}
}
[UserScopedSetting, DefaultSettingValue("")]
public string MOCompilerPath
{
get
{
string s = this["MOCompilerPath"] as string;
return (s == null) ? "" : s;
}
set
{
this["MOCompilerPath"] = (value == null) ? "" : value;
}
}
[UserScopedSetting, DefaultSettingValue("2000")]
public int MaxSearchResults
{
get
{
object o = this["MaxSearchResults"];
if (o is int)
{
int i = (int)o;
if (i > 0)
return i;
}
return 2000;
}
set
{
if (value < 0)
throw new ArgumentOutOfRangeException("MaxSearchResults");
this["MaxSearchResults"] = value;
}
}
[UserScopedSetting, DefaultSettingValue("false")]
public bool MOCompiler_CheckFormat
{
get
{
object o = this["MOCompiler_CheckFormat"];
if (o is bool)
{
return (bool)o;
}
return false;
}
set
{
this["MOCompiler_CheckFormat"] = value;
}
}
[UserScopedSetting, DefaultSettingValue("false")]
public bool MOCompiler_CheckHeader
{
get
{
object o = this["MOCompiler_CheckHeader"];
if (o is bool)
{
return (bool)o;
}
return false;
}
set
{
this["MOCompiler_CheckHeader"] = value;
}
}
private Dictionary<ColorEnviroPlace, Color> _colors = null;
public Dictionary<ColorEnviroPlace, Color> Colors
{
get
{
if (this._colors == null)
{
Dictionary<ColorEnviroPlace, Color> ris = null;
string[] flattenColors = this.FlattenColors;
if (flattenColors != null)
{
ris = new Dictionary<ColorEnviroPlace, Color>();
Regex rx = new Regex(@"^(?<enviro>[0-9]+)\|(?<place>[0-9]+)\:(?<r>[0-9]+)\,(?<g>[0-9]+)\,(?<b>[0-9]+)$", RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.ExplicitCapture | RegexOptions.Singleline);
foreach (string flattenColor in flattenColors)
{
Match match = rx.Match(flattenColor);
if (match.Success)
{
ColorEnviroPlace key = ColorEnviroPlace.Get((ColorEnviro)int.Parse(match.Groups["enviro"].Value), (ColorPlace)int.Parse(match.Groups["place"].Value));
if (!ris.ContainsKey(key))
ris.Add(key, Color.FromArgb(int.Parse(match.Groups["r"].Value), int.Parse(match.Groups["g"].Value), int.Parse(match.Groups["b"].Value)));
}
}
foreach (ColorPlace place in Enum.GetValues(typeof(ColorPlace)))
{
foreach (ColorEnviro enviro in Enum.GetValues(typeof(ColorEnviro)))
{
if (!ris.ContainsKey(ColorEnviroPlace.Get(enviro, place)))
{
ris = null;
break;
}
}
if (ris == null)
break;
}
}
if (ris == null)
{
ris = new Dictionary<ColorEnviroPlace, Color>(Vars.DefaultColors.Count);
foreach (KeyValuePair<ColorEnviroPlace, Color> kv in Vars.DefaultColors)
{
ris.Add(kv.Key, kv.Value);
}
}
this._colors = ris;
}
return this._colors;
}
}
private List<KeyValuePair<string, string>> _specialChars = null;
public List<KeyValuePair<string, string>> SpecialChars
{
get
{
if (this._specialChars == null)
{
List<KeyValuePair<string, string>> ris = new List<KeyValuePair<string, string>>();
string flattenSpecialCharsList = this.FlattenSpecialChars;
if (!string.IsNullOrEmpty(flattenSpecialCharsList))
{
foreach(string flattenSpecialChar in flattenSpecialCharsList.Split('\x01'))
{
if(!string.IsNullOrEmpty(flattenSpecialChar)) {
int p = flattenSpecialChar.IndexOf('\x02');
if ((p > 0) && (p < (flattenSpecialChar.Length - 1)))
{
string name = flattenSpecialChar.Substring(0, p).Trim();
string sc = flattenSpecialChar.Substring(p + 1);
if ((name.Length > 0) && (sc.Length > 0))
{
ris.Add(new KeyValuePair<string, string>(name, sc));
}
}
}
}
}
this._specialChars = ris;
}
return this._specialChars;
}
set
{
this._specialChars = (value == null) ? new List<KeyValuePair<string, string>>() : value;
}
}
public override void Save()
{
List<string> colors = new List<string>(this.Colors.Count);
foreach (KeyValuePair<ColorEnviroPlace, Color> kv in this.Colors)
colors.Add(string.Format("{0}|{1}:{2},{3},{4}", (int)kv.Key.Enviro, (int)kv.Key.Place, kv.Value.R, kv.Value.G, kv.Value.B));
this["FlattenColors"] = colors.ToArray();
StringBuilder specialChars = null;
foreach (KeyValuePair<string, string> kv in this.SpecialChars)
{
if (specialChars == null)
{
specialChars = new StringBuilder();
}
else
{
specialChars.Append('\x01');
}
specialChars.Append(kv.Key).Append('\x02').Append(kv.Value);
}
this.FlattenSpecialChars = (specialChars == null) ? "" : specialChars.ToString();
base.Save();
}
private static Dictionary<ColorEnviroPlace, Color> _defaultColors = null;
public static Dictionary<ColorEnviroPlace, Color> DefaultColors
{
get
{
if (Vars._defaultColors == null)
{
Dictionary<ColorEnviroPlace, Color> C = new Dictionary<ColorEnviroPlace, Color>();
foreach (ColorPlace place in Enum.GetValues(typeof(ColorPlace)))
{
foreach (ColorEnviro enviro in Enum.GetValues(typeof(ColorEnviro)))
{
switch (enviro)
{
case ColorEnviro.Untranslated:
switch (place)
{
case ColorPlace.ForeUnsel:
case ColorPlace.BackSel:
C.Add(ColorEnviroPlace.Get(enviro, place), Color.FromArgb(92, 0, 0));
break;
case ColorPlace.BackUnsel:
case ColorPlace.ForeSel:
C.Add(ColorEnviroPlace.Get(enviro, place), Color.FromArgb(255, 240, 240));
break;
default:
throw new Exception();
}
break;
case ColorEnviro.Translated:
switch (place)
{
case ColorPlace.ForeUnsel:
case ColorPlace.BackSel:
C.Add(ColorEnviroPlace.Get(enviro, place), Color.FromArgb(0, 92, 0));
break;
case ColorPlace.BackUnsel:
case ColorPlace.ForeSel:
C.Add(ColorEnviroPlace.Get(enviro, place), Color.FromArgb(240, 255, 240));
break;
default:
throw new Exception();
}
break;
case ColorEnviro.Removed:
switch (place)
{
case ColorPlace.ForeUnsel:
case ColorPlace.BackSel:
C.Add(ColorEnviroPlace.Get(enviro, place), Color.FromArgb(92, 92, 92));
break;
case ColorPlace.BackUnsel:
case ColorPlace.ForeSel:
C.Add(ColorEnviroPlace.Get(enviro, place), Color.FromArgb(240, 240, 240));
break;
default:
throw new Exception();
}
break;
default:
throw new Exception();
}
}
}
Vars._defaultColors = C;
}
return Vars._defaultColors;
}
}
[UserScopedSetting, DefaultSettingValue("")]
public string BingTranslatorClientID
{
get
{
string s = this["BingTranslatorClientID"] as string;
return (s == null) ? "" : s;
}
set
{
this["BingTranslatorClientID"] = (value == null) ? "" : value;
}
}
[UserScopedSetting, DefaultSettingValue("")]
public string BingTranslatorClientSecret
{
get
{
string s = this["BingTranslatorClientSecret"] as string;
return (s == null) ? "" : s;
}
set
{
this["BingTranslatorClientSecret"] = (value == null) ? "" : value;
}
}
}
}
| |
// Copyright (c) 2012, Miron Brezuleanu
// 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.
//
// 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 <COPYRIGHT HOLDER> 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.Generic;
using System.Net;
using System.Web;
using System.IO;
namespace _03_GuessTheNumberWebMany
{
class MainClass
{
static string Program ()
{
return @"
var game = fn () {
var secretNumber = floor(@random() * 100 + 1)
var attempt = 0
var iteration = fn () {
attempt = attempt + 1
@print('Attempt ' + string(attempt) + ' - ')
@print('enter a number between 1 and 100: ')
var guess = @readInt()
if guess < secretNumber {
@printLn('Too small!')
iteration()
}
else if guess > secretNumber {
@printLn('Too large!')
iteration()
}
else {
@printLn('You guessed it in ' + string(attempt) + ' attempts! Congratulations!')
@print('Another game? (y/n) ')
if @readChar() == 'y' game()
}
}
iteration()
}
game()
";
}
static List<Shovel.SourceFile> ProgramSources (string program)
{
return Shovel.Api.MakeSources ("guess.sho", program);
}
static Shovel.Instruction[] ProgramBytecode ()
{
try {
return Shovel.Api.GetBytecode (ProgramSources (Program ()));
} catch (Shovel.Exceptions.ShovelException shex) {
Console.WriteLine (shex.Message);
return null;
}
}
static IEnumerable<Shovel.Callable> Udps (Session session, string userInput)
{
var rng = new Random ();
Action<Shovel.VmApi, Shovel.Value[], Shovel.UdpResult> print = (api, args, result) =>
{
if (args.Length > 0 && args [0].Kind == Shovel.Value.Kinds.String) {
session.PageContent.Append ("<span>");
session.PageContent.Append (HttpUtility.HtmlEncode (args [0].String));
session.PageContent.Append ("</span>");
}
};
Action<Shovel.VmApi, Shovel.Value[], Shovel.UdpResult> printLn = (api, args, result) =>
{
if (args.Length > 0 && args [0].Kind == Shovel.Value.Kinds.String) {
session.PageContent.Append ("<span>");
session.PageContent.Append (HttpUtility.HtmlEncode (args [0].String));
session.PageContent.Append ("</span><br/>");
}
};
Action<Shovel.VmApi, Shovel.Value[], Shovel.UdpResult> readInt = (api, args, result) =>
{
if (session.ReadState == Session.ReadStates.None) {
result.After = Shovel.UdpResult.AfterCall.NapAndRetryOnWakeUp;
session.ReadState = Session.ReadStates.ReadInteger;
} else if (session.ReadState == Session.ReadStates.ReadInteger) {
int dummy;
if (!int.TryParse (userInput, out dummy)) {
dummy = 0;
}
result.Result = Shovel.Value.MakeInt (dummy);
session.ReadState = Session.ReadStates.None;
session.PageContent.Append (HttpUtility.HtmlEncode (userInput));
session.PageContent.Append ("<br/>");
} else {
throw new InvalidOperationException ();
}
};
Action<Shovel.VmApi, Shovel.Value[], Shovel.UdpResult> readChar = (api, args, result) =>
{
if (session.ReadState == Session.ReadStates.None) {
result.After = Shovel.UdpResult.AfterCall.NapAndRetryOnWakeUp;
session.ReadState = Session.ReadStates.ReadChar;
} else if (session.ReadState == Session.ReadStates.ReadChar) {
var line = userInput;
if (line.Length > 0) {
result.Result = Shovel.Value.Make (line.Substring (0, 1));
} else {
result.Result = Shovel.Value.Make ("");
}
session.ReadState = Session.ReadStates.None;
session.PageContent.Append (HttpUtility.HtmlEncode (userInput));
session.PageContent.Append ("<br/>");
} else {
throw new InvalidOperationException ();
}
};
Action<Shovel.VmApi, Shovel.Value[], Shovel.UdpResult> random = (api, args, result) =>
{
result.Result = Shovel.Value.MakeFloat (rng.NextDouble ());
};
return new Shovel.Callable[] {
Shovel.Callable.MakeUdp ("print", print, 1),
Shovel.Callable.MakeUdp ("printLn", printLn, 1),
Shovel.Callable.MakeUdp ("readInt", readInt, 0),
Shovel.Callable.MakeUdp ("readChar", readChar, 0),
Shovel.Callable.MakeUdp ("random", random, 0),
};
}
static Session FreshSession (FileSystemDatabase fsd)
{
var session = new Session ();
session.Id = fsd.GetFreshId ();
session.ShovelVmSources = Program ();
session.ShovelVmBytecode = Shovel.Api.SerializeBytecode (ProgramBytecode ());
return session;
}
private static void ServeGuessNumberRequest (HttpListenerContext ctx, FileSystemDatabase fsd)
{
ctx.Response.ContentType = "text/html";
var userInput = ctx.Request.QueryString ["input"];
int sessionId = 0;
var sessionIdStr = ctx.Request.QueryString ["sessionid"];
int.TryParse (sessionIdStr, out sessionId);
Session session = null;
if (sessionId != 0) {
session = Session.Load (fsd, sessionId);
}
if (session == null) {
session = FreshSession (fsd);
}
var vm = Shovel.Api.RunVm (
Shovel.Api.DeserializeBytecode (session.ShovelVmBytecode),
ProgramSources (Program ()),
Udps (session, userInput),
session.ShovelVmState);
if (Shovel.Api.VmExecutionComplete (vm)) {
ctx.Response.Redirect ("/");
} else {
session.ShovelVmState = Shovel.Api.SerializeVmState (vm);
// FIXME: Uncomment the next statement to fix the 'back button bug'.
//session.Id = fsd.GetFreshId ();
session.Save (fsd);
using (var sw = new StreamWriter(ctx.Response.OutputStream)) {
sw.Write ("<!DOCTYPE html>\n");
sw.Write (session.PageContent.ToString ());
sw.Write ("<form action='/' method='get'>");
sw.Write ("<input type='text' name='input' id='shovel-input'/>");
sw.Write ("<input type='submit' value='Submit'/>");
sw.Write (String.Format (
"<input type='hidden' name='sessionid' value='{0}' id='shovel-input'/>", session.Id));
sw.Write ("</form>");
sw.Write ("<script>\n");
sw.Write ("document.getElementById('shovel-input').focus()\n");
sw.Write ("</script>\n");
}
}
ctx.Response.OutputStream.Close ();
}
public static void Main (string[] args)
{
if (!HttpListener.IsSupported) {
Console.WriteLine ("HttpListener not available.");
Environment.Exit (-1);
}
var bytecode = ProgramBytecode ();
if (bytecode == null) {
Environment.Exit (-1);
}
HttpListener hl = new HttpListener ();
hl.Prefixes.Add ("http://localhost:8080/");
hl.Start ();
var requestNo = 1;
var fsd = new FileSystemDatabase ("db");
while (hl.IsListening) {
var ctx = hl.GetContext ();
Console.WriteLine ("Serving a request ({0} {1}).", requestNo, ctx.Request.Url.AbsolutePath);
if (ctx.Request.Url.AbsolutePath == "/") {
ServeGuessNumberRequest (ctx, fsd);
} else {
ctx.Response.OutputStream.Close ();
}
Console.WriteLine ("Served a request ({0}).", requestNo);
requestNo++;
}
}
}
}
| |
// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// 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 Google.Api.Ads.AdWords.Lib;
using Google.Api.Ads.AdWords.Util.BatchJob.v201809;
using Google.Api.Ads.AdWords.v201809;
using System;
using System.Collections.Generic;
using System.Threading;
namespace Google.Api.Ads.AdWords.Examples.CSharp.v201809
{
/// <summary>
/// This code sample illustrates how to use BatchJobService to create multiple
/// complete campaigns, including ad groups and keywords.
/// </summary>
public class AddCompleteCampaignsUsingBatchJob : ExampleBase
{
/// <summary>
/// The last ID that was automatically generated.
/// </summary>
private static long LAST_ID = -1;
/// <summary>
/// The number of campaigns to be added.
/// </summary>
private const long NUMBER_OF_CAMPAIGNS_TO_ADD = 2;
/// <summary>
/// The number of ad groups to be added per campaign.
/// </summary>
private const long NUMBER_OF_ADGROUPS_TO_ADD = 2;
/// <summary>
/// The number of keywords to be added per campaign.
/// </summary>
private const long NUMBER_OF_KEYWORDS_TO_ADD = 5;
/// <summary>
/// The polling interval base to be used for exponential backoff.
/// </summary>
private const int POLL_INTERVAL_SECONDS_BASE = 30;
/// <summary>
/// The maximum milliseconds to wait for completion.
/// </summary>
private const int TIME_TO_WAIT_FOR_COMPLETION = 15 * 60 * 1000; // 15 minutes
/// <summary>
/// Create a temporary ID generator that will produce a sequence of descending
/// negative numbers.
/// </summary>
/// <returns></returns>
private static long NextId()
{
return Interlocked.Decrement(ref LAST_ID);
}
/// <summary>
/// Main method, to run this code example as a standalone application.
/// </summary>
/// <param name="args">The command line arguments.</param>
public static void Main(string[] args)
{
AddCompleteCampaignsUsingBatchJob codeExample = new AddCompleteCampaignsUsingBatchJob();
Console.WriteLine(codeExample.Description);
try
{
codeExample.Run(new AdWordsUser());
}
catch (Exception e)
{
Console.WriteLine("An exception occurred while running this code example. {0}",
ExampleUtilities.FormatException(e));
}
}
/// <summary>
/// Returns a description about the code example.
/// </summary>
public override string Description
{
get
{
return
"This code sample illustrates how to use BatchJobService to create multiple " +
"complete campaigns, including ad groups and keywords.";
}
}
/// <summary>
/// Runs the code example.
/// </summary>
/// <param name="user">The AdWords user.</param>
public void Run(AdWordsUser user)
{
using (BatchJobService batchJobService =
(BatchJobService) user.GetService(AdWordsService.v201809.BatchJobService))
{
try
{
// Create a BatchJob.
BatchJobOperation addOp = new BatchJobOperation()
{
@operator = Operator.ADD,
operand = new BatchJob()
};
BatchJob batchJob = batchJobService.mutate(new BatchJobOperation[]
{
addOp
}).value[0];
// Get the upload URL from the new job.
string uploadUrl = batchJob.uploadUrl.url;
Console.WriteLine(
"Created BatchJob with ID {0}, status '{1}' and upload URL {2}.",
batchJob.id, batchJob.status, batchJob.uploadUrl.url);
// Create the mutate request that will be sent to the upload URL.
List<Operation> operations = new List<Operation>();
// Create and add an operation to create a new budget.
BudgetOperation budgetOperation = BuildBudgetOperation();
operations.Add(budgetOperation);
// Create and add operations to create new campaigns.
List<CampaignOperation> campaignOperations =
BuildCampaignOperations(budgetOperation.operand.budgetId);
operations.AddRange(campaignOperations);
// Create and add operations to create new ad groups.
List<AdGroupOperation> adGroupOperations = new List<AdGroupOperation>();
foreach (CampaignOperation campaignOperation in campaignOperations)
{
adGroupOperations.AddRange(
BuildAdGroupOperations(campaignOperation.operand.id));
}
operations.AddRange(adGroupOperations);
// Create and add operations to create new ad group ads (expanded text ads).
foreach (AdGroupOperation adGroupOperation in adGroupOperations)
{
operations.AddRange(BuildAdGroupAdOperations(adGroupOperation.operand.id));
}
// Create and add operations to create new ad group criteria (keywords).
foreach (AdGroupOperation adGroupOperation in adGroupOperations)
{
operations.AddRange(
BuildAdGroupCriterionOperations(adGroupOperation.operand.id));
}
BatchJobUtilities batchJobUploadHelper = new BatchJobUtilities(user);
// Create a resumable Upload URL to upload the operations.
string resumableUploadUrl =
batchJobUploadHelper.GetResumableUploadUrl(uploadUrl);
// Use the BatchJobUploadHelper to upload all operations.
batchJobUploadHelper.Upload(resumableUploadUrl, operations);
bool isCompleted = batchJobUploadHelper.WaitForPendingJob(batchJob.id,
TIME_TO_WAIT_FOR_COMPLETION,
delegate(BatchJob waitBatchJob, long timeElapsed)
{
Console.WriteLine("[{0} seconds]: Batch job ID {1} has status '{2}'.",
timeElapsed / 1000, waitBatchJob.id, waitBatchJob.status);
batchJob = waitBatchJob;
return false;
});
if (!isCompleted)
{
throw new TimeoutException(
"Job is still in pending state after waiting for " +
TIME_TO_WAIT_FOR_COMPLETION + " seconds.");
}
if (batchJob.processingErrors != null)
{
foreach (BatchJobProcessingError processingError in batchJob
.processingErrors)
{
Console.WriteLine(" Processing error: {0}, {1}, {2}, {3}, {4}",
processingError.ApiErrorType, processingError.trigger,
processingError.errorString, processingError.fieldPath,
processingError.reason);
}
}
if (batchJob.downloadUrl != null && batchJob.downloadUrl.url != null)
{
BatchJobMutateResponse mutateResponse =
batchJobUploadHelper.Download(batchJob.downloadUrl.url);
Console.WriteLine("Downloaded results from {0}.", batchJob.downloadUrl.url);
foreach (MutateResult mutateResult in mutateResponse.rval)
{
string outcome = mutateResult.errorList == null ? "SUCCESS" : "FAILURE";
Console.WriteLine(" Operation [{0}] - {1}", mutateResult.index,
outcome);
}
}
}
catch (Exception e)
{
throw new System.ApplicationException(
"Failed to add campaigns using batch job.", e);
}
}
}
/// <summary>
/// Builds the operation for creating an ad within an ad group.
/// </summary>
/// <param name="adGroupId">ID of the ad group for which ads are created.</param>
/// <returns>A list of operations for creating ads.</returns>
private static List<AdGroupAdOperation> BuildAdGroupAdOperations(long adGroupId)
{
List<AdGroupAdOperation> operations = new List<AdGroupAdOperation>();
AdGroupAd adGroupAd = new AdGroupAd()
{
adGroupId = adGroupId,
ad = new ExpandedTextAd()
{
headlinePart1 = "Luxury Cruise to Mars",
headlinePart2 = "Visit the Red Planet in style.",
description = "Low-gravity fun for everyone!",
finalUrls = new string[]
{
"http://www.example.com/1"
}
}
};
AdGroupAdOperation operation = new AdGroupAdOperation()
{
operand = adGroupAd,
@operator = Operator.ADD
};
operations.Add(operation);
return operations;
}
/// <summary>
/// Builds the operations for creating keywords within an ad group.
/// </summary>
/// <param name="adGroupId">ID of the ad group for which keywords are
/// created.</param>
/// <returns>A list of operations for creating keywords.</returns>
private static List<AdGroupCriterionOperation> BuildAdGroupCriterionOperations(
long adGroupId)
{
List<AdGroupCriterionOperation> adGroupCriteriaOperations =
new List<AdGroupCriterionOperation>();
// Create AdGroupCriterionOperations to add keywords.
for (int i = 0; i < NUMBER_OF_KEYWORDS_TO_ADD; i++)
{
// Create Keyword.
string text = string.Format("mars{0}", i);
// Make 50% of keywords invalid to demonstrate error handling.
if ((i % 2) == 0)
{
text = text + "!!!";
}
// Create AdGroupCriterionOperation.
AdGroupCriterionOperation operation = new AdGroupCriterionOperation()
{
operand = new BiddableAdGroupCriterion()
{
adGroupId = adGroupId,
criterion = new Keyword()
{
text = text,
matchType = KeywordMatchType.BROAD
}
},
@operator = Operator.ADD
};
// Add to list.
adGroupCriteriaOperations.Add(operation);
}
return adGroupCriteriaOperations;
}
/// <summary>
/// Builds the operations for creating ad groups within a campaign.
/// </summary>
/// <param name="campaignId">ID of the campaign for which ad groups are
/// created.</param>
/// <returns>A list of operations for creating ad groups.</returns>
private static List<AdGroupOperation> BuildAdGroupOperations(long campaignId)
{
List<AdGroupOperation> operations = new List<AdGroupOperation>();
for (int i = 0; i < NUMBER_OF_ADGROUPS_TO_ADD; i++)
{
AdGroup adGroup = new AdGroup()
{
campaignId = campaignId,
id = NextId(),
name = "Batch Ad Group # " + ExampleUtilities.GetRandomString(),
biddingStrategyConfiguration = new BiddingStrategyConfiguration()
{
bids = new Bids[]
{
new CpcBid()
{
bid = new Money()
{
microAmount = 10000000L
}
}
}
}
};
AdGroupOperation operation = new AdGroupOperation()
{
operand = adGroup,
@operator = Operator.ADD
};
operations.Add(operation);
}
return operations;
}
/// <summary>
/// Builds the operations for creating new campaigns.
/// </summary>
/// <param name="budgetId">ID of the budget to be used for the campaign.
/// </param>
/// <returns>A list of operations for creating campaigns.</returns>
private static List<CampaignOperation> BuildCampaignOperations(long budgetId)
{
List<CampaignOperation> operations = new List<CampaignOperation>();
for (int i = 0; i < NUMBER_OF_CAMPAIGNS_TO_ADD; i++)
{
Campaign campaign = new Campaign()
{
name = "Batch Campaign " + ExampleUtilities.GetRandomString(),
// Recommendation: Set the campaign to PAUSED when creating it to prevent
// the ads from immediately serving. Set to ENABLED once you've added
// targeting and the ads are ready to serve.
status = CampaignStatus.PAUSED,
id = NextId(),
advertisingChannelType = AdvertisingChannelType.SEARCH,
budget = new Budget()
{
budgetId = budgetId
},
biddingStrategyConfiguration = new BiddingStrategyConfiguration()
{
biddingStrategyType = BiddingStrategyType.MANUAL_CPC,
// You can optionally provide a bidding scheme in place of the type.
biddingScheme = new ManualCpcBiddingScheme()
}
};
CampaignOperation operation = new CampaignOperation()
{
operand = campaign,
@operator = Operator.ADD
};
operations.Add(operation);
}
return operations;
}
/// <summary>
/// Builds an operation for creating a budget.
/// </summary>
/// <returns>The operation for creating a budget.</returns>
private static BudgetOperation BuildBudgetOperation()
{
Budget budget = new Budget()
{
budgetId = NextId(),
name = "Interplanetary Cruise #" + ExampleUtilities.GetRandomString(),
amount = new Money()
{
microAmount = 50000000L,
},
deliveryMethod = BudgetBudgetDeliveryMethod.STANDARD,
};
BudgetOperation budgetOperation = new BudgetOperation()
{
operand = budget,
@operator = Operator.ADD
};
return budgetOperation;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Xml;
using Microsoft.Build.BackEnd;
using Microsoft.Build.Framework;
using Microsoft.Build.Collections;
using Microsoft.Build.Shared;
using System.Reflection;
using Microsoft.Build.Utilities;
using Microsoft.Build.Construction;
using ILoggingService = Microsoft.Build.BackEnd.Logging.ILoggingService;
using LoggingService = Microsoft.Build.BackEnd.Logging.LoggingService;
using InvalidProjectFileException = Microsoft.Build.Exceptions.InvalidProjectFileException;
using Xunit;
namespace Microsoft.Build.UnitTests.BackEnd
{
/// <summary>
/// Tests for the assembly task factory
/// </summary>
public class AssemblyTaskFactory_Tests
{
/// <summary>
/// A well instantiated task factory
/// </summary>
private AssemblyTaskFactory _taskFactory;
/// <summary>
/// The load info about a task to wrap in the assembly task factory
/// </summary>
private AssemblyLoadInfo _loadInfo;
/// <summary>
/// The loaded type from the initialized task factory.
/// </summary>
private LoadedType _loadedType;
/// <summary>
/// Initialize a task factory
/// </summary>
public AssemblyTaskFactory_Tests()
{
SetupTaskFactory(null, false);
}
#region AssemblyTaskFactory
#region ExpectExceptions
/// <summary>
/// Make sure we get an invalid project file exception when a null load info is passed to the factory
/// </summary>
[Fact]
public void NullLoadInfo()
{
Assert.Throws<ArgumentNullException>(() =>
{
AssemblyTaskFactory taskFactory = new AssemblyTaskFactory();
taskFactory.InitializeFactory(null, "TaskToTestFactories", new Dictionary<string, TaskPropertyInfo>(), string.Empty, null, false, null, ElementLocation.Create("NONE"), String.Empty);
}
);
}
/// <summary>
/// Make sure we get an invalid project file exception when a null task name is passed to the factory
/// </summary>
[Fact]
public void NullTaskName()
{
Assert.Throws<InvalidProjectFileException>(() =>
{
AssemblyTaskFactory taskFactory = new AssemblyTaskFactory();
taskFactory.InitializeFactory(_loadInfo, null, new Dictionary<string, TaskPropertyInfo>(), string.Empty, null, false, null, ElementLocation.Create("NONE"), String.Empty);
}
);
}
/// <summary>
/// Make sure we get an invalid project file exception when an empty task name is passed to the factory
/// </summary>
[Fact]
public void EmptyTaskName()
{
Assert.Throws<InvalidProjectFileException>(() =>
{
AssemblyTaskFactory taskFactory = new AssemblyTaskFactory();
taskFactory.InitializeFactory(_loadInfo, String.Empty, new Dictionary<string, TaskPropertyInfo>(), string.Empty, null, false, null, ElementLocation.Create("NONE"), String.Empty);
}
);
}
/// <summary>
/// Make sure we get an invalid project file exception when the task is not in the info
/// </summary>
[Fact]
public void GoodTaskNameButNotInInfo()
{
Assert.Throws<InvalidProjectFileException>(() =>
{
AssemblyTaskFactory taskFactory = new AssemblyTaskFactory();
taskFactory.InitializeFactory(_loadInfo, "RandomTask", new Dictionary<string, TaskPropertyInfo>(), string.Empty, null, false, null, ElementLocation.Create("NONE"), String.Empty);
}
);
}
/// <summary>
/// Make sure we get an internal error when we call the initialize factory on the public method.
/// This is done because we cannot properly initialize the task factory using the public interface and keep
/// backwards compatibility with orcas and whidbey.
/// </summary>
[Fact]
public void CallPublicInitializeFactory()
{
Assert.Throws<InternalErrorException>(() =>
{
AssemblyTaskFactory taskFactory = new AssemblyTaskFactory();
taskFactory.Initialize(String.Empty, new Dictionary<string, TaskPropertyInfo>(), String.Empty, null);
}
);
}
/// <summary>
/// Make sure we get an internal error when we call the ITaskFactory2 version of initialize factory.
/// This is done because we cannot properly initialize the task factory using the public interface and keep
/// backwards compatibility with orcas and whidbey.
/// </summary>
[Fact]
public void CallPublicInitializeFactory2()
{
Assert.Throws<InternalErrorException>(() =>
{
AssemblyTaskFactory taskFactory = new AssemblyTaskFactory();
taskFactory.Initialize(String.Empty, null, new Dictionary<string, TaskPropertyInfo>(), String.Empty, null);
}
);
}
#endregion
/// <summary>
/// Verify that we can ask the factory if a given task is in the factory and get the correct result back
/// </summary>
[Fact]
public void CreatableByTaskFactoryGoodName()
{
Assert.True(_taskFactory.TaskNameCreatableByFactory("TaskToTestFactories", null, String.Empty, null, ElementLocation.Create(".", 1, 1)));
}
/// <summary>
/// Expect a false answer when we ask for a task which is not in the factory.
/// </summary>
[Fact]
public void CreatableByTaskFactoryNotInAssembly()
{
Assert.False(_taskFactory.TaskNameCreatableByFactory("NotInAssembly", null, String.Empty, null, ElementLocation.Create(".", 1, 1)));
}
/// <summary>
/// Expect a false answer when we ask for a task which is not in the factory.
/// </summary>
[Fact]
public void CreatableByTaskFactoryNotInAssemblyEmptyTaskName()
{
Assert.Throws<InvalidProjectFileException>(() =>
{
Assert.False(_taskFactory.TaskNameCreatableByFactory(String.Empty, null, String.Empty, null, ElementLocation.Create(".", 1, 1)));
}
);
}
/// <summary>
/// Expect a false answer when we ask for a task which is not in the factory.
/// </summary>
[Fact]
public void CreatableByTaskFactoryNullTaskName()
{
Assert.Throws<InvalidProjectFileException>(() =>
{
Assert.False(_taskFactory.TaskNameCreatableByFactory(null, null, String.Empty, null, ElementLocation.Create(".", 1, 1)));
}
);
}
/// <summary>
/// Make sure that when an explicitly matching identity is specified (e.g. the identity is non-empty),
/// it still counts as correct.
/// </summary>
[Fact]
public void CreatableByTaskFactoryMatchingIdentity()
{
IDictionary<string, string> factoryIdentityParameters = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
factoryIdentityParameters.Add(XMakeAttributes.runtime, XMakeAttributes.MSBuildRuntimeValues.currentRuntime);
factoryIdentityParameters.Add(XMakeAttributes.architecture, XMakeAttributes.MSBuildArchitectureValues.currentArchitecture);
SetupTaskFactory(factoryIdentityParameters, false /* don't want task host */);
IDictionary<string, string> taskIdentityParameters = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
taskIdentityParameters.Add(XMakeAttributes.runtime, XMakeAttributes.MSBuildRuntimeValues.clr4);
taskIdentityParameters.Add(XMakeAttributes.architecture, XMakeAttributes.MSBuildArchitectureValues.any);
Assert.True(_taskFactory.TaskNameCreatableByFactory("TaskToTestFactories", taskIdentityParameters, String.Empty, null, ElementLocation.Create(".", 1, 1)));
}
/// <summary>
/// Verify that if the task identity parameters don't match the factory identity, TaskNameCreatableByFactory
/// returns false.
/// </summary>
[Fact]
public void CreatableByTaskFactoryMismatchedIdentity()
{
IDictionary<string, string> factoryIdentityParameters = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
factoryIdentityParameters.Add(XMakeAttributes.runtime, XMakeAttributes.MSBuildRuntimeValues.clr2);
factoryIdentityParameters.Add(XMakeAttributes.architecture, XMakeAttributes.MSBuildArchitectureValues.currentArchitecture);
SetupTaskFactory(factoryIdentityParameters, false /* don't want task host */);
IDictionary<string, string> taskIdentityParameters = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
taskIdentityParameters.Add(XMakeAttributes.runtime, XMakeAttributes.MSBuildRuntimeValues.clr4);
taskIdentityParameters.Add(XMakeAttributes.architecture, XMakeAttributes.MSBuildArchitectureValues.currentArchitecture);
Assert.False(_taskFactory.TaskNameCreatableByFactory("TaskToTestFactories", taskIdentityParameters, String.Empty, null, ElementLocation.Create(".", 1, 1)));
}
/// <summary>
/// Make sure the number of properties retrieved from the task factory are the same number retrieved from the type directly.
/// </summary>
[Fact]
public void VerifyGetTaskParameters()
{
TaskPropertyInfo[] propertyInfos = _taskFactory.GetTaskParameters();
LoadedType comparisonType = new LoadedType(typeof(TaskToTestFactories), _loadInfo);
PropertyInfo[] comparisonInfo = comparisonType.Type.GetProperties(BindingFlags.Instance | BindingFlags.Public);
Assert.Equal(comparisonInfo.Length, propertyInfos.Length);
bool foundExpectedParameter = false;
bool foundNotExpectedParameter = false;
for (int i = 0; i < propertyInfos.Length; i++)
{
if (propertyInfos[i].Name.Equals("ExpectedParameter", StringComparison.OrdinalIgnoreCase))
{
foundExpectedParameter = true;
}
if (propertyInfos[i].Name.Equals("NotExpectedParameter", StringComparison.OrdinalIgnoreCase))
{
foundNotExpectedParameter = true;
}
}
Assert.True(foundExpectedParameter);
Assert.False(foundNotExpectedParameter);
}
/// <summary>
/// Verify a good task can be created.
/// </summary>
[Fact]
public void VerifyGoodTaskInstantiation()
{
ITask createdTask = null;
try
{
createdTask = _taskFactory.CreateTaskInstance(ElementLocation.Create("MSBUILD"), null, new MockHost(), null,
#if FEATURE_APPDOMAIN
new AppDomainSetup(),
#endif
false);
Assert.NotNull(createdTask);
Assert.False(createdTask is TaskHostTask);
}
finally
{
if (createdTask != null)
{
_taskFactory.CleanupTask(createdTask);
}
}
}
/// <summary>
/// Verify a good task that does not use the task host can be created when passed "don't care"
/// for the task invocation task host parameters.
/// </summary>
[Fact]
public void VerifyMatchingTaskParametersDontLaunchTaskHost1()
{
ITask createdTask = null;
try
{
IDictionary<string, string> taskParameters = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
taskParameters.Add(XMakeAttributes.runtime, XMakeAttributes.MSBuildRuntimeValues.any);
taskParameters.Add(XMakeAttributes.architecture, XMakeAttributes.MSBuildArchitectureValues.any);
createdTask = _taskFactory.CreateTaskInstance(ElementLocation.Create("MSBUILD"), null, new MockHost(), taskParameters,
#if FEATURE_APPDOMAIN
new AppDomainSetup(),
#endif
false);
Assert.NotNull(createdTask);
Assert.False(createdTask is TaskHostTask);
}
finally
{
if (createdTask != null)
{
_taskFactory.CleanupTask(createdTask);
}
}
}
/// <summary>
/// Verify a good task that does not use the task host can be created when passed task host
/// parameters that explicitly match the current process.
/// </summary>
[Fact]
public void VerifyMatchingTaskParametersDontLaunchTaskHost2()
{
ITask createdTask = null;
try
{
IDictionary<string, string> taskParameters = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
taskParameters.Add(XMakeAttributes.runtime, XMakeAttributes.MSBuildRuntimeValues.clr4);
taskParameters.Add(XMakeAttributes.architecture, XMakeAttributes.GetCurrentMSBuildArchitecture());
createdTask = _taskFactory.CreateTaskInstance(ElementLocation.Create("MSBUILD"), null, new MockHost(), taskParameters,
#if FEATURE_APPDOMAIN
new AppDomainSetup(),
#endif
false);
Assert.NotNull(createdTask);
Assert.False(createdTask is TaskHostTask);
}
finally
{
if (createdTask != null)
{
_taskFactory.CleanupTask(createdTask);
}
}
}
/// <summary>
/// Verify a good task that does not use the task host can be created when passed "don't care"
/// for the task invocation task host parameters.
/// </summary>
[Fact]
public void VerifyMatchingUsingTaskParametersDontLaunchTaskHost1()
{
ITask createdTask = null;
try
{
IDictionary<string, string> taskParameters = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
taskParameters.Add(XMakeAttributes.runtime, XMakeAttributes.MSBuildRuntimeValues.any);
taskParameters.Add(XMakeAttributes.architecture, XMakeAttributes.MSBuildArchitectureValues.any);
SetupTaskFactory(taskParameters, false /* don't want task host */);
createdTask = _taskFactory.CreateTaskInstance(ElementLocation.Create("MSBUILD"), null, new MockHost(), null,
#if FEATURE_APPDOMAIN
new AppDomainSetup(),
#endif
false);
Assert.NotNull(createdTask);
Assert.False(createdTask is TaskHostTask);
}
finally
{
if (createdTask != null)
{
_taskFactory.CleanupTask(createdTask);
}
}
}
/// <summary>
/// Verify a good task that does not use the task host can be created when passed task host
/// parameters that explicitly match the current process.
/// </summary>
[Fact]
public void VerifyMatchingUsingTaskParametersDontLaunchTaskHost2()
{
ITask createdTask = null;
try
{
IDictionary<string, string> taskParameters = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
taskParameters.Add(XMakeAttributes.runtime, XMakeAttributes.MSBuildRuntimeValues.any);
taskParameters.Add(XMakeAttributes.architecture, XMakeAttributes.GetCurrentMSBuildArchitecture());
SetupTaskFactory(taskParameters, false /* don't want task host */);
createdTask = _taskFactory.CreateTaskInstance(ElementLocation.Create("MSBUILD"), null, new MockHost(), null,
#if FEATURE_APPDOMAIN
new AppDomainSetup(),
#endif
false);
Assert.NotNull(createdTask);
Assert.False(createdTask is TaskHostTask);
}
finally
{
if (createdTask != null)
{
_taskFactory.CleanupTask(createdTask);
}
}
}
/// <summary>
/// Verify a good task that uses the task host can be created when passed task host
/// parameters that explicitly do not match the current process.
/// </summary>
[Fact]
public void VerifyMatchingParametersDontLaunchTaskHost()
{
ITask createdTask = null;
try
{
IDictionary<string, string> factoryParameters = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
factoryParameters.Add(XMakeAttributes.runtime, XMakeAttributes.MSBuildRuntimeValues.clr4);
SetupTaskFactory(factoryParameters, false /* don't want task host */);
IDictionary<string, string> taskParameters = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
taskParameters.Add(XMakeAttributes.architecture, XMakeAttributes.MSBuildArchitectureValues.currentArchitecture);
createdTask = _taskFactory.CreateTaskInstance(ElementLocation.Create("MSBUILD"), null, new MockHost(), taskParameters,
#if FEATURE_APPDOMAIN
new AppDomainSetup(),
#endif
false);
Assert.NotNull(createdTask);
Assert.False(createdTask is TaskHostTask);
}
finally
{
if (createdTask != null)
{
_taskFactory.CleanupTask(createdTask);
}
}
}
/// <summary>
/// Verify a good task that uses the task host can be created when passed task host
/// parameters that explicitly do not match the current process.
/// </summary>
[Fact]
[Trait("Category", "mono-osx-failing")]
public void VerifyNonmatchingUsingTaskParametersLaunchTaskHost()
{
ITask createdTask = null;
try
{
IDictionary<string, string> taskParameters = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
taskParameters.Add(XMakeAttributes.runtime, XMakeAttributes.MSBuildRuntimeValues.clr2);
taskParameters.Add(XMakeAttributes.architecture, XMakeAttributes.MSBuildArchitectureValues.any);
SetupTaskFactory(taskParameters, false /* don't want task host */);
createdTask = _taskFactory.CreateTaskInstance(ElementLocation.Create("MSBUILD"), null, new MockHost(), null,
#if FEATURE_APPDOMAIN
new AppDomainSetup(),
#endif
false);
Assert.NotNull(createdTask);
Assert.IsType<TaskHostTask>(createdTask);
}
finally
{
if (createdTask != null)
{
_taskFactory.CleanupTask(createdTask);
}
}
}
/// <summary>
/// Verify a good task that uses the task host can be created when passed task host
/// parameters that explicitly do not match the current process.
/// </summary>
[Fact]
[Trait("Category", "mono-osx-failing")]
public void VerifyNonmatchingTaskParametersLaunchTaskHost()
{
ITask createdTask = null;
try
{
IDictionary<string, string> taskParameters = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
taskParameters.Add(XMakeAttributes.runtime, XMakeAttributes.MSBuildRuntimeValues.clr2);
taskParameters.Add(XMakeAttributes.architecture, XMakeAttributes.MSBuildArchitectureValues.any);
createdTask = _taskFactory.CreateTaskInstance(ElementLocation.Create("MSBUILD"), null, new MockHost(), taskParameters,
#if FEATURE_APPDOMAIN
new AppDomainSetup(),
#endif
false);
Assert.NotNull(createdTask);
Assert.IsType<TaskHostTask>(createdTask);
}
finally
{
if (createdTask != null)
{
_taskFactory.CleanupTask(createdTask);
}
}
}
/// <summary>
/// Verify a good task that uses the task host can be created when passed task host
/// parameters that explicitly do not match the current process.
/// </summary>
[Fact]
[Trait("Category", "mono-osx-failing")]
public void VerifyNonmatchingParametersLaunchTaskHost()
{
ITask createdTask = null;
try
{
IDictionary<string, string> factoryParameters = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
factoryParameters.Add(XMakeAttributes.runtime, XMakeAttributes.MSBuildRuntimeValues.clr2);
SetupTaskFactory(factoryParameters, false /* don't want task host */);
IDictionary<string, string> taskParameters = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
taskParameters.Add(XMakeAttributes.architecture, XMakeAttributes.MSBuildArchitectureValues.any);
createdTask = _taskFactory.CreateTaskInstance(ElementLocation.Create("MSBUILD"), null, new MockHost(), taskParameters,
#if FEATURE_APPDOMAIN
new AppDomainSetup(),
#endif
false);
Assert.NotNull(createdTask);
Assert.IsType<TaskHostTask>(createdTask);
}
finally
{
if (createdTask != null)
{
_taskFactory.CleanupTask(createdTask);
}
}
}
/// <summary>
/// Verify a good task that uses the task host can be created when the task factory is
/// explicitly instructed to launch the task host.
/// </summary>
[Fact]
public void VerifyExplicitlyLaunchTaskHost()
{
ITask createdTask = null;
try
{
SetupTaskFactory(null, true /* want task host */);
createdTask = _taskFactory.CreateTaskInstance(ElementLocation.Create("MSBUILD"), null, new MockHost(), null,
#if FEATURE_APPDOMAIN
new AppDomainSetup(),
#endif
false);
Assert.NotNull(createdTask);
Assert.IsType<TaskHostTask>(createdTask);
}
finally
{
if (createdTask != null)
{
_taskFactory.CleanupTask(createdTask);
}
}
}
/// <summary>
/// Verify a good task that uses the task host can be created when the task factory is
/// explicitly instructed to launch the task host.
/// </summary>
[Fact]
[Trait("Category", "mono-osx-failing")]
public void VerifyExplicitlyLaunchTaskHostEvenIfParametersMatch1()
{
ITask createdTask = null;
try
{
IDictionary<string, string> taskParameters = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
taskParameters.Add(XMakeAttributes.runtime, XMakeAttributes.MSBuildRuntimeValues.any);
taskParameters.Add(XMakeAttributes.architecture, XMakeAttributes.MSBuildArchitectureValues.any);
SetupTaskFactory(taskParameters, true /* want task host */);
createdTask = _taskFactory.CreateTaskInstance(ElementLocation.Create("MSBUILD"), null, new MockHost(), null,
#if FEATURE_APPDOMAIN
new AppDomainSetup(),
#endif
false);
Assert.NotNull(createdTask);
Assert.IsType<TaskHostTask>(createdTask);
}
finally
{
if (createdTask != null)
{
_taskFactory.CleanupTask(createdTask);
}
}
}
/// <summary>
/// Verify a good task that uses the task host can be created when the task factory is
/// explicitly instructed to launch the task host.
/// </summary>
[Fact]
[Trait("Category", "mono-osx-failing")]
public void VerifyExplicitlyLaunchTaskHostEvenIfParametersMatch2()
{
ITask createdTask = null;
try
{
SetupTaskFactory(null, true /* want task host */);
IDictionary<string, string> taskParameters = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
taskParameters.Add(XMakeAttributes.runtime, XMakeAttributes.MSBuildRuntimeValues.any);
taskParameters.Add(XMakeAttributes.architecture, XMakeAttributes.MSBuildArchitectureValues.any);
createdTask = _taskFactory.CreateTaskInstance(ElementLocation.Create("MSBUILD"), null, new MockHost(), taskParameters,
#if FEATURE_APPDOMAIN
new AppDomainSetup(),
#endif
false);
Assert.NotNull(createdTask);
Assert.IsType<TaskHostTask>(createdTask);
}
finally
{
if (createdTask != null)
{
_taskFactory.CleanupTask(createdTask);
}
}
}
/// <summary>
/// Verify a good task that uses the task host can be created when the task factory is
/// explicitly instructed to launch the task host.
/// </summary>
[Fact]
[Trait("Category", "mono-osx-failing")]
public void VerifySameFactoryCanGenerateDifferentTaskInstances()
{
ITask createdTask = null;
IDictionary<string, string> factoryParameters = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
factoryParameters.Add(XMakeAttributes.runtime, XMakeAttributes.MSBuildRuntimeValues.any);
factoryParameters.Add(XMakeAttributes.architecture, XMakeAttributes.MSBuildArchitectureValues.any);
SetupTaskFactory(factoryParameters, explicitlyLaunchTaskHost: false);
try
{
// #1: don't launch task host
createdTask = _taskFactory.CreateTaskInstance(ElementLocation.Create("MSBUILD"), null, new MockHost(), null,
#if FEATURE_APPDOMAIN
new AppDomainSetup(),
#endif
false);
Assert.NotNull(createdTask);
Assert.IsNotType<TaskHostTask>(createdTask);
}
finally
{
if (createdTask != null)
{
_taskFactory.CleanupTask(createdTask);
}
}
try
{
// #2: launch task host
var taskParameters = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
taskParameters.Add(XMakeAttributes.runtime, XMakeAttributes.MSBuildRuntimeValues.clr2);
taskParameters.Add(XMakeAttributes.architecture, XMakeAttributes.MSBuildArchitectureValues.currentArchitecture);
createdTask = _taskFactory.CreateTaskInstance(ElementLocation.Create("MSBUILD"), null, new MockHost(), taskParameters,
#if FEATURE_APPDOMAIN
new AppDomainSetup(),
#endif
false);
Assert.NotNull(createdTask);
Assert.IsType<TaskHostTask>(createdTask);
}
finally
{
if (createdTask != null)
{
_taskFactory.CleanupTask(createdTask);
}
}
}
/// <summary>
/// Abstract out the creation of the new AssemblyTaskFactory with default task, and
/// with some basic validation.
/// </summary>
private void SetupTaskFactory(IDictionary<string, string> factoryParameters, bool explicitlyLaunchTaskHost)
{
_taskFactory = new AssemblyTaskFactory();
#if FEATURE_ASSEMBLY_LOCATION
_loadInfo = AssemblyLoadInfo.Create(null, Assembly.GetAssembly(typeof(TaskToTestFactories)).Location);
#else
_loadInfo = AssemblyLoadInfo.Create(typeof(TaskToTestFactories).GetTypeInfo().Assembly.FullName, null);
#endif
_loadedType = _taskFactory.InitializeFactory(_loadInfo, "TaskToTestFactories", new Dictionary<string, TaskPropertyInfo>(), string.Empty, factoryParameters, explicitlyLaunchTaskHost, null, ElementLocation.Create("NONE"), String.Empty);
Assert.True(_loadedType.Assembly.Equals(_loadInfo)); // "Expected the AssemblyLoadInfo to be equal"
}
#endregion
#region InternalClasses
/// <summary>
/// Create a task which can be used to test the factories
/// </summary>
public class TaskToTestFactories
#if FEATURE_APPDOMAIN
: AppDomainIsolatedTask
#else
: Task
#endif
{
/// <summary>
/// Give a parameter which can be considered expected
/// </summary>
public string ExpectedParameter
{
get;
set;
}
/// <summary>
/// Expect not to find this parameter as it is internal
/// </summary>
internal string NotExpected
{
get;
set;
}
/// <summary>
/// Execute the test
/// </summary>
public override bool Execute()
{
return true;
}
}
#endregion
}
}
| |
using Lucene.Net.Diagnostics;
using Lucene.Net.Support;
using System;
using System.Diagnostics.CodeAnalysis;
using System.IO;
namespace Lucene.Net.Search
{
/*
* 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.
*/
//Used to hold non-generic nested types
public static class FieldValueHitQueue
{
// had to change from internal to public, due to public accessability of FieldValueHitQueue
public class Entry : ScoreDoc
{
public int Slot { get; set; } // LUCENENET NOTE: For some reason, this was not made readonly in the original
public Entry(int slot, int doc, float score)
: base(doc, score)
{
this.Slot = slot;
}
public override string ToString()
{
return "slot:" + Slot + " " + base.ToString();
}
}
/// <summary> An implementation of <see cref="FieldValueHitQueue" /> which is optimized in case
/// there is just one comparer.
/// </summary>
internal sealed class OneComparerFieldValueHitQueue<T> : FieldValueHitQueue<T>
where T : FieldValueHitQueue.Entry
{
private int oneReverseMul;
public OneComparerFieldValueHitQueue(SortField[] fields, int size)
: base(fields, size)
{
if (fields.Length == 0)
{
throw new ArgumentException("Sort must contain at least one field");
}
SortField field = fields[0];
SetComparer(0, field.GetComparer(size, 0));
oneReverseMul = field.reverse ? -1 : 1;
ReverseMul[0] = oneReverseMul;
}
/// <summary> Returns whether <c>a</c> is less relevant than <c>b</c>.</summary>
/// <param name="hitA">ScoreDoc</param>
/// <param name="hitB">ScoreDoc</param>
/// <returns><c>true</c> if document <c>a</c> should be sorted after document <c>b</c>.</returns>
protected internal override bool LessThan(T hitA, T hitB)
{
if (Debugging.AssertsEnabled)
{
Debugging.Assert(hitA != hitB);
Debugging.Assert(hitA.Slot != hitB.Slot);
}
int c = oneReverseMul * m_firstComparer.Compare(hitA.Slot, hitB.Slot);
if (c != 0)
{
return c > 0;
}
// avoid random sort order that could lead to duplicates (bug #31241):
return hitA.Doc > hitB.Doc;
}
}
/// <summary> An implementation of <see cref="FieldValueHitQueue" /> which is optimized in case
/// there is more than one comparer.
/// </summary>
internal sealed class MultiComparersFieldValueHitQueue<T> : FieldValueHitQueue<T>
where T : FieldValueHitQueue.Entry
{
public MultiComparersFieldValueHitQueue(SortField[] fields, int size)
: base(fields, size)
{
int numComparers = m_comparers.Length;
for (int i = 0; i < numComparers; ++i)
{
SortField field = fields[i];
m_reverseMul[i] = field.reverse ? -1 : 1;
SetComparer(i, field.GetComparer(size, i));
}
}
protected internal override bool LessThan(T hitA, T hitB)
{
if (Debugging.AssertsEnabled)
{
Debugging.Assert(hitA != hitB);
Debugging.Assert(hitA.Slot != hitB.Slot);
}
int numComparers = m_comparers.Length;
for (int i = 0; i < numComparers; ++i)
{
int c = m_reverseMul[i] * m_comparers[i].Compare(hitA.Slot, hitB.Slot);
if (c != 0)
{
// Short circuit
return c > 0;
}
}
// avoid random sort order that could lead to duplicates (bug #31241):
return hitA.Doc > hitB.Doc;
}
}
/// <summary> Creates a hit queue sorted by the given list of fields.
/// <para/><b>NOTE</b>: The instances returned by this method
/// pre-allocate a full array of length <c>numHits</c>.
/// </summary>
/// <param name="fields"><see cref="SortField"/> array we are sorting by in priority order (highest
/// priority first); cannot be <c>null</c> or empty
/// </param>
/// <param name="size">The number of hits to retain. Must be greater than zero.
/// </param>
/// <exception cref="IOException">If there is a low-level IO error</exception>
public static FieldValueHitQueue<T> Create<T>(SortField[] fields, int size)
where T : FieldValueHitQueue.Entry
{
if (fields.Length == 0)
{
throw new ArgumentException("Sort must contain at least one field");
}
if (fields.Length == 1)
{
return new FieldValueHitQueue.OneComparerFieldValueHitQueue<T>(fields, size);
}
else
{
return new FieldValueHitQueue.MultiComparersFieldValueHitQueue<T>(fields, size);
}
}
}
/// <summary>
/// Expert: A hit queue for sorting by hits by terms in more than one field.
/// Uses <c>FieldCache.DEFAULT</c> for maintaining
/// internal term lookup tables.
/// <para/>
/// @lucene.experimental
/// @since 2.9 </summary>
/// <seealso cref="IndexSearcher.Search(Query,Filter,int,Sort)"/>
/// <seealso cref="FieldCache"/>
public abstract class FieldValueHitQueue<T> : Util.PriorityQueue<T>
where T : FieldValueHitQueue.Entry
{
// prevent instantiation and extension.
internal FieldValueHitQueue(SortField[] fields, int size)
: base(size)
{
// When we get here, fields.length is guaranteed to be > 0, therefore no
// need to check it again.
// All these are required by this class's API - need to return arrays.
// Therefore even in the case of a single comparer, create an array
// anyway.
this.m_fields = fields;
int numComparers = fields.Length;
m_comparers = new FieldComparer[numComparers];
m_reverseMul = new int[numComparers];
}
[WritableArray]
[SuppressMessage("Microsoft.Performance", "CA1819", Justification = "Lucene's design requires some writable array properties")]
public virtual FieldComparer[] Comparers => m_comparers;
[WritableArray]
[SuppressMessage("Microsoft.Performance", "CA1819", Justification = "Lucene's design requires some writable array properties")]
public virtual int[] ReverseMul => m_reverseMul;
public virtual void SetComparer(int pos, FieldComparer comparer)
{
if (pos == 0)
{
m_firstComparer = comparer;
}
m_comparers[pos] = comparer;
}
/// <summary>
/// Stores the sort criteria being used. </summary>
protected readonly SortField[] m_fields;
protected readonly FieldComparer[] m_comparers; // use setComparer to change this array
protected FieldComparer m_firstComparer; // this must always be equal to comparers[0]
protected readonly int[] m_reverseMul;
internal FieldComparer FirstComparer => this.m_firstComparer;
// LUCENENET NOTE: We don't need this declaration because we are using
// a generic constraint on T
//public abstract bool LessThan(FieldValueHitQueue.Entry a, FieldValueHitQueue.Entry b);
/// <summary>
/// Given a queue <see cref="FieldValueHitQueue.Entry"/>, creates a corresponding <see cref="FieldDoc"/>
/// that contains the values used to sort the given document.
/// These values are not the raw values out of the index, but the internal
/// representation of them. This is so the given search hit can be collated by
/// a MultiSearcher with other search hits.
/// </summary>
/// <param name="entry"> The <see cref="FieldValueHitQueue.Entry"/> used to create a <see cref="FieldDoc"/> </param>
/// <returns> The newly created <see cref="FieldDoc"/> </returns>
/// <seealso cref="IndexSearcher.Search(Query,Filter,int,Sort)"/>
internal virtual FieldDoc FillFields(FieldValueHitQueue.Entry entry)
{
int n = m_comparers.Length;
IComparable[] fields = new IComparable[n];
for (int i = 0; i < n; ++i)
{
fields[i] = m_comparers[i][entry.Slot];
}
//if (maxscore > 1.0f) doc.score /= maxscore; // normalize scores
return new FieldDoc(entry.Doc, entry.Score, fields);
}
/// <summary>
/// Returns the <see cref="SortField"/>s being used by this hit queue. </summary>
[WritableArray]
[SuppressMessage("Microsoft.Performance", "CA1819", Justification = "Lucene's design requires some writable array properties")]
internal virtual SortField[] Fields => m_fields;
}
}
| |
namespace XenAdmin.Dialogs
{
partial class NewDiskDialog
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(NewDiskDialog));
this.DiskSizeNumericUpDown = new System.Windows.Forms.NumericUpDown();
this.SrListBox = new XenAdmin.Controls.SrPicker();
this.GbLabel = new System.Windows.Forms.Label();
this.CloseButton = new System.Windows.Forms.Button();
this.OkButton = new System.Windows.Forms.Button();
this.NameTextBox = new System.Windows.Forms.TextBox();
this.label2 = new System.Windows.Forms.Label();
this.DescriptionTextBox = new System.Windows.Forms.TextBox();
this.label3 = new System.Windows.Forms.Label();
this.label1 = new System.Windows.Forms.Label();
this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel();
this.panel1 = new System.Windows.Forms.FlowLayoutPanel();
this.label4 = new System.Windows.Forms.Label();
this.panel2 = new System.Windows.Forms.Panel();
this.comboBoxUnits = new System.Windows.Forms.ComboBox();
this.labelError = new System.Windows.Forms.Label();
this.pictureBoxError = new System.Windows.Forms.PictureBox();
this.label6 = new System.Windows.Forms.Label();
this.queuedBackgroundWorker1 = new XenCenterLib.QueuedBackgroundWorker();
((System.ComponentModel.ISupportInitialize)(this.DiskSizeNumericUpDown)).BeginInit();
this.tableLayoutPanel1.SuspendLayout();
this.panel1.SuspendLayout();
this.panel2.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxError)).BeginInit();
this.SuspendLayout();
//
// DiskSizeNumericUpDown
//
resources.ApplyResources(this.DiskSizeNumericUpDown, "DiskSizeNumericUpDown");
this.DiskSizeNumericUpDown.Maximum = new decimal(new int[] {
1000000000,
0,
0,
0});
this.DiskSizeNumericUpDown.Name = "DiskSizeNumericUpDown";
this.DiskSizeNumericUpDown.Value = new decimal(new int[] {
1,
0,
0,
0});
this.DiskSizeNumericUpDown.ValueChanged += new System.EventHandler(this.DiskSizeNumericUpDown_ValueChanged);
this.DiskSizeNumericUpDown.KeyUp += new System.Windows.Forms.KeyEventHandler(this.DiskSizeNumericUpDown_KeyUp);
//
// SrListBox
//
resources.ApplyResources(this.SrListBox, "SrListBox");
this.tableLayoutPanel1.SetColumnSpan(this.SrListBox, 3);
this.SrListBox.Connection = null;
this.SrListBox.Name = "SrListBox";
//
// GbLabel
//
resources.ApplyResources(this.GbLabel, "GbLabel");
this.GbLabel.Name = "GbLabel";
//
// CloseButton
//
resources.ApplyResources(this.CloseButton, "CloseButton");
this.CloseButton.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.CloseButton.Name = "CloseButton";
this.CloseButton.UseVisualStyleBackColor = true;
this.CloseButton.Click += new System.EventHandler(this.CloseButton_Click);
//
// OkButton
//
resources.ApplyResources(this.OkButton, "OkButton");
this.OkButton.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.OkButton.Name = "OkButton";
this.OkButton.UseVisualStyleBackColor = true;
this.OkButton.Click += new System.EventHandler(this.OkButton_Click);
//
// NameTextBox
//
this.tableLayoutPanel1.SetColumnSpan(this.NameTextBox, 3);
resources.ApplyResources(this.NameTextBox, "NameTextBox");
this.NameTextBox.Name = "NameTextBox";
this.NameTextBox.TextChanged += new System.EventHandler(this.NameTextBox_TextChanged);
//
// label2
//
resources.ApplyResources(this.label2, "label2");
this.label2.Name = "label2";
//
// DescriptionTextBox
//
this.tableLayoutPanel1.SetColumnSpan(this.DescriptionTextBox, 3);
resources.ApplyResources(this.DescriptionTextBox, "DescriptionTextBox");
this.DescriptionTextBox.Name = "DescriptionTextBox";
this.DescriptionTextBox.TextChanged += new System.EventHandler(this.NameTextBox_TextChanged);
//
// label3
//
resources.ApplyResources(this.label3, "label3");
this.label3.Name = "label3";
//
// label1
//
resources.ApplyResources(this.label1, "label1");
this.label1.Name = "label1";
//
// tableLayoutPanel1
//
resources.ApplyResources(this.tableLayoutPanel1, "tableLayoutPanel1");
this.tableLayoutPanel1.Controls.Add(this.label2, 0, 2);
this.tableLayoutPanel1.Controls.Add(this.label1, 0, 4);
this.tableLayoutPanel1.Controls.Add(this.NameTextBox, 1, 2);
this.tableLayoutPanel1.Controls.Add(this.DescriptionTextBox, 1, 3);
this.tableLayoutPanel1.Controls.Add(this.SrListBox, 1, 5);
this.tableLayoutPanel1.Controls.Add(this.label3, 0, 3);
this.tableLayoutPanel1.Controls.Add(this.DiskSizeNumericUpDown, 1, 4);
this.tableLayoutPanel1.Controls.Add(this.panel1, 1, 9);
this.tableLayoutPanel1.Controls.Add(this.label4, 0, 5);
this.tableLayoutPanel1.Controls.Add(this.panel2, 2, 4);
this.tableLayoutPanel1.Controls.Add(this.label6, 0, 1);
this.tableLayoutPanel1.Name = "tableLayoutPanel1";
//
// panel1
//
resources.ApplyResources(this.panel1, "panel1");
this.tableLayoutPanel1.SetColumnSpan(this.panel1, 3);
this.panel1.Controls.Add(this.CloseButton);
this.panel1.Controls.Add(this.OkButton);
this.panel1.Name = "panel1";
//
// label4
//
resources.ApplyResources(this.label4, "label4");
this.label4.Name = "label4";
//
// panel2
//
resources.ApplyResources(this.panel2, "panel2");
this.tableLayoutPanel1.SetColumnSpan(this.panel2, 2);
this.panel2.Controls.Add(this.comboBoxUnits);
this.panel2.Controls.Add(this.labelError);
this.panel2.Controls.Add(this.pictureBoxError);
this.panel2.Name = "panel2";
//
// comboBoxUnits
//
this.comboBoxUnits.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
resources.ApplyResources(this.comboBoxUnits, "comboBoxUnits");
this.comboBoxUnits.FormattingEnabled = true;
this.comboBoxUnits.Items.AddRange(new object[] {
resources.GetString("comboBoxUnits.Items"),
resources.GetString("comboBoxUnits.Items1")});
this.comboBoxUnits.Name = "comboBoxUnits";
//
// labelError
//
resources.ApplyResources(this.labelError, "labelError");
this.labelError.ForeColor = System.Drawing.Color.Red;
this.labelError.Name = "labelError";
//
// pictureBoxError
//
resources.ApplyResources(this.pictureBoxError, "pictureBoxError");
this.pictureBoxError.Name = "pictureBoxError";
this.pictureBoxError.TabStop = false;
//
// label6
//
resources.ApplyResources(this.label6, "label6");
this.tableLayoutPanel1.SetColumnSpan(this.label6, 4);
this.label6.Name = "label6";
//
// NewDiskDialog
//
this.AcceptButton = this.OkButton;
resources.ApplyResources(this, "$this");
this.CancelButton = this.CloseButton;
this.Controls.Add(this.tableLayoutPanel1);
this.Controls.Add(this.GbLabel);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Sizable;
this.Name = "NewDiskDialog";
((System.ComponentModel.ISupportInitialize)(this.DiskSizeNumericUpDown)).EndInit();
this.tableLayoutPanel1.ResumeLayout(false);
this.tableLayoutPanel1.PerformLayout();
this.panel1.ResumeLayout(false);
this.panel2.ResumeLayout(false);
this.panel2.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxError)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Label GbLabel;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Label label1;
public System.Windows.Forms.NumericUpDown DiskSizeNumericUpDown;
public XenAdmin.Controls.SrPicker SrListBox;
public System.Windows.Forms.Button CloseButton;
public System.Windows.Forms.Button OkButton;
public System.Windows.Forms.TextBox NameTextBox;
public System.Windows.Forms.TextBox DescriptionTextBox;
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1;
private System.Windows.Forms.FlowLayoutPanel panel1;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.Label labelError;
private System.Windows.Forms.PictureBox pictureBoxError;
private System.Windows.Forms.Panel panel2;
private System.Windows.Forms.Label label6;
private System.Windows.Forms.ComboBox comboBoxUnits;
private XenCenterLib.QueuedBackgroundWorker queuedBackgroundWorker1;
}
}
| |
using System;
using Org.BouncyCastle.Asn1;
using Org.BouncyCastle.Asn1.CryptoPro;
using Org.BouncyCastle.Asn1.Oiw;
using Org.BouncyCastle.Asn1.Pkcs;
using Org.BouncyCastle.Asn1.Sec;
using Org.BouncyCastle.Asn1.X509;
using Org.BouncyCastle.Asn1.X9;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Utilities;
namespace Org.BouncyCastle.Pkcs
{
public sealed class PrivateKeyInfoFactory
{
private PrivateKeyInfoFactory()
{
}
public static PrivateKeyInfo CreatePrivateKeyInfo(
IAsymmetricKeyParameter key)
{
if (key == null)
throw new ArgumentNullException("key");
if (!key.IsPrivate)
throw new ArgumentException(@"Public key passed - private key expected", "key");
if (key is ElGamalPrivateKeyParameters)
{
ElGamalPrivateKeyParameters _key = (ElGamalPrivateKeyParameters)key;
return new PrivateKeyInfo(
new AlgorithmIdentifier(
OiwObjectIdentifiers.ElGamalAlgorithm,
new ElGamalParameter(
_key.Parameters.P,
_key.Parameters.G).ToAsn1Object()),
new DerInteger(_key.X));
}
if (key is DsaPrivateKeyParameters)
{
DsaPrivateKeyParameters _key = (DsaPrivateKeyParameters)key;
return new PrivateKeyInfo(
new AlgorithmIdentifier(
X9ObjectIdentifiers.IdDsa,
new DsaParameter(
_key.Parameters.P,
_key.Parameters.Q,
_key.Parameters.G).ToAsn1Object()),
new DerInteger(_key.X));
}
if (key is DHPrivateKeyParameters)
{
DHPrivateKeyParameters _key = (DHPrivateKeyParameters)key;
DHParameter p = new DHParameter(
_key.Parameters.P, _key.Parameters.G, _key.Parameters.L);
return new PrivateKeyInfo(
new AlgorithmIdentifier(_key.AlgorithmOid, p.ToAsn1Object()),
new DerInteger(_key.X));
}
if (key is RsaKeyParameters)
{
AlgorithmIdentifier algID = new AlgorithmIdentifier(
PkcsObjectIdentifiers.RsaEncryption, DerNull.Instance);
RsaPrivateKeyStructure keyStruct;
if (key is RsaPrivateCrtKeyParameters)
{
RsaPrivateCrtKeyParameters _key = (RsaPrivateCrtKeyParameters)key;
keyStruct = new RsaPrivateKeyStructure(
_key.Modulus,
_key.PublicExponent,
_key.Exponent,
_key.P,
_key.Q,
_key.DP,
_key.DQ,
_key.QInv);
}
else
{
RsaKeyParameters _key = (RsaKeyParameters) key;
keyStruct = new RsaPrivateKeyStructure(
_key.Modulus,
BigInteger.Zero,
_key.Exponent,
BigInteger.Zero,
BigInteger.Zero,
BigInteger.Zero,
BigInteger.Zero,
BigInteger.Zero);
}
return new PrivateKeyInfo(algID, keyStruct.ToAsn1Object());
}
if (key is ECPrivateKeyParameters)
{
ECPrivateKeyParameters _key = (ECPrivateKeyParameters)key;
AlgorithmIdentifier algID;
ECPrivateKeyStructure ec;
if (_key.AlgorithmName == "ECGOST3410")
{
if (_key.PublicKeyParamSet == null)
throw Platform.CreateNotImplementedException("Not a CryptoPro parameter set");
Gost3410PublicKeyAlgParameters gostParams = new Gost3410PublicKeyAlgParameters(
_key.PublicKeyParamSet, CryptoProObjectIdentifiers.GostR3411x94CryptoProParamSet);
algID = new AlgorithmIdentifier(
CryptoProObjectIdentifiers.GostR3410x2001,
gostParams.ToAsn1Object());
// TODO Do we need to pass any parameters here?
ec = new ECPrivateKeyStructure(_key.D);
}
else
{
X962Parameters x962;
if (_key.PublicKeyParamSet == null)
{
ECDomainParameters kp = _key.Parameters;
X9ECParameters ecP = new X9ECParameters(kp.Curve, kp.G, kp.N, kp.H, kp.GetSeed());
x962 = new X962Parameters(ecP);
}
else
{
x962 = new X962Parameters(_key.PublicKeyParamSet);
}
Asn1Object x962Object = x962.ToAsn1Object();
// TODO Possible to pass the publicKey bitstring here?
ec = new ECPrivateKeyStructure(_key.D, x962Object);
algID = new AlgorithmIdentifier(X9ObjectIdentifiers.IdECPublicKey, x962Object);
}
return new PrivateKeyInfo(algID, ec.ToAsn1Object());
}
if (key is Gost3410PrivateKeyParameters)
{
Gost3410PrivateKeyParameters _key = (Gost3410PrivateKeyParameters)key;
if (_key.PublicKeyParamSet == null)
throw Platform.CreateNotImplementedException("Not a CryptoPro parameter set");
byte[] keyEnc = _key.X.ToByteArrayUnsigned();
byte[] keyBytes = new byte[keyEnc.Length];
for (int i = 0; i != keyBytes.Length; i++)
{
keyBytes[i] = keyEnc[keyEnc.Length - 1 - i]; // must be little endian
}
Gost3410PublicKeyAlgParameters algParams = new Gost3410PublicKeyAlgParameters(
_key.PublicKeyParamSet, CryptoProObjectIdentifiers.GostR3411x94CryptoProParamSet, null);
AlgorithmIdentifier algID = new AlgorithmIdentifier(
CryptoProObjectIdentifiers.GostR3410x94,
algParams.ToAsn1Object());
return new PrivateKeyInfo(algID, new DerOctetString(keyBytes));
}
throw new ArgumentException("Class provided is not convertible: " + key.GetType().FullName);
}
public static PrivateKeyInfo CreatePrivateKeyInfo(
char[] passPhrase,
EncryptedPrivateKeyInfo encInfo)
{
return CreatePrivateKeyInfo(passPhrase, false, encInfo);
}
public static PrivateKeyInfo CreatePrivateKeyInfo(
char[] passPhrase,
bool wrongPkcs12Zero,
EncryptedPrivateKeyInfo encInfo)
{
AlgorithmIdentifier algID = encInfo.EncryptionAlgorithm;
IBufferedCipher cipher = PbeUtilities.CreateEngine(algID) as IBufferedCipher;
if (cipher == null)
{
// TODO Throw exception?
}
ICipherParameters keyParameters = PbeUtilities.GenerateCipherParameters(
algID, passPhrase, wrongPkcs12Zero);
cipher.Init(false, keyParameters);
byte[] keyBytes = encInfo.GetEncryptedData();
byte[] encoding = cipher.DoFinal(keyBytes);
Asn1Object asn1Data = Asn1Object.FromByteArray(encoding);
return PrivateKeyInfo.GetInstance(asn1Data);
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using Analyzer.Utilities;
using Analyzer.Utilities.Extensions;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
namespace Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines
{
/// <summary>
/// CA1710: Identifiers should have correct suffix
/// </summary>
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public sealed class IdentifiersShouldHaveCorrectSuffixAnalyzer : DiagnosticAnalyzer
{
internal const string RuleId = "CA1710";
private static readonly LocalizableString s_localizableTitle = new LocalizableResourceString(nameof(MicrosoftCodeQualityAnalyzersResources.IdentifiersShouldHaveCorrectSuffixTitle), MicrosoftCodeQualityAnalyzersResources.ResourceManager, typeof(MicrosoftCodeQualityAnalyzersResources));
private static readonly LocalizableString s_localizableMessageDefault = new LocalizableResourceString(nameof(MicrosoftCodeQualityAnalyzersResources.IdentifiersShouldHaveCorrectSuffixMessageDefault), MicrosoftCodeQualityAnalyzersResources.ResourceManager, typeof(MicrosoftCodeQualityAnalyzersResources));
private static readonly LocalizableString s_localizableMessageSpecialCollection = new LocalizableResourceString(nameof(MicrosoftCodeQualityAnalyzersResources.IdentifiersShouldHaveCorrectSuffixMessageSpecialCollection), MicrosoftCodeQualityAnalyzersResources.ResourceManager, typeof(MicrosoftCodeQualityAnalyzersResources));
private static readonly LocalizableString s_localizableDescription = new LocalizableResourceString(nameof(MicrosoftCodeQualityAnalyzersResources.IdentifiersShouldHaveCorrectSuffixDescription), MicrosoftCodeQualityAnalyzersResources.ResourceManager, typeof(MicrosoftCodeQualityAnalyzersResources));
internal static DiagnosticDescriptor DefaultRule = DiagnosticDescriptorHelper.Create(RuleId,
s_localizableTitle,
s_localizableMessageDefault,
DiagnosticCategory.Naming,
RuleLevel.IdeHidden_BulkConfigurable,
description: s_localizableDescription,
isPortedFxCopRule: true,
isDataflowRule: false);
internal static DiagnosticDescriptor SpecialCollectionRule = DiagnosticDescriptorHelper.Create(RuleId,
s_localizableTitle,
s_localizableMessageSpecialCollection,
DiagnosticCategory.Naming,
RuleLevel.IdeHidden_BulkConfigurable,
description: s_localizableDescription,
isPortedFxCopRule: true,
isDataflowRule: false);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(DefaultRule, SpecialCollectionRule);
// Tuple says <TypeInheritedOrImplemented, AppropriateSuffix, Bool value saying if the suffix can `Collection` or the `AppropriateSuffix`>s
// The bool values are as mentioned in the Uri
private static readonly List<(string typeName, string suffix, bool canSuffixBeCollection)> s_baseTypesAndTheirSuffix = new List<(string, string, bool)>()
{
("System.Attribute", "Attribute", false),
("System.EventArgs", "EventArgs", false),
("System.Exception", "Exception", false),
("System.Collections.ICollection", "Collection", false),
("System.Collections.IDictionary", "Dictionary", false),
("System.Collections.IEnumerable", "Collection", false),
("System.Collections.Queue", "Queue", true),
("System.Collections.Stack", "Stack", true),
("System.Collections.Generic.Queue`1", "Queue", true),
("System.Collections.Generic.Stack`1", "Stack", true),
("System.Collections.Generic.ICollection`1", "Collection", false),
("System.Collections.Generic.IDictionary`2", "Dictionary", false),
("System.Collections.Generic.IReadOnlyDictionary`2", "Dictionary", false),
("System.Data.DataSet", "DataSet", false),
("System.Data.DataTable", "DataTable", true),
("System.IO.Stream", "Stream", false),
("System.Security.IPermission","Permission", false),
("System.Security.Policy.IMembershipCondition", "Condition", false)
};
public override void Initialize(AnalysisContext context)
{
context.EnableConcurrentExecution();
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
context.RegisterCompilationStartAction(AnalyzeCompilationStart);
}
private static void AnalyzeCompilationStart(CompilationStartAnalysisContext context)
{
var wellKnownTypeProvider = WellKnownTypeProvider.GetOrCreate(context.Compilation);
var baseTypeSuffixMapBuilder = ImmutableDictionary.CreateBuilder<INamedTypeSymbol, SuffixInfo>();
var interfaceTypeSuffixMapBuilder = ImmutableDictionary.CreateBuilder<INamedTypeSymbol, SuffixInfo>();
foreach (var (typeName, suffix, canSuffixBeCollection) in s_baseTypesAndTheirSuffix)
{
var wellKnownNamedType = wellKnownTypeProvider.GetOrCreateTypeByMetadataName(typeName);
if (wellKnownNamedType != null && wellKnownNamedType.OriginalDefinition != null)
{
// If the type is interface
if (wellKnownNamedType.OriginalDefinition.TypeKind == TypeKind.Interface)
{
interfaceTypeSuffixMapBuilder.Add(wellKnownNamedType.OriginalDefinition, SuffixInfo.Create(suffix, canSuffixBeCollection));
}
else
{
baseTypeSuffixMapBuilder.Add(wellKnownNamedType.OriginalDefinition, SuffixInfo.Create(suffix, canSuffixBeCollection));
}
}
}
var baseTypeSuffixMap = baseTypeSuffixMapBuilder.ToImmutable();
var interfaceTypeSuffixMap = interfaceTypeSuffixMapBuilder.ToImmutable();
context.RegisterSymbolAction((saContext) =>
{
var namedTypeSymbol = (INamedTypeSymbol)saContext.Symbol;
if (!saContext.Options.MatchesConfiguredVisibility(DefaultRule, namedTypeSymbol, saContext.Compilation, saContext.CancellationToken))
{
Debug.Assert(!saContext.Options.MatchesConfiguredVisibility(SpecialCollectionRule, namedTypeSymbol, saContext.Compilation, saContext.CancellationToken));
return;
}
Debug.Assert(saContext.Options.MatchesConfiguredVisibility(SpecialCollectionRule, namedTypeSymbol, saContext.Compilation, saContext.CancellationToken));
var excludeIndirectBaseTypes = context.Options.GetBoolOptionValue(EditorConfigOptionNames.ExcludeIndirectBaseTypes, DefaultRule,
namedTypeSymbol, context.Compilation, defaultValue: true, cancellationToken: context.CancellationToken);
var baseTypes = excludeIndirectBaseTypes
? namedTypeSymbol.BaseType != null ? ImmutableArray.Create(namedTypeSymbol.BaseType) : ImmutableArray<INamedTypeSymbol>.Empty
: namedTypeSymbol.GetBaseTypes();
var userTypeSuffixMap = context.Options.GetAdditionalRequiredSuffixesOption(DefaultRule, saContext.Symbol,
context.Compilation, context.CancellationToken);
if (TryGetTypeSuffix(baseTypes, baseTypeSuffixMap, userTypeSuffixMap, out var typeSuffixInfo))
{
// SpecialCollectionRule - Rename 'LastInFirstOut<T>' to end in either 'Collection' or 'Stack'.
// DefaultRule - Rename 'MyStringObjectHashtable' to end in 'Dictionary'.
var rule = typeSuffixInfo.CanSuffixBeCollection ? SpecialCollectionRule : DefaultRule;
if ((typeSuffixInfo.CanSuffixBeCollection && !namedTypeSymbol.Name.EndsWith("Collection", StringComparison.Ordinal) && !namedTypeSymbol.Name.EndsWith(typeSuffixInfo.Suffix, StringComparison.Ordinal)) ||
(!typeSuffixInfo.CanSuffixBeCollection && !namedTypeSymbol.Name.EndsWith(typeSuffixInfo.Suffix, StringComparison.Ordinal)))
{
saContext.ReportDiagnostic(namedTypeSymbol.CreateDiagnostic(rule, namedTypeSymbol.ToDisplayString(), typeSuffixInfo.Suffix));
}
return;
}
var interfaces = excludeIndirectBaseTypes
? namedTypeSymbol.Interfaces
: namedTypeSymbol.AllInterfaces;
if (TryGetTypeSuffix(interfaces, interfaceTypeSuffixMap, userTypeSuffixMap, out var interfaceSuffixInfo) &&
!namedTypeSymbol.Name.EndsWith(interfaceSuffixInfo.Suffix, StringComparison.Ordinal))
{
saContext.ReportDiagnostic(namedTypeSymbol.CreateDiagnostic(DefaultRule, namedTypeSymbol.ToDisplayString(), interfaceSuffixInfo.Suffix));
}
}
, SymbolKind.NamedType);
var eventArgsType = wellKnownTypeProvider.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemEventArgs);
if (eventArgsType != null)
{
context.RegisterSymbolAction((saContext) =>
{
const string eventHandlerString = "EventHandler";
var eventSymbol = (IEventSymbol)saContext.Symbol;
if (!eventSymbol.Type.Name.EndsWith(eventHandlerString, StringComparison.Ordinal) &&
eventSymbol.Type.IsInSource() &&
eventSymbol.Type.TypeKind == TypeKind.Delegate &&
((INamedTypeSymbol)eventSymbol.Type).DelegateInvokeMethod?.HasEventHandlerSignature(eventArgsType) == true)
{
saContext.ReportDiagnostic(eventSymbol.CreateDiagnostic(DefaultRule, eventSymbol.Type.Name, eventHandlerString));
}
},
SymbolKind.Event);
}
}
private static bool TryGetTypeSuffix(IEnumerable<INamedTypeSymbol> typeSymbols, ImmutableDictionary<INamedTypeSymbol, SuffixInfo> hardcodedMap,
SymbolNamesWithValueOption<string?> userMap, [NotNullWhen(true)] out SuffixInfo? suffixInfo)
{
foreach (var type in typeSymbols)
{
// User specific mapping has higher priority than hardcoded one
if (userMap.TryGetValue(type.OriginalDefinition, out var suffix) &&
!RoslynString.IsNullOrWhiteSpace(suffix))
{
suffixInfo = SuffixInfo.Create(suffix, canSuffixBeCollection: false);
return true;
}
if (hardcodedMap.TryGetValue(type.OriginalDefinition, out suffixInfo))
{
return true;
}
}
suffixInfo = null;
return false;
}
}
internal class SuffixInfo
{
public string Suffix { get; private set; }
public bool CanSuffixBeCollection { get; private set; }
private SuffixInfo(
string suffix,
bool canSuffixBeCollection)
{
Suffix = suffix;
CanSuffixBeCollection = canSuffixBeCollection;
}
internal static SuffixInfo Create(string suffix, bool canSuffixBeCollection)
{
return new SuffixInfo(suffix, canSuffixBeCollection);
}
}
}
| |
/*
Copyright 2014-2022 SourceGear, LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml;
public enum TFM
{
NONE,
UWP,
NETSTANDARD20,
NET461,
NET60,
}
public static class common
{
public const string ROOT_NAME = "SQLitePCLRaw";
public static string AsString(this TFM e)
{
switch (e)
{
case TFM.NONE: throw new Exception("TFM.NONE.AsString()");
case TFM.UWP: return "uap10.0";
case TFM.NETSTANDARD20: return "netstandard2.0";
case TFM.NET461: return "net461";
case TFM.NET60: return "net6.0";
default:
throw new NotImplementedException(string.Format("TFM.AsString for {0}", e));
}
}
public static void write_nuspec_file_entry(string src, string target, XmlWriter f)
{
f.WriteStartElement("file");
f.WriteAttributeString("src", src);
f.WriteAttributeString("target", target);
f.WriteEndElement(); // file
}
public static void write_empty(XmlWriter f, TFM tfm)
{
f.WriteComment("empty directory in lib to avoid nuget adding a reference");
f.WriteStartElement("file");
f.WriteAttributeString("src", "_._");
f.WriteAttributeString("target", string.Format("lib/{0}/_._", tfm.AsString()));
f.WriteEndElement(); // file
}
const string PACKAGE_TAGS = "sqlite;xamarin";
public static void write_nuspec_common_metadata(
string id,
XmlWriter f
)
{
f.WriteAttributeString("minClientVersion", "2.12"); // TODO not sure this is right
f.WriteElementString("id", id);
f.WriteElementString("title", id);
f.WriteElementString("version", "$version$");
f.WriteElementString("authors", "$authors$");
f.WriteElementString("copyright", "$copyright$");
f.WriteElementString("requireLicenseAcceptance", "false");
write_license(f);
f.WriteStartElement("repository");
f.WriteAttributeString("type", "git");
f.WriteAttributeString("url", "https://github.com/ericsink/SQLitePCL.raw");
f.WriteEndElement(); // repository
f.WriteElementString("summary", "$summary$");
f.WriteElementString("tags", PACKAGE_TAGS);
}
public static XmlWriterSettings XmlWriterSettings_default()
{
var settings = new XmlWriterSettings();
settings.NewLineChars = "\n";
settings.Indent = true;
return settings;
}
public static void gen_dummy_csproj(string dir_proj, string id)
{
var settings = XmlWriterSettings_default();
settings.OmitXmlDeclaration = true;
using (XmlWriter f = XmlWriter.Create(Path.Combine(dir_proj, $"{id}.csproj"), settings))
{
f.WriteStartDocument();
f.WriteComment("Automatically generated");
f.WriteStartElement("Project");
f.WriteAttributeString("Sdk", "Microsoft.NET.Sdk");
f.WriteStartElement("PropertyGroup");
f.WriteElementString("TargetFramework", "netstandard2.0");
f.WriteElementString("NoBuild", "true");
f.WriteElementString("IncludeBuildOutput", "false");
f.WriteElementString("NuspecFile", $"{id}.nuspec");
f.WriteElementString("NuspecProperties", "version=$(version);src_path=$(src_path);cb_bin_path=$(cb_bin_path);authors=$(Authors);copyright=$(Copyright);summary=$(Description)");
f.WriteEndElement(); // PropertyGroup
f.WriteEndElement(); // Project
f.WriteEndDocument();
}
}
private static void write_license(XmlWriter f)
{
f.WriteStartElement("license");
f.WriteAttributeString("type", "expression");
f.WriteString("Apache-2.0");
f.WriteEndElement();
}
}
public static class gen
{
enum LibSuffix
{
DLL,
DYLIB,
SO,
A,
}
// in cb, the sqlcipher builds do not have the e_ prefix.
// we do this so we can continue to build v1.
// but in v2, we want things to be called e_sqlcipher.
static string AsString_basename_in_cb(this WhichLib e)
{
switch (e)
{
case WhichLib.E_SQLITE3: return "e_sqlite3";
case WhichLib.E_SQLCIPHER: return "e_sqlcipher"; // TODO no e_ prefix in cb yet
default:
throw new NotImplementedException(string.Format("WhichLib.AsString for {0}", e));
}
}
static string AsString_basename_in_nupkg(this WhichLib e)
{
switch (e)
{
case WhichLib.E_SQLITE3: return "e_sqlite3";
case WhichLib.E_SQLCIPHER: return "e_sqlcipher";
default:
throw new NotImplementedException(string.Format("WhichLib.AsString for {0}", e));
}
}
static string basename_to_libname(string basename, LibSuffix suffix)
{
switch (suffix)
{
case LibSuffix.DLL:
return $"{basename}.dll";
case LibSuffix.DYLIB:
return $"lib{basename}.dylib";
case LibSuffix.SO:
return $"lib{basename}.so";
case LibSuffix.A:
return $"{basename}.a";
default:
throw new NotImplementedException();
}
}
static string AsString_libname_in_nupkg(this WhichLib e, LibSuffix suffix)
{
var basename = e.AsString_basename_in_nupkg();
return basename_to_libname(basename, suffix);
}
static string AsString_libname_in_cb(this WhichLib e, LibSuffix suffix)
{
var basename = e.AsString_basename_in_cb();
return basename_to_libname(basename, suffix);
}
private static void write_nuspec_file_entry_native(string src, string rid, string filename, XmlWriter f)
{
common.write_nuspec_file_entry(
src,
string.Format("runtimes\\{0}\\native\\{1}", rid, filename),
f
);
}
private static void write_nuspec_file_entry_nativeassets(string src, string rid, TFM tfm, string filename, XmlWriter f)
{
common.write_nuspec_file_entry(
src,
string.Format("runtimes\\{0}\\nativeassets\\{1}\\{2}", rid, tfm.AsString(), filename),
f
);
}
static string make_cb_path_win(
WhichLib lib,
string toolset,
string flavor,
string arch
)
{
var dir_name = lib.AsString_basename_in_cb();
var lib_name = lib.AsString_libname_in_cb(LibSuffix.DLL);
return Path.Combine("$cb_bin_path$", dir_name, "win", toolset, flavor, arch, lib_name);
}
static string make_cb_path_linux(
WhichLib lib,
string cpu
)
{
var dir_name = lib.AsString_basename_in_cb();
var lib_name = lib.AsString_libname_in_cb(LibSuffix.SO);
return Path.Combine("$cb_bin_path$", dir_name, "linux", cpu, lib_name);
}
static string make_cb_path_wasm(
WhichLib lib
)
{
var dir_name = lib.AsString_basename_in_cb();
var lib_name = lib.AsString_libname_in_cb(LibSuffix.A);
return Path.Combine("$cb_bin_path$", dir_name, "wasm", lib_name);
}
static string make_cb_path_mac(
WhichLib lib,
string cpu
)
{
var dir_name = lib.AsString_basename_in_cb();
var lib_name = lib.AsString_libname_in_cb(LibSuffix.DYLIB);
return Path.Combine("$cb_bin_path$", dir_name, "mac", cpu, lib_name);
}
static void write_nuspec_file_entry_native_linux(
WhichLib lib,
string cpu_in_cb,
string rid,
XmlWriter f
)
{
var filename = lib.AsString_libname_in_nupkg(LibSuffix.SO);
write_nuspec_file_entry_native(
make_cb_path_linux(lib, cpu_in_cb),
rid,
filename,
f
);
}
static void write_nuspec_file_entry_native_wasm(
WhichLib lib,
XmlWriter f
)
{
var filename = lib.AsString_libname_in_nupkg(LibSuffix.A);
write_nuspec_file_entry_nativeassets(
make_cb_path_wasm(lib),
"browser-wasm",
TFM.NET60,
filename,
f
);
}
static void write_nuspec_file_entry_native_mac(
WhichLib lib,
string cpu_in_cb,
string rid,
XmlWriter f
)
{
var filename = lib.AsString_libname_in_nupkg(LibSuffix.DYLIB);
write_nuspec_file_entry_native(
make_cb_path_mac(lib, cpu_in_cb),
rid,
filename,
f
);
}
static void write_nuspec_file_entry_native_win(
WhichLib lib,
string toolset,
string flavor,
string cpu,
string rid,
XmlWriter f
)
{
var filename = lib.AsString_libname_in_nupkg(LibSuffix.DLL);
write_nuspec_file_entry_native(
make_cb_path_win(lib, toolset, flavor, cpu),
rid,
filename,
f
);
}
static void write_nuspec_file_entry_native_uwp(
WhichLib lib,
string toolset,
string flavor,
string cpu,
string rid,
XmlWriter f
)
{
var filename = lib.AsString_libname_in_nupkg(LibSuffix.DLL);
write_nuspec_file_entry_nativeassets(
make_cb_path_win(lib, toolset, flavor, cpu),
rid,
TFM.UWP,
filename,
f
);
}
static void write_nuspec_file_entries_from_cb(
WhichLib lib,
string win_toolset,
XmlWriter f
)
{
write_nuspec_file_entry_native_win(lib, win_toolset, "plain", "x86", "win-x86", f);
write_nuspec_file_entry_native_win(lib, win_toolset, "plain", "x64", "win-x64", f);
write_nuspec_file_entry_native_win(lib, win_toolset, "plain", "arm", "win-arm", f);
write_nuspec_file_entry_native_win(lib, win_toolset, "plain", "arm64", "win-arm64", f);
write_nuspec_file_entry_native_uwp(lib, win_toolset, "appcontainer", "arm64", "win10-arm64", f);
write_nuspec_file_entry_native_uwp(lib, win_toolset, "appcontainer", "arm", "win10-arm", f);
write_nuspec_file_entry_native_uwp(lib, win_toolset, "appcontainer", "x64", "win10-x64", f);
write_nuspec_file_entry_native_uwp(lib, win_toolset, "appcontainer", "x86", "win10-x86", f);
write_nuspec_file_entry_native_mac(lib, "x86_64", "osx-x64", f);
write_nuspec_file_entry_native_mac(lib, "arm64", "osx-arm64", f);
write_nuspec_file_entry_native_linux(lib, "x64", "linux-x64", f);
write_nuspec_file_entry_native_linux(lib, "x86", "linux-x86", f);
write_nuspec_file_entry_native_linux(lib, "armhf", "linux-arm", f);
write_nuspec_file_entry_native_linux(lib, "armsf", "linux-armel", f);
write_nuspec_file_entry_native_linux(lib, "arm64", "linux-arm64", f);
// TODO seems sad to put two copies of each musl, one for linux-musl- RID and one for alpine- RID
write_nuspec_file_entry_native_linux(lib, "musl-x64", "linux-musl-x64", f);
write_nuspec_file_entry_native_linux(lib, "musl-armhf", "linux-musl-arm", f);
write_nuspec_file_entry_native_linux(lib, "musl-arm64", "linux-musl-arm64", f);
// TODO seems sad to put two copies of each musl, one for linux-musl- RID and one for alpine- RID
write_nuspec_file_entry_native_linux(lib, "musl-x64", "alpine-x64", f);
write_nuspec_file_entry_native_linux(lib, "musl-armhf", "alpine-arm", f);
write_nuspec_file_entry_native_linux(lib, "musl-arm64", "alpine-arm64", f);
write_nuspec_file_entry_native_linux(lib, "mips64", "linux-mips64", f);
write_nuspec_file_entry_native_linux(lib, "s390x", "linux-s390x", f);
write_nuspec_file_entry_native_wasm(lib, f);
}
private static void gen_nuspec_lib_e_sqlite3(string dir_src)
{
string id = string.Format("{0}.lib.e_sqlite3", common.ROOT_NAME);
var settings = common.XmlWriterSettings_default();
settings.OmitXmlDeclaration = false;
var dir_proj = Path.Combine(dir_src, id);
Directory.CreateDirectory(dir_proj);
common.gen_dummy_csproj(dir_proj, id);
using (XmlWriter f = XmlWriter.Create(Path.Combine(dir_proj, string.Format("{0}.nuspec", id)), settings))
{
f.WriteStartDocument();
f.WriteComment("Automatically generated");
f.WriteStartElement("package", "http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd");
f.WriteStartElement("metadata");
common.write_nuspec_common_metadata(id, f);
f.WriteElementString("description", "This package contains platform-specific native code builds of SQLite for use with SQLitePCLRaw. To use this, you need SQLitePCLRaw.core as well as one of the SQLitePCLRaw.provider.* packages. Convenience packages are named SQLitePCLRaw.bundle_*.");
f.WriteEndElement(); // metadata
f.WriteStartElement("files");
write_nuspec_file_entries_from_cb(WhichLib.E_SQLITE3, "v142", f);
{
var tname = string.Format("{0}.targets", id);
Directory.CreateDirectory(Path.Combine(dir_proj, "net461"));
var path_targets = Path.Combine(dir_proj, "net461", tname);
var relpath_targets = Path.Combine(".", "net461", tname);
gen_nuget_targets(path_targets, WhichLib.E_SQLITE3);
common.write_nuspec_file_entry(
relpath_targets,
string.Format("buildTransitive\\{0}", TFM.NET461.AsString()),
f
);
}
{
var tname = string.Format("{0}.targets", id);
Directory.CreateDirectory(Path.Combine(dir_proj, "net6.0"));
var path_targets = Path.Combine(dir_proj, "net6.0", tname);
var relpath_targets = Path.Combine(".", "net6.0", tname);
gen_nuget_targets_wasm(path_targets, WhichLib.E_SQLITE3);
common.write_nuspec_file_entry(
relpath_targets,
string.Format("buildTransitive\\{0}", TFM.NET60.AsString()),
f
);
}
// TODO need a comment here to explain these
common.write_empty(f, TFM.NET461);
common.write_empty(f, TFM.NETSTANDARD20);
f.WriteEndElement(); // files
f.WriteEndElement(); // package
f.WriteEndDocument();
}
}
private static void gen_nuspec_lib_e_sqlcipher(string dir_src)
{
string id = string.Format("{0}.lib.e_sqlcipher", common.ROOT_NAME);
var settings = common.XmlWriterSettings_default();
settings.OmitXmlDeclaration = false;
var dir_proj = Path.Combine(dir_src, id);
Directory.CreateDirectory(dir_proj);
common.gen_dummy_csproj(dir_proj, id);
using (XmlWriter f = XmlWriter.Create(Path.Combine(dir_proj, string.Format("{0}.nuspec", id)), settings))
{
f.WriteStartDocument();
f.WriteComment("Automatically generated");
f.WriteStartElement("package", "http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd");
f.WriteStartElement("metadata");
common.write_nuspec_common_metadata(id, f);
f.WriteElementString("description", "This package contains platform-specific native code builds of SQLCipher (see sqlcipher/sqlcipher on GitHub) for use with SQLitePCLRaw. Note that these sqlcipher builds are unofficial and unsupported. For official sqlcipher builds, contact Zetetic. To use this package, you need SQLitePCLRaw.core as well as one of the SQLitePCLRaw.provider.* packages. Convenience packages are named SQLitePCLRaw.bundle_*.");
f.WriteEndElement(); // metadata
f.WriteStartElement("files");
write_nuspec_file_entries_from_cb(WhichLib.E_SQLCIPHER, "v142", f);
{
var tname = string.Format("{0}.targets", id);
Directory.CreateDirectory(Path.Combine(dir_proj, "net461"));
var path_targets = Path.Combine(dir_proj, "net461", tname);
var relpath_targets = Path.Combine(".", "net461", tname);
gen_nuget_targets(path_targets, WhichLib.E_SQLCIPHER);
common.write_nuspec_file_entry(
relpath_targets,
string.Format("buildTransitive\\{0}", TFM.NET461.AsString()),
f
);
}
{
var tname = string.Format("{0}.targets", id);
Directory.CreateDirectory(Path.Combine(dir_proj, "net6.0"));
var path_targets = Path.Combine(dir_proj, "net6.0", tname);
var relpath_targets = Path.Combine(".", "net6.0", tname);
gen_nuget_targets_wasm(path_targets, WhichLib.E_SQLCIPHER);
common.write_nuspec_file_entry(
relpath_targets,
string.Format("buildTransitive\\{0}", TFM.NET60.AsString()),
f
);
}
// TODO need a comment here to explain these
common.write_empty(f, TFM.NET461);
common.write_empty(f, TFM.NETSTANDARD20);
f.WriteEndElement(); // files
f.WriteEndElement(); // package
f.WriteEndDocument();
}
}
enum WhichLib
{
NONE,
E_SQLITE3,
E_SQLCIPHER,
}
static LibSuffix get_lib_suffix_from_rid(string rid)
{
var parts = rid.Split('-');
var front = parts[0].ToLower();
if (front.StartsWith("win"))
{
return LibSuffix.DLL;
}
else if (front.StartsWith("osx"))
{
return LibSuffix.DYLIB;
}
else if (
front.StartsWith("linux")
|| front.StartsWith("alpine")
)
{
return LibSuffix.SO;
}
else
{
throw new NotImplementedException();
}
}
static void write_nuget_target_item(
string rid,
WhichLib lib,
XmlWriter f
)
{
var suffix = get_lib_suffix_from_rid(rid);
var filename = lib.AsString_libname_in_nupkg(suffix);
f.WriteStartElement("Content");
f.WriteAttributeString("Include", string.Format("$(MSBuildThisFileDirectory)..\\..\\runtimes\\{0}\\native\\{1}", rid, filename));
f.WriteElementString("Link", string.Format("runtimes\\{0}\\native\\{1}", rid, filename));
f.WriteElementString("CopyToOutputDirectory", "PreserveNewest");
f.WriteElementString("Pack", "false");
f.WriteEndElement(); // Content
}
private static void gen_nuget_targets(string dest, WhichLib lib)
{
var settings = common.XmlWriterSettings_default();
settings.OmitXmlDeclaration = false;
using (XmlWriter f = XmlWriter.Create(dest, settings))
{
f.WriteStartDocument();
f.WriteComment("Automatically generated");
f.WriteStartElement("Project", "http://schemas.microsoft.com/developer/msbuild/2003");
f.WriteAttributeString("ToolsVersion", "4.0");
f.WriteStartElement("ItemGroup");
f.WriteAttributeString("Condition", " '$(RuntimeIdentifier)' == '' AND '$(OS)' == 'Windows_NT' ");
write_nuget_target_item("win-x86", lib, f);
write_nuget_target_item("win-x64", lib, f);
write_nuget_target_item("win-arm", lib, f);
f.WriteEndElement(); // ItemGroup
f.WriteStartElement("ItemGroup");
f.WriteAttributeString("Condition", " '$(RuntimeIdentifier)' == '' AND '$(OS)' == 'Unix' AND Exists('/Library/Frameworks') ");
write_nuget_target_item("osx-x64", lib, f);
f.WriteEndElement(); // ItemGroup
f.WriteStartElement("ItemGroup");
f.WriteAttributeString("Condition", " '$(RuntimeIdentifier)' == '' AND '$(OS)' == 'Unix' AND !Exists('/Library/Frameworks') ");
write_nuget_target_item("linux-x86", lib, f);
write_nuget_target_item("linux-x64", lib, f);
write_nuget_target_item("linux-arm", lib, f);
write_nuget_target_item("linux-armel", lib, f);
write_nuget_target_item("linux-arm64", lib, f);
write_nuget_target_item("linux-x64", lib, f);
write_nuget_target_item("linux-mips64", lib, f);
write_nuget_target_item("linux-s390x", lib, f);
f.WriteEndElement(); // ItemGroup
f.WriteEndElement(); // Project
f.WriteEndDocument();
}
}
private static void gen_nuget_targets_wasm(string dest, WhichLib lib)
{
var settings = common.XmlWriterSettings_default();
settings.OmitXmlDeclaration = false;
using (XmlWriter f = XmlWriter.Create(dest, settings))
{
f.WriteStartDocument();
f.WriteComment("Automatically generated");
f.WriteStartElement("Project", "http://schemas.microsoft.com/developer/msbuild/2003");
f.WriteAttributeString("ToolsVersion", "4.0");
f.WriteStartElement("ItemGroup");
f.WriteAttributeString("Condition", " '$(RuntimeIdentifier)' == 'browser-wasm' ");
var filename = lib.AsString_libname_in_nupkg(LibSuffix.A);
f.WriteStartElement("NativeFileReference");
f.WriteAttributeString("Include", string.Format("$(MSBuildThisFileDirectory)..\\..\\runtimes\\browser-wasm\\nativeassets\\net6.0\\{0}", filename));
f.WriteEndElement(); // Content
f.WriteEndElement(); // ItemGroup
f.WriteEndElement(); // Project
f.WriteEndDocument();
}
}
public static void Main(string[] args)
{
string dir_root = Path.GetFullPath(args[0]);
var dir_src = Path.Combine(dir_root, "src");
gen_nuspec_lib_e_sqlite3(dir_src);
gen_nuspec_lib_e_sqlcipher(dir_src);
}
}
| |
// 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.IO;
using System.Net;
using System.Net.Http.Headers;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace System.Net.Http
{
internal partial class AuthenticationHelper
{
// Define digest constants
private const string Qop = "qop";
private const string Auth = "auth";
private const string AuthInt = "auth-int";
private const string Nonce = "nonce";
private const string NC = "nc";
private const string Realm = "realm";
private const string UserHash = "userhash";
private const string Username = "username";
private const string UsernameStar = "username*";
private const string Algorithm = "algorithm";
private const string Uri = "uri";
private const string Sha256 = "SHA-256";
private const string Md5 = "MD5";
private const string Sha256Sess = "SHA-256-sess";
private const string MD5Sess = "MD5-sess";
private const string CNonce = "cnonce";
private const string Opaque = "opaque";
private const string Response = "response";
private const string Stale = "stale";
// Define alphanumeric characters for cnonce
// 48='0', 65='A', 97='a'
private static readonly int[] s_alphaNumChooser = new int[] { 48, 65, 97 };
public static async Task<string> GetDigestTokenForCredential(NetworkCredential credential, HttpRequestMessage request, DigestResponse digestResponse)
{
StringBuilder sb = StringBuilderCache.Acquire();
// It is mandatory for servers to implement sha-256 per RFC 7616
// Keep MD5 for backward compatibility.
string algorithm;
bool isAlgorithmSpecified = digestResponse.Parameters.TryGetValue(Algorithm, out algorithm);
if (isAlgorithmSpecified)
{
if (!algorithm.Equals(Sha256, StringComparison.OrdinalIgnoreCase) &&
!algorithm.Equals(Md5, StringComparison.OrdinalIgnoreCase) &&
!algorithm.Equals(Sha256Sess, StringComparison.OrdinalIgnoreCase) &&
!algorithm.Equals(MD5Sess, StringComparison.OrdinalIgnoreCase))
{
if (NetEventSource.IsEnabled) NetEventSource.Error(digestResponse, $"Algorithm not supported: {algorithm}");
return null;
}
}
else
{
algorithm = Md5;
}
// Check if nonce is there in challenge
string nonce;
if (!digestResponse.Parameters.TryGetValue(Nonce, out nonce))
{
if (NetEventSource.IsEnabled) NetEventSource.Error(digestResponse, "Nonce missing");
return null;
}
// opaque token may or may not exist
string opaque;
digestResponse.Parameters.TryGetValue(Opaque, out opaque);
string realm;
if (!digestResponse.Parameters.TryGetValue(Realm, out realm))
{
if (NetEventSource.IsEnabled) NetEventSource.Error(digestResponse, "Realm missing");
return null;
}
// Add username
string userhash;
if (digestResponse.Parameters.TryGetValue(UserHash, out userhash) && userhash == "true")
{
sb.AppendKeyValue(Username, ComputeHash(credential.UserName + ":" + realm, algorithm));
sb.AppendKeyValue(UserHash, userhash, includeQuotes: false);
}
else
{
if (HeaderUtilities.ContainsNonAscii(credential.UserName))
{
string usernameStar = HeaderUtilities.Encode5987(credential.UserName);
sb.AppendKeyValue(UsernameStar, usernameStar, includeQuotes: false);
}
else
{
sb.AppendKeyValue(Username, credential.UserName);
}
}
// Add realm
if (realm != string.Empty)
sb.AppendKeyValue(Realm, realm);
// Add nonce
sb.AppendKeyValue(Nonce, nonce);
// Add uri
sb.AppendKeyValue(Uri, request.RequestUri.PathAndQuery);
// Set qop, default is auth
string qop = Auth;
bool isQopSpecified = digestResponse.Parameters.ContainsKey(Qop);
if (isQopSpecified)
{
// Check if auth-int present in qop string
int index1 = digestResponse.Parameters[Qop].IndexOf(AuthInt, StringComparison.Ordinal);
if (index1 != -1)
{
// Get index of auth if present in qop string
int index2 = digestResponse.Parameters[Qop].IndexOf(Auth, StringComparison.Ordinal);
// If index2 < index1, auth option is available
// If index2 == index1, check if auth option available later in string after auth-int.
if (index2 == index1)
{
index2 = digestResponse.Parameters[Qop].IndexOf(Auth, index1 + AuthInt.Length, StringComparison.Ordinal);
if (index2 == -1)
{
qop = AuthInt;
}
}
}
}
// Set cnonce
string cnonce = GetRandomAlphaNumericString();
// Calculate response
string a1 = credential.UserName + ":" + realm + ":" + credential.Password;
if (algorithm.EndsWith("sess", StringComparison.OrdinalIgnoreCase))
{
a1 = ComputeHash(a1, algorithm) + ":" + nonce + ":" + cnonce;
}
string a2 = request.Method.Method + ":" + request.RequestUri.PathAndQuery;
if (qop == AuthInt)
{
string content = request.Content == null ? string.Empty : await request.Content.ReadAsStringAsync().ConfigureAwait(false);
a2 = a2 + ":" + ComputeHash(content, algorithm);
}
string response;
if (isQopSpecified)
{
response = ComputeHash(ComputeHash(a1, algorithm) + ":" +
nonce + ":" +
DigestResponse.NonceCount + ":" +
cnonce + ":" +
qop + ":" +
ComputeHash(a2, algorithm), algorithm);
}
else
{
response = ComputeHash(ComputeHash(a1, algorithm) + ":" +
nonce + ":" +
ComputeHash(a2, algorithm), algorithm);
}
// Add response
sb.AppendKeyValue(Response, response, includeComma: opaque != null || isAlgorithmSpecified || isQopSpecified);
// Add opaque
if (opaque != null)
{
sb.AppendKeyValue(Opaque, opaque, includeComma: isAlgorithmSpecified || isQopSpecified);
}
if (isAlgorithmSpecified)
{
// Add algorithm
sb.AppendKeyValue(Algorithm, algorithm, includeQuotes: false, includeComma: isQopSpecified);
}
if (isQopSpecified)
{
// Add qop
sb.AppendKeyValue(Qop, qop, includeQuotes: false);
// Add nc
sb.AppendKeyValue(NC, DigestResponse.NonceCount, includeQuotes: false);
// Add cnonce
sb.AppendKeyValue(CNonce, cnonce, includeComma: false);
}
return StringBuilderCache.GetStringAndRelease(sb);
}
public static bool IsServerNonceStale(DigestResponse digestResponse)
{
string stale = null;
return digestResponse.Parameters.TryGetValue(Stale, out stale) && stale == "true";
}
private static string GetRandomAlphaNumericString()
{
const int Length = 16;
Span<byte> randomNumbers = stackalloc byte[Length * 2];
RandomNumberGenerator.Fill(randomNumbers);
StringBuilder sb = StringBuilderCache.Acquire(Length);
for (int i = 0; i < randomNumbers.Length;)
{
// Get a random digit 0-9, a random alphabet in a-z, or a random alphabeta in A-Z
int rangeIndex = randomNumbers[i++] % 3;
int value = randomNumbers[i++] % (rangeIndex == 0 ? 10 : 26);
sb.Append((char)(s_alphaNumChooser[rangeIndex] + value));
}
return StringBuilderCache.GetStringAndRelease(sb);
}
private static string ComputeHash(string data, string algorithm)
{
// Disable MD5 insecure warning.
#pragma warning disable CA5351
using (HashAlgorithm hash = algorithm.StartsWith(Sha256, StringComparison.OrdinalIgnoreCase) ? SHA256.Create() : (HashAlgorithm)MD5.Create())
#pragma warning restore CA5351
{
Span<byte> result = stackalloc byte[hash.HashSize / 8]; // HashSize is in bits
bool hashComputed = hash.TryComputeHash(Encoding.UTF8.GetBytes(data), result, out int bytesWritten);
Debug.Assert(hashComputed && bytesWritten == result.Length);
StringBuilder sb = StringBuilderCache.Acquire(result.Length * 2);
Span<char> byteX2 = stackalloc char[2];
for (int i = 0; i < result.Length; i++)
{
bool formatted = result[i].TryFormat(byteX2, out int charsWritten, "x2");
Debug.Assert(formatted && charsWritten == 2);
sb.Append(byteX2);
}
return StringBuilderCache.GetStringAndRelease(sb);
}
}
internal class DigestResponse
{
internal readonly Dictionary<string, string> Parameters = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
internal const string NonceCount = "00000001";
internal DigestResponse(string challenge)
{
if (!string.IsNullOrEmpty(challenge))
Parse(challenge);
}
private static bool CharIsSpaceOrTab(char ch)
{
return ch == ' ' || ch == '\t';
}
private static bool MustValueBeQuoted(string key)
{
// As per the RFC, these string must be quoted for historical reasons.
return key.Equals(Realm, StringComparison.OrdinalIgnoreCase) || key.Equals(Nonce, StringComparison.OrdinalIgnoreCase) ||
key.Equals(Opaque, StringComparison.OrdinalIgnoreCase) || key.Equals(Qop, StringComparison.OrdinalIgnoreCase);
}
private string GetNextKey(string data, int currentIndex, out int parsedIndex)
{
// Skip leading space or tab.
while (currentIndex < data.Length && CharIsSpaceOrTab(data[currentIndex]))
{
currentIndex++;
}
// Start parsing key
int start = currentIndex;
// Parse till '=' is encountered marking end of key.
// Key cannot contain space or tab, break if either is found.
while (currentIndex < data.Length && data[currentIndex] != '=' && !CharIsSpaceOrTab(data[currentIndex]))
{
currentIndex++;
}
if (currentIndex == data.Length)
{
// Key didn't terminate with '='
parsedIndex = currentIndex;
return null;
}
// Record end of key.
int length = currentIndex - start;
if (CharIsSpaceOrTab(data[currentIndex]))
{
// Key parsing terminated due to ' ' or '\t'.
// Parse till '=' is found.
while (currentIndex < data.Length && CharIsSpaceOrTab(data[currentIndex]))
{
currentIndex++;
}
if (currentIndex == data.Length || data[currentIndex] != '=')
{
// Key is invalid.
parsedIndex = currentIndex;
return null;
}
}
// Skip trailing space and tab and '='
while (currentIndex < data.Length && (CharIsSpaceOrTab(data[currentIndex]) || data[currentIndex] == '='))
{
currentIndex++;
}
// Set the parsedIndex to current valid char.
parsedIndex = currentIndex;
return data.Substring(start, length);
}
private string GetNextValue(string data, int currentIndex, bool expectQuotes, out int parsedIndex)
{
Debug.Assert(currentIndex < data.Length && !CharIsSpaceOrTab(data[currentIndex]));
// If quoted value, skip first quote.
bool quotedValue = false;
if (data[currentIndex] == '"')
{
quotedValue = true;
currentIndex++;
}
if (expectQuotes && !quotedValue)
{
parsedIndex = currentIndex;
return null;
}
StringBuilder sb = StringBuilderCache.Acquire();
while (currentIndex < data.Length && ((quotedValue && data[currentIndex] != '"') || (!quotedValue && data[currentIndex] != ',')))
{
sb.Append(data[currentIndex]);
currentIndex++;
if (currentIndex == data.Length)
break;
if (!quotedValue && CharIsSpaceOrTab(data[currentIndex]))
break;
if (quotedValue && data[currentIndex] == '"' && data[currentIndex - 1] == '\\')
{
// Include the escaped quote.
sb.Append(data[currentIndex]);
currentIndex++;
}
}
// Skip the quote.
if (quotedValue)
currentIndex++;
// Skip any whitespace.
while (currentIndex < data.Length && CharIsSpaceOrTab(data[currentIndex]))
currentIndex++;
// Return if this is last value.
if (currentIndex == data.Length)
{
parsedIndex = currentIndex;
return StringBuilderCache.GetStringAndRelease(sb);
}
// A key-value pair should end with ','
if (data[currentIndex++] != ',')
{
parsedIndex = currentIndex;
return null;
}
// Skip space and tab
while (currentIndex < data.Length && CharIsSpaceOrTab(data[currentIndex]))
{
currentIndex++;
}
// Set parsedIndex to current valid char.
parsedIndex = currentIndex;
return StringBuilderCache.GetStringAndRelease(sb);
}
private unsafe void Parse(string challenge)
{
int parsedIndex = 0;
while (parsedIndex < challenge.Length)
{
// Get the key.
string key = GetNextKey(challenge, parsedIndex, out parsedIndex);
// Ensure key is not empty and parsedIndex is still in range.
if (string.IsNullOrEmpty(key) || parsedIndex >= challenge.Length)
break;
// Get the value.
string value = GetNextValue(challenge, parsedIndex, MustValueBeQuoted(key), out parsedIndex);
// Ensure value is valid.
if (string.IsNullOrEmpty(value))
break;
// Add the key-value pair to Parameters.
Parameters.Add(key, value);
}
}
}
}
internal static class StringBuilderExtensions
{
// Characters that require escaping in quoted string
private static readonly char[] SpecialCharacters = new[] { '"', '\\' };
public static void AppendKeyValue(this StringBuilder sb, string key, string value, bool includeQuotes = true, bool includeComma = true)
{
sb.Append(key);
sb.Append('=');
if (includeQuotes)
{
sb.Append('"');
int lastSpecialIndex = 0;
int specialIndex;
while (true)
{
specialIndex = value.IndexOfAny(SpecialCharacters, lastSpecialIndex);
if (specialIndex >= 0)
{
sb.Append(value, lastSpecialIndex, specialIndex - lastSpecialIndex);
sb.Append('\\');
sb.Append(value[specialIndex]);
lastSpecialIndex = specialIndex + 1;
}
else
{
sb.Append(value, lastSpecialIndex, value.Length - lastSpecialIndex);
break;
}
}
sb.Append('"');
}
else
{
sb.Append(value);
}
if (includeComma)
{
sb.Append(',');
sb.Append(' ');
}
}
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Cloud.Debugger.V2.Snippets
{
using System.Threading.Tasks;
/// <summary>Generated snippets.</summary>
public sealed class AllGeneratedDebugger2ClientSnippets
{
/// <summary>Snippet for SetBreakpoint</summary>
public void SetBreakpointRequestObject()
{
// Snippet: SetBreakpoint(SetBreakpointRequest, CallSettings)
// Create client
Debugger2Client debugger2Client = Debugger2Client.Create();
// Initialize request argument(s)
SetBreakpointRequest request = new SetBreakpointRequest
{
DebuggeeId = "",
Breakpoint = new Breakpoint(),
ClientVersion = "",
};
// Make the request
SetBreakpointResponse response = debugger2Client.SetBreakpoint(request);
// End snippet
}
/// <summary>Snippet for SetBreakpointAsync</summary>
public async Task SetBreakpointRequestObjectAsync()
{
// Snippet: SetBreakpointAsync(SetBreakpointRequest, CallSettings)
// Additional: SetBreakpointAsync(SetBreakpointRequest, CancellationToken)
// Create client
Debugger2Client debugger2Client = await Debugger2Client.CreateAsync();
// Initialize request argument(s)
SetBreakpointRequest request = new SetBreakpointRequest
{
DebuggeeId = "",
Breakpoint = new Breakpoint(),
ClientVersion = "",
};
// Make the request
SetBreakpointResponse response = await debugger2Client.SetBreakpointAsync(request);
// End snippet
}
/// <summary>Snippet for SetBreakpoint</summary>
public void SetBreakpoint()
{
// Snippet: SetBreakpoint(string, Breakpoint, string, CallSettings)
// Create client
Debugger2Client debugger2Client = Debugger2Client.Create();
// Initialize request argument(s)
string debuggeeId = "";
Breakpoint breakpoint = new Breakpoint();
string clientVersion = "";
// Make the request
SetBreakpointResponse response = debugger2Client.SetBreakpoint(debuggeeId, breakpoint, clientVersion);
// End snippet
}
/// <summary>Snippet for SetBreakpointAsync</summary>
public async Task SetBreakpointAsync()
{
// Snippet: SetBreakpointAsync(string, Breakpoint, string, CallSettings)
// Additional: SetBreakpointAsync(string, Breakpoint, string, CancellationToken)
// Create client
Debugger2Client debugger2Client = await Debugger2Client.CreateAsync();
// Initialize request argument(s)
string debuggeeId = "";
Breakpoint breakpoint = new Breakpoint();
string clientVersion = "";
// Make the request
SetBreakpointResponse response = await debugger2Client.SetBreakpointAsync(debuggeeId, breakpoint, clientVersion);
// End snippet
}
/// <summary>Snippet for GetBreakpoint</summary>
public void GetBreakpointRequestObject()
{
// Snippet: GetBreakpoint(GetBreakpointRequest, CallSettings)
// Create client
Debugger2Client debugger2Client = Debugger2Client.Create();
// Initialize request argument(s)
GetBreakpointRequest request = new GetBreakpointRequest
{
DebuggeeId = "",
BreakpointId = "",
ClientVersion = "",
};
// Make the request
GetBreakpointResponse response = debugger2Client.GetBreakpoint(request);
// End snippet
}
/// <summary>Snippet for GetBreakpointAsync</summary>
public async Task GetBreakpointRequestObjectAsync()
{
// Snippet: GetBreakpointAsync(GetBreakpointRequest, CallSettings)
// Additional: GetBreakpointAsync(GetBreakpointRequest, CancellationToken)
// Create client
Debugger2Client debugger2Client = await Debugger2Client.CreateAsync();
// Initialize request argument(s)
GetBreakpointRequest request = new GetBreakpointRequest
{
DebuggeeId = "",
BreakpointId = "",
ClientVersion = "",
};
// Make the request
GetBreakpointResponse response = await debugger2Client.GetBreakpointAsync(request);
// End snippet
}
/// <summary>Snippet for GetBreakpoint</summary>
public void GetBreakpoint()
{
// Snippet: GetBreakpoint(string, string, string, CallSettings)
// Create client
Debugger2Client debugger2Client = Debugger2Client.Create();
// Initialize request argument(s)
string debuggeeId = "";
string breakpointId = "";
string clientVersion = "";
// Make the request
GetBreakpointResponse response = debugger2Client.GetBreakpoint(debuggeeId, breakpointId, clientVersion);
// End snippet
}
/// <summary>Snippet for GetBreakpointAsync</summary>
public async Task GetBreakpointAsync()
{
// Snippet: GetBreakpointAsync(string, string, string, CallSettings)
// Additional: GetBreakpointAsync(string, string, string, CancellationToken)
// Create client
Debugger2Client debugger2Client = await Debugger2Client.CreateAsync();
// Initialize request argument(s)
string debuggeeId = "";
string breakpointId = "";
string clientVersion = "";
// Make the request
GetBreakpointResponse response = await debugger2Client.GetBreakpointAsync(debuggeeId, breakpointId, clientVersion);
// End snippet
}
/// <summary>Snippet for DeleteBreakpoint</summary>
public void DeleteBreakpointRequestObject()
{
// Snippet: DeleteBreakpoint(DeleteBreakpointRequest, CallSettings)
// Create client
Debugger2Client debugger2Client = Debugger2Client.Create();
// Initialize request argument(s)
DeleteBreakpointRequest request = new DeleteBreakpointRequest
{
DebuggeeId = "",
BreakpointId = "",
ClientVersion = "",
};
// Make the request
debugger2Client.DeleteBreakpoint(request);
// End snippet
}
/// <summary>Snippet for DeleteBreakpointAsync</summary>
public async Task DeleteBreakpointRequestObjectAsync()
{
// Snippet: DeleteBreakpointAsync(DeleteBreakpointRequest, CallSettings)
// Additional: DeleteBreakpointAsync(DeleteBreakpointRequest, CancellationToken)
// Create client
Debugger2Client debugger2Client = await Debugger2Client.CreateAsync();
// Initialize request argument(s)
DeleteBreakpointRequest request = new DeleteBreakpointRequest
{
DebuggeeId = "",
BreakpointId = "",
ClientVersion = "",
};
// Make the request
await debugger2Client.DeleteBreakpointAsync(request);
// End snippet
}
/// <summary>Snippet for DeleteBreakpoint</summary>
public void DeleteBreakpoint()
{
// Snippet: DeleteBreakpoint(string, string, string, CallSettings)
// Create client
Debugger2Client debugger2Client = Debugger2Client.Create();
// Initialize request argument(s)
string debuggeeId = "";
string breakpointId = "";
string clientVersion = "";
// Make the request
debugger2Client.DeleteBreakpoint(debuggeeId, breakpointId, clientVersion);
// End snippet
}
/// <summary>Snippet for DeleteBreakpointAsync</summary>
public async Task DeleteBreakpointAsync()
{
// Snippet: DeleteBreakpointAsync(string, string, string, CallSettings)
// Additional: DeleteBreakpointAsync(string, string, string, CancellationToken)
// Create client
Debugger2Client debugger2Client = await Debugger2Client.CreateAsync();
// Initialize request argument(s)
string debuggeeId = "";
string breakpointId = "";
string clientVersion = "";
// Make the request
await debugger2Client.DeleteBreakpointAsync(debuggeeId, breakpointId, clientVersion);
// End snippet
}
/// <summary>Snippet for ListBreakpoints</summary>
public void ListBreakpointsRequestObject()
{
// Snippet: ListBreakpoints(ListBreakpointsRequest, CallSettings)
// Create client
Debugger2Client debugger2Client = Debugger2Client.Create();
// Initialize request argument(s)
ListBreakpointsRequest request = new ListBreakpointsRequest
{
DebuggeeId = "",
IncludeAllUsers = false,
IncludeInactive = false,
Action = new ListBreakpointsRequest.Types.BreakpointActionValue(),
WaitToken = "",
ClientVersion = "",
};
// Make the request
ListBreakpointsResponse response = debugger2Client.ListBreakpoints(request);
// End snippet
}
/// <summary>Snippet for ListBreakpointsAsync</summary>
public async Task ListBreakpointsRequestObjectAsync()
{
// Snippet: ListBreakpointsAsync(ListBreakpointsRequest, CallSettings)
// Additional: ListBreakpointsAsync(ListBreakpointsRequest, CancellationToken)
// Create client
Debugger2Client debugger2Client = await Debugger2Client.CreateAsync();
// Initialize request argument(s)
ListBreakpointsRequest request = new ListBreakpointsRequest
{
DebuggeeId = "",
IncludeAllUsers = false,
IncludeInactive = false,
Action = new ListBreakpointsRequest.Types.BreakpointActionValue(),
WaitToken = "",
ClientVersion = "",
};
// Make the request
ListBreakpointsResponse response = await debugger2Client.ListBreakpointsAsync(request);
// End snippet
}
/// <summary>Snippet for ListBreakpoints</summary>
public void ListBreakpoints()
{
// Snippet: ListBreakpoints(string, string, CallSettings)
// Create client
Debugger2Client debugger2Client = Debugger2Client.Create();
// Initialize request argument(s)
string debuggeeId = "";
string clientVersion = "";
// Make the request
ListBreakpointsResponse response = debugger2Client.ListBreakpoints(debuggeeId, clientVersion);
// End snippet
}
/// <summary>Snippet for ListBreakpointsAsync</summary>
public async Task ListBreakpointsAsync()
{
// Snippet: ListBreakpointsAsync(string, string, CallSettings)
// Additional: ListBreakpointsAsync(string, string, CancellationToken)
// Create client
Debugger2Client debugger2Client = await Debugger2Client.CreateAsync();
// Initialize request argument(s)
string debuggeeId = "";
string clientVersion = "";
// Make the request
ListBreakpointsResponse response = await debugger2Client.ListBreakpointsAsync(debuggeeId, clientVersion);
// End snippet
}
/// <summary>Snippet for ListDebuggees</summary>
public void ListDebuggeesRequestObject()
{
// Snippet: ListDebuggees(ListDebuggeesRequest, CallSettings)
// Create client
Debugger2Client debugger2Client = Debugger2Client.Create();
// Initialize request argument(s)
ListDebuggeesRequest request = new ListDebuggeesRequest
{
Project = "",
IncludeInactive = false,
ClientVersion = "",
};
// Make the request
ListDebuggeesResponse response = debugger2Client.ListDebuggees(request);
// End snippet
}
/// <summary>Snippet for ListDebuggeesAsync</summary>
public async Task ListDebuggeesRequestObjectAsync()
{
// Snippet: ListDebuggeesAsync(ListDebuggeesRequest, CallSettings)
// Additional: ListDebuggeesAsync(ListDebuggeesRequest, CancellationToken)
// Create client
Debugger2Client debugger2Client = await Debugger2Client.CreateAsync();
// Initialize request argument(s)
ListDebuggeesRequest request = new ListDebuggeesRequest
{
Project = "",
IncludeInactive = false,
ClientVersion = "",
};
// Make the request
ListDebuggeesResponse response = await debugger2Client.ListDebuggeesAsync(request);
// End snippet
}
/// <summary>Snippet for ListDebuggees</summary>
public void ListDebuggees()
{
// Snippet: ListDebuggees(string, string, CallSettings)
// Create client
Debugger2Client debugger2Client = Debugger2Client.Create();
// Initialize request argument(s)
string project = "";
string clientVersion = "";
// Make the request
ListDebuggeesResponse response = debugger2Client.ListDebuggees(project, clientVersion);
// End snippet
}
/// <summary>Snippet for ListDebuggeesAsync</summary>
public async Task ListDebuggeesAsync()
{
// Snippet: ListDebuggeesAsync(string, string, CallSettings)
// Additional: ListDebuggeesAsync(string, string, CancellationToken)
// Create client
Debugger2Client debugger2Client = await Debugger2Client.CreateAsync();
// Initialize request argument(s)
string project = "";
string clientVersion = "";
// Make the request
ListDebuggeesResponse response = await debugger2Client.ListDebuggeesAsync(project, clientVersion);
// End snippet
}
}
}
| |
// 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.Reflection;
using System.Collections.Generic;
#pragma warning disable 0414
namespace System.Reflection.Tests
{
public class PropertyInfoPropertyTests
{
//Verify CanRead for read write PropertyInfo
[Fact]
public static void TestCanRead1()
{
string propName = "MyPropAA";
PropertyInfo pi = GetProperty(typeof(SampleProperty), propName);
Assert.NotNull(pi);
Assert.True(pi.CanRead, "Failed! CanRead Failed for read write property. Expected True , returned False");
}
//Verify CanRead for readonly PropertyInfo
[Fact]
public static void TestCanRead2()
{
string propName = "MyPropBB";
PropertyInfo pi = GetProperty(typeof(SampleProperty), propName);
Assert.NotNull(pi);
Assert.True(pi.CanRead, "Failed! CanRead Failed for read only property. Expected True , returned False");
}
//Verify CanRead for writeonly PropertyInfo
[Fact]
public static void TestCanRead3()
{
string propName = "MyPropCC";
PropertyInfo pi = GetProperty(typeof(SampleProperty), propName);
Assert.NotNull(pi);
Assert.False(pi.CanRead, "Failed! CanRead Failed for write only property. Expected False , returned True");
}
//Verify CanWrite for read write PropertyInfo
[Fact]
public static void TestCanWrite1()
{
string propName = "MyPropAA";
PropertyInfo pi = GetProperty(typeof(SampleProperty), propName);
Assert.NotNull(pi);
Assert.True(pi.CanWrite, "Failed! CanWrite Failed for read write property. Expected True , returned False");
}
//Verify CanWrite for readonly PropertyInfo
[Fact]
public static void TestCanWrite2()
{
string propName = "MyPropBB";
PropertyInfo pi = GetProperty(typeof(SampleProperty), propName);
Assert.NotNull(pi);
Assert.False(pi.CanWrite, "Failed! CanWrite Failed for read only property. Expected False , returned True");
}
//Verify CanWrite for writeonly PropertyInfo
[Fact]
public static void TestCanWrite3()
{
string propName = "MyPropCC";
PropertyInfo pi = GetProperty(typeof(SampleProperty), propName);
Assert.NotNull(pi);
Assert.True(pi.CanWrite, "Failed! CanWrite Failed for write only property. Expected True , returned False");
}
//Verify DeclaringType for PropertyInfo
[Fact]
public static void TestDeclaringType1()
{
string propName = "DerivedProeprtyProperty";
PropertyInfo pi = GetProperty(typeof(DerivedProeprty), propName);
Assert.NotNull(pi);
Assert.NotNull(pi.DeclaringType.Name);
Assert.Equal("DerivedProeprty", pi.DeclaringType.Name);
}
//Verify DeclaringType for PropertyInfo
[Fact]
public static void TestDeclaringType2()
{
string propName = "BasePropertyProperty";
PropertyInfo pi = GetProperty(typeof(BaseProperty), propName);
Assert.NotNull(pi);
Assert.NotNull(pi.DeclaringType.Name);
Assert.Equal("BaseProperty", pi.DeclaringType.Name);
}
//Verify PropertyType for PropertyInfo
[Fact]
public static void TestPropertyType1()
{
string propName = "DerivedProeprtyProperty";
PropertyInfo pi = GetProperty(typeof(DerivedProeprty), propName);
Assert.NotNull(pi);
Assert.NotNull(pi.PropertyType);
Assert.Equal("Int32", pi.PropertyType.Name);
}
//Verify PropertyType for PropertyInfo
[Fact]
public static void TestPropertyType2()
{
string propName = "BasePropertyProperty";
PropertyInfo pi = GetProperty(typeof(BaseProperty), propName);
Assert.NotNull(pi);
Assert.NotNull(pi.PropertyType);
Assert.Equal("Int32", pi.PropertyType.Name);
}
//Verify PropertyType for PropertyInfo
[Fact]
public static void TestPropertyType3()
{
string propName = "MyPropAA";
PropertyInfo pi = GetProperty(typeof(SampleProperty), propName);
Assert.NotNull(pi);
Assert.NotNull(pi.PropertyType);
Assert.Equal("Int16", pi.PropertyType.Name);
}
//Verify Name for PropertyInfo
[Fact]
public static void TestName1()
{
string propName = "MyPropAA";
PropertyInfo pi = GetProperty(typeof(SampleProperty), propName);
Assert.NotNull(pi);
Assert.Equal(propName, pi.Name);
}
//Verify Name for PropertyInfo
[Fact]
public static void TestName2()
{
string propName = "MyPropBB";
PropertyInfo pi = GetProperty(typeof(SampleProperty), propName);
Assert.NotNull(pi);
Assert.Equal(propName, pi.Name);
}
//Verify Name for PropertyInfo
[Fact]
public static void TestName3()
{
string propName = "MyPropCC";
PropertyInfo pi = GetProperty(typeof(SampleProperty), propName);
Assert.NotNull(pi);
Assert.Equal(propName, pi.Name);
}
//Verify IsSpecialName for PropertyInfo
[Fact]
public static void TestIsSpecialName1()
{
string propName = "MyPropCC";
PropertyInfo pi = GetProperty(typeof(SampleProperty), propName);
Assert.NotNull(pi);
Assert.False(pi.IsSpecialName, "Failed: PropertyInfo IsSpecialName returned True for property: " + propName);
}
//Verify IsSpecialName for PropertyInfo
[Fact]
public static void TestIsSpecialName2()
{
string propName = "MyPropBB";
PropertyInfo pi = GetProperty(typeof(SampleProperty), propName);
Assert.NotNull(pi);
Assert.False(pi.IsSpecialName, "Failed: PropertyInfo IsSpecialName returned True for property: " + propName);
}
//Verify IsSpecialName for PropertyInfo
[Fact]
public static void TestIsSpecialName3()
{
string propName = "MyPropAA";
PropertyInfo pi = GetProperty(typeof(SampleProperty), propName);
Assert.NotNull(pi);
Assert.False(pi.IsSpecialName, "Failed: PropertyInfo IsSpecialName returned True for property: " + propName);
}
//Verify Attributes for Property
[Fact]
public static void TestAttributes1()
{
string propName = "Description";
PropertyInfo pi = GetProperty(typeof(DerivedProeprty), propName);
Assert.NotNull(pi);
PropertyAttributes pa = pi.Attributes;
Assert.Equal((object)pa, (object)PropertyAttributes.None);
}
//Verify Attributes for Property
[Fact]
public static void TestAttributes2()
{
string propName = "DerivedProeprtyProperty";
PropertyInfo pi = GetProperty(typeof(DerivedProeprty), propName);
Assert.NotNull(pi);
PropertyAttributes pa = pi.Attributes;
Assert.Equal((object)pa, (object)PropertyAttributes.None);
}
//Gets PropertyInfo object from a Type
public static PropertyInfo GetProperty(Type t, string property)
{
TypeInfo ti = t.GetTypeInfo();
IEnumerator<PropertyInfo> allproperties = ti.DeclaredProperties.GetEnumerator();
PropertyInfo pi = null;
while (allproperties.MoveNext())
{
if (allproperties.Current.Name.Equals(property))
{
//found property
pi = allproperties.Current;
break;
}
}
return pi;
}
}
//Reflection Metadata
public class SampleProperty
{
public short m_PropAA = -2;
public int m_PropBB = -2;
public long m_PropCC = -2;
public int m_PropDD = -2;
/// declare/define all the properties here
// MyPropAA - ReadWrite public property
public short MyPropAA
{
get { return m_PropAA; }
set { m_PropAA = value; }
}
// MyPropBB - ReadOnly public property
public int MyPropBB
{
get { return m_PropBB; }
}
// MyPropCC - WriteOnly public property
public int MyPropCC
{
set { m_PropCC = value; }
}
//indexer Property
public string[] mystrings = { "abc", "def", "ghi", "jkl" };
public string this[int Index]
{
get
{
return mystrings[Index];
}
set
{
mystrings[Index] = value;
}
}
}
public class BaseProperty
{
private int _baseprop = 10;
public int BasePropertyProperty
{
get { return _baseprop; }
set { _baseprop = value; }
}
}
public class DerivedProeprty : BaseProperty
{
private int _derivedprop = 100;
private string _description;
public int DerivedProeprtyProperty
{
get { return _derivedprop; }
set { _derivedprop = value; }
}
public string Description
{
get { return _description; }
set { _description = value; }
}
}
}
| |
using System;
using System.ComponentModel;
using System.Collections.Generic;
using System.Diagnostics;
using System.Resources;
using System.Text;
using System.Windows.Forms;
using System.Globalization;
using System.Reflection;
using DevComponents.Editors.DateTimeAdv;
using DevComponents.Editors;
using DevComponents.DotNetBar.Controls;
namespace SimpleCrm.Utils
{
/// <summary>
/// The data of object map to the control,or else.
/// </summary>
[ProvideProperty("PropertyName", typeof(Object))]
[ProvideProperty("FormatString", typeof(Object))]
public partial class DataBinding : Component, IExtenderProvider, ISupportInitialize
{
private string dateTimeFormat = "yyyy-MM-dd";
/// <summary>
/// Gets or sets the date time format.
/// </summary>
/// <value>The date time format.</value>
[Browsable(false)]
public string DateTimeFormat
{
get { return dateTimeFormat; }
set { dateTimeFormat = value; }
}
private IDictionary<Control, PropertyPair> m_InnerControlDictionary;
private static int DefaultPriority = 5;
private List<PropertyPair> m_SortedList;
/// <summary>
/// Gets or sets the inner control dictionary.
/// </summary>
/// <value>The inner control dictionary.</value>
[Browsable(false)]
public IDictionary<Control, PropertyPair> InnerControlDictionary
{
get { return this.m_InnerControlDictionary; }
private set { this.m_InnerControlDictionary = value; }
}
/// <summary>
/// Initializes a new instance of the <see cref="DataBinding"/> class.
/// </summary>
public DataBinding()
{
this.m_InnerControlDictionary = new Dictionary<Control, PropertyPair>();
}
/// <summary>
/// Initializes a new instance of the <see cref="DataBinding"/> class.
/// </summary>
/// <param name="container">The container.</param>
public DataBinding(IContainer container)
: this()
{
container.Add(this);
}
#region ISupportInitialize Members
/// <summary>
/// Signals the object that initialization is starting.
/// </summary>
public void BeginInit()
{
}
/// <summary>
/// Signals the object that initialization is complete.
/// </summary>
public void EndInit()
{
m_SortedList = new List<PropertyPair>(m_InnerControlDictionary.Values);
m_SortedList.Sort();
}
#endregion
#region IExtenderProvider Members
/// <summary>
/// Gets the name of the property.
/// </summary>
/// <param name="item">The item.</param>
/// <returns></returns>
[DefaultValue("")]
[Category("Mapping")]
[Description("The property of the class.Syntax is 'name:priority',priority may ignore,default priority is 5.")]
public string GetPropertyName(object item)
{
if (item is Control && m_InnerControlDictionary.ContainsKey((Control)item))
{
return m_InnerControlDictionary[(Control)item].DisplayPropertyName;
}
return string.Empty;
}
/// <summary>
/// Sets the name of the property.
/// </summary>
/// <param name="item">The item.</param>
/// <param name="value">The value.</param>
public void SetPropertyName(object item, string value)
{
if (item is Control)
{
if (string.IsNullOrEmpty(value))
{
if (m_InnerControlDictionary.ContainsKey((Control)item))
{
m_InnerControlDictionary.Remove((Control)item);
//m_PriorityList.
}
return;
}
//create the pair.
if (m_InnerControlDictionary.ContainsKey((Control)item) == false)
{
PropertyPair kv = new PropertyPair();
kv.Control = (Control)item;
m_InnerControlDictionary[(Control)item] = kv;
}
m_InnerControlDictionary[(Control)item].DisplayPropertyName = value;
}
}
/// <summary>
/// Gets the format string.
/// </summary>
/// <param name="item">The item.</param>
/// <returns></returns>
[DefaultValue("")]
[Category("Mapping")]
[Description("The format of the output string.")]
public string GetFormatString(object item)
{
if (item is Control && m_InnerControlDictionary.ContainsKey((Control)item))
{
return m_InnerControlDictionary[(Control)item].FormatString;
}
return string.Empty;
}
/// <summary>
/// Sets the format string.
/// </summary>
/// <param name="item">The item.</param>
/// <param name="value">The value.</param>
public void SetFormatString(object item, string value)
{
if (string.IsNullOrEmpty(value))
{
if (m_InnerControlDictionary.ContainsKey((Control)item))
{
m_InnerControlDictionary[(Control)item].FormatString = "";
}
return;
}
if (item is Control)
{
if (m_InnerControlDictionary.ContainsKey((Control)item) == false)
{
PropertyPair kv = new PropertyPair();
kv.Control = (Control)item;
m_InnerControlDictionary[(Control)item] = kv;
}
m_InnerControlDictionary[(Control)item].FormatString = value;
}
}
/// <summary>
/// Specifies whether this object can provide its extender properties to the specified object.
/// </summary>
/// <param name="extendee">The <see cref="T:System.Object"></see> to receive the extender properties.</param>
/// <returns>
/// true if this object can provide extender properties to the specified object; otherwise, false.
/// </returns>
public bool CanExtend(object extendee)
{
//todo Some control shall be exluded,eg ,button.
if (extendee is TextBox || extendee is Label || extendee is ComboBox || extendee is CheckBox
|| extendee is ListControl || extendee is DateTimePicker || extendee is VisualControlBase
|| extendee is TextBoxDropDown)
{
return true;
}
return false;
}
#endregion
#region Public Mapping Method
/// <summary>
/// Gets value of Control to assign to object.
/// </summary>
/// <param name="obj">The obj.</param>
public void MapToObject(object obj)
{
if (obj == null)
{
throw new ArgumentException("The argument of mapping object don't allow to be null.");
}
// System.ComponentModel.
foreach (KeyValuePair<Control, PropertyPair> kv in m_InnerControlDictionary)
{
if (string.IsNullOrEmpty(kv.Value.PropertyName))
{
continue;
}
//Find the property from object.
object declaredObject = obj;
PropertyInfo pi = GetProperty(kv.Value.PropertyName, ref declaredObject);
if (pi == null)
{
throw new Exception(String.Format("The property {0} didn't be found.", kv.Value.PropertyName));
}
Type propertyType = Nullable.GetUnderlyingType(pi.PropertyType) ?? pi.PropertyType;
TypeConverter converter = TypeDescriptor.GetConverter(propertyType);
if (pi.PropertyType == typeof(bool))
{
converter = new BooleanConverterEx();
}
object value = null;
if (kv.Key is TextBoxBase || kv.Key is Label || kv.Key is TextBoxDropDown)
{
Control control = kv.Key as Control;
if (control.Text.Trim() == "")
{
value = null;
}
else
{
value = control.Text.Trim();
}
}
else if (kv.Key is ComboBox)
{
ComboBox combobox = kv.Key as ComboBox;
value = combobox.SelectedValue;
if (combobox.SelectedItem == null
|| value == null
|| String.IsNullOrEmpty(value.ToString()))
{
value = null;
}
}
else if (kv.Key is CheckBox)
{
value = (kv.Key as CheckBox).Checked;
}
else if (kv.Key is DateTimePicker)
{
value = (kv.Key as DateTimePicker).Value;
}
else if (kv.Key is DateTimeInput)
{
value = (kv.Key as DateTimeInput).ValueObject;
}
else if (kv.Key is IntegerInput)
{
value = (kv.Key as IntegerInput).ValueObject;
}
else if (kv.Key is DoubleInput)
{
DoubleInput doubleInputControl = kv.Key as DoubleInput;
if (doubleInputControl.ValueObject != null)
{
value = Convert.ToString(doubleInputControl.Value);
}
}
if (value != null && value.GetType() != propertyType)
{
value = converter.ConvertFrom(value);
}
pi.SetValue(declaredObject, value, null);
}
}
/// <summary>
/// Resets the value of all controls.
/// </summary>
public void ClearControlValue()
{
if (m_InnerControlDictionary.Count == 0)
{
return;
}
foreach (PropertyPair pair in m_SortedList)
{
//Find the property from object.
if (pair.Control is TextBoxBase || pair.Control is Label || pair.Control is TextBoxDropDown)
{
pair.Control.Text = "";
}
else if (pair.Control is ComboBox)
{
ComboBox control = pair.Control as ComboBox;
control.SelectedIndex = -1;
}
else if (pair.Control is CheckBox)
{
(pair.Control as CheckBox).Checked = false;
}
else if (pair.Control is DateTimePicker)
{
(pair.Control as DateTimePicker).Checked = false;
}
else if (pair.Control is DateTimeInput)
{
(pair.Control as DateTimeInput).ValueObject = null;
}
else if (pair.Control is IntegerInput)
{
(pair.Control as IntegerInput).ValueObject = null;
}
else if (pair.Control is DoubleInput)
{
(pair.Control as DoubleInput).ValueObject = null;
}
}
}
/// <summary>
/// Display value from object.
/// </summary>
/// <param name="obj">The obj.</param>
public void MapToControl(object obj)
{
if (obj == null)
{
throw new ArgumentException("The argument of mapping object don't allow to be null.");
}
if (m_InnerControlDictionary.Count == 0)
{
return;
}
if (m_SortedList == null)
{
m_SortedList = new List<PropertyPair>(m_InnerControlDictionary.Values);
m_SortedList.Sort();
}
foreach (PropertyPair pair in m_SortedList)
{
//Find the property from object.
object declaredObject = obj;
PropertyInfo pi = GetProperty(pair.PropertyName, ref declaredObject);
if (pi == null)
{
throw new Exception(String.Format("The property {0} didn't be found.", pair.PropertyName));
}
Type propertyType = Nullable.GetUnderlyingType(pi.PropertyType) ?? pi.PropertyType;
object value = pi.GetValue(declaredObject, null);
string valueStr = Convert.ToString(value);
if (valueStr == "")
{
valueStr = null;
}
if (pair.Control is TextBoxBase || pair.Control is Label || pair.Control is TextBoxDropDown)
{
//Format the ouput string.
if (String.IsNullOrEmpty(pair.FormatString) == false)
{
valueStr = String.Format("{0:" + pair.FormatString + "}", value);
}
if (value == null)
{
valueStr = "";
}
else
{
if (propertyType == typeof(DateTime))
{
valueStr = ((DateTime)value).ToString(dateTimeFormat, DateTimeFormatInfo.InvariantInfo);
}
}
pair.Control.Text = valueStr;
}
else if (pair.Control is ComboBox)
{
ComboBox control = pair.Control as ComboBox;
if (value == null)
{
control.SelectedIndex = -1;
}
else
{
control.SelectedValue = value;
}
}
else if (pair.Control is CheckBox)
{
(pair.Control as CheckBox).Checked = Convert.ToBoolean(value ?? false);
}
else if (pair.Control is DateTimePicker)
{
DateTime valueDate;
if (value is String)
{
valueDate = DateTime.MinValue;
if (DateTime.TryParse(value.ToString(), out valueDate))
{
value = valueDate;
}
else
{
value = valueDate;
}
}
else
{
valueDate = (DateTime)value;
}
(pair.Control as DateTimePicker).Value = valueDate;
}
else if (pair.Control is DateTimeInput)
{
(pair.Control as DateTimeInput).ValueObject = value;
}
else if (pair.Control is IntegerInput)
{
(pair.Control as IntegerInput).ValueObject = value;
}
else if (pair.Control is DoubleInput)
{
DoubleInput dicontrol = pair.Control as DoubleInput;
if (String.IsNullOrEmpty(valueStr))
{
dicontrol.ValueObject = null;
}
else
{
(pair.Control as DoubleInput).ValueObject = Convert.ToDouble(valueStr);
}
}
}
}
/// <summary>
/// Gets the property.
/// </summary>
/// <param name="propertyName">Name of the property.</param>
/// <param name="declaredObj">The declared obj.</param>
/// <returns></returns>
public PropertyInfo GetProperty(String propertyName, ref object declaredObj)
{
if (declaredObj == null || propertyName == "")
{
return null;
}
Type objectType = declaredObj.GetType();
//propertyName may composite the string with dot spilter,eg, name.firstname.
string realPropertyName = "";
int dotLocation = propertyName.IndexOf('.');
if (dotLocation == 0 || dotLocation == propertyName.Length - 1)
{
throw new Exception("The format of property name " + propertyName + " is wrong.");
}
if (dotLocation > 0)
{
realPropertyName = propertyName.Substring(0, dotLocation);
propertyName = propertyName.Substring(dotLocation + 1);
}
else
{
realPropertyName = propertyName;
propertyName = "";
}
//Find the property from object.
PropertyInfo pi = objectType.GetProperty(realPropertyName);
//if (pi == null)
//{
// throw new Exception(String.Format("The property {0} didn't be found.", realPropertyName));
//}
if (pi == null || propertyName == "")
{
return pi;
}
else
{
declaredObj = pi.GetValue(declaredObj, null);
return GetProperty(propertyName, ref declaredObj);
}
}
#endregion
/// <summary>
/// Pair of perperty and value,control,priority.
/// </summary>
public class PropertyPair : IComparable<PropertyPair>
{
private string _key;
/// <summary>
/// Gets or sets the name of the property.
/// </summary>
/// <value>The name of the property.</value>
public string PropertyName
{
get { return _key; }
set { _key = value; }
}
/// <summary>
/// Gets or sets the display name of the property.
/// </summary>
/// <value>The display name of the property.</value>
public string DisplayPropertyName
{
get
{
if (priority == DataBinding.DefaultPriority)
{
return _key;
}
else
{
return _key + ":" + priority.ToString();
}
}
set
{
string[] s = value.Split(':');
_key = s[0];
if (s.Length > 1)
{
int p;
if (int.TryParse(s[1], out p))
{
priority = p;
}
else
{
priority = DataBinding.DefaultPriority;
}
}
}
}
private string _value;
/// <summary>
/// Gets or sets the format string.
/// </summary>
/// <value>The format string.</value>
public string FormatString
{
get { return _value; }
set { _value = value; }
}
private Control control;
/// <summary>
/// Gets or sets the control.
/// </summary>
/// <value>The control.</value>
public Control Control
{
get { return control; }
set { control = value; }
}
private int priority = DataBinding.DefaultPriority;
/// <summary>
/// Gets or sets the priority.
/// </summary>
/// <value>The priority.</value>
public int Priority
{
get { return priority; }
set { priority = value; }
}
#region IComparable<PropertyPair> Members
/// <summary>
/// Compares the current object with another object of the same type.
/// </summary>
/// <param name="other">An object to compare with this object.</param>
/// <returns>
/// A 32-bit signed integer that indicates the relative order of the objects being compared. The return value has the following meanings: Value Meaning Less than zero This object is less than the other parameter.Zero This object is equal to other. Greater than zero This object is greater than other.
/// </returns>
public int CompareTo(PropertyPair other)
{
if (this.priority == other.priority)
{
return 0;
}
else if (this.priority > other.priority)
{
return 1;
}
else
{
return -1;
}
}
#endregion
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
namespace System.Linq.Expressions.Tests
{
public static class ArrayArrayLengthTests
{
#region Boolean tests
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckBoolArrayArrayLengthTest(bool useInterpreter)
{
CheckBoolArrayArrayLengthExpression(GenerateBoolArrayArray(0), useInterpreter);
CheckBoolArrayArrayLengthExpression(GenerateBoolArrayArray(1), useInterpreter);
CheckBoolArrayArrayLengthExpression(GenerateBoolArrayArray(5), useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckExceptionBoolArrayArrayLengthTest(bool useInterpreter)
{
CheckExceptionBoolArrayArrayLength(null, useInterpreter);
}
#endregion
#region Byte tests
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckByteArrayArrayLengthTest(bool useInterpreter)
{
CheckByteArrayArrayLengthExpression(GenerateByteArrayArray(0), useInterpreter);
CheckByteArrayArrayLengthExpression(GenerateByteArrayArray(1), useInterpreter);
CheckByteArrayArrayLengthExpression(GenerateByteArrayArray(5), useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckExceptionByteArrayArrayLengthTest(bool useInterpreter)
{
CheckExceptionByteArrayArrayLength(null, useInterpreter);
}
#endregion
#region Custom tests
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckCustomArrayArrayLengthTest(bool useInterpreter)
{
CheckCustomArrayArrayLengthExpression(GenerateCustomArrayArray(0), useInterpreter);
CheckCustomArrayArrayLengthExpression(GenerateCustomArrayArray(1), useInterpreter);
CheckCustomArrayArrayLengthExpression(GenerateCustomArrayArray(5), useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckExceptionCustomArrayArrayLengthTest(bool useInterpreter)
{
CheckExceptionCustomArrayArrayLength(null, useInterpreter);
}
#endregion
#region Char tests
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckCharArrayArrayLengthTest(bool useInterpreter)
{
CheckCharArrayArrayLengthExpression(GenerateCharArrayArray(0), useInterpreter);
CheckCharArrayArrayLengthExpression(GenerateCharArrayArray(1), useInterpreter);
CheckCharArrayArrayLengthExpression(GenerateCharArrayArray(5), useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckExceptionCharArrayArrayLengthTest(bool useInterpreter)
{
CheckExceptionCharArrayArrayLength(null, useInterpreter);
}
#endregion
#region Custom2 tests
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckCustom2ArrayArrayLengthTest(bool useInterpreter)
{
CheckCustom2ArrayArrayLengthExpression(GenerateCustom2ArrayArray(0), useInterpreter);
CheckCustom2ArrayArrayLengthExpression(GenerateCustom2ArrayArray(1), useInterpreter);
CheckCustom2ArrayArrayLengthExpression(GenerateCustom2ArrayArray(5), useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckExceptionCustom2ArrayArrayLengthTest(bool useInterpreter)
{
CheckExceptionCustom2ArrayArrayLength(null, useInterpreter);
}
#endregion
#region Decimal tests
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckDecimalArrayArrayLengthTest(bool useInterpreter)
{
CheckDecimalArrayArrayLengthExpression(GenerateDecimalArrayArray(0), useInterpreter);
CheckDecimalArrayArrayLengthExpression(GenerateDecimalArrayArray(1), useInterpreter);
CheckDecimalArrayArrayLengthExpression(GenerateDecimalArrayArray(5), useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckExceptionDecimalArrayArrayLengthTest(bool useInterpreter)
{
CheckExceptionDecimalArrayArrayLength(null, useInterpreter);
}
#endregion
#region Delegate tests
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckDelegateArrayArrayLengthTest(bool useInterpreter)
{
CheckDelegateArrayArrayLengthExpression(GenerateDelegateArrayArray(0), useInterpreter);
CheckDelegateArrayArrayLengthExpression(GenerateDelegateArrayArray(1), useInterpreter);
CheckDelegateArrayArrayLengthExpression(GenerateDelegateArrayArray(5), useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckExceptionDelegateArrayArrayLengthTest(bool useInterpreter)
{
CheckExceptionDelegateArrayArrayLength(null, useInterpreter);
}
#endregion
#region Double tests
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckDoubleArrayArrayLengthTest(bool useInterpreter)
{
CheckDoubleArrayArrayLengthExpression(GenerateDoubleArrayArray(0), useInterpreter);
CheckDoubleArrayArrayLengthExpression(GenerateDoubleArrayArray(1), useInterpreter);
CheckDoubleArrayArrayLengthExpression(GenerateDoubleArrayArray(5), useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckExceptionDoubleArrayArrayLengthTest(bool useInterpreter)
{
CheckExceptionDoubleArrayArrayLength(null, useInterpreter);
}
#endregion
#region Enum tests
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckEnumArrayArrayLengthTest(bool useInterpreter)
{
CheckEnumArrayArrayLengthExpression(GenerateEnumArrayArray(0), useInterpreter);
CheckEnumArrayArrayLengthExpression(GenerateEnumArrayArray(1), useInterpreter);
CheckEnumArrayArrayLengthExpression(GenerateEnumArrayArray(5), useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckExceptionEnumArrayArrayLengthTest(bool useInterpreter)
{
CheckExceptionEnumArrayArrayLength(null, useInterpreter);
}
#endregion
#region EnumLong tests
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckEnumLongArrayArrayLengthTest(bool useInterpreter)
{
CheckEnumLongArrayArrayLengthExpression(GenerateEnumLongArrayArray(0), useInterpreter);
CheckEnumLongArrayArrayLengthExpression(GenerateEnumLongArrayArray(1), useInterpreter);
CheckEnumLongArrayArrayLengthExpression(GenerateEnumLongArrayArray(5), useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckExceptionEnumLongArrayArrayLengthTest(bool useInterpreter)
{
CheckExceptionEnumLongArrayArrayLength(null, useInterpreter);
}
#endregion
#region Float tests
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckFloatArrayArrayLengthTest(bool useInterpreter)
{
CheckFloatArrayArrayLengthExpression(GenerateFloatArrayArray(0), useInterpreter);
CheckFloatArrayArrayLengthExpression(GenerateFloatArrayArray(1), useInterpreter);
CheckFloatArrayArrayLengthExpression(GenerateFloatArrayArray(5), useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckExceptionFloatArrayArrayLengthTest(bool useInterpreter)
{
CheckExceptionFloatArrayArrayLength(null, useInterpreter);
}
#endregion
#region Func tests
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckFuncArrayArrayLengthTest(bool useInterpreter)
{
CheckFuncArrayArrayLengthExpression(GenerateFuncArrayArray(0), useInterpreter);
CheckFuncArrayArrayLengthExpression(GenerateFuncArrayArray(1), useInterpreter);
CheckFuncArrayArrayLengthExpression(GenerateFuncArrayArray(5), useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckExceptionFuncArrayArrayLengthTest(bool useInterpreter)
{
CheckExceptionFuncArrayArrayLength(null, useInterpreter);
}
#endregion
#region Interface tests
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckInterfaceArrayArrayLengthTest(bool useInterpreter)
{
CheckInterfaceArrayArrayLengthExpression(GenerateInterfaceArrayArray(0), useInterpreter);
CheckInterfaceArrayArrayLengthExpression(GenerateInterfaceArrayArray(1), useInterpreter);
CheckInterfaceArrayArrayLengthExpression(GenerateInterfaceArrayArray(5), useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckExceptionInterfaceArrayArrayLengthTest(bool useInterpreter)
{
CheckExceptionInterfaceArrayArrayLength(null, useInterpreter);
}
#endregion
#region IEquatableCustom tests
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckIEquatableCustomArrayArrayLengthTest(bool useInterpreter)
{
CheckIEquatableCustomArrayArrayLengthExpression(GenerateIEquatableCustomArrayArray(0), useInterpreter);
CheckIEquatableCustomArrayArrayLengthExpression(GenerateIEquatableCustomArrayArray(1), useInterpreter);
CheckIEquatableCustomArrayArrayLengthExpression(GenerateIEquatableCustomArrayArray(5), useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckExceptionIEquatableCustomArrayArrayLengthTest(bool useInterpreter)
{
CheckExceptionIEquatableCustomArrayArrayLength(null, useInterpreter);
}
#endregion
#region IEquatableCustom2 tests
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckIEquatableCustom2ArrayArrayLengthTest(bool useInterpreter)
{
CheckIEquatableCustom2ArrayArrayLengthExpression(GenerateIEquatableCustom2ArrayArray(0), useInterpreter);
CheckIEquatableCustom2ArrayArrayLengthExpression(GenerateIEquatableCustom2ArrayArray(1), useInterpreter);
CheckIEquatableCustom2ArrayArrayLengthExpression(GenerateIEquatableCustom2ArrayArray(5), useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckExceptionIEquatableCustom2ArrayArrayLengthTest(bool useInterpreter)
{
CheckExceptionIEquatableCustom2ArrayArrayLength(null, useInterpreter);
}
#endregion
#region Int tests
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckIntArrayArrayLengthTest(bool useInterpreter)
{
CheckIntArrayArrayLengthExpression(GenerateIntArrayArray(0), useInterpreter);
CheckIntArrayArrayLengthExpression(GenerateIntArrayArray(1), useInterpreter);
CheckIntArrayArrayLengthExpression(GenerateIntArrayArray(5), useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckExceptionIntArrayArrayLengthTest(bool useInterpreter)
{
CheckExceptionIntArrayArrayLength(null, useInterpreter);
}
#endregion
#region Long tests
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckLongArrayArrayLengthTest(bool useInterpreter)
{
CheckLongArrayArrayLengthExpression(GenerateLongArrayArray(0), useInterpreter);
CheckLongArrayArrayLengthExpression(GenerateLongArrayArray(1), useInterpreter);
CheckLongArrayArrayLengthExpression(GenerateLongArrayArray(5), useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckExceptionLongArrayArrayLengthTest(bool useInterpreter)
{
CheckExceptionLongArrayArrayLength(null, useInterpreter);
}
#endregion
#region Object tests
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckObjectArrayArrayLengthTest(bool useInterpreter)
{
CheckObjectArrayArrayLengthExpression(GenerateObjectArrayArray(0), useInterpreter);
CheckObjectArrayArrayLengthExpression(GenerateObjectArrayArray(1), useInterpreter);
CheckObjectArrayArrayLengthExpression(GenerateObjectArrayArray(5), useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckExceptionObjectArrayArrayLengthTest(bool useInterpreter)
{
CheckExceptionObjectArrayArrayLength(null, useInterpreter);
}
#endregion
#region Struct tests
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckStructArrayArrayLengthTest(bool useInterpreter)
{
CheckStructArrayArrayLengthExpression(GenerateStructArrayArray(0), useInterpreter);
CheckStructArrayArrayLengthExpression(GenerateStructArrayArray(1), useInterpreter);
CheckStructArrayArrayLengthExpression(GenerateStructArrayArray(5), useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckExceptionStructArrayArrayLengthTest(bool useInterpreter)
{
CheckExceptionStructArrayArrayLength(null, useInterpreter);
}
#endregion
#region SByte tests
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckSByteArrayArrayLengthTest(bool useInterpreter)
{
CheckSByteArrayArrayLengthExpression(GenerateSByteArrayArray(0), useInterpreter);
CheckSByteArrayArrayLengthExpression(GenerateSByteArrayArray(1), useInterpreter);
CheckSByteArrayArrayLengthExpression(GenerateSByteArrayArray(5), useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckExceptionSByteArrayArrayLengthTest(bool useInterpreter)
{
CheckExceptionSByteArrayArrayLength(null, useInterpreter);
}
#endregion
#region StructWithString tests
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckStructWithStringArrayArrayLengthTest(bool useInterpreter)
{
CheckStructWithStringArrayArrayLengthExpression(GenerateStructWithStringArrayArray(0), useInterpreter);
CheckStructWithStringArrayArrayLengthExpression(GenerateStructWithStringArrayArray(1), useInterpreter);
CheckStructWithStringArrayArrayLengthExpression(GenerateStructWithStringArrayArray(5), useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckExceptionStructWithStringArrayArrayLengthTest(bool useInterpreter)
{
CheckExceptionStructWithStringArrayArrayLength(null, useInterpreter);
}
#endregion
#region StructWithStringAndValue tests
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckStructWithStringAndValueArrayArrayLengthTest(bool useInterpreter)
{
CheckStructWithStringAndValueArrayArrayLengthExpression(GenerateStructWithStringAndValueArrayArray(0), useInterpreter);
CheckStructWithStringAndValueArrayArrayLengthExpression(GenerateStructWithStringAndValueArrayArray(1), useInterpreter);
CheckStructWithStringAndValueArrayArrayLengthExpression(GenerateStructWithStringAndValueArrayArray(5), useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckExceptionStructWithStringAndValueArrayArrayLengthTest(bool useInterpreter)
{
CheckExceptionStructWithStringAndValueArrayArrayLength(null, useInterpreter);
}
#endregion
#region Short tests
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckShortArrayArrayLengthTest(bool useInterpreter)
{
CheckShortArrayArrayLengthExpression(GenerateShortArrayArray(0), useInterpreter);
CheckShortArrayArrayLengthExpression(GenerateShortArrayArray(1), useInterpreter);
CheckShortArrayArrayLengthExpression(GenerateShortArrayArray(5), useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckExceptionShortArrayArrayLengthTest(bool useInterpreter)
{
CheckExceptionShortArrayArrayLength(null, useInterpreter);
}
#endregion
#region StructWithTwoValues tests
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckStructWithTwoValuesArrayArrayLengthTest(bool useInterpreter)
{
CheckStructWithTwoValuesArrayArrayLengthExpression(GenerateStructWithTwoValuesArrayArray(0), useInterpreter);
CheckStructWithTwoValuesArrayArrayLengthExpression(GenerateStructWithTwoValuesArrayArray(1), useInterpreter);
CheckStructWithTwoValuesArrayArrayLengthExpression(GenerateStructWithTwoValuesArrayArray(5), useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckExceptionStructWithTwoValuesArrayArrayLengthTest(bool useInterpreter)
{
CheckExceptionStructWithTwoValuesArrayArrayLength(null, useInterpreter);
}
#endregion
#region StructWithValue tests
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckStructWithValueArrayArrayLengthTest(bool useInterpreter)
{
CheckStructWithValueArrayArrayLengthExpression(GenerateStructWithValueArrayArray(0), useInterpreter);
CheckStructWithValueArrayArrayLengthExpression(GenerateStructWithValueArrayArray(1), useInterpreter);
CheckStructWithValueArrayArrayLengthExpression(GenerateStructWithValueArrayArray(5), useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckExceptionStructWithValueArrayArrayLengthTest(bool useInterpreter)
{
CheckExceptionStructWithValueArrayArrayLength(null, useInterpreter);
}
#endregion
#region String tests
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckStringArrayArrayLengthTest(bool useInterpreter)
{
CheckStringArrayArrayLengthExpression(GenerateStringArrayArray(0), useInterpreter);
CheckStringArrayArrayLengthExpression(GenerateStringArrayArray(1), useInterpreter);
CheckStringArrayArrayLengthExpression(GenerateStringArrayArray(5), useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckExceptionStringArrayArrayLengthTest(bool useInterpreter)
{
CheckExceptionStringArrayArrayLength(null, useInterpreter);
}
#endregion
#region UInt tests
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckUIntArrayArrayLengthTest(bool useInterpreter)
{
CheckUIntArrayArrayLengthExpression(GenerateUIntArrayArray(0), useInterpreter);
CheckUIntArrayArrayLengthExpression(GenerateUIntArrayArray(1), useInterpreter);
CheckUIntArrayArrayLengthExpression(GenerateUIntArrayArray(5), useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckExceptionUIntArrayArrayLengthTest(bool useInterpreter)
{
CheckExceptionUIntArrayArrayLength(null, useInterpreter);
}
#endregion
#region ULong tests
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckULongArrayArrayLengthTest(bool useInterpreter)
{
CheckULongArrayArrayLengthExpression(GenerateULongArrayArray(0), useInterpreter);
CheckULongArrayArrayLengthExpression(GenerateULongArrayArray(1), useInterpreter);
CheckULongArrayArrayLengthExpression(GenerateULongArrayArray(5), useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckExceptionULongArrayArrayLengthTest(bool useInterpreter)
{
CheckExceptionULongArrayArrayLength(null, useInterpreter);
}
#endregion
#region UShort tests
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckUShortArrayArrayLengthTest(bool useInterpreter)
{
CheckUShortArrayArrayLengthExpression(GenerateUShortArrayArray(0), useInterpreter);
CheckUShortArrayArrayLengthExpression(GenerateUShortArrayArray(1), useInterpreter);
CheckUShortArrayArrayLengthExpression(GenerateUShortArrayArray(5), useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckExceptionUShortArrayArrayLengthTest(bool useInterpreter)
{
CheckExceptionUShortArrayArrayLength(null, useInterpreter);
}
#endregion
#region Generic tests
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckGenericCustomArrayArrayLengthTest(bool useInterpreter)
{
CheckGenericArrayArrayLengthTestHelper<C>(useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckExceptionGenericCustomArrayArrayLengthTest(bool useInterpreter)
{
CheckExceptionGenericArrayArrayLengthTestHelper<C>(useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckGenericEnumArrayArrayLengthTest(bool useInterpreter)
{
CheckGenericArrayArrayLengthTestHelper<E>(useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckExceptionGenericEnumArrayArrayLengthTest(bool useInterpreter)
{
CheckExceptionGenericArrayArrayLengthTestHelper<E>(useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckGenericObjectArrayArrayLengthTest(bool useInterpreter)
{
CheckGenericArrayArrayLengthTestHelper<object>(useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckExceptionGenericObjectArrayArrayLengthTest(bool useInterpreter)
{
CheckExceptionGenericArrayArrayLengthTestHelper<object>(useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckGenericStructArrayArrayLengthTest(bool useInterpreter)
{
CheckGenericArrayArrayLengthTestHelper<S>(useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckExceptionGenericStructArrayArrayLengthTest(bool useInterpreter)
{
CheckExceptionGenericArrayArrayLengthTestHelper<S>(useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckGenericStructWithStringAndValueArrayArrayLengthTest(bool useInterpreter)
{
CheckGenericArrayArrayLengthTestHelper<Scs>(useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckExceptionGenericStructWithStringAndValueArrayArrayLengthTest(bool useInterpreter)
{
CheckExceptionGenericArrayArrayLengthTestHelper<Scs>(useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckGenericCustomWithClassRestrictionArrayArrayLengthTest(bool useInterpreter)
{
CheckGenericWithClassRestrictionArrayArrayLengthTestHelper<C>(useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckExceptionGenericCustomWithClassRestrictionArrayArrayLengthTest(bool useInterpreter)
{
CheckExceptionGenericWithClassRestrictionArrayArrayLengthTestHelper<C>(useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckGenericObjectWithClassRestrictionArrayArrayLengthTest(bool useInterpreter)
{
CheckGenericWithClassRestrictionArrayArrayLengthTestHelper<object>(useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckExceptionGenericObjectWithClassRestrictionArrayArrayLengthTest(bool useInterpreter)
{
CheckExceptionGenericWithClassRestrictionArrayArrayLengthTestHelper<object>(useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckGenericCustomWithSubClassRestrictionArrayArrayLengthTest(bool useInterpreter)
{
CheckGenericWithSubClassRestrictionArrayArrayLengthTestHelper<C>(useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckExceptionGenericCustomWithSubClassRestrictionArrayArrayLengthTest(bool useInterpreter)
{
CheckExceptionGenericWithSubClassRestrictionArrayArrayLengthTestHelper<C>(useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckGenericCustomWithClassAndNewRestrictionArrayArrayLengthTest(bool useInterpreter)
{
CheckGenericWithClassAndNewRestrictionArrayArrayLengthTestHelper<C>(useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckExceptionGenericCustomWithClassAndNewRestrictionArrayArrayLengthTest(bool useInterpreter)
{
CheckExceptionGenericWithClassAndNewRestrictionArrayArrayLengthTestHelper<C>(useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckGenericObjectWithClassAndNewRestrictionArrayArrayLengthTest(bool useInterpreter)
{
CheckGenericWithClassAndNewRestrictionArrayArrayLengthTestHelper<object>(useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckExceptionGenericObjectWithClassAndNewRestrictionArrayArrayLengthTest(bool useInterpreter)
{
CheckExceptionGenericWithClassAndNewRestrictionArrayArrayLengthTestHelper<object>(useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckGenericCustomWithSubClassAndNewRestrictionArrayArrayLengthTest(bool useInterpreter)
{
CheckGenericWithSubClassAndNewRestrictionArrayArrayLengthTestHelper<C>(useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckExceptionGenericCustomWithSubClassAndNewRestrictionArrayArrayLengthTest(bool useInterpreter)
{
CheckExceptionGenericWithSubClassAndNewRestrictionArrayArrayLengthTestHelper<C>(useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckGenericEnumWithStructRestrictionArrayArrayLengthTest(bool useInterpreter)
{
CheckGenericWithStructRestrictionArrayArrayLengthTestHelper<E>(useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckExceptionGenericEnumWithStructRestrictionArrayArrayLengthTest(bool useInterpreter)
{
CheckExceptionGenericWithStructRestrictionArrayArrayLengthTestHelper<E>(useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckGenericStructWithStructRestrictionArrayArrayLengthTest(bool useInterpreter)
{
CheckGenericWithStructRestrictionArrayArrayLengthTestHelper<S>(useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckExceptionGenericStructWithStructRestrictionArrayArrayLengthTest(bool useInterpreter)
{
CheckExceptionGenericWithStructRestrictionArrayArrayLengthTestHelper<S>(useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckGenericStructWithStringAndValueWithStructRestrictionArrayArrayLengthTest(bool useInterpreter)
{
CheckGenericWithStructRestrictionArrayArrayLengthTestHelper<Scs>(useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckExceptionGenericStructWithStringAndValueWithStructRestrictionArrayArrayLengthTest(bool useInterpreter)
{
CheckExceptionGenericWithStructRestrictionArrayArrayLengthTestHelper<Scs>(useInterpreter);
}
#endregion
#region Generic helpers
public static void CheckGenericArrayArrayLengthTestHelper<T>(bool useInterpreter)
{
CheckGenericArrayArrayLengthExpression<T>(GenerateGenericArrayArray<T>(0), useInterpreter);
CheckGenericArrayArrayLengthExpression<T>(GenerateGenericArrayArray<T>(1), useInterpreter);
CheckGenericArrayArrayLengthExpression<T>(GenerateGenericArrayArray<T>(5), useInterpreter);
}
public static void CheckExceptionGenericArrayArrayLengthTestHelper<T>(bool useInterpreter)
{
CheckExceptionGenericArrayArrayLength<T>(null, useInterpreter);
}
public static void CheckGenericWithClassRestrictionArrayArrayLengthTestHelper<Tc>(bool useInterpreter) where Tc : class
{
CheckGenericWithClassRestrictionArrayArrayLengthExpression<Tc>(GenerateGenericWithClassRestrictionArrayArray<Tc>(0), useInterpreter);
CheckGenericWithClassRestrictionArrayArrayLengthExpression<Tc>(GenerateGenericWithClassRestrictionArrayArray<Tc>(1), useInterpreter);
CheckGenericWithClassRestrictionArrayArrayLengthExpression<Tc>(GenerateGenericWithClassRestrictionArrayArray<Tc>(5), useInterpreter);
}
public static void CheckExceptionGenericWithClassRestrictionArrayArrayLengthTestHelper<Tc>(bool useInterpreter) where Tc : class
{
CheckExceptionGenericWithClassRestrictionArrayArrayLength<Tc>(null, useInterpreter);
}
public static void CheckGenericWithSubClassRestrictionArrayArrayLengthTestHelper<TC>(bool useInterpreter) where TC : C
{
CheckGenericWithSubClassRestrictionArrayArrayLengthExpression<TC>(GenerateGenericWithSubClassRestrictionArrayArray<TC>(0), useInterpreter);
CheckGenericWithSubClassRestrictionArrayArrayLengthExpression<TC>(GenerateGenericWithSubClassRestrictionArrayArray<TC>(1), useInterpreter);
CheckGenericWithSubClassRestrictionArrayArrayLengthExpression<TC>(GenerateGenericWithSubClassRestrictionArrayArray<TC>(5), useInterpreter);
}
public static void CheckExceptionGenericWithSubClassRestrictionArrayArrayLengthTestHelper<TC>(bool useInterpreter) where TC : C
{
CheckExceptionGenericWithSubClassRestrictionArrayArrayLength<TC>(null, useInterpreter);
}
public static void CheckGenericWithClassAndNewRestrictionArrayArrayLengthTestHelper<Tcn>(bool useInterpreter) where Tcn : class, new()
{
CheckGenericWithClassAndNewRestrictionArrayArrayLengthExpression<Tcn>(GenerateGenericWithClassAndNewRestrictionArrayArray<Tcn>(0), useInterpreter);
CheckGenericWithClassAndNewRestrictionArrayArrayLengthExpression<Tcn>(GenerateGenericWithClassAndNewRestrictionArrayArray<Tcn>(1), useInterpreter);
CheckGenericWithClassAndNewRestrictionArrayArrayLengthExpression<Tcn>(GenerateGenericWithClassAndNewRestrictionArrayArray<Tcn>(5), useInterpreter);
}
public static void CheckExceptionGenericWithClassAndNewRestrictionArrayArrayLengthTestHelper<Tcn>(bool useInterpreter) where Tcn : class, new()
{
CheckExceptionGenericWithClassAndNewRestrictionArrayArrayLength<Tcn>(null, useInterpreter);
}
public static void CheckGenericWithSubClassAndNewRestrictionArrayArrayLengthTestHelper<TCn>(bool useInterpreter) where TCn : C, new()
{
CheckGenericWithSubClassAndNewRestrictionArrayArrayLengthExpression<TCn>(GenerateGenericWithSubClassAndNewRestrictionArrayArray<TCn>(0), useInterpreter);
CheckGenericWithSubClassAndNewRestrictionArrayArrayLengthExpression<TCn>(GenerateGenericWithSubClassAndNewRestrictionArrayArray<TCn>(1), useInterpreter);
CheckGenericWithSubClassAndNewRestrictionArrayArrayLengthExpression<TCn>(GenerateGenericWithSubClassAndNewRestrictionArrayArray<TCn>(5), useInterpreter);
}
public static void CheckExceptionGenericWithSubClassAndNewRestrictionArrayArrayLengthTestHelper<TCn>(bool useInterpreter) where TCn : C, new()
{
CheckExceptionGenericWithSubClassAndNewRestrictionArrayArrayLength<TCn>(null, useInterpreter);
}
public static void CheckGenericWithStructRestrictionArrayArrayLengthTestHelper<Ts>(bool useInterpreter) where Ts : struct
{
CheckGenericWithStructRestrictionArrayArrayLengthExpression<Ts>(GenerateGenericWithStructRestrictionArrayArray<Ts>(0), useInterpreter);
CheckGenericWithStructRestrictionArrayArrayLengthExpression<Ts>(GenerateGenericWithStructRestrictionArrayArray<Ts>(1), useInterpreter);
CheckGenericWithStructRestrictionArrayArrayLengthExpression<Ts>(GenerateGenericWithStructRestrictionArrayArray<Ts>(5), useInterpreter);
}
public static void CheckExceptionGenericWithStructRestrictionArrayArrayLengthTestHelper<Ts>(bool useInterpreter) where Ts : struct
{
CheckExceptionGenericWithStructRestrictionArrayArrayLength<Ts>(null, useInterpreter);
}
#endregion
#region Generate array
private static bool[][] GenerateBoolArrayArray(int size)
{
bool[][] array = new bool[][] { null, new bool[0], new bool[] { true, false }, new bool[100] };
bool[][] result = new bool[size][];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static byte[][] GenerateByteArrayArray(int size)
{
byte[][] array = new byte[][] { null, new byte[0], new byte[] { 0, 1, byte.MaxValue }, new byte[100] };
byte[][] result = new byte[size][];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static C[][] GenerateCustomArrayArray(int size)
{
C[][] array = new C[][] { null, new C[0], new C[] { null, new C(), new D(), new D(0), new D(5) }, new C[100] };
C[][] result = new C[size][];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static char[][] GenerateCharArrayArray(int size)
{
char[][] array = new char[][] { null, new char[0], new char[] { '\0', '\b', 'A', '\uffff' }, new char[100] };
char[][] result = new char[size][];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static D[][] GenerateCustom2ArrayArray(int size)
{
D[][] array = new D[][] { null, new D[0], new D[] { null, new D(), new D(0), new D(5) }, new D[100] };
D[][] result = new D[size][];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static decimal[][] GenerateDecimalArrayArray(int size)
{
decimal[][] array = new decimal[][] { null, new decimal[0], new decimal[] { decimal.Zero, decimal.One, decimal.MinusOne, decimal.MinValue, decimal.MaxValue }, new decimal[100] };
decimal[][] result = new decimal[size][];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static Delegate[][] GenerateDelegateArrayArray(int size)
{
Delegate[][] array = new Delegate[][] { null, new Delegate[0], new Delegate[] { null, (Func<object>)delegate () { return null; }, (Func<int, int>)delegate (int i) { return i + 1; }, (Action<object>)delegate { } }, new Delegate[100] };
Delegate[][] result = new Delegate[size][];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static double[][] GenerateDoubleArrayArray(int size)
{
double[][] array = new double[][] { null, new double[0], new double[] { 0, 1, -1, double.MinValue, double.MaxValue, double.Epsilon, double.NegativeInfinity, double.PositiveInfinity, double.NaN }, new double[100] };
double[][] result = new double[size][];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static E[][] GenerateEnumArrayArray(int size)
{
E[][] array = new E[][] { null, new E[0], new E[] { (E)0, E.A, E.B, (E)int.MaxValue, (E)int.MinValue }, new E[100] };
E[][] result = new E[size][];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static El[][] GenerateEnumLongArrayArray(int size)
{
El[][] array = new El[][] { null, new El[0], new El[] { (El)0, El.A, El.B, (El)long.MaxValue, (El)long.MinValue }, new El[100] };
El[][] result = new El[size][];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static float[][] GenerateFloatArrayArray(int size)
{
float[][] array = new float[][] { null, new float[0], new float[] { 0, 1, -1, float.MinValue, float.MaxValue, float.Epsilon, float.NegativeInfinity, float.PositiveInfinity, float.NaN }, new float[100] };
float[][] result = new float[size][];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static Func<object>[][] GenerateFuncArrayArray(int size)
{
Func<object>[][] array = new Func<object>[][] { null, new Func<object>[0], new Func<object>[] { null, (Func<object>)delegate () { return null; } }, new Func<object>[100] };
Func<object>[][] result = new Func<object>[size][];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static I[][] GenerateInterfaceArrayArray(int size)
{
I[][] array = new I[][] { null, new I[0], new I[] { null, new C(), new D(), new D(0), new D(5) }, new I[100] };
I[][] result = new I[size][];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static IEquatable<C>[][] GenerateIEquatableCustomArrayArray(int size)
{
IEquatable<C>[][] array = new IEquatable<C>[][] { null, new IEquatable<C>[0], new IEquatable<C>[] { null, new C(), new D(), new D(0), new D(5) }, new IEquatable<C>[100] };
IEquatable<C>[][] result = new IEquatable<C>[size][];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static IEquatable<D>[][] GenerateIEquatableCustom2ArrayArray(int size)
{
IEquatable<D>[][] array = new IEquatable<D>[][] { null, new IEquatable<D>[0], new IEquatable<D>[] { null, new D(), new D(0), new D(5) }, new IEquatable<D>[100] };
IEquatable<D>[][] result = new IEquatable<D>[size][];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static int[][] GenerateIntArrayArray(int size)
{
int[][] array = new int[][] { null, new int[0], new int[] { 0, 1, -1, int.MinValue, int.MaxValue }, new int[100] };
int[][] result = new int[size][];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static long[][] GenerateLongArrayArray(int size)
{
long[][] array = new long[][] { null, new long[0], new long[] { 0, 1, -1, long.MinValue, long.MaxValue }, new long[100] };
long[][] result = new long[size][];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static object[][] GenerateObjectArrayArray(int size)
{
object[][] array = new object[][] { null, new object[0], new object[] { null, new object(), new C(), new D(3) }, new object[100] };
object[][] result = new object[size][];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static S[][] GenerateStructArrayArray(int size)
{
S[][] array = new S[][] { null, new S[0], new S[] { default(S), new S() }, new S[100] };
S[][] result = new S[size][];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static sbyte[][] GenerateSByteArrayArray(int size)
{
sbyte[][] array = new sbyte[][] { null, new sbyte[0], new sbyte[] { 0, 1, -1, sbyte.MinValue, sbyte.MaxValue }, new sbyte[100] };
sbyte[][] result = new sbyte[size][];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static Sc[][] GenerateStructWithStringArrayArray(int size)
{
Sc[][] array = new Sc[][] { null, new Sc[0], new Sc[] { default(Sc), new Sc(), new Sc(null) }, new Sc[100] };
Sc[][] result = new Sc[size][];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static Scs[][] GenerateStructWithStringAndValueArrayArray(int size)
{
Scs[][] array = new Scs[][] { null, new Scs[0], new Scs[] { default(Scs), new Scs(), new Scs(null, new S()) }, new Scs[100] };
Scs[][] result = new Scs[size][];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static short[][] GenerateShortArrayArray(int size)
{
short[][] array = new short[][] { null, new short[0], new short[] { 0, 1, -1, short.MinValue, short.MaxValue }, new short[100] };
short[][] result = new short[size][];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static Sp[][] GenerateStructWithTwoValuesArrayArray(int size)
{
Sp[][] array = new Sp[][] { null, new Sp[0], new Sp[] { default(Sp), new Sp(), new Sp(5, 5.0) }, new Sp[100] };
Sp[][] result = new Sp[size][];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static Ss[][] GenerateStructWithValueArrayArray(int size)
{
Ss[][] array = new Ss[][] { null, new Ss[0], new Ss[] { default(Ss), new Ss(), new Ss(new S()) }, new Ss[100] };
Ss[][] result = new Ss[size][];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static string[][] GenerateStringArrayArray(int size)
{
string[][] array = new string[][] { null, new string[0], new string[] { null, "", "a", "foo" }, new string[100] };
string[][] result = new string[size][];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static uint[][] GenerateUIntArrayArray(int size)
{
uint[][] array = new uint[][] { null, new uint[0], new uint[] { 0, 1, uint.MaxValue }, new uint[100] };
uint[][] result = new uint[size][];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static ulong[][] GenerateULongArrayArray(int size)
{
ulong[][] array = new ulong[][] { null, new ulong[0], new ulong[] { 0, 1, ulong.MaxValue }, new ulong[100] };
ulong[][] result = new ulong[size][];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static ushort[][] GenerateUShortArrayArray(int size)
{
ushort[][] array = new ushort[][] { null, new ushort[0], new ushort[] { 0, 1, ushort.MaxValue }, new ushort[100] };
ushort[][] result = new ushort[size][];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static T[][] GenerateGenericArrayArray<T>(int size)
{
T[][] array = new T[][] { null, new T[0], new T[] { default(T) }, new T[100] };
T[][] result = new T[size][];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static Tc[][] GenerateGenericWithClassRestrictionArrayArray<Tc>(int size) where Tc : class
{
Tc[][] array = new Tc[][] { null, new Tc[0], new Tc[] { null, default(Tc) }, new Tc[100] };
Tc[][] result = new Tc[size][];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static TC[][] GenerateGenericWithSubClassRestrictionArrayArray<TC>(int size) where TC : C
{
TC[][] array = new TC[][] { null, new TC[0], new TC[] { null, default(TC), (TC)new C() }, new TC[100] };
TC[][] result = new TC[size][];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static Tcn[][] GenerateGenericWithClassAndNewRestrictionArrayArray<Tcn>(int size) where Tcn : class, new()
{
Tcn[][] array = new Tcn[][] { null, new Tcn[0], new Tcn[] { null, default(Tcn), new Tcn() }, new Tcn[100] };
Tcn[][] result = new Tcn[size][];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static TCn[][] GenerateGenericWithSubClassAndNewRestrictionArrayArray<TCn>(int size) where TCn : C, new()
{
TCn[][] array = new TCn[][] { null, new TCn[0], new TCn[] { null, default(TCn), new TCn(), (TCn)new C() }, new TCn[100] };
TCn[][] result = new TCn[size][];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static Ts[][] GenerateGenericWithStructRestrictionArrayArray<Ts>(int size) where Ts : struct
{
Ts[][] array = new Ts[][] { null, new Ts[0], new Ts[] { default(Ts), new Ts() }, new Ts[100] };
Ts[][] result = new Ts[size][];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
#endregion
#region Check length expression
private static void CheckBoolArrayArrayLengthExpression(bool[][] array, bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(bool[][]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(array.Length, f());
}
private static void CheckByteArrayArrayLengthExpression(byte[][] array, bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(byte[][]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(array.Length, f());
}
private static void CheckCustomArrayArrayLengthExpression(C[][] array, bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(C[][]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(array.Length, f());
}
private static void CheckCharArrayArrayLengthExpression(char[][] array, bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(char[][]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(array.Length, f());
}
private static void CheckCustom2ArrayArrayLengthExpression(D[][] array, bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(D[][]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(array.Length, f());
}
private static void CheckDecimalArrayArrayLengthExpression(decimal[][] array, bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(decimal[][]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(array.Length, f());
}
private static void CheckDelegateArrayArrayLengthExpression(Delegate[][] array, bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(Delegate[][]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(array.Length, f());
}
private static void CheckDoubleArrayArrayLengthExpression(double[][] array, bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(double[][]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(array.Length, f());
}
private static void CheckEnumArrayArrayLengthExpression(E[][] array, bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(E[][]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(array.Length, f());
}
private static void CheckEnumLongArrayArrayLengthExpression(El[][] array, bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(El[][]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(array.Length, f());
}
private static void CheckFloatArrayArrayLengthExpression(float[][] array, bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(float[][]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(array.Length, f());
}
private static void CheckFuncArrayArrayLengthExpression(Func<object>[][] array, bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(Func<object>[][]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(array.Length, f());
}
private static void CheckInterfaceArrayArrayLengthExpression(I[][] array, bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(I[][]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(array.Length, f());
}
private static void CheckIEquatableCustomArrayArrayLengthExpression(IEquatable<C>[][] array, bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(IEquatable<C>[][]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(array.Length, f());
}
private static void CheckIEquatableCustom2ArrayArrayLengthExpression(IEquatable<D>[][] array, bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(IEquatable<D>[][]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(array.Length, f());
}
private static void CheckIntArrayArrayLengthExpression(int[][] array, bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(int[][]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(array.Length, f());
}
private static void CheckLongArrayArrayLengthExpression(long[][] array, bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(long[][]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(array.Length, f());
}
private static void CheckObjectArrayArrayLengthExpression(object[][] array, bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(object[][]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(array.Length, f());
}
private static void CheckStructArrayArrayLengthExpression(S[][] array, bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(S[][]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(array.Length, f());
}
private static void CheckSByteArrayArrayLengthExpression(sbyte[][] array, bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(sbyte[][]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(array.Length, f());
}
private static void CheckStructWithStringArrayArrayLengthExpression(Sc[][] array, bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(Sc[][]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(array.Length, f());
}
private static void CheckStructWithStringAndValueArrayArrayLengthExpression(Scs[][] array, bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(Scs[][]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(array.Length, f());
}
private static void CheckShortArrayArrayLengthExpression(short[][] array, bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(short[][]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(array.Length, f());
}
private static void CheckStructWithTwoValuesArrayArrayLengthExpression(Sp[][] array, bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(Sp[][]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(array.Length, f());
}
private static void CheckStructWithValueArrayArrayLengthExpression(Ss[][] array, bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(Ss[][]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(array.Length, f());
}
private static void CheckStringArrayArrayLengthExpression(string[][] array, bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(string[][]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(array.Length, f());
}
private static void CheckUIntArrayArrayLengthExpression(uint[][] array, bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(uint[][]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(array.Length, f());
}
private static void CheckULongArrayArrayLengthExpression(ulong[][] array, bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(ulong[][]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(array.Length, f());
}
private static void CheckUShortArrayArrayLengthExpression(ushort[][] array, bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(ushort[][]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(array.Length, f());
}
private static void CheckGenericArrayArrayLengthExpression<T>(T[][] array, bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(T[][]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(array.Length, f());
}
private static void CheckGenericWithClassRestrictionArrayArrayLengthExpression<Tc>(Tc[][] array, bool useInterpreter) where Tc : class
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(Tc[][]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(array.Length, f());
}
private static void CheckGenericWithSubClassRestrictionArrayArrayLengthExpression<TC>(TC[][] array, bool useInterpreter) where TC : C
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(TC[][]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(array.Length, f());
}
private static void CheckGenericWithClassAndNewRestrictionArrayArrayLengthExpression<Tcn>(Tcn[][] array, bool useInterpreter) where Tcn : class, new()
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(Tcn[][]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(array.Length, f());
}
private static void CheckGenericWithSubClassAndNewRestrictionArrayArrayLengthExpression<TCn>(TCn[][] array, bool useInterpreter) where TCn : C, new()
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(TCn[][]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(array.Length, f());
}
private static void CheckGenericWithStructRestrictionArrayArrayLengthExpression<Ts>(Ts[][] array, bool useInterpreter) where Ts : struct
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(Ts[][]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(array.Length, f());
}
#endregion
#region Check exception array length
private static void CheckExceptionBoolArrayArrayLength(bool[][] array, bool useInterpreter)
{
if (array == null)
Assert.Throws<NullReferenceException>(() => CheckBoolArrayArrayLengthExpression(array, useInterpreter));
else
Assert.Throws<IndexOutOfRangeException>(() => CheckBoolArrayArrayLengthExpression(array, useInterpreter));
}
private static void CheckExceptionByteArrayArrayLength(byte[][] array, bool useInterpreter)
{
if (array == null)
Assert.Throws<NullReferenceException>(() => CheckByteArrayArrayLengthExpression(array, useInterpreter));
else
Assert.Throws<IndexOutOfRangeException>(() => CheckByteArrayArrayLengthExpression(array, useInterpreter));
}
private static void CheckExceptionCustomArrayArrayLength(C[][] array, bool useInterpreter)
{
if (array == null)
Assert.Throws<NullReferenceException>(() => CheckCustomArrayArrayLengthExpression(array, useInterpreter));
else
Assert.Throws<IndexOutOfRangeException>(() => CheckCustomArrayArrayLengthExpression(array, useInterpreter));
}
private static void CheckExceptionCharArrayArrayLength(char[][] array, bool useInterpreter)
{
if (array == null)
Assert.Throws<NullReferenceException>(() => CheckCharArrayArrayLengthExpression(array, useInterpreter));
else
Assert.Throws<IndexOutOfRangeException>(() => CheckCharArrayArrayLengthExpression(array, useInterpreter));
}
private static void CheckExceptionCustom2ArrayArrayLength(D[][] array, bool useInterpreter)
{
if (array == null)
Assert.Throws<NullReferenceException>(() => CheckCustom2ArrayArrayLengthExpression(array, useInterpreter));
else
Assert.Throws<IndexOutOfRangeException>(() => CheckCustom2ArrayArrayLengthExpression(array, useInterpreter));
}
private static void CheckExceptionDecimalArrayArrayLength(decimal[][] array, bool useInterpreter)
{
if (array == null)
Assert.Throws<NullReferenceException>(() => CheckDecimalArrayArrayLengthExpression(array, useInterpreter));
else
Assert.Throws<IndexOutOfRangeException>(() => CheckDecimalArrayArrayLengthExpression(array, useInterpreter));
}
private static void CheckExceptionDelegateArrayArrayLength(Delegate[][] array, bool useInterpreter)
{
if (array == null)
Assert.Throws<NullReferenceException>(() => CheckDelegateArrayArrayLengthExpression(array, useInterpreter));
else
Assert.Throws<IndexOutOfRangeException>(() => CheckDelegateArrayArrayLengthExpression(array, useInterpreter));
}
private static void CheckExceptionDoubleArrayArrayLength(double[][] array, bool useInterpreter)
{
if (array == null)
Assert.Throws<NullReferenceException>(() => CheckDoubleArrayArrayLengthExpression(array, useInterpreter));
else
Assert.Throws<IndexOutOfRangeException>(() => CheckDoubleArrayArrayLengthExpression(array, useInterpreter));
}
private static void CheckExceptionEnumArrayArrayLength(E[][] array, bool useInterpreter)
{
if (array == null)
Assert.Throws<NullReferenceException>(() => CheckEnumArrayArrayLengthExpression(array, useInterpreter));
else
Assert.Throws<IndexOutOfRangeException>(() => CheckEnumArrayArrayLengthExpression(array, useInterpreter));
}
private static void CheckExceptionEnumLongArrayArrayLength(El[][] array, bool useInterpreter)
{
if (array == null)
Assert.Throws<NullReferenceException>(() => CheckEnumLongArrayArrayLengthExpression(array, useInterpreter));
else
Assert.Throws<IndexOutOfRangeException>(() => CheckEnumLongArrayArrayLengthExpression(array, useInterpreter));
}
private static void CheckExceptionFloatArrayArrayLength(float[][] array, bool useInterpreter)
{
if (array == null)
Assert.Throws<NullReferenceException>(() => CheckFloatArrayArrayLengthExpression(array, useInterpreter));
else
Assert.Throws<IndexOutOfRangeException>(() => CheckFloatArrayArrayLengthExpression(array, useInterpreter));
}
private static void CheckExceptionFuncArrayArrayLength(Func<object>[][] array, bool useInterpreter)
{
if (array == null)
Assert.Throws<NullReferenceException>(() => CheckFuncArrayArrayLengthExpression(array, useInterpreter));
else
Assert.Throws<IndexOutOfRangeException>(() => CheckFuncArrayArrayLengthExpression(array, useInterpreter));
}
private static void CheckExceptionInterfaceArrayArrayLength(I[][] array, bool useInterpreter)
{
if (array == null)
Assert.Throws<NullReferenceException>(() => CheckInterfaceArrayArrayLengthExpression(array, useInterpreter));
else
Assert.Throws<IndexOutOfRangeException>(() => CheckInterfaceArrayArrayLengthExpression(array, useInterpreter));
}
private static void CheckExceptionIEquatableCustomArrayArrayLength(IEquatable<C>[][] array, bool useInterpreter)
{
if (array == null)
Assert.Throws<NullReferenceException>(() => CheckIEquatableCustomArrayArrayLengthExpression(array, useInterpreter));
else
Assert.Throws<IndexOutOfRangeException>(() => CheckIEquatableCustomArrayArrayLengthExpression(array, useInterpreter));
}
private static void CheckExceptionIEquatableCustom2ArrayArrayLength(IEquatable<D>[][] array, bool useInterpreter)
{
if (array == null)
Assert.Throws<NullReferenceException>(() => CheckIEquatableCustom2ArrayArrayLengthExpression(array, useInterpreter));
else
Assert.Throws<IndexOutOfRangeException>(() => CheckIEquatableCustom2ArrayArrayLengthExpression(array, useInterpreter));
}
private static void CheckExceptionIntArrayArrayLength(int[][] array, bool useInterpreter)
{
if (array == null)
Assert.Throws<NullReferenceException>(() => CheckIntArrayArrayLengthExpression(array, useInterpreter));
else
Assert.Throws<IndexOutOfRangeException>(() => CheckIntArrayArrayLengthExpression(array, useInterpreter));
}
private static void CheckExceptionLongArrayArrayLength(long[][] array, bool useInterpreter)
{
if (array == null)
Assert.Throws<NullReferenceException>(() => CheckLongArrayArrayLengthExpression(array, useInterpreter));
else
Assert.Throws<IndexOutOfRangeException>(() => CheckLongArrayArrayLengthExpression(array, useInterpreter));
}
private static void CheckExceptionObjectArrayArrayLength(object[][] array, bool useInterpreter)
{
if (array == null)
Assert.Throws<NullReferenceException>(() => CheckObjectArrayArrayLengthExpression(array, useInterpreter));
else
Assert.Throws<IndexOutOfRangeException>(() => CheckObjectArrayArrayLengthExpression(array, useInterpreter));
}
private static void CheckExceptionStructArrayArrayLength(S[][] array, bool useInterpreter)
{
if (array == null)
Assert.Throws<NullReferenceException>(() => CheckStructArrayArrayLengthExpression(array, useInterpreter));
else
Assert.Throws<IndexOutOfRangeException>(() => CheckStructArrayArrayLengthExpression(array, useInterpreter));
}
private static void CheckExceptionSByteArrayArrayLength(sbyte[][] array, bool useInterpreter)
{
if (array == null)
Assert.Throws<NullReferenceException>(() => CheckSByteArrayArrayLengthExpression(array, useInterpreter));
else
Assert.Throws<IndexOutOfRangeException>(() => CheckSByteArrayArrayLengthExpression(array, useInterpreter));
}
private static void CheckExceptionStructWithStringArrayArrayLength(Sc[][] array, bool useInterpreter)
{
if (array == null)
Assert.Throws<NullReferenceException>(() => CheckStructWithStringArrayArrayLengthExpression(array, useInterpreter));
else
Assert.Throws<IndexOutOfRangeException>(() => CheckStructWithStringArrayArrayLengthExpression(array, useInterpreter));
}
private static void CheckExceptionStructWithStringAndValueArrayArrayLength(Scs[][] array, bool useInterpreter)
{
if (array == null)
Assert.Throws<NullReferenceException>(() => CheckStructWithStringAndValueArrayArrayLengthExpression(array, useInterpreter));
else
Assert.Throws<IndexOutOfRangeException>(() => CheckStructWithStringAndValueArrayArrayLengthExpression(array, useInterpreter));
}
private static void CheckExceptionShortArrayArrayLength(short[][] array, bool useInterpreter)
{
if (array == null)
Assert.Throws<NullReferenceException>(() => CheckShortArrayArrayLengthExpression(array, useInterpreter));
else
Assert.Throws<IndexOutOfRangeException>(() => CheckShortArrayArrayLengthExpression(array, useInterpreter));
}
private static void CheckExceptionStructWithTwoValuesArrayArrayLength(Sp[][] array, bool useInterpreter)
{
if (array == null)
Assert.Throws<NullReferenceException>(() => CheckStructWithTwoValuesArrayArrayLengthExpression(array, useInterpreter));
else
Assert.Throws<IndexOutOfRangeException>(() => CheckStructWithTwoValuesArrayArrayLengthExpression(array, useInterpreter));
}
private static void CheckExceptionStructWithValueArrayArrayLength(Ss[][] array, bool useInterpreter)
{
if (array == null)
Assert.Throws<NullReferenceException>(() => CheckStructWithValueArrayArrayLengthExpression(array, useInterpreter));
else
Assert.Throws<IndexOutOfRangeException>(() => CheckStructWithValueArrayArrayLengthExpression(array, useInterpreter));
}
private static void CheckExceptionStringArrayArrayLength(string[][] array, bool useInterpreter)
{
if (array == null)
Assert.Throws<NullReferenceException>(() => CheckStringArrayArrayLengthExpression(array, useInterpreter));
else
Assert.Throws<IndexOutOfRangeException>(() => CheckStringArrayArrayLengthExpression(array, useInterpreter));
}
private static void CheckExceptionUIntArrayArrayLength(uint[][] array, bool useInterpreter)
{
if (array == null)
Assert.Throws<NullReferenceException>(() => CheckUIntArrayArrayLengthExpression(array, useInterpreter));
else
Assert.Throws<IndexOutOfRangeException>(() => CheckUIntArrayArrayLengthExpression(array, useInterpreter));
}
private static void CheckExceptionULongArrayArrayLength(ulong[][] array, bool useInterpreter)
{
if (array == null)
Assert.Throws<NullReferenceException>(() => CheckULongArrayArrayLengthExpression(array, useInterpreter));
else
Assert.Throws<IndexOutOfRangeException>(() => CheckULongArrayArrayLengthExpression(array, useInterpreter));
}
private static void CheckExceptionUShortArrayArrayLength(ushort[][] array, bool useInterpreter)
{
if (array == null)
Assert.Throws<NullReferenceException>(() => CheckUShortArrayArrayLengthExpression(array, useInterpreter));
else
Assert.Throws<IndexOutOfRangeException>(() => CheckUShortArrayArrayLengthExpression(array, useInterpreter));
}
private static void CheckExceptionGenericArrayArrayLength<T>(T[][] array, bool useInterpreter)
{
if (array == null)
Assert.Throws<NullReferenceException>(() => CheckGenericArrayArrayLengthExpression(array, useInterpreter));
else
Assert.Throws<IndexOutOfRangeException>(() => CheckGenericArrayArrayLengthExpression(array, useInterpreter));
}
private static void CheckExceptionGenericWithClassRestrictionArrayArrayLength<Tc>(Tc[][] array, bool useInterpreter) where Tc : class
{
if (array == null)
Assert.Throws<NullReferenceException>(() => CheckGenericWithClassRestrictionArrayArrayLengthExpression(array, useInterpreter));
else
Assert.Throws<IndexOutOfRangeException>(() => CheckGenericWithClassRestrictionArrayArrayLengthExpression(array, useInterpreter));
}
private static void CheckExceptionGenericWithSubClassRestrictionArrayArrayLength<TC>(TC[][] array, bool useInterpreter) where TC : C
{
if (array == null)
Assert.Throws<NullReferenceException>(() => CheckGenericWithSubClassRestrictionArrayArrayLengthExpression(array, useInterpreter));
else
Assert.Throws<IndexOutOfRangeException>(() => CheckGenericWithSubClassRestrictionArrayArrayLengthExpression(array, useInterpreter));
}
private static void CheckExceptionGenericWithClassAndNewRestrictionArrayArrayLength<Tcn>(Tcn[][] array, bool useInterpreter) where Tcn : class, new()
{
if (array == null)
Assert.Throws<NullReferenceException>(() => CheckGenericWithClassAndNewRestrictionArrayArrayLengthExpression(array, useInterpreter));
else
Assert.Throws<IndexOutOfRangeException>(() => CheckGenericWithClassAndNewRestrictionArrayArrayLengthExpression(array, useInterpreter));
}
private static void CheckExceptionGenericWithSubClassAndNewRestrictionArrayArrayLength<TCn>(TCn[][] array, bool useInterpreter) where TCn : C, new()
{
if (array == null)
Assert.Throws<NullReferenceException>(() => CheckGenericWithSubClassAndNewRestrictionArrayArrayLengthExpression(array, useInterpreter));
else
Assert.Throws<IndexOutOfRangeException>(() => CheckGenericWithSubClassAndNewRestrictionArrayArrayLengthExpression(array, useInterpreter));
}
private static void CheckExceptionGenericWithStructRestrictionArrayArrayLength<Ts>(Ts[][] array, bool useInterpreter) where Ts : struct
{
if (array == null)
Assert.Throws<NullReferenceException>(() => CheckGenericWithStructRestrictionArrayArrayLengthExpression(array, useInterpreter));
else
Assert.Throws<IndexOutOfRangeException>(() => CheckGenericWithStructRestrictionArrayArrayLengthExpression(array, useInterpreter));
}
#endregion
#region Regression tests
[Fact]
public static void ArrayLength_MultiDimensionalOf1()
{
foreach (var e in new Expression[] { Expression.Parameter(typeof(int).MakeArrayType(1)), Expression.Constant(new int[2, 2]) })
{
AssertExtensions.Throws<ArgumentException>("array", () => Expression.ArrayLength(e));
}
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Dynamic.Utils;
using static System.Linq.Expressions.CachedReflectionInfo;
namespace System.Linq.Expressions.Compiler
{
/// <summary>
/// This type tracks "runtime" constants--live objects that appear in
/// ConstantExpression nodes and must be bound to the delegate.
/// </summary>
internal sealed class BoundConstants
{
/// <summary>
/// Constants can emit themselves as different types
/// For caching purposes, we need to treat each distinct Type as a
/// separate thing to cache. (If we have to cast it on the way out, it
/// ends up using a JIT temp and defeats the purpose of caching the
/// value in a local)
/// </summary>
private struct TypedConstant : IEquatable<TypedConstant>
{
internal readonly object Value;
internal readonly Type Type;
internal TypedConstant(object value, Type type)
{
Value = value;
Type = type;
}
public override int GetHashCode()
{
return RuntimeHelpers.GetHashCode(Value) ^ Type.GetHashCode();
}
public bool Equals(TypedConstant other)
{
return object.ReferenceEquals(Value, other.Value) && Type.Equals(other.Type);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2231:OverloadOperatorEqualsOnOverridingValueTypeEquals")]
public override bool Equals(object obj)
{
return (obj is TypedConstant) && Equals((TypedConstant)obj);
}
}
/// <summary>
/// The list of constants in the order they appear in the constant array
/// </summary>
private readonly List<object> _values = new List<object>();
/// <summary>
/// The index of each constant in the constant array
/// </summary>
private readonly Dictionary<object, int> _indexes = new Dictionary<object, int>(ReferenceEqualityComparer<object>.Instance);
/// <summary>
/// Each constant referenced within this lambda, and how often it was referenced
/// </summary>
private readonly Dictionary<TypedConstant, int> _references = new Dictionary<TypedConstant, int>();
/// <summary>
/// IL locals for storing frequently used constants
/// </summary>
private readonly Dictionary<TypedConstant, LocalBuilder> _cache = new Dictionary<TypedConstant, LocalBuilder>();
internal int Count => _values.Count;
internal object[] ToArray()
{
return _values.ToArray();
}
/// <summary>
/// Called by VariableBinder. Adds the constant to the list (if needed)
/// and increases the reference count by one
/// </summary>
internal void AddReference(object value, Type type)
{
if (!_indexes.ContainsKey(value))
{
_indexes.Add(value, _values.Count);
_values.Add(value);
}
Helpers.IncrementCount(new TypedConstant(value, type), _references);
}
/// <summary>
/// Emits a live object as a constant
/// </summary>
internal void EmitConstant(LambdaCompiler lc, object value, Type type)
{
Debug.Assert(!ILGen.CanEmitConstant(value, type));
#if FEATURE_COMPILE_TO_METHODBUILDER
if (!lc.CanEmitBoundConstants)
{
throw Error.CannotCompileConstant(value);
}
#endif
LocalBuilder local;
if (_cache.TryGetValue(new TypedConstant(value, type), out local))
{
lc.IL.Emit(OpCodes.Ldloc, local);
return;
}
EmitConstantsArray(lc);
EmitConstantFromArray(lc, value, type);
}
/// <summary>
/// Emit code to cache frequently used constants into IL locals,
/// instead of pulling them out of the array each time
/// </summary>
internal void EmitCacheConstants(LambdaCompiler lc)
{
int count = 0;
foreach (KeyValuePair<TypedConstant, int> reference in _references)
{
#if FEATURE_COMPILE_TO_METHODBUILDER
if (!lc.CanEmitBoundConstants)
{
throw Error.CannotCompileConstant(reference.Key.Value);
}
#endif
if (ShouldCache(reference.Value))
{
count++;
}
}
if (count == 0)
{
return;
}
EmitConstantsArray(lc);
// The same lambda can be in multiple places in the tree, so we
// need to clear any locals from last time.
_cache.Clear();
foreach (KeyValuePair<TypedConstant, int> reference in _references)
{
if (ShouldCache(reference.Value))
{
if (--count > 0)
{
// Dup array to keep it on the stack
lc.IL.Emit(OpCodes.Dup);
}
LocalBuilder local = lc.IL.DeclareLocal(reference.Key.Type);
EmitConstantFromArray(lc, reference.Key.Value, local.LocalType);
lc.IL.Emit(OpCodes.Stloc, local);
_cache.Add(reference.Key, local);
}
}
}
private static bool ShouldCache(int refCount)
{
// This caching is too aggressive in the face of conditionals and
// switch. Also, it is too conservative for variables used inside
// of loops.
return refCount > 2;
}
private static void EmitConstantsArray(LambdaCompiler lc)
{
#if FEATURE_COMPILE_TO_METHODBUILDER
Debug.Assert(lc.CanEmitBoundConstants); // this should've been checked already
#endif
lc.EmitClosureArgument();
lc.IL.Emit(OpCodes.Ldfld, Closure_Constants);
}
private void EmitConstantFromArray(LambdaCompiler lc, object value, Type type)
{
int index;
if (!_indexes.TryGetValue(value, out index))
{
_indexes.Add(value, index = _values.Count);
_values.Add(value);
}
lc.IL.EmitPrimitive(index);
lc.IL.Emit(OpCodes.Ldelem_Ref);
if (type.IsValueType)
{
lc.IL.Emit(OpCodes.Unbox_Any, type);
}
else if (type != typeof(object))
{
lc.IL.Emit(OpCodes.Castclass, type);
}
}
}
}
| |
using System;
using System.Globalization;
using System.IO;
using System.Net;
using System.Threading.Tasks;
using Newtonsoft.Json;
using WireMock.Logging;
using WireMock.Matchers;
using WireMock.RequestBuilders;
using WireMock.ResponseBuilders;
using WireMock.Server;
using WireMock.Settings;
using WireMock.Types;
using WireMock.Util;
namespace WireMock.Net.ConsoleApplication
{
public interface IHandleBarTransformer
{
string Name { get; }
void Render(TextWriter textWriter, dynamic context, object[] arguments);
}
public class CustomNameTransformer : IHandleBarTransformer
{
public string Name => "CustomName";
public void Render(TextWriter writer, dynamic context, object[] parameters)
{
/* Handlebar logic to render */
}
}
public static class MainApp
{
public static void Run()
{
var s = WireMockServer.Start();
s.Stop();
string url1 = "http://localhost:9091/";
string url2 = "http://localhost:9092/";
string url3 = "https://localhost:9443/";
var server = WireMockServer.Start(new WireMockServerSettings
{
AllowCSharpCodeMatcher = true,
Urls = new[] { url1, url2, url3 },
StartAdminInterface = true,
ReadStaticMappings = true,
WatchStaticMappings = true,
WatchStaticMappingsInSubdirectories = true,
//ProxyAndRecordSettings = new ProxyAndRecordSettings
//{
// SaveMapping = true
//},
PreWireMockMiddlewareInit = app => { System.Console.WriteLine($"PreWireMockMiddlewareInit : {app.GetType()}"); },
PostWireMockMiddlewareInit = app => { System.Console.WriteLine($"PostWireMockMiddlewareInit : {app.GetType()}"); },
#if USE_ASPNETCORE
AdditionalServiceRegistration = services => { System.Console.WriteLine($"AdditionalServiceRegistration : {services.GetType()}"); },
#endif
Logger = new WireMockConsoleLogger(),
HandlebarsRegistrationCallback = (handlebarsContext, fileSystemHandler) =>
{
var transformer = new CustomNameTransformer();
// handlebarsContext.RegisterHelper(transformer.Name, transformer.Render); TODO
},
// Uncomment below if you want to use the CustomFileSystemFileHandler
// FileSystemHandler = new CustomFileSystemFileHandler()
});
System.Console.WriteLine("WireMockServer listening at {0}", string.Join(",", server.Urls));
server.SetBasicAuthentication("a", "b");
//server.SetAzureADAuthentication("6c2a4722-f3b9-4970-b8fc-fac41e29stef", "8587fde1-7824-42c7-8592-faf92b04stef");
// server.AllowPartialMapping();
server.Given(Request.Create().WithPath("/mypath").UsingPost())
.RespondWith(Response.Create()
.WithHeader("Content-Type", "application/json")
.WithBodyAsJson("{{JsonPath.SelectToken request.body \"..name\"}}")
.WithTransformer()
);
server
.Given(Request.Create().WithPath(p => p.Contains("x")).UsingGet())
.AtPriority(4)
.RespondWith(Response.Create()
.WithStatusCode(200)
.WithHeader("Content-Type", "application/json")
.WithBody(@"{ ""result"": ""Contains x with FUNC 200""}"));
server
.Given(Request.Create()
.UsingGet()
.WithPath("/proxy-test-keep-alive")
)
.RespondWith(Response.Create()
.WithHeader("Keep-Alive", "timeout=1, max=1")
);
server
.Given(Request.Create()
.UsingPost()
.WithHeader("postmanecho", "post")
)
.RespondWith(Response.Create()
.WithProxy(new ProxyAndRecordSettings { Url = "http://postman-echo.com" })
);
server
.Given(Request.Create()
.UsingGet()
.WithHeader("postmanecho", "get")
)
.RespondWith(Response.Create()
.WithProxy(new ProxyAndRecordSettings { Url = "http://postman-echo.com/get" })
);
server
.Given(Request.Create()
.UsingGet()
.WithHeader("postmanecho", "get2")
)
.RespondWith(Response.Create()
.WithProxy(new ProxyAndRecordSettings
{
Url = "http://postman-echo.com/get",
WebProxySettings = new WebProxySettings
{
Address = "http://company",
UserName = "test",
Password = "pwd"
}
})
);
server
.Given(Request.Create()
.UsingGet()
.WithPath("/proxy-execute-keep-alive")
)
.RespondWith(Response.Create()
.WithProxy(new ProxyAndRecordSettings { Url = "http://localhost:9999", ExcludedHeaders = new[] { "Keep-Alive" } })
.WithHeader("Keep-Alive-Test", "stef")
);
server
.Given(Request.Create()
.WithPath("/xpath").UsingPost()
.WithBody(new XPathMatcher("/todo-list[count(todo-item) = 3]"))
)
.RespondWith(Response.Create().WithBody("XPathMatcher!"));
server
.Given(Request.Create()
.WithPath("/xpaths").UsingPost()
.WithBody(new[] { new XPathMatcher("/todo-list[count(todo-item) = 3]"), new XPathMatcher("/todo-list[count(todo-item) = 4]") })
)
.RespondWith(Response.Create().WithBody("xpaths!"));
server
.Given(Request
.Create()
.WithPath("/jsonthings")
.WithBody(new JsonPathMatcher("$.things[?(@.name == 'RequiredThing')]"))
.UsingPut())
.RespondWith(Response.Create()
.WithBody(@"{ ""result"": ""JsonPathMatcher !!!""}"));
server
.Given(Request
.Create()
.WithPath("/jsonbodytest1")
.WithBody(new JsonMatcher("{ \"x\": 42, \"s\": \"s\" }"))
.UsingPost())
.WithGuid("debaf408-3b23-4c04-9d18-ef1c020e79f2")
.RespondWith(Response.Create()
.WithBody(@"{ ""result"": ""jsonbodytest1"" }"));
server
.Given(Request
.Create()
.WithPath("/jsonbodytest2")
.WithBody(new JsonMatcher(new { x = 42, s = "s" }))
.UsingPost())
.WithGuid("debaf408-3b23-4c04-9d18-ef1c020e79f3")
.RespondWith(Response.Create()
.WithBody(@"{ ""result"": ""jsonbodytest2"" }"));
server
.Given(Request
.Create()
.WithPath(new WildcardMatcher("/navision/OData/Company('My Company')/School*", true))
.WithParam("$filter", "(substringof(Code, 'WA')")
.UsingGet())
.RespondWith(Response.Create()
.WithHeader("Content-Type", "application/json")
.WithBody(@"{ ""result"": ""odata""}"));
server
.Given(Request
.Create()
.WithPath(new WildcardMatcher("/param2", true))
.WithParam("key", "test")
.UsingGet())
.RespondWith(Response.Create()
.WithHeader("Content-Type", "application/json")
.WithBodyAsJson(new { result = "param2" }));
server
.Given(Request
.Create()
.WithPath(new WildcardMatcher("/param3", true))
.WithParam("key", new WildcardMatcher("t*"))
.UsingGet())
.RespondWith(Response.Create()
.WithHeader("Content-Type", "application/json")
.WithBodyAsJson(new { result = "param3" }));
server
.Given(Request.Create().WithPath("/headers", "/headers_test").UsingPost().WithHeader("Content-Type", "application/json*"))
.RespondWith(Response.Create()
.WithStatusCode(201)
.WithHeader("Content-Type", "application/json")
.WithBodyAsJson(new { result = "data:headers posted with 201" }));
if (!System.IO.File.Exists(@"c:\temp\x.json"))
{
System.IO.File.WriteAllText(@"c:\temp\x.json", "{ \"hello\": \"world\", \"answer\": 42 }");
}
server
.Given(Request.Create().WithPath("/file").UsingGet())
.RespondWith(Response.Create()
.WithBodyFromFile(@"c:\temp\x.json", false)
);
server
.Given(Request.Create().WithPath("/filecache").UsingGet())
.RespondWith(Response.Create()
.WithBodyFromFile(@"c:\temp\x.json")
);
server
.Given(Request.Create().WithPath("/file_rel").UsingGet())
.WithGuid("0000aaaa-fcf4-4256-a0d3-1c76e4862947")
.RespondWith(Response.Create()
.WithHeader("Content-Type", "application/xml")
.WithBodyFromFile("WireMock.Net.xml", false)
);
server
.Given(Request.Create().WithHeader("ProxyThis", "true")
.UsingGet())
.RespondWith(Response.Create()
.WithProxy("http://www.google.com")
);
server
.Given(Request.Create().WithHeader("ProxyThisHttps", "true")
.UsingGet())
.RespondWith(Response.Create()
.WithProxy("https://www.google.com")
);
server
.Given(Request.Create().WithPath("/bodyasbytes.png")
.UsingGet())
.RespondWith(Response.Create()
.WithHeader("Content-Type", "image/png")
.WithBody(Convert.FromBase64String("iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAIAAAACUFjqAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAZdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuMTczbp9jAAAAJ0lEQVQoU2NgUPuPD6Hz0RCEAtJoiAxpCCBXGgmRIo0TofORkdp/AMiMdRVnV6O0AAAAAElFTkSuQmCC"))
);
server
.Given(Request.Create().WithPath("/oauth2/access").UsingPost().WithBody("grant_type=password;username=u;password=p"))
.RespondWith(Response.Create()
.WithStatusCode(200)
.WithHeader("Content-Type", "application/json")
.WithBodyAsJson(new { access_token = "AT", refresh_token = "RT" }));
server
.Given(Request.Create().WithPath("/helloworld").UsingGet().WithHeader("Authorization", new RegexMatcher("^(?i)Bearer AT$")))
.RespondWith(Response.Create()
.WithStatusCode(200)
.WithBody("hi"));
server
.Given(Request.Create().WithPath("/data").UsingPost().WithBody(b => b != null && b.Contains("e")))
.AtPriority(999)
.RespondWith(Response.Create()
.WithStatusCode(201)
.WithHeader("Content-Type", "application/json")
.WithBodyAsJson(new { result = "data posted with FUNC 201" }));
server
.Given(Request.Create().WithPath("/json").UsingPost().WithBody(new JsonPathMatcher("$.things[?(@.name == 'RequiredThing')]")))
.RespondWith(Response.Create()
.WithStatusCode(201)
.WithHeader("Content-Type", "application/json")
.WithBody(@"{ ""result"": ""json posted with 201""}"));
server
.Given(Request.Create().WithPath("/json2").UsingPost().WithBody("x"))
.RespondWith(Response.Create()
.WithStatusCode(201)
.WithHeader("Content-Type", "application/json")
.WithBody(@"{ ""result"": ""json posted with x - 201""}"));
server
.Given(Request.Create().WithPath("/data").UsingDelete())
.RespondWith(Response.Create()
.WithStatusCode(200)
.WithHeader("Content-Type", "application/json")
.WithBody(@"{ ""result"": ""data deleted with 200""}"));
server
.Given(Request.Create()
.WithPath("/needs-a-key")
.UsingGet()
.WithHeader("api-key", "*", MatchBehaviour.AcceptOnMatch)
.UsingAnyMethod())
.RespondWith(Response.Create()
.WithStatusCode(HttpStatusCode.OK)
.WithBody(@"{ ""result"": ""api-key found""}"));
server
.Given(Request.Create()
.WithPath("/needs-a-key")
.UsingGet()
.WithHeader("api-key", "*", MatchBehaviour.RejectOnMatch)
.UsingAnyMethod())
.RespondWith(Response.Create()
.WithStatusCode(HttpStatusCode.Unauthorized)
.WithBody(@"{ ""result"": ""api-key missing""}"));
server
.Given(Request.Create().WithPath("/nobody").UsingGet())
.RespondWith(Response.Create().WithDelay(TimeSpan.FromSeconds(1))
.WithStatusCode(200));
server
.Given(Request.Create().WithPath("/partial").UsingPost().WithBody(new SimMetricsMatcher(new[] { "cat", "dog" })))
.RespondWith(Response.Create().WithStatusCode(200).WithBody("partial = 200"));
// http://localhost:9091/trans?start=1000&stop=1&stop=2
server
.Given(Request.Create().WithPath("/trans").UsingGet())
.WithGuid("90356dba-b36c-469a-a17e-669cd84f1f05")
.RespondWith(Response.Create()
.WithStatusCode(200)
.WithHeader("Content-Type", "application/json")
.WithHeader("Transformed-Postman-Token", "token is {{request.headers.Postman-Token}}")
.WithHeader("xyz_{{request.headers.Postman-Token}}", "token is {{request.headers.Postman-Token}}")
.WithBody(@"{""msg"": ""Hello world CATCH-ALL on /*, {{request.path}}, add={{Math.Add request.query.start.[0] 42}} bykey={{request.query.start}}, bykey={{request.query.stop}}, byidx0={{request.query.stop.[0]}}, byidx1={{request.query.stop.[1]}}"" }")
.WithTransformer(TransformerType.Handlebars, true, ReplaceNodeOptions.None)
.WithDelay(TimeSpan.FromMilliseconds(100))
);
server
.Given(Request.Create().WithPath("/jsonpathtestToken").UsingPost())
.RespondWith(Response.Create()
.WithHeader("Content-Type", "application/json")
.WithBody("{{JsonPath.SelectToken request.body \"$.Manufacturers[?(@.Name == 'Acme Co')]\"}}")
.WithTransformer()
);
server
.Given(Request.Create().WithPath("/zubinix").UsingPost())
.RespondWith(Response.Create()
.WithHeader("Content-Type", "application/json")
.WithBody("{ \"result\": \"{{JsonPath.SelectToken request.bodyAsJson \"username\"}}\" }")
.WithTransformer()
);
server
.Given(Request.Create().WithPath("/zubinix2").UsingPost())
.RespondWith(Response.Create()
.WithHeader("Content-Type", "application/json")
.WithBodyAsJson(new { path = "{{request.path}}", result = "{{JsonPath.SelectToken request.bodyAsJson \"username\"}}" })
.WithTransformer()
);
server
.Given(Request.Create().WithPath("/jsonpathtestTokenJson").UsingPost())
.RespondWith(Response.Create()
.WithHeader("Content-Type", "application/json")
.WithBodyAsJson(new { status = "OK", url = "{{request.url}}", transformed = "{{JsonPath.SelectToken request.body \"$.Manufacturers[?(@.Name == 'Acme Co')]\"}}" })
.WithTransformer()
);
server
.Given(Request.Create().WithPath("/jsonpathtestTokens").UsingPost())
.RespondWith(Response.Create()
.WithHeader("Content-Type", "application/json")
.WithBody("[{{#JsonPath.SelectTokens request.body \"$..Products[?(@.Price >= 50)].Name\"}} { \"idx\":{{id}}, \"value\":\"{{value}}\" }, {{/JsonPath.SelectTokens}} {} ]")
.WithTransformer()
);
server
.Given(Request.Create()
.WithPath("/state1")
.UsingGet())
.InScenario("s1")
.WillSetStateTo("Test state 1")
.RespondWith(Response.Create()
.WithBody("No state msg 1"));
server
.Given(Request.Create()
.WithPath("/foostate1")
.UsingGet())
.InScenario("s1")
.WhenStateIs("Test state 1")
.RespondWith(Response.Create()
.WithBody("Test state msg 1"));
server
.Given(Request.Create()
.WithPath("/state2")
.UsingGet())
.InScenario("s2")
.WillSetStateTo("Test state 2")
.RespondWith(Response.Create()
.WithBody("No state msg 2"));
server
.Given(Request.Create()
.WithPath("/foostate2")
.UsingGet())
.InScenario("s2")
.WhenStateIs("Test state 2")
.RespondWith(Response.Create()
.WithBody("Test state msg 2"));
server
.Given(Request.Create().WithPath("/encoded-test/a%20b"))
.RespondWith(Response.Create()
.WithBody("EncodedTest 1 : Path={{request.path}}, Url={{request.url}}")
.WithTransformer()
);
server
.Given(Request.Create().WithPath("/encoded-test/a b"))
.RespondWith(Response.Create()
.WithBody("EncodedTest 2 : Path={{request.path}}, Url={{request.url}}")
.WithTransformer()
);
// https://stackoverflow.com/questions/51985089/wiremock-request-matching-with-comparison-between-two-query-parameters
server
.Given(Request.Create().WithPath("/linq")
.WithParam("from", new LinqMatcher("DateTime.Parse(it) > \"2018-03-01 00:00:00\"")))
.RespondWith(Response.Create()
.WithBody("linq match !!!")
);
server
.Given(Request.Create().WithPath("/linq2")
.WithBody(new LinqMatcher("it.applicationId != null"))
.UsingPost()
)
.RespondWith(Response.Create()
.WithBody("linq2 match !!!")
);
server
.Given(Request.Create().WithPath("/myendpoint").UsingAnyMethod())
.RespondWith(Response.Create()
.WithStatusCode(500)
.WithBody(requestMessage =>
{
return JsonConvert.SerializeObject(new
{
Message = "Test error"
});
})
);
server
.Given(Request.Create().WithPath("/random"))
.RespondWith(Response.Create()
.WithHeader("Content-Type", "application/json")
.WithBodyAsJson(new
{
Xeger1 = "{{Xeger \"\\w{4}\\d{5}\"}}",
Xeger2 = "{{Xeger \"\\d{5}\"}}",
TextRegexPostcode = "{{Random Type=\"TextRegex\" Pattern=\"[1-9][0-9]{3}[A-Z]{2}\"}}",
Text = "{{Random Type=\"Text\" Min=8 Max=20}}",
TextLipsum = "{{Random Type=\"TextLipsum\"}}",
IBAN = "{{Random Type=\"IBAN\" CountryCode=\"NL\"}}",
TimeSpan1 = "{{Random Type=\"TimeSpan\" Format=\"c\" IncludeMilliseconds=false}}",
TimeSpan2 = "{{Random Type=\"TimeSpan\"}}",
DateTime1 = "{{Random Type=\"DateTime\"}}",
DateTimeNow = DateTime.Now,
DateTimeNowToString = DateTime.Now.ToString("s", CultureInfo.InvariantCulture),
Guid1 = "{{Random Type=\"Guid\" Uppercase=false}}",
Guid2 = "{{Random Type=\"Guid\"}}",
Guid3 = "{{Random Type=\"Guid\" Format=\"X\"}}",
Boolean = "{{Random Type=\"Boolean\"}}",
Integer = "{{Random Type=\"Integer\" Min=1000 Max=9999}}",
Long = "{{#Random Type=\"Long\" Min=10000000 Max=99999999}}{{this}}{{/Random}}",
Double = "{{Random Type=\"Double\" Min=10 Max=99}}",
Float = "{{Random Type=\"Float\" Min=100 Max=999}}",
IP4Address = "{{Random Type=\"IPv4Address\" Min=\"10.2.3.4\"}}",
IP6Address = "{{Random Type=\"IPv6Address\"}}",
MACAddress = "{{Random Type=\"MACAddress\" Separator=\"-\"}}",
StringListValue = "{{Random Type=\"StringList\" Values=[\"a\", \"b\", \"c\"]}}"
})
.WithTransformer()
);
server
.Given(Request.Create()
.UsingPost()
.WithPath("/xpathsoap")
.WithBody(new XPathMatcher("//*[local-name() = 'getMyData']"))
)
.RespondWith(Response.Create()
.WithHeader("Content-Type", "application/xml")
.WithBody("<xml>ok</xml>")
);
server
.Given(Request.Create()
.UsingPost()
.WithPath("/post_with_query")
.WithHeader("PRIVATE-TOKEN", "t")
.WithParam("name", "stef")
.WithParam("path", "p")
.WithParam("visibility", "Private")
.WithParam("parent_id", "1")
)
.RespondWith(Response.Create()
.WithBody("OK : post_with_query")
);
server.Given(Request.Create()
.WithPath("/services/query/")
.WithParam("q", "SELECT Id from User where username='[email protected]'")
.UsingGet())
.RespondWith(Response.Create()
.WithStatusCode(200)
.WithHeader("Content-Type", "application/json")
.WithBodyAsJson(new { Id = "5bdf076c-5654-4b3e-842c-7caf1fabf8c9" }));
server
.Given(Request.Create().WithPath("/random200or505").UsingGet())
.RespondWith(Response.Create().WithCallback(request =>
{
int code = new Random().Next(1, 2) == 1 ? 505 : 200;
return new ResponseMessage
{
BodyData = new BodyData { BodyAsString = "random200or505:" + code, DetectedBodyType = Types.BodyType.String },
StatusCode = code
};
}));
server
.Given(Request.Create().WithPath("/random200or505async").UsingGet())
.RespondWith(Response.Create().WithCallback(async request =>
{
await Task.Delay(1).ConfigureAwait(false);
int code = new Random().Next(1, 2) == 1 ? 505 : 200;
return new ResponseMessage
{
BodyData = new BodyData { BodyAsString = "random200or505async:" + code, DetectedBodyType = Types.BodyType.String },
StatusCode = code
};
}));
System.Console.WriteLine(JsonConvert.SerializeObject(server.MappingModels, Formatting.Indented));
System.Console.WriteLine("Press any key to stop the server");
System.Console.ReadKey();
server.Stop();
System.Console.WriteLine("Displaying all requests");
var allRequests = server.LogEntries;
System.Console.WriteLine(JsonConvert.SerializeObject(allRequests, Formatting.Indented));
System.Console.WriteLine("Press any key to quit");
System.Console.ReadKey();
server.Stop();
server.Dispose();
}
}
}
| |
// <copyright file=AxisAlignedBox.cs
// <copyright>
// Copyright (c) 2016, University of Stuttgart
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the Software),
// to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
// OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
// <license>MIT License</license>
// <main contributors>
// Markus Funk, Thomas Kosch, Sven Mayer
// </main contributors>
// <co-contributors>
// Paul Brombosch, Mai El-Komy, Juana Heusler,
// Matthias Hoppe, Robert Konrad, Alexander Martin
// </co-contributors>
// <patent information>
// We are aware that this software implements patterns and ideas,
// which might be protected by patents in your country.
// Example patents in Germany are:
// Patent reference number: DE 103 20 557.8
// Patent reference number: DE 10 2013 220 107.9
// Please make sure when using this software not to violate any existing patents in your country.
// </patent information>
// <date> 11/2/2016 12:25:57 PM</date>
using HciLab.Utilities.Mathematics.Core;
using System;
using System.ComponentModel;
using System.Runtime.Serialization;
using System.Text.RegularExpressions;
namespace HciLab.Utilities.Mathematics.Geometry2D
{
/// <summary>
/// Represents an axis aligned box in 2D space.
/// </summary>
/// <remarks>
/// An axis-aligned box is a box whose faces coincide with the standard basis axes.
/// </remarks>
[Serializable]
[TypeConverter(typeof(AxisAlignedBoxConverter))]
public struct AxisAlignedBox : ISerializable, ICloneable
{
#region Private Fields
private Vector2 _min;
private Vector2 _max;
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="AxisAlignedBox"/> class using given minimum and maximum points.
/// </summary>
/// <param name="min">A <see cref="Vector2"/> instance representing the minimum point.</param>
/// <param name="max">A <see cref="Vector2"/> instance representing the maximum point.</param>
public AxisAlignedBox(Vector2 min, Vector2 max)
{
_min = min;
_max = max;
}
/// <summary>
/// Initializes a new instance of the <see cref="AxisAlignedBox"/> class using given values from another box instance.
/// </summary>
/// <param name="box">A <see cref="AxisAlignedBox"/> instance to take values from.</param>
public AxisAlignedBox(AxisAlignedBox box)
{
_min = box.Min;
_max = box.Max;
}
/// <summary>
/// Initializes a new instance of the <see cref="AxisAlignedBox"/> class with serialized data.
/// </summary>
/// <param name="info">The object that holds the serialized object data.</param>
/// <param name="context">The contextual information about the source or destination.</param>
private AxisAlignedBox(SerializationInfo info, StreamingContext context)
{
_min = (Vector2)info.GetValue("Min", typeof(Vector2));
_max = (Vector2)info.GetValue("Max", typeof(Vector2));
}
#endregion
#region Public Properties
/// <summary>
/// Gets or sets the minimum point which is the box's minimum X and Y coordinates.
/// </summary>
public Vector2 Min
{
get { return _min; }
set { _min = value;}
}
/// <summary>
/// Gets or sets the maximum point which is the box's maximum X and Y coordinates.
/// </summary>
public Vector2 Max
{
get { return _max; }
set { _max = value;}
}
#endregion
#region ISerializable Members
/// <summary>
/// Populates a <see cref="SerializationInfo"/> with the data needed to serialize the target object.
/// </summary>
/// <param name="info">The <see cref="SerializationInfo"/> to populate with data. </param>
/// <param name="context">The destination (see <see cref="StreamingContext"/>) for this serialization.</param>
//[SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter=true)]
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("Max", _max, typeof(Vector2));
info.AddValue("Min", _min, typeof(Vector2));
}
#endregion
#region ICloneable Members
/// <summary>
/// Creates an exact copy of this <see cref="AxisAlignedBox"/> object.
/// </summary>
/// <returns>The <see cref="AxisAlignedBox"/> object this method creates, cast as an object.</returns>
object ICloneable.Clone()
{
return new AxisAlignedBox(this);
}
/// <summary>
/// Creates an exact copy of this <see cref="AxisAlignedBox"/> object.
/// </summary>
/// <returns>The <see cref="AxisAlignedBox"/> object this method creates.</returns>
public AxisAlignedBox Clone()
{
return new AxisAlignedBox(this);
}
#endregion
#region Public Static Parse Methods
/// <summary>
/// Converts the specified string to its <see cref="AxisAlignedBox"/> equivalent.
/// </summary>
/// <param name="s">A string representation of a <see cref="AxisAlignedBox"/></param>
/// <returns>A <see cref="AxisAlignedBox"/> that represents the vector specified by the <paramref name="s"/> parameter.</returns>
public static AxisAlignedBox Parse(string s)
{
Regex r = new Regex(@"AxisAlignedBox\(Min=(?<min>\([^\)]*\)), Max=(?<max>\([^\)]*\))\)", RegexOptions.None);
Match m = r.Match(s);
if (m.Success)
{
return new AxisAlignedBox(
Vector2.Parse(m.Result("${min}")),
Vector2.Parse(m.Result("${max}"))
);
}
else
{
throw new ParseException("Unsuccessful Match.");
}
}
#endregion
#region Public Methods
/// <summary>
/// Computes the box vertices.
/// </summary>
/// <returns>An array of <see cref="Vector2"/> containing the box vertices.</returns>
public Vector2[] ComputeVertices()
{
Vector2[] vertices = new Vector2[4];
vertices[0] = _min;
vertices[1] = new Vector2(_max.X, _min.Y);
vertices[2] = _max;
vertices[4] = new Vector2(_min.X, _max.Y);
return vertices;
}
#endregion
#region Overrides
/// <summary>
/// Returns the hashcode for this instance.
/// </summary>
/// <returns>A 32-bit signed integer hash code.</returns>
public override int GetHashCode()
{
return _min.GetHashCode() ^ _max.GetHashCode();
}
/// <summary>
/// Returns a value indicating whether this instance is equal to
/// the specified object.
/// </summary>
/// <param name="obj">An object to compare to this instance.</param>
/// <returns><see langword="true"/> if <paramref name="obj"/> is a <see cref="Vector2"/> and has the same values as this instance; otherwise, <see langword="false"/>.</returns>
public override bool Equals(object obj)
{
if (obj is AxisAlignedBox)
{
AxisAlignedBox box = (AxisAlignedBox)obj;
return (_min == box.Min) && (_max == box.Max);
}
return false;
}
/// <summary>
/// Returns a string representation of this object.
/// </summary>
/// <returns>A string representation of this object.</returns>
public override string ToString()
{
return string.Format("AxisAlignedBox(Min={0}, Max={1})", _min, _max);
}
#endregion
#region Comparison Operators
/// <summary>
/// Checks if the two given boxes are equal.
/// </summary>
/// <param name="a">The first of two boxes to compare.</param>
/// <param name="b">The second of two boxes to compare.</param>
/// <returns><b>true</b> if the boxes are equal; otherwise, <b>false</b>.</returns>
public static bool operator==(AxisAlignedBox a, AxisAlignedBox b)
{
return ValueType.Equals(a,b);
}
/// <summary>
/// Checks if the two given boxes are not equal.
/// </summary>
/// <param name="a">The first of two boxes to compare.</param>
/// <param name="b">The second of two boxes to compare.</param>
/// <returns><b>true</b> if the vectors are not equal; otherwise, <b>false</b>.</returns>
public static bool operator!=(AxisAlignedBox a, AxisAlignedBox b)
{
return !ValueType.Equals(a,b);
}
#endregion
}
#region AxisAlignedBoxConverter class
/// <summary>
/// Converts a <see cref="AxisAlignedBox"/> to and from string representation.
/// </summary>
public class AxisAlignedBoxConverter : ExpandableObjectConverter
{
/// <summary>
/// Returns whether this converter can convert an object of the given type to the type of this converter, using the specified context.
/// </summary>
/// <param name="context">An <see cref="ITypeDescriptorContext"/> that provides a format context.</param>
/// <param name="sourceType">A <see cref="Type"/> that represents the type you want to convert from.</param>
/// <returns><b>true</b> if this converter can perform the conversion; otherwise, <b>false</b>.</returns>
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
if (sourceType == typeof(string))
return true;
return base.CanConvertFrom (context, sourceType);
}
/// <summary>
/// Returns whether this converter can convert the object to the specified type, using the specified context.
/// </summary>
/// <param name="context">An <see cref="ITypeDescriptorContext"/> that provides a format context.</param>
/// <param name="destinationType">A <see cref="Type"/> that represents the type you want to convert to.</param>
/// <returns><b>true</b> if this converter can perform the conversion; otherwise, <b>false</b>.</returns>
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
if (destinationType == typeof(string))
return true;
return base.CanConvertTo (context, destinationType);
}
/// <summary>
/// Converts the given value object to the specified type, using the specified context and culture information.
/// </summary>
/// <param name="context">An <see cref="ITypeDescriptorContext"/> that provides a format context.</param>
/// <param name="culture">A <see cref="System.Globalization.CultureInfo"/> object. If a null reference (Nothing in Visual Basic) is passed, the current culture is assumed.</param>
/// <param name="value">The <see cref="Object"/> to convert.</param>
/// <param name="destinationType">The Type to convert the <paramref name="value"/> parameter to.</param>
/// <returns>An <see cref="Object"/> that represents the converted value.</returns>
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
{
if ((destinationType == typeof(string)) && (value is AxisAlignedBox))
{
AxisAlignedBox box = (AxisAlignedBox)value;
return box.ToString();
}
return base.ConvertTo (context, culture, value, destinationType);
}
/// <summary>
/// Converts the given object to the type of this converter, using the specified context and culture information.
/// </summary>
/// <param name="context">An <see cref="ITypeDescriptorContext"/> that provides a format context.</param>
/// <param name="culture">The <see cref="System.Globalization.CultureInfo"/> to use as the current culture. </param>
/// <param name="value">The <see cref="Object"/> to convert.</param>
/// <returns>An <see cref="Object"/> that represents the converted value.</returns>
/// <exception cref="ParseException">Failed parsing from string.</exception>
public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
{
if (value.GetType() == typeof(string))
{
return AxisAlignedBox.Parse((string)value);
}
return base.ConvertFrom (context, culture, value);
}
}
#endregion
}
| |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
namespace Microsoft.Azure.Commands.ResourceManager.Cmdlets.Implementation
{
using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Components;
using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Entities.Resources;
using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Extensions;
using Microsoft.WindowsAzure.Commands.Common;
using Newtonsoft.Json.Linq;
using System.Collections;
using System.Linq;
using System.Management.Automation;
using System.Threading.Tasks;
/// <summary>
/// A cmdlet that creates a new azure resource.
/// </summary>
[Cmdlet(VerbsCommon.Set, "AzureRmResource", SupportsShouldProcess = true, DefaultParameterSetName = ResourceManipulationCmdletBase.ResourceIdParameterSet), OutputType(typeof(PSObject))]
public sealed class SetAzureResourceCmdlet : ResourceManipulationCmdletBase
{
/// <summary>
/// Gets or sets the kind.
/// </summary>
[Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The resource kind.")]
[ValidateNotNullOrEmpty]
public string Kind { get; set; }
/// <summary>
/// Gets or sets the property object.
/// </summary>
[Alias("PropertyObject")]
[Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "A hash table which represents resource properties.")]
[ValidateNotNullOrEmpty]
public PSObject Properties { get; set; }
/// <summary>
/// Gets or sets the plan object.
/// </summary>
[Alias("PlanObject")]
[Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "A hash table which represents resource plan properties.")]
[ValidateNotNullOrEmpty]
public Hashtable Plan { get; set; }
/// <summary>
/// Gets or sets the Sku object.
/// </summary>
[Alias("SkuObject")]
[Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "A hash table which represents sku properties.")]
[ValidateNotNullOrEmpty]
public Hashtable Sku { get; set; }
/// <summary>
/// Gets or sets the tags.
/// </summary>
[Alias("Tags")]
[Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "A hash table which represents resource tags.")]
public Hashtable[] Tag { get; set; }
/// <summary>
/// Gets or sets a value that indicates if an HTTP PATCH request needs to be made instead of PUT.
/// </summary>
[Parameter(Mandatory = false, HelpMessage = "When set indicates if an HTTP PATCH should be used to update the object instead of PUT.")]
public SwitchParameter UsePatchSemantics { get; set; }
/// <summary>
/// Executes the cmdlet.
/// </summary>
protected override void OnProcessRecord()
{
base.OnProcessRecord();
if (!string.IsNullOrEmpty(this.ODataQuery))
{
this.WriteWarning("The ODataQuery parameter is being deprecated in Set-AzureRmResource cmdlet and will be removed in a future release.");
}
var resourceId = this.GetResourceId();
this.ConfirmAction(
this.Force,
"Are you sure you want to update the following resource: " + resourceId,
"Updating the resource...",
resourceId,
() =>
{
var apiVersion = this.DetermineApiVersion(resourceId: resourceId).Result;
var resourceBody = this.GetResourceBody();
var operationResult = this.ShouldUsePatchSemantics()
? this.GetResourcesClient()
.PatchResource(
resourceId: resourceId,
apiVersion: apiVersion,
resource: resourceBody,
cancellationToken: this.CancellationToken.Value,
odataQuery: this.ODataQuery)
.Result
: this.GetResourcesClient()
.PutResource(
resourceId: resourceId,
apiVersion: apiVersion,
resource: resourceBody,
cancellationToken: this.CancellationToken.Value,
odataQuery: this.ODataQuery)
.Result;
var managementUri = this.GetResourcesClient()
.GetResourceManagementRequestUri(
resourceId: resourceId,
apiVersion: apiVersion,
odataQuery: this.ODataQuery);
var activity = string.Format("{0} {1}", this.ShouldUsePatchSemantics() ? "PATCH" : "PUT", managementUri.PathAndQuery);
var result = this.GetLongRunningOperationTracker(activityName: activity, isResourceCreateOrUpdate: true)
.WaitOnOperation(operationResult: operationResult);
this.TryConvertToResourceAndWriteObject(result);
});
}
/// <summary>
/// Gets the resource body.
/// </summary>
private JToken GetResourceBody()
{
if (this.ShouldUsePatchSemantics())
{
var resourceBody = this.GetPatchResourceBody();
return resourceBody == null ? null : resourceBody.ToJToken();
}
else
{
var getResult = this.GetResource().Result;
if (getResult.CanConvertTo<Resource<JToken>>())
{
var resource = getResult.ToResource();
return new Resource<JToken>()
{
Kind = this.Kind ?? resource.Kind,
Plan = this.Plan.ToDictionary(addValueLayer: false).ToJson().FromJson<ResourcePlan>() ?? resource.Plan,
Sku = this.Sku.ToDictionary(addValueLayer: false).ToJson().FromJson<ResourceSku>() ?? resource.Sku,
Tags = TagsHelper.GetTagsDictionary(this.Tag) ?? resource.Tags,
Location = resource.Location,
Properties = this.Properties == null ? resource.Properties : this.Properties.ToResourcePropertiesBody(),
}.ToJToken();
}
else
{
return this.Properties.ToJToken();
}
}
}
/// <summary>
/// Gets the resource body for PATCH calls
/// </summary>
private Resource<JToken> GetPatchResourceBody()
{
Resource<JToken> resourceBody = null;
if (this.Properties != null)
{
resourceBody = new Resource<JToken>()
{
Properties = this.Properties.ToResourcePropertiesBody()
};
}
if (this.Plan != null)
{
if (resourceBody != null)
{
resourceBody.Plan = this.Plan.ToDictionary(addValueLayer: false).ToJson().FromJson<ResourcePlan>();
}
else
{
resourceBody = new Resource<JToken>()
{
Plan = this.Plan.ToDictionary(addValueLayer: false).ToJson().FromJson<ResourcePlan>()
};
}
}
if (this.Kind != null)
{
if (resourceBody != null)
{
resourceBody.Kind = this.Kind;
}
else
{
resourceBody = new Resource<JToken>()
{
Kind = this.Kind
};
}
}
if (this.Sku != null)
{
if (resourceBody != null)
{
resourceBody.Sku = this.Sku.ToDictionary(addValueLayer: false).ToJson().FromJson<ResourceSku>();
}
else
{
resourceBody = new Resource<JToken>()
{
Sku = this.Sku.ToDictionary(addValueLayer: false).ToJson().FromJson<ResourceSku>()
};
}
}
if (this.Tag != null)
{
if (resourceBody != null)
{
resourceBody.Tags = TagsHelper.GetTagsDictionary(this.Tag);
}
else
{
resourceBody = new Resource<JToken>()
{
Tags = TagsHelper.GetTagsDictionary(this.Tag)
};
}
}
return resourceBody;
}
/// <summary>
/// Determines if the cmdlet should use <c>PATCH</c> semantics.
/// </summary>
private bool ShouldUsePatchSemantics()
{
return this.UsePatchSemantics || ((this.Tag != null || this.Sku != null) && this.Plan == null && this.Properties == null && this.Kind == null);
}
/// <summary>
/// Gets a resource.
/// </summary>
private async Task<JObject> GetResource()
{
var resourceId = this.GetResourceId();
var apiVersion = await this
.DetermineApiVersion(resourceId: resourceId)
.ConfigureAwait(continueOnCapturedContext: false);
return await this
.GetResourcesClient()
.GetResource<JObject>(
resourceId: resourceId,
apiVersion: apiVersion,
cancellationToken: this.CancellationToken.Value)
.ConfigureAwait(continueOnCapturedContext: false);
}
}
}
| |
// ***********************************************************************
// Copyright (c) 2012 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.Generic;
namespace NUnit.Framework.Constraints
{
/// <summary>
/// Summary description for MsgUtilTests.
/// </summary>
[TestFixture]
public static class MsgUtilTests
{
#region FormatValue
class CustomFormattableType { }
[Test]
public static void FormatValue_ContextualCustomFormatterInvoked_FactoryArg()
{
TestContext.AddFormatter(next => val => (val is CustomFormattableType) ? "custom_formatted" : next(val));
Assert.That(MsgUtils.FormatValue(new CustomFormattableType()), Is.EqualTo("custom_formatted"));
}
[Test]
public static void FormatValue_ContextualCustomFormatterNotInvokedForNull()
{
// If this factory is actually called with null, it will throw
TestContext.AddFormatter(next => val => (val.GetType() == typeof(CustomFormattableType)) ? val.ToString() : next(val));
Assert.That(MsgUtils.FormatValue(null), Is.EqualTo("null"));
}
[Test]
public static void FormatValue_ContextualCustomFormatterInvoked_FormatterArg()
{
TestContext.AddFormatter<CustomFormattableType>(val => "custom_formatted_using_type");
Assert.That(MsgUtils.FormatValue(new CustomFormattableType()), Is.EqualTo("custom_formatted_using_type"));
}
[Test]
public static void FormatValue_IntegerIsWrittenAsIs()
{
Assert.That(MsgUtils.FormatValue(42), Is.EqualTo("42"));
}
[Test]
public static void FormatValue_StringIsWrittenWithQuotes()
{
Assert.That(MsgUtils.FormatValue("Hello"), Is.EqualTo("\"Hello\""));
}
// This test currently fails because control character replacement is
// done at a higher level...
// TODO: See if we should do it at a lower level
// [Test]
// public static void ControlCharactersInStringsAreEscaped()
// {
// WriteValue("Best Wishes,\r\n\tCharlie\r\n");
// Assert.That(writer.ToString(), Is.Is.EqualTo("\"Best Wishes,\\r\\n\\tCharlie\\r\\n\""));
// }
[Test]
public static void FormatValue_FloatIsWrittenWithTrailingF()
{
Assert.That(MsgUtils.FormatValue(0.5f), Is.EqualTo("0.5f"));
}
[Test]
public static void FormatValue_FloatIsWrittenToNineDigits()
{
string s = MsgUtils.FormatValue(0.33333333333333f);
int digits = s.Length - 3; // 0.dddddddddf
Assert.That(digits, Is.EqualTo(9));
}
[Test]
public static void FormatValue_DoubleIsWrittenWithTrailingD()
{
Assert.That(MsgUtils.FormatValue(0.5d), Is.EqualTo("0.5d"));
}
[Test]
public static void FormatValue_DoubleIsWrittenToSeventeenDigits()
{
string s = MsgUtils.FormatValue(0.33333333333333333333333333333333333333333333d);
Assert.That(s.Length, Is.EqualTo(20)); // add 3 for leading 0, decimal and trailing d
}
[Test]
public static void FormatValue_DecimalIsWrittenWithTrailingM()
{
Assert.That(MsgUtils.FormatValue(0.5m), Is.EqualTo("0.5m"));
}
[Test]
public static void FormatValue_DecimalIsWrittenToTwentyNineDigits()
{
Assert.That(MsgUtils.FormatValue(12345678901234567890123456789m), Is.EqualTo("12345678901234567890123456789m"));
}
[Test]
public static void FormatValue_DateTimeTest()
{
Assert.That(MsgUtils.FormatValue(new DateTime(2007, 7, 4, 9, 15, 30, 123)), Is.EqualTo("2007-07-04 09:15:30.123"));
}
[Test]
public static void FormatValue_DateTimeOffsetTest()
{
Assert.That(MsgUtils.FormatValue(new DateTimeOffset(2007, 7, 4, 9, 15, 30, 123, TimeSpan.FromHours(8))), Is.EqualTo("2007-07-04 09:15:30.123+08:00"));
}
[TestCase('a', "'a'")]
[TestCase('h', "'h'")]
[TestCase('z', "'z'")]
public static void FormatValue_CharTest(char c, string expected)
{
Assert.That(MsgUtils.FormatValue(c), Is.EqualTo(expected));
}
[TestCase(null, null, "[null, null]")]
[TestCase(null, "Second", "[null, \"Second\"]")]
[TestCase("First", null, "[\"First\", null]")]
[TestCase("First", "Second", "[\"First\", \"Second\"]")]
[TestCase(123, 'h', "[123, 'h']")]
public static void FormatValue_KeyValuePairTest(object key, object value, string expectedResult)
{
string s = MsgUtils.FormatValue(new KeyValuePair<object, object>(key, value));
Assert.That(s, Is.EqualTo(expectedResult));
}
#if NET45
[Test]
public static void FormatValue_EmptyValueTupleTest()
{
string s = MsgUtils.FormatValue(ValueTuple.Create());
Assert.That(s, Is.EqualTo("()"));
}
[Test]
public static void FormatValue_OneElementValueTupleTest()
{
string s = MsgUtils.FormatValue(ValueTuple.Create("Hello"));
Assert.That(s, Is.EqualTo("(\"Hello\")"));
}
[Test]
public static void FormatValue_TwoElementsValueTupleTest()
{
string s = MsgUtils.FormatValue(ValueTuple.Create("Hello", 123));
Assert.That(s, Is.EqualTo("(\"Hello\", 123)"));
}
[Test]
public static void FormatValue_ThreeElementsValueTupleTest()
{
string s = MsgUtils.FormatValue(ValueTuple.Create("Hello", 123, 'a'));
Assert.That(s, Is.EqualTo("(\"Hello\", 123, 'a')"));
}
[Test]
public static void FormatValue_EightElementsValueTupleTest()
{
var tuple = ValueTuple.Create(1, 2, 3, 4, 5, 6, 7, 8);
string s = MsgUtils.FormatValue(tuple);
Assert.That(s, Is.EqualTo("(1, 2, 3, 4, 5, 6, 7, 8)"));
}
[Test]
public static void FormatValue_EightElementsValueTupleNestedTest()
{
var tuple = ValueTuple.Create(1, 2, 3, 4, 5, 6, 7, ValueTuple.Create(8, "9"));
string s = MsgUtils.FormatValue(tuple);
Assert.That(s, Is.EqualTo("(1, 2, 3, 4, 5, 6, 7, (8, \"9\"))"));
}
[Test]
public static void FormatValue_FifteenElementsValueTupleTest()
{
var tupleLastElements = ValueTuple.Create(8, 9, 10, 11, "12", 13, 14, "15");
var tuple = new ValueTuple<int, int, int, int, int, int, int, ValueTuple<int, int, int, int, string, int, int, ValueTuple<string>>>
(1, 2, 3, 4, 5, 6, 7, tupleLastElements);
string s = MsgUtils.FormatValue(tuple);
Assert.That(s, Is.EqualTo("(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, \"12\", 13, 14, \"15\")"));
}
#endif
#if !NET35
[Test]
public static void FormatValue_OneElementTupleTest()
{
string s = MsgUtils.FormatValue(Tuple.Create("Hello"));
Assert.That(s, Is.EqualTo("(\"Hello\")"));
}
[Test]
public static void FormatValue_TwoElementsTupleTest()
{
string s = MsgUtils.FormatValue(Tuple.Create("Hello", 123));
Assert.That(s, Is.EqualTo("(\"Hello\", 123)"));
}
[Test]
public static void FormatValue_ThreeElementsTupleTest()
{
string s = MsgUtils.FormatValue(Tuple.Create("Hello", 123, 'a'));
Assert.That(s, Is.EqualTo("(\"Hello\", 123, 'a')"));
}
[Test]
public static void FormatValue_EightElementsTupleTest()
{
var tuple = Tuple.Create(1, 2, 3, 4, 5, 6, 7, 8);
string s = MsgUtils.FormatValue(tuple);
Assert.That(s, Is.EqualTo("(1, 2, 3, 4, 5, 6, 7, 8)"));
}
[Test]
public static void FormatValue_EightElementsTupleNestedTest()
{
var tuple = Tuple.Create(1, 2, 3, 4, 5, 6, 7, Tuple.Create(8, "9"));
string s = MsgUtils.FormatValue(tuple);
Assert.That(s, Is.EqualTo("(1, 2, 3, 4, 5, 6, 7, (8, \"9\"))"));
}
[Test]
public static void FormatValue_FifteenElementsTupleTest()
{
var tupleLastElements = Tuple.Create(8, 9, 10, 11, "12", 13, 14, "15");
var tuple = new Tuple<int, int, int, int, int, int, int, Tuple<int, int, int, int, string, int, int, Tuple<string>>>
(1, 2, 3, 4, 5, 6, 7, tupleLastElements);
string s = MsgUtils.FormatValue(tuple);
Assert.That(s, Is.EqualTo("(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, \"12\", 13, 14, \"15\")"));
}
#endif
#endregion
#region EscapeControlChars
[TestCase("\n", "\\n")]
[TestCase("\n\n", "\\n\\n")]
[TestCase("\n\n\n", "\\n\\n\\n")]
[TestCase("\r", "\\r")]
[TestCase("\r\r", "\\r\\r")]
[TestCase("\r\r\r", "\\r\\r\\r")]
[TestCase("\r\n", "\\r\\n")]
[TestCase("\n\r", "\\n\\r")]
[TestCase("This is a\rtest message", "This is a\\rtest message")]
[TestCase("", "")]
[TestCase(null, null)]
[TestCase("\t", "\\t")]
[TestCase("\t\n", "\\t\\n")]
[TestCase("\\r\\n", "\\\\r\\\\n")]
// TODO: Figure out why this fails in Mono
//[TestCase("\0", "\\0")]
[TestCase("\a", "\\a")]
[TestCase("\b", "\\b")]
[TestCase("\f", "\\f")]
[TestCase("\v", "\\v")]
[TestCase("\x0085", "\\x0085", Description = "Next line character")]
[TestCase("\x2028", "\\x2028", Description = "Line separator character")]
[TestCase("\x2029", "\\x2029", Description = "Paragraph separator character")]
public static void EscapeControlCharsTest(string input, string expected)
{
Assert.That( MsgUtils.EscapeControlChars(input), Is.EqualTo(expected) );
}
[Test]
public static void EscapeNullCharInString()
{
Assert.That(MsgUtils.EscapeControlChars("\0"), Is.EqualTo("\\0"));
}
#endregion
#region EscapeNullChars
[TestCase("\n", "\n")]
[TestCase("\r", "\r")]
[TestCase("\r\n\r", "\r\n\r")]
[TestCase("\f", "\f")]
[TestCase("\b", "\b")]
public static void DoNotEscapeNonNullControlChars(string input, string expected)
{
Assert.That(MsgUtils.EscapeNullCharacters(input), Is.EqualTo(expected));
}
[Test]
public static void EscapesNullControlChars()
{
Assert.That(MsgUtils.EscapeNullCharacters("\0"), Is.EqualTo("\\0"));
}
#endregion
#region ClipString
private const string s52 = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
[TestCase(s52, 52, 0, s52, TestName="NoClippingNeeded")]
[TestCase(s52, 29, 0, "abcdefghijklmnopqrstuvwxyz...", TestName="ClipAtEnd")]
[TestCase(s52, 29, 26, "...ABCDEFGHIJKLMNOPQRSTUVWXYZ", TestName="ClipAtStart")]
[TestCase(s52, 28, 26, "...ABCDEFGHIJKLMNOPQRSTUV...", TestName="ClipAtStartAndEnd")]
public static void TestClipString(string input, int max, int start, string result)
{
System.Console.WriteLine("input= \"{0}\"", input);
System.Console.WriteLine("result= \"{0}\"", result);
Assert.That(MsgUtils.ClipString(input, max, start), Is.EqualTo(result));
}
#endregion
#region ClipExpectedAndActual
[Test]
public static void ClipExpectedAndActual_StringsFitInLine()
{
string eClip = s52;
string aClip = "abcde";
MsgUtils.ClipExpectedAndActual(ref eClip, ref aClip, 52, 5);
Assert.That(eClip, Is.EqualTo(s52));
Assert.That(aClip, Is.EqualTo("abcde"));
eClip = s52;
aClip = "abcdefghijklmno?qrstuvwxyz";
MsgUtils.ClipExpectedAndActual(ref eClip, ref aClip, 52, 15);
Assert.That(eClip, Is.EqualTo(s52));
Assert.That(aClip, Is.EqualTo("abcdefghijklmno?qrstuvwxyz"));
}
[Test]
public static void ClipExpectedAndActual_StringTailsFitInLine()
{
string s1 = s52;
string s2 = s52.Replace('Z', '?');
MsgUtils.ClipExpectedAndActual(ref s1, ref s2, 29, 51);
Assert.That(s1, Is.EqualTo("...ABCDEFGHIJKLMNOPQRSTUVWXYZ"));
}
[Test]
public static void ClipExpectedAndActual_StringsDoNotFitInLine()
{
string s1 = s52;
string s2 = "abcdefghij";
MsgUtils.ClipExpectedAndActual(ref s1, ref s2, 29, 10);
Assert.That(s1, Is.EqualTo("abcdefghijklmnopqrstuvwxyz..."));
Assert.That(s2, Is.EqualTo("abcdefghij"));
s1 = s52;
s2 = "abcdefghijklmno?qrstuvwxyz";
MsgUtils.ClipExpectedAndActual(ref s1, ref s2, 25, 15);
Assert.That(s1, Is.EqualTo("...efghijklmnopqrstuvw..."));
Assert.That(s2, Is.EqualTo("...efghijklmno?qrstuvwxyz"));
}
#endregion
}
}
| |
//#define ProfileAstar
using UnityEngine;
using System.Collections;
using System.Text;
using Pathfinding;
[AddComponentMenu("Pathfinding/Pathfinding Debugger")]
[ExecuteInEditMode]
/** Debugger for the A* Pathfinding Project.
* This class can be used to profile different parts of the pathfinding system
* and the whole game as well to some extent.
*
* Clarification of the labels shown when enabled.
* All memory related things profiles <b>the whole game</b> not just the A* Pathfinding System.\n
* - Currently allocated: memory the GC (garbage collector) says the application has allocated right now.
* - Peak allocated: maximum measured value of the above.
* - Last collect peak: the last peak of 'currently allocated'.
* - Allocation rate: how much the 'currently allocated' value increases per second. This value is not as reliable as you can think
* it is often very random probably depending on how the GC thinks this application is using memory.
* - Collection frequency: how often the GC is called. Again, the GC might decide it is better with many small collections
* or with a few large collections. So you cannot really trust this variable much.
* - Last collect fps: FPS during the last garbage collection, the GC will lower the fps a lot.
*
* - FPS: current FPS (not updated every frame for readability)
* - Lowest FPS (last x): As the label says, the lowest fps of the last x frames.
*
* - Size: Size of the path pool.
* - Total created: Number of paths of that type which has been created. Pooled paths are not counted twice.
* If this value just keeps on growing and growing without an apparent stop, you are are either not pooling any paths
* or you have missed to pool some path somewhere in your code.
*
* \see pooling
*
* \todo Add field showing how many graph updates are being done right now
*/
[HelpURL("http://arongranberg.com/astar/docs/class_astar_debugger.php")]
public class AstarDebugger : MonoBehaviour {
public int yOffset = 5;
public bool show = true;
public bool showInEditor = false;
public bool showFPS = false;
public bool showPathProfile = false;
public bool showMemProfile = false;
public bool showGraph = false;
public int graphBufferSize = 200;
/** Font to use.
* A monospaced font is the best
*/
public Font font = null;
public int fontSize = 12;
StringBuilder text = new StringBuilder();
string cachedText;
float lastUpdate = -999;
private GraphPoint[] graph;
struct GraphPoint {
public float fps, memory;
public bool collectEvent;
}
private float delayedDeltaTime = 1;
private float lastCollect = 0;
private float lastCollectNum = 0;
private float delta = 0;
private float lastDeltaTime = 0;
private int allocRate = 0;
private int lastAllocMemory = 0;
private float lastAllocSet = -9999;
private int allocMem = 0;
private int collectAlloc = 0;
private int peakAlloc = 0;
private int fpsDropCounterSize = 200;
private float[] fpsDrops;
private Rect boxRect;
private GUIStyle style;
private Camera cam;
float graphWidth = 100;
float graphHeight = 100;
float graphOffset = 50;
public void Start () {
useGUILayout = false;
fpsDrops = new float[fpsDropCounterSize];
cam = GetComponent<Camera>();
if (cam == null) {
cam = Camera.main;
}
graph = new GraphPoint[graphBufferSize];
if (Time.unscaledDeltaTime > 0) {
for (int i = 0; i < fpsDrops.Length; i++) {
fpsDrops[i] = 1F / Time.unscaledDeltaTime;
}
}
}
int maxVecPool = 0;
int maxNodePool = 0;
PathTypeDebug[] debugTypes = new PathTypeDebug[] {
new PathTypeDebug("ABPath", () => PathPool.GetSize(typeof(ABPath)), () => PathPool.GetTotalCreated(typeof(ABPath)))
};
struct PathTypeDebug {
string name;
System.Func<int> getSize;
System.Func<int> getTotalCreated;
public PathTypeDebug (string name, System.Func<int> getSize, System.Func<int> getTotalCreated) {
this.name = name;
this.getSize = getSize;
this.getTotalCreated = getTotalCreated;
}
public void Print (StringBuilder text) {
int totCreated = getTotalCreated();
if (totCreated > 0) {
text.Append("\n").Append((" " + name).PadRight(25)).Append(getSize()).Append("/").Append(totCreated);
}
}
}
public void LateUpdate () {
if (!show || (!Application.isPlaying && !showInEditor)) return;
if (Time.unscaledDeltaTime <= 0.0001f)
return;
int collCount = System.GC.CollectionCount(0);
if (lastCollectNum != collCount) {
lastCollectNum = collCount;
delta = Time.realtimeSinceStartup-lastCollect;
lastCollect = Time.realtimeSinceStartup;
lastDeltaTime = Time.unscaledDeltaTime;
collectAlloc = allocMem;
}
allocMem = (int)System.GC.GetTotalMemory(false);
bool collectEvent = allocMem < peakAlloc;
peakAlloc = !collectEvent ? allocMem : peakAlloc;
if (Time.realtimeSinceStartup - lastAllocSet > 0.3F || !Application.isPlaying) {
int diff = allocMem - lastAllocMemory;
lastAllocMemory = allocMem;
lastAllocSet = Time.realtimeSinceStartup;
delayedDeltaTime = Time.unscaledDeltaTime;
if (diff >= 0) {
allocRate = diff;
}
}
if (Application.isPlaying) {
fpsDrops[Time.frameCount % fpsDrops.Length] = Time.unscaledDeltaTime > 0.00001f ? 1F / Time.unscaledDeltaTime : 0;
int graphIndex = Time.frameCount % graph.Length;
graph[graphIndex].fps = Time.unscaledDeltaTime < 0.00001f ? 1F / Time.unscaledDeltaTime : 0;
graph[graphIndex].collectEvent = collectEvent;
graph[graphIndex].memory = allocMem;
}
if (Application.isPlaying && cam != null && showGraph) {
graphWidth = cam.pixelWidth*0.8f;
float minMem = float.PositiveInfinity, maxMem = 0, minFPS = float.PositiveInfinity, maxFPS = 0;
for (int i = 0; i < graph.Length; i++) {
minMem = Mathf.Min(graph[i].memory, minMem);
maxMem = Mathf.Max(graph[i].memory, maxMem);
minFPS = Mathf.Min(graph[i].fps, minFPS);
maxFPS = Mathf.Max(graph[i].fps, maxFPS);
}
int currentGraphIndex = Time.frameCount % graph.Length;
Matrix4x4 m = Matrix4x4.TRS(new Vector3((cam.pixelWidth - graphWidth)/2f, graphOffset, 1), Quaternion.identity, new Vector3(graphWidth, graphHeight, 1));
for (int i = 0; i < graph.Length-1; i++) {
if (i == currentGraphIndex) continue;
DrawGraphLine(i, m, i/(float)graph.Length, (i+1)/(float)graph.Length, AstarMath.MapTo(minMem, maxMem, graph[i].memory), AstarMath.MapTo(minMem, maxMem, graph[i+1].memory), Color.blue);
DrawGraphLine(i, m, i/(float)graph.Length, (i+1)/(float)graph.Length, AstarMath.MapTo(minFPS, maxFPS, graph[i].fps), AstarMath.MapTo(minFPS, maxFPS, graph[i+1].fps), Color.green);
}
}
}
void DrawGraphLine (int index, Matrix4x4 m, float x1, float x2, float y1, float y2, Color col) {
Debug.DrawLine(cam.ScreenToWorldPoint(m.MultiplyPoint3x4(new Vector3(x1, y1))), cam.ScreenToWorldPoint(m.MultiplyPoint3x4(new Vector3(x2, y2))), col);
}
public void OnGUI () {
if (!show || (!Application.isPlaying && !showInEditor)) return;
if (style == null) {
style = new GUIStyle();
style.normal.textColor = Color.white;
style.padding = new RectOffset(5, 5, 5, 5);
}
if (Time.realtimeSinceStartup - lastUpdate > 0.5f || cachedText == null || !Application.isPlaying) {
lastUpdate = Time.realtimeSinceStartup;
boxRect = new Rect(5, yOffset, 310, 40);
text.Length = 0;
text.AppendLine("A* Pathfinding Project Debugger");
text.Append("A* Version: ").Append(AstarPath.Version.ToString());
if (showMemProfile) {
boxRect.height += 200;
text.AppendLine();
text.AppendLine();
text.Append("Currently allocated".PadRight(25));
text.Append((allocMem/1000000F).ToString("0.0 MB"));
text.AppendLine();
text.Append("Peak allocated".PadRight(25));
text.Append((peakAlloc/1000000F).ToString("0.0 MB")).AppendLine();
text.Append("Last collect peak".PadRight(25));
text.Append((collectAlloc/1000000F).ToString("0.0 MB")).AppendLine();
text.Append("Allocation rate".PadRight(25));
text.Append((allocRate/1000000F).ToString("0.0 MB")).AppendLine();
text.Append("Collection frequency".PadRight(25));
text.Append(delta.ToString("0.00"));
text.Append("s\n");
text.Append("Last collect fps".PadRight(25));
text.Append((1F/lastDeltaTime).ToString("0.0 fps"));
text.Append(" (");
text.Append(lastDeltaTime.ToString("0.000 s"));
text.Append(")");
}
if (showFPS) {
text.AppendLine();
text.AppendLine();
var delayedFPS = delayedDeltaTime > 0.00001f ? 1F/delayedDeltaTime : 0;
text.Append("FPS".PadRight(25)).Append(delayedFPS.ToString("0.0 fps"));
float minFps = Mathf.Infinity;
for (int i = 0; i < fpsDrops.Length; i++) if (fpsDrops[i] < minFps) minFps = fpsDrops[i];
text.AppendLine();
text.Append(("Lowest fps (last " + fpsDrops.Length + ")").PadRight(25)).Append(minFps.ToString("0.0"));
}
if (showPathProfile) {
AstarPath astar = AstarPath.active;
text.AppendLine();
if (astar == null) {
text.Append("\nNo AstarPath Object In The Scene");
} else {
if (Pathfinding.Util.ListPool<Vector3>.GetSize() > maxVecPool) maxVecPool = Pathfinding.Util.ListPool<Vector3>.GetSize();
if (Pathfinding.Util.ListPool<Pathfinding.GraphNode>.GetSize() > maxNodePool) maxNodePool = Pathfinding.Util.ListPool<Pathfinding.GraphNode>.GetSize();
text.Append("\nPool Sizes (size/total created)");
for (int i = 0; i < debugTypes.Length; i++) {
debugTypes[i].Print(text);
}
}
}
cachedText = text.ToString();
}
if (font != null) {
style.font = font;
style.fontSize = fontSize;
}
boxRect.height = style.CalcHeight(new GUIContent(cachedText), boxRect.width);
GUI.Box(boxRect, "");
GUI.Label(boxRect, cachedText, style);
if (showGraph) {
float minMem = float.PositiveInfinity, maxMem = 0, minFPS = float.PositiveInfinity, maxFPS = 0;
for (int i = 0; i < graph.Length; i++) {
minMem = Mathf.Min(graph[i].memory, minMem);
maxMem = Mathf.Max(graph[i].memory, maxMem);
minFPS = Mathf.Min(graph[i].fps, minFPS);
maxFPS = Mathf.Max(graph[i].fps, maxFPS);
}
float line;
GUI.color = Color.blue;
// Round to nearest x.x MB
line = Mathf.RoundToInt(maxMem/(100.0f*1000));
GUI.Label(new Rect(5, Screen.height - AstarMath.MapTo(minMem, maxMem, 0 + graphOffset, graphHeight + graphOffset, line*1000*100) - 10, 100, 20), (line/10.0f).ToString("0.0 MB"));
line = Mathf.Round(minMem/(100.0f*1000));
GUI.Label(new Rect(5, Screen.height - AstarMath.MapTo(minMem, maxMem, 0 + graphOffset, graphHeight + graphOffset, line*1000*100) - 10, 100, 20), (line/10.0f).ToString("0.0 MB"));
GUI.color = Color.green;
// Round to nearest x.x MB
line = Mathf.Round(maxFPS);
GUI.Label(new Rect(55, Screen.height - AstarMath.MapTo(minFPS, maxFPS, 0 + graphOffset, graphHeight + graphOffset, line) - 10, 100, 20), line.ToString("0 FPS"));
line = Mathf.Round(minFPS);
GUI.Label(new Rect(55, Screen.height - AstarMath.MapTo(minFPS, maxFPS, 0 + graphOffset, graphHeight + graphOffset, line) - 10, 100, 20), line.ToString("0 FPS"));
}
}
}
| |
//
// 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.
//
// LzBinTree.cs
using System;
using LZMA.LZ;
using LZMA;
namespace LZ
{
class BinTree : InWindow
{
UInt32 _cyclicBufferPos;
UInt32 _cyclicBufferSize = 0;
UInt32 _matchMaxLen;
UInt32[] _son;
UInt32[] _hash;
UInt32 _cutValue = 0xFF;
UInt32 _hashMask;
UInt32 _hashSizeSum = 0;
bool HASH_ARRAY = true;
const UInt32 kHash2Size = 1 << 10;
const UInt32 kHash3Size = 1 << 16;
const UInt32 kBT2HashSize = 1 << 16;
const UInt32 kStartMaxLen = 1;
const UInt32 kHash3Offset = kHash2Size;
const UInt32 kEmptyHashValue = 0;
const UInt32 kMaxValForNormalize = ((UInt32)1 << 31) - 1;
UInt32 kNumHashDirectBytes = 0;
UInt32 kMinMatchCheck = 4;
UInt32 kFixHashSize = kHash2Size + kHash3Size;
internal void SetType(int numHashBytes)
{
HASH_ARRAY = (numHashBytes > 2);
if (HASH_ARRAY)
{
kNumHashDirectBytes = 0;
kMinMatchCheck = 4;
kFixHashSize = kHash2Size + kHash3Size;
}
else
{
kNumHashDirectBytes = 2;
kMinMatchCheck = 2 + 1;
kFixHashSize = 0;
}
}
internal new void SetStream(System.IO.Stream stream) { base.SetStream(stream); }
internal new void ReleaseStream() { base.ReleaseStream(); }
internal new void Init()
{
base.Init();
for (UInt32 i = 0; i < _hashSizeSum; i++)
_hash[i] = kEmptyHashValue;
_cyclicBufferPos = 0;
ReduceOffsets(-1);
}
internal new void MovePos()
{
if (++_cyclicBufferPos >= _cyclicBufferSize)
_cyclicBufferPos = 0;
base.MovePos();
if (_pos == kMaxValForNormalize)
Normalize();
}
internal new Byte GetIndexByte(Int32 index) { return base.GetIndexByte(index); }
internal new UInt32 GetMatchLen(Int32 index, UInt32 distance, UInt32 limit)
{ return base.GetMatchLen(index, distance, limit); }
internal new UInt32 GetNumAvailableBytes() { return base.GetNumAvailableBytes(); }
internal void Create(UInt32 historySize, UInt32 keepAddBufferBefore,
UInt32 matchMaxLen, UInt32 keepAddBufferAfter)
{
if (historySize > kMaxValForNormalize - 256)
throw new Exception();
_cutValue = 16 + (matchMaxLen >> 1);
UInt32 windowReservSize = (historySize + keepAddBufferBefore +
matchMaxLen + keepAddBufferAfter) / 2 + 256;
base.Create(historySize + keepAddBufferBefore, matchMaxLen + keepAddBufferAfter, windowReservSize);
_matchMaxLen = matchMaxLen;
UInt32 cyclicBufferSize = historySize + 1;
if (_cyclicBufferSize != cyclicBufferSize)
_son = new UInt32[(_cyclicBufferSize = cyclicBufferSize) * 2];
UInt32 hs = kBT2HashSize;
if (HASH_ARRAY)
{
hs = historySize - 1;
hs |= (hs >> 1);
hs |= (hs >> 2);
hs |= (hs >> 4);
hs |= (hs >> 8);
hs >>= 1;
hs |= 0xFFFF;
if (hs > (1 << 24))
hs >>= 1;
_hashMask = hs;
hs++;
hs += kFixHashSize;
}
if (hs != _hashSizeSum)
_hash = new UInt32[_hashSizeSum = hs];
}
internal UInt32 GetMatches(UInt32[] distances)
{
UInt32 lenLimit;
if (_pos + _matchMaxLen <= _streamPos)
lenLimit = _matchMaxLen;
else
{
lenLimit = _streamPos - _pos;
if (lenLimit < kMinMatchCheck)
{
MovePos();
return 0;
}
}
UInt32 offset = 0;
UInt32 matchMinPos = (_pos > _cyclicBufferSize) ? (_pos - _cyclicBufferSize) : 0;
UInt32 cur = _bufferOffset + _pos;
UInt32 maxLen = kStartMaxLen; // to avoid items for len < hashSize;
UInt32 hashValue, hash2Value = 0, hash3Value = 0;
if (HASH_ARRAY)
{
UInt32 temp = CRC.Table[_bufferBase[cur]] ^ _bufferBase[cur + 1];
hash2Value = temp & (kHash2Size - 1);
temp ^= ((UInt32)(_bufferBase[cur + 2]) << 8);
hash3Value = temp & (kHash3Size - 1);
hashValue = (temp ^ (CRC.Table[_bufferBase[cur + 3]] << 5)) & _hashMask;
}
else
hashValue = _bufferBase[cur] ^ ((UInt32)(_bufferBase[cur + 1]) << 8);
UInt32 curMatch = _hash[kFixHashSize + hashValue];
if (HASH_ARRAY)
{
UInt32 curMatch2 = _hash[hash2Value];
UInt32 curMatch3 = _hash[kHash3Offset + hash3Value];
_hash[hash2Value] = _pos;
_hash[kHash3Offset + hash3Value] = _pos;
if (curMatch2 > matchMinPos)
if (_bufferBase[_bufferOffset + curMatch2] == _bufferBase[cur])
{
distances[offset++] = maxLen = 2;
distances[offset++] = _pos - curMatch2 - 1;
}
if (curMatch3 > matchMinPos)
if (_bufferBase[_bufferOffset + curMatch3] == _bufferBase[cur])
{
if (curMatch3 == curMatch2)
offset -= 2;
distances[offset++] = maxLen = 3;
distances[offset++] = _pos - curMatch3 - 1;
curMatch2 = curMatch3;
}
if (offset != 0 && curMatch2 == curMatch)
{
offset -= 2;
maxLen = kStartMaxLen;
}
}
_hash[kFixHashSize + hashValue] = _pos;
UInt32 ptr0 = (_cyclicBufferPos << 1) + 1;
UInt32 ptr1 = (_cyclicBufferPos << 1);
UInt32 len0, len1;
len0 = len1 = kNumHashDirectBytes;
if (kNumHashDirectBytes != 0)
{
if (curMatch > matchMinPos)
{
if (_bufferBase[_bufferOffset + curMatch + kNumHashDirectBytes] !=
_bufferBase[cur + kNumHashDirectBytes])
{
distances[offset++] = maxLen = kNumHashDirectBytes;
distances[offset++] = _pos - curMatch - 1;
}
}
}
UInt32 count = _cutValue;
while(true)
{
if(curMatch <= matchMinPos || count-- == 0)
{
_son[ptr0] = _son[ptr1] = kEmptyHashValue;
break;
}
UInt32 delta = _pos - curMatch;
UInt32 cyclicPos = ((delta <= _cyclicBufferPos) ?
(_cyclicBufferPos - delta) :
(_cyclicBufferPos - delta + _cyclicBufferSize)) << 1;
UInt32 pby1 = _bufferOffset + curMatch;
UInt32 len = Math.Min(len0, len1);
if (_bufferBase[pby1 + len] == _bufferBase[cur + len])
{
while(++len != lenLimit)
if (_bufferBase[pby1 + len] != _bufferBase[cur + len])
break;
if (maxLen < len)
{
distances[offset++] = maxLen = len;
distances[offset++] = delta - 1;
if (len == lenLimit)
{
_son[ptr1] = _son[cyclicPos];
_son[ptr0] = _son[cyclicPos + 1];
break;
}
}
}
if (_bufferBase[pby1 + len] < _bufferBase[cur + len])
{
_son[ptr1] = curMatch;
ptr1 = cyclicPos + 1;
curMatch = _son[ptr1];
len1 = len;
}
else
{
_son[ptr0] = curMatch;
ptr0 = cyclicPos;
curMatch = _son[ptr0];
len0 = len;
}
}
MovePos();
return offset;
}
internal void Skip(UInt32 num)
{
do
{
UInt32 lenLimit;
if (_pos + _matchMaxLen <= _streamPos)
lenLimit = _matchMaxLen;
else
{
lenLimit = _streamPos - _pos;
if (lenLimit < kMinMatchCheck)
{
MovePos();
continue;
}
}
UInt32 matchMinPos = (_pos > _cyclicBufferSize) ? (_pos - _cyclicBufferSize) : 0;
UInt32 cur = _bufferOffset + _pos;
UInt32 hashValue;
if (HASH_ARRAY)
{
UInt32 temp = CRC.Table[_bufferBase[cur]] ^ _bufferBase[cur + 1];
UInt32 hash2Value = temp & (kHash2Size - 1);
_hash[hash2Value] = _pos;
temp ^= ((UInt32)(_bufferBase[cur + 2]) << 8);
UInt32 hash3Value = temp & (kHash3Size - 1);
_hash[kHash3Offset + hash3Value] = _pos;
hashValue = (temp ^ (CRC.Table[_bufferBase[cur + 3]] << 5)) & _hashMask;
}
else
hashValue = _bufferBase[cur] ^ ((UInt32)(_bufferBase[cur + 1]) << 8);
UInt32 curMatch = _hash[kFixHashSize + hashValue];
_hash[kFixHashSize + hashValue] = _pos;
UInt32 ptr0 = (_cyclicBufferPos << 1) + 1;
UInt32 ptr1 = (_cyclicBufferPos << 1);
UInt32 len0, len1;
len0 = len1 = kNumHashDirectBytes;
UInt32 count = _cutValue;
while (true)
{
if (curMatch <= matchMinPos || count-- == 0)
{
_son[ptr0] = _son[ptr1] = kEmptyHashValue;
break;
}
UInt32 delta = _pos - curMatch;
UInt32 cyclicPos = ((delta <= _cyclicBufferPos) ?
(_cyclicBufferPos - delta) :
(_cyclicBufferPos - delta + _cyclicBufferSize)) << 1;
UInt32 pby1 = _bufferOffset + curMatch;
UInt32 len = Math.Min(len0, len1);
if (_bufferBase[pby1 + len] == _bufferBase[cur + len])
{
while (++len != lenLimit)
if (_bufferBase[pby1 + len] != _bufferBase[cur + len])
break;
if (len == lenLimit)
{
_son[ptr1] = _son[cyclicPos];
_son[ptr0] = _son[cyclicPos + 1];
break;
}
}
if (_bufferBase[pby1 + len] < _bufferBase[cur + len])
{
_son[ptr1] = curMatch;
ptr1 = cyclicPos + 1;
curMatch = _son[ptr1];
len1 = len;
}
else
{
_son[ptr0] = curMatch;
ptr0 = cyclicPos;
curMatch = _son[ptr0];
len0 = len;
}
}
MovePos();
}
while (--num != 0);
}
void NormalizeLinks(UInt32[] items, UInt32 numItems, UInt32 subValue)
{
for (UInt32 i = 0; i < numItems; i++)
{
UInt32 value = items[i];
if (value <= subValue)
value = kEmptyHashValue;
else
value -= subValue;
items[i] = value;
}
}
void Normalize()
{
UInt32 subValue = _pos - _cyclicBufferSize;
NormalizeLinks(_son, _cyclicBufferSize * 2, subValue);
NormalizeLinks(_hash, _hashSizeSum, subValue);
ReduceOffsets((Int32)subValue);
}
internal void SetCutValue(UInt32 cutValue) { _cutValue = cutValue; }
}
}
| |
using Stride.Core;
using Stride.Core.Mathematics;
using Stride.Engine;
using Stride.Physics;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using StrideToolkit.Collections;
namespace StrideToolkit.Engine.Navigation.Components
{
[Display("Scene Navigation Service")]
public class SceneNavigationService : StartupScript, ISceneNavigationService
{
public Scene StartScene { get; set; }
public bool KeepStartSceneLoaded { get; set; }
public bool IsNavigating { get; private set; }
private readonly List<SceneHistoryItem> back = new List<SceneHistoryItem>();
private readonly List<SceneHistoryItem> forward = new List<SceneHistoryItem>();
private SceneHistoryItem currentItem = default(SceneHistoryItem);
public override void Start()
{
Game.Services.AddService<ISceneNavigationService>(this);
if (StartScene != null)
{
var navTo = new SceneHistoryItem
{
Scene = StartScene,
KeepLoaded = KeepStartSceneLoaded,
};
if (!Content.TryGetAssetUrl(StartScene,out navTo.AssetName) && KeepStartSceneLoaded)
{
Log.Warning("Start Scene must be an Asset.");
}
Navigate(navTo, false);
}
//TODO: Put this else where
Script.AddTask(async () => {
while (Game.IsRunning)
{
var y = (int)Game.GraphicsContext.CommandList.Viewport.Height;
y -= 10;
DebugText.Print($"Number of running tasks: {Script.Scheduler.MicroThreads.Count}", new Int2(0, y));
await Script.NextFrame();
}
});
}
public override void Cancel()
{
Game.Services.RemoveService<ISceneNavigationService>();
ClearHistory();
if (currentItem.Scene != null)
{
SceneSystem.SceneInstance.RootScene.Children.Remove(currentItem.Scene);
if(currentItem.Scene != StartScene)
{
Content.Unload(currentItem.Scene);
}
}
ClearHistory();
currentItem = default(SceneHistoryItem);
}
public void ClearHistory()
{
foreach (var scene in back.Select(s => s.Scene).Where(s => s != null && s != StartScene))
{
Content.Unload(scene);
}
back.Clear();
foreach (var scene in forward.Select(s => s.Scene).Where(s => s != null && s != StartScene))
{
Content.Unload(scene);
}
forward.Clear();
}
public async Task<bool> NavigateAsync(string url, bool keepLoaded = false, bool rememberCurrent = true)
{
if (IsNavigating) return false;
IsNavigating = true;
if (!Content.Exists(url)) return false;
var navTo = new SceneHistoryItem
{
Scene = await Content.LoadAsync<Scene>(url),
AssetName = url,
KeepLoaded = keepLoaded,
};
Navigate(navTo, rememberCurrent);
IsNavigating = false;
return true;
}
private void Navigate(SceneHistoryItem navTo, bool rememberCurrent)
{
if(currentItem.Scene != null)
{
SceneSystem.SceneInstance.RootScene.Children.Remove(currentItem.Scene);
if (!currentItem.KeepLoaded)
{
Content.Unload(currentItem.Scene);
currentItem.Scene = null;
}
if (rememberCurrent)
{
back.Push(currentItem);
}
}
SceneSystem.SceneInstance.RootScene.Children.Add(navTo.Scene);
currentItem = navTo;
}
public bool CanGoBack => back.Count > 0;
public bool CanGoForward => forward.Count > 0;
public async Task<bool> GoBackAsync(bool rememberCurrent = true)
{
return await GoAsync(CanGoBack, back, forward, rememberCurrent);
}
public async Task<bool> GoForwardAsync(bool rememberCurrent = true)
{
return await GoAsync(CanGoForward, forward, back, rememberCurrent);
}
private async Task<bool> GoAsync(bool canNavigate, List<SceneHistoryItem> navigationFromStack, List<SceneHistoryItem> navigationToStack, bool rememberCurrent)
{
if (IsNavigating) return false;
IsNavigating = true;
if (!canNavigate)
{
IsNavigating = false;
return false;
}
var navTo = navigationFromStack.Pop();
if (navTo.Scene == null)
{
navTo.Scene = await Content.LoadAsync<Scene>(navTo.AssetName);
}
SceneSystem.SceneInstance.RootScene.Children.Remove(currentItem.Scene);
if (!currentItem.KeepLoaded)
{
Content.Unload(currentItem.Scene);
currentItem.Scene = null;
}
if (rememberCurrent)
{
navigationToStack.Push(currentItem);
}
SceneSystem.SceneInstance.RootScene.Children.Add(navTo.Scene);
currentItem = navTo;
IsNavigating = false;
return true;
}
private struct SceneHistoryItem
{
public Scene Scene;
public string AssetName;
public bool KeepLoaded;
}
}
}
| |
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading;
using Microsoft.Win32.SafeHandles;
using Voron.Exceptions;
using Voron.Global;
using Voron.Impl.Journal;
using Voron.Impl.Paging;
using Voron.Util;
using Sparrow.Binary;
namespace Voron.Platform.Win32
{
/// <summary>
/// This class assumes only a single writer at any given point in time
/// This require _external_ synchronization
/// </summary>S
public unsafe class Win32FileJournalWriter : IJournalWriter
{
private readonly StorageEnvironmentOptions _options;
private readonly int _pageSizeMultiplier;
private readonly string _filename;
private readonly SafeFileHandle _handle;
private SafeFileHandle _readHandle;
private Win32NativeFileMethods.FileSegmentElement* _segments;
private int _segmentsSize;
private NativeOverlapped* _nativeOverlapped;
private const int PhysicalPageSize = 4 * Constants.Size.Kilobyte;
public Win32FileJournalWriter(StorageEnvironmentOptions options, string filename, long journalSize)
{
_options = options;
_filename = filename;
_handle = Win32NativeFileMethods.CreateFile(filename,
Win32NativeFileAccess.GenericWrite, Win32NativeFileShare.Read, IntPtr.Zero,
Win32NativeFileCreationDisposition.OpenAlways,
Win32NativeFileAttributes.Write_Through | Win32NativeFileAttributes.NoBuffering | Win32NativeFileAttributes.Overlapped, IntPtr.Zero);
_pageSizeMultiplier = options.PageSize / PhysicalPageSize;
if (_handle.IsInvalid)
throw new Win32Exception();
Win32NativeFileMethods.SetFileLength(_handle, journalSize);
NumberOfAllocatedPages = (int)(journalSize / _options.PageSize);
_nativeOverlapped = (NativeOverlapped*) Marshal.AllocHGlobal(sizeof (NativeOverlapped));
_nativeOverlapped->InternalLow = IntPtr.Zero;
_nativeOverlapped->InternalHigh = IntPtr.Zero;
}
public void WriteGather(long position, IntPtr[] pages)
{
if (Disposed)
throw new ObjectDisposedException("Win32JournalWriter");
var physicalPages = EnsureSegmentsSize(pages);
_nativeOverlapped->OffsetLow = (int) (position & 0xffffffff);
_nativeOverlapped->OffsetHigh = (int) (position >> 32);
_nativeOverlapped->EventHandle = IntPtr.Zero;
PreparePagesToWrite(pages);
var sp = Stopwatch.StartNew();
// WriteFileGather will only be able to write x pages of size GetSystemInfo().dwPageSize. Usually that is 4096 (4kb). If you are
// having trouble with this method, ensure that this value havent changed for your environment.
var operationCompleted = Win32NativeFileMethods.WriteFileGather(_handle, _segments, (uint)(physicalPages * PhysicalPageSize), IntPtr.Zero, _nativeOverlapped);
uint lpNumberOfBytesWritten;
var sizeToWrite = physicalPages*PhysicalPageSize;
if (operationCompleted)
{
if (Win32NativeFileMethods.GetOverlappedResult(_handle, _nativeOverlapped, out lpNumberOfBytesWritten, true) == false)
throw new VoronUnrecoverableErrorException("Could not write to journal " + _filename, new Win32Exception(Marshal.GetLastWin32Error()));
// TODO : Measure IO times (RavenDB-4659) - Wrote {sizeToWrite/1024:#,#} kb in {sp.ElapsedMilliseconds:#,#} ms
return;
}
switch (Marshal.GetLastWin32Error())
{
case Win32NativeFileMethods.ErrorSuccess:
case Win32NativeFileMethods.ErrorIOPending:
if (Win32NativeFileMethods.GetOverlappedResult(_handle, _nativeOverlapped, out lpNumberOfBytesWritten, true) == false)
throw new VoronUnrecoverableErrorException("Could not write to journal " + _filename, new Win32Exception(Marshal.GetLastWin32Error()));
// TODO : Measure IO times (RavenDB-4659) - Wrote {sizeToWrite/1024:#,#} kb in {sp.ElapsedMilliseconds:#,#} ms
break;
default:
throw new VoronUnrecoverableErrorException("Could not write to journal " + _filename, new Win32Exception(Marshal.GetLastWin32Error()));
}
}
private void PreparePagesToWrite(IntPtr[] pages)
{
if (_pageSizeMultiplier == 1)
{
for (int i = 0; i < pages.Length; i++)
{
if (IntPtr.Size == 4)
_segments[i].Alignment = (ulong)pages[i];
else
_segments[i].Buffer = pages[i];
}
_segments[pages.Length].Alignment = 0; // null terminating
return;
}
var pageLength = pages.Length*_pageSizeMultiplier;
for (int step = 0; step < _pageSizeMultiplier; step++)
{
int offset = step * PhysicalPageSize;
for (int i = 0, ptr = step; i < pages.Length; i++, ptr += _pageSizeMultiplier)
{
if (IntPtr.Size == 4)
_segments[ptr].Alignment = (ulong)(pages[i] + offset);
else
_segments[ptr].Buffer = pages[i] + offset;
}
}
_segments[pageLength].Alignment = 0; // null terminating
}
private int EnsureSegmentsSize(IntPtr[] pages)
{
int physicalPages = (pages.Length * _pageSizeMultiplier);
if (_segmentsSize >= physicalPages + 1)
return physicalPages;
_segmentsSize = Bits.NextPowerOf2(physicalPages + 1);
if (_segments != null)
Marshal.FreeHGlobal((IntPtr) _segments);
_segments = (Win32NativeFileMethods.FileSegmentElement*) (Marshal.AllocHGlobal(_segmentsSize*sizeof (Win32NativeFileMethods.FileSegmentElement)));
return physicalPages;
}
public int NumberOfAllocatedPages { get; }
public bool DeleteOnClose { get; set; }
public AbstractPager CreatePager()
{
return new Win32MemoryMapPager(_options.PageSize,_filename);
}
public bool Read(long pageNumber, byte* buffer, int count)
{
if (_readHandle == null)
{
_readHandle = Win32NativeFileMethods.CreateFile(_filename,
Win32NativeFileAccess.GenericRead,
Win32NativeFileShare.Write | Win32NativeFileShare.Read | Win32NativeFileShare.Delete,
IntPtr.Zero,
Win32NativeFileCreationDisposition.OpenExisting,
Win32NativeFileAttributes.Normal,
IntPtr.Zero);
}
long position = pageNumber * _options.PageSize;
NativeOverlapped* nativeOverlapped = (NativeOverlapped*)Marshal.AllocHGlobal(sizeof(NativeOverlapped));
try
{
nativeOverlapped->OffsetLow = (int)(position & 0xffffffff);
nativeOverlapped->OffsetHigh = (int) (position >> 32);
nativeOverlapped->EventHandle = IntPtr.Zero;
while (count > 0)
{
int read;
if (Win32NativeFileMethods.ReadFile(_readHandle, buffer, count, out read, nativeOverlapped) == false)
{
int lastWin32Error = Marshal.GetLastWin32Error();
if (lastWin32Error == Win32NativeFileMethods.ErrorHandleEof)
return false;
throw new Win32Exception(lastWin32Error);
}
count -= read;
buffer += read;
position += read;
nativeOverlapped->OffsetLow = (int) (position & 0xffffffff);
nativeOverlapped->OffsetHigh = (int) (position >> 32);
}
return true;
}
finally
{
Marshal.FreeHGlobal((IntPtr) nativeOverlapped);
}
}
public void WriteBuffer(long position, byte* srcPointer, int sizeToWrite)
{
if (Disposed)
throw new ObjectDisposedException("Win32JournalWriter");
int written;
_nativeOverlapped->OffsetLow = (int)(position & 0xffffffff);
_nativeOverlapped->OffsetHigh = (int)(position >> 32);
_nativeOverlapped->EventHandle = IntPtr.Zero;
var sp = Stopwatch.StartNew();
var operationCompleted = Win32NativeFileMethods.WriteFile(_handle, srcPointer, sizeToWrite, out written, _nativeOverlapped);
uint lpNumberOfBytesWritten;
if (operationCompleted)
{
if (Win32NativeFileMethods.GetOverlappedResult(_handle, _nativeOverlapped, out lpNumberOfBytesWritten, true) == false)
throw new VoronUnrecoverableErrorException("Could not write lazy buffer to journal " + _filename, new Win32Exception(Marshal.GetLastWin32Error()));
// TODO : Measure IO times (RavenDB-4659) - Wrote {sizeToWrite/1024:#,#} kb in {sp.ElapsedMilliseconds:#,#} ms
return;
}
switch (Marshal.GetLastWin32Error())
{
case Win32NativeFileMethods.ErrorSuccess:
case Win32NativeFileMethods.ErrorIOPending:
if (Win32NativeFileMethods.GetOverlappedResult(_handle, _nativeOverlapped, out lpNumberOfBytesWritten, true) == false)
throw new VoronUnrecoverableErrorException("Could not write lazy buffer to journal " + _filename, new Win32Exception(Marshal.GetLastWin32Error()));
// TODO : Measure IO times (RavenDB-4659) - Wrote {sizeToWrite / 1024:#,#} kb in {sp.ElapsedMilliseconds:#,#} ms
break;
default:
throw new VoronUnrecoverableErrorException("Could not write lazy buffer to journal " + _filename, new Win32Exception(Marshal.GetLastWin32Error()));
}
}
public void Dispose()
{
Disposed = true;
GC.SuppressFinalize(this);
_readHandle?.Dispose();
_handle.Dispose();
if (_nativeOverlapped != null)
{
Marshal.FreeHGlobal((IntPtr) _nativeOverlapped);
_nativeOverlapped = null;
}
if (_segments != null)
{
Marshal.FreeHGlobal((IntPtr) _segments);
_segments = null;
}
if (DeleteOnClose)
{
try
{
File.Delete(_filename);
}
catch (Exception)
{
// if we can't delete, nothing that we can do here.
}
}
}
public bool Disposed { get; private set; }
~Win32FileJournalWriter()
{
Dispose();
}
}
}
| |
using J2N.IO;
using YAF.Lucene.Net.Util;
using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
namespace YAF.Lucene.Net.Store
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/// <summary>
/// Base <see cref="IndexInput"/> implementation that uses an array
/// of <see cref="ByteBuffer"/>s to represent a file.
/// <para/>
/// Because Java's <see cref="ByteBuffer"/> uses an <see cref="int"/> to address the
/// values, it's necessary to access a file greater
/// <see cref="int.MaxValue"/> in size using multiple byte buffers.
/// <para/>
/// For efficiency, this class requires that the buffers
/// are a power-of-two (<c>chunkSizePower</c>).
/// </summary>
public abstract class ByteBufferIndexInput : IndexInput
{
private ByteBuffer[] buffers;
private readonly long chunkSizeMask;
private readonly int chunkSizePower;
private int offset;
private long length;
private string sliceDescription;
private int curBufIndex;
private ByteBuffer curBuf; // redundant for speed: buffers[curBufIndex]
private bool isClone = false;
// LUCENENET: Using ConditionalWeakTable rather than WeakIdenityMap. ConditionalWeakTable
// uses RuntimeHelpers.GetHashCode() to find the item, so technically, it IS an identity collection.
private ConditionalWeakTable<ByteBufferIndexInput, BoolRefWrapper> clones;
private class BoolRefWrapper
{
private bool value;
// .NET port: this is needed as bool is not a reference type
public BoolRefWrapper(bool value)
{
this.value = value;
}
public static implicit operator bool(BoolRefWrapper value)
{
return value.value;
}
public static implicit operator BoolRefWrapper(bool value)
{
return new BoolRefWrapper(value);
}
}
internal ByteBufferIndexInput(string resourceDescription, ByteBuffer[] buffers, long length, int chunkSizePower, bool trackClones)
: base(resourceDescription)
{
//this.buffers = buffers; // LUCENENET: this is set in SetBuffers()
this.length = length;
this.chunkSizePower = chunkSizePower;
this.chunkSizeMask = (1L << chunkSizePower) - 1L;
// LUCENENET: Using ConditionalWeakTable rather than WeakIdenityMap. ConditionalWeakTable
// uses RuntimeHelpers.GetHashCode() to find the item, so technically, it IS an identity collection.
this.clones = trackClones ? new ConditionalWeakTable<ByteBufferIndexInput, BoolRefWrapper>() : null;
Debug.Assert(chunkSizePower >= 0 && chunkSizePower <= 30);
Debug.Assert(((long)((ulong)length >> chunkSizePower)) < int.MaxValue);
// LUCENENET specific: MMapIndexInput calls SetBuffers() to populate
// the buffers, so we need to skip that call if it is null here, and
// do the seek inside SetBuffers()
if (buffers != null)
{
SetBuffers(buffers);
}
}
// LUCENENET specific for encapsulating buffers field.
internal void SetBuffers(ByteBuffer[] buffers) // necessary for MMapIndexInput
{
this.buffers = buffers;
Seek(0L);
}
public override sealed byte ReadByte()
{
// LUCENENET: Refactored to avoid calls on invalid conditions instead of
// catching and re-throwing exceptions in the normal workflow.
EnsureOpen();
if (curBuf.HasRemaining)
{
return curBuf.Get();
}
do
{
curBufIndex++;
if (curBufIndex >= buffers.Length)
{
throw new EndOfStreamException("read past EOF: " + this);
}
curBuf = buffers[curBufIndex];
curBuf.Position = 0;
} while (!curBuf.HasRemaining);
return curBuf.Get();
}
public override sealed void ReadBytes(byte[] b, int offset, int len)
{
// LUCENENET: Refactored to avoid calls on invalid conditions instead of
// catching and re-throwing exceptions in the normal workflow.
EnsureOpen();
int curAvail = curBuf.Remaining;
if (len <= curAvail)
{
curBuf.Get(b, offset, len);
}
else
{
while (len > curAvail)
{
curBuf.Get(b, offset, curAvail);
len -= curAvail;
offset += curAvail;
curBufIndex++;
if (curBufIndex >= buffers.Length)
{
throw new EndOfStreamException("read past EOF: " + this);
}
curBuf = buffers[curBufIndex];
curBuf.Position = 0;
curAvail = curBuf.Remaining;
}
curBuf.Get(b, offset, len);
}
}
/// <summary>
/// NOTE: this was readShort() in Lucene
/// </summary>
public override sealed short ReadInt16()
{
// LUCENENET: Refactored to avoid calls on invalid conditions instead of
// catching and re-throwing exceptions in the normal workflow.
EnsureOpen();
if (curBuf.Remaining >= 2)
{
return curBuf.GetInt16();
}
return base.ReadInt16();
}
/// <summary>
/// NOTE: this was readInt() in Lucene
/// </summary>
public override sealed int ReadInt32()
{
// LUCENENET: Refactored to avoid calls on invalid conditions instead of
// catching and re-throwing exceptions in the normal workflow.
EnsureOpen();
if (curBuf.Remaining >= 4)
{
return curBuf.GetInt32();
}
return base.ReadInt32();
}
/// <summary>
/// NOTE: this was readLong() in Lucene
/// </summary>
public override sealed long ReadInt64()
{
// LUCENENET: Refactored to avoid calls on invalid conditions instead of
// catching and re-throwing exceptions in the normal workflow.
EnsureOpen();
if (curBuf.Remaining >= 8)
{
return curBuf.GetInt64();
}
return base.ReadInt64();
}
public override sealed long GetFilePointer()
{
// LUCENENET: Refactored to avoid calls on invalid conditions instead of
// catching and re-throwing exceptions in the normal workflow.
EnsureOpen();
return (((long)curBufIndex) << chunkSizePower) + curBuf.Position - offset;
}
public override sealed void Seek(long pos)
{
// necessary in case offset != 0 and pos < 0, but pos >= -offset
if (pos < 0L)
{
throw new ArgumentException("Seeking to negative position: " + this);
}
pos += offset;
// we use >> here to preserve negative, so we will catch AIOOBE,
// in case pos + offset overflows.
int bi = (int)(pos >> chunkSizePower);
try
{
ByteBuffer b = buffers[bi];
b.Position = ((int)(pos & chunkSizeMask));
// write values, on exception all is unchanged
this.curBufIndex = bi;
this.curBuf = b;
}
catch (IndexOutOfRangeException)
{
throw new EndOfStreamException("seek past EOF: " + this);
}
catch (ArgumentException)
{
throw new EndOfStreamException("seek past EOF: " + this);
}
catch (NullReferenceException)
{
throw new ObjectDisposedException(this.GetType().GetTypeInfo().FullName, "Already closed: " + this);
}
}
public override sealed long Length
{
get { return length; }
}
public override sealed object Clone()
{
ByteBufferIndexInput clone = BuildSlice(0L, this.length);
try
{
clone.Seek(GetFilePointer());
}
catch (IOException ioe)
{
throw new Exception("Should never happen: " + this, ioe);
}
return clone;
}
/// <summary>
/// Creates a slice of this index input, with the given description, offset, and length. The slice is seeked to the beginning.
/// </summary>
public ByteBufferIndexInput Slice(string sliceDescription, long offset, long length)
{
if (isClone) // well we could, but this is stupid
{
throw new InvalidOperationException("cannot slice() " + sliceDescription + " from a cloned IndexInput: " + this);
}
ByteBufferIndexInput clone = BuildSlice(offset, length);
clone.sliceDescription = sliceDescription;
try
{
clone.Seek(0L);
}
catch (IOException ioe)
{
throw new Exception("Should never happen: " + this, ioe);
}
return clone;
}
private ByteBufferIndexInput BuildSlice(long offset, long length)
{
if (buffers == null)
{
throw new ObjectDisposedException(this.GetType().GetTypeInfo().FullName, "Already closed: " + this);
}
if (offset < 0 || length < 0 || offset + length > this.length)
{
throw new ArgumentException("slice() " + sliceDescription + " out of bounds: offset=" + offset + ",length=" + length + ",fileLength=" + this.length + ": " + this);
}
// include our own offset into the final offset:
offset += this.offset;
ByteBufferIndexInput clone = (ByteBufferIndexInput)base.Clone();
clone.isClone = true;
// we keep clone.clones, so it shares the same map with original and we have no additional cost on clones
Debug.Assert(clone.clones == this.clones);
clone.buffers = BuildSlice(buffers, offset, length);
clone.offset = (int)(offset & chunkSizeMask);
clone.length = length;
// register the new clone in our clone list to clean it up on closing:
if (clones != null)
{
this.clones.Add(clone, true);
}
return clone;
}
/// <summary>
/// Returns a sliced view from a set of already-existing buffers:
/// the last buffer's <see cref="J2N.IO.Buffer.Limit"/> will be correct, but
/// you must deal with <paramref name="offset"/> separately (the first buffer will not be adjusted)
/// </summary>
private ByteBuffer[] BuildSlice(ByteBuffer[] buffers, long offset, long length)
{
long sliceEnd = offset + length;
int startIndex = (int)((long)((ulong)offset >> chunkSizePower));
int endIndex = (int)((long)((ulong)sliceEnd >> chunkSizePower));
// we always allocate one more slice, the last one may be a 0 byte one
ByteBuffer[] slices = new ByteBuffer[endIndex - startIndex + 1];
for (int i = 0; i < slices.Length; i++)
{
slices[i] = buffers[startIndex + i].Duplicate();
}
// set the last buffer's limit for the sliced view.
slices[slices.Length - 1].Limit = ((int)(sliceEnd & chunkSizeMask));
return slices;
}
private void UnsetBuffers()
{
buffers = null;
curBuf = null;
curBufIndex = 0;
}
// LUCENENET specific - rather than using all of this exception catching nonsense
// for control flow, we check whether we are disposed first.
private void EnsureOpen()
{
if (buffers == null || curBuf == null)
{
throw new ObjectDisposedException(this.GetType().GetTypeInfo().FullName, "Already closed: " + this);
}
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
try
{
if (buffers == null)
{
return;
}
// make local copy, then un-set early
ByteBuffer[] bufs = buffers;
UnsetBuffers();
if (clones != null)
{
clones.Remove(this);
}
if (isClone)
{
return;
}
// for extra safety unset also all clones' buffers:
if (clones != null)
{
// LUCENENET: Since .NET will GC types that go out of scope automatically,
// this isn't strictly necessary. However, we are doing it anyway when
// the enumerator is available (.NET Standard 2.1+)
#if FEATURE_CONDITIONALWEAKTABLE_ENUMERATOR
foreach (var pair in clones)
{
pair.Key.UnsetBuffers();
}
this.clones.Clear();
#endif
this.clones = null; // LUCENENET: de-reference the table so it can be GC'd
}
foreach (ByteBuffer b in bufs)
{
FreeBuffer(b); // LUCENENET: This calls Dispose() when necessary
}
}
finally
{
UnsetBuffers();
}
}
}
/// <summary>
/// Called when the contents of a buffer will be no longer needed.
/// </summary>
protected abstract void FreeBuffer(ByteBuffer b);
public override sealed string ToString()
{
if (sliceDescription != null)
{
return base.ToString() + " [slice=" + sliceDescription + "]";
}
else
{
return base.ToString();
}
}
}
}
| |
//---------------------------------------------------------------------------
//
// File: HtmlSchema.cs
//
// Copyright (C) Microsoft Corporation. All rights reserved.
//
// Description: Static information about HTML structure
//
//---------------------------------------------------------------------------
using System.Collections;
using System.Diagnostics;
/// <summary>
/// HtmlSchema class
/// maintains static information about HTML structure
/// can be used by HtmlParser to check conditions under which an element starts or ends, etc.
/// </summary>
internal class HtmlSchema
{
// ---------------------------------------------------------------------
//
// Constructors
//
// ---------------------------------------------------------------------
#region Constructors
/// <summary>
/// static constructor, initializes the ArrayLists
/// that hold the elements in various sub-components of the schema
/// e.g _htmlEmptyElements, etc.
/// </summary>
static HtmlSchema()
{
// initializes the list of all html elements
InitializeInlineElements();
InitializeBlockElements();
InitializeOtherOpenableElements();
// initialize empty elements list
InitializeEmptyElements();
// initialize list of elements closing on the outer element end
InitializeElementsClosingOnParentElementEnd();
// initalize list of elements that close when a new element starts
InitializeElementsClosingOnNewElementStart();
// Initialize character entities
InitializeHtmlCharacterEntities();
}
#endregion Constructors;
// ---------------------------------------------------------------------
//
// Internal Methods
//
// ---------------------------------------------------------------------
#region Internal Methods
/// <summary>
/// returns true when xmlElementName corresponds to empty element
/// </summary>
/// <param name="xmlElementName">
/// string representing name to test
/// </param>
internal static bool IsEmptyElement(string xmlElementName)
{
// convert to lowercase before we check
// because element names are not case sensitive
return _htmlEmptyElements.Contains(xmlElementName.ToLower());
}
/// <summary>
/// returns true if xmlElementName represents a block formattinng element.
/// It used in an algorithm of transferring inline elements over block elements
/// in HtmlParser
/// </summary>
/// <param name="xmlElementName"></param>
/// <returns></returns>
internal static bool IsBlockElement(string xmlElementName)
{
return _htmlBlockElements.Contains(xmlElementName);
}
/// <summary>
/// returns true if the xmlElementName represents an inline formatting element
/// </summary>
/// <param name="xmlElementName"></param>
/// <returns></returns>
internal static bool IsInlineElement(string xmlElementName)
{
return _htmlInlineElements.Contains(xmlElementName);
}
/// <summary>
/// It is a list of known html elements which we
/// want to allow to produce bt HTML parser,
/// but don'tt want to act as inline, block or no-scope.
/// Presence in this list will allow to open
/// elements during html parsing, and adding the
/// to a tree produced by html parser.
/// </summary>
internal static bool IsKnownOpenableElement(string xmlElementName)
{
return _htmlOtherOpenableElements.Contains(xmlElementName);
}
/// <summary>
/// returns true when xmlElementName closes when the outer element closes
/// this is true of elements with optional start tags
/// </summary>
/// <param name="xmlElementName">
/// string representing name to test
/// </param>
internal static bool ClosesOnParentElementEnd(string xmlElementName)
{
// convert to lowercase when testing
return _htmlElementsClosingOnParentElementEnd.Contains(xmlElementName.ToLower());
}
/// <summary>
/// returns true if the current element closes when the new element, whose name has just been read, starts
/// </summary>
/// <param name="currentElementName">
/// string representing current element name
/// </param>
/// <param name="elementName"></param>
/// string representing name of the next element that will start
internal static bool ClosesOnNextElementStart(string currentElementName, string nextElementName)
{
Debug.Assert(currentElementName == currentElementName.ToLower());
switch (currentElementName)
{
case "colgroup":
return _htmlElementsClosingColgroup.Contains(nextElementName) && HtmlSchema.IsBlockElement(nextElementName);
case "dd":
return _htmlElementsClosingDD.Contains(nextElementName) && HtmlSchema.IsBlockElement(nextElementName);
case "dt":
return _htmlElementsClosingDT.Contains(nextElementName) && HtmlSchema.IsBlockElement(nextElementName);
case "li":
return _htmlElementsClosingLI.Contains(nextElementName);
case "p":
return HtmlSchema.IsBlockElement(nextElementName);
case "tbody":
return _htmlElementsClosingTbody.Contains(nextElementName);
case "tfoot":
return _htmlElementsClosingTfoot.Contains(nextElementName);
case "thead":
return _htmlElementsClosingThead.Contains(nextElementName);
case "tr":
return _htmlElementsClosingTR.Contains(nextElementName);
case "td":
return _htmlElementsClosingTD.Contains(nextElementName);
case "th":
return _htmlElementsClosingTH.Contains(nextElementName);
}
return false;
}
/// <summary>
/// returns true if the string passed as argument is an Html entity name
/// </summary>
/// <param name="entityName">
/// string to be tested for Html entity name
/// </param>
internal static bool IsEntity(string entityName)
{
// we do not convert entity strings to lowercase because these names are case-sensitive
if (_htmlCharacterEntities.Contains(entityName))
{
return true;
}
else
{
return false;
}
}
/// <summary>
/// returns the character represented by the entity name string which is passed as an argument, if the string is an entity name
/// as specified in _htmlCharacterEntities, returns the character value of 0 otherwise
/// </summary>
/// <param name="entityName">
/// string representing entity name whose character value is desired
/// </param>
internal static char EntityCharacterValue(string entityName)
{
if (_htmlCharacterEntities.Contains(entityName))
{
return (char) _htmlCharacterEntities[entityName];
}
else
{
return (char)0;
}
}
#endregion Internal Methods
// ---------------------------------------------------------------------
//
// Internal Properties
//
// ---------------------------------------------------------------------
#region Internal Properties
#endregion Internal Indexers
// ---------------------------------------------------------------------
//
// Private Methods
//
// ---------------------------------------------------------------------
#region Private Methods
private static void InitializeInlineElements()
{
_htmlInlineElements = new ArrayList();
_htmlInlineElements.Add("a");
_htmlInlineElements.Add("abbr");
_htmlInlineElements.Add("acronym");
_htmlInlineElements.Add("address");
_htmlInlineElements.Add("b");
_htmlInlineElements.Add("bdo"); // ???
_htmlInlineElements.Add("big");
_htmlInlineElements.Add("button");
_htmlInlineElements.Add("code");
_htmlInlineElements.Add("del"); // deleted text
_htmlInlineElements.Add("dfn");
_htmlInlineElements.Add("em");
_htmlInlineElements.Add("font");
_htmlInlineElements.Add("i");
_htmlInlineElements.Add("ins"); // inserted text
_htmlInlineElements.Add("kbd"); // text to entered by a user
_htmlInlineElements.Add("label");
_htmlInlineElements.Add("legend"); // ???
_htmlInlineElements.Add("q"); // short inline quotation
_htmlInlineElements.Add("s"); // strike-through text style
_htmlInlineElements.Add("samp"); // Specifies a code sample
_htmlInlineElements.Add("small");
_htmlInlineElements.Add("span");
_htmlInlineElements.Add("strike");
_htmlInlineElements.Add("strong");
_htmlInlineElements.Add("sub");
_htmlInlineElements.Add("sup");
_htmlInlineElements.Add("u");
_htmlInlineElements.Add("var"); // indicates an instance of a program variable
}
private static void InitializeBlockElements()
{
_htmlBlockElements = new ArrayList();
_htmlBlockElements.Add("blockquote");
_htmlBlockElements.Add("body");
_htmlBlockElements.Add("caption");
_htmlBlockElements.Add("center");
_htmlBlockElements.Add("cite");
_htmlBlockElements.Add("dd");
_htmlBlockElements.Add("dir"); // treat as UL element
_htmlBlockElements.Add("div");
_htmlBlockElements.Add("dl");
_htmlBlockElements.Add("dt");
_htmlBlockElements.Add("form"); // Not a block according to XHTML spec
_htmlBlockElements.Add("h1");
_htmlBlockElements.Add("h2");
_htmlBlockElements.Add("h3");
_htmlBlockElements.Add("h4");
_htmlBlockElements.Add("h5");
_htmlBlockElements.Add("h6");
_htmlBlockElements.Add("html");
_htmlBlockElements.Add("li");
_htmlBlockElements.Add("menu"); // treat as UL element
_htmlBlockElements.Add("ol");
_htmlBlockElements.Add("p");
_htmlBlockElements.Add("pre"); // Renders text in a fixed-width font
_htmlBlockElements.Add("table");
_htmlBlockElements.Add("tbody");
_htmlBlockElements.Add("td");
_htmlBlockElements.Add("textarea");
_htmlBlockElements.Add("tfoot");
_htmlBlockElements.Add("th");
_htmlBlockElements.Add("thead");
_htmlBlockElements.Add("tr");
_htmlBlockElements.Add("tt");
_htmlBlockElements.Add("ul");
}
/// <summary>
/// initializes _htmlEmptyElements with empty elements in HTML 4 spec at
/// http://www.w3.org/TR/REC-html40/index/elements.html
/// </summary>
private static void InitializeEmptyElements()
{
// Build a list of empty (no-scope) elements
// (element not requiring closing tags, and not accepting any content)
_htmlEmptyElements = new ArrayList();
_htmlEmptyElements.Add("area");
_htmlEmptyElements.Add("base");
_htmlEmptyElements.Add("basefont");
_htmlEmptyElements.Add("br");
_htmlEmptyElements.Add("col");
_htmlEmptyElements.Add("frame");
_htmlEmptyElements.Add("hr");
_htmlEmptyElements.Add("img");
_htmlEmptyElements.Add("input");
_htmlEmptyElements.Add("isindex");
_htmlEmptyElements.Add("link");
_htmlEmptyElements.Add("meta");
_htmlEmptyElements.Add("param");
}
private static void InitializeOtherOpenableElements()
{
// It is a list of known html elements which we
// want to allow to produce bt HTML parser,
// but don'tt want to act as inline, block or no-scope.
// Presence in this list will allow to open
// elements during html parsing, and adding the
// to a tree produced by html parser.
_htmlOtherOpenableElements = new ArrayList();
_htmlOtherOpenableElements.Add("applet");
_htmlOtherOpenableElements.Add("base");
_htmlOtherOpenableElements.Add("basefont");
_htmlOtherOpenableElements.Add("colgroup");
_htmlOtherOpenableElements.Add("fieldset");
//_htmlOtherOpenableElements.Add("form"); --> treated as block
_htmlOtherOpenableElements.Add("frameset");
_htmlOtherOpenableElements.Add("head");
_htmlOtherOpenableElements.Add("iframe");
_htmlOtherOpenableElements.Add("map");
_htmlOtherOpenableElements.Add("noframes");
_htmlOtherOpenableElements.Add("noscript");
_htmlOtherOpenableElements.Add("object");
_htmlOtherOpenableElements.Add("optgroup");
_htmlOtherOpenableElements.Add("option");
_htmlOtherOpenableElements.Add("script");
_htmlOtherOpenableElements.Add("select");
_htmlOtherOpenableElements.Add("style");
_htmlOtherOpenableElements.Add("title");
}
/// <summary>
/// initializes _htmlElementsClosingOnParentElementEnd with the list of HTML 4 elements for which closing tags are optional
/// we assume that for any element for which closing tags are optional, the element closes when it's outer element
/// (in which it is nested) does
/// </summary>
private static void InitializeElementsClosingOnParentElementEnd()
{
_htmlElementsClosingOnParentElementEnd = new ArrayList();
_htmlElementsClosingOnParentElementEnd.Add("body");
_htmlElementsClosingOnParentElementEnd.Add("colgroup");
_htmlElementsClosingOnParentElementEnd.Add("dd");
_htmlElementsClosingOnParentElementEnd.Add("dt");
_htmlElementsClosingOnParentElementEnd.Add("head");
_htmlElementsClosingOnParentElementEnd.Add("html");
_htmlElementsClosingOnParentElementEnd.Add("li");
_htmlElementsClosingOnParentElementEnd.Add("p");
_htmlElementsClosingOnParentElementEnd.Add("tbody");
_htmlElementsClosingOnParentElementEnd.Add("td");
_htmlElementsClosingOnParentElementEnd.Add("tfoot");
_htmlElementsClosingOnParentElementEnd.Add("thead");
_htmlElementsClosingOnParentElementEnd.Add("th");
_htmlElementsClosingOnParentElementEnd.Add("tr");
}
private static void InitializeElementsClosingOnNewElementStart()
{
_htmlElementsClosingColgroup = new ArrayList();
_htmlElementsClosingColgroup.Add("colgroup");
_htmlElementsClosingColgroup.Add("tr");
_htmlElementsClosingColgroup.Add("thead");
_htmlElementsClosingColgroup.Add("tfoot");
_htmlElementsClosingColgroup.Add("tbody");
_htmlElementsClosingDD = new ArrayList();
_htmlElementsClosingDD.Add("dd");
_htmlElementsClosingDD.Add("dt");
// TODO: dd may end in other cases as well - if a new "p" starts, etc.
// TODO: these are the basic "legal" cases but there may be more recovery
_htmlElementsClosingDT = new ArrayList();
_htmlElementsClosingDD.Add("dd");
_htmlElementsClosingDD.Add("dt");
// TODO: dd may end in other cases as well - if a new "p" starts, etc.
// TODO: these are the basic "legal" cases but there may be more recovery
_htmlElementsClosingLI = new ArrayList();
_htmlElementsClosingLI.Add("li");
// TODO: more complex recovery
_htmlElementsClosingTbody = new ArrayList();
_htmlElementsClosingTbody.Add("tbody");
_htmlElementsClosingTbody.Add("thead");
_htmlElementsClosingTbody.Add("tfoot");
// TODO: more complex recovery
_htmlElementsClosingTR = new ArrayList();
// NOTE: tr should not really close on a new thead
// because if there are rows before a thead, it is assumed to be in tbody, whose start tag is optional
// and thead can't come after tbody
// however, if we do encounter this, it's probably best to end the row and ignore the thead or treat
// it as part of the table
_htmlElementsClosingTR.Add("thead");
_htmlElementsClosingTR.Add("tfoot");
_htmlElementsClosingTR.Add("tbody");
_htmlElementsClosingTR.Add("tr");
// TODO: more complex recovery
_htmlElementsClosingTD = new ArrayList();
_htmlElementsClosingTD.Add("td");
_htmlElementsClosingTD.Add("th");
_htmlElementsClosingTD.Add("tr");
_htmlElementsClosingTD.Add("tbody");
_htmlElementsClosingTD.Add("tfoot");
_htmlElementsClosingTD.Add("thead");
// TODO: more complex recovery
_htmlElementsClosingTH = new ArrayList();
_htmlElementsClosingTH.Add("td");
_htmlElementsClosingTH.Add("th");
_htmlElementsClosingTH.Add("tr");
_htmlElementsClosingTH.Add("tbody");
_htmlElementsClosingTH.Add("tfoot");
_htmlElementsClosingTH.Add("thead");
// TODO: more complex recovery
_htmlElementsClosingThead = new ArrayList();
_htmlElementsClosingThead.Add("tbody");
_htmlElementsClosingThead.Add("tfoot");
// TODO: more complex recovery
_htmlElementsClosingTfoot = new ArrayList();
_htmlElementsClosingTfoot.Add("tbody");
// although thead comes before tfoot, we add it because if it is found the tfoot should close
// and some recovery processing be done on the thead
_htmlElementsClosingTfoot.Add("thead");
// TODO: more complex recovery
}
/// <summary>
/// initializes _htmlCharacterEntities hashtable with the character corresponding to entity names
/// </summary>
private static void InitializeHtmlCharacterEntities()
{
_htmlCharacterEntities = new Hashtable();
_htmlCharacterEntities["Aacute"] = (char)193;
_htmlCharacterEntities["aacute"] = (char)225;
_htmlCharacterEntities["Acirc"] = (char)194;
_htmlCharacterEntities["acirc"] = (char)226;
_htmlCharacterEntities["acute"] = (char)180;
_htmlCharacterEntities["AElig"] = (char)198;
_htmlCharacterEntities["aelig"] = (char)230;
_htmlCharacterEntities["Agrave"] = (char)192;
_htmlCharacterEntities["agrave"] = (char)224;
_htmlCharacterEntities["alefsym"] = (char)8501;
_htmlCharacterEntities["Alpha"] = (char)913;
_htmlCharacterEntities["alpha"] = (char)945;
_htmlCharacterEntities["amp"] = (char)38;
_htmlCharacterEntities["and"] = (char)8743;
_htmlCharacterEntities["ang"] = (char)8736;
_htmlCharacterEntities["Aring"] = (char)197;
_htmlCharacterEntities["aring"] = (char)229;
_htmlCharacterEntities["asymp"] = (char)8776;
_htmlCharacterEntities["Atilde"] = (char)195;
_htmlCharacterEntities["atilde"] = (char)227;
_htmlCharacterEntities["Auml"] = (char)196;
_htmlCharacterEntities["auml"] = (char)228;
_htmlCharacterEntities["bdquo"] = (char)8222;
_htmlCharacterEntities["Beta"] = (char)914;
_htmlCharacterEntities["beta"] = (char)946;
_htmlCharacterEntities["brvbar"] = (char)166;
_htmlCharacterEntities["bull"] = (char)8226;
_htmlCharacterEntities["cap"] = (char)8745;
_htmlCharacterEntities["Ccedil"] = (char)199;
_htmlCharacterEntities["ccedil"] = (char)231;
_htmlCharacterEntities["cent"] = (char)162;
_htmlCharacterEntities["Chi"] = (char)935;
_htmlCharacterEntities["chi"] = (char)967;
_htmlCharacterEntities["circ"] = (char)710;
_htmlCharacterEntities["clubs"] = (char)9827;
_htmlCharacterEntities["cong"] = (char)8773;
_htmlCharacterEntities["copy"] = (char)169;
_htmlCharacterEntities["crarr"] = (char)8629;
_htmlCharacterEntities["cup"] = (char)8746;
_htmlCharacterEntities["curren"] = (char)164;
_htmlCharacterEntities["dagger"] = (char)8224;
_htmlCharacterEntities["Dagger"] = (char)8225;
_htmlCharacterEntities["darr"] = (char)8595;
_htmlCharacterEntities["dArr"] = (char)8659;
_htmlCharacterEntities["deg"] = (char)176;
_htmlCharacterEntities["Delta"] = (char)916;
_htmlCharacterEntities["delta"] = (char)948;
_htmlCharacterEntities["diams"] = (char)9830;
_htmlCharacterEntities["divide"] = (char)247;
_htmlCharacterEntities["Eacute"] = (char)201;
_htmlCharacterEntities["eacute"] = (char)233;
_htmlCharacterEntities["Ecirc"] = (char)202;
_htmlCharacterEntities["ecirc"] = (char)234;
_htmlCharacterEntities["Egrave"] = (char)200;
_htmlCharacterEntities["egrave"] = (char)232;
_htmlCharacterEntities["empty"] = (char)8709;
_htmlCharacterEntities["emsp"] = (char)8195;
_htmlCharacterEntities["ensp"] = (char)8194;
_htmlCharacterEntities["Epsilon"] = (char)917;
_htmlCharacterEntities["epsilon"] = (char)949;
_htmlCharacterEntities["equiv"] = (char)8801;
_htmlCharacterEntities["Eta"] = (char)919;
_htmlCharacterEntities["eta"] = (char)951;
_htmlCharacterEntities["ETH"] = (char)208;
_htmlCharacterEntities["eth"] = (char)240;
_htmlCharacterEntities["Euml"] = (char)203;
_htmlCharacterEntities["euml"] = (char)235;
_htmlCharacterEntities["euro"] = (char)8364;
_htmlCharacterEntities["exist"] = (char)8707;
_htmlCharacterEntities["fnof"] = (char)402;
_htmlCharacterEntities["forall"] = (char)8704;
_htmlCharacterEntities["frac12"] = (char)189;
_htmlCharacterEntities["frac14"] = (char)188;
_htmlCharacterEntities["frac34"] = (char)190;
_htmlCharacterEntities["frasl"] = (char)8260;
_htmlCharacterEntities["Gamma"] = (char)915;
_htmlCharacterEntities["gamma"] = (char)947;
_htmlCharacterEntities["ge"] = (char)8805;
_htmlCharacterEntities["gt"] = (char)62;
_htmlCharacterEntities["harr"] = (char)8596;
_htmlCharacterEntities["hArr"] = (char)8660;
_htmlCharacterEntities["hearts"] = (char)9829;
_htmlCharacterEntities["hellip"] = (char)8230;
_htmlCharacterEntities["Iacute"] = (char)205;
_htmlCharacterEntities["iacute"] = (char)237;
_htmlCharacterEntities["Icirc"] = (char)206;
_htmlCharacterEntities["icirc"] = (char)238;
_htmlCharacterEntities["iexcl"] = (char)161;
_htmlCharacterEntities["Igrave"] = (char)204;
_htmlCharacterEntities["igrave"] = (char)236;
_htmlCharacterEntities["image"] = (char)8465;
_htmlCharacterEntities["infin"] = (char)8734;
_htmlCharacterEntities["int"] = (char)8747;
_htmlCharacterEntities["Iota"] = (char)921;
_htmlCharacterEntities["iota"] = (char)953;
_htmlCharacterEntities["iquest"] = (char)191;
_htmlCharacterEntities["isin"] = (char)8712;
_htmlCharacterEntities["Iuml"] = (char)207;
_htmlCharacterEntities["iuml"] = (char)239;
_htmlCharacterEntities["Kappa"] = (char)922;
_htmlCharacterEntities["kappa"] = (char)954;
_htmlCharacterEntities["Lambda"] = (char)923;
_htmlCharacterEntities["lambda"] = (char)955;
_htmlCharacterEntities["lang"] = (char)9001;
_htmlCharacterEntities["laquo"] = (char)171;
_htmlCharacterEntities["larr"] = (char)8592;
_htmlCharacterEntities["lArr"] = (char)8656;
_htmlCharacterEntities["lceil"] = (char)8968;
_htmlCharacterEntities["ldquo"] = (char)8220;
_htmlCharacterEntities["le"] = (char)8804;
_htmlCharacterEntities["lfloor"] = (char)8970;
_htmlCharacterEntities["lowast"] = (char)8727;
_htmlCharacterEntities["loz"] = (char)9674;
_htmlCharacterEntities["lrm"] = (char)8206;
_htmlCharacterEntities["lsaquo"] = (char)8249;
_htmlCharacterEntities["lsquo"] = (char)8216;
_htmlCharacterEntities["lt"] = (char)60;
_htmlCharacterEntities["macr"] = (char)175;
_htmlCharacterEntities["mdash"] = (char)8212;
_htmlCharacterEntities["micro"] = (char)181;
_htmlCharacterEntities["middot"] = (char)183;
_htmlCharacterEntities["minus"] = (char)8722;
_htmlCharacterEntities["Mu"] = (char)924;
_htmlCharacterEntities["mu"] = (char)956;
_htmlCharacterEntities["nabla"] = (char)8711;
_htmlCharacterEntities["nbsp"] = (char)160;
_htmlCharacterEntities["ndash"] = (char)8211;
_htmlCharacterEntities["ne"] = (char)8800;
_htmlCharacterEntities["ni"] = (char)8715;
_htmlCharacterEntities["not"] = (char)172;
_htmlCharacterEntities["notin"] = (char)8713;
_htmlCharacterEntities["nsub"] = (char)8836;
_htmlCharacterEntities["Ntilde"] = (char)209;
_htmlCharacterEntities["ntilde"] = (char)241;
_htmlCharacterEntities["Nu"] = (char)925;
_htmlCharacterEntities["nu"] = (char)957;
_htmlCharacterEntities["Oacute"] = (char)211;
_htmlCharacterEntities["ocirc"] = (char)244;
_htmlCharacterEntities["OElig"] = (char)338;
_htmlCharacterEntities["oelig"] = (char)339;
_htmlCharacterEntities["Ograve"] = (char)210;
_htmlCharacterEntities["ograve"] = (char)242;
_htmlCharacterEntities["oline"] = (char)8254;
_htmlCharacterEntities["Omega"] = (char)937;
_htmlCharacterEntities["omega"] = (char)969;
_htmlCharacterEntities["Omicron"] = (char)927;
_htmlCharacterEntities["omicron"] = (char)959;
_htmlCharacterEntities["oplus"] = (char)8853;
_htmlCharacterEntities["or"] = (char)8744;
_htmlCharacterEntities["ordf"] = (char)170;
_htmlCharacterEntities["ordm"] = (char)186;
_htmlCharacterEntities["Oslash"] = (char)216;
_htmlCharacterEntities["oslash"] = (char)248;
_htmlCharacterEntities["Otilde"] = (char)213;
_htmlCharacterEntities["otilde"] = (char)245;
_htmlCharacterEntities["otimes"] = (char)8855;
_htmlCharacterEntities["Ouml"] = (char)214;
_htmlCharacterEntities["ouml"] = (char)246;
_htmlCharacterEntities["para"] = (char)182;
_htmlCharacterEntities["part"] = (char)8706;
_htmlCharacterEntities["permil"] = (char)8240;
_htmlCharacterEntities["perp"] = (char)8869;
_htmlCharacterEntities["Phi"] = (char)934;
_htmlCharacterEntities["phi"] = (char)966;
_htmlCharacterEntities["pi"] = (char)960;
_htmlCharacterEntities["piv"] = (char)982;
_htmlCharacterEntities["plusmn"] = (char)177;
_htmlCharacterEntities["pound"] = (char)163;
_htmlCharacterEntities["prime"] = (char)8242;
_htmlCharacterEntities["Prime"] = (char)8243;
_htmlCharacterEntities["prod"] = (char)8719;
_htmlCharacterEntities["prop"] = (char)8733;
_htmlCharacterEntities["Psi"] = (char)936;
_htmlCharacterEntities["psi"] = (char)968;
_htmlCharacterEntities["quot"] = (char)34;
_htmlCharacterEntities["radic"] = (char)8730;
_htmlCharacterEntities["rang"] = (char)9002;
_htmlCharacterEntities["raquo"] = (char)187;
_htmlCharacterEntities["rarr"] = (char)8594;
_htmlCharacterEntities["rArr"] = (char)8658;
_htmlCharacterEntities["rceil"] = (char)8969;
_htmlCharacterEntities["rdquo"] = (char)8221;
_htmlCharacterEntities["real"] = (char)8476;
_htmlCharacterEntities["reg"] = (char)174;
_htmlCharacterEntities["rfloor"] = (char)8971;
_htmlCharacterEntities["Rho"] = (char)929;
_htmlCharacterEntities["rho"] = (char)961;
_htmlCharacterEntities["rlm"] = (char)8207;
_htmlCharacterEntities["rsaquo"] = (char)8250;
_htmlCharacterEntities["rsquo"] = (char)8217;
_htmlCharacterEntities["sbquo"] = (char)8218;
_htmlCharacterEntities["Scaron"] = (char)352;
_htmlCharacterEntities["scaron"] = (char)353;
_htmlCharacterEntities["sdot"] = (char)8901;
_htmlCharacterEntities["sect"] = (char)167;
_htmlCharacterEntities["shy"] = (char)173;
_htmlCharacterEntities["Sigma"] = (char)931;
_htmlCharacterEntities["sigma"] = (char)963;
_htmlCharacterEntities["sigmaf"] = (char)962;
_htmlCharacterEntities["sim"] = (char)8764;
_htmlCharacterEntities["spades"] = (char)9824;
_htmlCharacterEntities["sub"] = (char)8834;
_htmlCharacterEntities["sube"] = (char)8838;
_htmlCharacterEntities["sum"] = (char)8721;
_htmlCharacterEntities["sup"] = (char)8835;
_htmlCharacterEntities["sup1"] = (char)185;
_htmlCharacterEntities["sup2"] = (char)178;
_htmlCharacterEntities["sup3"] = (char)179;
_htmlCharacterEntities["supe"] = (char)8839;
_htmlCharacterEntities["szlig"] = (char)223;
_htmlCharacterEntities["Tau"] = (char)932;
_htmlCharacterEntities["tau"] = (char)964;
_htmlCharacterEntities["there4"] = (char)8756;
_htmlCharacterEntities["Theta"] = (char)920;
_htmlCharacterEntities["theta"] = (char)952;
_htmlCharacterEntities["thetasym"] = (char)977;
_htmlCharacterEntities["thinsp"] = (char)8201;
_htmlCharacterEntities["THORN"] = (char)222;
_htmlCharacterEntities["thorn"] = (char)254;
_htmlCharacterEntities["tilde"] = (char)732;
_htmlCharacterEntities["times"] = (char)215;
_htmlCharacterEntities["trade"] = (char)8482;
_htmlCharacterEntities["Uacute"] = (char)218;
_htmlCharacterEntities["uacute"] = (char)250;
_htmlCharacterEntities["uarr"] = (char)8593;
_htmlCharacterEntities["uArr"] = (char)8657;
_htmlCharacterEntities["Ucirc"] = (char)219;
_htmlCharacterEntities["ucirc"] = (char)251;
_htmlCharacterEntities["Ugrave"] = (char)217;
_htmlCharacterEntities["ugrave"] = (char)249;
_htmlCharacterEntities["uml"] = (char)168;
_htmlCharacterEntities["upsih"] = (char)978;
_htmlCharacterEntities["Upsilon"] = (char)933;
_htmlCharacterEntities["upsilon"] = (char)965;
_htmlCharacterEntities["Uuml"] = (char)220;
_htmlCharacterEntities["uuml"] = (char)252;
_htmlCharacterEntities["weierp"] = (char)8472;
_htmlCharacterEntities["Xi"] = (char)926;
_htmlCharacterEntities["xi"] = (char)958;
_htmlCharacterEntities["Yacute"] = (char)221;
_htmlCharacterEntities["yacute"] = (char)253;
_htmlCharacterEntities["yen"] = (char)165;
_htmlCharacterEntities["Yuml"] = (char)376;
_htmlCharacterEntities["yuml"] = (char)255;
_htmlCharacterEntities["Zeta"] = (char)918;
_htmlCharacterEntities["zeta"] = (char)950;
_htmlCharacterEntities["zwj"] = (char)8205;
_htmlCharacterEntities["zwnj"] = (char)8204;
}
#endregion Private Methods
// ---------------------------------------------------------------------
//
// Private Fields
//
// ---------------------------------------------------------------------
#region Private Fields
// html element names
// this is an array list now, but we may want to make it a hashtable later for better performance
private static ArrayList _htmlInlineElements;
private static ArrayList _htmlBlockElements;
private static ArrayList _htmlOtherOpenableElements;
// list of html empty element names
private static ArrayList _htmlEmptyElements;
// names of html elements for which closing tags are optional, and close when the outer nested element closes
private static ArrayList _htmlElementsClosingOnParentElementEnd;
// names of elements that close certain optional closing tag elements when they start
// names of elements closing the colgroup element
private static ArrayList _htmlElementsClosingColgroup;
// names of elements closing the dd element
private static ArrayList _htmlElementsClosingDD;
// names of elements closing the dt element
private static ArrayList _htmlElementsClosingDT;
// names of elements closing the li element
private static ArrayList _htmlElementsClosingLI;
// names of elements closing the tbody element
private static ArrayList _htmlElementsClosingTbody;
// names of elements closing the td element
private static ArrayList _htmlElementsClosingTD;
// names of elements closing the tfoot element
private static ArrayList _htmlElementsClosingTfoot;
// names of elements closing the thead element
private static ArrayList _htmlElementsClosingThead;
// names of elements closing the th element
private static ArrayList _htmlElementsClosingTH;
// names of elements closing the tr element
private static ArrayList _htmlElementsClosingTR;
// html character entities hashtable
private static Hashtable _htmlCharacterEntities;
#endregion Private Fields
}
| |
// Copyright (c) Microsoft Corporation. All Rights Reserved.
// Licensed under the MIT License.
using System.Windows;
namespace InteractiveDataDisplay.WPF
{
/// <summary>
/// Describes a width, a height and location of a rectangle.
/// This type is very similar to <see cref="System.Windows.Rect"/>, but has one important difference:
/// while <see cref="System.Windows.Rect"/> describes a rectangle in screen coordinates, where y axis
/// points to bottom (that's why <see cref="System.Windows.Rect"/>'s Bottom property is greater than Top).
/// This type describes rectange in usual coordinates, and y axis point to top.
/// </summary>
public struct DataRect
{
private Range x;
private Range y;
/// <summary>
/// Gets the empty <see cref="DataRect"/>.
/// </summary>
public static readonly DataRect Empty =
new DataRect(Range.Empty, Range.Empty);
/// <summary>
/// Initializes a new instance of the <see cref="DataRect"/> struct.
/// </summary>
/// <param name="minX">Left value of DataRect.</param>
/// <param name="minY">Bottom value of DataRect.</param>
/// <param name="maxX">Right value of DataRect.</param>
/// <param name="maxY">Top value of DataRect.</param>
public DataRect(double minX, double minY, double maxX, double maxY)
: this()
{
X = new Range(minX, maxX);
Y = new Range(minY, maxY);
}
/// <summary>
/// Initializes a new instance of the <see cref="DataRect"/> struct.
/// </summary>
/// <param name="horizontal">Horizontal range</param>
/// <param name="vertical">Vertical range</param>
public DataRect(Range horizontal, Range vertical)
: this()
{
X = horizontal; Y = vertical;
}
/// <summary>
/// Gets of Sets horizontal range
/// </summary>
public Range X
{
get { return x; }
set { x = value; }
}
/// <summary>
/// Gets or sets vertical range
/// </summary>
public Range Y
{
get { return y; }
set { y = value; }
}
/// <summary>
/// Gets the width of <see cref="DataRect"/>.
/// </summary>
public double Width
{
get
{
return X.Max - X.Min;
}
}
/// <summary>
/// Gets the height of <see cref="DataRect"/>.
/// </summary>
public double Height
{
get
{
return Y.Max - Y.Min;
}
}
/// <summary>
/// Gets the left.
/// </summary>
/// <value>The left.</value>
public double XMin
{
get
{
return X.Min;
}
}
/// <summary>
/// Gets the right.
/// </summary>
/// <value>The right.</value>
public double XMax
{
get
{
return X.Max;
}
}
/// <summary>
/// Gets the bottom.
/// </summary>
/// <value>The bottom.</value>
public double YMin
{
get
{
return Y.Min;
}
}
/// <summary>
/// Gets the top.
/// </summary>
/// <value>The top.</value>
public double YMax
{
get
{
return Y.Max;
}
}
/// <summary>
/// Gets a center point of a rectangle.
/// </summary>
public Point Center
{
get
{
return new Point((X.Max + X.Min) / 2.0, (Y.Max + Y.Min) / 2.0);
}
}
/// <summary>
/// Gets a value indicating whether this instance is empty.
/// </summary>
/// <value><c>true</c> if this instance is empty; otherwise, <c>false</c>.</value>
public bool IsEmpty
{
get
{
return X.IsEmpty || Y.IsEmpty;
}
}
/// <summary>
/// Updates current instance of <see cref="DataRect"/> with minimal DataRect
/// which vertical range will contain current vertical range and x value and
/// horizontal range will contain current horizontal range and y value
/// </summary>
/// <param name="x">Value, which will be used for surrond of horizontal range</param>
/// <param name="y">Value, which will be used for surrond of vertical range</param>
public void Surround(double x, double y)
{
this.x.Surround(x);
this.y.Surround(y);
}
/// <summary>
/// Updates current instance of <see cref="DataRect"/> with minimal DataRect which will contain current DataRect and specified DataRect
/// </summary>
/// <param name="rect">DataRect, which will be used for surrond of current instance of <see cref="DataRect"/></param>
public void Surround(DataRect rect)
{
this.x.Surround(rect.X);
this.y.Surround(rect.Y);
}
/// <summary>
/// Updates horizontal range of current instance of <see cref="DataRect"/> with minimal range which will contain both horizontal range of current DataRect and specified value
/// </summary>
/// <param name="x">Value, which will be used for surrond of horizontal range of current instance of <see cref="DataRect"/></param>
public void XSurround(double x)
{
this.x.Surround(x);
}
/// <summary>
/// Updates horizontal range of current instance of <see cref="DataRect"/> with minimal range which will contain both horizontal range of current DataRect and specified range
/// </summary>
/// <param name="x">Range, which will be used for surrond of horizontal range of current instance of <see cref="DataRect"/></param>
public void XSurround(Range x)
{
this.x.Surround(x);
}
/// <summary>
/// Updates vertical range of current instance of <see cref="DataRect"/> with minimal range which will contain both vertical range of current DataRect and specified value
/// </summary>
/// <param name="y">Value, which will be used for surrond of vertical range of current instance of <see cref="DataRect"/></param>
public void YSurround(double y)
{
this.y.Surround(y);
}
/// <summary>
/// Updates vertical range of current instance of <see cref="DataRect"/> with minimal range which will contain both vertical range of current DataRect and specified range
/// </summary>
/// <param name="y">Range, which will be used for surrond of vertical range of current instance of <see cref="DataRect"/></param>
public void YSurround(Range y)
{
this.y.Surround(y);
}
/// <summary>
/// Returns a string that represents the current instance of <see cref="DataRect"/>.
/// </summary>
/// <returns>String that represents the current instance of <see cref="DataRect"/></returns>
public override string ToString()
{
return "{" + X.ToString() + " " + Y.ToString() + "}";
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using RealtimeFramework.Messaging.Exceptions;
namespace RealtimeFramework.Messaging.Ext {
internal class MsgProcessor {
private Client client;
internal MsgProcessor(Client context) {
this.client = context;
}
/// <summary>
/// Processes the operation validated.
/// </summary>
/// <param name="arguments">The arguments.</param>
internal void ProcessOperationValidated(string arguments) {
if (!String.IsNullOrEmpty(arguments)) {
bool isValid = false;
// Try to match with authentication
Match validatedAuthMatch = Regex.Match(arguments, Constants.VALIDATED_PATTERN);
if (validatedAuthMatch.Success) {
isValid = true;
string userPermissions = String.Empty;
if (validatedAuthMatch.Groups["up"].Length > 0) {
userPermissions = validatedAuthMatch.Groups["up"].Value;
}
if (validatedAuthMatch.Groups["set"].Length > 0) {
//_sessionExpirationTime = int.Parse(validatedAuthMatch.Groups["set"].Value);
}
/*
if (String.IsNullOrEmpty(ReadLocalStorage(_applicationKey, _sessionExpirationTime))) {
CreateLocalStorage(_applicationKey);
}*/
if (!String.IsNullOrEmpty(userPermissions) && userPermissions != "null") {
MatchCollection matchCollection = Regex.Matches(userPermissions, Constants.PERMISSIONS_PATTERN);
var permissions = new List<KeyValuePair<string, string>>();
foreach (Match match in matchCollection) {
string channel = match.Groups["key"].Value;
string hash = match.Groups["value"].Value;
permissions.Add(new KeyValuePair<string, string>(channel, hash));
}
client._permissions = new List<KeyValuePair<string, string>>(permissions);
}
}
if (isValid) {
client._isConnecting = false;
client.context.IsConnected = true;
if (client.context.HeartbeatActive) {
client.startHeartbeat();
//_heartbeatTimer.Interval = HeartbeatTime * 1000;
//_heartbeatTimer.Start();
}
if (client._alreadyConnectedFirstTime) {
List<String> channelsToRemove = new List<String>();
// Subscribe to the previously subscribed channels
foreach (KeyValuePair<string, ChannelSubscription> item in client._subscribedChannels) {
string channel = item.Key;
ChannelSubscription channelSubscription = item.Value;
// Subscribe again
if (channelSubscription.SubscribeOnReconnected && (channelSubscription.IsSubscribing || channelSubscription.IsSubscribed)) {
channelSubscription.IsSubscribing = true;
channelSubscription.IsSubscribed = false;
var domainChannelCharacterIndex = channel.IndexOf(':');
var channelToValidate = channel;
if (domainChannelCharacterIndex > 0) {
channelToValidate = channel.Substring(0, domainChannelCharacterIndex + 1) + "*";
}
string hash = client._permissions.Where(c => c.Key == channel || c.Key == channelToValidate).FirstOrDefault().Value;
string s = String.Format("subscribe;{0};{1};{2};{3}", client.context._applicationKey, client.context._authenticationToken, channel, hash);
client.DoSend(s);
} else {
channelsToRemove.Add(channel);
}
}
for (int i = 0; i < channelsToRemove.Count; i++) {
ChannelSubscription removeResult = null;
client._subscribedChannels.TryRemove(channelsToRemove[i], out removeResult);
}
// Clean messages buffer (can have lost message parts in memory)
client._multiPartMessagesBuffer.Clear();
client.context.DelegateReconnectedCallback();
} else {
client._alreadyConnectedFirstTime = true;
// Clear subscribed channels
client._subscribedChannels.Clear();
client.context.DelegateConnectedCallback();
}
if (arguments.IndexOf("busy") < 0)
{
client._reconnectTimer.Stop();
}
client._callDisconnectedCallback = true;
}
}
}
/// <summary>
/// Processes the operation subscribed.
/// </summary>
/// <param name="arguments">The arguments.</param>
internal void ProcessOperationSubscribed(string arguments) {
if (!String.IsNullOrEmpty(arguments)) {
Match subscribedMatch = Regex.Match(arguments, Constants.CHANNEL_PATTERN);
if (subscribedMatch.Success) {
string channelSubscribed = String.Empty;
if (subscribedMatch.Groups["channel"].Length > 0) {
channelSubscribed = subscribedMatch.Groups["channel"].Value;
}
if (!String.IsNullOrEmpty(channelSubscribed)) {
ChannelSubscription channelSubscription = null;
client._subscribedChannels.TryGetValue(channelSubscribed, out channelSubscription);
if (channelSubscription != null) {
channelSubscription.IsSubscribing = false;
channelSubscription.IsSubscribed = true;
}
client.context.DelegateSubscribedCallback(channelSubscribed);
}
}
}
}
/// <summary>
/// Processes the operation unsubscribed.
/// </summary>
/// <param name="arguments">The arguments.</param>
internal void ProcessOperationUnsubscribed(string arguments) {
if (!String.IsNullOrEmpty(arguments)) {
Match unsubscribedMatch = Regex.Match(arguments, Constants.CHANNEL_PATTERN);
if (unsubscribedMatch.Success) {
string channelUnsubscribed = String.Empty;
if (unsubscribedMatch.Groups["channel"].Length > 0) {
channelUnsubscribed = unsubscribedMatch.Groups["channel"].Value;
}
if (!String.IsNullOrEmpty(channelUnsubscribed)) {
ChannelSubscription channelSubscription = null;
client._subscribedChannels.TryGetValue(channelUnsubscribed, out channelSubscription);
if (channelSubscription != null) {
channelSubscription.IsSubscribed = false;
}
client.context.DelegateUnsubscribedCallback(channelUnsubscribed);
}
}
}
}
/// <summary>
/// Processes the operation error.
/// </summary>
/// <param name="arguments">The arguments.</param>
internal void ProcessOperationError(string arguments) {
if (!String.IsNullOrEmpty(arguments)) {
Match errorMatch = Regex.Match(arguments, Constants.EXCEPTION_PATTERN);
if (errorMatch.Success) {
string op = String.Empty;
string error = String.Empty;
string channel = String.Empty;
if (errorMatch.Groups["op"].Length > 0) {
op = errorMatch.Groups["op"].Value;
}
if (errorMatch.Groups["error"].Length > 0) {
error = errorMatch.Groups["error"].Value;
}
if (errorMatch.Groups["channel"].Length > 0) {
channel = errorMatch.Groups["channel"].Value;
}
if (!String.IsNullOrEmpty(error)) {
client.context.DelegateExceptionCallback(new OrtcGenericException(error));
}
if (!String.IsNullOrEmpty(op)) {
switch (op) {
case "validate":
if (!String.IsNullOrEmpty(error) && (error.Contains("Unable to connect") || error.Contains("Server is too busy"))) {
client.context.IsConnected = false;
client.DoReconnect();
} else {
client.DoStopReconnecting();
}
break;
case "subscribe":
if (!String.IsNullOrEmpty(channel)) {
ChannelSubscription channelSubscription = null;
client._subscribedChannels.TryGetValue(channel, out channelSubscription);
if (channelSubscription != null) {
channelSubscription.IsSubscribing = false;
}
}
break;
case "subscribe_maxsize":
case "unsubscribe_maxsize":
case "send_maxsize":
if (!String.IsNullOrEmpty(channel)) {
ChannelSubscription channelSubscription = null;
client._subscribedChannels.TryGetValue(channel, out channelSubscription);
if (channelSubscription != null) {
channelSubscription.IsSubscribing = false;
}
}
client.DoStopReconnecting();
client.DoDisconnect();
break;
default:
break;
}
}
}
}
}
/// <summary>
/// Processes the operation received.
/// </summary>
/// <param name="message">The message.</param>
//private void OldProcessOperationReceived(string message)
//{
// Match receivedMatch = Regex.Match(message, RECEIVED_PATTERN);
// // Received
// if (receivedMatch.Success)
// {
// string channelReceived = String.Empty;
// string messageReceived = String.Empty;
// if (receivedMatch.Groups["channel"].Length > 0)
// {
// channelReceived = receivedMatch.Groups["channel"].Value;
// }
// if (receivedMatch.Groups["message"].Length > 0)
// {
// messageReceived = receivedMatch.Groups["message"].Value;
// }
// if (!String.IsNullOrEmpty(channelReceived) && !String.IsNullOrEmpty(messageReceived) && _subscribedChannels.ContainsKey(channelReceived))
// {
// messageReceived = messageReceived.Replace(@"\\n", Environment.NewLine).Replace("\\\\\"", @"""").Replace("\\\\\\\\", @"\");
// // Multi part
// Match multiPartMatch = Regex.Match(messageReceived, MULTI_PART_MESSAGE_PATTERN);
// string messageId = String.Empty;
// int messageCurrentPart = 1;
// int messageTotalPart = 1;
// bool lastPart = false;
// List<BufferedMessage> messageParts = null;
// if (multiPartMatch.Success)
// {
// if (multiPartMatch.Groups["messageId"].Length > 0)
// {
// messageId = multiPartMatch.Groups["messageId"].Value;
// }
// if (multiPartMatch.Groups["messageCurrentPart"].Length > 0)
// {
// messageCurrentPart = Int32.Parse(multiPartMatch.Groups["messageCurrentPart"].Value);
// }
// if (multiPartMatch.Groups["messageTotalPart"].Length > 0)
// {
// messageTotalPart = Int32.Parse(multiPartMatch.Groups["messageTotalPart"].Value);
// }
// if (multiPartMatch.Groups["message"].Length > 0)
// {
// messageReceived = multiPartMatch.Groups["message"].Value;
// }
// }
// // Is a message part
// if (!String.IsNullOrEmpty(messageId))
// {
// if (!_multiPartMessagesBuffer.ContainsKey(messageId))
// {
// _multiPartMessagesBuffer.TryAdd(messageId, new List<BufferedMessage>());
// }
// _multiPartMessagesBuffer.TryGetValue(messageId, out messageParts);
// if (messageParts != null)
// {
// messageParts.Add(new BufferedMessage(messageCurrentPart, messageReceived));
// // Last message part
// if (messageParts.Count == messageTotalPart)
// {
// messageParts.Sort();
// lastPart = true;
// }
// }
// }
// // Message does not have multipart, like the messages received at announcement channels
// else
// {
// lastPart = true;
// }
// if (lastPart)
// {
// if (_subscribedChannels.ContainsKey(channelReceived))
// {
// ChannelSubscription channelSubscription = null;
// _subscribedChannels.TryGetValue(channelReceived, out channelSubscription);
// if (channelSubscription != null)
// {
// var ev = channelSubscription.OnMessage;
// if (ev != null)
// {
// if (!String.IsNullOrEmpty(messageId) && _multiPartMessagesBuffer.ContainsKey(messageId))
// {
// messageReceived = String.Empty;
// lock (messageParts)
// {
// foreach (BufferedMessage part in messageParts)
// {
// if (part != null)
// {
// messageReceived = String.Format("{0}{1}", messageReceived, part.Message);
// }
// }
// }
// // Remove from messages buffer
// List<BufferedMessage> removeResult = null;
// _multiPartMessagesBuffer.TryRemove(messageId, out removeResult);
// }
// if (!String.IsNullOrEmpty(messageReceived))
// {
// if (_synchContext != null)
// {
// _synchContext.Post(obj => ev(obj, channelReceived, messageReceived), this);
// }
// else
// {
// ev(this, channelReceived, messageReceived);
// }
// }
// }
// }
// }
// }
// }
// }
// else
// {
// // Unknown
// DelegateExceptionCallback(new OrtcGenericException(String.Format("Unknown message received: {0}", message)));
// //DoDisconnect();
// }
//}
internal void ProcessOperationReceived(string message) {
Match receivedMatch = Regex.Match(message, Constants.RECEIVED_PATTERN);
// Received
if (receivedMatch.Success) {
string channelReceived = String.Empty;
string messageReceived = String.Empty;
if (receivedMatch.Groups["channel"].Length > 0) {
channelReceived = receivedMatch.Groups["channel"].Value;
}
if (receivedMatch.Groups["message"].Length > 0) {
messageReceived = receivedMatch.Groups["message"].Value;
}
if (!String.IsNullOrEmpty(channelReceived) && !String.IsNullOrEmpty(messageReceived) && client._subscribedChannels.ContainsKey(channelReceived)) {
messageReceived = messageReceived.Replace(@"\\n", Environment.NewLine).Replace("\\\\\"", @"""").Replace("\\\\\\\\", @"\");
// Multi part
Match multiPartMatch = Regex.Match(messageReceived, Constants.MULTI_PART_MESSAGE_PATTERN);
string messageId = String.Empty;
int messageCurrentPart = 1;
int messageTotalPart = 1;
bool lastPart = false;
RealtimeDictionary<int, BufferedMessage> messageParts = null;
if (multiPartMatch.Success) {
if (multiPartMatch.Groups["messageId"].Length > 0) {
messageId = multiPartMatch.Groups["messageId"].Value;
}
if (multiPartMatch.Groups["messageCurrentPart"].Length > 0) {
messageCurrentPart = Int32.Parse(multiPartMatch.Groups["messageCurrentPart"].Value);
}
if (multiPartMatch.Groups["messageTotalPart"].Length > 0) {
messageTotalPart = Int32.Parse(multiPartMatch.Groups["messageTotalPart"].Value);
}
if (multiPartMatch.Groups["message"].Length > 0) {
messageReceived = multiPartMatch.Groups["message"].Value;
}
}
lock (client._multiPartMessagesBuffer) {
// Is a message part
if (!String.IsNullOrEmpty(messageId)) {
if (!client._multiPartMessagesBuffer.ContainsKey(messageId)) {
client._multiPartMessagesBuffer.Add(messageId, new RealtimeDictionary<int, BufferedMessage>());
}
client._multiPartMessagesBuffer.TryGetValue(messageId, out messageParts);
if (messageParts != null) {
lock (messageParts) {
messageParts.Add(messageCurrentPart, new BufferedMessage(messageCurrentPart, messageReceived));
// Last message part
if (messageParts.Count == messageTotalPart) {
//messageParts.Sort();
lastPart = true;
}
}
}
}
// Message does not have multipart, like the messages received at announcement channels
else {
lastPart = true;
}
if (lastPart) {
if (client._subscribedChannels.ContainsKey(channelReceived)) {
ChannelSubscription channelSubscription = null;
client._subscribedChannels.TryGetValue(channelReceived, out channelSubscription);
if (channelSubscription != null) {
var ev = channelSubscription.OnMessage;
if (ev != null) {
if (!String.IsNullOrEmpty(messageId) && client._multiPartMessagesBuffer.ContainsKey(messageId)) {
messageReceived = String.Empty;
//lock (messageParts)
//{
var bufferedMultiPartMessages = new List<BufferedMessage>();
foreach (var part in messageParts.Keys) {
bufferedMultiPartMessages.Add(messageParts[part]);
}
bufferedMultiPartMessages.Sort();
foreach (var part in bufferedMultiPartMessages) {
if (part != null) {
messageReceived = String.Format("{0}{1}", messageReceived, part.Message);
}
}
//}
// Remove from messages buffer
RealtimeDictionary<int, BufferedMessage> removeResult = null;
client._multiPartMessagesBuffer.TryRemove(messageId, out removeResult);
}
if (!String.IsNullOrEmpty(messageReceived)) {
if (client.context._synchContext != null) {
client.context._synchContext.Post(obj => ev(obj, channelReceived, messageReceived), this);
} else {
ev(this, channelReceived, messageReceived);
}
}
}
}
}
}
}
}
} else {
// Unknown
client.context.DelegateExceptionCallback(new OrtcGenericException(String.Format("Unknown message received: {0}", message)));
//DoDisconnect();
}
}
}
}
| |
/*
* SerializationInfo.cs - Implementation of the
* "System.Runtime.Serialization.SerializationInfo" class.
*
* Copyright (C) 2001, 2002 Southern Storm Software, Pty Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
namespace System.Runtime.Serialization
{
#if CONFIG_SERIALIZATION
using System.Collections;
public sealed class SerializationInfo
{
// Internal state.
private IFormatterConverter converter;
private String assemblyName;
private String fullTypeName;
internal ArrayList names;
internal ArrayList values;
internal ArrayList types;
internal int generation;
// Constructor.
[CLSCompliant(false)]
public SerializationInfo(Type type, IFormatterConverter converter)
{
if(type == null)
{
throw new ArgumentNullException("type");
}
if(converter == null)
{
throw new ArgumentNullException("converter");
}
this.converter = converter;
this.assemblyName = type.Assembly.FullName;
this.fullTypeName = type.FullName;
this.names = new ArrayList();
this.values = new ArrayList();
this.types = new ArrayList();
this.generation = 0;
}
// Get or set the assembly name to serialize.
public String AssemblyName
{
get
{
return assemblyName;
}
set
{
if(value == null)
{
throw new ArgumentNullException("value");
}
assemblyName = value;
}
}
// Get or set the full name of the type to serialize.
public String FullTypeName
{
get
{
return fullTypeName;
}
set
{
if(value == null)
{
throw new ArgumentNullException("value");
}
fullTypeName = value;
}
}
// Get the number of members that have been added to this object.
public int MemberCount
{
get
{
return values.Count;
}
}
// Add values to this serialization information object.
public void AddValue(String name, bool value)
{
AddValue(name, (Object)value, typeof(Boolean));
}
public void AddValue(String name, byte value)
{
AddValue(name, (Object)value, typeof(Byte));
}
[CLSCompliant(false)]
public void AddValue(String name, sbyte value)
{
AddValue(name, (Object)value, typeof(SByte));
}
public void AddValue(String name, short value)
{
AddValue(name, (Object)value, typeof(Int16));
}
[CLSCompliant(false)]
public void AddValue(String name, ushort value)
{
AddValue(name, (Object)value, typeof(UInt16));
}
public void AddValue(String name, char value)
{
AddValue(name, (Object)value, typeof(Char));
}
public void AddValue(String name, int value)
{
AddValue(name, (Object)value, typeof(Int32));
}
[CLSCompliant(false)]
public void AddValue(String name, uint value)
{
AddValue(name, (Object)value, typeof(UInt32));
}
public void AddValue(String name, long value)
{
AddValue(name, (Object)value, typeof(Int64));
}
[CLSCompliant(false)]
public void AddValue(String name, ulong value)
{
AddValue(name, (Object)value, typeof(UInt64));
}
public void AddValue(String name, float value)
{
AddValue(name, (Object)value, typeof(Single));
}
public void AddValue(String name, double value)
{
AddValue(name, (Object)value, typeof(Double));
}
public void AddValue(String name, DateTime value)
{
AddValue(name, (Object)value, typeof(DateTime));
}
public void AddValue(String name, Decimal value)
{
AddValue(name, (Object)value, typeof(Decimal));
}
internal void AddValue(String name, String value)
{
AddValue(name, (Object)value, typeof(String));
}
public void AddValue(String name, Object value)
{
AddValue(name, (Object)value, value.GetType());
}
public void AddValue(String name, Object value, Type type)
{
if(name == null)
{
throw new ArgumentNullException("name");
}
if(type == null)
{
throw new ArgumentNullException("type");
}
if(value != null && !type.IsAssignableFrom(value.GetType()))
{
throw new SerializationException
(_("Serialize_BadType"));
}
if(names.IndexOf(name) != -1)
{
throw new SerializationException
(_("Serialize_AlreadyPresent"));
}
++generation;
names.Add(name);
values.Add(value);
types.Add(type);
}
// Get a value from this serialization information object.
public bool GetBoolean(String name)
{
return (bool)GetValue(name, typeof(Boolean));
}
public byte GetByte(String name)
{
return (byte)GetValue(name, typeof(Byte));
}
[CLSCompliant(false)]
public sbyte GetSByte(String name)
{
return (sbyte)GetValue(name, typeof(SByte));
}
public short GetInt16(String name)
{
return (short)GetValue(name, typeof(Int16));
}
[CLSCompliant(false)]
public ushort GetUInt16(String name)
{
return (ushort)GetValue(name, typeof(UInt16));
}
public char GetChar(String name)
{
return (char)GetValue(name, typeof(Char));
}
public int GetInt32(String name)
{
return (int)GetValue(name, typeof(Int32));
}
[CLSCompliant(false)]
public uint GetUInt32(String name)
{
return (uint)GetValue(name, typeof(UInt32));
}
public long GetInt64(String name)
{
return (long)GetValue(name, typeof(Int64));
}
[CLSCompliant(false)]
public ulong GetUInt64(String name)
{
return (ulong)GetValue(name, typeof(UInt64));
}
public float GetSingle(String name)
{
return (float)GetValue(name, typeof(Single));
}
public double GetDouble(String name)
{
return (double)GetValue(name, typeof(Double));
}
public DateTime GetDateTime(String name)
{
return (DateTime)GetValue(name, typeof(DateTime));
}
public Decimal GetDecimal(String name)
{
return (Decimal)GetValue(name, typeof(Decimal));
}
public String GetString(String name)
{
return (String)GetValue(name, typeof(String));
}
public Object GetValue(String name, Type type)
{
int index;
Object value;
if(name == null)
{
throw new ArgumentNullException("name");
}
if(type == null)
{
throw new ArgumentNullException("type");
}
index = names.IndexOf(name);
if(index != -1)
{
value = values[index];
if(value != null)
{
if(type.IsAssignableFrom((Type)(types[index])))
{
return value;
}
else
{
return converter.Convert(value, type);
}
}
}
return null;
}
// Get values from this info object, while ignoring case
// during name matches.
internal String GetStringIgnoreCase(String name)
{
return (String)GetValueIgnoreCase(name, typeof(String));
}
internal Object GetValueIgnoreCase(String name, Type type)
{
int index;
Object value;
if(name == null)
{
throw new ArgumentNullException("name");
}
if(type == null)
{
throw new ArgumentNullException("type");
}
for(index = 0; index < names.Count; ++index)
{
if(String.Compare((String)(names[index]), name, true) == 0)
{
value = values[index];
if(value != null)
{
if(type.IsAssignableFrom((Type)(types[index])))
{
return value;
}
else
{
return converter.Convert(value, type);
}
}
}
}
return null;
}
// Get an enumerator for iterating over this information object.
public SerializationInfoEnumerator GetEnumerator()
{
return new SerializationInfoEnumerator(this);
}
// Set the serialization type associated with this object.
public void SetType(Type type)
{
if(type == null)
{
throw new ArgumentNullException("type");
}
assemblyName = type.Assembly.FullName;
fullTypeName = type.FullName;
}
}; // class SerializationInfo
#endif // CONFIG_SERIALIZATION
}; // namespace System.Runtime.Serialization
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.Utilities;
namespace Microsoft.CodeAnalysis.ImplementInterface
{
internal abstract partial class AbstractImplementInterfaceService
{
internal partial class ImplementInterfaceCodeAction
{
private ISymbol GenerateProperty(
Compilation compilation,
IPropertySymbol property,
Accessibility accessibility,
DeclarationModifiers modifiers,
bool generateAbstractly,
bool useExplicitInterfaceSymbol,
string memberName,
CancellationToken cancellationToken)
{
var factory = this.Document.GetLanguageService<SyntaxGenerator>();
var attributesToRemove = AttributesToRemove(compilation);
var getAccessor = GenerateGetAccessor(compilation, property, accessibility, generateAbstractly,
useExplicitInterfaceSymbol, attributesToRemove, cancellationToken);
var setAccessor = GenerateSetAccessor(compilation, property, accessibility,
generateAbstractly, useExplicitInterfaceSymbol, attributesToRemove, cancellationToken);
var syntaxFacts = Document.GetLanguageService<ISyntaxFactsService>();
var parameterNames = NameGenerator.EnsureUniqueness(
property.Parameters.Select(p => p.Name).ToList(), isCaseSensitive: syntaxFacts.IsCaseSensitive);
var updatedProperty = property.RenameParameters(parameterNames);
updatedProperty = updatedProperty.RemoveAttributeFromParameters(attributesToRemove);
// TODO(cyrusn): Delegate through throughMember if it's non-null.
return CodeGenerationSymbolFactory.CreatePropertySymbol(
updatedProperty,
accessibility: accessibility,
modifiers: modifiers,
explicitInterfaceSymbol: useExplicitInterfaceSymbol ? property : null,
name: memberName,
getMethod: getAccessor,
setMethod: setAccessor);
}
/// <summary>
/// Lists compiler attributes that we want to remove.
/// The TupleElementNames attribute is compiler generated (it is used for naming tuple element names).
/// We never want to place it in source code.
/// Same thing for the Dynamic attribute.
/// </summary>
private INamedTypeSymbol[] AttributesToRemove(Compilation compilation)
{
return new[] { compilation.ComAliasNameAttributeType(), compilation.TupleElementNamesAttributeType(),
compilation.DynamicAttributeType() };
}
private IMethodSymbol GenerateSetAccessor(
Compilation compilation,
IPropertySymbol property,
Accessibility accessibility,
bool generateAbstractly,
bool useExplicitInterfaceSymbol,
INamedTypeSymbol[] attributesToRemove,
CancellationToken cancellationToken)
{
if (property.SetMethod == null)
{
return null;
}
var setMethod = property.SetMethod.RemoveInaccessibleAttributesAndAttributesOfTypes(
this.State.ClassOrStructType,
attributesToRemove);
return CodeGenerationSymbolFactory.CreateAccessorSymbol(
setMethod,
attributes: null,
accessibility: accessibility,
explicitInterfaceSymbol: useExplicitInterfaceSymbol ? property.SetMethod : null,
statements: GetSetAccessorStatements(compilation, property, generateAbstractly, cancellationToken));
}
private IMethodSymbol GenerateGetAccessor(
Compilation compilation,
IPropertySymbol property,
Accessibility accessibility,
bool generateAbstractly,
bool useExplicitInterfaceSymbol,
INamedTypeSymbol[] attributesToRemove,
CancellationToken cancellationToken)
{
if (property.GetMethod == null)
{
return null;
}
var getMethod = property.GetMethod.RemoveInaccessibleAttributesAndAttributesOfTypes(
this.State.ClassOrStructType,
attributesToRemove);
return CodeGenerationSymbolFactory.CreateAccessorSymbol(
getMethod,
attributes: null,
accessibility: accessibility,
explicitInterfaceSymbol: useExplicitInterfaceSymbol ? property.GetMethod : null,
statements: GetGetAccessorStatements(compilation, property, generateAbstractly, cancellationToken));
}
private IList<SyntaxNode> GetSetAccessorStatements(
Compilation compilation,
IPropertySymbol property,
bool generateAbstractly,
CancellationToken cancellationToken)
{
if (generateAbstractly)
{
return null;
}
var factory = this.Document.GetLanguageService<SyntaxGenerator>();
if (ThroughMember != null)
{
var throughExpression = CreateThroughExpression(factory);
SyntaxNode expression;
if (property.IsIndexer)
{
expression = throughExpression;
}
else
{
expression = factory.MemberAccessExpression(
throughExpression, factory.IdentifierName(property.Name));
}
if (property.Parameters.Length > 0)
{
var arguments = factory.CreateArguments(property.Parameters.As<IParameterSymbol>());
expression = factory.ElementAccessExpression(expression, arguments);
}
expression = factory.AssignmentStatement(expression, factory.IdentifierName("value"));
return new[] { factory.ExpressionStatement(expression) };
}
return factory.CreateThrowNotImplementedStatementBlock(compilation);
}
private IList<SyntaxNode> GetGetAccessorStatements(
Compilation compilation,
IPropertySymbol property,
bool generateAbstractly,
CancellationToken cancellationToken)
{
if (generateAbstractly)
{
return null;
}
var factory = this.Document.GetLanguageService<SyntaxGenerator>();
if (ThroughMember != null)
{
var throughExpression = CreateThroughExpression(factory);
SyntaxNode expression;
if (property.IsIndexer)
{
expression = throughExpression;
}
else
{
expression = factory.MemberAccessExpression(
throughExpression, factory.IdentifierName(property.Name));
}
if (property.Parameters.Length > 0)
{
var arguments = factory.CreateArguments(property.Parameters.As<IParameterSymbol>());
expression = factory.ElementAccessExpression(expression, arguments);
}
return new[] { factory.ReturnStatement(expression) };
}
return factory.CreateThrowNotImplementedStatementBlock(compilation);
}
}
}
}
| |
using System;
using System.Diagnostics.CodeAnalysis;
namespace NQuery.Compilation
{
internal abstract class StandardVisitor
{
protected StandardVisitor()
{
}
#region Dispatcher
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
[SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling")]
public virtual AstNode Visit(AstNode node)
{
switch (node.NodeType)
{
case AstNodeType.Literal:
return VisitLiteralValue((LiteralExpression)node);
case AstNodeType.UnaryExpression:
return VisitUnaryExpression((UnaryExpression)node);
case AstNodeType.BinaryExpression:
return VisitBinaryExpression((BinaryExpression)node);
case AstNodeType.BetweenExpression:
return VisitBetweenExpression((BetweenExpression)node);
case AstNodeType.IsNullExpression:
return VisitIsNullExpression((IsNullExpression)node);
case AstNodeType.CastExpression:
return VisitCastExpression((CastExpression)node);
case AstNodeType.CaseExpression:
return VisitCaseExpression((CaseExpression)node);
case AstNodeType.CoalesceExpression:
return VisitCoalesceExpression((CoalesceExpression)node);
case AstNodeType.NullIfExpression:
return VisitNullIfExpression((NullIfExpression)node);
case AstNodeType.InExpression:
return VisitInExpression((InExpression)node);
case AstNodeType.NamedConstantExpression:
return VisitNamedConstantExpression((NamedConstantExpression)node);
case AstNodeType.ParameterExpression:
return VisitParameterExpression((ParameterExpression)node);
case AstNodeType.NameExpression:
return VisitNameExpression((NameExpression)node);
case AstNodeType.PropertyAccessExpression:
return VisitPropertyAccessExpression((PropertyAccessExpression)node);
case AstNodeType.FunctionInvocationExpression:
return VisitFunctionInvocationExpression((FunctionInvocationExpression)node);
case AstNodeType.MethodInvocationExpression:
return VisitMethodInvocationExpression((MethodInvocationExpression)node);
case AstNodeType.ColumnExpression:
return VisitColumnExpression((ColumnExpression)node);
case AstNodeType.RowBufferEntryExpression:
return VisitRowBufferEntryExpression((RowBufferEntryExpression)node);
case AstNodeType.AggregateExpression:
return VisitAggregagateExpression((AggregateExpression)node);
case AstNodeType.SingleRowSubselect:
return VisitSingleRowSubselect((SingleRowSubselect)node);
case AstNodeType.ExistsSubselect:
return VisitExistsSubselect((ExistsSubselect)node);
case AstNodeType.AllAnySubselect:
return VisitAllAnySubselect((AllAnySubselect)node);
case AstNodeType.NamedTableReference:
return VisitNamedTableReference((NamedTableReference)node);
case AstNodeType.JoinedTableReference:
return VisitJoinedTableReference((JoinedTableReference)node);
case AstNodeType.DerivedTableReference:
return VisitDerivedTableReference((DerivedTableReference)node);
case AstNodeType.SelectQuery:
return VisitSelectQuery((SelectQuery)node);
case AstNodeType.BinaryQuery:
return VisitBinaryQuery((BinaryQuery)node);
case AstNodeType.SortedQuery:
return VisitSortedQuery((SortedQuery)node);
case AstNodeType.CommonTableExpressionQuery:
return VisitCommonTableExpressionQuery((CommonTableExpressionQuery)node);
case AstNodeType.TableAlgebraNode:
return VisitTableAlgebraNode((TableAlgebraNode)node);
case AstNodeType.JoinAlgebraNode:
return VisitJoinAlgebraNode((JoinAlgebraNode)node);
case AstNodeType.ConstantScanAlgebraNode:
return VisitConstantScanAlgebraNode((ConstantScanAlgebraNode)node);
case AstNodeType.NullScanAlgebraNode:
return VisitNullScanAlgebraNode((NullScanAlgebraNode)node);
case AstNodeType.ConcatAlgebraNode:
return VisitConcatAlgebraNode((ConcatAlgebraNode)node);
case AstNodeType.SortAlgebraNode:
return VisitSortAlgebraNode((SortAlgebraNode)node);
case AstNodeType.AggregateAlgebraNode:
return VisitAggregateAlgebraNode((AggregateAlgebraNode)node);
case AstNodeType.TopAlgebraNode:
return VisitTopAlgebraNode((TopAlgebraNode)node);
case AstNodeType.FilterAlgebraNode:
return VisitFilterAlgebraNode((FilterAlgebraNode)node);
case AstNodeType.ComputeScalarAlgebraNode:
return VisitComputeScalarAlgebraNode((ComputeScalarAlgebraNode)node);
case AstNodeType.ResultAlgebraNode:
return VisitResultAlgebraNode((ResultAlgebraNode)node);
case AstNodeType.AssertAlgebraNode:
return VisitAssertAlgebraNode((AssertAlgebraNode)node);
case AstNodeType.IndexSpoolAlgebraNode:
return VisitIndexSpoolAlgebraNode((IndexSpoolAlgebraNode)node);
case AstNodeType.StackedTableSpoolAlgebraNode:
return VisitStackedTableSpoolAlgebraNode((StackedTableSpoolAlgebraNode)node);
case AstNodeType.StackedTableSpoolRefAlgebraNode:
return VisitTableSpoolRefAlgebraNode((StackedTableSpoolRefAlgebraNode)node);
case AstNodeType.HashMatchAlgebraNode:
return VisitHashMatchAlgebraNode((HashMatchAlgebraNode)node);
default:
throw ExceptionBuilder.UnhandledCaseLabel(node.NodeType);
}
}
#endregion
#region Expressions
public virtual ExpressionNode VisitExpression(ExpressionNode expression)
{
return (ExpressionNode)Visit(expression);
}
#region Literal Expression
public virtual LiteralExpression VisitLiteralValue(LiteralExpression expression)
{
return expression;
}
#endregion
#region Compound Expressions
public virtual ExpressionNode VisitUnaryExpression(UnaryExpression expression)
{
expression.Operand = VisitExpression(expression.Operand);
return expression;
}
public virtual ExpressionNode VisitBinaryExpression(BinaryExpression expression)
{
expression.Left = VisitExpression(expression.Left);
expression.Right = VisitExpression(expression.Right);
return expression;
}
public virtual ExpressionNode VisitBetweenExpression(BetweenExpression expression)
{
expression.Expression = VisitExpression(expression.Expression);
expression.LowerBound = VisitExpression(expression.LowerBound);
expression.UpperBound = VisitExpression(expression.UpperBound);
return expression;
}
public virtual ExpressionNode VisitIsNullExpression(IsNullExpression expression)
{
expression.Expression = VisitExpression(expression.Expression);
return expression;
}
public virtual ExpressionNode VisitCastExpression(CastExpression expression)
{
expression.Expression = VisitExpression(expression.Expression);
return expression;
}
public virtual ExpressionNode VisitCaseExpression(CaseExpression expression)
{
if (expression.InputExpression != null)
expression.InputExpression = VisitExpression(expression.InputExpression);
for (int i = 0; i < expression.WhenExpressions.Length; i++)
expression.WhenExpressions[i] = VisitExpression(expression.WhenExpressions[i]);
for (int i = 0; i < expression.ThenExpressions.Length; i++)
expression.ThenExpressions[i] = VisitExpression(expression.ThenExpressions[i]);
if (expression.ElseExpression != null)
expression.ElseExpression = VisitExpression(expression.ElseExpression);
return expression;
}
public virtual ExpressionNode VisitCoalesceExpression(CoalesceExpression expression)
{
for (int i = 0; i < expression.Expressions.Length; i++)
expression.Expressions[i] = VisitExpression(expression.Expressions[i]);
return expression;
}
public virtual ExpressionNode VisitNullIfExpression(NullIfExpression expression)
{
expression.LeftExpression = VisitExpression(expression.LeftExpression);
expression.RightExpression = VisitExpression(expression.RightExpression);
return expression;
}
public virtual ExpressionNode VisitInExpression(InExpression expression)
{
for (int i = 0; i < expression.RightExpressions.Length; i++)
expression.RightExpressions[i] = VisitExpression(expression.RightExpressions[i]);
return expression;
}
#endregion
#region Referencing Expression
public virtual ExpressionNode VisitNamedConstantExpression(NamedConstantExpression expression)
{
return expression;
}
public virtual ExpressionNode VisitParameterExpression(ParameterExpression expression)
{
return expression;
}
public virtual ExpressionNode VisitNameExpression(NameExpression expression)
{
return expression;
}
public virtual ExpressionNode VisitPropertyAccessExpression(PropertyAccessExpression expression)
{
expression.Target = VisitExpression(expression.Target);
return expression;
}
public virtual ExpressionNode VisitFunctionInvocationExpression(FunctionInvocationExpression expression)
{
for (int i = 0; i < expression.Arguments.Length; i++)
expression.Arguments[i] = VisitExpression(expression.Arguments[i]);
return expression;
}
public virtual ExpressionNode VisitMethodInvocationExpression(MethodInvocationExpression expression)
{
expression.Target = VisitExpression(expression.Target);
for (int i = 0; i < expression.Arguments.Length; i++)
expression.Arguments[i] = VisitExpression(expression.Arguments[i]);
return expression;
}
#endregion
#region Query Expressions
public virtual ExpressionNode VisitColumnExpression(ColumnExpression expression)
{
return expression;
}
public virtual ExpressionNode VisitRowBufferEntryExpression(RowBufferEntryExpression expression)
{
return expression;
}
public virtual ExpressionNode VisitAggregagateExpression(AggregateExpression expression)
{
expression.Argument = VisitExpression(expression.Argument);
return expression;
}
public virtual ExpressionNode VisitSingleRowSubselect(SingleRowSubselect expression)
{
expression.Query = VisitQuery(expression.Query);
return expression;
}
public virtual ExpressionNode VisitExistsSubselect(ExistsSubselect expression)
{
expression.Query = VisitQuery(expression.Query);
return expression;
}
public virtual ExpressionNode VisitAllAnySubselect(AllAnySubselect expression)
{
expression.Left = VisitExpression(expression.Left);
expression.Query = VisitQuery(expression.Query);
return expression;
}
#endregion
#endregion
#region Query
public virtual TableReference VisitTableReference(TableReference node)
{
return (TableReference)Visit(node);
}
public virtual TableReference VisitNamedTableReference(NamedTableReference node)
{
return node;
}
public virtual TableReference VisitJoinedTableReference(JoinedTableReference node)
{
node.Left = VisitTableReference(node.Left);
node.Right = VisitTableReference(node.Right);
if (node.Condition != null)
node.Condition = VisitExpression(node.Condition);
return node;
}
public virtual TableReference VisitDerivedTableReference(DerivedTableReference node)
{
node.Query = VisitQuery(node.Query);
return node;
}
public virtual QueryNode VisitQuery(QueryNode query)
{
return (QueryNode)Visit(query);
}
public virtual QueryNode VisitSelectQuery(SelectQuery query)
{
// Visit all column expressions
for (int i = 0; i < query.SelectColumns.Length; i++)
{
if (query.SelectColumns[i].Expression != null)
query.SelectColumns[i].Expression = VisitExpression(query.SelectColumns[i].Expression);
}
// Visit FROM table references
if (query.TableReferences != null)
query.TableReferences = VisitTableReference(query.TableReferences);
// Visit WHERE expression
if (query.WhereClause != null)
query.WhereClause = VisitExpression(query.WhereClause);
// Visit GROUP BY clause
if (query.GroupByColumns != null)
{
for (int i = 0; i < query.GroupByColumns.Length; i++)
query.GroupByColumns[i] = VisitExpression(query.GroupByColumns[i]);
}
if (query.HavingClause != null)
query.HavingClause = VisitExpression(query.HavingClause);
// Visit ORDER BY expressions
if (query.OrderByColumns != null)
{
for (int i = 0; i < query.OrderByColumns.Length; i++)
query.OrderByColumns[i].Expression = VisitExpression(query.OrderByColumns[i].Expression);
}
return query;
}
public virtual QueryNode VisitBinaryQuery(BinaryQuery query)
{
query.Left = VisitQuery(query.Left);
query.Right = VisitQuery(query.Right);
return query;
}
public virtual QueryNode VisitSortedQuery(SortedQuery query)
{
// Visit input
query.Input = VisitQuery(query.Input);
// Visit ORDER BY expressions
if (query.OrderByColumns != null)
{
for (int i = 0; i < query.OrderByColumns.Length; i++)
query.OrderByColumns[i].Expression = VisitExpression(query.OrderByColumns[i].Expression);
}
return query;
}
public virtual QueryNode VisitCommonTableExpressionQuery(CommonTableExpressionQuery query)
{
foreach (CommonTableExpression commonTableExpression in query.CommonTableExpressions)
commonTableExpression.QueryDeclaration = VisitQuery(commonTableExpression.QueryDeclaration);
query.Input = VisitQuery(query.Input);
return query;
}
#endregion
#region Algebra Nodes
public virtual AlgebraNode VisitAlgebraNode(AlgebraNode node)
{
return (AlgebraNode)Visit(node);
}
public virtual AlgebraNode VisitTableAlgebraNode(TableAlgebraNode node)
{
return node;
}
public virtual AlgebraNode VisitJoinAlgebraNode(JoinAlgebraNode node)
{
node.Left = VisitAlgebraNode(node.Left);
node.Right = VisitAlgebraNode(node.Right);
if (node.Predicate != null)
node.Predicate = VisitExpression(node.Predicate);
if (node.PassthruPredicate != null)
node.PassthruPredicate = VisitExpression(node.PassthruPredicate);
return node;
}
public virtual AlgebraNode VisitConstantScanAlgebraNode(ConstantScanAlgebraNode node)
{
if (node.DefinedValues != null)
{
foreach (ComputedValueDefinition definedValue in node.DefinedValues)
definedValue.Expression = VisitExpression(definedValue.Expression);
}
return node;
}
public virtual AlgebraNode VisitNullScanAlgebraNode(NullScanAlgebraNode node)
{
return node;
}
public virtual AlgebraNode VisitConcatAlgebraNode(ConcatAlgebraNode node)
{
for (int i = 0; i < node.Inputs.Length; i++)
node.Inputs[i] = VisitAlgebraNode(node.Inputs[i]);
return node;
}
public virtual AlgebraNode VisitSortAlgebraNode(SortAlgebraNode node)
{
node.Input = VisitAlgebraNode(node.Input);
return node;
}
public virtual AlgebraNode VisitAggregateAlgebraNode(AggregateAlgebraNode node)
{
node.Input = VisitAlgebraNode(node.Input);
if (node.DefinedValues != null)
{
foreach (AggregatedValueDefinition definedValue in node.DefinedValues)
definedValue.Argument = VisitExpression(definedValue.Argument);
}
return node;
}
public virtual AlgebraNode VisitTopAlgebraNode(TopAlgebraNode node)
{
node.Input = VisitAlgebraNode(node.Input);
return node;
}
public virtual AlgebraNode VisitFilterAlgebraNode(FilterAlgebraNode node)
{
node.Input = VisitAlgebraNode(node.Input);
node.Predicate = VisitExpression(node.Predicate);
return node;
}
public virtual AlgebraNode VisitComputeScalarAlgebraNode(ComputeScalarAlgebraNode node)
{
node.Input = VisitAlgebraNode(node.Input);
if (node.DefinedValues != null)
{
foreach (ComputedValueDefinition definedValue in node.DefinedValues)
definedValue.Expression = VisitExpression(definedValue.Expression);
}
return node;
}
public virtual AlgebraNode VisitResultAlgebraNode(ResultAlgebraNode node)
{
node.Input = VisitAlgebraNode(node.Input);
return node;
}
public virtual AlgebraNode VisitAssertAlgebraNode(AssertAlgebraNode node)
{
node.Input = VisitAlgebraNode(node.Input);
node.Predicate = VisitExpression(node.Predicate);
return node;
}
public virtual AlgebraNode VisitIndexSpoolAlgebraNode(IndexSpoolAlgebraNode node)
{
node.Input = VisitAlgebraNode(node.Input);
return node;
}
public virtual AstNode VisitStackedTableSpoolAlgebraNode(StackedTableSpoolAlgebraNode node)
{
node.Input = VisitAlgebraNode(node.Input);
return node;
}
public virtual AstNode VisitTableSpoolRefAlgebraNode(StackedTableSpoolRefAlgebraNode node)
{
return node;
}
public virtual AlgebraNode VisitHashMatchAlgebraNode(HashMatchAlgebraNode node)
{
node.Left = VisitAlgebraNode(node.Left);
node.Right = VisitAlgebraNode(node.Right);
if (node.ProbeResidual != null)
node.ProbeResidual = VisitExpression(node.ProbeResidual);
return node;
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using ActiproSoftware.SyntaxEditor;
using NQuery.Runtime;
namespace NQuery.UI
{
internal sealed class MemberAcceptor : IMemberCompletionAcceptor
{
private IntelliPromptMemberList _members;
private Dictionary<string, List<InvocableBinding>> _functionsTable = new Dictionary<string, List<InvocableBinding>>();
private Dictionary<string, List<MemberEntry>> _memberEntries = new Dictionary<string, List<MemberEntry>>();
private class MemberEntry
{
public int ImageIndex;
public string Description;
}
private const int AMBIGUOUS_NAME_IMG_INDEX = 0;
private const int TABLE_IMG_INDEX = 1;
private const int TABLE_REF_IMG_INDEX = 2;
private const int PROPERTY_IMG_INDEX = 3;
private const int FUNCTION_IMG_INDEX = 4;
private const int KEYWORD_IMG_INDEX = 5;
private const int AGGREGATE_IMG_INDEX = 6;
private const int PARAMETER_IMG_INDEX = 7;
private const int RELATION_IMG_INDEX = 8;
public MemberAcceptor(IntelliPromptMemberList members)
{
_members = members;
}
private void Add(string name, string fullname, string datatype, int imageIndex)
{
List<MemberEntry> membersWithSameName;
if (!_memberEntries.TryGetValue(name, out membersWithSameName))
{
membersWithSameName = new List<MemberEntry>();
_memberEntries.Add(name, membersWithSameName);
}
MemberEntry entry = new MemberEntry();
entry.Description = String.Format(CultureInfo.CurrentCulture, "<b>{0}</b> : {1}", fullname, datatype);
entry.ImageIndex = imageIndex;
membersWithSameName.Add(entry);
}
private void AddWithoutDuplicationCheck(string name, string fullname, string datatype, int imageIndex)
{
string preText = MaskIdentifier(name);
string description = String.Format(CultureInfo.CurrentCulture, "<b>{0}</b> : {1}", fullname, datatype);
IntelliPromptMemberListItem item = new IntelliPromptMemberListItem(name, imageIndex, description, preText, String.Empty);
_members.Add(item);
}
public void FlushBuffer()
{
AddBufferedMembers();
AddBufferedFunctions();
}
private static string MaskIdentifier(string name)
{
if (name.IndexOfAny(new char[] {' ', '\t'}) >= 0)
return "[" + name + "]";
return name;
}
private void AddBufferedMembers()
{
foreach (string name in _memberEntries.Keys)
{
List<MemberEntry> membersWithSameName = _memberEntries[name];
MemberEntry entry = membersWithSameName[0];
if (membersWithSameName.Count == 1)
{
string preText = MaskIdentifier(name);
IntelliPromptMemberListItem item = new IntelliPromptMemberListItem(name, entry.ImageIndex, entry.Description, preText, String.Empty);
_members.Add(item);
}
else
{
StringBuilder sb = new StringBuilder();
sb.Append("(Ambiguous name -- choose from the following:)");
foreach (MemberEntry entryWithSameName in membersWithSameName)
{
sb.Append("<br/>");
sb.Append(entryWithSameName.Description);
}
string description = sb.ToString();
string preText = MaskIdentifier(name);
IntelliPromptMemberListItem item = new IntelliPromptMemberListItem(name, AMBIGUOUS_NAME_IMG_INDEX, description, preText, String.Empty);
_members.Add(item);
}
}
}
private void AddBufferedFunctions()
{
foreach (string functionName in _functionsTable.Keys)
{
List<InvocableBinding> functionList = _functionsTable[functionName];
InvocableBinding invocable = functionList[0];
string description;
if (invocable is FunctionBinding)
{
if (functionList.Count == 1)
description = String.Format(CultureInfo.CurrentCulture, "<b>{0}</b> : {1}", invocable.Name, invocable.ReturnType.Name);
else
description = String.Format(CultureInfo.CurrentCulture, "<b>{0}</b> : {1} (+ {2} Overloadings)", invocable.Name, invocable.ReturnType.Name, functionList.Count);
}
else
{
MethodBinding method = (MethodBinding) invocable;
if (functionList.Count == 1)
description = String.Format(CultureInfo.CurrentCulture, "{0}.<b>{1}</b> : {2}", method.DeclaringType.Name, method.Name, method.ReturnType.Name);
else
description = String.Format(CultureInfo.CurrentCulture, "{0}.<b>{1}</b> : {2} (+ {3} Overloadings)", method.DeclaringType.Name, method.Name, method.ReturnType.Name, functionList.Count);
}
string preText = MaskIdentifier(invocable.Name);
IntelliPromptMemberListItem item = new IntelliPromptMemberListItem(invocable.Name, FUNCTION_IMG_INDEX, description, preText, String.Empty);
_members.Add(item);
}
}
public void AcceptTable(TableBinding table)
{
AddWithoutDuplicationCheck(table.Name, table.GetFullName(), "TABLE", TABLE_IMG_INDEX);
}
public void AcceptTableRef(TableRefBinding tableRef)
{
Add(tableRef.Name, tableRef.GetFullName(), "TABLE REF", TABLE_REF_IMG_INDEX);
}
public void AcceptColumnRef(ColumnRefBinding columnRef)
{
Add(columnRef.Name, columnRef.GetFullName(), columnRef.ColumnBinding.DataType.Name, PROPERTY_IMG_INDEX);
}
public void AcceptProperty(PropertyBinding property)
{
Add(property.Name, property.GetFullName(), property.DataType.Name, PROPERTY_IMG_INDEX);
}
public void AcceptKeyword(string keyword)
{
AddWithoutDuplicationCheck(keyword, keyword, "KEYWORD", KEYWORD_IMG_INDEX);
}
public void AcceptAggregate(AggregateBinding aggregate)
{
Add(aggregate.Name, aggregate.GetFullName(), "AGGREGATE", AGGREGATE_IMG_INDEX);
}
public void AcceptFunction(FunctionBinding function)
{
AddInvocable(function);
}
public void AcceptMethod(MethodBinding method)
{
AddInvocable(method);
}
private void AddInvocable(InvocableBinding invocable)
{
List<InvocableBinding> functionList;
if (!_functionsTable.TryGetValue(invocable.Name, out functionList))
{
functionList = new List<InvocableBinding>();
_functionsTable.Add(invocable.Name, functionList);
}
functionList.Add(invocable);
}
public void AcceptParameter(ParameterBinding parameter)
{
Add("@" + parameter.Name, parameter.GetFullName(), parameter.DataType.Name, PARAMETER_IMG_INDEX);
Add(parameter.Name, parameter.GetFullName(), parameter.DataType.Name, PARAMETER_IMG_INDEX);
}
public void AcceptConstant(ConstantBinding constant)
{
Add(constant.Name, constant.GetFullName(), constant.DataType.Name, PROPERTY_IMG_INDEX);
}
public void AcceptRelation(TableRefBinding parentBinding, TableRefBinding childBinding, TableRelation relation)
{
ColumnBindingCollection parentColumns;
if (parentBinding.TableBinding == relation.ParentTable)
parentColumns = relation.ParentColumns;
else
parentColumns = relation.ChildColumns;
ColumnBindingCollection childColumns;
if (childBinding.TableBinding == relation.ChildTable)
childColumns = relation.ChildColumns;
else
childColumns = relation.ParentColumns;
// Item in member list:
// ~~~~~~~~~~~~~~~~~~~~
// parentRef(col1, col2) ---> childRef(col1, col2)
StringBuilder sb = new StringBuilder();
sb.Append(parentBinding.Name);
sb.Append(" (");
for (int i = 0; i < relation.ColumnCount; i++)
{
if (i > 0)
sb.Append(", ");
sb.Append(parentColumns[i].Name);
}
sb.Append(") ---> ");
sb.Append(childBinding.Name);
sb.Append(" (");
for (int i = 0; i < relation.ColumnCount; i++)
{
if (i > 0)
sb.Append(", ");
sb.Append(childColumns[i].Name);
}
sb.Append(")");
string name = sb.ToString();
sb.Length = 0;
// Description:
// ~~~~~~~~~~~~
// Relation <b>parentTable parentRef</b> ---> <b>ChildTable childRef</b> <br/>
// ON (parentRef.Col1 = childRef.Col1 AND parentRef.Col2 = childRef.Col2)
sb.Append("Relation <br/>");
sb.Append("<b>");
sb.Append(MaskIdentifier(parentBinding.TableBinding.Name));
sb.Append(" AS ");
sb.Append(MaskIdentifier(parentBinding.Name));
sb.Append("</b>");
sb.Append(" ---> ");
sb.Append("<b>");
sb.Append(MaskIdentifier(childBinding.TableBinding.Name));
sb.Append(" AS ");
sb.Append(MaskIdentifier(childBinding.Name));
sb.Append("</b><br/>ON (");
for (int i = 0; i < relation.ColumnCount; i++)
{
if (i > 0)
sb.Append(" AND ");
sb.Append(MaskIdentifier(parentBinding.Name));
sb.Append(".");
sb.Append(MaskIdentifier(parentColumns[i].Name));
sb.Append(" = ");
sb.Append(MaskIdentifier(childBinding.Name));
sb.Append(".");
sb.Append(MaskIdentifier(childColumns[i].Name));
}
sb.Append(")");
string description = sb.ToString();
sb.Length = 0;
// PreText:
// ~~~~~~~~
// parentAlias.Col1 = childAlias.Col1 AND parentAlias.Col2 = childAlias.Col2
for (int i = 0; i < relation.ColumnCount; i++)
{
if (i > 0)
sb.Append(" AND ");
sb.Append(MaskIdentifier(parentBinding.Name));
sb.Append(".");
sb.Append(MaskIdentifier(parentColumns[i].Name));
sb.Append(" = ");
sb.Append(MaskIdentifier(childBinding.Name));
sb.Append(".");
sb.Append(MaskIdentifier(childColumns[i].Name));
}
string preText = sb.ToString();
sb.Length = 0;
IntelliPromptMemberListItem item = new IntelliPromptMemberListItem(name, RELATION_IMG_INDEX, description, preText, String.Empty);
_members.Add(item);
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="TraceSource.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Threading;
using System.Configuration;
using System.Security;
using System.Security.Permissions;
using System.Diagnostics.CodeAnalysis;
namespace System.Diagnostics {
public class TraceSource {
private static List<WeakReference> tracesources = new List<WeakReference>();
private static int s_LastCollectionCount;
private volatile SourceSwitch internalSwitch;
private volatile TraceListenerCollection listeners;
private StringDictionary attributes;
private SourceLevels switchLevel;
private volatile string sourceName;
internal volatile bool _initCalled = false; // Whether we've called Initialize already.
public TraceSource(string name)
: this(name, SourceLevels.Off) {
}
public TraceSource(string name, SourceLevels defaultLevel) {
if (name == null)
throw new ArgumentNullException("name");
if (name.Length == 0)
throw new ArgumentException("name");
sourceName = name;
switchLevel = defaultLevel;
// Delay load config to avoid perf (and working set) issues in retail
// Add a weakreference to this source and cleanup invalid references
lock(tracesources) {
_pruneCachedTraceSources();
tracesources.Add(new WeakReference(this));
}
}
private static void _pruneCachedTraceSources() {
lock (tracesources) {
if (s_LastCollectionCount != GC.CollectionCount(2)) {
List<WeakReference> buffer = new List<WeakReference>(tracesources.Count);
for (int i = 0; i < tracesources.Count; i++) {
TraceSource tracesource = ((TraceSource)tracesources[i].Target);
if (tracesource != null) {
buffer.Add(tracesources[i]);
}
}
if (buffer.Count < tracesources.Count) {
tracesources.Clear();
tracesources.AddRange(buffer);
tracesources.TrimExcess();
}
s_LastCollectionCount = GC.CollectionCount(2);
}
}
}
private void Initialize() {
if (!_initCalled) {
lock(this) {
if (_initCalled)
return;
#if CONFIGURATION_DEP
SourceElementsCollection sourceElements = DiagnosticsConfiguration.Sources;
if (sourceElements != null) {
SourceElement sourceElement = sourceElements[sourceName];
if (sourceElement != null) {
if (!String.IsNullOrEmpty(sourceElement.SwitchName)) {
CreateSwitch(sourceElement.SwitchType, sourceElement.SwitchName);
}
else {
CreateSwitch(sourceElement.SwitchType, sourceName);
if (!String.IsNullOrEmpty(sourceElement.SwitchValue))
internalSwitch.Level = (SourceLevels) Enum.Parse(typeof(SourceLevels), sourceElement.SwitchValue);
}
listeners = sourceElement.Listeners.GetRuntimeObject();
attributes = new StringDictionary();
TraceUtils.VerifyAttributes(sourceElement.Attributes, GetSupportedAttributes(), this);
attributes.ReplaceHashtable(sourceElement.Attributes);
}
else
NoConfigInit();
}
else
#endif
NoConfigInit();
_initCalled = true;
}
}
}
private void NoConfigInit() {
internalSwitch = new SourceSwitch(sourceName, switchLevel.ToString());
listeners = new TraceListenerCollection();
listeners.Add(new DefaultTraceListener());
attributes = null;
}
[SecurityPermission(SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.UnmanagedCode)]
public void Close() {
// No need to call Initialize()
if (listeners != null) {
// Use global lock
lock (TraceInternal.critSec) {
foreach (TraceListener listener in listeners) {
listener.Close();
}
}
}
}
public void Flush() {
// No need to call Initialize()
if (listeners != null) {
if (TraceInternal.UseGlobalLock) {
lock (TraceInternal.critSec) {
foreach (TraceListener listener in listeners) {
listener.Flush();
}
}
}
else {
foreach (TraceListener listener in listeners) {
if (!listener.IsThreadSafe) {
lock (listener) {
listener.Flush();
}
}
else {
listener.Flush();
}
}
}
}
}
virtual protected internal string[] GetSupportedAttributes() {
return null;
}
internal static void RefreshAll() {
lock (tracesources) {
_pruneCachedTraceSources();
for (int i=0; i<tracesources.Count; i++) {
TraceSource tracesource = ((TraceSource) tracesources[i].Target);
if (tracesource != null) {
tracesource.Refresh();
}
}
}
}
internal void Refresh() {
if (!_initCalled) {
Initialize();
return;
}
#if CONFIGURATION_DEP
SourceElementsCollection sources = DiagnosticsConfiguration.Sources;
if (sources != null) {
SourceElement sourceElement = sources[Name];
if (sourceElement != null) {
// first check if the type changed
if ((String.IsNullOrEmpty(sourceElement.SwitchType) && internalSwitch.GetType() != typeof(SourceSwitch)) ||
(sourceElement.SwitchType != internalSwitch.GetType().AssemblyQualifiedName)) {
if (!String.IsNullOrEmpty(sourceElement.SwitchName)) {
CreateSwitch(sourceElement.SwitchType, sourceElement.SwitchName);
}
else {
CreateSwitch(sourceElement.SwitchType, Name);
if (!String.IsNullOrEmpty(sourceElement.SwitchValue))
internalSwitch.Level = (SourceLevels) Enum.Parse(typeof(SourceLevels), sourceElement.SwitchValue);
}
}
else if (!String.IsNullOrEmpty(sourceElement.SwitchName)) {
// create a new switch if the name changed, otherwise just refresh.
if (sourceElement.SwitchName != internalSwitch.DisplayName)
CreateSwitch(sourceElement.SwitchType, sourceElement.SwitchName);
else
internalSwitch.Refresh();
}
else {
// the switchValue changed. Just update our internalSwitch.
if (!String.IsNullOrEmpty(sourceElement.SwitchValue))
internalSwitch.Level = (SourceLevels) Enum.Parse(typeof(SourceLevels), sourceElement.SwitchValue);
else
internalSwitch.Level = SourceLevels.Off;
}
TraceListenerCollection newListenerCollection = new TraceListenerCollection();
foreach (ListenerElement listenerElement in sourceElement.Listeners) {
TraceListener listener = listeners[listenerElement.Name];
if (listener != null) {
newListenerCollection.Add(listenerElement.RefreshRuntimeObject(listener));
}
else {
newListenerCollection.Add(listenerElement.GetRuntimeObject());
}
}
TraceUtils.VerifyAttributes(sourceElement.Attributes, GetSupportedAttributes(), this);
attributes = new StringDictionary();
attributes.ReplaceHashtable(sourceElement.Attributes);
listeners = newListenerCollection;
}
else {
// there was no config, so clear whatever we have.
internalSwitch.Level = switchLevel;
listeners.Clear();
attributes = null;
}
}
#endif
}
[Conditional("TRACE")]
public void TraceEvent(TraceEventType eventType, int id) {
// Ensure that config is loaded
Initialize();
TraceEventCache manager = new TraceEventCache();
if (internalSwitch.ShouldTrace(eventType) && listeners != null) {
if (TraceInternal.UseGlobalLock) {
// we lock on the same object that Trace does because we're writing to the same Listeners.
lock (TraceInternal.critSec) {
for (int i=0; i<listeners.Count; i++) {
TraceListener listener = listeners[i];
listener.TraceEvent(manager, Name, eventType, id);
if (Trace.AutoFlush) listener.Flush();
}
}
}
else {
for (int i=0; i<listeners.Count; i++) {
TraceListener listener = listeners[i];
if (!listener.IsThreadSafe) {
lock (listener) {
listener.TraceEvent(manager, Name, eventType, id);
if (Trace.AutoFlush) listener.Flush();
}
}
else {
listener.TraceEvent(manager, Name, eventType, id);
if (Trace.AutoFlush) listener.Flush();
}
}
}
}
}
[Conditional("TRACE")]
public void TraceEvent(TraceEventType eventType, int id, string message) {
// Ensure that config is loaded
Initialize();
TraceEventCache manager = new TraceEventCache();
if (internalSwitch.ShouldTrace(eventType) && listeners != null) {
if (TraceInternal.UseGlobalLock) {
// we lock on the same object that Trace does because we're writing to the same Listeners.
lock (TraceInternal.critSec) {
for (int i=0; i<listeners.Count; i++) {
TraceListener listener = listeners[i];
listener.TraceEvent(manager, Name, eventType, id, message);
if (Trace.AutoFlush) listener.Flush();
}
}
}
else {
for (int i=0; i<listeners.Count; i++) {
TraceListener listener = listeners[i];
if (!listener.IsThreadSafe) {
lock (listener) {
listener.TraceEvent(manager, Name, eventType, id, message);
if (Trace.AutoFlush) listener.Flush();
}
}
else {
listener.TraceEvent(manager, Name, eventType, id, message);
if (Trace.AutoFlush) listener.Flush();
}
}
}
}
}
[Conditional("TRACE")]
public void TraceEvent(TraceEventType eventType, int id, string format, params object[] args) {
// Ensure that config is loaded
Initialize();
TraceEventCache manager = new TraceEventCache();
if (internalSwitch.ShouldTrace(eventType) && listeners != null) {
if (TraceInternal.UseGlobalLock) {
// we lock on the same object that Trace does because we're writing to the same Listeners.
lock (TraceInternal.critSec) {
for (int i=0; i<listeners.Count; i++) {
TraceListener listener = listeners[i];
listener.TraceEvent(manager, Name, eventType, id, format, args);
if (Trace.AutoFlush) listener.Flush();
}
}
}
else {
for (int i=0; i<listeners.Count; i++) {
TraceListener listener = listeners[i];
if (!listener.IsThreadSafe) {
lock (listener) {
listener.TraceEvent(manager, Name, eventType, id, format, args);
if (Trace.AutoFlush) listener.Flush();
}
}
else {
listener.TraceEvent(manager, Name, eventType, id, format, args);
if (Trace.AutoFlush) listener.Flush();
}
}
}
}
}
[Conditional("TRACE")]
public void TraceData(TraceEventType eventType, int id, object data) {
// Ensure that config is loaded
Initialize();
TraceEventCache manager = new TraceEventCache();
if (internalSwitch.ShouldTrace(eventType) && listeners != null) {
if (TraceInternal.UseGlobalLock) {
// we lock on the same object that Trace does because we're writing to the same Listeners.
lock (TraceInternal.critSec) {
for (int i=0; i<listeners.Count; i++) {
TraceListener listener = listeners[i];
listener.TraceData(manager, Name, eventType, id, data);
if (Trace.AutoFlush) listener.Flush();
}
}
}
else {
for (int i=0; i<listeners.Count; i++) {
TraceListener listener = listeners[i];
if (!listener.IsThreadSafe) {
lock (listener) {
listener.TraceData(manager, Name, eventType, id, data);
if (Trace.AutoFlush) listener.Flush();
}
}
else {
listener.TraceData(manager, Name, eventType, id, data);
if (Trace.AutoFlush) listener.Flush();
}
}
}
}
}
[Conditional("TRACE")]
public void TraceData(TraceEventType eventType, int id, params object[] data) {
// Ensure that config is loaded
Initialize();
TraceEventCache manager = new TraceEventCache();
if (internalSwitch.ShouldTrace(eventType) && listeners != null) {
if (TraceInternal.UseGlobalLock) {
// we lock on the same object that Trace does because we're writing to the same Listeners.
lock (TraceInternal.critSec) {
for (int i=0; i<listeners.Count; i++) {
TraceListener listener = listeners[i];
listener.TraceData(manager, Name, eventType, id, data);
if (Trace.AutoFlush) listener.Flush();
}
}
}
else {
for (int i=0; i<listeners.Count; i++) {
TraceListener listener = listeners[i];
if (!listener.IsThreadSafe) {
lock (listener) {
listener.TraceData(manager, Name, eventType, id, data);
if (Trace.AutoFlush) listener.Flush();
}
}
else {
listener.TraceData(manager, Name, eventType, id, data);
if (Trace.AutoFlush) listener.Flush();
}
}
}
}
}
[Conditional("TRACE")]
public void TraceInformation(string message) { // eventType= TraceEventType.Info, id=0
// No need to call Initialize()
TraceEvent(TraceEventType.Information, 0, message, null);
}
[Conditional("TRACE")]
public void TraceInformation(string format, params object[] args) {
// No need to call Initialize()
TraceEvent(TraceEventType.Information, 0, format, args);
}
[Conditional("TRACE")]
public void TraceTransfer(int id, string message, Guid relatedActivityId) {
// Ensure that config is loaded
Initialize();
TraceEventCache manager = new TraceEventCache();
if (internalSwitch.ShouldTrace(TraceEventType.Transfer) && listeners != null) {
if (TraceInternal.UseGlobalLock) {
// we lock on the same object that Trace does because we're writing to the same Listeners.
lock (TraceInternal.critSec) {
for (int i=0; i<listeners.Count; i++) {
TraceListener listener = listeners[i];
listener.TraceTransfer(manager, Name, id, message, relatedActivityId);
if (Trace.AutoFlush) listener.Flush();
}
}
}
else {
for (int i=0; i<listeners.Count; i++) {
TraceListener listener = listeners[i];
if (!listener.IsThreadSafe) {
lock (listener) {
listener.TraceTransfer(manager, Name, id, message, relatedActivityId);
if (Trace.AutoFlush) listener.Flush();
}
}
else {
listener.TraceTransfer(manager, Name, id, message, relatedActivityId);
if (Trace.AutoFlush) listener.Flush();
}
}
}
}
}
private void CreateSwitch(string typename, string name) {
if (!String.IsNullOrEmpty(typename))
internalSwitch = (SourceSwitch) TraceUtils.GetRuntimeObject(typename, typeof(SourceSwitch), name);
else
internalSwitch = new SourceSwitch(name, switchLevel.ToString());
}
public StringDictionary Attributes {
get {
// Ensure that config is loaded
Initialize();
if (attributes == null)
attributes = new StringDictionary();
return attributes;
}
}
public string Name {
get {
return sourceName;
}
}
public TraceListenerCollection Listeners {
[SecurityPermission(SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.UnmanagedCode)]
get {
// Ensure that config is loaded
Initialize();
return listeners;
}
}
public SourceSwitch Switch {
// No need for security demand here. SourceSwitch.set_Level is protected already.
get {
// Ensure that config is loaded
Initialize();
return internalSwitch;
}
[SecurityPermission(SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.UnmanagedCode)]
set {
if (value == null)
throw new ArgumentNullException("Switch");
// Ensure that config is loaded
Initialize();
internalSwitch = value;
}
}
}
}
| |
// 3D Projective Geometric Algebra
// Written by a generator written by enki.
using System;
using System.Text;
using static HYP.HYPERBOLIC; // static variable acces
namespace HYP
{
public class HYPERBOLIC
{
// just for debug and print output, the basis names
public static string[] _basis = new[] { "1","e1" };
private float[] _mVec = new float[2];
/// <summary>
/// Ctor
/// </summary>
/// <param name="f"></param>
/// <param name="idx"></param>
public HYPERBOLIC(float f = 0f, int idx = 0)
{
_mVec[idx] = f;
}
#region Array Access
public float this[int idx]
{
get { return _mVec[idx]; }
set { _mVec[idx] = value; }
}
#endregion
#region Overloaded Operators
/// <summary>
/// HYPERBOLIC.Reverse : res = ~a
/// Reverse the order of the basis blades.
/// </summary>
public static HYPERBOLIC operator ~ (HYPERBOLIC a)
{
HYPERBOLIC res = new HYPERBOLIC();
res[0]=a[0];
res[1]=a[1];
return res;
}
/// <summary>
/// HYPERBOLIC.Dual : res = !a
/// Poincare duality operator.
/// </summary>
public static HYPERBOLIC operator ! (HYPERBOLIC a)
{
HYPERBOLIC res = new HYPERBOLIC();
res[0]=a[1];
res[1]=a[0];
return res;
}
/// <summary>
/// HYPERBOLIC.Conjugate : res = a.Conjugate()
/// Clifford Conjugation
/// </summary>
public HYPERBOLIC Conjugate ()
{
HYPERBOLIC res = new HYPERBOLIC();
res[0]=this[0];
res[1]=-this[1];
return res;
}
/// <summary>
/// HYPERBOLIC.Involute : res = a.Involute()
/// Main involution
/// </summary>
public HYPERBOLIC Involute ()
{
HYPERBOLIC res = new HYPERBOLIC();
res[0]=this[0];
res[1]=-this[1];
return res;
}
/// <summary>
/// HYPERBOLIC.Mul : res = a * b
/// The geometric product.
/// </summary>
public static HYPERBOLIC operator * (HYPERBOLIC a, HYPERBOLIC b)
{
HYPERBOLIC res = new HYPERBOLIC();
res[0]=b[0]*a[0]+b[1]*a[1];
res[1]=b[1]*a[0]+b[0]*a[1];
return res;
}
/// <summary>
/// HYPERBOLIC.Wedge : res = a ^ b
/// The outer product. (MEET)
/// </summary>
public static HYPERBOLIC operator ^ (HYPERBOLIC a, HYPERBOLIC b)
{
HYPERBOLIC res = new HYPERBOLIC();
res[0]=b[0]*a[0];
res[1]=b[1]*a[0]+b[0]*a[1];
return res;
}
/// <summary>
/// HYPERBOLIC.Vee : res = a & b
/// The regressive product. (JOIN)
/// </summary>
public static HYPERBOLIC operator & (HYPERBOLIC a, HYPERBOLIC b)
{
HYPERBOLIC res = new HYPERBOLIC();
res[1]=1*(a[1]*b[1]);
res[0]=1*(a[0]*b[1]+a[1]*b[0]);
return res;
}
/// <summary>
/// HYPERBOLIC.Dot : res = a | b
/// The inner product.
/// </summary>
public static HYPERBOLIC operator | (HYPERBOLIC a, HYPERBOLIC b)
{
HYPERBOLIC res = new HYPERBOLIC();
res[0]=b[0]*a[0]+b[1]*a[1];
res[1]=b[1]*a[0]+b[0]*a[1];
return res;
}
/// <summary>
/// HYPERBOLIC.Add : res = a + b
/// Multivector addition
/// </summary>
public static HYPERBOLIC operator + (HYPERBOLIC a, HYPERBOLIC b)
{
HYPERBOLIC res = new HYPERBOLIC();
res[0] = a[0]+b[0];
res[1] = a[1]+b[1];
return res;
}
/// <summary>
/// HYPERBOLIC.Sub : res = a - b
/// Multivector subtraction
/// </summary>
public static HYPERBOLIC operator - (HYPERBOLIC a, HYPERBOLIC b)
{
HYPERBOLIC res = new HYPERBOLIC();
res[0] = a[0]-b[0];
res[1] = a[1]-b[1];
return res;
}
/// <summary>
/// HYPERBOLIC.smul : res = a * b
/// scalar/multivector multiplication
/// </summary>
public static HYPERBOLIC operator * (float a, HYPERBOLIC b)
{
HYPERBOLIC res = new HYPERBOLIC();
res[0] = a*b[0];
res[1] = a*b[1];
return res;
}
/// <summary>
/// HYPERBOLIC.muls : res = a * b
/// multivector/scalar multiplication
/// </summary>
public static HYPERBOLIC operator * (HYPERBOLIC a, float b)
{
HYPERBOLIC res = new HYPERBOLIC();
res[0] = a[0]*b;
res[1] = a[1]*b;
return res;
}
/// <summary>
/// HYPERBOLIC.sadd : res = a + b
/// scalar/multivector addition
/// </summary>
public static HYPERBOLIC operator + (float a, HYPERBOLIC b)
{
HYPERBOLIC res = new HYPERBOLIC();
res[0] = a+b[0];
res[1] = b[1];
return res;
}
/// <summary>
/// HYPERBOLIC.adds : res = a + b
/// multivector/scalar addition
/// </summary>
public static HYPERBOLIC operator + (HYPERBOLIC a, float b)
{
HYPERBOLIC res = new HYPERBOLIC();
res[0] = a[0]+b;
res[1] = a[1];
return res;
}
/// <summary>
/// HYPERBOLIC.ssub : res = a - b
/// scalar/multivector subtraction
/// </summary>
public static HYPERBOLIC operator - (float a, HYPERBOLIC b)
{
HYPERBOLIC res = new HYPERBOLIC();
res[0] = a-b[0];
res[1] = -b[1];
return res;
}
/// <summary>
/// HYPERBOLIC.subs : res = a - b
/// multivector/scalar subtraction
/// </summary>
public static HYPERBOLIC operator - (HYPERBOLIC a, float b)
{
HYPERBOLIC res = new HYPERBOLIC();
res[0] = a[0]-b;
res[1] = a[1];
return res;
}
#endregion
/// <summary>
/// HYPERBOLIC.norm()
/// Calculate the Euclidean norm. (strict positive).
/// </summary>
public float norm() { return (float) Math.Sqrt(Math.Abs((this*this.Conjugate())[0]));}
/// <summary>
/// HYPERBOLIC.inorm()
/// Calculate the Ideal norm. (signed)
/// </summary>
public float inorm() { return this[1]!=0.0f?this[1]:this[15]!=0.0f?this[15]:(!this).norm();}
/// <summary>
/// HYPERBOLIC.normalized()
/// Returns a normalized (Euclidean) element.
/// </summary>
public HYPERBOLIC normalized() { return this*(1/norm()); }
// The basis blades
public static HYPERBOLIC e1 = new HYPERBOLIC(1f, 1);
/// string cast
public override string ToString()
{
var sb = new StringBuilder();
var n=0;
for (int i = 0; i < 2; ++i)
if (_mVec[i] != 0.0f) {
sb.Append($"{_mVec[i]}{(i == 0 ? string.Empty : _basis[i])} + ");
n++;
}
if (n==0) sb.Append("0");
return sb.ToString().TrimEnd(' ', '+');
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine("e1*e1 : "+e1*e1);
Console.WriteLine("pss : "+e1);
Console.WriteLine("pss*pss : "+e1*e1);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Threading.Tasks;
using ThorIOClient.Models;
using ThorIOClient.Attributes;
using ThorIOClient.Serialization;
using ThorIOClient.Interfaces;
using System.Threading;
using ThorIOClient.Extensions;
namespace ThorIOClient {
public partial class ProxyBase : IProxyBase {
public ISerializer Serializer {
get;
set;
}
public ISocket Socket { get; set; }
public string alias;
private List < Listener > Listeners;
public Dictionary < string, dynamic > Delegates;
List < ProxyCustomMethodInfo > CustomEvents {
get;
set;
}
public void CreateDelegates() {
this.CustomEvents = new List <ProxyCustomMethodInfo > ();
this.Delegates = new Dictionary<string, dynamic>();
var t = this.GetType();
var prop = t.GetCustomAttributes(typeof (ProxyProperties)).FirstOrDefault() as ProxyProperties;
this.alias = prop.Alias;
foreach(var member in t.GetMembers()) {
if (member.GetCustomAttributes(typeof (Invokable), true).Length > 0) {
var method = t.GetMethod(member.Name);
var methodAlias = member.Name;
var invokable = method.GetCustomAttributes(typeof(Invokable),true).First() as Invokable;
if(invokable != null) methodAlias = invokable.Alias;
this.CustomEvents.Add(new ProxyCustomMethodInfo(method,methodAlias));
var parameters = method.GetParameters()
.Select(pi => Expression.Parameter(pi.ParameterType, pi.Name)).ToList();
switch (parameters.Count) {
case 0:
{
var le = Expression.Lambda(
Expression.Call(
Expression.Constant(this),
method));
var f = le.Compile();
Delegates.Add(method.Name, f);
}
break;
case 1:
{
var le = Expression.Lambda(
Expression.Call(
Expression.Constant(this),
method, parameters[0]), parameters[0]);
var f = le.Compile();
Delegates.Add(method.Name, f);
}
break;
case 2:
{
var le = Expression.Lambda(
Expression.Call(
Expression.Constant(this),
method, parameters[0],parameters[1]), parameters[0],parameters[1]);
var f = le.Compile();
Delegates.Add(method.Name, f);
}
break;
case 3:
{
var le = Expression.Lambda(
Expression.Call(
Expression.Constant(this),
method, parameters[0],parameters[1],parameters[2]), parameters[0],parameters[1],parameters[2]);
var f = le.Compile();
Delegates.Add(method.Name, f);
}
break;
case 4:
{
var le = Expression.Lambda(
Expression.Call(
Expression.Constant(this),
method, parameters[0],parameters[1],parameters[2],parameters[3]),
parameters[0],parameters[1],parameters[2],parameters[3]);
var f = le.Compile();
Delegates.Add(method.Name, f);
}
break;
case 5:
{
var le = Expression.Lambda(
Expression.Call(
Expression.Constant(this),
method, parameters[0],parameters[1],parameters[2],parameters[3],parameters[4]),
parameters[0],parameters[1],parameters[2],parameters[3],parameters[4]);
var f = le.Compile();
Delegates.Add(method.Name, f);
}
break;
case 6:
{
var le = Expression.Lambda(
Expression.Call(
Expression.Constant(this),
method, parameters[0],parameters[1],parameters[2],parameters[3],parameters[4],
parameters[5]),
parameters[0],parameters[1],parameters[2],parameters[3],parameters[4],
parameters[5]
);
var f = le.Compile();
Delegates.Add(method.Name, f);
}
break;
case 7:
{
var le = Expression.Lambda(
Expression.Call(
Expression.Constant(this),
method, parameters[0],parameters[1],parameters[2],parameters[3],parameters[4],
parameters[5],parameters[6]),
parameters[0],parameters[1],parameters[2],parameters[3],parameters[4],
parameters[5],parameters[6]
);
var f = le.Compile();
Delegates.Add(method.Name, f);
}
break;
};
}
}
}
public ThorIOClient.Queue.ThreadSafeQueue<Message> messageQueue;
public ProxyBase() {
this.Serializer = new NewtonJsonSerialization();
this.Listeners = new List < Listener > ();
this.On < ConnectionInformation > ("___open", (ConnectionInformation info) => {
this.IsConnected = true;
this.OnOpen(info);
});
this.On < ErrorMessage > ("___error", (ErrorMessage err) => {
if(this.OnError != null)
this.OnError(err);
});
this.messageQueue = new ThorIOClient.Queue.ThreadSafeQueue<Message>();
var ct = new CancellationTokenSource();
new Task(action: async () =>
{
for (var i = 0; i < this.messageQueue.Count; i++)
{
var message = this.messageQueue.Dequeue();
this.SendQueueMessage(message);
}
}).Repeat(ct.Token, TimeSpan.FromMilliseconds(60));
}
public Action < ConnectionInformation > OnOpen;
public Action < ConnectionInformation > OnClose;
public Action < ErrorMessage > OnError;
public bool IsConnected {
get;
set;
}
public async Task Connect() {
await this.Send(new Message("___connect", "{}", this.alias)).ConfigureAwait(false);
}
private async Task Send(Message message) {
this.messageQueue.Enqueue(message);
}
private void SendQueueMessage(Message message){
// try {
// await Task.Run(() => {
var data = Serializer.Serialize < Message > (message);
this.Socket.SendMessage(data);
// }).ConfigureAwait(false);
// } catch (Exception ex) {
// this.OnError(new ErrorMessage(ex.Message));
// }
}
public async Task < ProxyBase > Close() {
await this.Send(new Message("___close", "{}", this.alias)).ConfigureAwait(false);
return this;
}
public ProxyBase On < T > (string topic, Action < T > fn) {
if (typeof (T) == typeof (IMessage)) {
this.Listeners.Add(new Listener(topic, message => fn((T) message)));
} else {
var listener = new Listener(topic, message => fn(Serializer.Deserialize < T > (message.Data)));
this.Listeners.Add(listener);
}
return this;
}
public ProxyBase Off(string name) {
var listener = this.FindListener(name);
this.Listeners.Remove(listener);
return this;
}
public async Task < ProxyBase > Subscribe < T > (string topic, Action < T > fn) {
var message = new Message("___subscribe", Serializer.Serialize < Subscription > (new Subscription(topic, this.alias)),
this.alias);
await this.Send(message).ConfigureAwait(false);
this.On < T > (topic, fn);
return this;
}
public async Task < ProxyBase > UnSubscribe(string topic) {
var message = new Message("___unsubscribe",
Serializer.Serialize < Subscription > (new Subscription(topic, this.alias)), this.alias);
await this.Send(message).ConfigureAwait(false);
this.Off(topic);
return this;
}
public async Task < ProxyBase > Invoke < T > (string topic, T data) {
await this.Send(new Message(topic, Serializer.Serialize < T > (data), this.alias)).ConfigureAwait(false);
return this;
}
public async Task < ProxyBase > Publish < T > (string topic, T data) {
await this.Invoke < T > (topic, data).ConfigureAwait(false);
return this;
}
public async Task < ProxyBase > SetProperty < T > (string propName, T propValue) {
await this.Invoke < T > (propName, propValue).ConfigureAwait(false);
return this;
}
public void Dispatch(IMessage msg) {
var hasCustomEvent = this.CustomEvents != null && this.CustomEvents.Count( p => p.Alias == msg.Topic) > 0;
if (hasCustomEvent) {
var method = this.CustomEvents.SingleOrDefault(p => p.Alias == msg.Topic);
ThorIOClient.Extensions.ProxyExtensions.InvokeProxyMethod(this,method,msg.Data);
} else {
var listener = this.FindListener(msg.Topic);
if (listener != null) {
if (listener.fn != null)
listener.fn(msg);
} else
return;
}
}
private Listener FindListener(string topic) {
return this.Listeners.Find((Listener pre) => {
return pre.Topic == topic;
});
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using MinistryPlatform.Translation.Areas.HelpPage.ModelDescriptions;
using MinistryPlatform.Translation.Areas.HelpPage.Models;
namespace MinistryPlatform.Translation.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System {
using System.Text;
using System;
using System.Runtime;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Diagnostics.Contracts;
using System.Globalization;
// TimeSpan represents a duration of time. A TimeSpan can be negative
// or positive.
//
// TimeSpan is internally represented as a number of milliseconds. While
// this maps well into units of time such as hours and days, any
// periods longer than that aren't representable in a nice fashion.
// For instance, a month can be between 28 and 31 days, while a year
// can contain 365 or 364 days. A decade can have between 1 and 3 leapyears,
// depending on when you map the TimeSpan into the calendar. This is why
// we do not provide Years() or Months().
//
// Note: System.TimeSpan needs to interop with the WinRT structure
// type Windows::Foundation:TimeSpan. These types are currently binary-compatible in
// memory so no custom marshalling is required. If at any point the implementation
// details of this type should change, or new fields added, we need to remember to add
// an appropriate custom ILMarshaler to keep WInRT interop scenarios enabled.
//
[System.Runtime.InteropServices.ComVisible(true)]
[Serializable] public struct TimeSpan : IComparable
, IComparable<TimeSpan>, IEquatable<TimeSpan>, IFormattable
{
public const long TicksPerMillisecond = 10000;
private const double MillisecondsPerTick = 1.0 / TicksPerMillisecond;
public const long TicksPerSecond = TicksPerMillisecond * 1000; // 10,000,000
private const double SecondsPerTick = 1.0 / TicksPerSecond; // 0.0001
public const long TicksPerMinute = TicksPerSecond * 60; // 600,000,000
private const double MinutesPerTick = 1.0 / TicksPerMinute; // 1.6666666666667e-9
public const long TicksPerHour = TicksPerMinute * 60; // 36,000,000,000
private const double HoursPerTick = 1.0 / TicksPerHour; // 2.77777777777777778e-11
public const long TicksPerDay = TicksPerHour * 24; // 864,000,000,000
private const double DaysPerTick = 1.0 / TicksPerDay; // 1.1574074074074074074e-12
private const int MillisPerSecond = 1000;
private const int MillisPerMinute = MillisPerSecond * 60; // 60,000
private const int MillisPerHour = MillisPerMinute * 60; // 3,600,000
private const int MillisPerDay = MillisPerHour * 24; // 86,400,000
internal const long MaxSeconds = Int64.MaxValue / TicksPerSecond;
internal const long MinSeconds = Int64.MinValue / TicksPerSecond;
internal const long MaxMilliSeconds = Int64.MaxValue / TicksPerMillisecond;
internal const long MinMilliSeconds = Int64.MinValue / TicksPerMillisecond;
internal const long TicksPerTenthSecond = TicksPerMillisecond * 100;
public static readonly TimeSpan Zero = new TimeSpan(0);
public static readonly TimeSpan MaxValue = new TimeSpan(Int64.MaxValue);
public static readonly TimeSpan MinValue = new TimeSpan(Int64.MinValue);
// internal so that DateTime doesn't have to call an extra get
// method for some arithmetic operations.
internal long _ticks;
//public TimeSpan() {
// _ticks = 0;
//}
public TimeSpan(long ticks) {
this._ticks = ticks;
}
public TimeSpan(int hours, int minutes, int seconds) {
_ticks = TimeToTicks(hours, minutes, seconds);
}
public TimeSpan(int days, int hours, int minutes, int seconds)
: this(days,hours,minutes,seconds,0)
{
}
public TimeSpan(int days, int hours, int minutes, int seconds, int milliseconds)
{
Int64 totalMilliSeconds = ((Int64)days * 3600 * 24 + (Int64)hours * 3600 + (Int64)minutes * 60 + seconds) * 1000 + milliseconds;
if (totalMilliSeconds > MaxMilliSeconds || totalMilliSeconds < MinMilliSeconds)
throw new ArgumentOutOfRangeException(null, Environment.GetResourceString("Overflow_TimeSpanTooLong"));
_ticks = (long)totalMilliSeconds * TicksPerMillisecond;
}
public long Ticks {
get { return _ticks; }
}
public int Days {
get { return (int)(_ticks / TicksPerDay); }
}
public int Hours {
get { return (int)((_ticks / TicksPerHour) % 24); }
}
public int Milliseconds {
get { return (int)((_ticks / TicksPerMillisecond) % 1000); }
}
public int Minutes {
get { return (int)((_ticks / TicksPerMinute) % 60); }
}
public int Seconds {
get { return (int)((_ticks / TicksPerSecond) % 60); }
}
public double TotalDays {
get { return ((double)_ticks) * DaysPerTick; }
}
public double TotalHours {
get { return (double)_ticks * HoursPerTick; }
}
public double TotalMilliseconds {
get {
double temp = (double)_ticks * MillisecondsPerTick;
if (temp > MaxMilliSeconds)
return (double)MaxMilliSeconds;
if (temp < MinMilliSeconds)
return (double)MinMilliSeconds;
return temp;
}
}
public double TotalMinutes {
get { return (double)_ticks * MinutesPerTick; }
}
public double TotalSeconds {
get { return (double)_ticks * SecondsPerTick; }
}
public TimeSpan Add(TimeSpan ts) {
long result = _ticks + ts._ticks;
// Overflow if signs of operands was identical and result's
// sign was opposite.
// >> 63 gives the sign bit (either 64 1's or 64 0's).
if ((_ticks >> 63 == ts._ticks >> 63) && (_ticks >> 63 != result >> 63))
throw new OverflowException(Environment.GetResourceString("Overflow_TimeSpanTooLong"));
return new TimeSpan(result);
}
// Compares two TimeSpan values, returning an integer that indicates their
// relationship.
//
public static int Compare(TimeSpan t1, TimeSpan t2) {
if (t1._ticks > t2._ticks) return 1;
if (t1._ticks < t2._ticks) return -1;
return 0;
}
// Returns a value less than zero if this object
public int CompareTo(Object value) {
if (value == null) return 1;
if (!(value is TimeSpan))
throw new ArgumentException(Environment.GetResourceString("Arg_MustBeTimeSpan"));
long t = ((TimeSpan)value)._ticks;
if (_ticks > t) return 1;
if (_ticks < t) return -1;
return 0;
}
public int CompareTo(TimeSpan value) {
long t = value._ticks;
if (_ticks > t) return 1;
if (_ticks < t) return -1;
return 0;
}
public static TimeSpan FromDays(double value) {
return Interval(value, MillisPerDay);
}
public TimeSpan Duration() {
if (Ticks==TimeSpan.MinValue.Ticks)
throw new OverflowException(Environment.GetResourceString("Overflow_Duration"));
Contract.EndContractBlock();
return new TimeSpan(_ticks >= 0? _ticks: -_ticks);
}
public override bool Equals(Object value) {
if (value is TimeSpan) {
return _ticks == ((TimeSpan)value)._ticks;
}
return false;
}
public bool Equals(TimeSpan obj)
{
return _ticks == obj._ticks;
}
public static bool Equals(TimeSpan t1, TimeSpan t2) {
return t1._ticks == t2._ticks;
}
public override int GetHashCode() {
return (int)_ticks ^ (int)(_ticks >> 32);
}
public static TimeSpan FromHours(double value) {
return Interval(value, MillisPerHour);
}
private static TimeSpan Interval(double value, int scale) {
if (Double.IsNaN(value))
throw new ArgumentException(Environment.GetResourceString("Arg_CannotBeNaN"));
Contract.EndContractBlock();
double tmp = value * scale;
double millis = tmp + (value >= 0? 0.5: -0.5);
if ((millis > Int64.MaxValue / TicksPerMillisecond) || (millis < Int64.MinValue / TicksPerMillisecond))
throw new OverflowException(Environment.GetResourceString("Overflow_TimeSpanTooLong"));
return new TimeSpan((long)millis * TicksPerMillisecond);
}
public static TimeSpan FromMilliseconds(double value) {
return Interval(value, 1);
}
public static TimeSpan FromMinutes(double value) {
return Interval(value, MillisPerMinute);
}
public TimeSpan Negate() {
if (Ticks==TimeSpan.MinValue.Ticks)
throw new OverflowException(Environment.GetResourceString("Overflow_NegateTwosCompNum"));
Contract.EndContractBlock();
return new TimeSpan(-_ticks);
}
public static TimeSpan FromSeconds(double value) {
return Interval(value, MillisPerSecond);
}
public TimeSpan Subtract(TimeSpan ts) {
long result = _ticks - ts._ticks;
// Overflow if signs of operands was different and result's
// sign was opposite from the first argument's sign.
// >> 63 gives the sign bit (either 64 1's or 64 0's).
if ((_ticks >> 63 != ts._ticks >> 63) && (_ticks >> 63 != result >> 63))
throw new OverflowException(Environment.GetResourceString("Overflow_TimeSpanTooLong"));
return new TimeSpan(result);
}
public static TimeSpan FromTicks(long value) {
return new TimeSpan(value);
}
internal static long TimeToTicks(int hour, int minute, int second) {
// totalSeconds is bounded by 2^31 * 2^12 + 2^31 * 2^8 + 2^31,
// which is less than 2^44, meaning we won't overflow totalSeconds.
long totalSeconds = (long)hour * 3600 + (long)minute * 60 + (long)second;
if (totalSeconds > MaxSeconds || totalSeconds < MinSeconds)
throw new ArgumentOutOfRangeException(null, Environment.GetResourceString("Overflow_TimeSpanTooLong"));
return totalSeconds * TicksPerSecond;
}
// See System.Globalization.TimeSpanParse and System.Globalization.TimeSpanFormat
#region ParseAndFormat
public static TimeSpan Parse(String s) {
/* Constructs a TimeSpan from a string. Leading and trailing white space characters are allowed. */
return TimeSpanParse.Parse(s, null);
}
public static TimeSpan Parse(String input, IFormatProvider formatProvider) {
return TimeSpanParse.Parse(input, formatProvider);
}
public static TimeSpan ParseExact(String input, String format, IFormatProvider formatProvider) {
return TimeSpanParse.ParseExact(input, format, formatProvider, TimeSpanStyles.None);
}
public static TimeSpan ParseExact(String input, String[] formats, IFormatProvider formatProvider) {
return TimeSpanParse.ParseExactMultiple(input, formats, formatProvider, TimeSpanStyles.None);
}
public static TimeSpan ParseExact(String input, String format, IFormatProvider formatProvider, TimeSpanStyles styles) {
TimeSpanParse.ValidateStyles(styles, "styles");
return TimeSpanParse.ParseExact(input, format, formatProvider, styles);
}
public static TimeSpan ParseExact(String input, String[] formats, IFormatProvider formatProvider, TimeSpanStyles styles) {
TimeSpanParse.ValidateStyles(styles, "styles");
return TimeSpanParse.ParseExactMultiple(input, formats, formatProvider, styles);
}
public static Boolean TryParse(String s, out TimeSpan result) {
return TimeSpanParse.TryParse(s, null, out result);
}
public static Boolean TryParse(String input, IFormatProvider formatProvider, out TimeSpan result) {
return TimeSpanParse.TryParse(input, formatProvider, out result);
}
public static Boolean TryParseExact(String input, String format, IFormatProvider formatProvider, out TimeSpan result) {
return TimeSpanParse.TryParseExact(input, format, formatProvider, TimeSpanStyles.None, out result);
}
public static Boolean TryParseExact(String input, String[] formats, IFormatProvider formatProvider, out TimeSpan result) {
return TimeSpanParse.TryParseExactMultiple(input, formats, formatProvider, TimeSpanStyles.None, out result);
}
public static Boolean TryParseExact(String input, String format, IFormatProvider formatProvider, TimeSpanStyles styles, out TimeSpan result) {
TimeSpanParse.ValidateStyles(styles, "styles");
return TimeSpanParse.TryParseExact(input, format, formatProvider, styles, out result);
}
public static Boolean TryParseExact(String input, String[] formats, IFormatProvider formatProvider, TimeSpanStyles styles, out TimeSpan result) {
TimeSpanParse.ValidateStyles(styles, "styles");
return TimeSpanParse.TryParseExactMultiple(input, formats, formatProvider, styles, out result);
}
public override String ToString() {
return TimeSpanFormat.Format(this, null, null);
}
public String ToString(String format) {
return TimeSpanFormat.Format(this, format, null);
}
public String ToString(String format, IFormatProvider formatProvider) {
if (LegacyMode) {
return TimeSpanFormat.Format(this, null, null);
}
else {
return TimeSpanFormat.Format(this, format, formatProvider);
}
}
#endregion
public static TimeSpan operator -(TimeSpan t) {
if (t._ticks==TimeSpan.MinValue._ticks)
throw new OverflowException(Environment.GetResourceString("Overflow_NegateTwosCompNum"));
return new TimeSpan(-t._ticks);
}
public static TimeSpan operator -(TimeSpan t1, TimeSpan t2) {
return t1.Subtract(t2);
}
public static TimeSpan operator +(TimeSpan t) {
return t;
}
public static TimeSpan operator +(TimeSpan t1, TimeSpan t2) {
return t1.Add(t2);
}
public static bool operator ==(TimeSpan t1, TimeSpan t2) {
return t1._ticks == t2._ticks;
}
public static bool operator !=(TimeSpan t1, TimeSpan t2) {
return t1._ticks != t2._ticks;
}
public static bool operator <(TimeSpan t1, TimeSpan t2) {
return t1._ticks < t2._ticks;
}
public static bool operator <=(TimeSpan t1, TimeSpan t2) {
return t1._ticks <= t2._ticks;
}
public static bool operator >(TimeSpan t1, TimeSpan t2) {
return t1._ticks > t2._ticks;
}
public static bool operator >=(TimeSpan t1, TimeSpan t2) {
return t1._ticks >= t2._ticks;
}
//
// In .NET Framework v1.0 - v3.5 System.TimeSpan did not implement IFormattable
// The composite formatter ignores format specifiers on types that do not implement
// IFormattable, so the following code would 'just work' by using TimeSpan.ToString()
// under the hood:
// String.Format("{0:_someRandomFormatString_}", myTimeSpan);
//
// In .NET Framework v4.0 System.TimeSpan implements IFormattable. This causes the
// composite formatter to call TimeSpan.ToString(string format, FormatProvider provider)
// and pass in "_someRandomFormatString_" for the format parameter. When the format
// parameter is invalid a FormatException is thrown.
//
// The 'NetFx40_TimeSpanLegacyFormatMode' per-AppDomain configuration option and the 'TimeSpan_LegacyFormatMode'
// process-wide configuration option allows applications to run with the v1.0 - v3.5 legacy behavior. When
// either switch is specified the format parameter is ignored and the default output is returned.
//
// There are three ways to use the process-wide configuration option:
//
// 1) Config file (MyApp.exe.config)
// <?xml version ="1.0"?>
// <configuration>
// <runtime>
// <TimeSpan_LegacyFormatMode enabled="true"/>
// </runtime>
// </configuration>
// 2) Environment variable
// set COMPLUS_TimeSpan_LegacyFormatMode=1
// 3) RegistryKey
// [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework]
// "TimeSpan_LegacyFormatMode"=dword:00000001
//
#if !FEATURE_CORECLR
[System.Security.SecurityCritical]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern bool LegacyFormatMode();
#endif // !FEATURE_CORECLR
//
// In Silverlight v4, specifying the APP_EARLIER_THAN_SL4.0 quirks mode allows applications to
// run in v2 - v3 legacy behavior.
//
#if !FEATURE_CORECLR
[System.Security.SecuritySafeCritical]
#endif
private static bool GetLegacyFormatMode() {
#if !FEATURE_CORECLR
if (LegacyFormatMode()) // FCALL to check COMPLUS_TimeSpan_LegacyFormatMode
return true;
return CompatibilitySwitches.IsNetFx40TimeSpanLegacyFormatMode;
#else
return CompatibilitySwitches.IsAppEarlierThanSilverlight4;
#endif // !FEATURE_CORECLR
}
private static volatile bool _legacyConfigChecked;
private static volatile bool _legacyMode;
private static bool LegacyMode {
get {
if (!_legacyConfigChecked) {
// no need to lock - idempotent
_legacyMode = GetLegacyFormatMode();
_legacyConfigChecked = true;
}
return _legacyMode;
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using Xunit;
namespace System.Linq.Tests
{
public class SequenceEqualTests
{
private class AnagramEqualityComparer : IEqualityComparer<string>
{
public bool Equals(string x, string y)
{
if (ReferenceEquals(x, y)) return true;
if (x == null | y == null) return false;
int length = x.Length;
if (length != y.Length) return false;
using (var en = x.OrderBy(i => i).GetEnumerator())
{
foreach (char c in y.OrderBy(i => i))
{
en.MoveNext();
if (c != en.Current) return false;
}
}
return true;
}
public int GetHashCode(string obj)
{
int hash = 0;
foreach (char c in obj)
hash ^= (int)c;
return hash;
}
}
private static IEnumerable<T> ForceNotCollection<T>(IEnumerable<T> source)
{
foreach (T item in source) yield return item;
}
private static IEnumerable<T> FlipIsCollection<T>(IEnumerable<T> source)
{
return source is ICollection<T> ? ForceNotCollection(source) : new List<T>(source);
}
[Fact]
public void SameResultsRepeatCallsIntQuery()
{
var q1 = from x1 in new int?[] { 2, 3, null, 2, null, 4, 5 }
select x1;
var q2 = from x2 in new int?[] { 1, 9, null, 4 }
select x2;
Assert.Equal(q1.SequenceEqual(q2), q1.SequenceEqual(q2));
}
[Fact]
public void SameResultsRepeatCallsStringQuery()
{
var q1 = from x1 in new[] { "AAA", String.Empty, "q", "C", "#", "!@#$%^", "0987654321", "Calling Twice" }
select x1;
var q2 = from x2 in new[] { "!@#$%^", "C", "AAA", "", "Calling Twice", "SoS" }
select x2;
Assert.Equal(q1.SequenceEqual(q2), q1.SequenceEqual(q2));
}
[Fact]
public void BothEmpty()
{
int[] first = { };
int[] second = { };
Assert.True(first.SequenceEqual(second));
Assert.True(FlipIsCollection(first).SequenceEqual(second));
Assert.True(first.SequenceEqual(FlipIsCollection(second)));
Assert.True(FlipIsCollection(first).SequenceEqual(FlipIsCollection(second)));
}
[Fact]
public void MismatchInMiddle()
{
int?[] first = { 1, 2, 3, 4 };
int?[] second = { 1, 2, 6, 4 };
Assert.False(first.SequenceEqual(second));
Assert.False(FlipIsCollection(first).SequenceEqual(second));
Assert.False(first.SequenceEqual(FlipIsCollection(second)));
Assert.False(FlipIsCollection(first).SequenceEqual(FlipIsCollection(second)));
}
[Fact]
public void NullComparer()
{
string[] first = { "Bob", "Tim", "Chris" };
string[] second = { "Bbo", "mTi", "rishC" };
Assert.False(first.SequenceEqual(second, null));
Assert.False(FlipIsCollection(first).SequenceEqual(second, null));
Assert.False(first.SequenceEqual(FlipIsCollection(second), null));
Assert.False(FlipIsCollection(first).SequenceEqual(FlipIsCollection(second), null));
}
[Fact]
public void CustomComparer()
{
string[] first = { "Bob", "Tim", "Chris" };
string[] second = { "Bbo", "mTi", "rishC" };
Assert.True(first.SequenceEqual(second, new AnagramEqualityComparer()));
Assert.True(FlipIsCollection(first).SequenceEqual(second, new AnagramEqualityComparer()));
Assert.True(first.SequenceEqual(FlipIsCollection(second), new AnagramEqualityComparer()));
Assert.True(FlipIsCollection(first).SequenceEqual(FlipIsCollection(second), new AnagramEqualityComparer()));
}
[Fact]
public void BothSingleNullExplicitComparer()
{
string[] first = { null };
string[] second = { null };
Assert.True(first.SequenceEqual(second, StringComparer.Ordinal));
Assert.True(FlipIsCollection(first).SequenceEqual(second, StringComparer.Ordinal));
Assert.True(first.SequenceEqual(FlipIsCollection(second), StringComparer.Ordinal));
Assert.True(FlipIsCollection(first).SequenceEqual(FlipIsCollection(second), StringComparer.Ordinal));
}
[Fact]
public void BothMatchIncludingNullElements()
{
int?[] first = { -6, null, 0, -4, 9, 10, 20 };
int?[] second = { -6, null, 0, -4, 9, 10, 20 };
Assert.True(first.SequenceEqual(second));
Assert.True(FlipIsCollection(first).SequenceEqual(second));
Assert.True(first.SequenceEqual(FlipIsCollection(second)));
Assert.True(FlipIsCollection(first).SequenceEqual(FlipIsCollection(second)));
}
[Fact]
public void EmptyWithNonEmpty()
{
int?[] first = { };
int?[] second = { 2, 3, 4 };
Assert.False(first.SequenceEqual(second));
Assert.False(FlipIsCollection(first).SequenceEqual(second));
Assert.False(first.SequenceEqual(FlipIsCollection(second)));
Assert.False(FlipIsCollection(first).SequenceEqual(FlipIsCollection(second)));
}
[Fact]
public void NonEmptyWithEmpty()
{
int?[] first = { 2, 3, 4 };
int?[] second = { };
Assert.False(first.SequenceEqual(second));
Assert.False(FlipIsCollection(first).SequenceEqual(second));
Assert.False(first.SequenceEqual(FlipIsCollection(second)));
Assert.False(FlipIsCollection(first).SequenceEqual(FlipIsCollection(second)));
}
[Fact]
public void MismatchingSingletons()
{
int?[] first = { 2 };
int?[] second = { 4 };
Assert.False(first.SequenceEqual(second));
Assert.False(FlipIsCollection(first).SequenceEqual(second));
Assert.False(first.SequenceEqual(FlipIsCollection(second)));
Assert.False(FlipIsCollection(first).SequenceEqual(FlipIsCollection(second)));
}
[Fact]
public void MismatchOnFirst()
{
int?[] first = { 1, 2, 3, 4, 5 };
int?[] second = { 2, 2, 3, 4, 5 };
Assert.False(first.SequenceEqual(second));
Assert.False(FlipIsCollection(first).SequenceEqual(second));
Assert.False(first.SequenceEqual(FlipIsCollection(second)));
Assert.False(FlipIsCollection(first).SequenceEqual(FlipIsCollection(second)));
}
[Fact]
public void MismatchOnLast()
{
int?[] first = { 1, 2, 3, 4, 4 };
int?[] second = { 1, 2, 3, 4, 5 };
Assert.False(first.SequenceEqual(second));
Assert.False(FlipIsCollection(first).SequenceEqual(second));
Assert.False(first.SequenceEqual(FlipIsCollection(second)));
Assert.False(FlipIsCollection(first).SequenceEqual(FlipIsCollection(second)));
}
[Fact]
public void SecondLargerThanFirst()
{
int?[] first = { 1, 2, 3, 4 };
int?[] second = { 1, 2, 3, 4, 4 };
Assert.False(first.SequenceEqual(second));
Assert.False(FlipIsCollection(first).SequenceEqual(second));
Assert.False(first.SequenceEqual(FlipIsCollection(second)));
Assert.False(FlipIsCollection(first).SequenceEqual(FlipIsCollection(second)));
}
[Fact]
public void FirstLargerThanSecond()
{
int?[] first = { 1, 2, 3, 4, 4 };
int?[] second = { 1, 2, 3, 4 };
Assert.False(first.SequenceEqual(second));
Assert.False(FlipIsCollection(first).SequenceEqual(second));
Assert.False(first.SequenceEqual(FlipIsCollection(second)));
Assert.False(FlipIsCollection(first).SequenceEqual(FlipIsCollection(second)));
}
[Fact]
public void FirstSourceNull()
{
int[] first = null;
int[] second = { };
Assert.Throws<ArgumentNullException>("first", () => first.SequenceEqual(second));
}
[Fact]
public void SecondSourceNull()
{
int[] first = { };
int[] second = null;
Assert.Throws<ArgumentNullException>("second", () => first.SequenceEqual(second));
}
}
}
| |
using Microsoft.TeamFoundation.DistributedTask.WebApi;
using Microsoft.VisualStudio.Services.Agent.Util;
using Microsoft.VisualStudio.Services.Common;
using Microsoft.VisualStudio.Services.WebApi;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Net.Http;
namespace Microsoft.VisualStudio.Services.Agent.Worker
{
[ServiceLocator(Default = typeof(JobRunner))]
public interface IJobRunner : IAgentService
{
Task<TaskResult> RunAsync(AgentJobRequestMessage message, CancellationToken jobRequestCancellationToken);
}
public sealed class JobRunner : AgentService, IJobRunner
{
private IJobServerQueue _jobServerQueue;
private ITempDirectoryManager _tempDirectoryManager;
public async Task<TaskResult> RunAsync(AgentJobRequestMessage message, CancellationToken jobRequestCancellationToken)
{
// Validate parameters.
Trace.Entering();
ArgUtil.NotNull(message, nameof(message));
ArgUtil.NotNull(message.Environment, nameof(message.Environment));
ArgUtil.NotNull(message.Environment.Variables, nameof(message.Environment.Variables));
ArgUtil.NotNull(message.Tasks, nameof(message.Tasks));
Trace.Info("Job ID {0}", message.JobId);
// Agent.RunMode
RunMode runMode;
if (message.Environment.Variables.ContainsKey(Constants.Variables.Agent.RunMode) &&
Enum.TryParse(message.Environment.Variables[Constants.Variables.Agent.RunMode], ignoreCase: true, result: out runMode) &&
runMode == RunMode.Local)
{
HostContext.RunMode = runMode;
}
// System.AccessToken
if (message.Environment.Variables.ContainsKey(Constants.Variables.System.EnableAccessToken) &&
StringUtil.ConvertToBoolean(message.Environment.Variables[Constants.Variables.System.EnableAccessToken]))
{
// TODO: get access token use Util Method
message.Environment.Variables[Constants.Variables.System.AccessToken] = message.Environment.SystemConnection.Authorization.Parameters["AccessToken"];
}
// Make sure SystemConnection Url and Endpoint Url match Config Url base
ReplaceConfigUriBaseInJobRequestMessage(message);
// Setup the job server and job server queue.
var jobServer = HostContext.GetService<IJobServer>();
VssCredentials jobServerCredential = ApiUtil.GetVssCredential(message.Environment.SystemConnection);
Uri jobServerUrl = message.Environment.SystemConnection.Url;
Trace.Info($"Creating job server with URL: {jobServerUrl}");
// jobServerQueue is the throttling reporter.
_jobServerQueue = HostContext.GetService<IJobServerQueue>();
VssConnection jobConnection = ApiUtil.CreateConnection(jobServerUrl, jobServerCredential, new DelegatingHandler[] { new ThrottlingReportHandler(_jobServerQueue) });
await jobServer.ConnectAsync(jobConnection);
_jobServerQueue.Start(message);
IExecutionContext jobContext = null;
CancellationTokenRegistration? agentShutdownRegistration = null;
try
{
// Create the job execution context.
jobContext = HostContext.CreateService<IExecutionContext>();
jobContext.InitializeJob(message, jobRequestCancellationToken);
Trace.Info("Starting the job execution context.");
jobContext.Start();
jobContext.Section(StringUtil.Loc("StepStarting", message.JobName));
agentShutdownRegistration = HostContext.AgentShutdownToken.Register(() =>
{
// log an issue, then agent get shutdown by Ctrl-C or Ctrl-Break.
// the server will use Ctrl-Break to tells the agent that operating system is shutting down.
string errorMessage;
switch (HostContext.AgentShutdownReason)
{
case ShutdownReason.UserCancelled:
errorMessage = StringUtil.Loc("UserShutdownAgent");
break;
case ShutdownReason.OperatingSystemShutdown:
errorMessage = StringUtil.Loc("OperatingSystemShutdown", Environment.MachineName);
break;
default:
throw new ArgumentException(HostContext.AgentShutdownReason.ToString(), nameof(HostContext.AgentShutdownReason));
}
jobContext.AddIssue(new Issue() { Type = IssueType.Error, Message = errorMessage });
});
// Set agent version variable.
jobContext.Variables.Set(Constants.Variables.Agent.Version, Constants.Agent.Version);
jobContext.Output(StringUtil.Loc("AgentVersion", Constants.Agent.Version));
// Print proxy setting information for better diagnostic experience
var agentWebProxy = HostContext.GetService<IVstsAgentWebProxy>();
if (!string.IsNullOrEmpty(agentWebProxy.ProxyAddress))
{
jobContext.Output(StringUtil.Loc("AgentRunningBehindProxy", agentWebProxy.ProxyAddress));
}
// Validate directory permissions.
string workDirectory = HostContext.GetDirectory(WellKnownDirectory.Work);
Trace.Info($"Validating directory permissions for: '{workDirectory}'");
try
{
Directory.CreateDirectory(workDirectory);
IOUtil.ValidateExecutePermission(workDirectory);
}
catch (Exception ex)
{
Trace.Error(ex);
jobContext.Error(ex);
return await CompleteJobAsync(jobServer, jobContext, message, TaskResult.Failed);
}
// Set agent variables.
AgentSettings settings = HostContext.GetService<IConfigurationStore>().GetSettings();
jobContext.Variables.Set(Constants.Variables.Agent.Id, settings.AgentId.ToString(CultureInfo.InvariantCulture));
jobContext.Variables.Set(Constants.Variables.Agent.HomeDirectory, IOUtil.GetRootPath());
jobContext.Variables.Set(Constants.Variables.Agent.JobName, message.JobName);
jobContext.Variables.Set(Constants.Variables.Agent.MachineName, Environment.MachineName);
jobContext.Variables.Set(Constants.Variables.Agent.Name, settings.AgentName);
jobContext.Variables.Set(Constants.Variables.Agent.OS, VarUtil.OS);
jobContext.Variables.Set(Constants.Variables.Agent.RootDirectory, IOUtil.GetWorkPath(HostContext));
#if OS_WINDOWS
jobContext.Variables.Set(Constants.Variables.Agent.ServerOMDirectory, Path.Combine(IOUtil.GetExternalsPath(), Constants.Path.ServerOMDirectory));
#endif
jobContext.Variables.Set(Constants.Variables.Agent.WorkFolder, IOUtil.GetWorkPath(HostContext));
jobContext.Variables.Set(Constants.Variables.System.WorkFolder, IOUtil.GetWorkPath(HostContext));
if (string.IsNullOrEmpty(Environment.GetEnvironmentVariable("AGENT_TOOLSDIRECTORY")))
{
string toolsDirectory = Path.Combine(HostContext.GetDirectory(WellKnownDirectory.Work), Constants.Path.ToolDirectory);
Directory.CreateDirectory(toolsDirectory);
jobContext.Variables.Set(Constants.Variables.Agent.ToolsDirectory, toolsDirectory);
}
// Setup TEMP directories
_tempDirectoryManager = HostContext.GetService<ITempDirectoryManager>();
_tempDirectoryManager.InitializeTempDirectory(jobContext);
// todo: task server can throw. try/catch and fail job gracefully.
// prefer task definitions url, then TFS collection url, then TFS account url
var taskServer = HostContext.GetService<ITaskServer>();
Uri taskServerUri = null;
if (!string.IsNullOrEmpty(jobContext.Variables.System_TaskDefinitionsUri))
{
taskServerUri = new Uri(jobContext.Variables.System_TaskDefinitionsUri);
}
else if (!string.IsNullOrEmpty(jobContext.Variables.System_TFCollectionUrl))
{
taskServerUri = new Uri(jobContext.Variables.System_TFCollectionUrl);
}
var taskServerCredential = ApiUtil.GetVssCredential(message.Environment.SystemConnection);
if (taskServerUri != null)
{
Trace.Info($"Creating task server with {taskServerUri}");
await taskServer.ConnectAsync(ApiUtil.CreateConnection(taskServerUri, taskServerCredential));
}
if (taskServerUri == null || !await taskServer.TaskDefinitionEndpointExist())
{
Trace.Info($"Can't determine task download url from JobMessage or the endpoint doesn't exist.");
var configStore = HostContext.GetService<IConfigurationStore>();
taskServerUri = new Uri(configStore.GetSettings().ServerUrl);
Trace.Info($"Recreate task server with configuration server url: {taskServerUri}");
await taskServer.ConnectAsync(ApiUtil.CreateConnection(taskServerUri, taskServerCredential));
}
// Expand the endpoint data values.
foreach (ServiceEndpoint endpoint in jobContext.Endpoints)
{
jobContext.Variables.ExpandValues(target: endpoint.Data);
VarUtil.ExpandEnvironmentVariables(HostContext, target: endpoint.Data);
}
// Get the job extension.
Trace.Info("Getting job extension.");
var hostType = jobContext.Variables.System_HostType;
var extensionManager = HostContext.GetService<IExtensionManager>();
// We should always have one job extension
IJobExtension jobExtension =
(extensionManager.GetExtensions<IJobExtension>() ?? new List<IJobExtension>())
.Where(x => x.HostType.HasFlag(hostType))
.FirstOrDefault();
ArgUtil.NotNull(jobExtension, nameof(jobExtension));
IEnumerable<IStep> preJobSteps = new List<IStep>();
IEnumerable<IStep> jobSteps = new List<IStep>();
IEnumerable<IStep> postJobSteps = new List<IStep>();
try
{
Trace.Info("Initialize job. Getting all job steps.");
var initializeResult = await jobExtension.InitializeJob(jobContext, message);
IStepsQueue stepsQueue = new StepsQueue(HostContext, jobContext, initializeResult);
preJobSteps = stepsQueue.GetPreJobSteps();
jobSteps = stepsQueue.GetJobSteps();
postJobSteps = stepsQueue.GetPostJobSteps();
}
catch (OperationCanceledException ex) when (jobContext.CancellationToken.IsCancellationRequested)
{
// set the job to canceled
// don't log error issue to job ExecutionContext, since server owns the job level issue
Trace.Error($"Job is canceled during initialize.");
Trace.Error($"Caught exception: {ex}");
return await CompleteJobAsync(jobServer, jobContext, message, TaskResult.Canceled);
}
catch (Exception ex)
{
// set the job to failed.
// don't log error issue to job ExecutionContext, since server owns the job level issue
Trace.Error($"Job initialize failed.");
Trace.Error($"Caught exception from {nameof(jobExtension.InitializeJob)}: {ex}");
return await CompleteJobAsync(jobServer, jobContext, message, TaskResult.Failed);
}
// Run all pre job steps
// All pre job steps are critical to the job
// Stop execution on any step failure or cancelled
Trace.Info("Run all pre-job steps.");
var stepsRunner = HostContext.GetService<IStepsRunner>();
try
{
await stepsRunner.RunAsync(jobContext, preJobSteps, JobRunStage.PreJob);
}
catch (Exception ex)
{
// StepRunner should never throw exception out.
// End up here mean there is a bug in StepRunner
// Log the error and fail the job.
Trace.Error($"Caught exception from pre-job steps {nameof(StepsRunner)}: {ex}");
jobContext.Error(ex);
return await CompleteJobAsync(jobServer, jobContext, message, TaskResult.Failed);
}
Trace.Info($"Job result after all pre-job steps finish: {jobContext.Result}");
// Base on the Job result after all pre-job steps finish.
// Run all job steps only if the job result is still Succeeded or SucceededWithIssues
if (jobContext.Result == null ||
jobContext.Result == TaskResult.Succeeded ||
jobContext.Result == TaskResult.SucceededWithIssues)
{
Trace.Info("Run all job steps.");
try
{
await stepsRunner.RunAsync(jobContext, jobSteps, JobRunStage.Main);
}
catch (Exception ex)
{
// StepRunner should never throw exception out.
// End up here mean there is a bug in StepRunner
// Log the error and fail the job.
Trace.Error($"Caught exception from job steps {nameof(StepsRunner)}: {ex}");
jobContext.Error(ex);
return await CompleteJobAsync(jobServer, jobContext, message, TaskResult.Failed);
}
}
else
{
Trace.Info("Skip all job steps due to pre-job step failure.");
foreach (var step in jobSteps)
{
step.ExecutionContext.Start();
step.ExecutionContext.Complete(TaskResult.Skipped);
}
}
Trace.Info($"Job result after all job steps finish: {jobContext.Result}");
// Always run all post job steps
// step might not run base on it's own condition.
Trace.Info("Run all post-job steps.");
try
{
await stepsRunner.RunAsync(jobContext, postJobSteps, JobRunStage.PostJob);
}
catch (Exception ex)
{
// StepRunner should never throw exception out.
// End up here mean there is a bug in StepRunner
// Log the error and fail the job.
Trace.Error($"Caught exception from post-job steps {nameof(StepsRunner)}: {ex}");
jobContext.Error(ex);
return await CompleteJobAsync(jobServer, jobContext, message, TaskResult.Failed);
}
Trace.Info($"Job result after all post-job steps finish: {jobContext.Result}");
// Complete the job.
Trace.Info("Completing the job execution context.");
return await CompleteJobAsync(jobServer, jobContext, message);
}
finally
{
if (agentShutdownRegistration != null)
{
agentShutdownRegistration.Value.Dispose();
agentShutdownRegistration = null;
}
await ShutdownQueue(throwOnFailure: false);
}
}
private async Task<TaskResult> CompleteJobAsync(IJobServer jobServer, IExecutionContext jobContext, AgentJobRequestMessage message, TaskResult? taskResult = null)
{
// Clean TEMP.
_tempDirectoryManager?.CleanupTempDirectory(jobContext);
jobContext.Section(StringUtil.Loc("StepFinishing", message.JobName));
TaskResult result = jobContext.Complete(taskResult);
try
{
await ShutdownQueue(throwOnFailure: true);
}
catch (Exception ex)
{
Trace.Error($"Caught exception from {nameof(JobServerQueue)}.{nameof(_jobServerQueue.ShutdownAsync)}");
Trace.Error("This indicate a failure during publish output variables. Fail the job to prevent unexpected job outputs.");
Trace.Error(ex);
result = TaskResultUtil.MergeTaskResults(result, TaskResult.Failed);
}
if (!jobContext.Features.HasFlag(PlanFeatures.JobCompletedPlanEvent))
{
Trace.Info($"Skip raise job completed event call from worker because Plan version is {message.Plan.Version}");
return result;
}
Trace.Info("Raising job completed event.");
var jobCompletedEvent = new JobCompletedEvent(message.RequestId, message.JobId, result);
var completeJobRetryLimit = 5;
var exceptions = new List<Exception>();
while (completeJobRetryLimit-- > 0)
{
try
{
await jobServer.RaisePlanEventAsync(message.Plan.ScopeIdentifier, message.Plan.PlanType, message.Plan.PlanId, jobCompletedEvent, default(CancellationToken));
return result;
}
catch (TaskOrchestrationPlanNotFoundException ex)
{
Trace.Error($"TaskOrchestrationPlanNotFoundException received, while attempting to raise JobCompletedEvent for job {message.JobId}.");
Trace.Error(ex);
return TaskResult.Failed;
}
catch (TaskOrchestrationPlanSecurityException ex)
{
Trace.Error($"TaskOrchestrationPlanSecurityException received, while attempting to raise JobCompletedEvent for job {message.JobId}.");
Trace.Error(ex);
return TaskResult.Failed;
}
catch (Exception ex)
{
Trace.Error($"Catch exception while attempting to raise JobCompletedEvent for job {message.JobId}, job request {message.RequestId}.");
Trace.Error(ex);
exceptions.Add(ex);
}
// delay 5 seconds before next retry.
await Task.Delay(TimeSpan.FromSeconds(5));
}
// rethrow exceptions from all attempts.
throw new AggregateException(exceptions);
}
private async Task ShutdownQueue(bool throwOnFailure)
{
if (_jobServerQueue != null)
{
try
{
Trace.Info("Shutting down the job server queue.");
await _jobServerQueue.ShutdownAsync();
}
catch (Exception ex) when (!throwOnFailure)
{
Trace.Error($"Caught exception from {nameof(JobServerQueue)}.{nameof(_jobServerQueue.ShutdownAsync)}");
Trace.Error(ex);
}
finally
{
_jobServerQueue = null; // Prevent multiple attempts.
}
}
}
// the scheme://hostname:port (how the agent knows the server) is external to our server
// in other words, an agent may have it's own way (DNS, hostname) of refering
// to the server. it owns that. That's the scheme://hostname:port we will use.
// Example: Server's notification url is http://tfsserver:8080/tfs
// Agent config url is https://tfsserver.mycompany.com:9090/tfs
private Uri ReplaceWithConfigUriBase(Uri messageUri)
{
AgentSettings settings = HostContext.GetService<IConfigurationStore>().GetSettings();
try
{
if (UrlUtil.IsHosted(messageUri.AbsoluteUri))
{
// If messageUri is hosted service URL, return the messageUri as it is.
return messageUri;
}
Uri result = null;
Uri configUri = new Uri(settings.ServerUrl);
if (Uri.TryCreate(new Uri(configUri.GetComponents(UriComponents.SchemeAndServer, UriFormat.Unescaped)), messageUri.PathAndQuery, out result))
{
//replace the schema and host portion of messageUri with the host from the
//server URI (which was set at config time)
return result;
}
}
catch (InvalidOperationException ex)
{
//cannot parse the Uri - not a fatal error
Trace.Error(ex);
}
catch (UriFormatException ex)
{
//cannot parse the Uri - not a fatal error
Trace.Error(ex);
}
return messageUri;
}
private void ReplaceConfigUriBaseInJobRequestMessage(AgentJobRequestMessage message)
{
// fixup any endpoint Url that match SystemConnect server.
foreach (var endpoint in message.Environment.Endpoints)
{
if (Uri.Compare(endpoint.Url, message.Environment.SystemConnection.Url, UriComponents.SchemeAndServer, UriFormat.Unescaped, StringComparison.OrdinalIgnoreCase) == 0)
{
endpoint.Url = ReplaceWithConfigUriBase(endpoint.Url);
Trace.Info($"Ensure endpoint url match config url base. {endpoint.Url}");
}
}
// fixup well known variables. (taskDefinitionsUrl, tfsServerUrl, tfsCollectionUrl)
if (message.Environment.Variables.ContainsKey(WellKnownDistributedTaskVariables.TaskDefinitionsUrl))
{
string taskDefinitionsUrl = message.Environment.Variables[WellKnownDistributedTaskVariables.TaskDefinitionsUrl];
message.Environment.Variables[WellKnownDistributedTaskVariables.TaskDefinitionsUrl] = ReplaceWithConfigUriBase(new Uri(taskDefinitionsUrl)).AbsoluteUri;
Trace.Info($"Ensure System.TaskDefinitionsUrl match config url base. {message.Environment.Variables[WellKnownDistributedTaskVariables.TaskDefinitionsUrl]}");
}
if (message.Environment.Variables.ContainsKey(WellKnownDistributedTaskVariables.TFCollectionUrl))
{
string tfsCollectionUrl = message.Environment.Variables[WellKnownDistributedTaskVariables.TFCollectionUrl];
message.Environment.Variables[WellKnownDistributedTaskVariables.TFCollectionUrl] = ReplaceWithConfigUriBase(new Uri(tfsCollectionUrl)).AbsoluteUri;
Trace.Info($"Ensure System.TFCollectionUrl match config url base. {message.Environment.Variables[WellKnownDistributedTaskVariables.TFCollectionUrl]}");
}
// fixup SystemConnection Url
message.Environment.SystemConnection.Url = ReplaceWithConfigUriBase(message.Environment.SystemConnection.Url);
Trace.Info($"Ensure SystemConnection url match config url base. {message.Environment.SystemConnection.Url}");
// back compat server url
message.Environment.Variables[Constants.Variables.System.TFServerUrl] = message.Environment.SystemConnection.Url.AbsoluteUri;
Trace.Info($"Ensure System.TFServerUrl match config url base. {message.Environment.SystemConnection.Url.AbsoluteUri}");
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using Microsoft.Research.DataStructures;
namespace Microsoft.Research.CodeAnalysis
{
using Provenance = IEnumerable<ProofObligation>;
using System.Diagnostics.CodeAnalysis;
public class BasicAnalysisDriver<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, LogOptions>
: IBasicAnalysisDriver<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, LogOptions>
where LogOptions : IFrameworkLogOptions
where Type : IEquatable<Type>
{
#region Protected
protected readonly LogOptions options;
protected readonly IOutput output;
protected readonly MethodCache<Local, Parameter, Type, Method, Field, Property, Event, Attribute, Assembly> methodCache;
protected readonly IDecodeMetaData<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly> mdDecoder;
protected readonly IDecodeContracts<Local, Parameter, Method, Field, Type> contractDecoder;
#endregion
[ContractInvariantMethod]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Justification = "Required for code contracts.")]
private void ObjectInvariant()
{
Contract.Invariant(this.options != null);
}
public BasicAnalysisDriver(
IDecodeMetaData<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly> mdDecoder,
IDecodeContracts<Local, Parameter, Method, Field, Type> contractDecoder,
IOutput output,
LogOptions options
)
{
Contract.Requires(mdDecoder != null);
Contract.Requires(contractDecoder != null);
Contract.Requires(output != null);
Contract.Requires(options != null);
this.methodCache = new MethodCache<Local, Parameter, Type, Method, Field, Property, Event, Attribute, Assembly>(mdDecoder, contractDecoder, output.WriteLine);
this.mdDecoder = mdDecoder;
this.contractDecoder = contractDecoder;
this.output = output;
this.options = options;
}
public LogOptions Options { get { return this.options; } }
public MethodCache<Local, Parameter, Type, Method, Field, Property, Event, Attribute, Assembly> MethodCache { get { return this.methodCache; } }
public IDecodeMetaData<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly> MetaDataDecoder { get { return this.mdDecoder; } }
public IDecodeContracts<Local, Parameter, Method, Field, Type> ContractDecoder { get { return this.contractDecoder; } }
public IOutput Output { get { return this.output; } }
//public abstract IBasicMethodDriver<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, LogOptions> BasicMethodDriver(Method method);
}
public abstract class AnalysisDriver<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Expression, Variable, LogOptions, MethodResult>
: IBasicAnalysisDriver<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, LogOptions>
where LogOptions : IFrameworkLogOptions
where Type : IEquatable<Type>
{
#region Invariant
[ContractInvariantMethod]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Justification = "Required for code contracts.")]
private void ObjectInvariant()
{
Contract.Invariant(this.mCDrivers != null);
}
#endregion
#region Protected
// public (anyone can register a contract for pretty output, or ask for them)
protected readonly OutputPrettyCS.ContractsHandlerMgr<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Expression, Variable, LogOptions, MethodResult> mContractsHandlerMgr;
public OutputPrettyCS.ContractsHandlerMgr<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Expression, Variable, LogOptions, MethodResult> ContractsHandlerManager { get { return this.mContractsHandlerMgr; } }
protected readonly Dictionary<Type, WeakReference> mCDrivers;
protected int mMaxClassDriversCount;
/// class drivers actually stored (ie. non-null in the map, so != mCDrivers.Count)
protected int mCDriversCount
{
get
{
return this.mCDrivers.Where(pair => pair.Value != null && pair.Value.IsAlive).Count();
}
}
protected IBasicAnalysisDriver<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, LogOptions> basicDriver;
#endregion
protected AnalysisDriver(
IBasicAnalysisDriver<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, LogOptions> basicDriver
)
{
this.basicDriver = basicDriver;
this.mContractsHandlerMgr = new OutputPrettyCS.ContractsHandlerMgr<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Expression, Variable, LogOptions, MethodResult>(this, this.Output);
this.mCDrivers = new Dictionary<Type, WeakReference>();
this.mMaxClassDriversCount = 0;
}
public void InstallPostconditions(List<BoxedExpression.AssertExpression> inferredPostconditions, Method method)
{
Contract.Requires(inferredPostconditions != null);
if (inferredPostconditions.Count == 0) return;
//this.Output.WriteLine("Trying to install {0} inferred postconditions.", inferredPostconditions.Count);
// Ordering by ToString should avoid in most of the cases the non-determinism problem we have
// when the order of inferred post conditions changes, causing the hash to change in the caching.
var ordered = inferredPostconditions.OrderBy(post => post.ToString()).ToList();
var seq = BoxedExpression.Sequence(ordered.Cast<BoxedExpression>());
BoxedExpression.PC postStart = new BoxedExpression.PC(seq, 0);
bool result = this.MethodCache.AddPostCondition(method, postStart, ClousotExpressionCodeProvider<Local, Parameter, Method, Field, Type>.Decoder);
if (result)
{
foreach (var post in ordered)
{
this.mContractsHandlerMgr.RegisterMethodPostCondition(method, post.Condition);
}
}
}
public void InstallPreconditions(List<BoxedExpression.AssumeExpression> inferredPreconditions, Method method)
{
Contract.Requires(inferredPreconditions != null);
if (inferredPreconditions.Count == 0) return;
//this.Output.WriteLine("Trying to install {0} inferred preconditions.", inferredPreconditions.Count);
// Ordering by ToString should avoid in most of the cases the non-determinism problem we have
// when the order of inferred pre conditions changes, causing the hash to change in the caching.
var ordered = inferredPreconditions.OrderBy(pre => pre.ToString()).ToList();
var seq = BoxedExpression.Sequence(ordered.Cast<BoxedExpression>());
BoxedExpression.PC preStart = new BoxedExpression.PC(seq, 0);
if (this.MethodCache.AddPreCondition(method, preStart, ClousotExpressionCodeProvider<Local, Parameter, Method, Field, Type>.Decoder))
{
foreach (var pre in ordered)
{
this.mContractsHandlerMgr.RegisterMethodPreCondition(method, pre.Condition);
}
}
}
public void InstallObjectInvariants(List<BoxedExpression> objectInvariants, Type type)
{
Contract.Requires(objectInvariants != null);
if (objectInvariants.Count == 0)
{
return;
}
// Ordering by ToString should avoid in most of the cases the non-determinism problem we have
// when the order of inferred invariants, causing the hash to change in the caching.
var ordered = objectInvariants.OrderBy(inv => inv.ToString()).ToList();
// TODO: COMMENT
Console.WriteLine("Installing the object invariants");
foreach (var e in ordered)
{
Console.WriteLine(" {0}", e);
}
// END TODO
var seq = BoxedExpression.Sequence(ordered);
var pc = new BoxedExpression.PC(seq, 0);
if (this.MethodCache.AddInvariant(type, pc, ClousotExpressionCodeProvider<Local, Parameter, Method, Field, Type>.Decoder))
{
foreach (var inv in ordered)
{
this.mContractsHandlerMgr.RegisterClassInvariant(type, inv);
}
}
}
/// <summary>
/// Responsibility to make sure the assume can be properly decoded lies with the serializer/deserializer.
/// The SER/DES should have enough detail and checks to make sure a deserialized expression can be decoded without
/// failing due to stack mismatch or failed type assumptions.
/// </summary>
public void InstallCalleeAssumes(ICFG cfg, IEnumerable<Pair<BoxedExpression, Method>> inferredAssumes, Method method)
{
Contract.Requires(inferredAssumes != null);
#if false
if (!inferredAssumes.Any())
return;
//this.Output.WriteLine("Trying to install {0} inferred assumes.", inferredAssumes.Count);
// We lookup by name
var locs = this.MetaDataDecoder.Locals(method).Enumerate().Select(local => this.MetaDataDecoder.Name(local));
var paramz = this.MetaDataDecoder.Parameters(method).Enumerate().Select(parameter => this.MetaDataDecoder.Name(parameter));
var fields = this.MetaDataDecoder.Fields(this.MetaDataDecoder.DeclaringType(method)).Select(m => this.MetaDataDecoder.Name(method));
#endif
// TODO: can the name / expr matching get mixed up during deserialization?
foreach (var inferredAssume in inferredAssumes)
{
var assume = inferredAssume.One;
//this.Output.WriteLine("Installing assume " + assume);
#if false
#region Ensure that all var's in the assume expression still exist in the new version of the function
// Check that the variables appearing in the assume to install exists in the scope.
// We use the name of the variables to make sure they are the same variable
var foundAllVariables = assume.Variables().TrueForAll(v =>
{
var vToString = v.ToString();
// check for var in locs
var found = locs.Any(loc => vToString == loc);
// check for var in params
found = found || paramz.Any(param => vToString == param);
//string paramStr = this.MetaDataDecoder.ParameterType(paramz[j]) + " " + v.ToString(); // create str with same format as parameter string; hacky, but needed
// check for var in fields
found = found || fields.Any(fName =>
{
return vToString == fName // "normal" case
|| vToString == String.Format("this.{0}", fName); // case where field prefixed with "this"
});
return found;
});
if (!foundAllVariables)
{
continue;
}
#endregion
// found all locals, going to try to install this assume
#endif
var dummyAPC = cfg.Entry; // TODO: do something better here! we don't know the APC yet, so we just pick some legitimate APC to avoid null ptr deref when looking up src context
Provenance provenance = null;
var be = new BoxedExpression.AssumeExpression(assume, "assume", dummyAPC, provenance, assume.ToString<Type>(type => OutputPrettyCS.TypeHelper.TypeFullName(this.MetaDataDecoder, type)));
var pc = new BoxedExpression.PC(be, 0);
var calleeName = inferredAssume.Two;
this.MethodCache.AddCalleeAssumeAsPostCondition(cfg, method, calleeName, pc, ClousotExpressionCodeProvider<Local, Parameter, Method, Field, Type>.Decoder);
}
}
public void InstallEntryAssumes(ICFG cfg, IEnumerable<Pair<BoxedExpression, Method>> inferredAssumes, Method method)
{
Contract.Requires(inferredAssumes != null);
foreach (var inferredAssume in inferredAssumes)
{
var assume = inferredAssume.One;
var dummyAPC = cfg.Entry; // TODO: do something better here! we don't know the APC yet, so we just pick some legitimate APC to avoid null ptr deref when looking up src context
Provenance provenance = null;
var be = new BoxedExpression.AssumeExpression(assume, "assume", dummyAPC, provenance, assume.ToString<Type>(type => OutputPrettyCS.TypeHelper.TypeFullName(this.MetaDataDecoder, type)));
var pc = new BoxedExpression.PC(be, 0);
this.MethodCache.AddEntryAssume(cfg, method, pc, ClousotExpressionCodeProvider<Local, Parameter, Method, Field, Type>.Decoder);
}
}
public void RemoveInferredPrecondition(Method method)
{
this.MethodCache.RemovePreCondition(method);
}
public void RemoveContractsFor(Method method)
{
this.MethodCache.RemoveContractsFor(method);
}
public abstract IMethodDriver<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Expression, Variable, LogOptions> MethodDriver(
Method method,
IClassDriver<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Expression, Variable, LogOptions, MethodResult> classDriver,
bool removeInferredPrecondition = false);
#region Class driver
public IClassDriver<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Expression, Variable, LogOptions, MethodResult> ClassDriver(Type type, bool inferInvariantsJustForReadonlyFields = true)
{
WeakReference reference;
CDriver result;
if (mCDrivers.TryGetValue(type, out reference) && reference != null && reference.IsAlive)
{
result = reference.Target as CDriver;
return result;
}
else
{
if (!inferInvariantsJustForReadonlyFields || this.MetaDataDecoder.Fields(type).Where(this.MetaDataDecoder.IsReadonly).Any())
{
var cd = new CDriver(this, MetaDataDecoder, type);
mCDrivers[type] = new WeakReference(cd);
this.mMaxClassDriversCount = Math.Max(mCDriversCount, this.mMaxClassDriversCount);
#if DEBUG && false
var old = Console.ForegroundColor;
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("-- ADD CLASS DRIVER -- Max Class Drivers Count is: {0} ; class drivers count is: {1}", this.mMaxClassDriversCount, mCDriversCount); // DEBUG
Console.ForegroundColor = old;
#endif
return cd;
}
else
{
#if DEBUG && false
this.Output.WriteLine("The type {0} does not contain any readonly field. As a consequence we do not need a class driver", MetaDataDecoder.Name(type));
#endif
return null;
}
}
}
public int MaxClassDriversCount { get { return mMaxClassDriversCount; } }
public void RemoveClassDriver(IClassDriver<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Expression, Variable, LogOptions, MethodResult> cdriver)
{
Contract.Requires(cdriver != null);
mCDrivers[cdriver.ClassType] = null; // don't need the class driver anymore, but don't need to actually rebuild it anymore either
#if DEBUG && false
ConsoleColor old = Console.ForegroundColor; // DEBUG
Console.ForegroundColor = ConsoleColor.Yellow; // DEBUG
Console.WriteLine("-- REMOVE CLASS DRIVER -- Max Class Drivers Count is: {0} ; class drivers count is: {1}", this.mMaxClassDriversCount, mCDriversCount); // DEBUG
Console.ForegroundColor = old; // DEBUG
#endif
}
#endregion
///////////////////////////////////////////
// CDriver
///////////////////////////////////////////
protected class CDriver : IClassDriver<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Expression, Variable, LogOptions, MethodResult>
{
#region Privates
public IDecodeMetaData<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly> MetaDataDecoder { get; private set; }
public Type ClassType { get; private set; }
public LogOptions Options { get; private set; }
private List<BoxedExpression> mInvariants;
#if false
private List<WeakReference> weakConstructors; // weak references to Method
#endif
public List<Method> Constructors { get; private set; }
#if false
private readonly Dictionary<Method, MethodInfo> mConstructorsInfo;
#endif
private int mMethodsCount;
private int mAnalyzedMethodsCount;
/// <summary>
/// Stores all the information about the analysis of each the class method
/// </summary>
private readonly Dictionary<Method, MethodAnalysisStatus> mMass;
public IConstructorsAnalysisStatus<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Expression, Variable, LogOptions, MethodResult> ConstructorsStatus { get; private set; }
#endregion
public CDriver(AnalysisDriver<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Expression, Variable, LogOptions, MethodResult> parent, IDecodeMetaData<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly> mdDecoder, Type type)
{
Contract.Requires(mdDecoder != null);
this.ParentDriver = parent;
this.MetaDataDecoder = mdDecoder;
mInvariants = new List<BoxedExpression>();
this.ClassType = type;
var nonStaticMethods = mdDecoder.Methods(type).Where(m => !mdDecoder.IsStatic(m));
mMethodsCount = nonStaticMethods.Count();
this.Constructors = nonStaticMethods.Where(mdDecoder.IsConstructor).ToList();
var constructorsCount = this.Constructors.Count();
mAnalyzedMethodsCount = 0;
#if false
mConstructorsInfo = new Dictionary<Method, MethodInfo>(capacity: constructorsCount);
#endif
this.ConstructorsStatus = new ConstructorsAnalysisStatus(type, constructorsCount);
mMass = new Dictionary<Method, AnalysisDriver<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Expression, Variable, LogOptions, MethodResult>.MethodAnalysisStatus>();
}
public AnalysisDriver<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Expression, Variable, LogOptions, MethodResult> ParentDriver { get; private set; }
#if false
public List<Method> Constructors
{
get
{
List<Method> result = new List<Method>();
if (weakConstructors != null)
{
foreach (var wm in weakConstructors)
{
var m = wm.Target;
if (m == null)
break;
result.Add((Method)m);
}
if (result.Count == weakConstructors.Count)
return result;
weakConstructors.Clear();
}
else
{
weakConstructors = new List<WeakReference>();
}
result.Clear();
foreach (var m in this.MetaDataDecoder.Methods(this.ClassType))
if (this.MetaDataDecoder.IsConstructor(m) && !this.MetaDataDecoder.IsStatic(m))
{
result.Add(m);
weakConstructors.Add(new WeakReference(m));
}
return result;
}
}
#endif
public bool IsExistingInvariant(string invariantString)
{
foreach (var be in mInvariants)
{
if (be.ToString() == invariantString)
return true;
}
return false;
}
public bool AddInvariant(BoxedExpression boxedExpression)
{
if (CanAddInvariants() && !IsExistingInvariant(boxedExpression.ToString()))
{
mInvariants.Add(boxedExpression);
return true;
}
return false;
}
public bool CanAddInvariants()
{
return MetaDataDecoder.IsClass(ClassType);
}
public bool InstallInvariantsAsConstructorPostconditions(Parameter methodThis, IEnumerable<Pair<BoxedExpression, Provenance>> boxedExpressions, Method method)
{
if (boxedExpressions == null)
return false;
var beArray = boxedExpressions.ToArray();
if (beArray.Length == 0)
return true;
var result = true;
foreach (var constructor in this.Constructors)
{
var ctorThis = this.MetaDataDecoder.This(constructor);
var pc = this.NormalExitPC(constructor);
// We need to replace any 'this' occuring in the expression by the 'this' of the constructor
var postConditions = beArray
.Select(be =>
{
var exp = this.SubstituteThis(be.One, methodThis, ctorThis);
var definingMethod = this.MetaDataDecoder.Name(method);
return new BoxedExpression.AssertExpression(exp, "invariant", pc, be.Two ?? new List<ProofObligation>() { new FakeProofObligationForAssertionFromTheCache(be.One, definingMethod, null) },
exp.ToString<Type>(type => OutputPrettyCS.TypeHelper.TypeFullName(this.MetaDataDecoder, type)));
}) // We use trick or returning a non-empty proof obligation to signal that the assertion has been inferred, even if we lost the context
.ToList();
// var postConditions = beArray.Select(be => new BoxedExpression.AssertExpression(this.SubstituteThis(be.One, methodThis, ctorThis), "ensures", pc, be.Two)).ToList();
this.ParentDriver.InstallPostconditions(postConditions, constructor);
}
return result;
}
[SuppressMessage("Microsoft.Contracts", "TestAlwaysEvaluatingToAConstant", Justification = "Bug in Clousot")]
private PathElement[] SubstituteThis(PathElement[] path, Parameter from, Parameter to)
{
PathElement[] result = null;
for (int i = 0; i < path.Length; i++)
{
var pathElement = path[i];
Contract.Assume(pathElement != null);
var subst = pathElement.SubstituteElement(from, to);
if (subst != pathElement)
{
if (result == null)
path.CopyTo(result = new PathElement[path.Length], 0);
result[i] = subst;
}
}
return result ?? path;
}
private BoxedExpression SubstituteThis(BoxedExpression be, Parameter from, Parameter to)
{
return be.Substitute<object>((_, variableExpression) =>
{
var accessPath = SubstituteThis(variableExpression.AccessPath, from, to);
if (accessPath == variableExpression.AccessPath)
return variableExpression;
BoxedExpression writableBytes;
object type;
if (!variableExpression.TryGetType(out type))
type = null;
if (variableExpression.TryGetAssociatedInfo(AssociatedInfo.WritableBytes, out writableBytes))
return new BoxedExpression.VariableExpression(variableExpression.UnderlyingVariable, accessPath, writableBytes, type);
return new BoxedExpression.VariableExpression(variableExpression.UnderlyingVariable, accessPath, type);
});
}
public void MethodHasBeenAnalyzed(
string analyze_name,
MethodResult result,
Method method)
{
MethodAnalysisStatus mas;
if (!mMass.TryGetValue(method, out mas))
{
mas = new MethodAnalysisStatus(method);
mMass.Add(method, mas);
}
else
{
Contract.Assume(mas != null);
}
mas.AddMethodResult(analyze_name, result);
}
public void MethodHasBeenFullyAnalyzed(Method method)
{
var isStatic = this.MetaDataDecoder.IsStatic(method);
var isConstructor = this.MetaDataDecoder.IsConstructor(method) && !isStatic;
if (!isStatic)
mAnalyzedMethodsCount++;
if (!mMass.ContainsKey(method))
return; // don't have any info about this method! shouldn't happen
if (isConstructor)
ConstructorsStatus.ConstructorAnalyzed(mMass[method]);
}
#if false
class MethodInfo
{
public readonly APC NormalExit;
public readonly PathElement This;
public MethodInfo(IMethodDriver<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Expression, Variable, LogOptions> mdriver)
{
Contract.Requires(mdriver != null);
this.NormalExit = mdriver.CFG.NormalExit;
var entryAfterRequires = mdriver.CFG.EntryAfterRequires;
var parameterThis = mdriver.MetaDataDecoder.This(mdriver.CurrentMethod);
Variable symbolicThis;
if (mdriver.Context.ValueContext.TryParameterValue(entryAfterRequires, parameterThis, out symbolicThis))
{
var pathThis = mdriver.Context.ValueContext.AccessPathList(mdriver.CFG.EntryAfterRequires, symbolicThis, false, false);
if (pathThis != null)
this.This = pathThis.Head;
}
}
}
#endif
private APC NormalExitPC(Method method)
{
var cfg = this.ParentDriver.MethodCache.GetCFG(method);
return cfg.NormalExit;
}
#if false
private MethodInfo GetConstructorInfo(Method method)
{
MethodInfo result;
if (mConstructorsInfo.TryGetValue(method, out result))
return result;
var mdriver = this.ParentDriver.MethodDriver(method, this);
mdriver.RunHeapAndExpressionAnalyses();
result = new MethodInfo(mdriver);
mConstructorsInfo.Add(method, result);
return result;
}
#endif
public int PendingConstructors { get { return ConstructorsStatus.Pending; } }
public bool IsClassFullyAnalyzed()
{
return mAnalyzedMethodsCount == mMethodsCount;
}
}
public class ConstructorsAnalysisStatus
: IConstructorsAnalysisStatus<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Expression, Variable, LogOptions, MethodResult>
{
[ContractInvariantMethod]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Justification = "Required for code contracts.")]
private void ObjectInvariant()
{
Contract.Invariant(this.AnalysesResults != null);
}
public ConstructorsAnalysisStatus(Type type, int totalnb)
{
this.ClassType = type;
Pending = totalnb;
TotalNb = totalnb;
AnalysesResults = new Dictionary<Method, IMethodAnalysisStatus<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Expression, Variable, LogOptions, MethodResult>>();
}
/// <summary>
/// Decrease the count of pending constructors to analyze by one
/// </summary>
/// <returns>The new pending count (maybe 0)</returns>
private int DecreasePendingCount()
{
return --Pending;
}
public void ConstructorAnalyzed(IMethodAnalysisStatus<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Expression, Variable, LogOptions, MethodResult> mas)
{
if (!AnalysesResults.ContainsKey(mas.MethodObj)) // protect in case we analyze twice the same method
{
AnalysesResults.Add(mas.MethodObj, mas);
DecreasePendingCount(); // a constructor was analyzed
}
}
public Type ClassType { get; private set; }
public int Pending { get; private set; } /// number of constructors left to analyze before starting the ObjectInvariant analysis
public int TotalNb { get; private set; } /// total number of constructors for this type
public Dictionary<Method, IMethodAnalysisStatus<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Expression, Variable, LogOptions, MethodResult>> AnalysesResults { get; private set; }
}
public class MethodAnalysisStatus
: IMethodAnalysisStatus<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Expression, Variable, LogOptions, MethodResult>
{
#region Object invariant
[ContractInvariantMethod]
private void ObjectInvariant()
{
Contract.Invariant(this.Results != null);
}
#endregion
public MethodAnalysisStatus(
Method method)
{
this.MethodObj = method;
Results = new Dictionary<string, MethodResult>();
}
public void AddMethodResult(string analyze_name, MethodResult result)
{
if (!Results.ContainsKey(analyze_name))
Results.Add(analyze_name, result);
}
public Method MethodObj { get; private set; }
public Dictionary<string, MethodResult> Results { get; private set; }
}
#region delegate IBasicAnalysisDriver<Local,Parameter,Method,Field,Property,Event,Type,Attribute,Assembly,LogOptions> Members
public LogOptions Options
{
get { return basicDriver.Options; }
}
public MethodCache<Local, Parameter, Type, Method, Field, Property, Event, Attribute, Assembly> MethodCache
{
get
{
return basicDriver.MethodCache;
}
}
public IDecodeMetaData<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly> MetaDataDecoder
{
get
{
return basicDriver.MetaDataDecoder;
}
}
public IDecodeContracts<Local, Parameter, Method, Field, Type> ContractDecoder
{
get { return basicDriver.ContractDecoder; }
}
public IOutput Output { get { return basicDriver.Output; } }
#endregion
}
}
| |
/*
Copyright 2019 Esri
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
namespace SimpleLogWindowCS
{
partial class LoggingDockableWindow
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.lstPendingMessage = new System.Windows.Forms.ListBox();
this.ctxMenuStrip = new System.Windows.Forms.ContextMenuStrip(this.components);
this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator();
this.clearToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.grpBoxCtxMenu = new System.Windows.Forms.GroupBox();
this.flowLayoutPanel1 = new System.Windows.Forms.FlowLayoutPanel();
this.radDotNetCtx = new System.Windows.Forms.RadioButton();
this.radFramework = new System.Windows.Forms.RadioButton();
this.radDynamic = new System.Windows.Forms.RadioButton();
this.splitContainer1 = new System.Windows.Forms.SplitContainer();
this.toolTip1 = new System.Windows.Forms.ToolTip(this.components);
this.lblMsg = new System.Windows.Forms.Label();
this.txtInput = new System.Windows.Forms.TextBox();
this.ctxMenuStrip.SuspendLayout();
this.grpBoxCtxMenu.SuspendLayout();
this.flowLayoutPanel1.SuspendLayout();
this.splitContainer1.Panel1.SuspendLayout();
this.splitContainer1.Panel2.SuspendLayout();
this.splitContainer1.SuspendLayout();
this.SuspendLayout();
//
// lstPendingMessage
//
this.lstPendingMessage.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.lstPendingMessage.ContextMenuStrip = this.ctxMenuStrip;
this.lstPendingMessage.HorizontalScrollbar = true;
this.lstPendingMessage.IntegralHeight = false;
this.lstPendingMessage.Location = new System.Drawing.Point(0, 22);
this.lstPendingMessage.Name = "lstPendingMessage";
this.lstPendingMessage.Size = new System.Drawing.Size(338, 78);
this.lstPendingMessage.TabIndex = 0;
//
// ctxMenuStrip
//
this.ctxMenuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.toolStripSeparator1,
this.clearToolStripMenuItem});
this.ctxMenuStrip.Name = "ctxMenuStrip";
this.ctxMenuStrip.RenderMode = System.Windows.Forms.ToolStripRenderMode.System;
this.ctxMenuStrip.ShowItemToolTips = false;
this.ctxMenuStrip.Size = new System.Drawing.Size(100, 32);
this.ctxMenuStrip.Opening += new System.ComponentModel.CancelEventHandler(this.ctxMenuStrip_Opening);
this.ctxMenuStrip.ItemClicked += new System.Windows.Forms.ToolStripItemClickedEventHandler(this.ctxMenuStrip_ItemClicked);
//
// toolStripSeparator1
//
this.toolStripSeparator1.Name = "toolStripSeparator1";
this.toolStripSeparator1.Size = new System.Drawing.Size(149, 6);
//
// clearToolStripMenuItem
//
this.clearToolStripMenuItem.Name = "clearToolStripMenuItem";
this.clearToolStripMenuItem.Size = new System.Drawing.Size(152, 22);
this.clearToolStripMenuItem.Text = "Clear";
this.clearToolStripMenuItem.Click += new System.EventHandler(this.clearToolStripMenuItem_Click);
//
// grpBoxCtxMenu
//
this.grpBoxCtxMenu.Controls.Add(this.flowLayoutPanel1);
this.grpBoxCtxMenu.Dock = System.Windows.Forms.DockStyle.Fill;
this.grpBoxCtxMenu.Location = new System.Drawing.Point(0, 0);
this.grpBoxCtxMenu.Name = "grpBoxCtxMenu";
this.grpBoxCtxMenu.Size = new System.Drawing.Size(338, 75);
this.grpBoxCtxMenu.TabIndex = 2;
this.grpBoxCtxMenu.TabStop = false;
this.grpBoxCtxMenu.Text = "Context Menu Option";
//
// flowLayoutPanel1
//
this.flowLayoutPanel1.Controls.Add(this.radDotNetCtx);
this.flowLayoutPanel1.Controls.Add(this.radFramework);
this.flowLayoutPanel1.Controls.Add(this.radDynamic);
this.flowLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Fill;
this.flowLayoutPanel1.Location = new System.Drawing.Point(3, 16);
this.flowLayoutPanel1.Name = "flowLayoutPanel1";
this.flowLayoutPanel1.Size = new System.Drawing.Size(332, 56);
this.flowLayoutPanel1.TabIndex = 3;
//
// radDotNetCtx
//
this.radDotNetCtx.AutoSize = true;
this.radDotNetCtx.Checked = true;
this.radDotNetCtx.Location = new System.Drawing.Point(3, 3);
this.radDotNetCtx.Name = "radDotNetCtx";
this.radDotNetCtx.Size = new System.Drawing.Size(149, 17);
this.radDotNetCtx.TabIndex = 0;
this.radDotNetCtx.TabStop = true;
this.radDotNetCtx.Text = "Pure .Net (Windows Form)";
this.toolTip1.SetToolTip(this.radDotNetCtx, "Pure .Net Windows Form context menu (ContextMenuStrip Class)");
this.radDotNetCtx.UseVisualStyleBackColor = true;
this.radDotNetCtx.CheckedChanged += new System.EventHandler(this.radCtxMenu_CheckedChanged);
//
// radFramework
//
this.radFramework.AutoSize = true;
this.radFramework.Location = new System.Drawing.Point(158, 3);
this.radFramework.Name = "radFramework";
this.radFramework.Size = new System.Drawing.Size(140, 17);
this.radFramework.TabIndex = 1;
this.radFramework.TabStop = true;
this.radFramework.Text = "Pre-defined (ArcObjects)";
this.toolTip1.SetToolTip(this.radFramework, "Use a predefined context menu registered in ArcGIS framework");
this.radFramework.UseVisualStyleBackColor = true;
this.radFramework.CheckedChanged += new System.EventHandler(this.radCtxMenu_CheckedChanged);
//
// radDynamic
//
this.radDynamic.AutoSize = true;
this.radDynamic.Location = new System.Drawing.Point(3, 26);
this.radDynamic.Name = "radDynamic";
this.radDynamic.Size = new System.Drawing.Size(127, 17);
this.radDynamic.TabIndex = 2;
this.radDynamic.TabStop = true;
this.radDynamic.Text = "Dynamic (ArcObjects)";
this.toolTip1.SetToolTip(this.radDynamic, "Use a temporary context menu created at runtime");
this.radDynamic.UseVisualStyleBackColor = true;
this.radDynamic.CheckedChanged += new System.EventHandler(this.radCtxMenu_CheckedChanged);
//
// splitContainer1
//
this.splitContainer1.Dock = System.Windows.Forms.DockStyle.Fill;
this.splitContainer1.Location = new System.Drawing.Point(0, 0);
this.splitContainer1.Name = "splitContainer1";
this.splitContainer1.Orientation = System.Windows.Forms.Orientation.Horizontal;
//
// splitContainer1.Panel1
//
this.splitContainer1.Panel1.Controls.Add(this.lblMsg);
this.splitContainer1.Panel1.Controls.Add(this.txtInput);
this.splitContainer1.Panel1.Controls.Add(this.lstPendingMessage);
//
// splitContainer1.Panel2
//
this.splitContainer1.Panel2.Controls.Add(this.grpBoxCtxMenu);
this.splitContainer1.Size = new System.Drawing.Size(338, 179);
this.splitContainer1.SplitterDistance = 100;
this.splitContainer1.TabIndex = 3;
//
// lblMsg
//
this.lblMsg.AutoSize = true;
this.lblMsg.Location = new System.Drawing.Point(1, 3);
this.lblMsg.Name = "lblMsg";
this.lblMsg.Size = new System.Drawing.Size(58, 13);
this.lblMsg.TabIndex = 4;
this.lblMsg.Text = "Input Text:";
//
// txtInput
//
this.txtInput.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.txtInput.Location = new System.Drawing.Point(82, 0);
this.txtInput.Name = "txtInput";
this.txtInput.Size = new System.Drawing.Size(256, 20);
this.txtInput.TabIndex = 3;
this.txtInput.KeyUp += new System.Windows.Forms.KeyEventHandler(this.txtInput_KeyUp);
//
// LoggingDockableWindow
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.splitContainer1);
this.Name = "LoggingDockableWindow";
this.Size = new System.Drawing.Size(338, 179);
this.ctxMenuStrip.ResumeLayout(false);
this.grpBoxCtxMenu.ResumeLayout(false);
this.flowLayoutPanel1.ResumeLayout(false);
this.flowLayoutPanel1.PerformLayout();
this.splitContainer1.Panel1.ResumeLayout(false);
this.splitContainer1.Panel1.PerformLayout();
this.splitContainer1.Panel2.ResumeLayout(false);
this.splitContainer1.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.ListBox lstPendingMessage;
private System.Windows.Forms.GroupBox grpBoxCtxMenu;
private System.Windows.Forms.RadioButton radFramework;
private System.Windows.Forms.RadioButton radDotNetCtx;
private System.Windows.Forms.ContextMenuStrip ctxMenuStrip;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator1;
private System.Windows.Forms.ToolStripMenuItem clearToolStripMenuItem;
private System.Windows.Forms.FlowLayoutPanel flowLayoutPanel1;
private System.Windows.Forms.RadioButton radDynamic;
private System.Windows.Forms.SplitContainer splitContainer1;
private System.Windows.Forms.ToolTip toolTip1;
internal System.Windows.Forms.Label lblMsg;
internal System.Windows.Forms.TextBox txtInput;
}
}
| |
using System;
using System.IO;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Terraria;
namespace Terraria.ModLoader
{
/// <summary>
/// This class serves as a place for you to place all your properties and hooks for each NPC. Create instances of ModNPC (preferably overriding this class) to pass as parameters to Mod.AddNPC.
/// </summary>
public class ModNPC
{
//add modNPC property to Terraria.NPC (internal set)
//set modNPC to null at beginning of Terraria.NPC.SetDefaults
/// <summary>
/// The NPC object that this ModNPC controls.
/// </summary>
public NPC npc
{
get;
internal set;
}
/// <summary>
/// The mod that added this ModNPC.
/// </summary>
public Mod mod
{
get;
internal set;
}
internal string texture;
internal string[] altTextures;
/// <summary>
/// Determines which type of vanilla NPC this ModNPC will copy the behavior (AI) of. Leave as 0 to not copy any behavior. Defaults to 0.
/// </summary>
public int aiType = 0;
/// <summary>
/// Determines which type of vanilla NPC this ModNPC will copy the animation (FindFrame) of. Leave as 0 to not copy any animation. Defaults to 0.
/// </summary>
public int animationType = 0;
/// <summary>
/// The item type of the boss bag that is dropped when DropBossBags is called for this NPC.
/// </summary>
public int bossBag = -1;
//make changes to Terraria.Main.UpdateMusic (see patch files)
/// <summary>
/// The ID of the music that plays when this NPC is on or near the screen. Defaults to -1, which means music plays normally.
/// </summary>
public int music = -1;
//in Terraria.Main.NPCAddHeight at end of else if chain add
// else if(Main.npc[i].modNPC != null) { num = Main.npc[i].modNPC.drawOffsetY; }
/// <summary>
/// The vertical offset used for drawing this NPC. Defaults to 0.
/// </summary>
public float drawOffsetY = 0f;
//in Terraria.Item.NPCToBanner before returning 0 add
// if(i >= NPCID.Count) { return NPCLoader.npcs[i].banner; }
//in Terraria.Item.BannerToNPC before returning 0 add
// if(i >= NPCID.Count) { return i; }
/// <summary>
/// The type of NPC that this NPC will be considered as when determining banner drops and banner bonuses. By default this will be 0, which means this NPC is not associated with any banner. To give your NPC its own banner, set this field to the NPC's type.
/// </summary>
public int banner = 0;
//in Terraria.NPC.NPCLoot after if statements setting num6 add
// if(num3 >= NPCID.Count) { num6 = NPCLoader.npcs[num3].bannerItem; }
/// <summary>
/// The type of the item this NPC drops for every 50 times it is defeated. For any ModNPC whose banner field is set to the type of this NPC, that ModNPC will drop this banner.
/// </summary>
public int bannerItem = 0;
/// <summary>
/// ModNPC constructor.
/// </summary>
public ModNPC()
{
npc = new NPC();
}
/// <summary>
/// Allows you to automatically load an NPC instead of using Mod.AddNPC. Return true to allow autoloading; by default returns the mod's autoload property. Name is initialized to the overriding class name, texture is initialized to the namespace and overriding class name with periods replaced with slashes, and altTextures is initialized to null. Use this method to either force or stop an autoload, to change the default display name and texture path, or to give the NPC alternate textures.
/// </summary>
/// <param name="name"></param>
/// <param name="texture"></param>
/// <param name="altTextures"></param>
/// <returns></returns>
public virtual bool Autoload(ref string name, ref string texture, ref string[] altTextures)
{
return mod.Properties.Autoload;
}
/// <summary>
/// Allows you to control the path to this NPC's head texture when it is autoloaded. The headTexture defaults to the default NPC texture plus "_Head", and the bossHeadTexture defaults to the default headTexture plus "_Head_Boss". If the textures don't exist, the NPC will not be given a head texture. The headTexture should be used for town NPCs, and the bossHeadTexture should be used for any non-town NPC that you want to display on the map.
/// </summary>
/// <param name="headTexture"></param>
/// <param name="bossHeadTexture"></param>
public virtual void AutoloadHead(ref string headTexture, ref string bossHeadTexture)
{
}
internal void SetupNPC(NPC npc)
{
ModNPC newNPC = (ModNPC)(CloneNewInstances ? MemberwiseClone() : Activator.CreateInstance(GetType()));
newNPC.npc = npc;
npc.modNPC = newNPC;
newNPC.mod = mod;
newNPC.SetDefaults();
}
/// <summary>
/// Whether instances of this ModNPC are created through a memberwise clone or its constructor. Defaults to false.
/// </summary>
public virtual bool CloneNewInstances => false;
/// <summary>
/// Allows you to set all your NPC's properties, such as width, damage, aiStyle, lifeMax, etc.
/// </summary>
public virtual void SetDefaults()
{
}
/// <summary>
/// Allows you to customize this NPC's stats in expert mode. This is useful because expert mode's doubling of damage and life might be too much sometimes (for example, with bosses). Also useful for scaling life with the number of players in the world.
/// </summary>
/// <param name="numPlayers"></param>
/// <param name="bossLifeScale"></param>
public virtual void ScaleExpertStats(int numPlayers, float bossLifeScale)
{
}
/// <summary>
/// This is where you reset any fields you add to your subclass to their default states. This is necessary in order to reset your fields if they are conditionally set by a tick update but the condition is no longer satisfied. (Note: This hook is only really useful for GlobalNPC, but is included in ModNPC for completion.)
/// </summary>
public virtual void ResetEffects()
{
}
/// <summary>
/// Allows you to determine how this NPC behaves. Return false to stop the vanilla AI and the AI hook from being run. Returns true by default.
/// </summary>
/// <returns></returns>
public virtual bool PreAI()
{
return true;
}
/// <summary>
/// Allows you to determine how this NPC behaves. This will only be called if PreAI returns true.
/// </summary>
public virtual void AI()
{
}
//Allows you to determine how this NPC behaves. This will be called regardless of what PreAI returns.
public virtual void PostAI()
{
}
/// <summary>
/// If you are storing AI information outside of the npc.ai array, use this to send that AI information between clients and servers.
/// </summary>
/// <param name="writer"></param>
public virtual void SendExtraAI(BinaryWriter writer)
{
}
/// <summary>
/// Use this to receive information that was sent in SendExtraAI.
/// </summary>
/// <param name="reader"></param>
public virtual void ReceiveExtraAI(BinaryReader reader)
{
}
/// <summary>
/// Allows you to modify the frame from this NPC's texture that is drawn, which is necessary in order to animate NPCs.
/// </summary>
/// <param name="frameHeight"></param>
public virtual void FindFrame(int frameHeight)
{
}
/// <summary>
/// Allows you to make things happen whenever this NPC is hit, such as creating dust or gores.
/// </summary>
/// <param name="hitDirection"></param>
/// <param name="damage"></param>
public virtual void HitEffect(int hitDirection, double damage)
{
}
/// <summary>
/// Allows you to make the NPC either regenerate health or take damage over time by setting npc.lifeRegen. Regeneration or damage will occur at a rate of half of npc.lifeRegen per second. The damage parameter is the number that appears above the NPC's head if it takes damage over time.
/// </summary>
/// <param name="damage"></param>
public virtual void UpdateLifeRegen(ref int damage)
{
}
/// <summary>
/// Whether or not to run the code for checking whether this NPC will remain active. Return false to stop this NPC from being despawned and to stop this NPC from counting towards the limit for how many NPCs can exist near a player. Returns true by default.
/// </summary>
/// <returns></returns>
public virtual bool CheckActive()
{
return true;
}
/// <summary>
/// Whether or not this NPC should be killed when it reaches 0 health. You may program extra effects in this hook (for example, how Golem's head lifts up for the second phase of its fight). Return false to stop this NPC from being killed. Returns true by default.
/// </summary>
/// <returns></returns>
public virtual bool CheckDead()
{
return true;
}
/// <summary>
/// Allows you to determine whether or not this NPC will drop anything at all. Return false to stop the NPC from dropping anything. Returns true by default.
/// </summary>
/// <returns></returns>
public virtual bool PreNPCLoot()
{
return true;
}
/// <summary>
/// Allows you to make things happen when this NPC dies (for example, dropping items).
/// </summary>
public virtual void NPCLoot()
{
}
/// <summary>
/// Allows you to customize what happens when this boss dies, such as which name is displayed in the defeat message and what type of potion it drops.
/// </summary>
/// <param name="name"></param>
/// <param name="potionType"></param>
public virtual void BossLoot(ref string name, ref int potionType)
{
}
/// <summary>
/// Allows you to determine whether this NPC can hit the given player. Return false to block this NPC from hitting the target. Returns true by default. CooldownSlot determines which of the player's cooldown counters to use (-1, 0, or 1), and defaults to -1.
/// </summary>
/// <param name="target"></param>
/// <param name="cooldownSlot"></param>
/// <returns></returns>
public virtual bool CanHitPlayer(Player target, ref int cooldownSlot)
{
return true;
}
/// <summary>
/// Allows you to modify the damage, etc., that this NPC does to a player.
/// </summary>
/// <param name="target"></param>
/// <param name="damage"></param>
/// <param name="crit"></param>
public virtual void ModifyHitPlayer(Player target, ref int damage, ref bool crit)
{
}
/// <summary>
/// Allows you to create special effects when this NPC hits a player (for example, inflicting debuffs).
/// </summary>
/// <param name="target"></param>
/// <param name="damage"></param>
/// <param name="crit"></param>
public virtual void OnHitPlayer(Player target, int damage, bool crit)
{
}
/// <summary>
/// Allows you to determine whether this NPC can hit the given friendly NPC. Return true to allow hitting the target, return false to block this NPC from hitting the target, and return null to use the vanilla code for whether the target can be hit. Returns null by default.
/// </summary>
/// <param name="target"></param>
/// <returns></returns>
public virtual bool? CanHitNPC(NPC target)
{
return null;
}
/// <summary>
/// Allows you to modify the damage, knockback, etc., that this NPC does to a friendly NPC.
/// </summary>
/// <param name="target"></param>
/// <param name="damage"></param>
/// <param name="knockback"></param>
/// <param name="crit"></param>
public virtual void ModifyHitNPC(NPC target, ref int damage, ref float knockback, ref bool crit)
{
}
/// <summary>
/// Allows you to create special effects when this NPC hits a friendly NPC.
/// </summary>
/// <param name="target"></param>
/// <param name="damage"></param>
/// <param name="knockback"></param>
/// <param name="crit"></param>
public virtual void OnHitNPC(NPC target, int damage, float knockback, bool crit)
{
}
/// <summary>
/// Allows you to determine whether this NPC can be hit by the given melee weapon when swung. Return true to allow hitting the NPC, return false to block hitting the NPC, and return null to use the vanilla code for whether the NPC can be hit. Returns null by default.
/// </summary>
/// <param name="player"></param>
/// <param name="item"></param>
/// <returns></returns>
public virtual bool? CanBeHitByItem(Player player, Item item)
{
return null;
}
/// <summary>
/// Allows you to modify the damage, knockback, etc., that this NPC takes from a melee weapon.
/// </summary>
/// <param name="player"></param>
/// <param name="item"></param>
/// <param name="damage"></param>
/// <param name="knockback"></param>
/// <param name="crit"></param>
public virtual void ModifyHitByItem(Player player, Item item, ref int damage, ref float knockback, ref bool crit)
{
}
/// <summary>
/// Allows you to create special effects when this NPC is hit by a melee weapon.
/// </summary>
/// <param name="player"></param>
/// <param name="item"></param>
/// <param name="damage"></param>
/// <param name="knockback"></param>
/// <param name="crit"></param>
public virtual void OnHitByItem(Player player, Item item, int damage, float knockback, bool crit)
{
}
/// <summary>
/// Allows you to determine whether this NPC can be hit by the given projectile. Return true to allow hitting the NPC, return false to block hitting the NPC, and return null to use the vanilla code for whether the NPC can be hit. Returns null by default.
/// </summary>
/// <param name="projectile"></param>
/// <returns></returns>
public virtual bool? CanBeHitByProjectile(Projectile projectile)
{
return null;
}
/// <summary>
/// Allows you to modify the damage, knockback, etc., that this NPC takes from a projectile.
/// </summary>
/// <param name="projectile"></param>
/// <param name="damage"></param>
/// <param name="knockback"></param>
/// <param name="crit"></param>
/// <param name="hitDirection"></param>
public virtual void ModifyHitByProjectile(Projectile projectile, ref int damage, ref float knockback, ref bool crit, ref int hitDirection)
{
}
/// <summary>
/// Allows you to create special effects when this NPC is hit by a projectile.
/// </summary>
/// <param name="projectile"></param>
/// <param name="damage"></param>
/// <param name="knockback"></param>
/// <param name="crit"></param>
public virtual void OnHitByProjectile(Projectile projectile, int damage, float knockback, bool crit)
{
}
/// <summary>
/// Allows you to use a custom damage formula for when this NPC takes damage from any source. For example, you can change the way defense works or use a different crit multiplier. Return false to stop the game from running the vanilla damage formula; returns true by default.
/// </summary>
/// <param name="damage"></param>
/// <param name="defense"></param>
/// <param name="knockback"></param>
/// <param name="hitDirection"></param>
/// <param name="crit"></param>
/// <returns></returns>
public virtual bool StrikeNPC(ref double damage, int defense, ref float knockback, int hitDirection, ref bool crit)
{
return true;
}
/// <summary>
/// Allows you to customize the boss head texture used by this NPC based on its state.
/// </summary>
/// <param name="index"></param>
public virtual void BossHeadSlot(ref int index)
{
}
/// <summary>
/// Allows you to customize the rotation of this NPC's boss head icon on the map.
/// </summary>
/// <param name="rotation"></param>
public virtual void BossHeadRotation(ref float rotation)
{
}
/// <summary>
/// Allows you to flip this NPC's boss head icon on the map.
/// </summary>
/// <param name="spriteEffects"></param>
public virtual void BossHeadSpriteEffects(ref SpriteEffects spriteEffects)
{
}
/// <summary>
/// Allows you to determine the color and transparency in which this NPC is drawn. Return null to use the default color (normally light and buff color). Returns null by default.
/// </summary>
/// <param name="drawColor"></param>
/// <returns></returns>
public virtual Color? GetAlpha(Color drawColor)
{
return null;
}
/// <summary>
/// Allows you to add special visual effects to this NPC (such as creating dust), and modify the color in which the NPC is drawn.
/// </summary>
/// <param name="drawColor"></param>
public virtual void DrawEffects(ref Color drawColor)
{
}
/// <summary>
/// Allows you to draw things behind this NPC, or to modify the way this NPC is drawn. Return false to stop the game from drawing the NPC (useful if you're manually drawing the NPC). Returns true by default.
/// </summary>
/// <param name="spriteBatch"></param>
/// <param name="drawColor"></param>
/// <returns></returns>
public virtual bool PreDraw(SpriteBatch spriteBatch, Color drawColor)
{
return true;
}
/// <summary>
/// Allows you to draw things in front of this NPC. This method is called even if PreDraw returns false.
/// </summary>
/// <param name="spriteBatch"></param>
/// <param name="drawColor"></param>
public virtual void PostDraw(SpriteBatch spriteBatch, Color drawColor)
{
}
/// <summary>
/// Allows you to control how the health bar for this NPC is drawn. The hbPosition parameter is the same as Main.hbPosition; it determines whether the health bar gets drawn above or below the NPC by default. The scale parameter is the health bar's size. By default, it will be the normal 1f; most bosses set this to 1.5f. Return null to let the normal vanilla health-bar-drawing code to run. Return false to stop the health bar from being drawn. Return true to draw the health bar in the position specified by the position parameter (note that this is the world position, not screen position).
/// </summary>
/// <param name="hbPosition"></param>
/// <param name="scale"></param>
/// <param name="position"></param>
/// <returns></returns>
public virtual bool? DrawHealthBar(byte hbPosition, ref float scale, ref Vector2 position)
{
return null;
}
/// <summary>
/// Whether or not this NPC can spawn with the given spawning conditions. Return the weight for the chance of this NPC to spawn compared to vanilla mobs. All vanilla mobs combined have a total weight of 1. Returns 0 by default, which disables natural spawning.
/// </summary>
/// <param name="spawnInfo"></param>
/// <returns></returns>
public virtual float CanSpawn(NPCSpawnInfo spawnInfo)
{
return 0f;
}
/// <summary>
/// Allows you to customize how this NPC is created when it naturally spawns (for example, its position or ai array). Return the return value of NPC.NewNPC. By default this method spawns this NPC on top of the tile at the given coordinates.
/// </summary>
/// <param name="tileX"></param>
/// <param name="tileY"></param>
/// <returns></returns>
public virtual int SpawnNPC(int tileX, int tileY)
{
return NPC.NewNPC(tileX * 16 + 8, tileY * 16, npc.type);
}
/// <summary>
/// Whether or not the conditions have been met for this town NPC to be able to move into town. For example, the Demolitionist requires that any player has an explosive.
/// </summary>
/// <param name="numTownNPCs"></param>
/// <param name="money"></param>
/// <returns></returns>
public virtual bool CanTownNPCSpawn(int numTownNPCs, int money)
{
return false;
}
/// <summary>
/// Allows you to define special conditions required for this town NPC's house. For example, Truffle requires the house to be in an aboveground mushroom biome.
/// </summary>
/// <param name="left"></param>
/// <param name="right"></param>
/// <param name="top"></param>
/// <param name="bottom"></param>
/// <returns></returns>
public virtual bool CheckConditions(int left, int right, int top, int bottom)
{
return true;
}
/// <summary>
/// Allows you to give this town NPC any name when it spawns. By default returns something embarrassing.
/// </summary>
/// <returns></returns>
public virtual string TownNPCName()
{
return "No-Name";
}
/// <summary>
/// Allows you to determine whether this town NPC wears a party hat during a party. Returns true by default.
/// </summary>
/// <returns></returns>
public virtual bool UsesPartyHat()
{
return true;
}
/// <summary>
/// Allows you to give this town NPC a chat message when a player talks to it. By default returns something embarrassing.
/// </summary>
/// <returns></returns>
public virtual string GetChat()
{
return "My modder forgot to give me a chat message.";
}
/// <summary>
/// Allows you to set the text for the buttons that appear on this town NPC's chat window. A parameter left as an empty string will not be included as a button on the chat window.
/// </summary>
/// <param name="button"></param>
/// <param name="button2"></param>
public virtual void SetChatButtons(ref string button, ref string button2)
{
}
/// <summary>
/// Allows you to make something happen whenever a button is clicked on this town NPC's chat window. The firstButton parameter tells whether the first button or second button (button and button2 from SetChatButtons) was clicked. Set the shop parameter to true to open this NPC's shop.
/// </summary>
/// <param name="firstButton"></param>
/// <param name="shop"></param>
public virtual void OnChatButtonClicked(bool firstButton, ref bool shop)
{
}
/// <summary>
/// Allows you to add items to this town NPC's shop. Add an item by setting the defaults of shop.item[nextSlot] then incrementing nextSlot. In the end, nextSlot must have a value of 1 greater than the highest index in shop.item that contains an item.
/// </summary>
/// <param name="shop"></param>
/// <param name="nextSlot"></param>
public virtual void SetupShop(Chest shop, ref int nextSlot)
{
}
/// <summary>
/// Allows you to determine the damage and knockback of this town NPC's attack before the damage is scaled. (More information on scaling in GlobalNPC.BuffTownNPCs.)
/// </summary>
/// <param name="damage"></param>
/// <param name="knockback"></param>
public virtual void TownNPCAttackStrength(ref int damage, ref float knockback)
{
}
/// <summary>
/// Allows you to determine the cooldown between each of this town NPC's attack. The cooldown will be a number greater than or equal to the first parameter, and less then the sum of the two parameters.
/// </summary>
/// <param name="cooldown"></param>
/// <param name="randExtraCooldown"></param>
public virtual void TownNPCAttackCooldown(ref int cooldown, ref int randExtraCooldown)
{
}
/// <summary>
/// Allows you to determine the projectile type of this town NPC's attack, and how long it takes for the projectile to actually appear. This hook is only used when the town NPC has an attack type of 0 (throwing), 1 (shooting), or 2 (magic).
/// </summary>
/// <param name="projType"></param>
/// <param name="attackDelay"></param>
public virtual void TownNPCAttackProj(ref int projType, ref int attackDelay)
{
}
/// <summary>
/// Allows you to determine the speed at which this town NPC throws a projectile when it attacks. Multiplier is the speed of the projectile, gravityCorrection is how much extra the projectile gets thrown upwards, and randomOffset allows you to randomize the projectile's velocity in a square centered around the original velocity. This hook is only used when the town NPC has an attack type of 0 (throwing), 1 (shooting), or 2 (magic).
/// </summary>
/// <param name="multiplier"></param>
/// <param name="gravityCorrection"></param>
/// <param name="randomOffset"></param>
public virtual void TownNPCAttackProjSpeed(ref float multiplier, ref float gravityCorrection, ref float randomOffset)
{
}
/// <summary>
/// Allows you to tell the game that this town NPC has already created a projectile and will still create more projectiles as part of a single attack so that the game can animate the NPC's attack properly. Only used when the town NPC has an attack type of 1 (shooting).
/// </summary>
/// <param name="inBetweenShots"></param>
public virtual void TownNPCAttackShoot(ref bool inBetweenShots)
{
}
/// <summary>
/// Allows you to control the brightness of the light emitted by this town NPC's aura when it performs a magic attack. Only used when the town NPC has an attack type of 2 (magic)
/// </summary>
/// <param name="auraLightMultiplier"></param>
public virtual void TownNPCAttackMagic(ref float auraLightMultiplier)
{
}
/// <summary>
/// Allows you to determine the width and height of the item this town NPC swings when it attacks, which controls the range of this NPC's swung weapon. Only used when the town NPC has an attack type of 3 (swinging).
/// </summary>
/// <param name="itemWidth"></param>
/// <param name="itemHeight"></param>
public virtual void TownNPCAttackSwing(ref int itemWidth, ref int itemHeight)
{
}
/// <summary>
/// Allows you to customize how this town NPC's weapon is drawn when this NPC is shooting (this NPC must have an attack type of 1). Scale is a multiplier for the item's drawing size, item is the ID of the item to be drawn, and closeness is how close the item should be drawn to the NPC.
/// </summary>
/// <param name="scale"></param>
/// <param name="item"></param>
/// <param name="closeness"></param>
public virtual void DrawTownAttackGun(ref float scale, ref int item, ref int closeness)
{
}
/// <summary>
/// Allows you to customize how this town NPC's weapon is drawn when this NPC is swinging it (this NPC must have an attack type of 3). Item is the Texture2D instance of the item to be drawn (use Main.itemTexture[id of item]), itemSize is the width and height of the item's hitbox (the same values for TownNPCAttackSwing), scale is the multiplier for the item's drawing size, and offset is the offset from which to draw the item from its normal position.
/// </summary>
/// <param name="item"></param>
/// <param name="itemSize"></param>
/// <param name="scale"></param>
/// <param name="offset"></param>
public virtual void DrawTownAttackSwing(ref Texture2D item, ref int itemSize, ref float scale, ref Vector2 offset)
{
}
}
}
| |
using EIDSS.Reports.Document.ActiveSurveillance.SessionFarmReportDataSetTableAdapters;
namespace EIDSS.Reports.Document.ActiveSurveillance
{
partial class SessionFarmReport
{
/// <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 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(SessionFarmReport));
this.Detail = new DevExpress.XtraReports.UI.DetailBand();
this.xrTable2 = new DevExpress.XtraReports.UI.XRTable();
this.xrTableRow3 = new DevExpress.XtraReports.UI.XRTableRow();
this.cellNo = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell15 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell16 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell17 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell18 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell19 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell20 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell21 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell22 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell23 = new DevExpress.XtraReports.UI.XRTableCell();
this.TopMargin = new DevExpress.XtraReports.UI.TopMarginBand();
this.BottomMargin = new DevExpress.XtraReports.UI.BottomMarginBand();
this.PageHeader = new DevExpress.XtraReports.UI.PageHeaderBand();
this.MainTable = new DevExpress.XtraReports.UI.XRTable();
this.xrTableRow1 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell7 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell4 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell8 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell1 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell5 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell9 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell10 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell2 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell6 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell3 = new DevExpress.XtraReports.UI.XRTableCell();
this.GroupHeader1 = new DevExpress.XtraReports.UI.GroupHeaderBand();
this.xrTable1 = new DevExpress.XtraReports.UI.XRTable();
this.xrTableRow2 = new DevExpress.XtraReports.UI.XRTableRow();
this.cellFarm = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell12 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell13 = new DevExpress.XtraReports.UI.XRTableCell();
this.m_SessionFarmReportDataSet = new SessionFarmReportDataSet();
this.m_SessionFarmAdapter = new SessionFarmAdapter();
this.GroupFooter1 = new DevExpress.XtraReports.UI.GroupFooterBand();
((System.ComponentModel.ISupportInitialize)(this.xrTable2)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.MainTable)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.xrTable1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.m_SessionFarmReportDataSet)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this)).BeginInit();
//
// Detail
//
this.Detail.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.xrTable2});
resources.ApplyResources(this.Detail, "Detail");
this.Detail.Name = "Detail";
this.Detail.Padding = new DevExpress.XtraPrinting.PaddingInfo(0, 0, 0, 0, 100F);
//
// xrTable2
//
this.xrTable2.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Right)
| DevExpress.XtraPrinting.BorderSide.Bottom)));
resources.ApplyResources(this.xrTable2, "xrTable2");
this.xrTable2.Name = "xrTable2";
this.xrTable2.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] {
this.xrTableRow3});
this.xrTable2.StylePriority.UseBorders = false;
this.xrTable2.StylePriority.UseTextAlignment = false;
//
// xrTableRow3
//
this.xrTableRow3.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.cellNo,
this.xrTableCell15,
this.xrTableCell16,
this.xrTableCell17,
this.xrTableCell18,
this.xrTableCell19,
this.xrTableCell20,
this.xrTableCell21,
this.xrTableCell22,
this.xrTableCell23});
this.xrTableRow3.Name = "xrTableRow3";
this.xrTableRow3.Weight = 1.3333332824707032;
//
// cellNo
//
this.cellNo.Multiline = true;
this.cellNo.Name = "cellNo";
this.cellNo.Weight = 0.14258556787591714;
this.cellNo.BeforePrint += new System.Drawing.Printing.PrintEventHandler(this.cellNo_BeforePrint);
//
// xrTableCell15
//
this.xrTableCell15.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "SessionFarm.strAnimalCode")});
this.xrTableCell15.Multiline = true;
this.xrTableCell15.Name = "xrTableCell15";
resources.ApplyResources(this.xrTableCell15, "xrTableCell15");
this.xrTableCell15.Weight = 0.3419351030388541;
//
// xrTableCell16
//
this.xrTableCell16.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "SessionFarm.strSpeciesType")});
this.xrTableCell16.Multiline = true;
this.xrTableCell16.Name = "xrTableCell16";
resources.ApplyResources(this.xrTableCell16, "xrTableCell16");
this.xrTableCell16.Weight = 0.51357830421664874;
//
// xrTableCell17
//
this.xrTableCell17.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "SessionFarm.strAnimalAge")});
this.xrTableCell17.Multiline = true;
this.xrTableCell17.Name = "xrTableCell17";
resources.ApplyResources(this.xrTableCell17, "xrTableCell17");
this.xrTableCell17.Weight = 0.28517113575183428;
//
// xrTableCell18
//
this.xrTableCell18.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "SessionFarm.strAnimalColor")});
this.xrTableCell18.Multiline = true;
this.xrTableCell18.Name = "xrTableCell18";
resources.ApplyResources(this.xrTableCell18, "xrTableCell18");
this.xrTableCell18.Weight = 0.28517113575183428;
//
// xrTableCell19
//
this.xrTableCell19.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "SessionFarm.strAnimalName")});
this.xrTableCell19.Multiline = true;
this.xrTableCell19.Name = "xrTableCell19";
resources.ApplyResources(this.xrTableCell19, "xrTableCell19");
this.xrTableCell19.Weight = 0.28517113575183423;
//
// xrTableCell20
//
this.xrTableCell20.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "SessionFarm.strAnimalGender")});
this.xrTableCell20.Multiline = true;
this.xrTableCell20.Name = "xrTableCell20";
resources.ApplyResources(this.xrTableCell20, "xrTableCell20");
this.xrTableCell20.Weight = 0.28517113575183428;
//
// xrTableCell21
//
this.xrTableCell21.Multiline = true;
this.xrTableCell21.Name = "xrTableCell21";
this.xrTableCell21.Weight = 0.28517113575183434;
//
// xrTableCell22
//
this.xrTableCell22.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "SessionFarm.strFieldBarcode")});
this.xrTableCell22.Multiline = true;
this.xrTableCell22.Name = "xrTableCell22";
resources.ApplyResources(this.xrTableCell22, "xrTableCell22");
this.xrTableCell22.Weight = 0.28517113575183423;
//
// xrTableCell23
//
this.xrTableCell23.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "SessionFarm.strSpecimenName")});
this.xrTableCell23.Multiline = true;
this.xrTableCell23.Name = "xrTableCell23";
resources.ApplyResources(this.xrTableCell23, "xrTableCell23");
this.xrTableCell23.Weight = 0.28517113575183428;
//
// TopMargin
//
resources.ApplyResources(this.TopMargin, "TopMargin");
this.TopMargin.Name = "TopMargin";
this.TopMargin.Padding = new DevExpress.XtraPrinting.PaddingInfo(0, 0, 0, 0, 100F);
//
// BottomMargin
//
resources.ApplyResources(this.BottomMargin, "BottomMargin");
this.BottomMargin.Name = "BottomMargin";
this.BottomMargin.Padding = new DevExpress.XtraPrinting.PaddingInfo(0, 0, 0, 0, 100F);
//
// PageHeader
//
this.PageHeader.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.MainTable});
resources.ApplyResources(this.PageHeader, "PageHeader");
this.PageHeader.Name = "PageHeader";
//
// MainTable
//
this.MainTable.Borders = ((DevExpress.XtraPrinting.BorderSide)((((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top)
| DevExpress.XtraPrinting.BorderSide.Right)
| DevExpress.XtraPrinting.BorderSide.Bottom)));
resources.ApplyResources(this.MainTable, "MainTable");
this.MainTable.Name = "MainTable";
this.MainTable.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] {
this.xrTableRow1});
this.MainTable.StylePriority.UseBorders = false;
this.MainTable.StylePriority.UseTextAlignment = false;
//
// xrTableRow1
//
this.xrTableRow1.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell7,
this.xrTableCell4,
this.xrTableCell8,
this.xrTableCell1,
this.xrTableCell5,
this.xrTableCell9,
this.xrTableCell10,
this.xrTableCell2,
this.xrTableCell6,
this.xrTableCell3});
this.xrTableRow1.Name = "xrTableRow1";
this.xrTableRow1.Weight = 1.3333332824707032;
//
// xrTableCell7
//
this.xrTableCell7.Multiline = true;
this.xrTableCell7.Name = "xrTableCell7";
resources.ApplyResources(this.xrTableCell7, "xrTableCell7");
this.xrTableCell7.Weight = 0.14258556787591714;
//
// xrTableCell4
//
this.xrTableCell4.Multiline = true;
this.xrTableCell4.Name = "xrTableCell4";
resources.ApplyResources(this.xrTableCell4, "xrTableCell4");
this.xrTableCell4.Weight = 0.34193514461400515;
//
// xrTableCell8
//
this.xrTableCell8.Multiline = true;
this.xrTableCell8.Name = "xrTableCell8";
resources.ApplyResources(this.xrTableCell8, "xrTableCell8");
this.xrTableCell8.Weight = 0.51357826264149775;
//
// xrTableCell1
//
this.xrTableCell1.Multiline = true;
this.xrTableCell1.Name = "xrTableCell1";
resources.ApplyResources(this.xrTableCell1, "xrTableCell1");
this.xrTableCell1.Weight = 0.28517113575183428;
//
// xrTableCell5
//
this.xrTableCell5.Multiline = true;
this.xrTableCell5.Name = "xrTableCell5";
resources.ApplyResources(this.xrTableCell5, "xrTableCell5");
this.xrTableCell5.Weight = 0.28517113575183428;
//
// xrTableCell9
//
this.xrTableCell9.Multiline = true;
this.xrTableCell9.Name = "xrTableCell9";
resources.ApplyResources(this.xrTableCell9, "xrTableCell9");
this.xrTableCell9.Weight = 0.28517113575183423;
//
// xrTableCell10
//
this.xrTableCell10.Multiline = true;
this.xrTableCell10.Name = "xrTableCell10";
resources.ApplyResources(this.xrTableCell10, "xrTableCell10");
this.xrTableCell10.Weight = 0.28517113575183428;
//
// xrTableCell2
//
this.xrTableCell2.Multiline = true;
this.xrTableCell2.Name = "xrTableCell2";
resources.ApplyResources(this.xrTableCell2, "xrTableCell2");
this.xrTableCell2.Weight = 0.28517113575183434;
//
// xrTableCell6
//
this.xrTableCell6.Multiline = true;
this.xrTableCell6.Name = "xrTableCell6";
resources.ApplyResources(this.xrTableCell6, "xrTableCell6");
this.xrTableCell6.Weight = 0.28517113575183423;
//
// xrTableCell3
//
this.xrTableCell3.Multiline = true;
this.xrTableCell3.Name = "xrTableCell3";
resources.ApplyResources(this.xrTableCell3, "xrTableCell3");
this.xrTableCell3.Weight = 0.28517113575183428;
//
// GroupHeader1
//
this.GroupHeader1.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.xrTable1});
this.GroupHeader1.GroupFields.AddRange(new DevExpress.XtraReports.UI.GroupField[] {
new DevExpress.XtraReports.UI.GroupField("idfFarm", DevExpress.XtraReports.UI.XRColumnSortOrder.Ascending)});
resources.ApplyResources(this.GroupHeader1, "GroupHeader1");
this.GroupHeader1.Name = "GroupHeader1";
//
// xrTable1
//
resources.ApplyResources(this.xrTable1, "xrTable1");
this.xrTable1.Name = "xrTable1";
this.xrTable1.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] {
this.xrTableRow2});
this.xrTable1.StylePriority.UseTextAlignment = false;
//
// xrTableRow2
//
this.xrTableRow2.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.cellFarm,
this.xrTableCell12,
this.xrTableCell13});
this.xrTableRow2.Name = "xrTableRow2";
this.xrTableRow2.Weight = 1;
//
// cellFarm
//
this.cellFarm.Borders = ((DevExpress.XtraPrinting.BorderSide)((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Bottom)));
this.cellFarm.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "SessionFarm.strFarmCode")});
this.cellFarm.Name = "cellFarm";
this.cellFarm.StylePriority.UseBorders = false;
resources.ApplyResources(this.cellFarm, "cellFarm");
this.cellFarm.Weight = 2.30456342290368;
this.cellFarm.BeforePrint += new System.Drawing.Printing.PrintEventHandler(this.cellFarm_BeforePrint);
//
// xrTableCell12
//
this.xrTableCell12.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
this.xrTableCell12.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "SessionFarm.strOwnerName")});
this.xrTableCell12.Name = "xrTableCell12";
this.xrTableCell12.StylePriority.UseBorders = false;
resources.ApplyResources(this.xrTableCell12, "xrTableCell12");
this.xrTableCell12.Weight = 3.5610065485516667;
//
// xrTableCell13
//
this.xrTableCell13.Borders = ((DevExpress.XtraPrinting.BorderSide)((DevExpress.XtraPrinting.BorderSide.Right | DevExpress.XtraPrinting.BorderSide.Bottom)));
this.xrTableCell13.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "SessionFarm.strFarmAddress")});
this.xrTableCell13.Name = "xrTableCell13";
this.xrTableCell13.StylePriority.UseBorders = false;
resources.ApplyResources(this.xrTableCell13, "xrTableCell13");
this.xrTableCell13.Weight = 5.1240076652634032;
//
// m_SessionFarmReportDataSet
//
this.m_SessionFarmReportDataSet.DataSetName = "SessionFarmReportDataSet";
this.m_SessionFarmReportDataSet.SchemaSerializationMode = System.Data.SchemaSerializationMode.IncludeSchema;
//
// m_SessionFarmAdapter
//
this.m_SessionFarmAdapter.ClearBeforeFill = true;
//
// GroupFooter1
//
resources.ApplyResources(this.GroupFooter1, "GroupFooter1");
this.GroupFooter1.Name = "GroupFooter1";
//
// SessionFarmReport
//
this.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] {
this.Detail,
this.TopMargin,
this.BottomMargin,
this.PageHeader,
this.GroupHeader1,
this.GroupFooter1});
this.DataAdapter = this.m_SessionFarmAdapter;
this.DataMember = "SessionFarm";
this.DataSource = this.m_SessionFarmReportDataSet;
this.Landscape = true;
resources.ApplyResources(this, "$this");
this.PageHeight = 827;
this.PageWidth = 1169;
this.PaperKind = System.Drawing.Printing.PaperKind.A4;
this.Version = "10.1";
((System.ComponentModel.ISupportInitialize)(this.xrTable2)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.MainTable)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.xrTable1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.m_SessionFarmReportDataSet)).EndInit();
((System.ComponentModel.ISupportInitialize)(this)).EndInit();
}
#endregion
private DevExpress.XtraReports.UI.DetailBand Detail;
private DevExpress.XtraReports.UI.TopMarginBand TopMargin;
private DevExpress.XtraReports.UI.BottomMarginBand BottomMargin;
private DevExpress.XtraReports.UI.PageHeaderBand PageHeader;
private DevExpress.XtraReports.UI.XRTable MainTable;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow1;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell1;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell2;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell3;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell7;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell4;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell8;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell5;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell9;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell6;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell10;
private DevExpress.XtraReports.UI.GroupHeaderBand GroupHeader1;
private DevExpress.XtraReports.UI.XRTable xrTable1;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow2;
private DevExpress.XtraReports.UI.XRTableCell cellFarm;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell12;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell13;
private SessionFarmReportDataSet m_SessionFarmReportDataSet;
private SessionFarmAdapter m_SessionFarmAdapter;
private DevExpress.XtraReports.UI.XRTable xrTable2;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow3;
private DevExpress.XtraReports.UI.XRTableCell cellNo;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell15;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell16;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell17;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell18;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell19;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell20;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell21;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell22;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell23;
private DevExpress.XtraReports.UI.GroupFooterBand GroupFooter1;
}
}
| |
// 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.ServiceModel
{
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Runtime;
using System.ServiceModel.Channels;
using System.Text;
using Microsoft.Xml;
public class UdpBinding : Binding, IBindingRuntimePreferences
{
private TextMessageEncodingBindingElement _textEncoding;
private UdpTransportBindingElement _udpTransport;
public UdpBinding()
: base()
{
_textEncoding = new TextMessageEncodingBindingElement();
_udpTransport = new UdpTransportBindingElement();
}
private UdpBinding(UdpTransportBindingElement transport, TextMessageEncodingBindingElement encoding)
: this()
{
this.DuplicateMessageHistoryLength = transport.DuplicateMessageHistoryLength;
this.MaxBufferPoolSize = transport.MaxBufferPoolSize;
this.MaxPendingMessagesTotalSize = transport.MaxPendingMessagesTotalSize;
this.MaxReceivedMessageSize = transport.MaxReceivedMessageSize;
this.MaxRetransmitCount = Math.Max(transport.RetransmissionSettings.MaxUnicastRetransmitCount, transport.RetransmissionSettings.MaxMulticastRetransmitCount);
this.MulticastInterfaceId = transport.MulticastInterfaceId;
this.TimeToLive = transport.TimeToLive;
this.ReaderQuotas = encoding.ReaderQuotas;
this.TextEncoding = encoding.WriteEncoding;
}
[DefaultValue(UdpConstants.Defaults.DuplicateMessageHistoryLength)]
public int DuplicateMessageHistoryLength
{
get
{
return _udpTransport.DuplicateMessageHistoryLength;
}
set
{
_udpTransport.DuplicateMessageHistoryLength = value;
}
}
[DefaultValue(TransportDefaults.MaxBufferPoolSize)]
public long MaxBufferPoolSize
{
get
{
return _udpTransport.MaxBufferPoolSize;
}
set
{
_udpTransport.MaxBufferPoolSize = value;
}
}
[DefaultValue(UdpConstants.Defaults.MaxRetransmitCount)]
public int MaxRetransmitCount
{
get
{
return Math.Max(_udpTransport.RetransmissionSettings.MaxUnicastRetransmitCount, _udpTransport.RetransmissionSettings.MaxMulticastRetransmitCount);
}
set
{
_udpTransport.RetransmissionSettings.MaxUnicastRetransmitCount = value;
_udpTransport.RetransmissionSettings.MaxMulticastRetransmitCount = value;
}
}
[DefaultValue(UdpConstants.Defaults.DefaultMaxPendingMessagesTotalSize)]
public long MaxPendingMessagesTotalSize
{
get
{
return _udpTransport.MaxPendingMessagesTotalSize;
}
set
{
_udpTransport.MaxPendingMessagesTotalSize = value;
}
}
[DefaultValue(UdpConstants.Defaults.MaxReceivedMessageSize)]
public long MaxReceivedMessageSize
{
get
{
return _udpTransport.MaxReceivedMessageSize;
}
set
{
_udpTransport.MaxReceivedMessageSize = value;
}
}
[DefaultValue(UdpConstants.Defaults.MulticastInterfaceId)]
public string MulticastInterfaceId
{
get { return _udpTransport.MulticastInterfaceId; }
set { _udpTransport.MulticastInterfaceId = value; }
}
public XmlDictionaryReaderQuotas ReaderQuotas
{
get { return _textEncoding.ReaderQuotas; }
set
{
if (value == null)
{
throw FxTrace.Exception.ArgumentNull("value");
}
value.CopyTo(_textEncoding.ReaderQuotas);
}
}
//TODO: [TypeConverter(typeof(EncodingConverter))]
public Encoding TextEncoding
{
get { return _textEncoding.WriteEncoding; }
set { _textEncoding.WriteEncoding = value; }
}
[DefaultValue(UdpConstants.Defaults.TimeToLive)]
public int TimeToLive
{
get { return _udpTransport.TimeToLive; }
set { _udpTransport.TimeToLive = value; }
}
public override string Scheme
{
get { return _udpTransport.Scheme; }
}
public override BindingElementCollection CreateBindingElements()
{
BindingElementCollection bindingElements = new BindingElementCollection();
bindingElements.Add(_textEncoding);
bindingElements.Add(_udpTransport);
return bindingElements.Clone();
}
private bool BindingElementsPropertiesMatch(UdpTransportBindingElement transport, MessageEncodingBindingElement encoding)
{
if (!_udpTransport.IsMatch(transport))
{
return false;
}
if (!_textEncoding.IsMatch(encoding))
{
return false;
}
return true;
}
[SuppressMessage(FxCop.Category.Design, FxCop.Rule.InterfaceMethodsShouldBeCallableByChildTypes, Justification = "no need to call this from derrived classes")]
bool IBindingRuntimePreferences.ReceiveSynchronously
{
get { return false; }
}
[EditorBrowsable(EditorBrowsableState.Never)]
public bool ShouldSerializeReaderQuotas()
{
return (!EncoderDefaults.IsDefaultReaderQuotas(this.ReaderQuotas));
}
[EditorBrowsable(EditorBrowsableState.Never)]
public bool ShouldSerializeTextEncoding()
{
return (!this.TextEncoding.Equals(TextEncoderDefaults.Encoding));
}
internal static bool TryCreate(BindingElementCollection bindingElements, out Binding binding)
{
binding = null;
if (bindingElements.Count > 2)
{
return false;
}
UdpTransportBindingElement transport = null;
TextMessageEncodingBindingElement encoding = null;
foreach (BindingElement bindingElement in bindingElements)
{
if (bindingElement is UdpTransportBindingElement)
{
transport = bindingElement as UdpTransportBindingElement;
}
else if (bindingElement is TextMessageEncodingBindingElement)
{
encoding = bindingElement as TextMessageEncodingBindingElement;
}
else
{
return false;
}
}
if (transport == null || encoding == null)
{
return false;
}
UdpBinding udpBinding = new UdpBinding(transport, encoding);
if (!udpBinding.BindingElementsPropertiesMatch(transport, encoding))
{
return false;
}
binding = udpBinding;
return true;
}
}
}
| |
// 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.
/*
* Ordered String/Object collection of name/value pairs with support for null key
*
* This class is intended to be used as a base class
*
*/
#pragma warning disable 618 // obsolete types, namely IHashCodeProvider
using System.Globalization;
using System.Runtime.Serialization;
namespace System.Collections.Specialized
{
/// <devdoc>
/// <para>Provides the <see langword='abstract '/>base class for a sorted collection of associated <see cref='System.String' qualify='true'/> keys
/// and <see cref='System.Object' qualify='true'/> values that can be accessed either with the hash code of
/// the key or with the index.</para>
/// </devdoc>
public abstract class NameObjectCollectionBase : ICollection, ISerializable, IDeserializationCallback
{
// const names used for serialization
private const String ReadOnlyName = "ReadOnly";
private const String CountName = "Count";
private const String ComparerName = "Comparer";
private const String HashCodeProviderName = "HashProvider";
private const String KeysName = "Keys";
private const String ValuesName = "Values";
private const String KeyComparerName = "KeyComparer";
private const String VersionName = "Version";
private bool _readOnly = false;
private ArrayList _entriesArray;
private IEqualityComparer _keyComparer;
private volatile Hashtable _entriesTable;
private volatile NameObjectEntry _nullKeyEntry;
private KeysCollection _keys;
private int _version;
private SerializationInfo _serializationInfo;
[NonSerialized]
private Object _syncRoot;
private static readonly StringComparer s_defaultComparer = CultureInfo.InvariantCulture.CompareInfo.GetStringComparer(CompareOptions.IgnoreCase);
/// <devdoc>
/// <para> Creates an empty <see cref='System.Collections.Specialized.NameObjectCollectionBase'/> instance with the default initial capacity and using the default case-insensitive hash
/// code provider and the default case-insensitive comparer.</para>
/// </devdoc>
protected NameObjectCollectionBase() : this(s_defaultComparer)
{
}
protected NameObjectCollectionBase(IEqualityComparer equalityComparer)
{
_keyComparer = (equalityComparer == null) ? s_defaultComparer : equalityComparer;
Reset();
}
protected NameObjectCollectionBase(Int32 capacity, IEqualityComparer equalityComparer) : this(equalityComparer)
{
Reset(capacity);
}
[Obsolete("Please use NameObjectCollectionBase(IEqualityComparer) instead.")]
protected NameObjectCollectionBase(IHashCodeProvider hashProvider, IComparer comparer) {
_keyComparer = new CompatibleComparer(hashProvider, comparer);
Reset();
}
[Obsolete("Please use NameObjectCollectionBase(Int32, IEqualityComparer) instead.")]
protected NameObjectCollectionBase(int capacity, IHashCodeProvider hashProvider, IComparer comparer) {
_keyComparer = new CompatibleComparer(hashProvider, comparer);
Reset(capacity);
}
/// <devdoc>
/// <para>Creates an empty <see cref='System.Collections.Specialized.NameObjectCollectionBase'/> instance with the specified
/// initial capacity and using the default case-insensitive hash code provider
/// and the default case-insensitive comparer.</para>
/// </devdoc>
protected NameObjectCollectionBase(int capacity)
{
_keyComparer = s_defaultComparer;
Reset(capacity);
}
protected NameObjectCollectionBase(SerializationInfo info, StreamingContext context)
{
_serializationInfo = info;
}
public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
{
throw new ArgumentNullException(nameof(info));
}
info.AddValue(ReadOnlyName, _readOnly);
// Maintain backward serialization compatibility if new APIs are not used.
if (_keyComparer == s_defaultComparer)
{
info.AddValue(HashCodeProviderName, CaseInsensitiveHashCodeProvider.DefaultInvariant, typeof(IHashCodeProvider));
info.AddValue(ComparerName, CaseInsensitiveComparer.DefaultInvariant, typeof(IComparer));
}
else if (_keyComparer == null)
{
info.AddValue(HashCodeProviderName, null, typeof(IHashCodeProvider));
info.AddValue(ComparerName, null, typeof(IComparer));
}
else if (_keyComparer is CompatibleComparer)
{
CompatibleComparer c = (CompatibleComparer)_keyComparer;
info.AddValue(HashCodeProviderName, c.HashCodeProvider, typeof(IHashCodeProvider));
info.AddValue(ComparerName, c.Comparer, typeof(IComparer));
}
else
{
info.AddValue(KeyComparerName, _keyComparer, typeof(IEqualityComparer));
}
int count = _entriesArray.Count;
info.AddValue(CountName, count);
string[] keys = new string[count];
object[] values = new object[count];
for (int i = 0; i < count; i++)
{
NameObjectEntry entry = (NameObjectEntry)_entriesArray[i];
keys[i] = entry.Key;
values[i] = entry.Value;
}
info.AddValue(KeysName, keys, typeof(String[]));
info.AddValue(ValuesName, values, typeof(Object[]));
info.AddValue(VersionName, _version);
}
public virtual void OnDeserialization(object sender)
{
if (_keyComparer != null)
{
//Somebody had a dependency on this and fixed us up before the ObjectManager got to it.
return;
}
if (_serializationInfo == null)
{
throw new SerializationException();
}
SerializationInfo info = _serializationInfo;
_serializationInfo = null;
bool readOnly = false;
int count = 0;
string[] keys = null;
object[] values = null;
IHashCodeProvider hashProvider = null;
IComparer comparer = null;
bool hasVersion = false;
int serializedVersion = 0;
SerializationInfoEnumerator enumerator = info.GetEnumerator();
while (enumerator.MoveNext())
{
switch (enumerator.Name)
{
case ReadOnlyName:
readOnly = info.GetBoolean(ReadOnlyName); ;
break;
case HashCodeProviderName:
hashProvider = (IHashCodeProvider)info.GetValue(HashCodeProviderName, typeof(IHashCodeProvider)); ;
break;
case ComparerName:
comparer = (IComparer)info.GetValue(ComparerName, typeof(IComparer));
break;
case KeyComparerName:
_keyComparer = (IEqualityComparer)info.GetValue(KeyComparerName, typeof(IEqualityComparer));
break;
case CountName:
count = info.GetInt32(CountName);
break;
case KeysName:
keys = (String[])info.GetValue(KeysName, typeof(String[]));
break;
case ValuesName:
values = (Object[])info.GetValue(ValuesName, typeof(Object[]));
break;
case VersionName:
hasVersion = true;
serializedVersion = info.GetInt32(VersionName);
break;
}
}
if (_keyComparer == null)
{
if (comparer == null || hashProvider == null)
{
throw new SerializationException();
}
else
{
// create a new key comparer for V1 Object
_keyComparer = new CompatibleComparer(hashProvider, comparer);
}
}
if (keys == null || values == null)
{
throw new SerializationException();
}
Reset(count);
for (int i = 0; i < count; i++)
{
BaseAdd(keys[i], values[i]);
}
_readOnly = readOnly; // after collection populated
if (hasVersion)
{
_version = serializedVersion;
}
}
//
// Private helpers
//
private void Reset()
{
_entriesArray = new ArrayList();
_entriesTable = new Hashtable(_keyComparer);
_nullKeyEntry = null;
_version++;
}
private void Reset(int capacity)
{
_entriesArray = new ArrayList(capacity);
_entriesTable = new Hashtable(capacity, _keyComparer);
_nullKeyEntry = null;
_version++;
}
private NameObjectEntry FindEntry(String key)
{
if (key != null)
return (NameObjectEntry)_entriesTable[key];
else
return _nullKeyEntry;
}
internal IEqualityComparer Comparer
{
get
{
return _keyComparer;
}
set
{
_keyComparer = value;
}
}
/// <devdoc>
/// <para>Gets or sets a value indicating whether the <see cref='System.Collections.Specialized.NameObjectCollectionBase'/> instance is read-only.</para>
/// </devdoc>
protected bool IsReadOnly
{
get { return _readOnly; }
set { _readOnly = value; }
}
/// <devdoc>
/// <para>Gets a value indicating whether the <see cref='System.Collections.Specialized.NameObjectCollectionBase'/> instance contains entries whose
/// keys are not <see langword='null'/>.</para>
/// </devdoc>
protected bool BaseHasKeys()
{
return (_entriesTable.Count > 0); // any entries with keys?
}
//
// Methods to add / remove entries
//
/// <devdoc>
/// <para>Adds an entry with the specified key and value into the
/// <see cref='System.Collections.Specialized.NameObjectCollectionBase'/> instance.</para>
/// </devdoc>
protected void BaseAdd(String name, Object value)
{
if (_readOnly)
throw new NotSupportedException(SR.CollectionReadOnly);
NameObjectEntry entry = new NameObjectEntry(name, value);
// insert entry into hashtable
if (name != null)
{
if (_entriesTable[name] == null)
_entriesTable.Add(name, entry);
}
else
{ // null key -- special case -- hashtable doesn't like null keys
if (_nullKeyEntry == null)
_nullKeyEntry = entry;
}
// add entry to the list
_entriesArray.Add(entry);
_version++;
}
/// <devdoc>
/// <para>Removes the entries with the specified key from the
/// <see cref='System.Collections.Specialized.NameObjectCollectionBase'/> instance.</para>
/// </devdoc>
protected void BaseRemove(String name)
{
if (_readOnly)
throw new NotSupportedException(SR.CollectionReadOnly);
if (name != null)
{
// remove from hashtable
_entriesTable.Remove(name);
// remove from array
for (int i = _entriesArray.Count - 1; i >= 0; i--)
{
if (_keyComparer.Equals(name, BaseGetKey(i)))
_entriesArray.RemoveAt(i);
}
}
else
{ // null key -- special case
// null out special 'null key' entry
_nullKeyEntry = null;
// remove from array
for (int i = _entriesArray.Count - 1; i >= 0; i--)
{
if (BaseGetKey(i) == null)
_entriesArray.RemoveAt(i);
}
}
_version++;
}
/// <devdoc>
/// <para> Removes the entry at the specified index of the
/// <see cref='System.Collections.Specialized.NameObjectCollectionBase'/> instance.</para>
/// </devdoc>
protected void BaseRemoveAt(int index)
{
if (_readOnly)
throw new NotSupportedException(SR.CollectionReadOnly);
String key = BaseGetKey(index);
if (key != null)
{
// remove from hashtable
_entriesTable.Remove(key);
}
else
{ // null key -- special case
// null out special 'null key' entry
_nullKeyEntry = null;
}
// remove from array
_entriesArray.RemoveAt(index);
_version++;
}
/// <devdoc>
/// <para>Removes all entries from the <see cref='System.Collections.Specialized.NameObjectCollectionBase'/> instance.</para>
/// </devdoc>
protected void BaseClear()
{
if (_readOnly)
throw new NotSupportedException(SR.CollectionReadOnly);
Reset();
}
//
// Access by name
//
/// <devdoc>
/// <para>Gets the value of the first entry with the specified key from
/// the <see cref='System.Collections.Specialized.NameObjectCollectionBase'/> instance.</para>
/// </devdoc>
protected Object BaseGet(String name)
{
NameObjectEntry e = FindEntry(name);
return (e != null) ? e.Value : null;
}
/// <devdoc>
/// <para>Sets the value of the first entry with the specified key in the <see cref='System.Collections.Specialized.NameObjectCollectionBase'/>
/// instance, if found; otherwise, adds an entry with the specified key and value
/// into the <see cref='System.Collections.Specialized.NameObjectCollectionBase'/>
/// instance.</para>
/// </devdoc>
protected void BaseSet(String name, Object value)
{
if (_readOnly)
throw new NotSupportedException(SR.CollectionReadOnly);
NameObjectEntry entry = FindEntry(name);
if (entry != null)
{
entry.Value = value;
_version++;
}
else
{
BaseAdd(name, value);
}
}
//
// Access by index
//
/// <devdoc>
/// <para>Gets the value of the entry at the specified index of
/// the <see cref='System.Collections.Specialized.NameObjectCollectionBase'/> instance.</para>
/// </devdoc>
protected Object BaseGet(int index)
{
NameObjectEntry entry = (NameObjectEntry)_entriesArray[index];
return entry.Value;
}
/// <devdoc>
/// <para>Gets the key of the entry at the specified index of the
/// <see cref='System.Collections.Specialized.NameObjectCollectionBase'/>
/// instance.</para>
/// </devdoc>
protected String BaseGetKey(int index)
{
NameObjectEntry entry = (NameObjectEntry)_entriesArray[index];
return entry.Key;
}
/// <devdoc>
/// <para>Sets the value of the entry at the specified index of
/// the <see cref='System.Collections.Specialized.NameObjectCollectionBase'/> instance.</para>
/// </devdoc>
protected void BaseSet(int index, Object value)
{
if (_readOnly)
throw new NotSupportedException(SR.CollectionReadOnly);
NameObjectEntry entry = (NameObjectEntry)_entriesArray[index];
entry.Value = value;
_version++;
}
//
// ICollection implementation
//
/// <devdoc>
/// <para>Returns an enumerator that can iterate through the <see cref='System.Collections.Specialized.NameObjectCollectionBase'/>.</para>
/// </devdoc>
public virtual IEnumerator GetEnumerator()
{
return new NameObjectKeysEnumerator(this);
}
/// <devdoc>
/// <para>Gets the number of key-and-value pairs in the <see cref='System.Collections.Specialized.NameObjectCollectionBase'/> instance.</para>
/// </devdoc>
public virtual int Count
{
get
{
return _entriesArray.Count;
}
}
void ICollection.CopyTo(Array array, int index)
{
if (array == null)
{
throw new ArgumentNullException(nameof(array));
}
if (array.Rank != 1)
{
throw new ArgumentException(SR.Arg_MultiRank, nameof(array));
}
if (index < 0)
{
throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (array.Length - index < _entriesArray.Count)
{
throw new ArgumentException(SR.Arg_InsufficientSpace);
}
for (IEnumerator e = this.GetEnumerator(); e.MoveNext();)
array.SetValue(e.Current, index++);
}
Object ICollection.SyncRoot
{
get
{
if (_syncRoot == null)
{
System.Threading.Interlocked.CompareExchange(ref _syncRoot, new Object(), null);
}
return _syncRoot;
}
}
bool ICollection.IsSynchronized
{
get { return false; }
}
//
// Helper methods to get arrays of keys and values
//
/// <devdoc>
/// <para>Returns a <see cref='System.String' qualify='true'/> array containing all the keys in the
/// <see cref='System.Collections.Specialized.NameObjectCollectionBase'/> instance.</para>
/// </devdoc>
protected String[] BaseGetAllKeys()
{
int n = _entriesArray.Count;
String[] allKeys = new String[n];
for (int i = 0; i < n; i++)
allKeys[i] = BaseGetKey(i);
return allKeys;
}
/// <devdoc>
/// <para>Returns an <see cref='System.Object' qualify='true'/> array containing all the values in the
/// <see cref='System.Collections.Specialized.NameObjectCollectionBase'/> instance.</para>
/// </devdoc>
protected Object[] BaseGetAllValues()
{
int n = _entriesArray.Count;
Object[] allValues = new Object[n];
for (int i = 0; i < n; i++)
allValues[i] = BaseGet(i);
return allValues;
}
/// <devdoc>
/// <para>Returns an array of the specified type containing
/// all the values in the <see cref='System.Collections.Specialized.NameObjectCollectionBase'/> instance.</para>
/// </devdoc>
protected object[] BaseGetAllValues(Type type)
{
int n = _entriesArray.Count;
if (type == null)
{
throw new ArgumentNullException(nameof(type));
}
object[] allValues = (object[])Array.CreateInstance(type, n);
for (int i = 0; i < n; i++)
{
allValues[i] = BaseGet(i);
}
return allValues;
}
//
// Keys property
//
/// <devdoc>
/// <para>Returns a <see cref='System.Collections.Specialized.NameObjectCollectionBase.KeysCollection'/> instance containing
/// all the keys in the <see cref='System.Collections.Specialized.NameObjectCollectionBase'/> instance.</para>
/// </devdoc>
public virtual KeysCollection Keys
{
get
{
if (_keys == null)
_keys = new KeysCollection(this);
return _keys;
}
}
//
// Simple entry class to allow substitution of values and indexed access to keys
//
internal class NameObjectEntry
{
internal NameObjectEntry(String name, Object value)
{
Key = name;
Value = value;
}
internal String Key;
internal Object Value;
}
//
// Enumerator over keys of NameObjectCollection
//
internal class NameObjectKeysEnumerator : IEnumerator
{
private int _pos;
private NameObjectCollectionBase _coll;
private int _version;
internal NameObjectKeysEnumerator(NameObjectCollectionBase coll)
{
_coll = coll;
_version = _coll._version;
_pos = -1;
}
public bool MoveNext()
{
if (_version != _coll._version)
throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion);
if (_pos < _coll.Count - 1)
{
_pos++;
return true;
}
else
{
_pos = _coll.Count;
return false;
}
}
public void Reset()
{
if (_version != _coll._version)
throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion);
_pos = -1;
}
public Object Current
{
get
{
if (_pos >= 0 && _pos < _coll.Count)
{
return _coll.BaseGetKey(_pos);
}
else
{
throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen);
}
}
}
}
//
// Keys collection
//
/// <devdoc>
/// <para>Represents a collection of the <see cref='System.String' qualify='true'/> keys of a collection.</para>
/// </devdoc>
public class KeysCollection : ICollection
{
private NameObjectCollectionBase _coll;
internal KeysCollection(NameObjectCollectionBase coll)
{
_coll = coll;
}
// Indexed access
/// <devdoc>
/// <para> Gets the key at the specified index of the collection.</para>
/// </devdoc>
public virtual String Get(int index)
{
return _coll.BaseGetKey(index);
}
/// <devdoc>
/// <para>Represents the entry at the specified index of the collection.</para>
/// </devdoc>
public String this[int index]
{
get
{
return Get(index);
}
}
// ICollection implementation
/// <devdoc>
/// <para>Returns an enumerator that can iterate through the
/// <see cref='System.Collections.Specialized.NameObjectCollectionBase.KeysCollection'/>.</para>
/// </devdoc>
public IEnumerator GetEnumerator()
{
return new NameObjectKeysEnumerator(_coll);
}
/// <devdoc>
/// <para>Gets the number of keys in the <see cref='System.Collections.Specialized.NameObjectCollectionBase.KeysCollection'/>.</para>
/// </devdoc>
public int Count
{
get
{
return _coll.Count;
}
}
void ICollection.CopyTo(Array array, int index)
{
if (array == null)
{
throw new ArgumentNullException(nameof(array));
}
if (array.Rank != 1)
{
throw new ArgumentException(SR.Arg_MultiRank, nameof(array));
}
if (index < 0)
{
throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (array.Length - index < _coll.Count)
{
throw new ArgumentException(SR.Arg_InsufficientSpace);
}
for (IEnumerator e = this.GetEnumerator(); e.MoveNext();)
array.SetValue(e.Current, index++);
}
Object ICollection.SyncRoot
{
get { return ((ICollection)_coll).SyncRoot; }
}
bool ICollection.IsSynchronized
{
get { return false; }
}
}
}
}
| |
public static class GlobalMembersColor_name
{
/* $Id$ */
#if __cplusplus
#endif
#define GD_H
#define GD_MAJOR_VERSION
#define GD_MINOR_VERSION
#define GD_RELEASE_VERSION
#define GD_EXTRA_VERSION
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdXXX_VERSION_STR(mjr, mnr, rev, ext) mjr "." mnr "." rev ext
#define GDXXX_VERSION_STR
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdXXX_STR(s) gd.gdXXX_SSTR(s)
#define GDXXX_STR
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdXXX_SSTR(s) #s
#define GDXXX_SSTR
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define GD_VERSION_STRING "GD_MAJOR_VERSION" "." "GD_MINOR_VERSION" "." "GD_RELEASE_VERSION" GD_EXTRA_VERSION
#define GD_VERSION_STRING
#if _WIN32 || CYGWIN || _WIN32_WCE
#if BGDWIN32
#if NONDLL
#define BGD_EXPORT_DATA_PROT
#else
#if __GNUC__
#define BGD_EXPORT_DATA_PROT
#else
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define BGD_EXPORT_DATA_PROT __declspec(dllexport)
#define BGD_EXPORT_DATA_PROT
#endif
#endif
#else
#if __GNUC__
#define BGD_EXPORT_DATA_PROT
#else
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define BGD_EXPORT_DATA_PROT __declspec(dllimport)
#define BGD_EXPORT_DATA_PROT
#endif
#endif
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define BGD_STDCALL __stdcall
#define BGD_STDCALL
#define BGD_EXPORT_DATA_IMPL
#else
#if HAVE_VISIBILITY
#define BGD_EXPORT_DATA_PROT
#define BGD_EXPORT_DATA_IMPL
#else
#define BGD_EXPORT_DATA_PROT
#define BGD_EXPORT_DATA_IMPL
#endif
#define BGD_STDCALL
#endif
#if BGD_EXPORT_DATA_PROT_ConditionalDefinition1
#if BGD_STDCALL_ConditionalDefinition1
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define BGD_DECLARE (rt) rt __stdcall
#define BGD_DECLARE
#elif BGD_STDCALL_ConditionalDefinition2
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define BGD_DECLARE (rt) rt
#define BGD_DECLARE
#else
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define BGD_DECLARE (rt) rt BGD_STDCALLTangibleTempImmunity
#define BGD_DECLARE
#endif
#elif BGD_EXPORT_DATA_PROT_ConditionalDefinition2
#if BGD_STDCALL_ConditionalDefinition1
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define BGD_DECLARE (rt) rt __stdcall
#define BGD_DECLARE
#elif BGD_STDCALL_ConditionalDefinition2
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define BGD_DECLARE (rt) rt
#define BGD_DECLARE
#else
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define BGD_DECLARE (rt) rt BGD_STDCALLTangibleTempImmunity
#define BGD_DECLARE
#endif
#elif BGD_EXPORT_DATA_PROT_ConditionalDefinition3
#if BGD_STDCALL_ConditionalDefinition1
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define BGD_DECLARE (rt) __declspec(dllexport) rt __stdcall
#define BGD_DECLARE
#elif BGD_STDCALL_ConditionalDefinition2
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define BGD_DECLARE (rt) __declspec(dllexport) rt
#define BGD_DECLARE
#else
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define BGD_DECLARE (rt) __declspec(dllexport) rt BGD_STDCALLTangibleTempImmunity
#define BGD_DECLARE
#endif
#elif BGD_EXPORT_DATA_PROT_ConditionalDefinition4
#if BGD_STDCALL_ConditionalDefinition1
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define BGD_DECLARE (rt) __declspec(dllimport) rt __stdcall
#define BGD_DECLARE
#elif BGD_STDCALL_ConditionalDefinition2
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define BGD_DECLARE (rt) __declspec(dllimport) rt
#define BGD_DECLARE
#else
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define BGD_DECLARE (rt) __declspec(dllimport) rt BGD_STDCALLTangibleTempImmunity
#define BGD_DECLARE
#endif
#else
#if BGD_STDCALL_ConditionalDefinition1
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define BGD_DECLARE (rt) BGD_EXPORT_DATA_PROTTangibleTempImmunity rt __stdcall
#define BGD_DECLARE
#elif BGD_STDCALL_ConditionalDefinition2
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define BGD_DECLARE (rt) BGD_EXPORT_DATA_PROTTangibleTempImmunity rt
#define BGD_DECLARE
#else
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define Bgd.gd_DECLARE(rt) BGD_EXPORT_DATA_PROTTangibleTempImmunity rt BGD_STDCALLTangibleTempImmunity
#define BGD_DECLARE
#endif
#endif
#if __cplusplus
#endif
#if __cplusplus
#endif
#define GD_IO_H
#if VMS
#endif
#if __cplusplus
#endif
#define gdMaxColors
#define gdAlphaMax
#define gdAlphaOpaque
#define gdAlphaTransparent
#define gdRedMax
#define gdGreenMax
#define gdBlueMax
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdTrueColorGetAlpha(c) (((c) & 0x7F000000) >> 24)
#define gdTrueColorGetAlpha
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdTrueColorGetRed(c) (((c) & 0xFF0000) >> 16)
#define gdTrueColorGetRed
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdTrueColorGetGreen(c) (((c) & 0x00FF00) >> 8)
#define gdTrueColorGetGreen
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdTrueColorGetBlue(c) ((c) & 0x0000FF)
#define gdTrueColorGetBlue
#define gdEffectReplace
#define gdEffectAlphaBlend
#define gdEffectNormal
#define gdEffectOverlay
#define GD_TRUE
#define GD_FALSE
#define GD_EPSILON
#define M_PI
#define gdDashSize
#define gdStyled
#define gdBrushed
#define gdStyledBrushed
#define gdTiled
#define gdTransparent
#define gdAntiAliased
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gdImageCreatePalette gdImageCreate
#define gdImageCreatePalette
#define gdFTEX_LINESPACE
#define gdFTEX_CHARMAP
#define gdFTEX_RESOLUTION
#define gdFTEX_DISABLE_KERNING
#define gdFTEX_XSHOW
#define gdFTEX_FONTPATHNAME
#define gdFTEX_FONTCONFIG
#define gdFTEX_RETURNFONTPATHNAME
#define gdFTEX_Unicode
#define gdFTEX_Shift_JIS
#define gdFTEX_Big5
#define gdFTEX_Adobe_Custom
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdTrueColor(r, g, b) (((r) << 16) + ((g) << 8) + (b))
#define gdTrueColor
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdTrueColorAlpha(r, g, b, a) (((a) << 24) + ((r) << 16) + ((g) << 8) + (b))
#define gdTrueColorAlpha
#define gdArc
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gdPie gdArc
#define gdPie
#define gdChord
#define gdNoFill
#define gdEdged
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdImageTrueColor(im) ((im)->trueColor)
#define gdImageTrueColor
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdImageSX(im) ((im)->sx)
#define gdImageSX
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdImageSY(im) ((im)->sy)
#define gdImageSY
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdImageColorsTotal(im) ((im)->colorsTotal)
#define gdImageColorsTotal
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdImageRed(im, c) ((im)->trueColor ? (((c) & 0xFF0000) >> 16) : (im)->red[(c)])
#define gdImageRed
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdImageGreen(im, c) ((im)->trueColor ? (((c) & 0x00FF00) >> 8) : (im)->green[(c)])
#define gdImageGreen
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdImageBlue(im, c) ((im)->trueColor ? ((c) & 0x0000FF) : (im)->blue[(c)])
#define gdImageBlue
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdImageAlpha(im, c) ((im)->trueColor ? (((c) & 0x7F000000) >> 24) : (im)->alpha[(c)])
#define gdImageAlpha
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdImageGetTransparent(im) ((im)->transparent)
#define gdImageGetTransparent
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdImageGetInterlaced(im) ((im)->interlace)
#define gdImageGetInterlaced
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdImagePalettePixel(im, x, y) (im)->pixels[(y)][(x)]
#define gdImagePalettePixel
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdImageTrueColorPixel(im, x, y) (im)->tpixels[(y)][(x)]
#define gdImageTrueColorPixel
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdImageResolutionX(im) (im)->res_x
#define gdImageResolutionX
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdImageResolutionY(im) (im)->res_y
#define gdImageResolutionY
#define GD2_CHUNKSIZE
#define GD2_CHUNKSIZE_MIN
#define GD2_CHUNKSIZE_MAX
#define GD2_VERS
#define GD2_ID
#define GD2_FMT_RAW
#define GD2_FMT_COMPRESSED
#define GD_FLIP_HORINZONTAL
#define GD_FLIP_VERTICAL
#define GD_FLIP_BOTH
#define GD_CMP_IMAGE
#define GD_CMP_NUM_COLORS
#define GD_CMP_COLOR
#define GD_CMP_SIZE_X
#define GD_CMP_SIZE_Y
#define GD_CMP_TRANSPARENT
#define GD_CMP_BACKGROUND
#define GD_CMP_INTERLACE
#define GD_CMP_TRUECOLOR
#define GD_RESOLUTION
#if __cplusplus
#endif
#if __cplusplus
#endif
#define GDFX_H
#if __cplusplus
#endif
#if __cplusplus
#endif
#define GDTEST_TOP_DIR
#define GDTEST_STRING_MAX
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdAssertImageEqualsToFile(ex,ac) gd.gdTestImageCompareToFile(__FILE__,__LINE__,NULL,(ex),(ac))
#define gdAssertImageEqualsToFile
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdAssertImageFileEqualsMsg(ex,ac) gd.gdTestImageCompareFiles(__FILE__,__LINE__,(ms),(ex),(ac))
#define gdAssertImageFileEqualsMsg
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdAssertImageEquals(tc,ex,ac) CuAssertImageEquals_LineMsg((tc),__FILE__,__LINE__,NULL,(ex),(ac))
#define gdAssertImageEquals
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdAssertImageEqualsMsg(tc,ex,ac) CuAssertImageEquals_LineMsg((tc),__FILE__,__LINE__,(ms),(ex),(ac))
#define gdAssertImageEqualsMsg
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdTestAssert(cond) _gd.gdTestAssert(__FILE__, __LINE__, "assert failed in <%s:%i>\n", (cond))
#define gdTestAssert
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdTestErrorMsg(...) _gd.gdTestErrorMsg(__FILE__, __LINE__, __VA_ARGS__)
#define gdTestErrorMsg
static int Main()
{
gdImageStruct im;
string path = new string(new char[1024]);
int c;
int result;
path = string.Format("{0}/xpm/color_name.xpm", DefineConstants.GDTEST_TOP_DIR);
im = gd.gdImageCreateFromXpm(path);
if (im == null)
{
return 2;
}
c = gd.gdImageGetPixel(im, 2, 2);
if (((im).trueColor != 0 ? (((c) & 0xFF0000) >> 16) : (im).red[(c)]) == 0xFF && ((im).trueColor != 0 ? (((c) & 0x00FF00) >> 8) : (im).green[(c)]) == 0xFF && ((im).trueColor != 0 ? ((c) & 0x0000FF) : (im).blue[(c)]) == 0x0)
{
result = 0;
}
else
{
result = 1;
}
gd.gdImageDestroy(im);
return result;
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//
namespace System.Reflection.Emit
{
using System.Runtime.InteropServices;
using System;
using System.Reflection;
using System.Diagnostics.Contracts;
using CultureInfo = System.Globalization.CultureInfo;
[Serializable]
internal enum TypeKind
{
IsArray = 1,
IsPointer = 2,
IsByRef = 3,
}
// This is a kind of Type object that will represent the compound expression of a parameter type or field type.
internal sealed class SymbolType : TypeInfo
{
public override bool IsAssignableFrom(System.Reflection.TypeInfo typeInfo)
{
if (typeInfo == null) return false;
return IsAssignableFrom(typeInfo.AsType());
}
#region Static Members
internal static Type FormCompoundType(string format, Type baseType, int curIndex)
{
// This function takes a string to describe the compound type, such as "[,][]", and a baseType.
//
// Example: [2..4] - one dimension array with lower bound 2 and size of 3
// Example: [3, 5, 6] - three dimension array with lower bound 3, 5, 6
// Example: [-3, ] [] - one dimensional array of two dimensional array (with lower bound -3 for
// the first dimension)
// Example: []* - pointer to a one dimensional array
// Example: *[] - one dimensional array. The element type is a pointer to the baseType
// Example: []& - ByRef of a single dimensional array. Only one & is allowed and it must appear the last!
// Example: [?] - Array with unknown bound
SymbolType symbolType;
int iLowerBound;
int iUpperBound;
if (format == null || curIndex == format.Length)
{
// we have consumed all of the format string
return baseType;
}
if (format[curIndex] == '&')
{
// ByRef case
symbolType = new SymbolType(TypeKind.IsByRef);
symbolType.SetFormat(format, curIndex, 1);
curIndex++;
if (curIndex != format.Length)
// ByRef has to be the last char!!
throw new ArgumentException(SR.Argument_BadSigFormat);
symbolType.SetElementType(baseType);
return symbolType;
}
if (format[curIndex] == '[')
{
// Array type.
symbolType = new SymbolType(TypeKind.IsArray);
int startIndex = curIndex;
curIndex++;
iLowerBound = 0;
iUpperBound = -1;
// Example: [2..4] - one dimension array with lower bound 2 and size of 3
// Example: [3, 5, 6] - three dimension array with lower bound 3, 5, 6
// Example: [-3, ] [] - one dimensional array of two dimensional array (with lower bound -3 sepcified)
while (format[curIndex] != ']')
{
if (format[curIndex] == '*')
{
symbolType.m_isSzArray = false;
curIndex++;
}
// consume, one dimension at a time
if ((format[curIndex] >= '0' && format[curIndex] <= '9') || format[curIndex] == '-')
{
bool isNegative = false;
if (format[curIndex] == '-')
{
isNegative = true;
curIndex++;
}
// lower bound is specified. Consume the low bound
while (format[curIndex] >= '0' && format[curIndex] <= '9')
{
iLowerBound = iLowerBound * 10;
iLowerBound += format[curIndex] - '0';
curIndex++;
}
if (isNegative)
{
iLowerBound = 0 - iLowerBound;
}
// set the upper bound to be less than LowerBound to indicate that upper bound it not specified yet!
iUpperBound = iLowerBound - 1;
}
if (format[curIndex] == '.')
{
// upper bound is specified
// skip over ".."
curIndex++;
if (format[curIndex] != '.')
{
// bad format!! Throw exception
throw new ArgumentException(SR.Argument_BadSigFormat);
}
curIndex++;
// consume the upper bound
if ((format[curIndex] >= '0' && format[curIndex] <= '9') || format[curIndex] == '-')
{
bool isNegative = false;
iUpperBound = 0;
if (format[curIndex] == '-')
{
isNegative = true;
curIndex++;
}
// lower bound is specified. Consume the low bound
while (format[curIndex] >= '0' && format[curIndex] <= '9')
{
iUpperBound = iUpperBound * 10;
iUpperBound += format[curIndex] - '0';
curIndex++;
}
if (isNegative)
{
iUpperBound = 0 - iUpperBound;
}
if (iUpperBound < iLowerBound)
{
// User specified upper bound less than lower bound, this is an error.
// Throw error exception.
throw new ArgumentException(SR.Argument_BadSigFormat);
}
}
}
if (format[curIndex] == ',')
{
// We have more dimension to deal with.
// now set the lower bound, the size, and increase the dimension count!
curIndex++;
symbolType.SetBounds(iLowerBound, iUpperBound);
// clear the lower and upper bound information for next dimension
iLowerBound = 0;
iUpperBound = -1;
}
else if (format[curIndex] != ']')
{
throw new ArgumentException(SR.Argument_BadSigFormat);
}
}
// The last dimension information
symbolType.SetBounds(iLowerBound, iUpperBound);
// skip over ']'
curIndex++;
symbolType.SetFormat(format, startIndex, curIndex - startIndex);
// set the base type of array
symbolType.SetElementType(baseType);
return FormCompoundType(format, symbolType, curIndex);
}
else if (format[curIndex] == '*')
{
// pointer type.
symbolType = new SymbolType(TypeKind.IsPointer);
symbolType.SetFormat(format, curIndex, 1);
curIndex++;
symbolType.SetElementType(baseType);
return FormCompoundType(format, symbolType, curIndex);
}
return null;
}
#endregion
#region Data Members
internal TypeKind m_typeKind;
internal Type m_baseType;
internal int m_cRank; // count of dimension
// If LowerBound and UpperBound is equal, that means one element.
// If UpperBound is less than LowerBound, then the size is not specified.
internal int[] m_iaLowerBound;
internal int[] m_iaUpperBound; // count of dimension
private string m_format; // format string to form the full name.
private bool m_isSzArray = true;
#endregion
#region Constructor
internal SymbolType(TypeKind typeKind)
{
m_typeKind = typeKind;
m_iaLowerBound = new int[4];
m_iaUpperBound = new int[4];
}
#endregion
#region Internal Members
internal void SetElementType(Type baseType)
{
if (baseType == null)
throw new ArgumentNullException(nameof(baseType));
Contract.EndContractBlock();
m_baseType = baseType;
}
private void SetBounds(int lower, int upper)
{
// Increase the rank, set lower and upper bound
if (lower != 0 || upper != -1)
m_isSzArray = false;
if (m_iaLowerBound.Length <= m_cRank)
{
// resize the bound array
int[] iaTemp = new int[m_cRank * 2];
Array.Copy(m_iaLowerBound, 0, iaTemp, 0, m_cRank);
m_iaLowerBound = iaTemp;
Array.Copy(m_iaUpperBound, 0, iaTemp, 0, m_cRank);
m_iaUpperBound = iaTemp;
}
m_iaLowerBound[m_cRank] = lower;
m_iaUpperBound[m_cRank] = upper;
m_cRank++;
}
internal void SetFormat(string format, int curIndex, int length)
{
// Cache the text display format for this SymbolType
m_format = format.Substring(curIndex, length);
}
#endregion
#region Type Overrides
public override bool IsSZArray => m_cRank <= 1 && m_isSzArray;
public override Type MakePointerType()
{
return SymbolType.FormCompoundType(m_format + "*", m_baseType, 0);
}
public override Type MakeByRefType()
{
return SymbolType.FormCompoundType(m_format + "&", m_baseType, 0);
}
public override Type MakeArrayType()
{
return SymbolType.FormCompoundType(m_format + "[]", m_baseType, 0);
}
public override Type MakeArrayType(int rank)
{
if (rank <= 0)
throw new IndexOutOfRangeException();
Contract.EndContractBlock();
string szrank = "";
if (rank == 1)
{
szrank = "*";
}
else
{
for (int i = 1; i < rank; i++)
szrank += ",";
}
string s = String.Format(CultureInfo.InvariantCulture, "[{0}]", szrank); // [,,]
SymbolType st = SymbolType.FormCompoundType(m_format + s, m_baseType, 0) as SymbolType;
return st;
}
public override int GetArrayRank()
{
if (!IsArray)
throw new NotSupportedException(SR.NotSupported_SubclassOverride);
Contract.EndContractBlock();
return m_cRank;
}
public override Guid GUID
{
get { throw new NotSupportedException(SR.NotSupported_NonReflectedType); }
}
public override Object InvokeMember(String name, BindingFlags invokeAttr, Binder binder, Object target,
Object[] args, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParameters)
{
throw new NotSupportedException(SR.NotSupported_NonReflectedType);
}
public override Module Module
{
get
{
Type baseType;
for (baseType = m_baseType; baseType is SymbolType; baseType = ((SymbolType)baseType).m_baseType) ;
return baseType.Module;
}
}
public override Assembly Assembly
{
get
{
Type baseType;
for (baseType = m_baseType; baseType is SymbolType; baseType = ((SymbolType)baseType).m_baseType) ;
return baseType.Assembly;
}
}
public override RuntimeTypeHandle TypeHandle
{
get { throw new NotSupportedException(SR.NotSupported_NonReflectedType); }
}
public override String Name
{
get
{
Type baseType;
String sFormat = m_format;
for (baseType = m_baseType; baseType is SymbolType; baseType = ((SymbolType)baseType).m_baseType)
sFormat = ((SymbolType)baseType).m_format + sFormat;
return baseType.Name + sFormat;
}
}
public override String FullName
{
get
{
return TypeNameBuilder.ToString(this, TypeNameBuilder.Format.FullName);
}
}
public override String AssemblyQualifiedName
{
get
{
return TypeNameBuilder.ToString(this, TypeNameBuilder.Format.AssemblyQualifiedName);
}
}
public override String ToString()
{
return TypeNameBuilder.ToString(this, TypeNameBuilder.Format.ToString);
}
public override String Namespace
{
get { return m_baseType.Namespace; }
}
public override Type BaseType
{
get { return typeof(System.Array); }
}
protected override ConstructorInfo GetConstructorImpl(BindingFlags bindingAttr, Binder binder,
CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers)
{
throw new NotSupportedException(SR.NotSupported_NonReflectedType);
}
public override ConstructorInfo[] GetConstructors(BindingFlags bindingAttr)
{
throw new NotSupportedException(SR.NotSupported_NonReflectedType);
}
protected override MethodInfo GetMethodImpl(String name, BindingFlags bindingAttr, Binder binder,
CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers)
{
throw new NotSupportedException(SR.NotSupported_NonReflectedType);
}
public override MethodInfo[] GetMethods(BindingFlags bindingAttr)
{
throw new NotSupportedException(SR.NotSupported_NonReflectedType);
}
public override FieldInfo GetField(String name, BindingFlags bindingAttr)
{
throw new NotSupportedException(SR.NotSupported_NonReflectedType);
}
public override FieldInfo[] GetFields(BindingFlags bindingAttr)
{
throw new NotSupportedException(SR.NotSupported_NonReflectedType);
}
public override Type GetInterface(String name, bool ignoreCase)
{
throw new NotSupportedException(SR.NotSupported_NonReflectedType);
}
public override Type[] GetInterfaces()
{
throw new NotSupportedException(SR.NotSupported_NonReflectedType);
}
public override EventInfo GetEvent(String name, BindingFlags bindingAttr)
{
throw new NotSupportedException(SR.NotSupported_NonReflectedType);
}
public override EventInfo[] GetEvents()
{
throw new NotSupportedException(SR.NotSupported_NonReflectedType);
}
protected override PropertyInfo GetPropertyImpl(String name, BindingFlags bindingAttr, Binder binder,
Type returnType, Type[] types, ParameterModifier[] modifiers)
{
throw new NotSupportedException(SR.NotSupported_NonReflectedType);
}
public override PropertyInfo[] GetProperties(BindingFlags bindingAttr)
{
throw new NotSupportedException(SR.NotSupported_NonReflectedType);
}
public override Type[] GetNestedTypes(BindingFlags bindingAttr)
{
throw new NotSupportedException(SR.NotSupported_NonReflectedType);
}
public override Type GetNestedType(String name, BindingFlags bindingAttr)
{
throw new NotSupportedException(SR.NotSupported_NonReflectedType);
}
public override MemberInfo[] GetMember(String name, MemberTypes type, BindingFlags bindingAttr)
{
throw new NotSupportedException(SR.NotSupported_NonReflectedType);
}
public override MemberInfo[] GetMembers(BindingFlags bindingAttr)
{
throw new NotSupportedException(SR.NotSupported_NonReflectedType);
}
public override InterfaceMapping GetInterfaceMap(Type interfaceType)
{
throw new NotSupportedException(SR.NotSupported_NonReflectedType);
}
public override EventInfo[] GetEvents(BindingFlags bindingAttr)
{
throw new NotSupportedException(SR.NotSupported_NonReflectedType);
}
protected override TypeAttributes GetAttributeFlagsImpl()
{
// Return the attribute flags of the base type?
Type baseType;
for (baseType = m_baseType; baseType is SymbolType; baseType = ((SymbolType)baseType).m_baseType) ;
return baseType.Attributes;
}
protected override bool IsArrayImpl()
{
return m_typeKind == TypeKind.IsArray;
}
protected override bool IsPointerImpl()
{
return m_typeKind == TypeKind.IsPointer;
}
protected override bool IsByRefImpl()
{
return m_typeKind == TypeKind.IsByRef;
}
protected override bool IsPrimitiveImpl()
{
return false;
}
protected override bool IsValueTypeImpl()
{
return false;
}
protected override bool IsCOMObjectImpl()
{
return false;
}
public override bool IsConstructedGenericType
{
get
{
return false;
}
}
public override Type GetElementType()
{
return m_baseType;
}
protected override bool HasElementTypeImpl()
{
return m_baseType != null;
}
public override Type UnderlyingSystemType
{
get { return this; }
}
public override Object[] GetCustomAttributes(bool inherit)
{
throw new NotSupportedException(SR.NotSupported_NonReflectedType);
}
public override Object[] GetCustomAttributes(Type attributeType, bool inherit)
{
throw new NotSupportedException(SR.NotSupported_NonReflectedType);
}
public override bool IsDefined(Type attributeType, bool inherit)
{
throw new NotSupportedException(SR.NotSupported_NonReflectedType);
}
#endregion
}
}
| |
using System.Collections.Generic;
using System.Composition;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
using OmniSharp.Mef;
using OmniSharp.Models;
namespace OmniSharp.Roslyn.CSharp.Services.Signatures
{
[OmniSharpHandler(OmnisharpEndpoints.SignatureHelp, LanguageNames.CSharp)]
public class SignatureHelpService : RequestHandler<SignatureHelpRequest, SignatureHelp>
{
private readonly OmnisharpWorkspace _workspace;
[ImportingConstructor]
public SignatureHelpService(OmnisharpWorkspace workspace)
{
_workspace = workspace;
}
public async Task<SignatureHelp> Handle(SignatureHelpRequest request)
{
var invocations = new List<InvocationContext>();
foreach (var document in _workspace.GetDocuments(request.FileName))
{
var invocation = await GetInvocation(document, request);
if (invocation != null)
{
invocations.Add(invocation);
}
}
if (invocations.Count == 0)
{
return null;
}
var response = new SignatureHelp();
// define active parameter by position
foreach (var comma in invocations.First().ArgumentList.Arguments.GetSeparators())
{
if (comma.Span.Start > invocations.First().Position)
{
break;
}
response.ActiveParameter += 1;
}
// process all signatures, define active signature by types
var signaturesSet = new HashSet<SignatureHelpItem>();
var bestScore = int.MinValue;
SignatureHelpItem bestScoredItem = null;
foreach (var invocation in invocations)
{
var types = invocation.ArgumentList.Arguments
.Select(argument => invocation.SemanticModel.GetTypeInfo(argument.Expression));
foreach (var methodOverload in GetMethodOverloads(invocation.SemanticModel, invocation.Receiver))
{
var signature = BuildSignature(methodOverload);
signaturesSet.Add(signature);
var score = InvocationScore(methodOverload, types);
if (score > bestScore)
{
bestScore = score;
bestScoredItem = signature;
}
}
}
var signaturesList = signaturesSet.ToList();
response.Signatures = signaturesList;
response.ActiveSignature = signaturesList.IndexOf(bestScoredItem);
return response;
}
private async Task<InvocationContext> GetInvocation(Document document, Request request)
{
var sourceText = await document.GetTextAsync();
var position = sourceText.Lines.GetPosition(new LinePosition(request.Line, request.Column));
var tree = await document.GetSyntaxTreeAsync();
var root = await tree.GetRootAsync();
var node = root.FindToken(position).Parent;
// Walk up until we find a node that we're interested in.
while (node != null)
{
var invocation = node as InvocationExpressionSyntax;
if (invocation != null && invocation.ArgumentList.Span.Contains(position))
{
return new InvocationContext()
{
SemanticModel = await document.GetSemanticModelAsync(),
Position = position,
Receiver = invocation.Expression,
ArgumentList = invocation.ArgumentList
};
}
var objectCreation = node as ObjectCreationExpressionSyntax;
if (objectCreation != null && objectCreation.ArgumentList.Span.Contains(position))
{
return new InvocationContext()
{
SemanticModel = await document.GetSemanticModelAsync(),
Position = position,
Receiver = objectCreation,
ArgumentList = objectCreation.ArgumentList
};
}
node = node.Parent;
}
return null;
}
private IEnumerable<IMethodSymbol> GetMethodOverloads(SemanticModel semanticModel, SyntaxNode node)
{
ISymbol symbol = null;
var symbolInfo = semanticModel.GetSymbolInfo(node);
if (symbolInfo.Symbol != null)
{
symbol = symbolInfo.Symbol;
}
else if (!symbolInfo.CandidateSymbols.IsEmpty)
{
symbol = symbolInfo.CandidateSymbols.First();
}
if (symbol == null || symbol.ContainingType == null)
{
return new IMethodSymbol[] { };
}
return symbol.ContainingType.GetMembers(symbol.Name).OfType<IMethodSymbol>();
}
private int InvocationScore(IMethodSymbol symbol, IEnumerable<TypeInfo> types)
{
var parameters = GetParameters(symbol);
if (parameters.Count() < types.Count())
{
return int.MinValue;
}
var score = 0;
var invocationEnum = types.GetEnumerator();
var definitionEnum = parameters.GetEnumerator();
while (invocationEnum.MoveNext() && definitionEnum.MoveNext())
{
if (invocationEnum.Current.ConvertedType == null)
{
// 1 point for having a parameter
score += 1;
}
else if (invocationEnum.Current.ConvertedType.Equals(definitionEnum.Current.Type))
{
// 2 points for having a parameter and being
// the same type
score += 2;
}
}
return score;
}
private SignatureHelpItem BuildSignature(IMethodSymbol symbol)
{
var signature = new SignatureHelpItem();
signature.Documentation = symbol.GetDocumentationCommentXml();
if (symbol.MethodKind == MethodKind.Constructor)
{
signature.Name = symbol.ContainingType.Name;
signature.Label = symbol.ContainingType.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat);
}
else
{
signature.Name = symbol.Name;
signature.Label = symbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat);
}
signature.Parameters = GetParameters(symbol).Select(parameter =>
{
return new SignatureHelpParameter()
{
Name = parameter.Name,
Label = parameter.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat),
Documentation = parameter.GetDocumentationCommentXml()
};
});
return signature;
}
private static IEnumerable<IParameterSymbol> GetParameters(IMethodSymbol methodSymbol)
{
if (!methodSymbol.IsExtensionMethod)
{
return methodSymbol.Parameters;
}
else
{
return methodSymbol.Parameters.RemoveAt(0);
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.