context
stringlengths
2.52k
185k
gt
stringclasses
1 value
using System.Linq; using FluentNHibernate.MappingModel; using FluentNHibernate.MappingModel.Collections; using NUnit.Framework; namespace FluentNHibernate.Testing.FluentInterfaceTests { [TestFixture] public class ManyToManyMutablePropertyModelGenerationTests : BaseModelFixture { [Test] public void ShouldSetName() { ManyToMany(x => x.BagOfChildren) .Mapping(m => { }) .ModelShouldMatch(x => x.Name.ShouldEqual("BagOfChildren")); } [Test] public void AccessShouldSetModelAccessPropertyToValue() { ManyToMany(x => x.BagOfChildren) .Mapping(m => m.Access.Field()) .ModelShouldMatch(x => x.Access.ShouldEqual("field")); } [Test] public void BatchSizeShouldSetModelBatchSizePropertyToValue() { ManyToMany(x => x.BagOfChildren) .Mapping(m => m.BatchSize(10)) .ModelShouldMatch(x => x.BatchSize.ShouldEqual(10)); } [Test] public void CacheShouldSetModelCachePropertyToValue() { ManyToMany(x => x.BagOfChildren) .Mapping(m => m.Cache.ReadOnly()) .ModelShouldMatch(x => { x.Cache.ShouldNotBeNull(); x.Cache.Usage.ShouldEqual("read-only"); }); } [Test] public void CascadeShouldSetModelCascadePropertyToValue() { ManyToMany(x => x.BagOfChildren) .Mapping(m => m.Cascade.All()) .ModelShouldMatch(x => x.Cascade.ShouldEqual("all")); } [Test] public void CollectionTypeShouldSetModelCollectionTypePropertyToValue() { ManyToMany(x => x.BagOfChildren) .Mapping(m => m.CollectionType("type")) .ModelShouldMatch(x => x.CollectionType.ShouldEqual(new TypeReference("type"))); } [Test] public void ForeignKeyCascadeOnDeleteShouldSetModelKeyOnDeletePropertyToCascade() { ManyToMany(x => x.BagOfChildren) .Mapping(m => m.ForeignKeyCascadeOnDelete()) .ModelShouldMatch(x => x.Key.OnDelete.ShouldEqual("cascade")); } [Test] public void InverseShouldSetModelInversePropertyToTrue() { ManyToMany(x => x.BagOfChildren) .Mapping(m => m.Inverse()) .ModelShouldMatch(x => x.Inverse.ShouldBeTrue()); } [Test] public void NotInverseShouldSetModelInversePropertyToFalse() { ManyToMany(x => x.BagOfChildren) .Mapping(m => m.Not.Inverse()) .ModelShouldMatch(x => x.Inverse.ShouldBeFalse()); } [Test] public void WithParentKeyColumnShouldAddColumnToModelKeyColumnsCollection() { ManyToMany(x => x.BagOfChildren) .Mapping(m => m.ParentKeyColumn("col")) .ModelShouldMatch(x => x.Key.Columns.Count().ShouldEqual(1)); } [Test] public void WithForeignKeyConstraintNamesShouldAddForeignKeyToBothColumns() { ManyToMany(x => x.BagOfChildren) .Mapping(m => m.ForeignKeyConstraintNames("p_fk", "c_fk")) .ModelShouldMatch(x => { x.Key.ForeignKey.ShouldEqual("p_fk"); ((ManyToManyMapping)x.Relationship).ForeignKey.ShouldEqual("c_fk"); }); } [Test] public void WithChildKeyColumnShouldAddColumnToModelRelationshipColumnsCollection() { ManyToMany(x => x.BagOfChildren) .Mapping(m => m.ChildKeyColumn("col")) .ModelShouldMatch(x => ((ManyToManyMapping)x.Relationship).Columns.Count().ShouldEqual(1)); } [Test] public void LazyLoadShouldSetModelLazyPropertyToTrue() { ManyToMany(x => x.BagOfChildren) .Mapping(m => m.LazyLoad()) .ModelShouldMatch(x => x.Lazy.ShouldEqual(true)); } [Test] public void NotLazyLoadShouldSetModelLazyPropertyToFalse() { ManyToMany(x => x.BagOfChildren) .Mapping(m => m.Not.LazyLoad()) .ModelShouldMatch(x => x.Lazy.ShouldEqual(false)); } [Test] public void NotFoundShouldSetModelRelationshipNotFoundPropertyToValue() { ManyToMany(x => x.BagOfChildren) .Mapping(m => m.NotFound.Ignore()) .ModelShouldMatch(x => ((ManyToManyMapping)x.Relationship).NotFound.ShouldEqual("ignore")); } [Test] public void WhereShouldSetModelWherePropertyToValue() { ManyToMany(x => x.BagOfChildren) .Mapping(m => m.Where("x = 1")) .ModelShouldMatch(x => x.Where.ShouldEqual("x = 1")); } [Test] public void WithTableNameShouldSetModelTableNamePropertyToValue() { ManyToMany(x => x.BagOfChildren) .Mapping(m => m.Table("t")) .ModelShouldMatch(x => x.TableName.ShouldEqual("t")); } [Test] public void SchemaIsShouldSetModelSchemaPropertyToValue() { ManyToMany(x => x.BagOfChildren) .Mapping(m => m.Schema("dto")) .ModelShouldMatch(x => x.Schema.ShouldEqual("dto")); } [Test] public void FetchShouldSetModelFetchPropertyToValue() { ManyToMany(x => x.BagOfChildren) .Mapping(m => m.Fetch.Select()) .ModelShouldMatch(x => x.Fetch.ShouldEqual("select")); } [Test] public void PersisterShouldSetModelPersisterPropertyToAssemblyQualifiedName() { ManyToMany(x => x.BagOfChildren) .Mapping(m => m.Persister<CustomPersister>()) .ModelShouldMatch(x => x.Persister.GetUnderlyingSystemType().ShouldEqual(typeof(CustomPersister))); } [Test] public void CheckShouldSetModelCheckToValue() { ManyToMany(x => x.BagOfChildren) .Mapping(m => m.Check("x > 100")) .ModelShouldMatch(x => x.Check.ShouldEqual("x > 100")); } [Test] public void OptimisticLockShouldSetModelOptimisticLockToValue() { ManyToMany(x => x.BagOfChildren) .Mapping(m => m.OptimisticLock.All()) .ModelShouldMatch(x => x.OptimisticLock.ShouldEqual("all")); } [Test] public void GenericShouldSetModelGenericToTrue() { ManyToMany(x => x.BagOfChildren) .Mapping(m => m.Generic()) .ModelShouldMatch(x => x.Generic.ShouldBeTrue()); } [Test] public void NotGenericShouldSetModelGenericToTrue() { ManyToMany(x => x.BagOfChildren) .Mapping(m => m.Not.Generic()) .ModelShouldMatch(x => x.Generic.ShouldBeFalse()); } [Test] public void ReadOnlyShouldSetModelMutableToFalse() { ManyToMany(x => x.BagOfChildren) .Mapping(m => m.ReadOnly()) .ModelShouldMatch(x => x.Mutable.ShouldBeFalse()); } [Test] public void NotReadOnlyShouldSetModelMutableToTrue() { ManyToMany(x => x.BagOfChildren) .Mapping(m => m.Not.ReadOnly()) .ModelShouldMatch(x => x.Mutable.ShouldBeTrue()); } [Test] public void SubselectShouldSetModelSubselectToValue() { ManyToMany(x => x.BagOfChildren) .Mapping(m => m.Subselect("whee")) .ModelShouldMatch(x => x.Subselect.ShouldEqual("whee")); } } }
// ---------------------------------------------------------------------------------- // // 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. // ---------------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Linq; using Microsoft.WindowsAzure.Commands.Common; using Microsoft.WindowsAzure.Commands.Common.Models; using Microsoft.WindowsAzure.Commands.Utilities.Properties; using Microsoft.WindowsAzure.Commands.Utilities.Scheduler.Common; using Microsoft.WindowsAzure.Commands.Utilities.Scheduler.Model; using Microsoft.WindowsAzure.Management.Scheduler; using Microsoft.WindowsAzure.Management.Scheduler.Models; using Microsoft.WindowsAzure.Scheduler; using Microsoft.WindowsAzure.Scheduler.Models; namespace Microsoft.WindowsAzure.Commands.Utilities.Scheduler { public partial class SchedulerMgmntClient { private SchedulerManagementClient schedulerManagementClient; private CloudServiceManagementClient csmClient; private AzureSubscription currentSubscription; private const string SupportedRegionsKey = "SupportedGeoRegions"; private const string FreeMaxJobCountKey = "PlanDetail:Free:Quota:MaxJobCount"; private const string FreeMinRecurrenceKey = "PlanDetail:Free:Quota:MinRecurrence"; private const string StandardMaxJobCountKey = "PlanDetail:Standard:Quota:MaxJobCount"; private const string StandardMinRecurrenceKey = "PlanDetail:Standard:Quota:MinRecurrence"; private const string PremiumMaxJobCountKey = "PlanDetail:Premium:Quota:MaxJobCount"; private const string PremiumMinRecurrenceKey = "PlanDetail:Premium:Quota:MinRecurrence"; private int FreeMaxJobCountValue { get; set; } private TimeSpan FreeMinRecurrenceValue { get; set; } private int StandardMaxJobCountValue { get; set; } private TimeSpan StandardMinRecurrenceValue { get; set; } private int PremiumMaxJobCountValue { get; set; } private TimeSpan PremiumMinRecurrenceValue { get; set; } private List<string> AvailableRegions { get; set; } /// <summary> /// Creates new Scheduler Management Convenience Client /// </summary> /// <param name="subscription">Subscription containing websites to manipulate</param> public SchedulerMgmntClient(AzureSubscription subscription) { currentSubscription = subscription; csmClient = AzureSession.ClientFactory.CreateClient<CloudServiceManagementClient>(subscription, AzureEnvironment.Endpoint.ServiceManagement); schedulerManagementClient = AzureSession.ClientFactory.CreateClient<SchedulerManagementClient>(subscription, AzureEnvironment.Endpoint.ServiceManagement); //Get RP properties IDictionary<string, string> dict = schedulerManagementClient.GetResourceProviderProperties().Properties; //Get available regions string val = string.Empty; if (dict.TryGetValue(SupportedRegionsKey, out val)) { AvailableRegions = new List<string>(); val.Split(',').ToList().ForEach(s => AvailableRegions.Add(s)); } //Store global counts for max jobs and min recurrence for each plan if (dict.TryGetValue(FreeMaxJobCountKey, out val)) FreeMaxJobCountValue = Convert.ToInt32(dict[FreeMaxJobCountKey]); if (dict.TryGetValue(FreeMinRecurrenceKey, out val)) FreeMinRecurrenceValue = TimeSpan.Parse(dict[FreeMinRecurrenceKey]); if (dict.TryGetValue(StandardMaxJobCountKey, out val)) StandardMaxJobCountValue = Convert.ToInt32(dict[StandardMaxJobCountKey]); if (dict.TryGetValue(StandardMinRecurrenceKey, out val)) StandardMinRecurrenceValue = TimeSpan.Parse(dict[StandardMinRecurrenceKey]); if (dict.TryGetValue(PremiumMaxJobCountKey, out val)) PremiumMaxJobCountValue = Convert.ToInt32(dict[PremiumMaxJobCountKey]); if (dict.TryGetValue(PremiumMinRecurrenceKey, out val)) PremiumMinRecurrenceValue = TimeSpan.Parse(dict[PremiumMinRecurrenceKey]); } #region Get Available Regions public List<string> GetAvailableRegions() { return AvailableRegions; } #endregion #region Job Collections public List<PSJobCollection> GetJobCollection(string region = "", string jobCollection = "") { List<PSJobCollection> lstSchedulerJobCollection = new List<PSJobCollection>(); CloudServiceListResponse csList = csmClient.CloudServices.List(); if (!string.IsNullOrEmpty(region)) { if (!this.AvailableRegions.Contains(region, StringComparer.OrdinalIgnoreCase)) throw new Exception(Resources.SchedulerInvalidLocation); string cloudService = region.ToCloudServiceName(); foreach (CloudServiceListResponse.CloudService cs in csList.CloudServices) { if (cs.Name.Equals(cloudService, StringComparison.OrdinalIgnoreCase)) { GetSchedulerJobCollection(cs, jobCollection).ForEach(x => lstSchedulerJobCollection.Add(x)); //If job collection parameter was passed and we found a matching job collection already, exit out of the loop and return the job collection if (!string.IsNullOrEmpty(jobCollection) && lstSchedulerJobCollection.Count > 0) return lstSchedulerJobCollection; } } } else if (string.IsNullOrEmpty(region)) { foreach (CloudServiceListResponse.CloudService cs in csList.CloudServices) { if (cs.Name.Equals(Constants.CloudServiceNameFirst + cs.GeoRegion.Replace(" ", string.Empty) + Constants.CloudServiceNameSecond, StringComparison.OrdinalIgnoreCase)) { GetSchedulerJobCollection(cs, jobCollection).ForEach(x => lstSchedulerJobCollection.Add(x)); //If job collection parameter was passed and we found a matching job collection already, exit out of the loop and return the job collection if (!string.IsNullOrEmpty(jobCollection) && lstSchedulerJobCollection.Count > 0) return lstSchedulerJobCollection; } } } return lstSchedulerJobCollection; } private List<PSJobCollection> GetSchedulerJobCollection(CloudServiceListResponse.CloudService cloudService, string jobCollection) { List<PSJobCollection> lstSchedulerJobCollection = new List<PSJobCollection>(); foreach (CloudServiceGetResponse.Resource csRes in csmClient.CloudServices.Get(cloudService.Name).Resources) { if (csRes.Type.Contains(Constants.JobCollectionResource)) { JobCollectionGetResponse jcGetResponse = schedulerManagementClient.JobCollections.Get(cloudService.Name, csRes.Name); if (string.IsNullOrEmpty(jobCollection) || (!string.IsNullOrEmpty(jobCollection) && jcGetResponse.Name.Equals(jobCollection, StringComparison.OrdinalIgnoreCase))) { PSJobCollection jc = new PSJobCollection { CloudServiceName = cloudService.Name, JobCollectionName = jcGetResponse.Name, State = Enum.GetName(typeof(JobCollectionState), jcGetResponse.State), Location = cloudService.GeoRegion, Uri = csmClient.BaseUri.AbsoluteUri + csmClient.Credentials.SubscriptionId + "cloudservices/" + cloudService.Name + Constants.JobCollectionResourceURL + jcGetResponse.Name }; if (jcGetResponse.IntrinsicSettings != null) { jc.Plan = Enum.GetName(typeof(JobCollectionPlan), jcGetResponse.IntrinsicSettings.Plan); if (jcGetResponse.IntrinsicSettings.Quota != null) { jc.MaxJobCount = jcGetResponse.IntrinsicSettings.Quota.MaxJobCount == null ? string.Empty : jcGetResponse.IntrinsicSettings.Quota.MaxJobCount.ToString(); jc.MaxRecurrence = jcGetResponse.IntrinsicSettings.Quota.MaxRecurrence == null ? string.Empty : jcGetResponse.IntrinsicSettings.Quota.MaxRecurrence.Interval.ToString() + " per " + jcGetResponse.IntrinsicSettings.Quota.MaxRecurrence.Frequency.ToString(); } } lstSchedulerJobCollection.Add(jc); } } } return lstSchedulerJobCollection; } #endregion #region Scheduler Jobs public List<PSSchedulerJob> GetJob(string region, string jobCollection, string job = "", string state = "") { if (!this.AvailableRegions.Contains(region, StringComparer.OrdinalIgnoreCase)) throw new Exception(Resources.SchedulerInvalidLocation); List<PSSchedulerJob> lstJob = new List<PSSchedulerJob>(); string cloudService = region.ToCloudServiceName(); if (!string.IsNullOrEmpty(job)) { PSJobDetail jobDetail = GetJobDetail(jobCollection, job, cloudService); if (string.IsNullOrEmpty(state) || (!string.IsNullOrEmpty(state) && jobDetail.Status.Equals(state, StringComparison.OrdinalIgnoreCase))) { lstJob.Add(jobDetail); return lstJob; } } else if (string.IsNullOrEmpty(job)) { GetSchedulerJobs(cloudService, jobCollection).ForEach(x => { if (string.IsNullOrEmpty(state) || (!string.IsNullOrEmpty(state) && x.Status.Equals(state, StringComparison.OrdinalIgnoreCase))) { lstJob.Add(x); } }); } return lstJob; } private List<PSSchedulerJob> GetSchedulerJobs(string cloudService, string jobCollection) { List<PSSchedulerJob> lstJobs = new List<PSSchedulerJob>(); CloudServiceGetResponse csDetails = csmClient.CloudServices.Get(cloudService); foreach (CloudServiceGetResponse.Resource csRes in csDetails.Resources) { if (csRes.ResourceProviderNamespace.Equals(Constants.SchedulerRPNameProvider, StringComparison.OrdinalIgnoreCase) && csRes.Name.Equals(jobCollection, StringComparison.OrdinalIgnoreCase)) { SchedulerClient schedClient = AzureSession.ClientFactory.CreateCustomClient<SchedulerClient>(cloudService, jobCollection, csmClient.Credentials, schedulerManagementClient.BaseUri); JobListResponse jobs = schedClient.Jobs.List(new JobListParameters { Skip = 0, }); foreach (Job job in jobs) { lstJobs.Add(new PSSchedulerJob { JobName = job.Id, Lastrun = job.Status == null ? null : job.Status.LastExecutionTime, Nextrun = job.Status == null ? null : job.Status.NextExecutionTime, Status = job.State.ToString(), StartTime = job.StartTime, Recurrence = job.Recurrence == null ? string.Empty : job.Recurrence.Interval.ToString() + " per " + job.Recurrence.Frequency.ToString(), Failures = job.Status == null ? default(int?) : job.Status.FailureCount, Faults = job.Status == null ? default(int?) : job.Status.FaultedCount, Executions = job.Status == null ? default(int?) : job.Status.ExecutionCount, EndSchedule = GetEndTime(job), JobCollectionName = jobCollection }); } } } return lstJobs; } private string GetEndTime(Job job) { if (job.Recurrence == null) return "Run once"; else if (job.Recurrence != null) { if (job.Recurrence.Count == null) return "None"; if (job.Recurrence.Count != null) return "Until " + job.Recurrence.Count + " executions"; else return job.Recurrence.Interval + " executions every " + job.Recurrence.Frequency.ToString(); } return null; } #endregion #region Job History public List<PSJobHistory> GetJobHistory(string jobCollection, string job, string region, string jobStatus = "") { if (!this.AvailableRegions.Contains(region, StringComparer.OrdinalIgnoreCase)) throw new Exception(Resources.SchedulerInvalidLocation); List<PSJobHistory> lstPSJobHistory = new List<PSJobHistory>(); string cloudService = region.ToCloudServiceName(); CloudServiceGetResponse csDetails = csmClient.CloudServices.Get(cloudService); foreach (CloudServiceGetResponse.Resource csRes in csDetails.Resources) { if (csRes.ResourceProviderNamespace.Equals(Constants.SchedulerRPNameProvider, StringComparison.InvariantCultureIgnoreCase) && csRes.Name.Equals(jobCollection, StringComparison.OrdinalIgnoreCase)) { SchedulerClient schedClient = AzureSession.ClientFactory.CreateCustomClient<SchedulerClient>(cloudService, jobCollection.Trim(), csmClient.Credentials, schedulerManagementClient.BaseUri); List<JobGetHistoryResponse.JobHistoryEntry> lstHistory = new List<JobGetHistoryResponse.JobHistoryEntry>(); int currentTop = 100; if (string.IsNullOrEmpty(jobStatus)) { JobGetHistoryResponse history = schedClient.Jobs.GetHistory(job.Trim(), new JobGetHistoryParameters { Top = 100 }); lstHistory.AddRange(history.JobHistory); while (history.JobHistory.Count > 99) { history = schedClient.Jobs.GetHistory(job.Trim(), new JobGetHistoryParameters { Top = 100, Skip = currentTop }); currentTop += 100; lstHistory.AddRange(history.JobHistory); } } else if (!string.IsNullOrEmpty(jobStatus)) { JobHistoryStatus status = jobStatus.Equals("Completed") ? JobHistoryStatus.Completed : JobHistoryStatus.Failed; JobGetHistoryResponse history = schedClient.Jobs.GetHistoryWithFilter(job.Trim(), new JobGetHistoryWithFilterParameters { Top = 100, Status = status }); lstHistory.AddRange(history.JobHistory); while (history.JobHistory.Count > 99) { history = schedClient.Jobs.GetHistoryWithFilter(job.Trim(), new JobGetHistoryWithFilterParameters { Top = 100, Skip = currentTop }); currentTop += 100; lstHistory.AddRange(history.JobHistory); } } foreach (JobGetHistoryResponse.JobHistoryEntry entry in lstHistory) { PSJobHistory historyObj = new PSJobHistory(); historyObj.Status = entry.Status.ToString(); historyObj.StartTime = entry.StartTime; historyObj.EndTime = entry.EndTime; historyObj.JobName = entry.Id; historyObj.Details = GetHistoryDetails(entry.Message); historyObj.Retry = entry.RetryCount; historyObj.Occurence = entry.RepeatCount; if (JobHistoryActionName.ErrorAction == entry.ActionName) { PSJobHistoryError errorObj = historyObj.ToJobHistoryError(); errorObj.ErrorAction = JobHistoryActionName.ErrorAction.ToString(); lstPSJobHistory.Add(errorObj); } else lstPSJobHistory.Add(historyObj); } } } return lstPSJobHistory; } private PSJobHistoryDetail GetHistoryDetails(string message) { PSJobHistoryDetail detail = new PSJobHistoryDetail(); if (message.Contains("Http Action -")) { PSJobHistoryHttpDetail details = new PSJobHistoryHttpDetail { ActionType = "http" }; if (message.Contains("Request to host") && message.Contains("failed:")) { int firstIndex = message.IndexOf("'"); int secondIndex = message.IndexOf("'", firstIndex + 1); details.HostName = message.Substring(firstIndex + 1, secondIndex - (firstIndex + 1)); details.Response = "Failed"; details.ResponseBody = message; } else { int firstIndex = message.IndexOf("'"); int secondIndex = message.IndexOf("'", firstIndex + 1); int thirdIndex = message.IndexOf("'", secondIndex + 1); int fourthIndex = message.IndexOf("'", thirdIndex + 1); details.HostName = message.Substring(firstIndex + 1, secondIndex - (firstIndex + 1)); details.Response = message.Substring(thirdIndex + 1, fourthIndex - (thirdIndex + 1)); int bodyIndex = message.IndexOf("Body: "); details.ResponseBody = message.Substring(bodyIndex + 6); } return details; } else if (message.Contains("StorageQueue Action -")) { PSJobHistoryStorageDetail details = new PSJobHistoryStorageDetail { ActionType = "Storage" }; if (message.Contains("does not exist")) { int firstIndex = message.IndexOf("'"); int secondIndex = message.IndexOf("'", firstIndex + 1); details.StorageAccountName = string.Empty; details.StorageQueueName = message.Substring(firstIndex + 1, secondIndex - (firstIndex + 1)); details.ResponseBody = message; details.ResponseStatus = "Failed"; } else { int firstIndex = message.IndexOf("'"); int secondIndex = message.IndexOf("'", firstIndex + 1); int thirdIndex = message.IndexOf("'", secondIndex + 1); int fourthIndex = message.IndexOf("'", thirdIndex + 1); details.StorageAccountName = message.Substring(firstIndex + 1, secondIndex - (firstIndex + 1)); details.StorageQueueName = message.Substring(thirdIndex + 1, fourthIndex - (thirdIndex + 1)); details.ResponseStatus = message.Substring(fourthIndex + 2); details.ResponseBody = message; } return details; } return detail; } #endregion #region Get Job Details public PSJobDetail GetJobDetail(string jobCollection, string job, string cloudService) { CloudServiceGetResponse csDetails = csmClient.CloudServices.Get(cloudService); foreach (CloudServiceGetResponse.Resource csRes in csDetails.Resources) { if (csRes.ResourceProviderNamespace.Equals(Constants.SchedulerRPNameProvider, StringComparison.OrdinalIgnoreCase) && csRes.Name.Equals(jobCollection, StringComparison.OrdinalIgnoreCase)) { SchedulerClient schedClient = AzureSession.ClientFactory.CreateCustomClient<SchedulerClient>(cloudService, jobCollection, csmClient.Credentials, schedulerManagementClient.BaseUri); JobListResponse jobs = schedClient.Jobs.List(new JobListParameters { Skip = 0, }); foreach (Job j in jobs) { if (j.Id.ToLower().Equals(job.ToLower())) { if (Enum.GetName(typeof(JobActionType), j.Action.Type).Contains("Http")) { PSHttpJobDetail jobDetail = new PSHttpJobDetail(); jobDetail.JobName = j.Id; jobDetail.JobCollectionName = jobCollection; jobDetail.CloudService = cloudService; jobDetail.ActionType = Enum.GetName(typeof(JobActionType), j.Action.Type); jobDetail.Uri = j.Action.Request.Uri; jobDetail.Method = j.Action.Request.Method; jobDetail.Body = j.Action.Request.Body; jobDetail.Headers = j.Action.Request.Headers; jobDetail.Status = j.State.ToString(); jobDetail.StartTime = j.StartTime; jobDetail.EndSchedule = GetEndTime(j); jobDetail.Recurrence = j.Recurrence == null ? string.Empty : j.Recurrence.Interval.ToString() + " (" + j.Recurrence.Frequency.ToString() + "s)"; if (j.Status != null) { jobDetail.Failures = j.Status.FailureCount; jobDetail.Faults = j.Status.FaultedCount; jobDetail.Executions = j.Status.ExecutionCount; jobDetail.Lastrun = j.Status.LastExecutionTime; jobDetail.Nextrun = j.Status.NextExecutionTime; } if (j.Action.Request.Authentication != null) { switch(j.Action.Request.Authentication.Type) { case HttpAuthenticationType.ClientCertificate: PSClientCertAuthenticationJobDetail ClientCertJobDetail = new PSClientCertAuthenticationJobDetail(jobDetail); ClientCertJobDetail.ClientCertExpiryDate = ((j.Action.Request.Authentication) as ClientCertAuthentication).CertificateExpiration.ToString(); ClientCertJobDetail.ClientCertSubjectName = ((j.Action.Request.Authentication) as ClientCertAuthentication).CertificateSubjectName; ClientCertJobDetail.ClientCertThumbprint = ((j.Action.Request.Authentication) as ClientCertAuthentication).CertificateThumbprint; return ClientCertJobDetail; case HttpAuthenticationType.ActiveDirectoryOAuth: PSAADOAuthenticationJobDetail AADOAuthJobDetail = new PSAADOAuthenticationJobDetail(jobDetail); AADOAuthJobDetail.Audience = ((j.Action.Request.Authentication) as AADOAuthAuthentication).Audience; AADOAuthJobDetail.ClientId = ((j.Action.Request.Authentication) as AADOAuthAuthentication).ClientId; AADOAuthJobDetail.Tenant = ((j.Action.Request.Authentication) as AADOAuthAuthentication).Tenant; return AADOAuthJobDetail; case HttpAuthenticationType.Basic: PSBasicAuthenticationJobDetail BasicAuthJobDetail = new PSBasicAuthenticationJobDetail(jobDetail); BasicAuthJobDetail.Username = ((j.Action.Request.Authentication) as BasicAuthentication).Username; return BasicAuthJobDetail; } } return jobDetail; } else { return new PSStorageQueueJobDetail { JobName = j.Id, JobCollectionName = jobCollection, CloudService = cloudService, ActionType = Enum.GetName(typeof(JobActionType), j.Action.Type), StorageAccountName = j.Action.QueueMessage.StorageAccountName, StorageQueueName = j.Action.QueueMessage.QueueName, SasToken = j.Action.QueueMessage.SasToken, QueueMessage = j.Action.QueueMessage.Message, Status = j.State.ToString(), EndSchedule = GetEndTime(j), StartTime = j.StartTime, Recurrence = j.Recurrence == null ? string.Empty : j.Recurrence.Interval.ToString() + " (" + j.Recurrence.Frequency.ToString() + "s)", Failures = j.Status == null ? default(int?) : j.Status.FailureCount, Faults = j.Status == null ? default(int?) : j.Status.FaultedCount, Executions = j.Status == null ? default(int?) : j.Status.ExecutionCount, Lastrun = j.Status == null ? null : j.Status.LastExecutionTime, Nextrun = j.Status == null ? null : j.Status.NextExecutionTime }; } } } } } return null; } #endregion #region Delete Jobs public bool DeleteJob(string jobCollection, string jobName, string region = "") { if (!string.IsNullOrEmpty(region)) { if (!this.AvailableRegions.Contains(region, StringComparer.OrdinalIgnoreCase)) throw new Exception(Resources.SchedulerInvalidLocation); SchedulerClient schedClient = AzureSession.ClientFactory.CreateCustomClient<SchedulerClient>(region.ToCloudServiceName(), jobCollection, csmClient.Credentials, schedulerManagementClient.BaseUri); OperationResponse response = schedClient.Jobs.Delete(jobName); return response.StatusCode == System.Net.HttpStatusCode.OK ? true : false; } else if (string.IsNullOrEmpty(region)) { CloudServiceListResponse csList = csmClient.CloudServices.List(); foreach (CloudServiceListResponse.CloudService cs in csList.CloudServices) { foreach (CloudServiceGetResponse.Resource csRes in csmClient.CloudServices.Get(cs.Name).Resources) { if (csRes.Type.Contains(Constants.JobCollectionResource)) { JobCollectionGetResponse jcGetResponse = schedulerManagementClient.JobCollections.Get(cs.Name, csRes.Name); if (jcGetResponse.Name.Equals(jobCollection, StringComparison.OrdinalIgnoreCase)) { foreach (PSSchedulerJob job in GetSchedulerJobs(cs.Name, jobCollection)) { if (job.JobName.Equals(jobName, StringComparison.OrdinalIgnoreCase)) { SchedulerClient schedClient = AzureSession.ClientFactory.CreateCustomClient<SchedulerClient>(cs.Name, jobCollection, csmClient.Credentials, schedulerManagementClient.BaseUri); OperationResponse response = schedClient.Jobs.Delete(jobName); return response.StatusCode == System.Net.HttpStatusCode.OK ? true : false; } } } } } } } return false; } #endregion #region Delete Job Collection public bool DeleteJobCollection(string jobCollection, string region = "") { if (!string.IsNullOrEmpty(region)) { if (!this.AvailableRegions.Contains(region, StringComparer.OrdinalIgnoreCase)) throw new Exception(Resources.SchedulerInvalidLocation); SchedulerOperationStatusResponse response = schedulerManagementClient.JobCollections.Delete(region.ToCloudServiceName(), jobCollection); return response.StatusCode == System.Net.HttpStatusCode.OK ? true : false; } else if (string.IsNullOrEmpty(region)) { CloudServiceListResponse csList = csmClient.CloudServices.List(); foreach (CloudServiceListResponse.CloudService cs in csList.CloudServices) { foreach (CloudServiceGetResponse.Resource csRes in csmClient.CloudServices.Get(cs.Name).Resources) { if (csRes.Type.Contains(Constants.JobCollectionResource)) { JobCollectionGetResponse jcGetResponse = schedulerManagementClient.JobCollections.Get(cs.Name, csRes.Name); if (jcGetResponse.Name.Equals(jobCollection, StringComparison.OrdinalIgnoreCase)) { SchedulerOperationStatusResponse response = schedulerManagementClient.JobCollections.Delete(region.ToCloudServiceName(), jobCollection); return response.StatusCode == System.Net.HttpStatusCode.OK ? true : false; } } } } } return false; } #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.Diagnostics; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; namespace System.Runtime { // CONTRACT with Runtime // This class lists all the static methods that the redhawk runtime exports to a class library // These are not expected to change much but are needed by the class library to implement its functionality // // The contents of this file can be modified if needed by the class library // E.g., the class and methods are marked internal assuming that only the base class library needs them // but if a class library wants to factor differently (such as putting the GCHandle methods in an // optional library, those methods can be moved to a different file/namespace/dll public static class RuntimeImports { private const string RuntimeLibrary = "[MRT]"; // // calls to GC // These methods are needed to implement System.GC like functionality (optional) // // Force a garbage collection. [MethodImpl(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhCollect")] internal static extern void RhCollect(int generation, InternalGCCollectionMode mode); // Mark an object instance as already finalized. [MethodImpl(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhSuppressFinalize")] internal static extern void RhSuppressFinalize(Object obj); internal static void RhReRegisterForFinalize(Object obj) { if (!_RhReRegisterForFinalize(obj)) throw new OutOfMemoryException(); } [MethodImpl(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhReRegisterForFinalize")] private static extern bool _RhReRegisterForFinalize(Object obj); // Wait for all pending finalizers. This must be a p/invoke to avoid starving the GC. [DllImport(RuntimeLibrary, ExactSpelling = true)] private static extern void RhWaitForPendingFinalizers(int allowReentrantWait); // Temporary workaround to unblock shareable assembly bring-up - without shared interop, // we must prevent RhWaitForPendingFinalizers from using marshaling because it would // rewrite System.Private.CoreLib to reference the non-shareable interop assembly. With shared interop, // we will be able to remove this helper method and change the DllImport above // to directly accept a boolean parameter. internal static void RhWaitForPendingFinalizers(bool allowReentrantWait) { RhWaitForPendingFinalizers(allowReentrantWait ? 1 : 0); } // Get maximum GC generation number. [MethodImplAttribute(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhGetMaxGcGeneration")] internal static extern int RhGetMaxGcGeneration(); // Get count of collections so far. [MethodImplAttribute(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhGetGcCollectionCount")] internal static extern int RhGetGcCollectionCount(int generation, bool getSpecialGCCount); [MethodImplAttribute(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhGetGeneration")] internal static extern int RhGetGeneration(Object obj); [MethodImpl(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhGetGcLatencyMode")] internal static extern GCLatencyMode RhGetGcLatencyMode(); [MethodImpl(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhSetGcLatencyMode")] internal static extern void RhSetGcLatencyMode(GCLatencyMode newLatencyMode); [MethodImpl(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhIsServerGc")] internal static extern bool RhIsServerGc(); [MethodImpl(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhGetGcTotalMemory")] internal static extern long RhGetGcTotalMemory(); [MethodImpl(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhGetLohCompactionMode")] internal static extern int RhGetLohCompactionMode(); [MethodImpl(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhSetLohCompactionMode")] internal static extern void RhSetLohCompactionMode(int newLohCompactionMode); [MethodImpl(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhGetCurrentObjSize")] internal static extern long RhGetCurrentObjSize(); [MethodImpl(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhGetGCNow")] internal static extern long RhGetGCNow(); [MethodImpl(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhGetLastGCStartTime")] internal static extern long RhGetLastGCStartTime(int generation); [MethodImpl(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhGetLastGCDuration")] internal static extern long RhGetLastGCDuration(int generation); // // calls for GCHandle. // These methods are needed to implement GCHandle class like functionality (optional) // // Allocate handle. [MethodImpl(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhpHandleAlloc")] private static extern IntPtr RhpHandleAlloc(Object value, GCHandleType type); internal static IntPtr RhHandleAlloc(Object value, GCHandleType type) { IntPtr h = RhpHandleAlloc(value, type); if (h == IntPtr.Zero) throw new OutOfMemoryException(); return h; } // Allocate handle for dependent handle case where a secondary can be set at the same time. [MethodImpl(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhpHandleAllocDependent")] private static extern IntPtr RhpHandleAllocDependent(Object primary, Object secondary); internal static IntPtr RhHandleAllocDependent(Object primary, Object secondary) { IntPtr h = RhpHandleAllocDependent(primary, secondary); if (h == IntPtr.Zero) throw new OutOfMemoryException(); return h; } // Allocate variable handle with its initial type. [MethodImpl(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhpHandleAllocVariable")] private static extern IntPtr RhpHandleAllocVariable(Object value, uint type); internal static IntPtr RhHandleAllocVariable(Object value, uint type) { IntPtr h = RhpHandleAllocVariable(value, type); if (h == IntPtr.Zero) throw new OutOfMemoryException(); return h; } // Free handle. [MethodImpl(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhHandleFree")] internal static extern void RhHandleFree(IntPtr handle); // Get object reference from handle. [MethodImpl(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhHandleGet")] internal static extern Object RhHandleGet(IntPtr handle); // Get primary and secondary object references from dependent handle. [MethodImpl(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhHandleGetDependent")] internal static extern Object RhHandleGetDependent(IntPtr handle, out Object secondary); // Set object reference into handle. [MethodImpl(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhHandleSet")] internal static extern void RhHandleSet(IntPtr handle, Object value); // Set the secondary object reference into a dependent handle. [MethodImpl(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhHandleSetDependentSecondary")] internal static extern void RhHandleSetDependentSecondary(IntPtr handle, Object secondary); // Get the handle type associated with a variable handle. [MethodImpl(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhHandleGetVariableType")] internal static extern uint RhHandleGetVariableType(IntPtr handle); // Set the handle type associated with a variable handle. [MethodImpl(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhHandleSetVariableType")] internal static extern void RhHandleSetVariableType(IntPtr handle, uint type); // Conditionally and atomically set the handle type associated with a variable handle if the current // type is the one specified. Returns the previous handle type. [MethodImpl(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhHandleCompareExchangeVariableType")] internal static extern uint RhHandleCompareExchangeVariableType(IntPtr handle, uint oldType, uint newType); // // calls to runtime for type equality checks // [MethodImpl(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhTypeCast_AreTypesEquivalent")] internal static extern bool AreTypesEquivalent(EETypePtr pType1, EETypePtr pType2); [MethodImpl(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhTypeCast_AreTypesAssignable")] internal static extern bool AreTypesAssignable(EETypePtr pSourceType, EETypePtr pTargetType); [MethodImpl(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhGetEETypeHash")] internal static extern uint RhGetEETypeHash(EETypePtr pType); [MethodImpl(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhTypeCast_CheckArrayStore")] internal static extern void RhCheckArrayStore(Object array, Object obj); [MethodImpl(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhTypeCast_IsInstanceOf")] internal static extern object IsInstanceOf(object obj, EETypePtr pTargetType); [MethodImpl(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhTypeCast_IsInstanceOfClass")] internal static extern object IsInstanceOfClass(object obj, EETypePtr pTargetType); [MethodImpl(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhTypeCast_IsInstanceOfInterface")] internal static extern object IsInstanceOfInterface(object obj, EETypePtr pTargetType); // // calls to runtime for allocation // These calls are needed in types which cannot use "new" to allocate and need to do it manually // // calls to runtime for allocation // [MethodImpl(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhNewObject")] internal static extern object RhNewObject(EETypePtr pEEType); [MethodImpl(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhNewArray")] internal static extern Array RhNewArray(EETypePtr pEEType, int length); // @todo: Should we just have a proper export for this? [MethodImpl(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhNewArray")] internal static extern String RhNewArrayAsString(EETypePtr pEEType, int length); // Given the OS handle of a loaded Redhawk module, return true if the runtime no longer has any // references to resources in that module (i.e. the module can be safely unloaded with FreeLibrary, at // least as far as the runtime knows). [MethodImpl(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhCanUnloadModule")] internal static extern bool RhCanUnloadModule(IntPtr hOsModule); [MethodImpl(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhBox")] internal static unsafe extern object RhBox(EETypePtr pEEType, void* pData); [MethodImpl(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhUnbox")] internal static unsafe extern void RhUnbox(object obj, void* pData, EETypePtr pUnboxToEEType); [MethodImpl(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhMemberwiseClone")] internal static extern object RhMemberwiseClone(object obj); // Busy spin for the given number of iterations. [MethodImpl(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhSpinWait")] internal static extern void RhSpinWait(int iterations); // Yield the cpu to another thread ready to process, if one is available. [MethodImpl(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhYield")] internal static extern bool RhYield(); // Wait for any object to be signalled, in a way that's compatible with the CLR's behavior in an STA. // ExactSpelling = 'true' to force MCG to resolve it to default [DllImport(RuntimeLibrary, ExactSpelling = true)] private static unsafe extern int RhCompatibleReentrantWaitAny(int alertable, int timeout, int count, IntPtr* handles); // Temporary workaround to unblock shareable assembly bring-up - without shared interop, // we must prevent RhCompatibleReentrantWaitAny from using marshaling because it would // rewrite System.Private.CoreLib to reference the non-shareable interop assembly. With shared interop, // we will be able to remove this helper method and change the DllImport above // to directly accept a boolean parameter and use the SetLastError = true modifier. internal static unsafe int RhCompatibleReentrantWaitAny(bool alertable, int timeout, int count, IntPtr* handles) { return RhCompatibleReentrantWaitAny(alertable ? 1 : 0, timeout, count, handles); } // // EEType interrogation methods. // [MethodImplAttribute(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhGetEETypeClassification")] internal static extern RhEETypeClassification RhGetEETypeClassification(EETypePtr pEEType); [MethodImplAttribute(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhGetEETypeClassification")] internal static extern RhEETypeClassification RhGetEETypeClassification(IntPtr pEEType); [MethodImplAttribute(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhIsValueType")] internal static extern bool RhIsValueType(EETypePtr pEEType); [MethodImplAttribute(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhIsInterface")] internal static extern bool RhIsInterface(EETypePtr pEEType); [MethodImplAttribute(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhIsArray")] internal static extern bool RhIsArray(EETypePtr pEEType); [MethodImplAttribute(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhIsString")] internal static extern bool RhIsString(EETypePtr pEEType); [MethodImplAttribute(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhHasReferenceFields")] internal static extern bool RhHasReferenceFields(EETypePtr pEEType); [MethodImplAttribute(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhGetCorElementType")] internal static extern RhCorElementType RhGetCorElementType(EETypePtr pEEType); [MethodImplAttribute(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhGetValueTypeSize")] internal static extern uint RhGetValueTypeSize(EETypePtr pEEType); [MethodImplAttribute(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhIsNullable")] internal static extern bool RhIsNullable(EETypePtr pEEType); [MethodImplAttribute(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhGetNullableType")] internal static extern EETypePtr RhGetNullableType(EETypePtr pEEType); // // EEType Array Dissectors // [MethodImplAttribute(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhGetRelatedParameterType")] internal static extern EETypePtr RhGetRelatedParameterType(EETypePtr pEEType); [MethodImplAttribute(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhGetComponentSize")] internal static extern ushort RhGetComponentSize(EETypePtr pEEType); // // EEType Parent Hierarchy // [MethodImplAttribute(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhGetNonArrayBaseType")] internal static extern EETypePtr RhGetNonArrayBaseType(EETypePtr pEEType); // Note: This reports the transitive closure, not just the directly implemented interfaces. [MethodImplAttribute(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhGetNumInterfaces")] internal static extern uint RhGetNumInterfaces(EETypePtr pEEType); [MethodImplAttribute(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhGetInterface")] internal static extern EETypePtr RhGetInterface(EETypePtr pEEType, uint index); [MethodImplAttribute(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhGetGCDescSize")] internal static extern int RhGetGCDescSize(EETypePtr eeType); [MethodImplAttribute(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhCreateGenericInstanceDescForType2")] internal static unsafe extern bool RhCreateGenericInstanceDescForType2(EETypePtr pEEType, int arity, int nonGcStaticDataSize, int nonGCStaticDataOffset, int gcStaticDataSize, int threadStaticsOffset, void* pGcStaticsDesc, void* pThreadStaticsDesc, int* pGenericVarianceFlags); [MethodImplAttribute(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhAllocateMemory")] internal static unsafe extern IntPtr RhAllocateMemory(int sizeInBytes); [MethodImplAttribute(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhSetInterface")] internal static unsafe extern void RhSetInterface(EETypePtr pEEType, int index, EETypePtr pEETypeInterface); [MethodImplAttribute(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhSetGenericInstantiation")] internal static unsafe extern bool RhSetGenericInstantiation(EETypePtr pEEType, EETypePtr pEETypeDef, int arity, EETypePtr* pInstantiation); [MethodImplAttribute(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhNewInterfaceDispatchCell")] internal static unsafe extern IntPtr RhNewInterfaceDispatchCell(EETypePtr pEEType, int slotNumber); [MethodImplAttribute(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhResolveDispatch")] internal static extern IntPtr RhResolveDispatch(object pObject, EETypePtr pInterfaceType, ushort slot); [MethodImplAttribute(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhGetNonGcStaticFieldData")] internal static unsafe extern IntPtr RhGetNonGcStaticFieldData(EETypePtr pEEType); [MethodImplAttribute(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhGetGcStaticFieldData")] internal static unsafe extern IntPtr RhGetGcStaticFieldData(EETypePtr pEEType); [MethodImplAttribute(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhAllocateThunksFromTemplate")] internal static extern IntPtr RhAllocateThunksFromTemplate(IntPtr moduleHandle, int templateRva, int templateSize); [MethodImplAttribute(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhGetThreadLocalStorageForDynamicType")] internal static extern IntPtr RhGetThreadLocalStorageForDynamicType(int index, int tlsStorageSize, int numTlsCells); [MethodImplAttribute(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhIsDynamicType")] internal static unsafe extern bool RhIsDynamicType(EETypePtr pEEType); [MethodImplAttribute(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhHasCctor")] internal static unsafe extern bool RhHasCctor(EETypePtr pEEType); [MethodImplAttribute(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhResolveDispatchOnType")] internal static extern IntPtr RhResolveDispatchOnType(EETypePtr instanceType, EETypePtr interfaceType, ushort slot); // Keep in sync with RH\src\rtu\runtimeinstance.cpp internal enum RuntimeHelperKind { AllocateObject, IsInst, CastClass, AllocateArray, CheckArrayElementType, } [MethodImplAttribute(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhGetRuntimeHelperForType")] internal static unsafe extern IntPtr RhGetRuntimeHelperForType(EETypePtr pEEType, RuntimeHelperKind kind); [MethodImplAttribute(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhGetDispatchMapForType")] internal static unsafe extern IntPtr RhGetDispatchMapForType(EETypePtr pEEType); // // Support for GC and HandleTable callouts. // internal enum GcRestrictedCalloutKind { StartCollection = 0, // Collection is about to begin EndCollection = 1, // Collection has completed AfterMarkPhase = 2, // All live objects are marked (not including ready for finalization objects), // no handles have been cleared } [MethodImplAttribute(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhRegisterGcCallout")] internal static extern bool RhRegisterGcCallout(GcRestrictedCalloutKind eKind, IntPtr pCalloutMethod); [MethodImplAttribute(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhUnregisterGcCallout")] internal static extern void RhUnregisterGcCallout(GcRestrictedCalloutKind eKind, IntPtr pCalloutMethod); [MethodImplAttribute(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhRegisterRefCountedHandleCallback")] internal static extern bool RhRegisterRefCountedHandleCallback(IntPtr pCalloutMethod, EETypePtr pTypeFilter); [MethodImplAttribute(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhUnregisterRefCountedHandleCallback")] internal static extern void RhUnregisterRefCountedHandleCallback(IntPtr pCalloutMethod, EETypePtr pTypeFilter); [MethodImplAttribute(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhIsPromoted")] internal static extern bool RhIsPromoted(object obj); // // Blob support // [MethodImplAttribute(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhFindBlob")] internal static unsafe extern bool RhFindBlob(IntPtr hOsModule, uint blobId, byte** ppbBlob, uint* pcbBlob); #if CORERT internal static uint RhGetLoadedModules(IntPtr[] resultArray) { IntPtr[] loadedModules = Internal.Runtime.CompilerHelpers.StartupCodeHelpers.Modules; if (resultArray != null) { Array.Copy(loadedModules, resultArray, Math.Min(loadedModules.Length, resultArray.Length)); } return (uint)loadedModules.Length; } #else [MethodImplAttribute(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhGetLoadedModules")] internal static extern uint RhGetLoadedModules(IntPtr[] resultArray); #endif [MethodImplAttribute(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhGetModuleFromPointer")] internal static extern IntPtr RhGetModuleFromPointer(IntPtr pointerVal); [MethodImplAttribute(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhGetModuleFromEEType")] internal static extern IntPtr RhGetModuleFromEEType(IntPtr pEEType); [MethodImplAttribute(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhGetThreadStaticFieldAddress")] internal static unsafe extern byte* RhGetThreadStaticFieldAddress(EETypePtr pEEType, IntPtr fieldCookie); [MethodImplAttribute(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhGetCodeTarget")] internal static extern IntPtr RhGetCodeTarget(IntPtr pCode); [MethodImplAttribute(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhGetJmpStubCodeTarget")] internal static extern IntPtr RhGetJmpStubCodeTarget(IntPtr pCode); // // EH helpers // [MethodImplAttribute(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhGetModuleFileName")] #if PLATFORM_UNIX internal static extern unsafe int RhGetModuleFileName(IntPtr moduleHandle, out byte* moduleName); #else internal static extern unsafe int RhGetModuleFileName(IntPtr moduleHandle, out char* moduleName); #endif [MethodImplAttribute(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhGetExceptionsForCurrentThread")] internal static extern unsafe bool RhGetExceptionsForCurrentThread(Exception[] outputArray, out int writtenCountOut); // returns the previous value. [MethodImplAttribute(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhSetErrorInfoBuffer")] internal static extern unsafe void* RhSetErrorInfoBuffer(void* pNewBuffer); // // StackTrace helper // [MethodImplAttribute(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhFindMethodStartAddress")] internal static extern unsafe IntPtr RhFindMethodStartAddress(IntPtr codeAddr); // Fetch a (managed) stack trace. Fills in the given array with "return address IPs" for the current // thread's (managed) stack (array index 0 will be the caller of this method). The return value is // the number of frames in the stack or a negative number (representing the required array size) if // the passed-in buffer is too small. [MethodImplAttribute(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhGetCurrentThreadStackTrace")] internal static extern int RhGetCurrentThreadStackTrace(IntPtr[] outputBuffer); // Functions involved in thunks from managed to managed functions (Universal transition transitions // from an arbitrary method call into a defined function, and CallDescrWorker goes the other way. [MethodImplAttribute(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhGetUniversalTransitionThunk")] internal static extern IntPtr RhGetUniversalTransitionThunk(); [MethodImplAttribute(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhCallDescrWorker")] internal static extern void RhCallDescrWorker(IntPtr callDescr); // Moves memory from smem to dmem. Size must be a positive value. // This copy uses an intrinsic to be safe for copying arbitrary bits of // heap memory [MethodImplAttribute(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhBulkMoveWithWriteBarrier")] internal static extern unsafe void RhBulkMoveWithWriteBarrier(byte* dmem, byte* smem, int size); // The GC conservative reporting descriptor is a special structure of data that the GC // parses to determine whether there are specific regions of memory that it should not // collect or move around. // This can only be used to report memory regions on the current stack and the structure must itself // be located on the stack. // This structure is contractually required to be 4 pointers in size. All details about // the contents are abstracted into the runtime // To use, place one of these structures on the stack, and then pass it by ref to a function // which will pin the byref to create a pinned interior pointer. // Then, call RhInitializeConservativeReportingRegion to mark the region as conservatively reported. // When done, call RhDisableConservativeReportingRegion to disable conservative reporting, or // simply let it be pulled off the stack. internal struct ConservativelyReportedRegionDesc { IntPtr ptr1; IntPtr ptr2; IntPtr ptr3; IntPtr ptr4; } [MethodImplAttribute(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhInitializeConservativeReportingRegion")] internal static extern unsafe void RhInitializeConservativeReportingRegion(ConservativelyReportedRegionDesc* regionDesc, void* bufferBegin, int cbBuffer); [MethodImplAttribute(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhDisableConservativeReportingRegion")] internal static extern unsafe void RhDisableConservativeReportingRegion(ConservativelyReportedRegionDesc* regionDesc); // // ETW helpers. // [MethodImplAttribute(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhpETWLogLiveCom")] internal extern static void RhpETWLogLiveCom(int eventType, IntPtr CCWHandle, IntPtr objectID, IntPtr typeRawValue, IntPtr IUnknown, IntPtr VTable, Int32 comRefCount, Int32 jupiterRefCount, Int32 flags); [MethodImplAttribute(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhpETWShouldWalkCom")] internal extern static bool RhpETWShouldWalkCom(); [MethodImplAttribute(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhpEtwExceptionThrown")] internal extern static unsafe void RhpEtwExceptionThrown(char* exceptionTypeName, char* exceptionMessage, IntPtr faultingIP, long hresult); #if CORERT // // Interlocked helpers // [MethodImplAttribute(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhpLockCmpXchg32")] internal extern static int InterlockedCompareExchange(ref int location1, int value, int comparand); [MethodImplAttribute(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhpLockCmpXchg64")] internal extern static long InterlockedCompareExchange(ref long location1, long value, long comparand); [MethodImplAttribute(MethodImplOptions.InternalCall)] #if BIT64 [RuntimeImport(RuntimeLibrary, "RhpLockCmpXchg64")] #else [RuntimeImport(RuntimeLibrary, "RhpLockCmpXchg32")] #endif internal extern static IntPtr InterlockedCompareExchange(ref IntPtr location1, IntPtr value, IntPtr comparand); [MethodImplAttribute(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhpCheckedLockCmpXchg")] internal extern static object InterlockedCompareExchange(ref object location1, object value, object comparand); [MethodImplAttribute(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhpCheckedXchg")] internal extern static object InterlockedExchange(ref object location1, object value); [MethodImplAttribute(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhpMemoryBarrier")] internal extern static void MemoryBarrier(); [Intrinsic] [MethodImplAttribute(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "fabs")] internal static extern double fabs(double x); #endif // CORERT #if !CORERT [Intrinsic] [MethodImplAttribute(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "_copysign")] internal static extern double _copysign(double x, double y); #endif // !CORERT [Intrinsic] [MethodImplAttribute(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "floor")] internal static extern double floor(double x); [Intrinsic] [MethodImplAttribute(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "fmod")] internal static extern double fmod(double x, double y); [Intrinsic] [MethodImplAttribute(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "pow")] internal static extern double pow(double x, double y); [Intrinsic] [MethodImplAttribute(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "sqrt")] internal static extern double sqrt(double x); [Intrinsic] [MethodImplAttribute(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "ceil")] internal static extern double ceil(double x); [Intrinsic] [MethodImplAttribute(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "cos")] internal static extern double cos(double x); [Intrinsic] [MethodImplAttribute(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "sin")] internal static extern double sin(double x); [Intrinsic] [MethodImplAttribute(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "tan")] internal static extern double tan(double x); [Intrinsic] [MethodImplAttribute(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "cosh")] internal static extern double cosh(double x); [Intrinsic] [MethodImplAttribute(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "sinh")] internal static extern double sinh(double x); [Intrinsic] [MethodImplAttribute(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "tanh")] internal static extern double tanh(double x); [Intrinsic] [MethodImplAttribute(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "acos")] internal static extern double acos(double x); [Intrinsic] [MethodImplAttribute(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "asin")] internal static extern double asin(double x); [Intrinsic] [MethodImplAttribute(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "atan")] internal static extern double atan(double x); [Intrinsic] [MethodImplAttribute(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "atan2")] internal static extern double atan2(double x, double y); [Intrinsic] [MethodImplAttribute(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "log")] internal static extern double log(double x); [Intrinsic] [MethodImplAttribute(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "log10")] internal static extern double log10(double x); [Intrinsic] [MethodImplAttribute(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "exp")] internal static extern double exp(double x); [Intrinsic] [MethodImplAttribute(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "modf")] internal static unsafe extern double modf(double x, double* intptr); #if !PLATFORM_UNIX // ExactSpelling = 'true' to force MCG to resolve it to default [DllImport(RuntimeImports.RuntimeLibrary, ExactSpelling = true)] internal static unsafe extern void _ecvt_s(byte* buffer, int sizeInBytes, double value, int count, int* dec, int* sign); #endif #if BIT64 [DllImport(RuntimeImports.RuntimeLibrary, ExactSpelling = true)] internal static unsafe extern void memmove(byte* dmem, byte* smem, ulong size); #else [DllImport(RuntimeImports.RuntimeLibrary, ExactSpelling = true)] internal static unsafe extern void memmove(byte* dmem, byte* smem, uint size); #endif [MethodImpl(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhpArrayCopy")] internal static extern bool TryArrayCopy(Array sourceArray, int sourceIndex, Array destinationArray, int destinationIndex, int length); [MethodImpl(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhpArrayClear")] internal static extern bool TryArrayClear(Array array, int index, int length); // Only the values defined below are valid. Any other value returned from RhGetCorElementType // indicates only that the type is not one of the primitives defined below and is otherwise undefined // and subject to change. internal enum RhCorElementType : byte { ELEMENT_TYPE_BOOLEAN = 0x2, ELEMENT_TYPE_CHAR = 0x3, ELEMENT_TYPE_I1 = 0x4, ELEMENT_TYPE_U1 = 0x5, ELEMENT_TYPE_I2 = 0x6, ELEMENT_TYPE_U2 = 0x7, ELEMENT_TYPE_I4 = 0x8, ELEMENT_TYPE_U4 = 0x9, ELEMENT_TYPE_I8 = 0xa, ELEMENT_TYPE_U8 = 0xb, ELEMENT_TYPE_R4 = 0xc, ELEMENT_TYPE_R8 = 0xd, ELEMENT_TYPE_I = 0x18, ELEMENT_TYPE_U = 0x19, } // Keep in sync with ProjectN\src\RH\src\rtm\System\Runtime\RuntimeExports.cs internal enum RhEETypeClassification { Regular, // Object, String, Int32 Array, // String[] Generic, // List<Int32> GenericTypeDefinition, // List<T> UnmanagedPointer, // void* } internal static RhCorElementTypeInfo GetRhCorElementTypeInfo(RuntimeImports.RhCorElementType elementType) { return RhCorElementTypeInfo.GetRhCorElementTypeInfo(elementType); } internal struct RhCorElementTypeInfo { public RhCorElementTypeInfo(byte log2OfSize, ushort widenMask, bool isPrimitive = false) { _log2OfSize = log2OfSize; RhCorElementTypeInfoFlags flags = RhCorElementTypeInfoFlags.IsValid; if (isPrimitive) flags |= RhCorElementTypeInfoFlags.IsPrimitive; _flags = flags; _widenMask = widenMask; } public bool IsPrimitive { get { return 0 != (_flags & RhCorElementTypeInfoFlags.IsPrimitive); } } public bool IsFloat { get { return 0 != (_flags & RhCorElementTypeInfoFlags.IsFloat); } } public byte Log2OfSize { get { return _log2OfSize; } } // // This is a port of InvokeUtil::CanPrimitiveWiden() in the desktop runtime. This is used by various apis such as Array.SetValue() // and Delegate.DynamicInvoke() which allow value-preserving widenings from one primitive type to another. // public bool CanWidenTo(RuntimeImports.RhCorElementType targetElementType) { // Caller expected to ensure that both sides are primitive before calling us. Debug.Assert(this.IsPrimitive); Debug.Assert(GetRhCorElementTypeInfo(targetElementType).IsPrimitive); // Once we've asserted that the target is a primitive, we can also assert that it is >= ET_BOOLEAN. Debug.Assert(targetElementType >= RuntimeImports.RhCorElementType.ELEMENT_TYPE_BOOLEAN); byte targetElementTypeAsByte = (byte)targetElementType; ushort mask = (ushort)(1 << targetElementTypeAsByte); // This is expected to overflow on larger ET_I and ET_U - this is ok and anticipated. if (0 != (_widenMask & mask)) return true; return false; } internal static RhCorElementTypeInfo GetRhCorElementTypeInfo(RuntimeImports.RhCorElementType elementType) { // The _lookupTable array only covers a subset of RhCorElementTypes, so we return a default // info when someone asks for an elementType which does not have an entry in the table. if ((int)elementType > s_lookupTable.Length) return default(RhCorElementTypeInfo); return s_lookupTable[(int)elementType]; } private byte _log2OfSize; private RhCorElementTypeInfoFlags _flags; [Flags] private enum RhCorElementTypeInfoFlags : byte { IsValid = 0x01, // Set for all valid CorElementTypeInfo's IsPrimitive = 0x02, // Is it a primitive type (as defined by TypeInfo.IsPrimitive) IsFloat = 0x04, // Is it a floating point type } private ushort _widenMask; #if BIT64 const byte log2PointerSize = 3; #else private const byte log2PointerSize = 2; #endif [PreInitialized] // The enclosing class (RuntimeImports) is depended upon (indirectly) by // __vtable_IUnknown, which is an eager-init class, so this type must not have a // lazy-init .cctor private static RhCorElementTypeInfo[] s_lookupTable = new RhCorElementTypeInfo[] { // index = 0x0 new RhCorElementTypeInfo { _log2OfSize = 0, _widenMask = 0x0000, _flags = 0 }, // index = 0x1 new RhCorElementTypeInfo { _log2OfSize = 0, _widenMask = 0x0000, _flags = 0 }, // index = 0x2 = ELEMENT_TYPE_BOOLEAN (W = BOOL) new RhCorElementTypeInfo { _log2OfSize = 0, _widenMask = 0x0004, _flags = RhCorElementTypeInfoFlags.IsValid|RhCorElementTypeInfoFlags.IsPrimitive }, // index = 0x3 = ELEMENT_TYPE_CHAR (W = U2, CHAR, I4, U4, I8, U8, R4, R8) (U2 == Char) new RhCorElementTypeInfo { _log2OfSize = 1, _widenMask = 0x3f88, _flags = RhCorElementTypeInfoFlags.IsValid|RhCorElementTypeInfoFlags.IsPrimitive }, // index = 0x4 = ELEMENT_TYPE_I1 (W = I1, I2, I4, I8, R4, R8) new RhCorElementTypeInfo { _log2OfSize = 0, _widenMask = 0x3550, _flags = RhCorElementTypeInfoFlags.IsValid|RhCorElementTypeInfoFlags.IsPrimitive }, // index = 0x5 = ELEMENT_TYPE_U1 (W = CHAR, U1, I2, U2, I4, U4, I8, U8, R4, R8) new RhCorElementTypeInfo { _log2OfSize = 0, _widenMask = 0x3FE8, _flags = RhCorElementTypeInfoFlags.IsValid|RhCorElementTypeInfoFlags.IsPrimitive }, // index = 0x6 = ELEMENT_TYPE_I2 (W = I2, I4, I8, R4, R8) new RhCorElementTypeInfo { _log2OfSize = 1, _widenMask = 0x3540, _flags = RhCorElementTypeInfoFlags.IsValid|RhCorElementTypeInfoFlags.IsPrimitive }, // index = 0x7 = ELEMENT_TYPE_U2 (W = U2, CHAR, I4, U4, I8, U8, R4, R8) new RhCorElementTypeInfo { _log2OfSize = 1, _widenMask = 0x3F88, _flags = RhCorElementTypeInfoFlags.IsValid|RhCorElementTypeInfoFlags.IsPrimitive }, // index = 0x8 = ELEMENT_TYPE_I4 (W = I4, I8, R4, R8) new RhCorElementTypeInfo { _log2OfSize = 2, _widenMask = 0x3500, _flags = RhCorElementTypeInfoFlags.IsValid|RhCorElementTypeInfoFlags.IsPrimitive }, // index = 0x9 = ELEMENT_TYPE_U4 (W = U4, I8, R4, R8) new RhCorElementTypeInfo { _log2OfSize = 2, _widenMask = 0x3E00, _flags = RhCorElementTypeInfoFlags.IsValid|RhCorElementTypeInfoFlags.IsPrimitive }, // index = 0xa = ELEMENT_TYPE_I8 (W = I8, R4, R8) new RhCorElementTypeInfo { _log2OfSize = 3, _widenMask = 0x3400, _flags = RhCorElementTypeInfoFlags.IsValid|RhCorElementTypeInfoFlags.IsPrimitive }, // index = 0xb = ELEMENT_TYPE_U8 (W = U8, R4, R8) new RhCorElementTypeInfo { _log2OfSize = 3, _widenMask = 0x3800, _flags = RhCorElementTypeInfoFlags.IsValid|RhCorElementTypeInfoFlags.IsPrimitive }, // index = 0xc = ELEMENT_TYPE_R4 (W = R4, R8) new RhCorElementTypeInfo { _log2OfSize = 2, _widenMask = 0x3000, _flags = RhCorElementTypeInfoFlags.IsValid|RhCorElementTypeInfoFlags.IsPrimitive|RhCorElementTypeInfoFlags.IsFloat }, // index = 0xd = ELEMENT_TYPE_R8 (W = R8) new RhCorElementTypeInfo { _log2OfSize = 3, _widenMask = 0x2000, _flags = RhCorElementTypeInfoFlags.IsValid|RhCorElementTypeInfoFlags.IsPrimitive|RhCorElementTypeInfoFlags.IsFloat }, // index = 0xe new RhCorElementTypeInfo { _log2OfSize = 0, _widenMask = 0x0000, _flags = 0 }, // index = 0xf new RhCorElementTypeInfo { _log2OfSize = 0, _widenMask = 0x0000, _flags = 0 }, // index = 0x10 new RhCorElementTypeInfo { _log2OfSize = 0, _widenMask = 0x0000, _flags = 0 }, // index = 0x11 new RhCorElementTypeInfo { _log2OfSize = 0, _widenMask = 0x0000, _flags = 0 }, // index = 0x12 new RhCorElementTypeInfo { _log2OfSize = 0, _widenMask = 0x0000, _flags = 0 }, // index = 0x13 new RhCorElementTypeInfo { _log2OfSize = 0, _widenMask = 0x0000, _flags = 0 }, // index = 0x14 new RhCorElementTypeInfo { _log2OfSize = 0, _widenMask = 0x0000, _flags = 0 }, // index = 0x15 new RhCorElementTypeInfo { _log2OfSize = 0, _widenMask = 0x0000, _flags = 0 }, // index = 0x16 new RhCorElementTypeInfo { _log2OfSize = 0, _widenMask = 0x0000, _flags = 0 }, // index = 0x17 new RhCorElementTypeInfo { _log2OfSize = 0, _widenMask = 0x0000, _flags = 0 }, // index = 0x18 = ELEMENT_TYPE_I new RhCorElementTypeInfo { _log2OfSize = log2PointerSize, _widenMask = 0x0000, _flags = RhCorElementTypeInfoFlags.IsValid|RhCorElementTypeInfoFlags.IsPrimitive }, // index = 0x19 = ELEMENT_TYPE_U new RhCorElementTypeInfo { _log2OfSize = log2PointerSize, _widenMask = 0x0000, _flags = RhCorElementTypeInfoFlags.IsValid|RhCorElementTypeInfoFlags.IsPrimitive }, }; } } }
using UnityEngine; using System.Collections.Generic; using Pathfinding.Serialization; namespace Pathfinding { public delegate void GraphNodeDelegate (GraphNode node); public delegate bool GraphNodeDelegateCancelable (GraphNode node); public abstract class GraphNode { /** Internal unique index */ private int nodeIndex; /** Bitpacked field holding several pieces of data. * \see Walkable * \see Area * \see GraphIndex * \see Tag */ protected uint flags; /** Penalty cost for walking on this node. * This can be used to make it harder/slower to walk over certain nodes. * * A penalty of 1000 (Int3.Precision) corresponds to the cost of walking one world unit. */ private uint penalty; /** Constructor for a graph node. */ protected GraphNode (AstarPath astar) { if (!System.Object.ReferenceEquals (astar, null)) { this.nodeIndex = astar.GetNewNodeIndex(); astar.InitializeNode (this); } else { throw new System.Exception ("No active AstarPath object to bind to"); } } /** Destroys the node. * Cleans up any temporary pathfinding data used for this node. * The graph is responsible for calling this method on nodes when they are destroyed, including when the whole graph is destoyed. * Otherwise memory leaks might present themselves. * * Once called the #Destroyed property will return true and subsequent calls to this method will not do anything. * * \note Assumes the current active AstarPath instance is the same one that created this node. * * \warning Should only be called by graph classes on their own nodes */ internal void Destroy () { //Already destroyed if (Destroyed) return; ClearConnections(true); if (AstarPath.active != null) { AstarPath.active.DestroyNode(this); } nodeIndex = -1; } public bool Destroyed { get { return nodeIndex == -1; } } /** Internal unique index. * Every node will get a unique index. * This index is not necessarily correlated with e.g the position of the node in the graph. */ public int NodeIndex { get {return nodeIndex;}} /** Position of the node in world space. * \note The position is stored as an Int3, not a Vector3. * You can convert an Int3 to a Vector3 using an explicit conversion. * \code var v3 = (Vector3)node.position; \endcode */ public Int3 position; #region Constants /** Position of the walkable bit. \see Walkable */ const int FlagsWalkableOffset = 0; /** Mask of the walkable bit. \see Walkable */ const uint FlagsWalkableMask = 1 << FlagsWalkableOffset; /** Start of area bits. \see Area */ const int FlagsAreaOffset = 1; /** Mask of area bits. \see Area */ const uint FlagsAreaMask = (131072-1) << FlagsAreaOffset; /** Start of graph index bits. \see GraphIndex */ const int FlagsGraphOffset = 24; /** Mask of graph index bits. \see GraphIndex */ const uint FlagsGraphMask = (256u-1) << FlagsGraphOffset; public const uint MaxAreaIndex = FlagsAreaMask >> FlagsAreaOffset; /** Max number of graphs-1 */ public const uint MaxGraphIndex = FlagsGraphMask >> FlagsGraphOffset; /** Start of tag bits. \see Tag */ const int FlagsTagOffset = 19; /** Mask of tag bits. \see Tag */ const uint FlagsTagMask = (32-1) << FlagsTagOffset; #endregion #region Properties /** Holds various bitpacked variables. */ public uint Flags { get { return flags; } set { flags = value; } } /** Penalty cost for walking on this node. This can be used to make it harder/slower to walk over certain areas. */ public uint Penalty { get { return penalty; } set { if (value > 0xFFFFFF) Debug.LogWarning ("Very high penalty applied. Are you sure negative values haven't underflowed?\n" + "Penalty values this high could with long paths cause overflows and in some cases infinity loops because of that.\n" + "Penalty value applied: "+value); penalty = value; } } /** True if the node is traversable */ public bool Walkable { get { return (flags & FlagsWalkableMask) != 0; } set { flags = flags & ~FlagsWalkableMask | (value ? 1U : 0U) << FlagsWalkableOffset; } } public uint Area { get { return (flags & FlagsAreaMask) >> FlagsAreaOffset; } set { flags = (flags & ~FlagsAreaMask) | (value << FlagsAreaOffset); } } public uint GraphIndex { get { return (flags & FlagsGraphMask) >> FlagsGraphOffset; } set { flags = flags & ~FlagsGraphMask | value << FlagsGraphOffset; } } public uint Tag { get { return (flags & FlagsTagMask) >> FlagsTagOffset; } set { flags = flags & ~FlagsTagMask | value << FlagsTagOffset; } } #endregion public void UpdateG (Path path, PathNode pathNode) { #if ASTAR_NO_TRAVERSAL_COST pathNode.G = pathNode.parent.G + pathNode.cost; #else pathNode.G = pathNode.parent.G + pathNode.cost + path.GetTraversalCost(this); #endif } public virtual void UpdateRecursiveG (Path path, PathNode pathNode, PathHandler handler) { //Simple but slow default implementation UpdateG (path,pathNode); handler.PushNode (pathNode); GetConnections (delegate (GraphNode other) { PathNode otherPN = handler.GetPathNode (other); if (otherPN.parent == pathNode && otherPN.pathID == handler.PathID) other.UpdateRecursiveG (path, otherPN,handler); }); } public virtual void FloodFill (Stack<GraphNode> stack, uint region) { //Simple but slow default implementation GetConnections (delegate (GraphNode other) { if (other.Area != region) { other.Area = region; stack.Push (other); } }); } /** Calls the delegate with all connections from this node */ public abstract void GetConnections (GraphNodeDelegate del); public abstract void AddConnection (GraphNode node, uint cost); public abstract void RemoveConnection (GraphNode node); /** Remove all connections from this node. * \param alsoReverse if true, neighbours will be requested to remove connections to this node. */ public abstract void ClearConnections (bool alsoReverse); /** Checks if this node has a connection to the specified node */ public virtual bool ContainsConnection (GraphNode node) { // Simple but slow default implementation bool contains = false; GetConnections (neighbour => { contains |= neighbour == node; }); return contains; } /** Recalculates all connection costs from this node. * Depending on the node type, this may or may not be supported. * Nothing will be done if the operation is not supported * \todo Use interface? */ public virtual void RecalculateConnectionCosts () { } /** Add a portal from this node to the specified node. * This function should add a portal to the left and right lists which is connecting the two nodes (\a this and \a other). * * \param other The node which is on the other side of the portal (strictly speaking it does not actually have to be on the other side of the portal though). * \param left List of portal points on the left side of the funnel * \param right List of portal points on the right side of the funnel * \param backwards If this is true, the call was made on a node with the \a other node as the node before this one in the path. * In this case you may choose to do nothing since a similar call will be made to the \a other node with this node referenced as \a other (but then with backwards = true). * You do not have to care about switching the left and right lists, that is done for you already. * * \returns True if the call was deemed successful. False if some unknown case was encountered and no portal could be added. * If both calls to node1.GetPortal (node2,...) and node2.GetPortal (node1,...) return false, the funnel modifier will fall back to adding to the path * the positions of the node. * * The default implementation simply returns false. * * This function may add more than one portal if necessary. * * \see http://digestingduck.blogspot.se/2010/03/simple-stupid-funnel-algorithm.html */ public virtual bool GetPortal (GraphNode other, List<Vector3> left, List<Vector3> right, bool backwards) { return false; } /** Open the node */ public abstract void Open (Path path, PathNode pathNode, PathHandler handler); public virtual void SerializeNode (GraphSerializationContext ctx) { //Write basic node data. ctx.writer.Write (Penalty); ctx.writer.Write (Flags); } public virtual void DeserializeNode (GraphSerializationContext ctx) { Penalty = ctx.reader.ReadUInt32(); Flags = ctx.reader.ReadUInt32(); // Set the correct graph index (which might have changed, e.g if loading additively) GraphIndex = (uint)ctx.graphIndex; } /** Used to serialize references to other nodes e.g connections. * Use the GraphSerializationContext.GetNodeIdentifier and * GraphSerializationContext.GetNodeFromIdentifier methods * for serialization and deserialization respectively. * * Nodes must override this method and serialize their connections. * Graph generators do not need to call this method, it will be called automatically on all * nodes at the correct time by the serializer. */ public virtual void SerializeReferences (GraphSerializationContext ctx) { } /** Used to deserialize references to other nodes e.g connections. * Use the GraphSerializationContext.GetNodeIdentifier and * GraphSerializationContext.GetNodeFromIdentifier methods * for serialization and deserialization respectively. * * Nodes must override this method and serialize their connections. * Graph generators do not need to call this method, it will be called automatically on all * nodes at the correct time by the serializer. */ public virtual void DeserializeReferences (GraphSerializationContext ctx) { } } public abstract class MeshNode : GraphNode { protected MeshNode (AstarPath astar) : base (astar) { } public GraphNode[] connections; public uint[] connectionCosts; public abstract Int3 GetVertex (int i); public abstract int GetVertexCount (); public abstract Vector3 ClosestPointOnNode (Vector3 p); public abstract Vector3 ClosestPointOnNodeXZ (Vector3 p); public override void ClearConnections (bool alsoReverse) { // Remove all connections to this node from our neighbours if (alsoReverse && connections != null) { for (int i=0;i<connections.Length;i++) { connections[i].RemoveConnection (this); } } connections = null; connectionCosts = null; } public override void GetConnections (GraphNodeDelegate del) { if (connections == null) return; for (int i=0;i<connections.Length;i++) del (connections[i]); } public override void FloodFill (Stack<GraphNode> stack, uint region) { //Faster, more specialized implementation to override the slow default implementation if (connections == null) return; // Iterate through all connections, set the area and push the neighbour to the stack // This is a simple DFS (https://en.wikipedia.org/wiki/Depth-first_search) for (int i=0;i<connections.Length;i++) { GraphNode other = connections[i]; if (other.Area != region) { other.Area = region; stack.Push (other); } } } public override bool ContainsConnection (GraphNode node) { for (int i=0;i<connections.Length;i++) if (connections[i] == node) return true; return false; } public override void UpdateRecursiveG (Path path, PathNode pathNode, PathHandler handler) { UpdateG (path,pathNode); handler.PushNode (pathNode); for (int i=0;i<connections.Length;i++) { GraphNode other = connections[i]; PathNode otherPN = handler.GetPathNode (other); if (otherPN.parent == pathNode && otherPN.pathID == handler.PathID) { other.UpdateRecursiveG (path, otherPN,handler); } } } /** Add a connection from this node to the specified node. * If the connection already exists, the cost will simply be updated and * no extra connection added. * * \note Only adds a one-way connection. Consider calling the same function on the other node * to get a two-way connection. */ public override void AddConnection (GraphNode node, uint cost) { // Check if we already have a connection to the node if (connections != null) { for (int i=0;i<connections.Length;i++) { if (connections[i] == node) { // Just update the cost for the existing connection connectionCosts[i] = cost; return; } } } // Create new arrays which include the new connection int connLength = connections != null ? connections.Length : 0; var newconns = new GraphNode[connLength+1]; var newconncosts = new uint[connLength+1]; for (int i=0;i<connLength;i++) { newconns[i] = connections[i]; newconncosts[i] = connectionCosts[i]; } newconns[connLength] = node; newconncosts[connLength] = cost; connections = newconns; connectionCosts = newconncosts; } /** Removes any connection from this node to the specified node. * If no such connection exists, nothing will be done. * * \note This only removes the connection from this node to the other node. * You may want to call the same function on the other node to remove its eventual connection * to this node. */ public override void RemoveConnection (GraphNode node) { if (connections == null) return; // Iterate through all connections and check if there are any to the node for (int i=0;i<connections.Length;i++) { if (connections[i] == node) { // Create new arrays which have the specified node removed int connLength = connections.Length; var newconns = new GraphNode[connLength-1]; var newconncosts = new uint[connLength-1]; for (int j=0;j<i;j++) { newconns[j] = connections[j]; newconncosts[j] = connectionCosts[j]; } for (int j=i+1;j<connLength;j++) { newconns[j-1] = connections[j]; newconncosts[j-1] = connectionCosts[j]; } connections = newconns; connectionCosts = newconncosts; return; } } } /** Checks if \a p is inside the node in XZ space * * The default implementation uses XZ space and is in large part got from the website linked below * \author http://unifycommunity.com/wiki/index.php?title=PolyContainsPoint (Eric5h5) * * The TriangleMeshNode overrides this and implements faster code for that case. */ public virtual bool ContainsPoint (Int3 p) { bool inside = false; int count = GetVertexCount(); for (int i = 0, j=count-1; i < count; j = i++) { if ( ((GetVertex(i).z <= p.z && p.z < GetVertex(j).z) || (GetVertex(j).z <= p.z && p.z < GetVertex(i).z)) && (p.x < (GetVertex(j).x - GetVertex(i).x) * (p.z - GetVertex(i).z) / (GetVertex(j).z - GetVertex(i).z) + GetVertex(i).x)) inside = !inside; } return inside; } public override void SerializeReferences (GraphSerializationContext ctx) { if (connections == null) { ctx.writer.Write(-1); } else { ctx.writer.Write (connections.Length); for (int i=0;i<connections.Length;i++) { ctx.writer.Write (ctx.GetNodeIdentifier (connections[i])); ctx.writer.Write (connectionCosts[i]); } } } public override void DeserializeReferences (GraphSerializationContext ctx) { int count = ctx.reader.ReadInt32(); if (count == -1) { connections = null; connectionCosts = null; } else { connections = new GraphNode[count]; connectionCosts = new uint[count]; for (int i=0;i<count;i++) { connections[i] = ctx.GetNodeFromIdentifier (ctx.reader.ReadInt32()); connectionCosts[i] = ctx.reader.ReadUInt32(); } } } } }
// ******************************************************************************************************** // Product Name: DotSpatial.Controls.dll // Description: The Windows Forms user interface controls like the map, legend, toolbox, ribbon and others. // ******************************************************************************************************** // The contents of this file are subject to the MIT License (MIT) // you may not use this file except in compliance with the License. You may obtain a copy of the License at // http://dotspatial.codeplex.com/license // // Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF // ANY KIND, either expressed or implied. See the License for the specific language governing rights and // limitations under the License. // // The Original Code is from MapWindow.dll version 6.0 // // The Initial Developer of this Original Code is Ted Dunsford. Created 11/8/2008 2:13:10 PM // // Contributor(s): (Open source contributors should list themselves and their modifications here). // // Name | Date | Comments //--------------------|--------------------|-------------------------------------------------------- // Jiri Kadlec | 2/18/2010 | Added zoom out button and custom mouse cursors // ******************************************************************************************************** using System; using System.ComponentModel; using System.IO; using System.Linq; using System.Windows.Forms; using System.Xml; using DotSpatial.Data; using DotSpatial.Symbology; namespace DotSpatial.Controls { /// <summary> /// Preconfigured tool strip menu. /// </summary> //This control will no longer be visible [ToolboxItem(false)] // [ToolboxBitmap(typeof(SpatialToolStrip), "SpatialToolStrip.ico")] public partial class SpatialToolStrip : ToolStrip { #region Private Variables private IMap _basicMap; private AppManager _applicationManager; #endregion #region Constructors /// <summary> /// Creates a new instance of mwToolBar /// </summary> public SpatialToolStrip() : this(null) { } /// <summary> /// Constructs and initializes this toolbar using the specified IBasicMap /// </summary> /// <param name="map">The map for the toolbar to interact with</param> public SpatialToolStrip(IMap map) { InitializeComponent(); Map = map; EnableControlsToMap(); EnableControlsToAppManager(); } #endregion #region Properties /// <summary> /// Gets or sets the basic map that this toolbar will interact with by default /// </summary> [Description(" Gets or sets the basic map that this toolbar will interact with by default")] public IMap Map { get { return _basicMap; } set { if (_basicMap != null) { _basicMap.MapFrame.ViewExtentsChanged -= MapFrame_ViewExtentsChanged; } if (ApplicationManager != null && ApplicationManager.Map != null && ApplicationManager.Map != value) throw new ArgumentException("Map cannot be different than the map assigned to the AppManager. Assign this map to the AppManager first."); _basicMap = value; if (_basicMap != null) { _basicMap.MapFrame.ViewExtentsChanged += MapFrame_ViewExtentsChanged; } EnableControlsToMap(); } } /// <summary> /// Gets or sets the application manager. /// </summary> /// <value> /// The application manager. /// </value> [Description("Gets or sets the application manager.")] public AppManager ApplicationManager { get { return _applicationManager; } set { if (_applicationManager == value) return; _applicationManager = value; EnableControlsToAppManager(); } } #endregion private void EnableControlsToMap() { // Enable buttons which depends from Map cmdZoomPrevious.Enabled = cmdZoomNext.Enabled = cmdAddData.Enabled = cmdPan.Enabled = cmdSelect.Enabled = cmdZoom.Enabled = cmdZoomOut.Enabled = cmdInfo.Enabled = cmdTable.Enabled = cmdMaxExtents.Enabled = cmdLabel.Enabled = cmdZoomToCoordinates.Enabled = Map != null; } private void EnableControlsToAppManager() { // Enable buttons which depends from ApplicationManager cmdNew.Enabled = cmdOpen.Enabled = cmdSave.Enabled = ApplicationManager != null; } private void MapFrame_ViewExtentsChanged(object sender, ExtentArgs e) { var mapFrame = sender as MapFrame; if (mapFrame == null) return; cmdZoomNext.Enabled = mapFrame.CanZoomToNext(); cmdZoomPrevious.Enabled = mapFrame.CanZoomToPrevious(); } private void cmdLabel_Click(object sender, EventArgs e) { Map.FunctionMode = FunctionMode.Label; } private void cmdMaxExtents_Click(object sender, EventArgs e) { Map.ZoomToMaxExtent(); } private void cmdTable_Click(object sender, EventArgs e) { foreach (var fl in Map.MapFrame.GetAllLayers() .Where(l => l.IsSelected) .OfType<IFeatureLayer>()) { fl.ShowAttributes(); } } private void cmdInfo_Click(object sender, EventArgs e) { Map.FunctionMode = FunctionMode.Info; } private void cmdZoom_Click(object sender, EventArgs e) { Map.FunctionMode = FunctionMode.ZoomIn; } private void cmdZoomOut_Click(object sender, EventArgs e) { Map.FunctionMode = FunctionMode.ZoomOut; } private void cmdSelect_Click(object sender, EventArgs e) { Map.FunctionMode = FunctionMode.Select; } private void cmdPan_Click(object sender, EventArgs e) { Map.FunctionMode = FunctionMode.Pan; } private void cmdAddData_Click(object sender, EventArgs e) { Map.AddLayer(); } private void cmdPrint_Click(object sender, EventArgs e) { using (var layout = new LayoutForm()) { layout.MapControl = Map as Map; layout.ShowDialog(this); } } private void cmdSave_Click(object sender, EventArgs e) { using (var dlg = new SaveFileDialog { Filter = ApplicationManager.SerializationManager.SaveDialogFilterText, SupportMultiDottedExtensions = true }) { if (dlg.ShowDialog(this) != DialogResult.OK) return; string fileName = dlg.FileName; try { ApplicationManager.SerializationManager.SaveProject(fileName); } catch (XmlException) { ShowSaveAsError(fileName); } catch (IOException) { ShowSaveAsError(fileName); } } } private static void ShowSaveAsError(string fileName) { MessageBox.Show(String.Format(MessageStrings.FailedToWriteTheSpecifiedMapFile, fileName), MessageStrings.Error, MessageBoxButtons.OK, MessageBoxIcon.Error); } private void cmdOpen_Click(object sender, EventArgs e) { using (var dlg = new OpenFileDialog()) { dlg.Filter = ApplicationManager.SerializationManager.OpenDialogFilterText; if (dlg.ShowDialog() != DialogResult.OK) return; try { //use the AppManager.SerializationManager to open the project ApplicationManager.SerializationManager.OpenProject(dlg.FileName); ApplicationManager.Map.Invalidate(); } catch (IOException) { MessageBox.Show(String.Format(MessageStrings.CouldNotOpenTheSpecifiedMapFile, dlg.FileName), MessageStrings.Error, MessageBoxButtons.OK, MessageBoxIcon.Error); } catch (XmlException) { MessageBox.Show(String.Format(MessageStrings.FailedToReadTheSpecifiedMapFile, dlg.FileName), MessageStrings.Error, MessageBoxButtons.OK, MessageBoxIcon.Error); } catch (ArgumentException) { MessageBox.Show(String.Format(MessageStrings.FailedToReadAPortionOfTheSpecifiedMapFile, dlg.FileName), MessageStrings.Error, MessageBoxButtons.OK, MessageBoxIcon.Error); } } } private void cmdNew_Click(object sender, EventArgs e) { var app = ApplicationManager; // to avoid long names // if the map is empty or if the current project is already saved, start a new project directly if (!app.SerializationManager.IsDirty || app.Map.Layers == null || app.Map.Layers.Count == 0) { app.SerializationManager.New(); } else if (String.IsNullOrEmpty(app.SerializationManager.CurrentProjectFile)) { //if the current project is not specified - just ask to discard changes if (MessageBox.Show(MessageStrings.ClearAllDataAndStartANewMap, MessageStrings.DiscardChanges, MessageBoxButtons.YesNo) == DialogResult.Yes) { app.SerializationManager.New(); } } else { //the current project is specified - ask the users if they want to save changes to current project var saveProjectMessage = String.Format(MessageStrings.SaveChangesToCurrentProject, Path.GetFileName(app.SerializationManager.CurrentProjectFile)); var msgBoxResult = MessageBox.Show(saveProjectMessage, MessageStrings.DiscardChanges, MessageBoxButtons.YesNoCancel); if (msgBoxResult == DialogResult.Yes) { app.SerializationManager.SaveProject(ApplicationManager.SerializationManager.CurrentProjectFile); } if (msgBoxResult != DialogResult.Cancel) { app.SerializationManager.New(); } } } private void cmdZoomPrevious_Click(object sender, EventArgs e) { Map.MapFrame.ZoomToPrevious(); } private void cmdZoomNext_Click(object sender, EventArgs e) { Map.MapFrame.ZoomToNext(); } private void cmdZoomToCoordinates_Click(object sender, EventArgs e) { using (var dialog = new ZoomToCoordinatesDialog(Map)) dialog.ShowDialog(); } } }
// 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.Text.RegularExpressions; using Xunit; public class RightToLeft { // This test case was added to improve code coverage on methods that have a different code path with the RightToLeft option [Fact] public static void RightToLeftTests() { //////////// Global Variables used for all tests String strLoc = "Loc_000oo"; // 000ooOooo spooky String strValue = String.Empty; int iCountErrors = 0; Regex r; String s; Match m; MatchCollection mCollection; string replace, actualResult, expectedResult; string[] splitResult, expectedSplitResult; try { ///////////////////////// START TESTS //////////////////////////// /////////////////////////////////////////////////////////////////// //[]IsMatch(string) with RightToLeft strLoc = "Loc_sdfa9849"; r = new Regex(@"\s+\d+", RegexOptions.RightToLeft); s = @"sdf 12sad"; if (!r.IsMatch(s)) { iCountErrors++; Console.WriteLine("Err_16891dfa Expected match"); } s = @" asdf12 "; if (r.IsMatch(s)) { iCountErrors++; Console.WriteLine("Err_16891dafes Did not expect match"); } //[]Match(string, int, int) with RightToLeft strLoc = "Loc_6589aead"; r = new Regex(@"foo\d+", RegexOptions.RightToLeft); s = @"0123456789foo4567890foo "; m = r.Match(s, 0, s.Length); if (!m.Success) { iCountErrors++; Console.WriteLine("Err_86847sdae Expected match"); } if (m.Value != "foo4567890") { iCountErrors++; Console.WriteLine("Err_4988awea Expected Value={0} actual={1}", "foo4567890", m.Value); } m = r.Match(s, 10, s.Length - 10); if (!m.Success) { iCountErrors++; Console.WriteLine("Err_658asea Expected match"); } if (m.Value != "foo4567890") { iCountErrors++; Console.WriteLine("Err_6488ead Expected Value={0} actual={1}", "foo4567890", m.Value); } m = r.Match(s, 10, 4); if (!m.Success) { iCountErrors++; Console.WriteLine("Err_2389eads Expected match"); } if (m.Value != "foo4") { iCountErrors++; Console.WriteLine("Err_65489asdead Expected Value={0} actual={1}", "foo4", m.Value); } m = r.Match(s, 10, 3); if (m.Success) { iCountErrors++; Console.WriteLine("Err_6489sdfwa Did not expect match"); } m = r.Match(s, 11, s.Length - 11); if (m.Success) { iCountErrors++; Console.WriteLine("Err_64542adesa Did not expect match"); } //[]Matches(string) with RightToLeft strLoc = "Loc_49487depmz"; r = new Regex(@"foo\d+", RegexOptions.RightToLeft); s = @"0123456789foo4567890foo1foo 0987"; mCollection = r.Matches(s); if (mCollection.Count != 2) { iCountErrors++; Console.WriteLine("Err_49889eadf Expected match"); } else { if (mCollection[0].Value != "foo1") { iCountErrors++; Console.WriteLine("Err_8977eade Expected Value={0} actual={1}", "foo1", mCollection[0].Value); } if (mCollection[1].Value != "foo4567890") { iCountErrors++; Console.WriteLine("Err_97884dsae Expected Value={0} actual={1}", "foo4567890", mCollection[0].Value); } } //[]Replace(string, string) with RightToLeft strLoc = "Loc_3215dsfg"; r = new Regex(@"foo\s+", RegexOptions.RightToLeft); s = @"0123456789foo4567890foo "; replace = "bar"; actualResult = r.Replace(s, replace); expectedResult = "0123456789foo4567890bar"; if (actualResult != expectedResult) { iCountErrors++; Console.WriteLine("Err_65489asdead Expected Result={0} actual={1}", expectedResult, actualResult); } //[]Replace(string, string, int count) with RightToLeft strLoc = "Loc_90822safwe"; r = new Regex(@"\d", RegexOptions.RightToLeft); s = @"0123456789foo4567890foo "; replace = "#"; actualResult = r.Replace(s, replace, 17); expectedResult = "##########foo#######foo "; if (actualResult != expectedResult) { iCountErrors++; Console.WriteLine("Err_1658asead Expected Result='{0}' actual='{1}'", expectedResult, actualResult); } actualResult = r.Replace(s, replace, 7); expectedResult = "0123456789foo#######foo "; if (actualResult != expectedResult) { iCountErrors++; Console.WriteLine("Err_1238jhioa Expected Result='{0}' actual='{1}'", expectedResult, actualResult); } actualResult = r.Replace(s, replace, 0); expectedResult = "0123456789foo4567890foo "; if (actualResult != expectedResult) { iCountErrors++; Console.WriteLine("Err_56498dafe Expected Result='{0}' actual='{1}'", expectedResult, actualResult); } actualResult = r.Replace(s, replace, -1); expectedResult = "##########foo#######foo "; if (actualResult != expectedResult) { iCountErrors++; Console.WriteLine("Err_80972jnklase Expected Result='{0}' actual='{1}'", expectedResult, actualResult); } //[]Replace(string, MatchEvaluator) with RightToLeft strLoc = "Loc_5645eade"; r = new Regex(@"foo\s+", RegexOptions.RightToLeft); s = @"0123456789foo4567890foo "; replace = "bar"; actualResult = r.Replace(s, new MatchEvaluator(MyBarMatchEvaluator)); expectedResult = "0123456789foo4567890bar"; if (actualResult != expectedResult) { iCountErrors++; Console.WriteLine("Err_489894sead Expected Result={0} actual={1}", expectedResult, actualResult); } //[]Replace(string, string, int count) with RightToLeft strLoc = "Loc_6548eada"; r = new Regex(@"\d", RegexOptions.RightToLeft); s = @"0123456789foo4567890foo "; actualResult = r.Replace(s, new MatchEvaluator(MyPoundMatchEvaluator), 17); expectedResult = "##########foo#######foo "; if (actualResult != expectedResult) { iCountErrors++; Console.WriteLine("Err_6589adsfe Expected Result='{0}' actual='{1}'", expectedResult, actualResult); } actualResult = r.Replace(s, new MatchEvaluator(MyPoundMatchEvaluator), 7); expectedResult = "0123456789foo#######foo "; if (actualResult != expectedResult) { iCountErrors++; Console.WriteLine("Err_65489eadea Expected Result='{0}' actual='{1}'", expectedResult, actualResult); } actualResult = r.Replace(s, new MatchEvaluator(MyPoundMatchEvaluator), 0); expectedResult = "0123456789foo4567890foo "; if (actualResult != expectedResult) { iCountErrors++; Console.WriteLine("Err_56489eafd Expected Result='{0}' actual='{1}'", expectedResult, actualResult); } actualResult = r.Replace(s, new MatchEvaluator(MyPoundMatchEvaluator), -1); expectedResult = "##########foo#######foo "; if (actualResult != expectedResult) { iCountErrors++; Console.WriteLine("Err_6487eafd Expected Result='{0}' actual='{1}'", expectedResult, actualResult); } //[]Split(string) with RightToLeft strLoc = "Loc_5645eade"; r = new Regex(@"foo", RegexOptions.RightToLeft); s = @"0123456789foo4567890foo "; splitResult = r.Split(s); expectedSplitResult = new string[] { "0123456789", "4567890", " " } ; if (splitResult.Length != expectedSplitResult.Length) { iCountErrors++; Console.WriteLine("Err_65489aeee Expected {0} string actual={1}", expectedSplitResult.Length, splitResult.Length); } else { for (int i = 0; i < expectedSplitResult.Length; i++) { if (splitResult[i] != expectedSplitResult[i]) { iCountErrors++; Console.WriteLine("Err_0232jkoas Expected Result={0} actual={1}", expectedSplitResult[i], splitResult[i]); } } } //[]Split(string, int) with RightToLeft strLoc = "Loc_5645eade"; r = new Regex(@"\d", RegexOptions.RightToLeft); s = @"1a2b3c4d5e6f7g8h9i0k"; splitResult = r.Split(s, 11); expectedSplitResult = new string[] { "", "a", "b", "c", "d", "e", "f", "g", "h", "i", "k" } ; if (splitResult.Length != expectedSplitResult.Length) { iCountErrors++; Console.WriteLine("Err_68ead Expected {0} string actual={1}", expectedSplitResult.Length, splitResult.Length); } else { for (int i = 0; i < expectedSplitResult.Length; i++) { if (splitResult[i] != expectedSplitResult[i]) { iCountErrors++; Console.WriteLine("Err_1235eas Expected Result={0} actual={1}", expectedSplitResult[i], splitResult[i]); } } } splitResult = r.Split(s, 10); expectedSplitResult = new string[] { "1a", "b", "c", "d", "e", "f", "g", "h", "i", "k" } ; if (splitResult.Length != expectedSplitResult.Length) { iCountErrors++; Console.WriteLine("Err_66898adejl Expected {0} string actual={1}", expectedSplitResult.Length, splitResult.Length); } else { for (int i = 0; i < expectedSplitResult.Length; i++) { if (splitResult[i] != expectedSplitResult[i]) { iCountErrors++; Console.WriteLine("Err_9648kojk Expected Result={0} actual={1}", expectedSplitResult[i], splitResult[i]); } } } splitResult = r.Split(s, 2); expectedSplitResult = new string[] { "1a2b3c4d5e6f7g8h9i", "k" } ; if (splitResult.Length != expectedSplitResult.Length) { iCountErrors++; Console.WriteLine("Err_66898adejl Expected {0} string actual={1}", expectedSplitResult.Length, splitResult.Length); } else { for (int i = 0; i < expectedSplitResult.Length; i++) { if (splitResult[i] != expectedSplitResult[i]) { iCountErrors++; Console.WriteLine("Err_9648kojk Expected Result={0} actual={1}", expectedSplitResult[i], splitResult[i]); } } } splitResult = r.Split(s, 1); expectedSplitResult = new string[] { "1a2b3c4d5e6f7g8h9i0k" } ; if (splitResult.Length != expectedSplitResult.Length) { iCountErrors++; Console.WriteLine("Err_56987dellp Expected {0} string actual={1}", expectedSplitResult.Length, splitResult.Length); } else { for (int i = 0; i < expectedSplitResult.Length; i++) { if (splitResult[i] != expectedSplitResult[i]) { iCountErrors++; Console.WriteLine("Err_13678jhuy Expected Result={0} actual={1}", expectedSplitResult[i], splitResult[i]); } } } /////////////////////////////////////////////////////////////////// /////////////////////////// END TESTS ///////////////////////////// } catch (Exception exc_general) { ++iCountErrors; Console.WriteLine("Error Err_8888yyy! strLoc==" + strLoc + ", exc_general==" + exc_general.ToString()); } Assert.Equal(0, iCountErrors); } private static string MyBarMatchEvaluator(Match m) { return "bar"; } private static string MyPoundMatchEvaluator(Match m) { return "#"; } }
#region Apache Notice /***************************************************************************** * $Header: $ * $Revision: 408099 $ * $Date: 2006-05-20 23:56:36 +0200 (sam., 20 mai 2006) $ * * iBATIS.NET Data Mapper * Copyright (C) 2004 - Gilles Bayon * * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ********************************************************************************/ #endregion using System; using System.Collections; using System.Text; using IBatisNet.Common.Exceptions; using IBatisNet.Common.Utilities; using IBatisNet.Common.Utilities.Objects; using IBatisNet.DataMapper.Configuration.Sql.Dynamic; using IBatisNet.DataMapper.Configuration.Statements; using IBatisNet.DataMapper.Exceptions; using IBatisNet.DataMapper.Scope; using IBatisNet.DataMapper.TypeHandlers; namespace IBatisNet.DataMapper.Configuration.ParameterMapping { /// <summary> /// InlineParameterMapParser. /// </summary> internal class InlineParameterMapParser { #region Fields private const string PARAMETER_TOKEN = "#"; private const string PARAM_DELIM = ":"; #endregion #region Constructors /// <summary> /// Constructor /// </summary> public InlineParameterMapParser() { } #endregion /// <summary> /// Parse Inline ParameterMap /// </summary> /// <param name="statement"></param> /// <param name="sqlStatement"></param> /// <returns>A new sql command text.</returns> /// <param name="scope"></param> public SqlText ParseInlineParameterMap(IScope scope, IStatement statement, string sqlStatement) { string newSql = sqlStatement; ArrayList mappingList = new ArrayList(); Type parameterClassType = null; if (statement != null) { parameterClassType = statement.ParameterClass; } StringTokenizer parser = new StringTokenizer(sqlStatement, PARAMETER_TOKEN, true); StringBuilder newSqlBuffer = new StringBuilder(); string token = null; string lastToken = null; IEnumerator enumerator = parser.GetEnumerator(); while (enumerator.MoveNext()) { token = (string)enumerator.Current; if (PARAMETER_TOKEN.Equals(lastToken)) { if (PARAMETER_TOKEN.Equals(token)) { newSqlBuffer.Append(PARAMETER_TOKEN); token = null; } else { ParameterProperty mapping = null; if (token.IndexOf(PARAM_DELIM) > -1) { mapping = OldParseMapping(token, parameterClassType, scope); } else { mapping = NewParseMapping(token, parameterClassType, scope); } mappingList.Add(mapping); newSqlBuffer.Append("? "); enumerator.MoveNext(); token = (string)enumerator.Current; if (!PARAMETER_TOKEN.Equals(token)) { throw new DataMapperException("Unterminated inline parameter in mapped statement (" + statement.Id + ")."); } token = null; } } else { if (!PARAMETER_TOKEN.Equals(token)) { newSqlBuffer.Append(token); } } lastToken = token; } newSql = newSqlBuffer.ToString(); ParameterProperty[] mappingArray = (ParameterProperty[])mappingList.ToArray(typeof(ParameterProperty)); SqlText sqlText = new SqlText(); sqlText.Text = newSql; sqlText.Parameters = mappingArray; return sqlText; } /// <summary> /// Parse inline parameter with syntax as /// #propertyName,type=string,dbype=Varchar,direction=Input,nullValue=N/A,handler=string# /// </summary> /// <param name="token"></param> /// <param name="parameterClassType"></param> /// <param name="scope"></param> /// <returns></returns> private ParameterProperty NewParseMapping(string token, Type parameterClassType, IScope scope) { ParameterProperty mapping = new ParameterProperty(); StringTokenizer paramParser = new StringTokenizer(token, "=,", false); IEnumerator enumeratorParam = paramParser.GetEnumerator(); enumeratorParam.MoveNext(); mapping.PropertyName = ((string)enumeratorParam.Current).Trim(); while (enumeratorParam.MoveNext()) { string field = (string)enumeratorParam.Current; if (enumeratorParam.MoveNext()) { string value = (string)enumeratorParam.Current; if ("type".Equals(field)) { mapping.CLRType = value; } else if ("dbType".Equals(field)) { mapping.DbType = value; } else if ("direction".Equals(field)) { mapping.DirectionAttribute = value; } else if ("nullValue".Equals(field)) { mapping.NullValue = value; } else if ("handler".Equals(field)) { mapping.CallBackName = value; } else { throw new DataMapperException("Unrecognized parameter mapping field: '" + field + "' in " + token); } } else { throw new DataMapperException("Incorrect inline parameter map format (missmatched name=value pairs): " + token); } } if (mapping.CallBackName.Length > 0) { mapping.Initialize(scope, parameterClassType); } else { ITypeHandler handler = null; if (parameterClassType == null) { handler = scope.DataExchangeFactory.TypeHandlerFactory.GetUnkownTypeHandler(); } else { handler = ResolveTypeHandler(scope.DataExchangeFactory.TypeHandlerFactory, parameterClassType, mapping.PropertyName, mapping.CLRType, mapping.DbType); } mapping.TypeHandler = handler; mapping.Initialize(scope, parameterClassType); } return mapping; } /// <summary> /// Parse inline parameter with syntax as /// #propertyName:dbType:nullValue# /// </summary> /// <param name="token"></param> /// <param name="parameterClassType"></param> /// <param name="scope"></param> /// <returns></returns> private ParameterProperty OldParseMapping(string token, Type parameterClassType, IScope scope) { ParameterProperty mapping = new ParameterProperty(); if (token.IndexOf(PARAM_DELIM) > -1) { StringTokenizer paramParser = new StringTokenizer(token, PARAM_DELIM, true); IEnumerator enumeratorParam = paramParser.GetEnumerator(); int n1 = paramParser.TokenNumber; if (n1 == 3) { enumeratorParam.MoveNext(); string propertyName = ((string)enumeratorParam.Current).Trim(); mapping.PropertyName = propertyName; enumeratorParam.MoveNext(); enumeratorParam.MoveNext(); //ignore ":" string dBType = ((string)enumeratorParam.Current).Trim(); mapping.DbType = dBType; ITypeHandler handler = null; if (parameterClassType == null) { handler = scope.DataExchangeFactory.TypeHandlerFactory.GetUnkownTypeHandler(); } else { handler = ResolveTypeHandler(scope.DataExchangeFactory.TypeHandlerFactory, parameterClassType, propertyName, null, dBType); } mapping.TypeHandler = handler; mapping.Initialize(scope, parameterClassType); } else if (n1 >= 5) { enumeratorParam.MoveNext(); string propertyName = ((string)enumeratorParam.Current).Trim(); enumeratorParam.MoveNext(); enumeratorParam.MoveNext(); //ignore ":" string dBType = ((string)enumeratorParam.Current).Trim(); enumeratorParam.MoveNext(); enumeratorParam.MoveNext(); //ignore ":" string nullValue = ((string)enumeratorParam.Current).Trim(); while (enumeratorParam.MoveNext()) { nullValue = nullValue + ((string)enumeratorParam.Current).Trim(); } mapping.PropertyName = propertyName; mapping.DbType = dBType; mapping.NullValue = nullValue; ITypeHandler handler = null; if (parameterClassType == null) { handler = scope.DataExchangeFactory.TypeHandlerFactory.GetUnkownTypeHandler(); } else { handler = ResolveTypeHandler(scope.DataExchangeFactory.TypeHandlerFactory, parameterClassType, propertyName, null, dBType); } mapping.TypeHandler = handler; mapping.Initialize(scope, parameterClassType); } else { throw new ConfigurationException("Incorrect inline parameter map format: " + token); } } else { mapping.PropertyName = token; ITypeHandler handler = null; if (parameterClassType == null) { handler = scope.DataExchangeFactory.TypeHandlerFactory.GetUnkownTypeHandler(); } else { handler = ResolveTypeHandler(scope.DataExchangeFactory.TypeHandlerFactory, parameterClassType, token, null, null); } mapping.TypeHandler = handler; mapping.Initialize(scope, parameterClassType); } return mapping; } /// <summary> /// Resolve TypeHandler /// </summary> /// <param name="parameterClassType"></param> /// <param name="propertyName"></param> /// <param name="propertyType"></param> /// <param name="dbType"></param> /// <param name="typeHandlerFactory"></param> /// <returns></returns> private ITypeHandler ResolveTypeHandler(TypeHandlerFactory typeHandlerFactory, Type parameterClassType, string propertyName, string propertyType, string dbType) { ITypeHandler handler = null; if (parameterClassType == null) { handler = typeHandlerFactory.GetUnkownTypeHandler(); } else if (typeof(IDictionary).IsAssignableFrom(parameterClassType)) { if (propertyType == null || propertyType.Length == 0) { handler = typeHandlerFactory.GetUnkownTypeHandler(); } else { try { Type typeClass = TypeUtils.ResolveType(propertyType); handler = typeHandlerFactory.GetTypeHandler(typeClass, dbType); } catch (Exception e) { throw new ConfigurationException("Error. Could not set TypeHandler. Cause: " + e.Message, e); } } } else if (typeHandlerFactory.GetTypeHandler(parameterClassType, dbType) != null) { handler = typeHandlerFactory.GetTypeHandler(parameterClassType, dbType); } else { Type typeClass = ObjectProbe.GetMemberTypeForGetter(parameterClassType, propertyName); handler = typeHandlerFactory.GetTypeHandler(typeClass, dbType); } return handler; } } }
using System; using System.Collections.Generic; using System.Text; using System.Drawing; using M2M; using NearestNeighbor; using ConvexHullEngine; using PositionSetViewer; using PositionSetEditer; using Configuration; using Position_Interface; using Position_Implement; using AlgorithmDemo.Properties; namespace AlgorithmDemo { public class AlgorithmDemo_M2M_CH { M2M_CH m2m_CH; Layers layers; FlowControlerForm flowControlerForm; dUpdate Update; IM2MStructure m2mStructure; Color[] aryMainColor = { Color.FromArgb(30, 249, 35), Color.FromArgb(255, 0, 255), Color.FromArgb(255, 0, 0), Color.FromArgb(0, 0, 235), Color.FromArgb(236, 19, 225) }; public AlgorithmDemo_M2M_CH(M2M_CH m2m_CH, Layers layers, FlowControlerForm flowControlerForm, dUpdate update) { this.m2m_CH = m2m_CH; this.layers = layers; this.flowControlerForm = flowControlerForm; this.Update = update; m2m_CH.GetM2MStructure += delegate(IM2MStructure m2mStructure) { this.m2mStructure = m2mStructure; }; m2m_CH.GetChildPositionSetInSpecificLevelOfConvexHull += delegate { if (representativeHullLayer != null) { representativeHullLayer.Visible = false; } if (convexHullLayer != null) { lock (layers) { convexHullLayer.Visible = false; } flowControlerForm.BeginInvoke(Update); flowControlerForm.SuspendAndRecordWorkerThread(); } }; m2m_CH.GetConvexHullPositionSetInSpecificLevel += delegate { if (linePartSetLayer != null) { lock (layers) { linePartSetLayer.Visible = false; BottonLevelPositionSetLayer.Visible = false; } flowControlerForm.BeginInvoke(Update); flowControlerForm.SuspendAndRecordWorkerThread(); } }; m2m_CH.GetRealConvexHull += delegate { if (representativeHullLayer != null) { lock (layers) { representativeHullLayer.Visible = false; } } if (convexHullLayer != null) { lock (layers) { convexHullLayer.Visible = false; } flowControlerForm.BeginInvoke(Update); flowControlerForm.SuspendAndRecordWorkerThread(); } }; IsGetM2MStructure = true; IsGetPositionSetToGetConvexHull = true; IsGetConvexHullPositionSetInSpecificLevel = true; IsGetRepresentativeHullInSpecificLevel = true; IsGetLinePositionSetInSpecificLevel = true; IsGetChildPositionSetInSpecificLevelOfConvexHull = true; IsGetRealConvexHull = true; m2m_CH.GetConvexHullPositionSetInSpecificLevel += delegate { if (childPositionSetOfConvexHullLayer != null) { lock (layers) { childPositionSetOfConvexHullLayer.Visible = false; } flowControlerForm.BeginInvoke(Update); flowControlerForm.SuspendAndRecordWorkerThread(); } }; m2m_CH.GetConvexHullPositionSetInSpecificLevel += delegate { if (convexHullLayer != null) { lock (layers) { convexHullLayer.ConvexHull.Visible = false; } flowControlerForm.BeginInvoke(Update); flowControlerForm.SuspendAndRecordWorkerThread(); } }; m2m_CH.GetRealConvexHull += delegate { if (linePartSetLayer != null) { lock (layers) { linePartSetLayer.Visible = false; BottonLevelPositionSetLayer.Visible = false; } flowControlerForm.BeginInvoke(Update); flowControlerForm.SuspendAndRecordWorkerThread(); } }; flowControlerForm.SelectConfiguratoinObject(this); flowControlerForm.SuspendAndRecordWorkerThread(); } public void EndDemo() { IsGetM2MStructure = false; IsGetPositionSetToGetConvexHull = false; IsGetConvexHullPositionSetInSpecificLevel = false; IsGetRepresentativeHullInSpecificLevel = false; IsGetLinePositionSetInSpecificLevel = false; IsGetChildPositionSetInSpecificLevelOfConvexHull = false; IsGetRealConvexHull = false; flowControlerForm.SelectConfiguratoinObject(null); flowControlerForm.Reset(); } bool isGetPositionSetToGetConvexHull = false; public bool IsGetPositionSetToGetConvexHull { get { return isGetPositionSetToGetConvexHull; } set { if (isGetPositionSetToGetConvexHull != value) { isGetPositionSetToGetConvexHull = value; if (value) { m2m_CH.GetPositionSetToGetConvexHull += OnGetPositionSetToGetConvexHull; } else { m2m_CH.GetPositionSetToGetConvexHull -= OnGetPositionSetToGetConvexHull; } } } } bool isGetM2MStructure = false; public bool IsGetM2MStructure { get { return isGetM2MStructure; } set { if (isGetM2MStructure != value) { isGetM2MStructure = value; if (value) { m2m_CH.GetM2MStructure += OnGetM2MStructure; } else { m2m_CH.GetM2MStructure -= OnGetM2MStructure; } } } } bool isGetConvexHullPositionSetInSpecificLevel = false; public bool IsGetConvexHullPositionSetInSpecificLevel { get { return isGetConvexHullPositionSetInSpecificLevel; } set { if (isGetConvexHullPositionSetInSpecificLevel != value) { isGetConvexHullPositionSetInSpecificLevel = value; if (value) { m2m_CH.GetConvexHullPositionSetInSpecificLevel += OnGetConvexHullPositionSetInSpecificLevel; } else { m2m_CH.GetConvexHullPositionSetInSpecificLevel -= OnGetConvexHullPositionSetInSpecificLevel; } } } } bool isGetRepresentativeHull = false; public bool IsGetRepresentativeHullInSpecificLevel { get { return isGetRepresentativeHull; } set { if (isGetRepresentativeHull != value) { isGetRepresentativeHull = value; if (value) { m2m_CH.GetRepresentativeHullInSpecificLevel += OnGetRepresentativeHullInSpecificLevel; m2m_CH.GetConvexHullPositionSetInSpecificLevel += delegate { representativeHullLayer = null; }; } else { m2m_CH.GetRepresentativeHullInSpecificLevel -= OnGetRepresentativeHullInSpecificLevel; m2m_CH.GetConvexHullPositionSetInSpecificLevel += delegate { representativeHullLayer = null; }; } } } } bool isGetLinePositionSetInSpecificLevel = false; public bool IsGetLinePositionSetInSpecificLevel { get { return isGetLinePositionSetInSpecificLevel; } set { if (isGetLinePositionSetInSpecificLevel != value) { isGetLinePositionSetInSpecificLevel = value; if (value) { m2m_CH.GetLinePositionSetInSpecificLevel += OnGetLinePositionSetInSpecificLevel; m2m_CH.GetConvexHullPositionSetInSpecificLevel += delegate { OnTheEndOfGetLinePositionSetInSpecificLevel(); }; } else { m2m_CH.GetLinePositionSetInSpecificLevel -= OnGetLinePositionSetInSpecificLevel; m2m_CH.GetConvexHullPositionSetInSpecificLevel -= delegate { OnTheEndOfGetLinePositionSetInSpecificLevel(); }; } } } } bool isGetChildPositionSetInSpecificLevelOfConvexHull = false; public bool IsGetChildPositionSetInSpecificLevelOfConvexHull { get { return isGetChildPositionSetInSpecificLevelOfConvexHull; } set { if (isGetChildPositionSetInSpecificLevelOfConvexHull != value) { isGetChildPositionSetInSpecificLevelOfConvexHull = value; if (value) { m2m_CH.GetChildPositionSetInSpecificLevelOfConvexHull += OnGetChildPositionSetInSpecificLevelOfConvexHull; } else { m2m_CH.GetChildPositionSetInSpecificLevelOfConvexHull -= OnGetChildPositionSetInSpecificLevelOfConvexHull; } } } } bool isGetRealConvexHull = false; public bool IsGetRealConvexHull { get { return isGetRealConvexHull; } set { if (isGetRealConvexHull != value) { isGetRealConvexHull = value; if (value) { m2m_CH.GetRealConvexHull += OnGetRealConvexHull; } else { m2m_CH.GetRealConvexHull -= OnGetRealConvexHull; } } } } private void OnGetPositionSetToGetConvexHull(IPositionSet positionSet) { lock (layers) { Layer_PositionSet_Point layer = new Layer_PositionSet_Point(new PositionSet_Cloned(positionSet)); layer.MainColor = Settings.Default.PositionSetToGetConvexHullColor; layer.Point.PointRadius = 1; layers.Add(layer); } flowControlerForm.BeginInvoke(Update); flowControlerForm.SuspendAndRecordWorkerThread(); } private void OnGetM2MStructure(IM2MStructure m2mStructure) { lock (layers) { layers.Add(new Layer_M2MStructure(m2mStructure)); } flowControlerForm.BeginInvoke(Update); flowControlerForm.SuspendAndRecordWorkerThread(); } Layer_PositionSet_ConvexHull convexHullLayer; private void OnGetConvexHullPositionSetInSpecificLevel(ILevel level, int levelSequence, IPositionSet positionSet) { lock (layers) { convexHullLayer = new Layer_PositionSet_ConvexHull(new PositionSet_Cloned(positionSet)); convexHullLayer.MainColor = Settings.Default.ConvexHullPositionSetInSpecificLevelColor; convexHullLayer.ConvexHull.LineWidth = 2; convexHullLayer.ConvexHull.LineStyle = System.Drawing.Drawing2D.DashStyle.Dot; convexHullLayer.HullPoint.IsDrawPointBorder = true; convexHullLayer.HullPoint.PointRadius = 3; convexHullLayer.HullPoint.PointColor = Color.Red; convexHullLayer.SetPositionSetTransformByM2MLevel(level); convexHullLayer.Active = true; layers.Add(convexHullLayer); } flowControlerForm.BeginInvoke(Update); flowControlerForm.SuspendAndRecordWorkerThread(); } Layer_PositionSet_Path representativeHullLayer; private void OnGetRepresentativeHullInSpecificLevel(ILevel level, int levelSequence, IPositionSet positionSet) { lock (layers) { if (representativeHullLayer == null) { representativeHullLayer = new Layer_PositionSet_Path(positionSet); representativeHullLayer.PositionSetTranslationX = -(level.ConvertRealValueToRelativeValueX(0)); representativeHullLayer.PositionSetTranslationY = -(level.ConvertRealValueToRelativeValueY(0)); representativeHullLayer.MainColor = Color.FromArgb(255, 128, 0); representativeHullLayer.PathLine.LineWidth = 2; representativeHullLayer.PathLine.LineStyle = System.Drawing.Drawing2D.DashStyle.Dash; representativeHullLayer.PathPoint.PointColor = Color.FromArgb(255, 128, 0); representativeHullLayer.PathPoint.IsDrawPointBorder = true; representativeHullLayer.PathPoint.PointRadius = 2; representativeHullLayer.Active = true; layers.Add(representativeHullLayer); } representativeHullLayer.SpringLayerMaxRectChangedEvent(); } flowControlerForm.BeginInvoke(Update); flowControlerForm.SuspendAndRecordWorkerThread(); } Layer_M2MPartSetInSpecificLevel linePartSetLayer = null; Layer_PositionSet_Point BottonLevelPositionSetLayer = null; PositionSetSet positionSetSet; private void OnGetLinePositionSetInSpecificLevel(ILevel level, int levelSequence, IPositionSet positionSet) { lock (layers) { if (linePartSetLayer == null) { linePartSetLayer = new Layer_M2MPartSetInSpecificLevel(level, positionSet); linePartSetLayer.MainColor = Settings.Default.LinePositionSetInSpecificLevelColor; linePartSetLayer.Alpha = 50; //linePartSetLayer.LineColor = Color.Red; linePartSetLayer.Active = true; layers.Add(linePartSetLayer); positionSetSet = new PositionSetSet(); BottonLevelPositionSetLayer = new Layer_PositionSet_Point(positionSetSet); BottonLevelPositionSetLayer.Point.IsDrawPointBorder = true; BottonLevelPositionSetLayer.Point.PointRadius = 2; BottonLevelPositionSetLayer.Point.PointColor = Settings.Default.BottonLevelPositionSetColor; layers.Add(BottonLevelPositionSetLayer); } else { linePartSetLayer.SpringLayerRepresentationChangedEvent(linePartSetLayer); } positionSetSet.Clear(); positionSet.InitToTraverseSet(); while (positionSet.NextPosition()) { IPart tempPart = level.GetPartRefByPartIndex((int)positionSet.GetPosition().GetX(), (int)positionSet.GetPosition().GetY()); if (tempPart != null) { positionSetSet.AddPositionSet(m2mStructure.GetBottonLevelPositionSetByAncestorPart(( tempPart), levelSequence)); } } BottonLevelPositionSetLayer.SpringLayerRepresentationChangedEvent(BottonLevelPositionSetLayer); } flowControlerForm.BeginInvoke(Update); flowControlerForm.SuspendAndRecordWorkerThread(); } private void OnTheEndOfGetLinePositionSetInSpecificLevel() { linePartSetLayer = null; } Layer_PositionSet_Point childPositionSetOfConvexHullLayer; private void OnGetChildPositionSetInSpecificLevelOfConvexHull(ILevel level, int levelSequence, IPositionSet positionSet) { lock (layers) { childPositionSetOfConvexHullLayer = new Layer_PositionSet_Point(new PositionSet_Cloned(positionSet)); childPositionSetOfConvexHullLayer.SetPositionSetTransformByM2MLevel(level); childPositionSetOfConvexHullLayer.MainColor = Settings.Default.ChildPositionSetInSpecificLevelOfConvexHullColor; //layer.MainColor = GenerateColor.GetSimilarColor(GenerateColor.GetSimilarColor(GenerateColor.GetSimilarColor(aryMainColor[levelSequence]))); childPositionSetOfConvexHullLayer.Point.PointRadius = 2; childPositionSetOfConvexHullLayer.Point.IsDrawPointBorder = true; childPositionSetOfConvexHullLayer.Active = true; layers.Add(childPositionSetOfConvexHullLayer); } flowControlerForm.BeginInvoke(Update); flowControlerForm.SuspendAndRecordWorkerThread(); } private void OnGetRealConvexHull(IPositionSet positionSet) { lock (layers) { Layer_PositionSet_ConvexHull layer = new Layer_PositionSet_ConvexHull(new PositionSet_Cloned(positionSet)); layer.MainColor = Settings.Default.RealConvexHullColor; layer.ConvexHull.LineWidth = 2; layer.Active = true; layers.Add(layer); } flowControlerForm.BeginInvoke(Update); flowControlerForm.SuspendAndRecordWorkerThread(); } } }
// *********************************************************************** // Copyright (c) 2011 Charlie Poole // // 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. // *********************************************************************** #if !SILVERLIGHT && !PORTABLE using System; using System.Reflection; using System.Text; using System.Globalization; using NUnit.Framework; namespace NUnit.Common.Tests { using System.Collections.Generic; [TestFixture] public class CommandLineTests { #region General Tests [Test] public void NoInputFiles() { ConsoleOptions options = new ConsoleOptions(); Assert.True(options.Validate()); Assert.AreEqual(0, options.InputFiles.Count); } // [Test] // public void AllowForwardSlashDefaultsCorrectly() // { // ConsoleOptions options = new ConsoleOptions(); // Assert.AreEqual( Path.DirectorySeparatorChar != '/', options.AllowForwardSlash ); // } [TestCase("ShowHelp", "help|h")] [TestCase("StopOnError", "stoponerror")] [TestCase("WaitBeforeExit", "wait")] [TestCase("NoHeader", "noheader|noh")] [TestCase("Full", "full")] #if !NUNITLITE [TestCase("RunAsX86", "x86")] [TestCase("DisposeRunners", "dispose-runners")] [TestCase("ShadowCopyFiles", "shadowcopy")] #endif #if !SILVERLIGHT && !NETCF [TestCase("TeamCity", "teamcity")] #endif public void CanRecognizeBooleanOptions(string propertyName, string pattern) { Console.WriteLine("Testing " + propertyName); string[] prototypes = pattern.Split('|'); PropertyInfo property = GetPropertyInfo(propertyName); Assert.AreEqual(typeof(bool), property.PropertyType, "Property '{0}' is wrong type", propertyName); foreach (string option in prototypes) { ConsoleOptions options = new ConsoleOptions("-" + option); Assert.AreEqual(true, (bool)property.GetValue(options, null), "Didn't recognize -" + option); options = new ConsoleOptions("-" + option + "+"); Assert.AreEqual(true, (bool)property.GetValue(options, null), "Didn't recognize -" + option + "+"); options = new ConsoleOptions("-" + option + "-"); Assert.AreEqual(false, (bool)property.GetValue(options, null), "Didn't recognize -" + option + "-"); options = new ConsoleOptions("--" + option); Assert.AreEqual(true, (bool)property.GetValue(options, null), "Didn't recognize --" + option); options = new ConsoleOptions("/" + option); Assert.AreEqual(true, (bool)property.GetValue(options, null), "Didn't recognize /" + option); } } [TestCase("Include", "include", new string[] { "Short,Fast" }, new string[0])] [TestCase("Exclude", "exclude", new string[] { "Long" }, new string[0])] #if !NUNITLITE [TestCase("ActiveConfig", "config", new string[] { "Debug" }, new string[0])] [TestCase("ProcessModel", "process", new string[] { "Single", "Separate", "Multiple" }, new string[] { "JUNK" })] [TestCase("DomainUsage", "domain", new string[] { "None", "Single", "Multiple" }, new string[] { "JUNK" })] [TestCase("Framework", "framework", new string[] { "net-4.0" }, new string[0])] #endif [TestCase("OutFile", "output|out", new string[] { "output.txt" }, new string[0])] [TestCase("ErrFile", "err", new string[] { "error.txt" }, new string[0])] [TestCase("WorkDirectory", "work", new string[] { "results" }, new string[0])] [TestCase("DisplayTestLabels", "labels", new string[] { "Off", "On", "All" }, new string[] { "JUNK" })] [TestCase("InternalTraceLevel", "trace", new string[] { "Off", "Error", "Warning", "Info", "Debug", "Verbose" }, new string[] { "JUNK" })] public void CanRecognizeStringOptions(string propertyName, string pattern, string[] goodValues, string[] badValues) { string[] prototypes = pattern.Split('|'); PropertyInfo property = GetPropertyInfo(propertyName); Assert.AreEqual(typeof(string), property.PropertyType); foreach (string option in prototypes) { foreach (string value in goodValues) { string optionPlusValue = string.Format("--{0}:{1}", option, value); ConsoleOptions options = new ConsoleOptions(optionPlusValue); Assert.True(options.Validate(), "Should be valid: " + optionPlusValue); Assert.AreEqual(value, (string)property.GetValue(options, null), "Didn't recognize " + optionPlusValue); } foreach (string value in badValues) { string optionPlusValue = string.Format("--{0}:{1}", option, value); ConsoleOptions options = new ConsoleOptions(optionPlusValue); Assert.False(options.Validate(), "Should not be valid: " + optionPlusValue); } } } #if !NUNITLITE [TestCase("ProcessModel", "process", new string[] { "Single", "Separate", "Multiple" })] [TestCase("DomainUsage", "domain", new string[] { "None", "Single", "Multiple" })] #endif [TestCase("DisplayTestLabels", "labels", new string[] { "Off", "On", "All" })] [TestCase("InternalTraceLevel", "trace", new string[] { "Off", "Error", "Warning", "Info", "Debug", "Verbose" })] public void CanRecognizeLowerCaseOptionValues(string propertyName, string optionName, string[] canonicalValues) { PropertyInfo property = GetPropertyInfo(propertyName); Assert.AreEqual(typeof(string), property.PropertyType); foreach (string canonicalValue in canonicalValues) { string lowercaseValue = canonicalValue.ToLower(CultureInfo.InvariantCulture); string optionPlusValue = string.Format("--{0}:{1}", optionName, lowercaseValue); ConsoleOptions options = new ConsoleOptions(optionPlusValue); Assert.True(options.Validate(), "Should be valid: " + optionPlusValue); Assert.AreEqual(canonicalValue, (string)property.GetValue(options, null), "Didn't recognize " + optionPlusValue); } } [TestCase("DefaultTimeout", "timeout")] [TestCase("RandomSeed", "seed")] #if PARALLEL [TestCase("NumWorkers", "workers")] #endif public void CanRecognizeIntOptions(string propertyName, string pattern) { string[] prototypes = pattern.Split('|'); PropertyInfo property = GetPropertyInfo(propertyName); Assert.AreEqual(typeof(int), property.PropertyType); foreach (string option in prototypes) { ConsoleOptions options = new ConsoleOptions("--" + option + ":42"); Assert.AreEqual(42, (int)property.GetValue(options, null), "Didn't recognize --" + option + ":text"); } } // [TestCase("InternalTraceLevel", "trace", typeof(InternalTraceLevel))] // public void CanRecognizeEnumOptions(string propertyName, string pattern, Type enumType) // { // string[] prototypes = pattern.Split('|'); // PropertyInfo property = GetPropertyInfo(propertyName); // Assert.IsNotNull(property, "Property {0} not found", propertyName); // Assert.IsTrue(property.PropertyType.IsEnum, "Property {0} is not an enum", propertyName); // Assert.AreEqual(enumType, property.PropertyType); // foreach (string option in prototypes) // { // foreach (string name in Enum.GetNames(enumType)) // { // { // ConsoleOptions options = new ConsoleOptions("--" + option + ":" + name); // Assert.AreEqual(name, property.GetValue(options, null).ToString(), "Didn't recognize -" + option + ":" + name); // } // } // } // } [TestCase("--include")] [TestCase("--exclude")] #if !NUNITLITE [TestCase("--config")] [TestCase("--process")] [TestCase("--domain")] [TestCase("--framework")] #endif [TestCase("--timeout")] // [TestCase("--xml")] [TestCase("--output")] [TestCase("--err")] [TestCase("--work")] [TestCase("--trace")] public void MissingValuesAreReported(string option) { ConsoleOptions options = new ConsoleOptions(option + "="); Assert.False(options.Validate(), "Missing value should not be valid"); Assert.AreEqual("Missing required value for option '" + option + "'.", options.ErrorMessages[0]); } [Test] public void AssemblyName() { ConsoleOptions options = new ConsoleOptions("nunit.tests.dll"); Assert.True(options.Validate()); Assert.AreEqual(1, options.InputFiles.Count); Assert.AreEqual("nunit.tests.dll", options.InputFiles[0]); } // [Test] // public void FixtureNamePlusAssemblyIsValid() // { // ConsoleOptions options = new ConsoleOptions( "-fixture:NUnit.Tests.AllTests", "nunit.tests.dll" ); // Assert.AreEqual("nunit.tests.dll", options.Parameters[0]); // Assert.AreEqual("NUnit.Tests.AllTests", options.fixture); // Assert.IsTrue(options.Validate()); // } [Test] public void AssemblyAloneIsValid() { ConsoleOptions options = new ConsoleOptions("nunit.tests.dll"); Assert.True(options.Validate()); Assert.AreEqual(0, options.ErrorMessages.Count, "command line should be valid"); } [Test] public void InvalidOption() { ConsoleOptions options = new ConsoleOptions("-asembly:nunit.tests.dll"); Assert.False(options.Validate()); Assert.AreEqual(1, options.ErrorMessages.Count); Assert.AreEqual("Invalid argument: -asembly:nunit.tests.dll", options.ErrorMessages[0]); } // [Test] // public void NoFixtureNameProvided() // { // ConsoleOptions options = new ConsoleOptions( "-fixture:", "nunit.tests.dll" ); // Assert.IsFalse(options.Validate()); // } [Test] public void InvalidCommandLineParms() { ConsoleOptions options = new ConsoleOptions("-garbage:TestFixture", "-assembly:Tests.dll"); Assert.False(options.Validate()); Assert.AreEqual(2, options.ErrorMessages.Count); Assert.AreEqual("Invalid argument: -garbage:TestFixture", options.ErrorMessages[0]); Assert.AreEqual("Invalid argument: -assembly:Tests.dll", options.ErrorMessages[1]); } #endregion #region Timeout Option [Test] public void TimeoutIsMinusOneIfNoOptionIsProvided() { ConsoleOptions options = new ConsoleOptions("tests.dll"); Assert.True(options.Validate()); Assert.AreEqual(-1, options.DefaultTimeout); } [Test] public void TimeoutThrowsExceptionIfOptionHasNoValue() { Assert.Throws<Mono.Options.OptionException>(() => new ConsoleOptions("tests.dll", "-timeout")); } [Test] public void TimeoutParsesIntValueCorrectly() { ConsoleOptions options = new ConsoleOptions("tests.dll", "-timeout:5000"); Assert.True(options.Validate()); Assert.AreEqual(5000, options.DefaultTimeout); } [Test] public void TimeoutCausesErrorIfValueIsNotInteger() { ConsoleOptions options = new ConsoleOptions("tests.dll", "-timeout:abc"); Assert.False(options.Validate()); Assert.AreEqual(-1, options.DefaultTimeout); } #endregion #region EngineResult Option [Test] public void ResultOptionWithFilePath() { ConsoleOptions options = new ConsoleOptions("tests.dll", "-result:results.xml"); Assert.True(options.Validate()); Assert.AreEqual(1, options.InputFiles.Count, "assembly should be set"); Assert.AreEqual("tests.dll", options.InputFiles[0]); OutputSpecification spec = options.ResultOutputSpecifications[0]; Assert.AreEqual("results.xml", spec.OutputPath); Assert.AreEqual("nunit3", spec.Format); Assert.Null(spec.Transform); } [Test] public void ResultOptionWithFilePathAndFormat() { ConsoleOptions options = new ConsoleOptions("tests.dll", "-result:results.xml;format=nunit2"); Assert.True(options.Validate()); Assert.AreEqual(1, options.InputFiles.Count, "assembly should be set"); Assert.AreEqual("tests.dll", options.InputFiles[0]); OutputSpecification spec = options.ResultOutputSpecifications[0]; Assert.AreEqual("results.xml", spec.OutputPath); Assert.AreEqual("nunit2", spec.Format); Assert.Null(spec.Transform); } [Test] public void ResultOptionWithFilePathAndTransform() { ConsoleOptions options = new ConsoleOptions("tests.dll", "-result:results.xml;transform=transform.xslt"); Assert.True(options.Validate()); Assert.AreEqual(1, options.InputFiles.Count, "assembly should be set"); Assert.AreEqual("tests.dll", options.InputFiles[0]); OutputSpecification spec = options.ResultOutputSpecifications[0]; Assert.AreEqual("results.xml", spec.OutputPath); Assert.AreEqual("user", spec.Format); Assert.AreEqual("transform.xslt", spec.Transform); } [Test] public void FileNameWithoutResultOptionLooksLikeParameter() { ConsoleOptions options = new ConsoleOptions("tests.dll", "results.xml"); Assert.True(options.Validate()); Assert.AreEqual(0, options.ErrorMessages.Count); Assert.AreEqual(2, options.InputFiles.Count); } [Test] public void ResultOptionWithoutFileNameIsInvalid() { ConsoleOptions options = new ConsoleOptions("tests.dll", "-result:"); Assert.False(options.Validate(), "Should not be valid"); Assert.AreEqual(1, options.ErrorMessages.Count, "An error was expected"); } [Test] public void ResultOptionMayBeRepeated() { ConsoleOptions options = new ConsoleOptions("tests.dll", "-result:results.xml", "-result:nunit2results.xml;format=nunit2", "-result:myresult.xml;transform=mytransform.xslt"); Assert.True(options.Validate(), "Should be valid"); var specs = options.ResultOutputSpecifications; Assert.AreEqual(3, specs.Count); var spec1 = specs[0]; Assert.AreEqual("results.xml", spec1.OutputPath); Assert.AreEqual("nunit3", spec1.Format); Assert.Null(spec1.Transform); var spec2 = specs[1]; Assert.AreEqual("nunit2results.xml", spec2.OutputPath); Assert.AreEqual("nunit2", spec2.Format); Assert.Null(spec2.Transform); var spec3 = specs[2]; Assert.AreEqual("myresult.xml", spec3.OutputPath); Assert.AreEqual("user", spec3.Format); Assert.AreEqual("mytransform.xslt", spec3.Transform); } [Test] public void DefaultResultSpecification() { var options = new ConsoleOptions("test.dll"); Assert.AreEqual(1, options.ResultOutputSpecifications.Count); var spec = options.ResultOutputSpecifications[0]; Assert.AreEqual("TestResult.xml", spec.OutputPath); Assert.AreEqual("nunit3", spec.Format); Assert.Null(spec.Transform); } [Test] public void NoResultSuppressesDefaultResultSpecification() { var options = new ConsoleOptions("test.dll", "-noresult"); Assert.AreEqual(0, options.ResultOutputSpecifications.Count); } [Test] public void NoResultSuppressesAllResultSpecifications() { var options = new ConsoleOptions("test.dll", "-result:results.xml", "-noresult", "-result:nunit2results.xml;format=nunit2"); Assert.AreEqual(0, options.ResultOutputSpecifications.Count); } #endregion #region Explore Option [Test] public void ExploreOptionWithoutPath() { ConsoleOptions options = new ConsoleOptions("tests.dll", "-explore"); Assert.True(options.Validate()); Assert.True(options.Explore); } [Test] public void ExploreOptionWithFilePath() { ConsoleOptions options = new ConsoleOptions("tests.dll", "-explore:results.xml"); Assert.True(options.Validate()); Assert.AreEqual(1, options.InputFiles.Count, "assembly should be set"); Assert.AreEqual("tests.dll", options.InputFiles[0]); Assert.True(options.Explore); OutputSpecification spec = options.ExploreOutputSpecifications[0]; Assert.AreEqual("results.xml", spec.OutputPath); Assert.AreEqual("nunit3", spec.Format); Assert.Null(spec.Transform); } [Test] public void ExploreOptionWithFilePathAndFormat() { ConsoleOptions options = new ConsoleOptions("tests.dll", "-explore:results.xml;format=cases"); Assert.True(options.Validate()); Assert.AreEqual(1, options.InputFiles.Count, "assembly should be set"); Assert.AreEqual("tests.dll", options.InputFiles[0]); Assert.True(options.Explore); OutputSpecification spec = options.ExploreOutputSpecifications[0]; Assert.AreEqual("results.xml", spec.OutputPath); Assert.AreEqual("cases", spec.Format); Assert.Null(spec.Transform); } [Test] public void ExploreOptionWithFilePathAndTransform() { ConsoleOptions options = new ConsoleOptions("tests.dll", "-explore:results.xml;transform=myreport.xslt"); Assert.True(options.Validate()); Assert.AreEqual(1, options.InputFiles.Count, "assembly should be set"); Assert.AreEqual("tests.dll", options.InputFiles[0]); Assert.True(options.Explore); OutputSpecification spec = options.ExploreOutputSpecifications[0]; Assert.AreEqual("results.xml", spec.OutputPath); Assert.AreEqual("user", spec.Format); Assert.AreEqual("myreport.xslt", spec.Transform); } [Test] public void ExploreOptionWithFilePathUsingEqualSign() { ConsoleOptions options = new ConsoleOptions("tests.dll", "-explore=C:/nunit/tests/bin/Debug/console-test.xml"); Assert.True(options.Validate()); Assert.True(options.Explore); Assert.AreEqual(1, options.InputFiles.Count, "assembly should be set"); Assert.AreEqual("tests.dll", options.InputFiles[0]); Assert.AreEqual("C:/nunit/tests/bin/Debug/console-test.xml", options.ExploreOutputSpecifications[0].OutputPath); } #if !SILVERLIGHT && !NETCF [TestCase(true, null, true)] [TestCase(false, null, false)] [TestCase(true, false, true)] [TestCase(false, false, false)] [TestCase(true, true, true)] [TestCase(false, true, true)] public void ShouldSetTeamCityFlagAccordingToArgsAndDefauls(bool hasTeamcityInCmd, bool? defaultTeamcity, bool expectedTeamCity) { // Given List<string> args = new List<string> { "tests.dll" }; if (hasTeamcityInCmd) { args.Add("--teamcity"); } ConsoleOptions options; if (defaultTeamcity.HasValue) { options = new ConsoleOptions(new DefaultOptionsProviderStub(defaultTeamcity.Value), args.ToArray()); } else { options = new ConsoleOptions(args.ToArray()); } // When var actualTeamCity = options.TeamCity; // Then Assert.AreEqual(actualTeamCity, expectedTeamCity); } #endif #endregion #region Helper Methods private static FieldInfo GetFieldInfo(string fieldName) { FieldInfo field = typeof(ConsoleOptions).GetField(fieldName); Assert.IsNotNull(field, "The field '{0}' is not defined", fieldName); return field; } private static PropertyInfo GetPropertyInfo(string propertyName) { PropertyInfo property = typeof(ConsoleOptions).GetProperty(propertyName); Assert.IsNotNull(property, "The property '{0}' is not defined", propertyName); return property; } #endregion internal sealed class DefaultOptionsProviderStub : IDefaultOptionsProvider { public DefaultOptionsProviderStub(bool teamCity) { TeamCity = teamCity; } public bool TeamCity { get; private set; } } } } #endif
// // InternetRadioSource.cs // // Author: // Aaron Bockover <abockover@novell.com> // // 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 Mono.Unix; using Gtk; using Hyena; using Banshee.Base; using Banshee.Sources; using Banshee.Streaming; using Banshee.ServiceStack; using Banshee.Collection; using Banshee.Collection.Database; using Banshee.Configuration; using Banshee.PlaybackController; using Banshee.Gui; using Banshee.Sources.Gui; namespace Banshee.InternetRadio { public class InternetRadioSource : PrimarySource, IDisposable, IBasicPlaybackController { private uint ui_id; public InternetRadioSource () : base (Catalog.GetString ("Radio"), Catalog.GetString ("Radio"), "internet-radio", 52) { Properties.SetString ("Icon.Name", "radio"); TypeUniqueId = "internet-radio"; IsLocal = false; AfterInitialized (); InterfaceActionService uia_service = ServiceManager.Get<InterfaceActionService> (); uia_service.GlobalActions.Add ( new ActionEntry ("AddRadioStationAction", Stock.Add, Catalog.GetString ("Add Station"), null, Catalog.GetString ("Add a new Internet Radio station or playlist"), OnAddStation) ); uia_service.GlobalActions["AddRadioStationAction"].IsImportant = false; ui_id = uia_service.UIManager.AddUiFromResource ("GlobalUI.xml"); Properties.SetString ("ActiveSourceUIResource", "ActiveSourceUI.xml"); Properties.Set<bool> ("ActiveSourceUIResourcePropagate", true); Properties.Set<System.Reflection.Assembly> ("ActiveSourceUIResource.Assembly", typeof(InternetRadioSource).Assembly); Properties.SetString ("GtkActionPath", "/InternetRadioContextMenu"); Properties.Set<bool> ("Nereid.SourceContentsPropagate", true); Properties.Set<ISourceContents> ("Nereid.SourceContents", new LazyLoadSourceContents<InternetRadioSourceContents> ()); Properties.Set<string> ("SearchEntryDescription", Catalog.GetString ("Search your stations")); Properties.SetString ("TrackEditorActionLabel", Catalog.GetString ("Edit Station")); Properties.Set<InvokeHandler> ("TrackEditorActionHandler", delegate { var track_actions = ServiceManager.Get<InterfaceActionService> ().TrackActions; var tracks = track_actions.SelectedTracks; if (tracks == null || tracks.Count <= 0) { return; } foreach (var track in tracks) { var station_track = track as DatabaseTrackInfo; if (station_track != null) { EditStation (station_track); return; } } }); Properties.SetString ("TrackView.ColumnControllerXml", String.Format (@" <column-controller> <!--<column modify-default=""IndicatorColumn""> <renderer type=""Banshee.Podcasting.Gui.ColumnCellPodcastStatusIndicator"" /> </column>--> <add-default column=""IndicatorColumn"" /> <add-default column=""GenreColumn"" /> <column modify-default=""GenreColumn""> <visible>false</visible> </column> <add-default column=""TitleColumn"" /> <column modify-default=""TitleColumn""> <title>{0}</title> <long-title>{0}</long-title> </column> <add-default column=""ArtistColumn"" /> <column modify-default=""ArtistColumn""> <title>{1}</title> <long-title>{1}</long-title> </column> <add-default column=""CommentColumn"" /> <column modify-default=""CommentColumn""> <title>{2}</title> <long-title>{2}</long-title> </column> <add-default column=""RatingColumn"" /> <add-default column=""PlayCountColumn"" /> <add-default column=""LastPlayedColumn"" /> <add-default column=""LastSkippedColumn"" /> <add-default column=""DateAddedColumn"" /> <add-default column=""UriColumn"" /> <sort-column direction=""asc"">genre</sort-column> </column-controller>", Catalog.GetString ("Station"), Catalog.GetString ("Creator"), Catalog.GetString ("Description") )); ServiceManager.PlayerEngine.TrackIntercept += OnPlayerEngineTrackIntercept; //ServiceManager.PlayerEngine.ConnectEvent (OnTrackInfoUpdated, Banshee.MediaEngine.PlayerEvent.TrackInfoUpdated); TrackEqualHandler = delegate (DatabaseTrackInfo a, TrackInfo b) { RadioTrackInfo radio_track = b as RadioTrackInfo; return radio_track != null && DatabaseTrackInfo.TrackEqual ( radio_track.ParentTrack as DatabaseTrackInfo, a); }; TrackIsPlayingHandler = ServiceManager.PlayerEngine.IsPlaying; var migrator = new XspfMigrator (this); if (migrator.Migrate () | migrator.LoadDefaults ()) { Reload (); } } public override string GetPluralItemCountString (int count) { return Catalog.GetPluralString ("{0} station", "{0} stations", count); } protected override IEnumerable<IFilterListModel> CreateFiltersFor (DatabaseSource src) { DatabaseQueryFilterModel<string> genre_model = new DatabaseQueryFilterModel<string> (src, src.DatabaseTrackModel, ServiceManager.DbConnection, Catalog.GetString ("All Genres ({0})"), src.UniqueId, Banshee.Query.BansheeQuery.GenreField, "Genre"); if (this == src) { this.genre_model = genre_model; } yield return genre_model; } public override void Dispose () { base.Dispose (); //ServiceManager.PlayerEngine.DisconnectEvent (OnTrackInfoUpdated); InterfaceActionService uia_service = ServiceManager.Get<InterfaceActionService> (); if (uia_service == null) { return; } if (ui_id > 0) { uia_service.UIManager.RemoveUi (ui_id); uia_service.GlobalActions.Remove ("AddRadioStationAction"); ui_id = 0; } ServiceManager.PlayerEngine.TrackIntercept -= OnPlayerEngineTrackIntercept; } // TODO the idea with this is to grab and display cover art when we get updated info // for a radio station (eg it changes song and lets us know). The problem is I'm not sure // if that info ever/usually includes the album name, and also we would probably want to mark // such downloaded/cached cover art as temporary. /*private void OnTrackInfoUpdated (Banshee.MediaEngine.PlayerEventArgs args) { RadioTrackInfo radio_track = ServiceManager.PlaybackController.CurrentTrack as RadioTrackInfo; if (radio_track != null) { Banshee.Metadata.MetadataService.Instance.Lookup (radio_track); } }*/ private bool OnPlayerEngineTrackIntercept (TrackInfo track) { DatabaseTrackInfo station = track as DatabaseTrackInfo; if (station == null || station.PrimarySource != this) { return false; } new RadioTrackInfo (station).Play (); return true; } private void OnAddStation (object o, EventArgs args) { EditStation (null); } private void EditStation (DatabaseTrackInfo track) { StationEditor editor = new StationEditor (track); editor.Response += OnStationEditorResponse; editor.Show (); } private void OnStationEditorResponse (object o, ResponseArgs args) { StationEditor editor = (StationEditor)o; bool destroy = true; try { if (args.ResponseId == ResponseType.Ok) { DatabaseTrackInfo track = editor.Track ?? new DatabaseTrackInfo (); track.PrimarySource = this; track.IsLive = true; try { track.Uri = new SafeUri (editor.StreamUri); } catch { destroy = false; editor.ErrorMessage = Catalog.GetString ("Please provide a valid station URI"); } if (!String.IsNullOrEmpty (editor.StationCreator)) { track.ArtistName = editor.StationCreator; } track.Comment = editor.Description; if (!String.IsNullOrEmpty (editor.Genre)) { track.Genre = editor.Genre; } else { destroy = false; editor.ErrorMessage = Catalog.GetString ("Please provide a station genre"); } if (!String.IsNullOrEmpty (editor.StationTitle)) { track.TrackTitle = editor.StationTitle; track.AlbumTitle = editor.StationTitle; } else { destroy = false; editor.ErrorMessage = Catalog.GetString ("Please provide a station title"); } track.Rating = editor.Rating; if (destroy) { track.Save (); } } } finally { if (destroy) { editor.Response -= OnStationEditorResponse; editor.Destroy (); } } } #region IBasicPlaybackController implementation public bool First () { return false; } public bool Next (bool restart, bool changeImmediately) { /* * TODO: It should be technically possible to handle changeImmediately=False * correctly here, but the current implementation is quite hostile. * For the moment, just SetNextTrack (null), and go on to OpenPlay if * the engine isn't currently playing. */ if (!changeImmediately) { ServiceManager.PlayerEngine.SetNextTrack ((SafeUri)null); if (ServiceManager.PlayerEngine.IsPlaying ()) { return true; } } RadioTrackInfo radio_track = ServiceManager.PlaybackController.CurrentTrack as RadioTrackInfo; if (radio_track != null && radio_track.PlayNextStream ()) { return true; } else { return false; } } public bool Previous (bool restart) { RadioTrackInfo radio_track = ServiceManager.PlaybackController.CurrentTrack as RadioTrackInfo; if (radio_track != null && radio_track.PlayPreviousStream ()) { return true; } else { return false; } } #endregion public override bool AcceptsInputFromSource (Source source) { return false; } public override bool CanDeleteTracks { get { return false; } } public override bool ShowBrowser { get { return true; } } public override bool CanRename { get { return false; } } protected override bool HasArtistAlbum { get { return false; } } public override bool HasViewableTrackProperties { get { return false; } } public override bool HasEditableTrackProperties { get { return true; } } } }
using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using System.Reflection; using System.Data; using System.Data.Common; using Mono.Data.Sqlite; using System.IO; using Newtonsoft.Json.Linq; namespace AccountServer { /// <summary> /// Interface to SQLite /// </summary> public class SQLiteDatabase : DbInterface { static object _lock = new object(); SqliteConnection _conn; SqliteTransaction _tran; static SQLiteDatabase() { SqliteDateDiff.RegisterFunction(typeof(SqliteDateDiff)); SqliteSum.RegisterFunction(typeof(SqliteSum)); } public SQLiteDatabase(string connectionString) { createDatabase(connectionString); _conn = new SqliteConnection(); _conn.ConnectionString = connectionString; _conn.Open(); } public void BeginTransaction() { lock (_lock) { if (_tran == null) _tran = _conn.BeginTransaction(); } } /// <summary> /// Return SQL to cast a value to a type /// </summary> public string Cast(string value, string type) { return value; } public void CleanDatabase() { foreach (string table in Database.TableNames) { Table t = Database.TableFor(table); if(t.PrimaryKey.AutoIncrement) Execute(string.Format("UPDATE sqlite_sequence SET seq = (SELECT MAX({1}) FROM {0}) WHERE name='{0}'", table, t.PrimaryKey.Name)); } Execute("VACUUM"); } public void CreateTable(Table t) { View v = t as View; if (v != null) { executeLog(string.Format("CREATE VIEW `{0}` AS {1}", v.Name, v.Sql)); return; } createTable(t, t.Name); createIndexes(t); } public void CreateIndex(Table t, Index index) { executeLog(string.Format("ALTER TABLE `{0}` ADD CONSTRAINT `{1}` UNIQUE ({2})", t.Name, index.Name, string.Join(",", index.Fields.Select(f => "`" + f.Name + "` ASC").ToArray()))); } public void Commit() { if (_tran != null) { lock (_lock) { _tran.Commit(); _tran.Dispose(); _tran = null; } } } public void Dispose() { Rollback(); if (_conn != null) { _conn.Dispose(); _conn = null; } } public void DropTable(Table t) { executeLogSafe("DROP TABLE IF EXISTS " + t.Name); executeLogSafe("DROP VIEW IF EXISTS " + t.Name); } public void DropIndex(Table t, Index index) { executeLogSafe(string.Format("ALTER TABLE `{0}` DROP INDEX `{1}`", t.Name, index.Name)); } int Execute(string sql) { int lastInserttId; return Execute(sql, out lastInserttId); } public int Execute(string sql, out int lastInsertId) { lock (_lock) { using (SqliteCommand cmd = command(sql)) { var ret = cmd.ExecuteNonQuery(); cmd.CommandText = "select last_insert_rowid()"; lastInsertId = (int)(Int64)cmd.ExecuteScalar(); return ret; } } } public bool FieldsMatch(Table t, Field code, Field database) { if (code.TypeName != database.TypeName) return false; if (t.IsView) return true; // Database does not always give correct values for view columns if (code.AutoIncrement != database.AutoIncrement) return false; if (code.Length != database.Length) return false; if (code.Nullable != database.Nullable) return false; if (code.DefaultValue != database.DefaultValue) return false; return true; } public IEnumerable<JObject> Query(string query) { lock (_lock) { using (SqliteCommand cmd = command(query)) { using (SqliteDataReader r = executeReader(cmd, query)) { JObject row; while ((row = readRow(r, query)) != null) { yield return row; } } } } } public JObject QueryOne(string query) { return Query(query + " LIMIT 1").FirstOrDefault(); } static public string Quote(object o) { if (o == null || o == DBNull.Value) return "NULL"; if (o is int || o is long || o is double) return o.ToString(); if (o is decimal) return ((decimal)o).ToString("0.00"); if (o is double) return (Math.Round((decimal)o, 4)).ToString(); if (o is double) return ((decimal)o).ToString("0"); if (o is bool) return (bool)o ? "1" : "0"; if (o is DateTime) return "'" + ((DateTime)o).ToString("yyyy-MM-dd") + "'"; return "'" + o.ToString().Replace("'", "''") + "'"; } public void Rollback() { if (_tran != null) { lock (_lock) { _tran.Rollback(); _tran.Dispose(); _tran = null; } } } public Dictionary<string, Table> Tables() { Dictionary<string, Table> tables = new Dictionary<string, Table>(); createDatabase(AppSettings.Default.ConnectionString); using (SqliteConnection conn = new SqliteConnection(AppSettings.Default.ConnectionString)) { conn.Open(); DataTable tabs = conn.GetSchema("Tables"); DataTable cols = conn.GetSchema("Columns"); DataTable fkeyCols = conn.GetSchema("ForeignKeys"); DataTable indexes = conn.GetSchema("Indexes"); DataTable indexCols = conn.GetSchema("IndexColumns"); DataTable views = conn.GetSchema("Views"); DataTable viewCols = conn.GetSchema("ViewColumns"); foreach(DataRow table in tabs.Rows) { string name = table["TABLE_NAME"].ToString(); string filter = "TABLE_NAME = " + Quote(name); Field[] fields = cols.Select(filter, "ORDINAL_POSITION") .Select(c => new Field(c["COLUMN_NAME"].ToString(), typeFor(c["DATA_TYPE"].ToString()), lengthFromColumn(c), c["IS_NULLABLE"].ToString() == "True", c["AUTOINCREMENT"].ToString() == "True", defaultFromColumn(c))).ToArray(); List<Index> tableIndexes = new List<Index>(); foreach (DataRow ind in indexes.Select(filter + " AND PRIMARY_KEY = 'True'")) { string indexName = ind["INDEX_NAME"].ToString(); tableIndexes.Add(new Index("PRIMARY", indexCols.Select(filter + " AND INDEX_NAME = " + Quote(indexName), "ORDINAL_POSITION") .Select(r => fields.First(f => f.Name == r["COLUMN_NAME"].ToString())).ToArray())); } foreach (DataRow ind in indexes.Select(filter + " AND PRIMARY_KEY = 'False' AND UNIQUE = 'True'")) { string indexName = ind["INDEX_NAME"].ToString(); tableIndexes.Add(new Index(indexName, indexCols.Select(filter + " AND INDEX_NAME = " + Quote(indexName), "ORDINAL_POSITION") .Select(r => fields.First(f => f.Name == r["COLUMN_NAME"].ToString())).ToArray())); } tables[name] = new Table(name, fields, tableIndexes.ToArray()); } foreach (DataRow fk in fkeyCols.Rows) { Table detail = tables[fk["TABLE_NAME"].ToString()]; Table master = tables[fk["FKEY_TO_TABLE"].ToString()]; Field masterField = master.FieldFor(fk["FKEY_TO_COLUMN"].ToString()); detail.FieldFor(fk["FKEY_FROM_COLUMN"].ToString()).ForeignKey = new ForeignKey(master, masterField); } foreach (DataRow table in views.Select()) { string name = table["TABLE_NAME"].ToString(); string filter = "VIEW_NAME = " + Quote(name); Field[] fields = viewCols.Select(filter, "ORDINAL_POSITION") .Select(c => new Field(c["VIEW_COLUMN_NAME"].ToString(), typeFor(c["DATA_TYPE"].ToString()), lengthFromColumn(c), c["IS_NULLABLE"].ToString() == "True", false, defaultFromColumn(c))).ToArray(); Table updateTable = null; tables.TryGetValue(Regex.Replace(name, "^.*_", ""), out updateTable); tables[name] = new View(name, fields, new Index[] { new Index("PRIMARY", fields[0]) }, table["VIEW_DEFINITION"].ToString(), updateTable); } } return tables; } public void UpgradeTable(Table code, Table database, List<Field> insert, List<Field> update, List<Field> remove, List<Field> insertFK, List<Field> dropFK, List<Index> insertIndex, List<Index> dropIndex) { for (int i = dropIndex.Count; i-- > 0; ) { Index ind = dropIndex[i]; if ((ind.Fields.Length == 1 && ind.Fields[0].Name == code.PrimaryKey.Name) || ind.Name.StartsWith("sqlite_autoindex_")) dropIndex.RemoveAt(i); } if (update.Count > 0 || remove.Count > 0 || insertFK.Count > 0 || dropFK.Count > 0 || insertIndex.Count > 0 || dropIndex.Count > 0) { reCreateTable(code, database); return; } if (insert.Count != 0) { foreach(string def in insert.Select(f => "ADD COLUMN " + fieldDef(f))) { executeLog(string.Format("ALTER TABLE `{0}` {1}", code.Name, def)); } } } public bool? ViewsMatch(View code, View database) { string c = Regex.Replace(code.Sql, @"[ \r\n\t]+", " ", RegexOptions.Singleline).Trim(); string d = Regex.Replace(database.Sql, @"[ \r\n\t]+", " ", RegexOptions.Singleline).Trim(); return c == d; } SqliteCommand command(string sql) { try { return new SqliteCommand(sql, _conn, _tran); } catch (Exception ex) { throw new DatabaseException(ex, sql); } } static void createDatabase(string connectionString) { Match m = Regex.Match(connectionString, @"Data Source=([^;]+)", RegexOptions.IgnoreCase); if (m.Success && !File.Exists(m.Groups[1].Value)) { WebServer.Log("Creating SQLite database {0}", m.Groups[1].Value); Directory.CreateDirectory(Path.GetDirectoryName(m.Groups[1].Value)); SqliteConnection.CreateFile(m.Groups[1].Value); } } void createTable(Table t, string name) { List<string> defs = new List<string>(t.Fields.Select(f => fieldDef(f))); for (int i = 0; i < t.Indexes.Length; i++) { Index index = t.Indexes[i]; if (i == 0) { if (index.Fields.Length != 1 || !index.Fields[0].AutoIncrement) defs.Add(string.Format("CONSTRAINT `PRIMARY` PRIMARY KEY ({0})", string.Join(",", index.Fields .Select(f => "`" + f.Name + "`").ToArray()))); } else defs.Add(string.Format("CONSTRAINT `{0}` UNIQUE ({1})", index.Name, string.Join(",", index.Fields.Select(f => "`" + f.Name + "` ASC").ToArray()))); } defs.AddRange(t.Fields.Where(f => f.ForeignKey != null).Select(f => string.Format(@"CONSTRAINT `fk_{0}_{1}_{2}` FOREIGN KEY (`{2}`) REFERENCES `{1}` (`{3}`) ON DELETE NO ACTION ON UPDATE NO ACTION", t.Name, f.ForeignKey.Table.Name, f.Name, f.ForeignKey.Table.PrimaryKey.Name))); executeLog(string.Format("CREATE TABLE `{0}` ({1})", name, string.Join(",\r\n", defs.ToArray()))); } void createIndexes(Table t) { foreach (string sql in t.Fields.Where(f => f.ForeignKey != null && t.Indexes.FirstOrDefault(i => i.Fields[0] == f) == null) .Select(f => string.Format(@"CREATE INDEX `fk_{0}_{1}_{2}_idx` ON {0} (`{2}` ASC)", t.Name, f.ForeignKey.Table.Name, f.Name))) executeLog(sql); } static string defaultFromColumn(DataRow def) { if (def.IsNull("COLUMN_DEFAULT")) return null; string r = def["COLUMN_DEFAULT"].ToString(); Match m = Regex.Match(r, @"^'(.*)'$"); return m.Success ? m.Groups[1].Value : r; } int executeLog(string sql) { WebServer.Log(sql); lock (_lock) { using (SqliteCommand cmd = command(sql)) { return cmd.ExecuteNonQuery(); } } } int executeLogSafe(string sql) { try { return executeLog(sql); } catch (Exception ex) { WebServer.Log(ex.Message); return -1; } } SqliteDataReader executeReader(SqliteCommand cmd, string sql) { try { return cmd.ExecuteReader(); } catch (Exception ex) { throw new DatabaseException(ex, sql); } } string fieldDef(Field f) { StringBuilder b = new StringBuilder(); b.AppendFormat("`{0}` ", f.Name); switch (f.Type.Name) { case "Int32": b.Append("INTEGER"); break; case "Decimal": b.AppendFormat("DECIMAL({0})", f.Length.ToString("0.0").Replace(System.Globalization.CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator, ",")); break; case "Double": b.Append("DOUBLE"); break; case "Boolean": b.Append("BIT"); break; case "DateTime": b.Append("DATETIME"); break; case "String": if (f.Length == 0) b.Append("TEXT"); else b.AppendFormat("VARCHAR({0})", f.Length); b.Append(" COLLATE NOCASE"); break; default: throw new CheckException("Unknown type {0}", f.Type.Name); } if (f.AutoIncrement) b.Append(" PRIMARY KEY AUTOINCREMENT"); else { b.AppendFormat(" {0}NULL", f.Nullable ? "" : "NOT "); if (f.DefaultValue != null) b.AppendFormat(" DEFAULT {0}", Quote(f.DefaultValue)); } return b.ToString(); } decimal lengthFromColumn(DataRow c) { try { switch (c["DATA_TYPE"].ToString().ToLower()) { case "int": case "integer": return 11; case "tinyint": case "bit": return 1; case "decimal": string s = c["NUMERIC_PRECISION"] + System.Globalization.CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator + c["NUMERIC_SCALE"]; return s == "." ? 10.2M : decimal.Parse(s); case "double": case "float": return 10.4M; case "varchar": return Convert.ToDecimal(c["CHARACTER_MAXIMUM_LENGTH"]); default: return 0; } } catch (Exception ex) { WebServer.Log(ex.ToString()); return 0; } } JObject readRow(SqliteDataReader r, string sql) { try { lock (_lock) { if (!r.Read()) return null; } JObject row = new JObject(); for (int i = 0; i < r.FieldCount; i++) { row.Add(Regex.Replace(r.GetName(i), @"^.*\.", ""), r[i].ToJToken()); } return row; } catch (Exception ex) { throw new DatabaseException(ex, sql); } } void reCreateTable(Table code, Table database) { string newTable = "_NEW_" + code.Name; try { executeLogSafe("PRAGMA foreign_keys=OFF"); executeLog("BEGIN TRANSACTION"); createTable(code, newTable); executeLog(string.Format("INSERT INTO {0} ({2}) SELECT {2} FROM {1}", newTable, database.Name, string.Join(", ", code.Fields.Select(f => f.Name) .Where(f => database.Fields.FirstOrDefault(d => d.Name == f) != null).ToArray()))); DropTable(database); executeLog("ALTER TABLE " + newTable + " RENAME TO " + code.Name); createIndexes(code); executeLog("PRAGMA foreign_key_check"); executeLog("COMMIT TRANSACTION"); } catch (Exception ex) { WebServer.Log("Exception: {0}", ex); executeLogSafe("ROLLBACK TRANSACTION"); throw; } finally { executeLogSafe("PRAGMA foreign_keys=ON"); } } static Type typeFor(string s) { switch (s.ToLower()) { case "int": case "integer": return typeof(int); case "tinyint": case "bit": return typeof(bool); case "decimal": return typeof(decimal); case "double": case "float": return typeof(double); case "datetime": case "date": return typeof(DateTime); case "varchar": case "text": default: return typeof(string); } } } /// <summary> /// DATEDIFF function (like MySql's) /// </summary> [SqliteFunctionAttribute(Name = "DATEDIFF", Arguments = 2, FuncType = FunctionType.Scalar)] class SqliteDateDiff : SqliteFunction { public override object Invoke(object[] args) { if (args.Length < 2 || args[0] == null || args[0] == DBNull.Value || args[1] == null || args[1] == DBNull.Value) return null; try { DateTime d1 = DateTime.Parse(args[0].ToString()); DateTime d2 = DateTime.Parse(args[1].ToString()); return (d1 - d2).TotalDays; } catch (Exception ex) { WebServer.Log("Exception: {0}", ex); return null; } } } [SqliteFunctionAttribute(Name = "NOW", Arguments = 0, FuncType = FunctionType.Scalar)] class Now : SqliteFunction { public override object Invoke(object[] args) { try { return Utils.Now.ToString("yyyy-MM-ddThh:mm:ss"); } catch (Exception ex) { WebServer.Log("Exception: {0}", ex); return null; } } } /// <summary> /// SUM function which rounds as it sums, so it works like MySql's /// </summary> [SqliteFunctionAttribute(Name = "SUM", Arguments = 1, FuncType = FunctionType.Aggregate)] class SqliteSum : SqliteFunction { public override void Step(object[] args, int stepNumber, ref object contextData) { if (args.Length < 1 || args[0] == null || args[0] == DBNull.Value) return; try { decimal d = Math.Round(Convert.ToDecimal(args[0]), 4); if (contextData != null) d += (Decimal)contextData; contextData = d; } catch (Exception ex) { WebServer.Log("Exception: {0}", ex); } } public override object Final(object contextData) { return contextData; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Net; using System.Net.Http; using System.Net.Quic; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Features; using Microsoft.AspNetCore.Testing; using Microsoft.Net.Http.Headers; using Xunit; // Not tested here: Http.Sys supports sending an altsvc HTTP/2 frame if you enable the following reg key. // reg add "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\HTTP\Parameters" /v EnableAltSvc /t REG_DWORD /d 1 /f // However, this only works with certificate bindings that specify a name. We test with the IP based bindings created by IIS Express. // I don't know if the client supports the HTTP/2 altsvc frame. namespace Microsoft.AspNetCore.Server.HttpSys { [MsQuicSupported] // Required by HttpClient [HttpSysHttp3Supported] public class Http3Tests { [ConditionalFact] public async Task Http3_Direct() { using var server = Utilities.CreateDynamicHttpsServer(out var address, async httpContext => { try { Assert.True(httpContext.Request.IsHttps); await httpContext.Response.WriteAsync(httpContext.Request.Protocol); } catch (Exception ex) { await httpContext.Response.WriteAsync(ex.ToString()); } }); var handler = new HttpClientHandler(); // Needed on CI, the IIS Express cert we use isn't trusted there. handler.ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator; using var client = new HttpClient(handler); client.DefaultRequestVersion = HttpVersion.Version30; client.DefaultVersionPolicy = HttpVersionPolicy.RequestVersionExact; var response = await client.GetStringAsync(address); Assert.Equal("HTTP/3", response); } [ConditionalFact] public async Task Http3_AltSvcHeader_UpgradeFromHttp1() { var altsvc = ""; using var server = Utilities.CreateDynamicHttpsServer(out var address, async httpContext => { try { Assert.True(httpContext.Request.IsHttps); // Alt-Svc is not supported by Http.Sys, you need to add it yourself. httpContext.Response.Headers.AltSvc = altsvc; await httpContext.Response.WriteAsync(httpContext.Request.Protocol); } catch (Exception ex) { await httpContext.Response.WriteAsync(ex.ToString()); } }); altsvc = $@"h3="":{new Uri(address).Port}"""; var handler = new HttpClientHandler(); // Needed on CI, the IIS Express cert we use isn't trusted there. handler.ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator; using var client = new HttpClient(handler); client.DefaultVersionPolicy = HttpVersionPolicy.RequestVersionOrHigher; // First request is HTTP/1.1, gets an alt-svc response var request = new HttpRequestMessage(HttpMethod.Get, address); request.Version = HttpVersion.Version11; request.VersionPolicy = HttpVersionPolicy.RequestVersionExact; var response1 = await client.SendAsync(request); response1.EnsureSuccessStatusCode(); Assert.Equal("HTTP/1.1", await response1.Content.ReadAsStringAsync()); Assert.Equal(altsvc, response1.Headers.GetValues(HeaderNames.AltSvc).SingleOrDefault()); // Second request is HTTP/3 var response3 = await client.GetStringAsync(address); Assert.Equal("HTTP/3", response3); } [ConditionalFact] public async Task Http3_AltSvcHeader_UpgradeFromHttp2() { var altsvc = ""; using var server = Utilities.CreateDynamicHttpsServer(out var address, async httpContext => { try { Assert.True(httpContext.Request.IsHttps); // Alt-Svc is not supported by Http.Sys, you need to add it yourself. httpContext.Response.Headers.AltSvc = altsvc; await httpContext.Response.WriteAsync(httpContext.Request.Protocol); } catch (Exception ex) { await httpContext.Response.WriteAsync(ex.ToString()); } }); altsvc = $@"h3="":{new Uri(address).Port}"""; var handler = new HttpClientHandler(); // Needed on CI, the IIS Express cert we use isn't trusted there. handler.ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator; using var client = new HttpClient(handler); client.DefaultRequestVersion = HttpVersion.Version20; client.DefaultVersionPolicy = HttpVersionPolicy.RequestVersionOrHigher; // First request is HTTP/2, gets an alt-svc response var response2 = await client.GetAsync(address); response2.EnsureSuccessStatusCode(); Assert.Equal(altsvc, response2.Headers.GetValues(HeaderNames.AltSvc).SingleOrDefault()); Assert.Equal("HTTP/2", await response2.Content.ReadAsStringAsync()); // Second request is HTTP/3 var response3 = await client.GetStringAsync(address); Assert.Equal("HTTP/3", response3); } [ConditionalFact] public async Task Http3_ResponseTrailers() { using var server = Utilities.CreateDynamicHttpsServer(out var address, async httpContext => { try { Assert.True(httpContext.Request.IsHttps); await httpContext.Response.WriteAsync(httpContext.Request.Protocol); httpContext.Response.AppendTrailer("custom", "value"); } catch (Exception ex) { await httpContext.Response.WriteAsync(ex.ToString()); } }); var handler = new HttpClientHandler(); // Needed on CI, the IIS Express cert we use isn't trusted there. handler.ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator; using var client = new HttpClient(handler); client.DefaultRequestVersion = HttpVersion.Version30; client.DefaultVersionPolicy = HttpVersionPolicy.RequestVersionExact; var response = await client.GetAsync(address); response.EnsureSuccessStatusCode(); var result = await response.Content.ReadAsStringAsync(); Assert.Equal("HTTP/3", result); Assert.Equal("value", response.TrailingHeaders.GetValues("custom").SingleOrDefault()); } [ConditionalFact] public async Task Http3_ResetBeforeHeaders() { using var server = Utilities.CreateDynamicHttpsServer(out var address, async httpContext => { try { Assert.True(httpContext.Request.IsHttps); httpContext.Features.Get<IHttpResetFeature>().Reset(0x010b); // H3_REQUEST_REJECTED } catch (Exception ex) { await httpContext.Response.WriteAsync(ex.ToString()); } }); var handler = new HttpClientHandler(); // Needed on CI, the IIS Express cert we use isn't trusted there. handler.ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator; using var client = new HttpClient(handler); client.DefaultRequestVersion = HttpVersion.Version30; client.DefaultVersionPolicy = HttpVersionPolicy.RequestVersionExact; var ex = await Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync(address)); var qex = Assert.IsType<QuicStreamAbortedException>(ex.InnerException); Assert.Equal(0x010b, qex.ErrorCode); } [ConditionalFact] public async Task Http3_ResetAfterHeaders() { var headersReceived = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); using var server = Utilities.CreateDynamicHttpsServer(out var address, async httpContext => { try { Assert.True(httpContext.Request.IsHttps); await httpContext.Response.Body.FlushAsync(); await headersReceived.Task.DefaultTimeout(); httpContext.Features.Get<IHttpResetFeature>().Reset(0x010c); // H3_REQUEST_CANCELLED } catch (Exception ex) { await httpContext.Response.WriteAsync(ex.ToString()); } }); var handler = new HttpClientHandler(); // Needed on CI, the IIS Express cert we use isn't trusted there. handler.ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator; using var client = new HttpClient(handler); client.DefaultRequestVersion = HttpVersion.Version30; client.DefaultVersionPolicy = HttpVersionPolicy.RequestVersionExact; var response = await client.GetAsync(address, HttpCompletionOption.ResponseHeadersRead); headersReceived.SetResult(); response.EnsureSuccessStatusCode(); var ex = await Assert.ThrowsAsync<HttpRequestException>(() => response.Content.ReadAsStringAsync()); var qex = Assert.IsType<QuicStreamAbortedException>(ex.InnerException?.InnerException?.InnerException); Assert.Equal(0x010c, qex.ErrorCode); } [ConditionalFact] public async Task Http3_AppExceptionAfterHeaders_InternalError() { var headersReceived = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); using var server = Utilities.CreateDynamicHttpsServer(out var address, async httpContext => { await httpContext.Response.Body.FlushAsync(); await headersReceived.Task.DefaultTimeout(); throw new Exception("App Exception"); }); var handler = new HttpClientHandler(); // Needed on CI, the IIS Express cert we use isn't trusted there. handler.ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator; using var client = new HttpClient(handler); client.DefaultRequestVersion = HttpVersion.Version30; client.DefaultVersionPolicy = HttpVersionPolicy.RequestVersionExact; var response = await client.GetAsync(address, HttpCompletionOption.ResponseHeadersRead); headersReceived.SetResult(); response.EnsureSuccessStatusCode(); var ex = await Assert.ThrowsAsync<HttpRequestException>(() => response.Content.ReadAsStringAsync()); var qex = Assert.IsType<QuicStreamAbortedException>(ex.InnerException?.InnerException?.InnerException); Assert.Equal(0x0102, qex.ErrorCode); // H3_INTERNAL_ERROR } [ConditionalFact] public async Task Http3_Abort_Cancel() { using var server = Utilities.CreateDynamicHttpsServer(out var address, httpContext => { httpContext.Abort(); return Task.CompletedTask; }); var handler = new HttpClientHandler(); // Needed on CI, the IIS Express cert we use isn't trusted there. handler.ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator; using var client = new HttpClient(handler); client.DefaultRequestVersion = HttpVersion.Version30; client.DefaultVersionPolicy = HttpVersionPolicy.RequestVersionExact; var ex = await Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync(address)); var qex = Assert.IsType<QuicStreamAbortedException>(ex.InnerException); Assert.Equal(0x010c, qex.ErrorCode); // H3_REQUEST_CANCELLED } } }
using System; using System.IO; using System.Text; using Weborb.Message; using Weborb.Types; using Weborb.Exceptions; using Weborb.Util.IO; using Weborb.Util.Logging; using Weborb.Reader; using Weborb.Protocols; using Weborb.Writer; using Weborb.Writer.Amf; namespace Weborb.Protocols.Amf { public class RequestParser : IMessageFactory { private static ITypeReader[] V1READERS; private static ITypeReader[] V3READERS; private static ITypeReader[][] READERS; #if (FULL_BUILD) ASCIIEncoding encoding = new ASCIIEncoding(); #endif static RequestParser() { //TODO: review caching this or making it static V1READERS = new ITypeReader[Datatypes.TOTAL_V1TYPES]; V1READERS[Datatypes.NUMBER_DATATYPE_V1] = new NumberReader(); V1READERS[Datatypes.BOOLEAN_DATATYPE_V1] = new BooleanReader(); V1READERS[Datatypes.UTFSTRING_DATATYPE_V1] = new UTFStringReader(); V1READERS[Datatypes.OBJECT_DATATYPE_V1] = new AnonymousObjectReader(); V1READERS[Datatypes.NULL_DATATYPE_V1] = new NullReader(); V1READERS[Datatypes.POINTER_DATATYPE_V1] = new PointerReader(); V1READERS[Datatypes.OBJECTARRAY_DATATYPE_V1] = new BoundPropertyBagReader(); V1READERS[Datatypes.ENDOFOBJECT_DATATYPE_V1] = new NotAReader(); V1READERS[Datatypes.UNKNOWN_DATATYPE_V1] = new UndefinedTypeReader(); V1READERS[Datatypes.ARRAY_DATATYPE_V1] = new ArrayReader(); V1READERS[Datatypes.DATE_DATATYPE_V1] = new DateReader(); V1READERS[Datatypes.LONGUTFSTRING_DATATYPE_V1] = new LongUTFStringReader(); #if (FULL_BUILD) V1READERS[Datatypes.REMOTEREFERENCE_DATATYPE_V1] = new RemoteReferenceReader(); V1READERS[Datatypes.PARSEDXML_DATATYPE_V1] = new XmlReader(); #endif V1READERS[Datatypes.RECORDSET_DATATYPE_V1] = null; V1READERS[Datatypes.NAMEDOBJECT_DATATYPE_V1] = new NamedObjectReader(); V1READERS[Datatypes.V3_DATATYPE] = new V3Reader(); V3READERS = new ITypeReader[Datatypes.TOTAL_V3TYPES]; V3READERS[Datatypes.UNKNOWN_DATATYPE_V3] = new UndefinedTypeReader(); V3READERS[Datatypes.NULL_DATATYPE_V3] = new NullReader(); V3READERS[Datatypes.BOOLEAN_DATATYPE_FALSEV3] = new BooleanReader(false); V3READERS[Datatypes.BOOLEAN_DATATYPE_TRUEV3] = new BooleanReader(true); V3READERS[Datatypes.INTEGER_DATATYPE_V3] = new IntegerReader(); V3READERS[Datatypes.DOUBLE_DATATYPE_V3] = new NumberReader(); V3READERS[Datatypes.UTFSTRING_DATATYPE_V3] = new V3StringReader(); V3READERS[Datatypes.DATE_DATATYPE_V3] = new V3DateReader(); V3READERS[Datatypes.ARRAY_DATATYPE_V3] = new V3ArrayReader(); V3READERS[Datatypes.OBJECT_DATATYPE_V3] = new V3ObjectReader(); #if (FULL_BUILD) V3READERS[Datatypes.LONGXML_DATATYPE_V3] = new V3XmlReader(); V3READERS[Datatypes.XML_DATATYPE_V3] = new V3XmlReader(); #endif V3READERS[Datatypes.BYTEARRAY_DATATYPE_V3] = new V3ByteArrayReader(); V3READERS[Datatypes.INT_VECTOR_V3] = new V3VectorReader<int>(); V3READERS[Datatypes.UINT_VECTOR_V3] = new V3VectorReader<uint>(); V3READERS[Datatypes.DOUBLE_VECTOR_V3] = new V3VectorReader<double>(); V3READERS[Datatypes.OBJECT_VECTOR_V3] = new V3VectorReader<object>(); V3READERS[Datatypes.V3_DATATYPE] = new V3Reader(); READERS = new ITypeReader[4][]; READERS[0] = V1READERS; READERS[1] = null; READERS[2] = null; READERS[3] = V3READERS; } public static void setAMF3Reader(int dataType, ITypeReader reader) { V3READERS[dataType] = reader; } public static ITypeReader getAMF3Reader(int dataType) { return V3READERS[dataType]; } public string GetProtocolName(Request input) { return "amf" + (int)input.getVersion(); } public string[] GetProtocolNames() { return new string[] { "amf0", "amf3" }; } public Request readMessage(Stream input) { FlashorbBinaryReader reader = new FlashorbBinaryReader(input); try { if (Log.isLogging(LoggingConstants.DEBUG)) Log.log(LoggingConstants.DEBUG, "MessageReader:: parsing stream"); int version = reader.ReadUnsignedShort(); int totalHeaders = reader.ReadUnsignedShort(); if (Log.isLogging(LoggingConstants.DEBUG)) Log.log(LoggingConstants.DEBUG, "MessageReader:: parsing message - version: " + version + " totalHeaders: " + totalHeaders); Header[] headers = new Header[totalHeaders]; for (int i = 0; i < totalHeaders; i++) headers[i] = readHeader(reader); int totalBodyParts = reader.ReadUnsignedShort(); if (Log.isLogging(LoggingConstants.DEBUG)) Log.log(LoggingConstants.DEBUG, "MessageReader:: Total body parts: " + totalBodyParts); Body[] bodies = new Body[totalBodyParts]; for (int i = 0; i < totalBodyParts; i++) bodies[i] = readBodyPart(reader); if (Log.isLogging(LoggingConstants.DEBUG)) Log.log(LoggingConstants.DEBUG, "MessageReader:: returning AMFMessage"); Request request = new Request(version, headers, bodies); request.SetFormatter(version == 3 ? (IProtocolFormatter)new AmfV3Formatter() : (IProtocolFormatter)new AmfFormatter()); return request; } catch (Exception exception) { if (Log.isLogging(LoggingConstants.EXCEPTION)) Log.log(LoggingConstants.EXCEPTION, "Exception: " + exception.Message + " StackTrace: " + exception.StackTrace); return null; } } private Header readHeader(FlashorbBinaryReader reader) { int nameLength = reader.ReadUnsignedShort(); byte[] bytes = reader.ReadBytes(nameLength); #if (FULL_BUILD) string headerName = encoding.GetString(bytes); #else string headerName = BitConverter.ToString( bytes ); #endif bool mustUnderstand = reader.ReadBoolean(); //int length = reader.ReadInt32(); int length = reader.ReadInteger(); if (Log.isLogging(LoggingConstants.DEBUG)) Log.log(LoggingConstants.DEBUG, "MessageReader::readHeader: name - " + headerName + " mustUnderstand - " + mustUnderstand + " length - " + length); return new Header(headerName, mustUnderstand, length, readData(reader)); } private Body readBodyPart(FlashorbBinaryReader reader) { int serviceURILength = reader.ReadUnsignedShort(); #if (FULL_BUILD) string serviceURI = encoding.GetString(reader.ReadBytes(serviceURILength)); #else string serviceURI = BitConverter.ToString( reader.ReadBytes( serviceURILength ) ); #endif int responseURILength = reader.ReadUnsignedShort(); #if (FULL_BUILD) string responseURI = encoding.GetString(reader.ReadBytes(responseURILength)); #else string responseURI = BitConverter.ToString( reader.ReadBytes( responseURILength ) ); #endif int length = reader.ReadInteger(); if (Log.isLogging(LoggingConstants.DEBUG)) Log.log(LoggingConstants.DEBUG, "MessageReader::readBodyPart: serviceURI - " + serviceURI + " responseURI - " + responseURI + " length: " + length); return new Body(serviceURI, responseURI, length, readData(reader)); } public static IAdaptingType readData(FlashorbBinaryReader reader) { return readData(reader, new ParseContext(0), V1READERS); } public static IAdaptingType readData(FlashorbBinaryReader reader, int version) { return readData(reader, new ParseContext(version), READERS[version]); } public static IAdaptingType readData(FlashorbBinaryReader reader, ParseContext parseContext) { return readData(reader, parseContext, READERS[parseContext.getVersion()]); } public static IAdaptingType readData(FlashorbBinaryReader reader, ParseContext parseContext, ITypeReader[] readers) { int type = reader.ReadByte(); return readers[type].read(reader, parseContext); } public static IAdaptingType readData(int dataType, FlashorbBinaryReader reader, ParseContext parseContext) { return readData(dataType, reader, parseContext, READERS[parseContext.getVersion()]); } public static IAdaptingType readData(int dataType, FlashorbBinaryReader reader, ParseContext parseContext, ITypeReader[] readers) { return readers[dataType].read(reader, parseContext); } #region IMessageFactory Members public bool CanParse(String contentType) { return contentType.ToLower().Equals("application/x-amf"); } public Request Parse(Stream requestStream) { return readMessage(requestStream); } #endregion } }
/* DBFHeader Class for reading the metadata assuming that the given InputStream carries DBF data. This file is part of DotNetDBF packege. original author (javadbf): anil@linuxense.com 2004/03/31 License: LGPL (http://www.gnu.org/copyleft/lesser.html) ported to C# (DotNetDBF): Jay Tuley <jay+dotnetdbf@tuley.name> 6/28/2007 */ using System; using System.Collections.Generic; using System.IO; namespace DotNetDBF { static public class DBFSigniture { public const byte NotSet = 0, WithMemo = 0x80, DBase3 = 0x03, DBase3WithMemo = DBase3 | WithMemo; } [Flags] public enum MemoFlags : byte { } public class DBFHeader { public const byte HeaderRecordTerminator = 0x0D; private byte _day; /* 3 */ private byte _encryptionFlag; /* 15 */ private DBFField[] _fieldArray; /* each 32 bytes */ private int _freeRecordThread; /* 16-19 */ private short _headerLength; /* 8-9 */ private byte _incompleteTransaction; /* 14 */ private byte _languageDriver; /* 29 */ private byte _mdxFlag; /* 28 */ private byte _month; /* 2 */ private int _numberOfRecords; /* 4-7 */ private short _recordLength; /* 10-11 */ private short _reserv1; /* 12-13 */ private int _reserv2; /* 20-23 */ private int _reserv3; /* 24-27 */ private short reserv4; /* 30-31 */ private byte _signature; /* 0 */ private byte _year; /* 1 */ public DBFHeader() { _signature = DBFSigniture.DBase3; } internal byte Signiture { get { return _signature; }set { _signature = value; } } internal short Size { get { return (short) (sizeof (byte) + sizeof (byte) + sizeof (byte) + sizeof (byte) + sizeof (int) + sizeof (short) + sizeof (short) + sizeof (short) + sizeof (byte) + sizeof (byte) + sizeof (int) + sizeof (int) + sizeof (int) + sizeof (byte) + sizeof (byte) + sizeof (short) + (DBFField.SIZE * _fieldArray.Length) + sizeof (byte)); } } internal short RecordSize { get { int tRecordLength = 0; for (int i = 0; i < _fieldArray.Length; i++) { tRecordLength += _fieldArray[i].FieldLength; } return (short)(tRecordLength + 1); } } internal short HeaderLength { set { _headerLength = value; } get { return _headerLength; } } internal DBFField[] FieldArray { set { _fieldArray = value; } get { return _fieldArray; } } internal byte Year { set { _year = value; } get { return _year; } } internal byte Month { set { _month = value; } get { return _month; } } internal byte Day { set { _day = value; } get { return _day; } } internal int NumberOfRecords { set { _numberOfRecords = value; } get { return _numberOfRecords; } } internal short RecordLength { set { _recordLength = value; } get { return _recordLength; } } internal byte LanguageDriver { get { return _languageDriver; } set { _languageDriver = value; } } internal void Read(BinaryReader dataInput) { _signature = dataInput.ReadByte(); /* 0 */ _year = dataInput.ReadByte(); /* 1 */ _month = dataInput.ReadByte(); /* 2 */ _day = dataInput.ReadByte(); /* 3 */ _numberOfRecords = dataInput.ReadInt32(); /* 4-7 */ _headerLength = dataInput.ReadInt16(); /* 8-9 */ _recordLength = dataInput.ReadInt16(); /* 10-11 */ _reserv1 = dataInput.ReadInt16(); /* 12-13 */ _incompleteTransaction = dataInput.ReadByte(); /* 14 */ _encryptionFlag = dataInput.ReadByte(); /* 15 */ _freeRecordThread = dataInput.ReadInt32(); /* 16-19 */ _reserv2 = dataInput.ReadInt32(); /* 20-23 */ _reserv3 = dataInput.ReadInt32(); /* 24-27 */ _mdxFlag = dataInput.ReadByte(); /* 28 */ _languageDriver = dataInput.ReadByte(); /* 29 */ reserv4 = dataInput.ReadInt16(); /* 30-31 */ List<DBFField> v_fields = new List<DBFField>(); DBFField field = DBFField.CreateField(dataInput); /* 32 each */ while (field != null) { v_fields.Add(field); field = DBFField.CreateField(dataInput); } _fieldArray = v_fields.ToArray(); //System.out.println( "Number of fields: " + _fieldArray.length); } internal void Write(BinaryWriter dataOutput) { dataOutput.Write(_signature); /* 0 */ DateTime tNow = DateTime.Now; _year = (byte) (tNow.Year - 1900); _month = (byte) (tNow.Month); _day = (byte) (tNow.Day); dataOutput.Write(_year); /* 1 */ dataOutput.Write(_month); /* 2 */ dataOutput.Write(_day); /* 3 */ //System.out.println( "Number of records in O/S: " + numberOfRecords); dataOutput.Write(_numberOfRecords); /* 4-7 */ _headerLength = Size; dataOutput.Write(_headerLength); /* 8-9 */ _recordLength = RecordSize; dataOutput.Write(_recordLength); /* 10-11 */ dataOutput.Write(_reserv1); /* 12-13 */ dataOutput.Write(_incompleteTransaction); /* 14 */ dataOutput.Write(_encryptionFlag); /* 15 */ dataOutput.Write(_freeRecordThread); /* 16-19 */ dataOutput.Write(_reserv2); /* 20-23 */ dataOutput.Write(_reserv3); /* 24-27 */ dataOutput.Write(_mdxFlag); /* 28 */ dataOutput.Write(_languageDriver); /* 29 */ dataOutput.Write(reserv4); /* 30-31 */ for (int i = 0; i < _fieldArray.Length; i++) { //System.out.println( "Length: " + _fieldArray[i].getFieldLength()); _fieldArray[i].Write(dataOutput); } dataOutput.Write(HeaderRecordTerminator); /* n+1 */ } } }
// 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.Text; namespace Microsoft.CodeAnalysis.Text { /// <summary> /// An <see cref="SourceText"/> that represents a subrange of another <see cref="SourceText"/>. /// </summary> public sealed class SubText : SourceText { public SubText(SourceText text, TextSpan span) : base(checksumAlgorithm: text.ChecksumAlgorithm) { if (text == null) { throw new ArgumentNullException(nameof(text)); } if (span.Start < 0 || span.Start >= text.Length || span.End < 0 || span.End > text.Length) { throw new ArgumentOutOfRangeException(nameof(span)); } UnderlyingText = text; UnderlyingSpan = span; } public override Encoding Encoding => UnderlyingText.Encoding; public SourceText UnderlyingText { get; } public TextSpan UnderlyingSpan { get; } public override int Length => UnderlyingSpan.Length; public override char this[int position] { get { if (position < 0 || position > this.Length) { throw new ArgumentOutOfRangeException(nameof(position)); } return UnderlyingText[UnderlyingSpan.Start + position]; } } public override string ToString(TextSpan span) { CheckSubSpan(span); return UnderlyingText.ToString(GetCompositeSpan(span.Start, span.Length)); } public override SourceText GetSubText(TextSpan span) { return new SubText(UnderlyingText, GetCompositeSpan(span.Start, span.Length)); } public SubText Substring(TextSpan span) { CheckSubSpan(span); return new SubText(UnderlyingText, GetCompositeSpan(span.Start, span.Length)); } public SubText Substring(int start) { return Substring(new TextSpan(start, Length - start)); } public SubText Substring(int start, int length) { return Substring(new TextSpan(start, length)); } public override void CopyTo(int sourceIndex, char[] destination, int destinationIndex, int count) { var span = GetCompositeSpan(sourceIndex, count); UnderlyingText.CopyTo(span.Start, destination, destinationIndex, span.Length); } private TextSpan GetCompositeSpan(int start, int length) { int compositeStart = Math.Min(UnderlyingText.Length, UnderlyingSpan.Start + start); int compositeEnd = Math.Min(UnderlyingText.Length, compositeStart + length); return new TextSpan(compositeStart, compositeEnd - compositeStart); } internal void CheckSubSpan(TextSpan span) { if (span.Start < 0 || span.Start > Length || span.End > Length) { throw new ArgumentOutOfRangeException(nameof(span)); } } /// <inheritdoc /> public static bool operator ==(SubText left, string right) { return left?.Equals(right) ?? right == null; } /// <inheritdoc /> public static bool operator !=(SubText left, string right) { return !(left?.Equals(right) ?? right == null); } public override bool Equals(object obj) { return base.Equals(obj); } public override int GetHashCode() { return base.GetHashCode(); } /// <inheritdoc /> public bool Equals(string other) { if (other == null) { return false; } var length = Length; if (length != other.Length) { return false; } for (int i = 0; i < length; i++) { if (this[i] != other[i]) { return false; } } return true; } /// <summary> /// Returns the index of the first occurrence of a string within the segment, or -1 if the string doesn't occur in the segment. /// </summary> public int IndexOf(string value, int start = 0) { var length = Length; if (value.Length == 0) { return 0; } for (int index = start; index < length; index++) { if (value.Length > (length - index)) { return -1; } bool found = true; for (int subIndex = 0; subIndex < value.Length; subIndex++) { if (this[index + subIndex] != value[subIndex]) { found = false; break; } } if (found) { return index; } } return -1; } } public static class SubTextExtensions { public static SubText TrimEnd(this SubText text) { return Trim(text, trimStart: false, trimEnd: true); } public static SubText TrimStart(this SubText text) { return Trim(text, trimStart: true, trimEnd: false); } public static SubText Trim(this SubText text, bool trimStart = true, bool trimEnd = true) { if (text.Length == 0) { return text; } int start = 0; int length = text.Length; int end = text.Length - 1; if (trimStart) { for (start = 0; start < length; start++) { if (!char.IsWhiteSpace(text[start])) { break; } } } if (trimEnd) { for (end = length - 1; end >= start; end--) { if (!char.IsWhiteSpace(text[end])) { break; } } } return text.Substring(TextSpan.FromBounds(start, end + 1)); } } }
using System; using UnityEngine; namespace Cinemachine { /// <summary> /// Describes a blend between 2 Cinemachine Virtual Cameras, and holds the /// current state of the blend. /// </summary> public class CinemachineBlend { /// <summary>First camera in the blend</summary> public ICinemachineCamera CamA { get; set; } /// <summary>Second camera in the blend</summary> public ICinemachineCamera CamB { get; set; } /// <summary>The curve that describes the way the blend transitions over time /// from the first camera to the second. X-axis is time in seconds over which /// the blend takes place and Y axis is blend weight (0..1)</summary> public AnimationCurve BlendCurve { get; set; } /// <summary>The current time relative to the start of the blend</summary> public float TimeInBlend { get; set; } /// <summary>The current weight of the blend. This is an evaluation of the /// BlendCurve at the current time relative to the start of the blend. /// 0 means camA, 1 means camB.</summary> public float BlendWeight { get { return BlendCurve != null ? BlendCurve.Evaluate(TimeInBlend) : 0; } } /// <summary>Validity test for the blend. True if both cameras are defined.</summary> public bool IsValid { get { return (CamA != null || CamB != null); } } /// <summary>Duration in seconds of the blend. /// This is given read from the BlendCurve.</summary> public float Duration { get; set; } /// <summary>True if the time relative to the start of the blend is greater /// than or equal to the blend duration</summary> public bool IsComplete { get { return TimeInBlend >= Duration; } } /// <summary>Text description of the blend, for debugging</summary> public string Description { get { string fromName = (CamA != null) ? CamA.Name : "(none)"; string toName = (CamB != null) ? CamB.Name : "(none)"; int percent = (int)(BlendWeight * 100f); return string.Format("{0} {1}% from {2}", toName, percent, fromName); } } /// <summary>Does the blend use a specific Cinemachine Virtual Camera?</summary> /// <param name="cam">The camera to test</param> /// <returns>True if the camera is involved in the blend</returns> public bool Uses(ICinemachineCamera cam) { if (cam == CamA || cam == CamB) return true; BlendSourceVirtualCamera b = CamA as BlendSourceVirtualCamera; if (b != null && b.Blend.Uses(cam)) return true; b = CamB as BlendSourceVirtualCamera; if (b != null && b.Blend.Uses(cam)) return true; return false; } /// <summary>Construct a blend</summary> /// <param name="a">First camera</param> /// <param name="b">Second camera</param> /// <param name="curve">Blend curve</param> /// <param name="t">Current time in blend, relative to the start of the blend</param> public CinemachineBlend( ICinemachineCamera a, ICinemachineCamera b, AnimationCurve curve, float duration, float t) { if (a == null || b == null) throw new ArgumentException("Blend cameras cannot be null"); CamA = a; CamB = b; BlendCurve = curve; TimeInBlend = t; Duration = duration; } /// <summary>Make sure the source cameras get updated.</summary> /// <param name="worldUp">Default world up. Individual vcams may modify this</param> /// <param name="deltaTime">Time increment used for calculating time-based behaviours (e.g. damping)</param> public void UpdateCameraState(Vector3 worldUp, float deltaTime) { // Make sure both cameras have been updated (they are not necessarily // enabled, and only enabled top-level cameras get updated automatically // every frame) CinemachineCore.Instance.UpdateVirtualCamera(CamA, worldUp, deltaTime); CinemachineCore.Instance.UpdateVirtualCamera(CamB, worldUp, deltaTime); } /// <summary>Compute the blended CameraState for the current time in the blend.</summary> public CameraState State { get { return CameraState.Lerp(CamA.State, CamB.State, BlendWeight); } } } /// <summary>Definition of a Camera blend. This struct holds the information /// necessary to generate a suitable AnimationCurve for a Cinemachine Blend.</summary> [Serializable] [DocumentationSorting(10.2f, DocumentationSortingAttribute.Level.UserRef)] public struct CinemachineBlendDefinition { /// <summary>Supported predefined shapes for the blend curve.</summary> [DocumentationSorting(10.21f, DocumentationSortingAttribute.Level.UserRef)] public enum Style { /// <summary>Zero-length blend</summary> Cut, /// <summary>S-shaped curve, giving a gentle and smooth transition</summary> EaseInOut, /// <summary>Linear out of the outgoing shot, and easy into the incoming</summary> EaseIn, /// <summary>Easy out of the outgoing shot, and linear into the incoming</summary> EaseOut, /// <summary>Easy out of the outgoing, and hard into the incoming</summary> HardIn, /// <summary>Hard out of the outgoing, and easy into the incoming</summary> HardOut, /// <summary>Linear blend. Mechanical-looking.</summary> Linear }; /// <summary>The shape of the blend curve.</summary> [Tooltip("Shape of the blend curve")] public Style m_Style; /// <summary>The duration (in seconds) of the blend</summary> [Tooltip("Duration (in seconds) of the blend")] public float m_Time; /// <summary>Constructor</summary> /// <param name="style">The shape of the blend curve.</param> /// <param name="time">The duration (in seconds) of the blend</param> public CinemachineBlendDefinition(Style style, float time) { m_Style = style; m_Time = time; } /// <summary> /// An AnimationCurve specifying the interpolation duration and value /// for this camera blend. The time of the last key frame is assumed to the be the /// duration of the blend. Y-axis values must be in range [0,1] (internally clamped /// within Blender) and time must be in range of [0, +infinity) /// </summary> public AnimationCurve BlendCurve { get { float time = Mathf.Max(0, m_Time); switch (m_Style) { default: case Style.Cut: return new AnimationCurve(); case Style.EaseInOut: return AnimationCurve.EaseInOut(0f, 0f, time, 1f); case Style.EaseIn: { AnimationCurve curve = AnimationCurve.Linear(0f, 0f, time, 1f); Keyframe[] keys = curve.keys; keys[1].inTangent = 0; curve.keys = keys; return curve; } case Style.EaseOut: { AnimationCurve curve = AnimationCurve.Linear(0f, 0f, time, 1f); Keyframe[] keys = curve.keys; keys[0].outTangent = 0; curve.keys = keys; return curve; } case Style.HardIn: { AnimationCurve curve = AnimationCurve.Linear(0f, 0f, time, 1f); Keyframe[] keys = curve.keys; keys[0].outTangent = 0; keys[1].inTangent = 1.5708f; // pi/2 = up curve.keys = keys; return curve; } case Style.HardOut: { AnimationCurve curve = AnimationCurve.Linear(0f, 0f, time, 1f); Keyframe[] keys = curve.keys; keys[0].outTangent = 1.5708f; // pi/2 = up keys[1].inTangent = 0; curve.keys = keys; return curve; } case Style.Linear: return AnimationCurve.Linear(0f, 0f, time, 1f); } } } } }
using YAF.Lucene.Net.Util; using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using JCG = J2N.Collections.Generic; namespace YAF.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. */ using AtomicReaderContext = YAF.Lucene.Net.Index.AtomicReaderContext; using IBits = YAF.Lucene.Net.Util.IBits; using IndexReader = YAF.Lucene.Net.Index.IndexReader; using Term = YAF.Lucene.Net.Index.Term; /// <summary> /// A query that generates the union of documents produced by its subqueries, and that scores each document with the maximum /// score for that document as produced by any subquery, plus a tie breaking increment for any additional matching subqueries. /// This is useful when searching for a word in multiple fields with different boost factors (so that the fields cannot be /// combined equivalently into a single search field). We want the primary score to be the one associated with the highest boost, /// not the sum of the field scores (as <see cref="BooleanQuery"/> would give). /// <para/> /// If the query is "albino elephant" this ensures that "albino" matching one field and "elephant" matching /// another gets a higher score than "albino" matching both fields. /// <para/> /// To get this result, use both <see cref="BooleanQuery"/> and <see cref="DisjunctionMaxQuery"/>: for each term a <see cref="DisjunctionMaxQuery"/> searches for it in /// each field, while the set of these <see cref="DisjunctionMaxQuery"/>'s is combined into a <see cref="BooleanQuery"/>. /// The tie breaker capability allows results that include the same term in multiple fields to be judged better than results that /// include this term in only the best of those multiple fields, without confusing this with the better case of two different terms /// in the multiple fields. /// <para/> /// Collection initializer note: To create and populate a <see cref="DisjunctionMaxQuery"/> /// in a single statement, you can use the following example as a guide: /// /// <code> /// var disjunctionMaxQuery = new DisjunctionMaxQuery(0.1f) { /// new TermQuery(new Term("field1", "albino")), /// new TermQuery(new Term("field2", "elephant")) /// }; /// </code> /// </summary> public class DisjunctionMaxQuery : Query, IEnumerable<Query> { /// <summary> /// The subqueries /// </summary> private IList<Query> disjuncts = new JCG.List<Query>(); /// <summary> /// Multiple of the non-max disjunct scores added into our final score. Non-zero values support tie-breaking. /// </summary> private float tieBreakerMultiplier = 0.0f; /// <summary> /// Creates a new empty <see cref="DisjunctionMaxQuery"/>. Use <see cref="Add(Query)"/> to add the subqueries. </summary> /// <param name="tieBreakerMultiplier"> The score of each non-maximum disjunct for a document is multiplied by this weight /// and added into the final score. If non-zero, the value should be small, on the order of 0.1, which says that /// 10 occurrences of word in a lower-scored field that is also in a higher scored field is just as good as a unique /// word in the lower scored field (i.e., one that is not in any higher scored field). </param> public DisjunctionMaxQuery(float tieBreakerMultiplier) { this.tieBreakerMultiplier = tieBreakerMultiplier; } /// <summary> /// Creates a new <see cref="DisjunctionMaxQuery"/> </summary> /// <param name="disjuncts"> A <see cref="T:ICollection{Query}"/> of all the disjuncts to add </param> /// <param name="tieBreakerMultiplier"> The weight to give to each matching non-maximum disjunct </param> public DisjunctionMaxQuery(ICollection<Query> disjuncts, float tieBreakerMultiplier) { this.tieBreakerMultiplier = tieBreakerMultiplier; Add(disjuncts); } /// <summary> /// Add a subquery to this disjunction </summary> /// <param name="query"> The disjunct added </param> public virtual void Add(Query query) { disjuncts.Add(query); } /// <summary> /// Add a collection of disjuncts to this disjunction /// via <see cref="T:IEnumerable{Query}"/> </summary> /// <param name="disjuncts"> A collection of queries to add as disjuncts. </param> public virtual void Add(ICollection<Query> disjuncts) { this.disjuncts.AddRange(disjuncts); } /// <returns> An <see cref="T:IEnumerator{Query}"/> over the disjuncts </returns> public virtual IEnumerator<Query> GetEnumerator() { return disjuncts.GetEnumerator(); } // LUCENENET specific IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } /// <returns> The disjuncts. </returns> public virtual IList<Query> Disjuncts => disjuncts; /// <returns> Tie breaker value for multiple matches. </returns> public virtual float TieBreakerMultiplier => tieBreakerMultiplier; /// <summary> /// Expert: the Weight for DisjunctionMaxQuery, used to /// normalize, score and explain these queries. /// /// <para>NOTE: this API and implementation is subject to /// change suddenly in the next release.</para> /// </summary> protected class DisjunctionMaxWeight : Weight { private readonly DisjunctionMaxQuery outerInstance; /// <summary> /// The <see cref="Weight"/>s for our subqueries, in 1-1 correspondence with disjuncts </summary> protected List<Weight> m_weights = new List<Weight>(); // The Weight's for our subqueries, in 1-1 correspondence with disjuncts /// <summary> /// Construct the <see cref="Weight"/> for this <see cref="Search.Query"/> searched by <paramref name="searcher"/>. Recursively construct subquery weights. </summary> public DisjunctionMaxWeight(DisjunctionMaxQuery outerInstance, IndexSearcher searcher) { this.outerInstance = outerInstance; foreach (Query disjunctQuery in outerInstance.disjuncts) { m_weights.Add(disjunctQuery.CreateWeight(searcher)); } } /// <summary> /// Return our associated <see cref="DisjunctionMaxQuery"/> </summary> public override Query Query => outerInstance; /// <summary> /// Compute the sub of squared weights of us applied to our subqueries. Used for normalization. </summary> public override float GetValueForNormalization() { float max = 0.0f, sum = 0.0f; foreach (Weight currentWeight in m_weights) { float sub = currentWeight.GetValueForNormalization(); sum += sub; max = Math.Max(max, sub); } float boost = outerInstance.Boost; return (((sum - max) * outerInstance.tieBreakerMultiplier * outerInstance.tieBreakerMultiplier) + max) * boost * boost; } /// <summary> /// Apply the computed normalization factor to our subqueries </summary> public override void Normalize(float norm, float topLevelBoost) { topLevelBoost *= outerInstance.Boost; // Incorporate our boost foreach (Weight wt in m_weights) { wt.Normalize(norm, topLevelBoost); } } /// <summary> /// Create the scorer used to score our associated <see cref="DisjunctionMaxQuery"/> </summary> public override Scorer GetScorer(AtomicReaderContext context, IBits acceptDocs) { IList<Scorer> scorers = new List<Scorer>(); foreach (Weight w in m_weights) { // we will advance() subscorers Scorer subScorer = w.GetScorer(context, acceptDocs); if (subScorer != null) { scorers.Add(subScorer); } } if (scorers.Count == 0) { // no sub-scorers had any documents return null; } DisjunctionMaxScorer result = new DisjunctionMaxScorer(this, outerInstance.tieBreakerMultiplier, scorers.ToArray()); return result; } /// <summary> /// Explain the score we computed for doc </summary> public override Explanation Explain(AtomicReaderContext context, int doc) { if (outerInstance.disjuncts.Count == 1) { return m_weights[0].Explain(context, doc); } ComplexExplanation result = new ComplexExplanation(); float max = 0.0f, sum = 0.0f; result.Description = outerInstance.tieBreakerMultiplier == 0.0f ? "max of:" : "max plus " + outerInstance.tieBreakerMultiplier + " times others of:"; foreach (Weight wt in m_weights) { Explanation e = wt.Explain(context, doc); if (e.IsMatch) { result.Match = true; result.AddDetail(e); sum += e.Value; max = Math.Max(max, e.Value); } } result.Value = max + (sum - max) * outerInstance.tieBreakerMultiplier; return result; } } // end of DisjunctionMaxWeight inner class /// <summary> /// Create the <see cref="Weight"/> used to score us </summary> public override Weight CreateWeight(IndexSearcher searcher) { return new DisjunctionMaxWeight(this, searcher); } /// <summary> /// Optimize our representation and our subqueries representations </summary> /// <param name="reader"> The <see cref="IndexReader"/> we query </param> /// <returns> An optimized copy of us (which may not be a copy if there is nothing to optimize) </returns> public override Query Rewrite(IndexReader reader) { int numDisjunctions = disjuncts.Count; if (numDisjunctions == 1) { Query singleton = disjuncts[0]; Query result = singleton.Rewrite(reader); if (Boost != 1.0f) { if (result == singleton) { result = (Query)result.Clone(); } result.Boost = Boost * result.Boost; } return result; } DisjunctionMaxQuery clone = null; for (int i = 0; i < numDisjunctions; i++) { Query clause = disjuncts[i]; Query rewrite = clause.Rewrite(reader); if (rewrite != clause) { if (clone == null) { clone = (DisjunctionMaxQuery)this.Clone(); } clone.disjuncts[i] = rewrite; } } if (clone != null) { return clone; } else { return this; } } /// <summary> /// Create a shallow copy of us -- used in rewriting if necessary </summary> /// <returns> A copy of us (but reuse, don't copy, our subqueries) </returns> public override object Clone() { DisjunctionMaxQuery clone = (DisjunctionMaxQuery)base.Clone(); clone.disjuncts = new JCG.List<Query>(this.disjuncts); return clone; } /// <summary> /// Expert: adds all terms occurring in this query to the terms set. Only /// works if this query is in its rewritten (<see cref="Rewrite(IndexReader)"/>) form. /// </summary> /// <exception cref="InvalidOperationException"> If this query is not yet rewritten </exception> public override void ExtractTerms(ISet<Term> terms) { foreach (Query query in disjuncts) { query.ExtractTerms(terms); } } /// <summary> /// Prettyprint us. </summary> /// <param name="field"> The field to which we are applied </param> /// <returns> A string that shows what we do, of the form "(disjunct1 | disjunct2 | ... | disjunctn)^boost" </returns> public override string ToString(string field) { StringBuilder buffer = new StringBuilder(); buffer.Append("("); int numDisjunctions = disjuncts.Count; for (int i = 0; i < numDisjunctions; i++) { Query subquery = disjuncts[i]; if (subquery is BooleanQuery) // wrap sub-bools in parens { buffer.Append("("); buffer.Append(subquery.ToString(field)); buffer.Append(")"); } else { buffer.Append(subquery.ToString(field)); } if (i != numDisjunctions - 1) { buffer.Append(" | "); } } buffer.Append(")"); if (tieBreakerMultiplier != 0.0f) { buffer.Append("~"); buffer.Append(tieBreakerMultiplier); } if (Boost != 1.0) { buffer.Append("^"); buffer.Append(Boost); } return buffer.ToString(); } /// <summary> /// Return <c>true</c> if we represent the same query as <paramref name="o"/> </summary> /// <param name="o"> Another object </param> /// <returns> <c>true</c> if <paramref name="o"/> is a <see cref="DisjunctionMaxQuery"/> with the same boost and the same subqueries, in the same order, as us </returns> public override bool Equals(object o) { if (!(o is DisjunctionMaxQuery)) { return false; } DisjunctionMaxQuery other = (DisjunctionMaxQuery)o; return this.Boost == other.Boost && this.tieBreakerMultiplier == other.tieBreakerMultiplier && this.disjuncts.Equals(other.disjuncts); } /// <summary> /// Compute a hash code for hashing us </summary> /// <returns> the hash code </returns> public override int GetHashCode() { return J2N.BitConversion.SingleToInt32Bits(Boost) + J2N.BitConversion.SingleToInt32Bits(tieBreakerMultiplier) + disjuncts.GetHashCode(); } } }
using System; using System.Diagnostics; using System.Drawing; using System.Drawing.Drawing2D; using System.Text.RegularExpressions; using System.Xml; namespace SharpVectors.Dom.Svg { public enum SvgLengthAdjust { Unknown = 0, Spacing = 1, SpacingAndGlyphs = 2 } /// <summary> /// Summary description for SvgTextContentElement. /// </summary> public class SvgTextContentElement : SvgTransformableElement, ISharpGDIPath, ISvgTextContentElement, IGraphicsElement { internal SvgTextContentElement(string prefix, string localname, string ns, SvgDocument doc) : base(prefix, localname, ns, doc) { svgExternalResourcesRequired = new SvgExternalResourcesRequired(this); svgTests = new SvgTests(this); } #region Implementation of ISvgExternalResourcesRequired private SvgExternalResourcesRequired svgExternalResourcesRequired; public ISvgAnimatedBoolean ExternalResourcesRequired { get { return svgExternalResourcesRequired.ExternalResourcesRequired; } } #endregion #region Implementation of ISvgTests private SvgTests svgTests; public ISvgStringList RequiredFeatures { get { return svgTests.RequiredFeatures; } } public ISvgStringList RequiredExtensions { get { return svgTests.RequiredExtensions; } } public ISvgStringList SystemLanguage { get { return svgTests.SystemLanguage; } } public bool HasExtension(string extension) { return svgTests.HasExtension(extension); } #endregion public ISvgAnimatedLength TextLength { get{throw new NotImplementedException();} } public ISvgAnimatedEnumeration LengthAdjust { get{throw new NotImplementedException();} } protected string TrimText(string val) { Regex tabNewline = new Regex(@"[\n\f\t]"); if(this.XmlSpace != "preserve") val = val.Replace("\n", String.Empty); val = tabNewline.Replace(val, " "); if(this.XmlSpace == "preserve") return val; else return val.Trim(); } public virtual string GetText(XmlNode child) { return this.TrimText(child.Value); } protected SvgTextElement OwnerTextElement { get { XmlNode node = (XmlNode) this; while(node != null) { if(node is SvgTextElement) return (SvgTextElement) node; node = node.ParentNode; } return null; } } public void Invalidate() { CssInvalidate(); gp = null; renderingNode = null; } #region Update handling public override void HandleAttributeChange(XmlAttribute attribute) { if(attribute.NamespaceURI.Length == 0) { // This list may be too long to be useful... switch(attribute.LocalName) { // Additional attributes case "x": case "y": case "dx": case "dy": case "rotate": case "textLength": case "lengthAdjust": // Text.attrib case "writing-mode": // TextContent.attrib case "alignment-baseline": case "baseline-shift": case "direction": case "dominant-baseline": case "glyph-orientation-horizontal": case "glyph-orientation-vertical": case "kerning": case "letter-spacing": case "text-anchor": case "text-decoration": case "unicode-bidi": case "word-spacing": // Font.attrib case "font-family": case "font-size": case "font-size-adjust": case "font-stretch": case "font-style": case "font-variant": case "font-weight": // textPath case "startOffset": case "method": case "spacing": // Color.attrib, Paint.attrib case "color": case "fill": case "fill-rule": case "stroke": case "stroke-dasharray": case "stroke-dashoffset": case "stroke-linecap": case "stroke-linejoin": case "stroke-miterlimit": case "stroke-width": // Opacity.attrib case "opacity": case "stroke-opacity": case "fill-opacity": // Graphics.attrib case "display": case "image-rendering": case "shape-rendering": case "text-rendering": case "visibility": Invalidate(); return; case "transform": Invalidate(); break; } base.HandleAttributeChange(attribute); } else if (attribute.Name == "xml:preserve" || attribute.Name == "xlink:href") { // xml:preserve and xlink:href changes may affect the actual text content Invalidate(); } } public override void ElementChange(Object src, XmlNodeChangedEventArgs args) { Invalidate(); base.ElementChange(src, args); } #endregion protected GraphicsPath gp = null; public virtual GraphicsPath GetGraphicsPath() { if(gp == null) { this.OwnerTextElement.GetGraphicsPath(); } return gp; } protected void AddGraphicsPath(ref PointF ctp, string text) { if(text.Length == 0) return; float emSize = _getComputedFontSize(); FontFamily family = _getGDIFontFamily(emSize); int style = _getGDIStyle(); StringFormat sf = _getGDIStringFormat(); GraphicsPath gp2 = new GraphicsPath(); gp2.StartFigure(); float xCorrection = 0; if(sf.Alignment == StringAlignment.Near) xCorrection = emSize * 1 /6; else if(sf.Alignment == StringAlignment.Far) xCorrection = -emSize * 1 /6; float yCorrection = (float)(family.GetCellAscent(FontStyle.Regular)) / (float)(family.GetEmHeight(FontStyle.Regular)) * emSize; // TODO: font property PointF p = new PointF(ctp.X-xCorrection, ctp.Y - yCorrection); gp2.AddString(text, family, style, emSize, p, sf); if(!gp2.GetBounds().IsEmpty) { float bboxWidth = gp2.GetBounds().Width; if(sf.Alignment == StringAlignment.Center) bboxWidth /= 2; else if(sf.Alignment == StringAlignment.Far) bboxWidth = 0; ctp.X += bboxWidth + emSize/4; } gp.AddPath(gp2, false); gp2.Dispose(); } protected virtual void GetGraphicsPath(ref PointF ctp) { gp = new GraphicsPath(); if(this is SvgTextPositioningElement) { SvgTextPositioningElement tpElm = (SvgTextPositioningElement) this; ctp = this.GetCurrentTextPosition(tpElm, ctp); } string sBaselineShift = GetPropertyValue("baseline-shift").Trim(); double shiftBy = 0; if(sBaselineShift.Length > 0) { SvgTextElement textElement = this as SvgTextElement; if(textElement == null) { textElement = (SvgTextElement)this.SelectSingleNode("ancestor::svg:text", this.OwnerDocument.NamespaceManager); } float textFontSize = textElement._getComputedFontSize(); if(sBaselineShift.EndsWith("%")) { shiftBy = SvgNumber.ParseToFloat(sBaselineShift.Substring(0, sBaselineShift.Length-1)) / 100 * textFontSize; } else if(sBaselineShift == "sub") { shiftBy = -0.6F * textFontSize; } else if(sBaselineShift == "super") { shiftBy = 0.6F * textFontSize; } else if(sBaselineShift == "baseline") { shiftBy = 0; } else { shiftBy = SvgNumber.ParseToFloat(sBaselineShift); } } foreach(XmlNode child in this.ChildNodes) { gp.StartFigure(); if(child.NodeType == XmlNodeType.Text) { ctp.Y -= (float)shiftBy; this.AddGraphicsPath(ref ctp, GetText(child)); ctp.Y += (float)shiftBy; } else if(child is SvgTRefElement) { SvgTRefElement trChild = (SvgTRefElement) child; trChild.GetGraphicsPath(ref ctp); } else if(child is SvgTextContentElement) { SvgTextContentElement tcChild = (SvgTextContentElement) child; tcChild.GetGraphicsPath(ref ctp); } } } protected PointF GetCurrentTextPosition(SvgTextPositioningElement posElement, PointF p) { if(posElement.X.AnimVal.NumberOfItems>0) { p.X = (float)posElement.X.AnimVal.GetItem(0).Value; } if(posElement.Y.AnimVal.NumberOfItems>0) { p.Y = (float)posElement.Y.AnimVal.GetItem(0).Value; } if(posElement.Dx.AnimVal.NumberOfItems>0) { p.X += (float)posElement.Dx.AnimVal.GetItem(0).Value; } if(posElement.Dy.AnimVal.NumberOfItems>0) { p.Y += (float)posElement.Dy.AnimVal.GetItem(0).Value; } return p; } private int _getGDIStyle() { int style = (int)FontStyle.Regular; string fontWeight = GetPropertyValue("font-weight"); if(fontWeight == "bold" || fontWeight == "bolder" || fontWeight == "600" || fontWeight == "700" || fontWeight == "800" || fontWeight == "900") { style = style | (int)FontStyle.Bold; } if(GetPropertyValue("font-style")=="italic") { style = style | (int)FontStyle.Italic; } string textDeco = GetPropertyValue("text-decoration"); if(textDeco=="line-through") { style = style | (int)FontStyle.Strikeout; } else if(textDeco=="underline") { style = style | (int)FontStyle.Underline; } return style; } private FontFamily _getGDIFontFamily(float fontSize) { string fontFamily = GetPropertyValue("font-family"); string[] fontNames = fontNames = fontFamily.Split(new char[1]{','}); FontFamily family; foreach(string fn in fontNames) { try { string fontName = fn.Trim(new char[]{' ', '\'', '"'}); if(fontName == "serif") family = FontFamily.GenericSerif; else if(fontName == "sans-serif") family = FontFamily.GenericSansSerif; else if(fontName == "monospace") family = FontFamily.GenericMonospace; else family = new FontFamily(fontName); // Font(,fontSize).FontFamily; return family; } catch { } } // no known font-family was found => default to arial return new FontFamily("Arial"); } private StringFormat _getGDIStringFormat() { StringFormat sf = new StringFormat(); bool doAlign = true; if(this is SvgTSpanElement || this is SvgTRefElement) { SvgTextPositioningElement posElement = (SvgTextPositioningElement) this; if(posElement.X.AnimVal.NumberOfItems == 0) doAlign = false; } if(doAlign) { string anchor = GetPropertyValue("text-anchor"); if(anchor == "middle") sf.Alignment = StringAlignment.Center; if(anchor == "end") sf.Alignment = StringAlignment.Far; } string dir = GetPropertyValue("direction"); if(dir == "rtl") { if(sf.Alignment == StringAlignment.Far)sf.Alignment = StringAlignment.Near; else if(sf.Alignment == StringAlignment.Near)sf.Alignment = StringAlignment.Far; sf.FormatFlags = StringFormatFlags.DirectionRightToLeft; } dir = GetPropertyValue("writing-mode"); if(dir == "tb") { sf.FormatFlags = sf.FormatFlags | StringFormatFlags.DirectionVertical; } sf.FormatFlags = sf.FormatFlags | StringFormatFlags.MeasureTrailingSpaces; return sf; } private float _getComputedFontSize() { string str = GetPropertyValue("font-size"); float fontSize = 12; if(str.EndsWith("%")) { // percentage of inherited value } else if(new Regex(@"^\d").IsMatch(str)) { // svg length fontSize = (float)new SvgLength(this, "font-size", SvgLengthDirection.Viewport, str, "10px").Value; } else if(str == "larger") { } else if(str == "smaller") { } else { // check for absolute value } return fontSize; } public long GetNumberOfChars ( ) { return this.InnerText.Length; } public float GetComputedTextLength () { throw new NotImplementedException(); } public float GetSubStringLength (long charnum, long nchars ) { throw new NotImplementedException(); //raises( DOMException ); } public ISvgPoint GetStartPositionOfChar (long charnum ) { throw new NotImplementedException(); //raises( DOMException ); } public ISvgPoint GetEndPositionOfChar (long charnum ) { throw new NotImplementedException(); //raises( DOMException ); } public ISvgRect GetExtentOfChar (long charnum ) { throw new NotImplementedException(); //raises( DOMException ); } public float GetRotationOfChar (long charnum ) { throw new NotImplementedException(); //raises( DOMException ); } public long GetCharNumAtPosition (ISvgPoint point ) { throw new NotImplementedException(); } public void SelectSubString (long charnum, long nchars ) { throw new NotImplementedException(); //raises( DOMException ); } } }
// 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.Globalization; using System.IO; using System.Reflection; using System.Threading; using Microsoft.Build.BackEnd; using Microsoft.Build.Framework; using Microsoft.Build.Shared; using Microsoft.Build.Utilities; using Xunit; namespace Microsoft.Build.UnitTests.BackEnd { /// <summary> /// Unit Tests for TaskHostConfiguration packet. /// </summary> public class TaskHostConfiguration_Tests { /// <summary> /// Override for ContinueOnError /// </summary> private bool _continueOnErrorDefault = true; /// <summary> /// Test that an exception is thrown when the task name is null. /// </summary> [Fact] public void ConstructorWithNullName() { Assert.Throws<InternalErrorException>(() => { TaskHostConfiguration config = new TaskHostConfiguration( 1, Directory.GetCurrentDirectory(), null, #if FEATURE_THREAD_CULTURE Thread.CurrentThread.CurrentCulture, Thread.CurrentThread.CurrentUICulture, #else CultureInfo.CurrentCulture, CultureInfo.CurrentCulture, #endif #if FEATURE_APPDOMAIN null, #endif 1, 1, @"c:\my project\myproj.proj", _continueOnErrorDefault, null, @"c:\my tasks\mytask.dll", null); } ); } /// <summary> /// Test that an exception is thrown when the task name is empty. /// </summary> [Fact] public void ConstructorWithEmptyName() { Assert.Throws<InternalErrorException>(() => { TaskHostConfiguration config = new TaskHostConfiguration( 1, Directory.GetCurrentDirectory(), null, #if FEATURE_THREAD_CULTURE Thread.CurrentThread.CurrentCulture, Thread.CurrentThread.CurrentUICulture, #else CultureInfo.CurrentCulture, CultureInfo.CurrentCulture, #endif #if FEATURE_APPDOMAIN null, #endif 1, 1, @"c:\my project\myproj.proj", _continueOnErrorDefault, String.Empty, @"c:\my tasks\mytask.dll", null); } ); } /// <summary> /// Test that an exception is thrown when the path to the task assembly is null /// </summary> [Fact] public void ConstructorWithNullLocation() { Assert.Throws<InternalErrorException>(() => { TaskHostConfiguration config = new TaskHostConfiguration( 1, Directory.GetCurrentDirectory(), null, #if FEATURE_THREAD_CULTURE Thread.CurrentThread.CurrentCulture, Thread.CurrentThread.CurrentUICulture, #else CultureInfo.CurrentCulture, CultureInfo.CurrentCulture, #endif #if FEATURE_APPDOMAIN null, #endif 1, 1, @"c:\my project\myproj.proj", _continueOnErrorDefault, "TaskName", null, null); } ); } #if FEATURE_ASSEMBLY_LOADFROM /// <summary> /// Test that an exception is thrown when the path to the task assembly is empty /// </summary> [Fact] public void ConstructorWithEmptyLocation() { Assert.Throws<InternalErrorException>(() => { TaskHostConfiguration config = new TaskHostConfiguration( 1, Directory.GetCurrentDirectory(), null, #if FEATURE_THREAD_CULTURE Thread.CurrentThread.CurrentCulture, Thread.CurrentThread.CurrentUICulture, #else CultureInfo.CurrentCulture, CultureInfo.CurrentCulture, #endif #if FEATURE_APPDOMAIN null, #endif 1, 1, @"c:\my project\myproj.proj", _continueOnErrorDefault, "TaskName", String.Empty, null); } ); } #endif /// <summary> /// Test the valid constructors. /// </summary> [Fact] public void TestValidConstructors() { TaskHostConfiguration config = new TaskHostConfiguration( 1, Directory.GetCurrentDirectory(), null, #if FEATURE_THREAD_CULTURE Thread.CurrentThread.CurrentCulture, Thread.CurrentThread.CurrentUICulture, #else CultureInfo.CurrentCulture, CultureInfo.CurrentCulture, #endif #if FEATURE_APPDOMAIN null, #endif 1, 1, @"c:\my project\myproj.proj", _continueOnErrorDefault, "TaskName", @"c:\MyTasks\MyTask.dll", null); TaskHostConfiguration config2 = new TaskHostConfiguration( 1, Directory.GetCurrentDirectory(), null, #if FEATURE_THREAD_CULTURE Thread.CurrentThread.CurrentCulture, Thread.CurrentThread.CurrentUICulture, #else CultureInfo.CurrentCulture, CultureInfo.CurrentCulture, #endif #if FEATURE_APPDOMAIN null, #endif 1, 1, @"c:\my project\myproj.proj", _continueOnErrorDefault, "TaskName", @"c:\MyTasks\MyTask.dll", null); IDictionary<string, object> parameters = new Dictionary<string, object>(); TaskHostConfiguration config3 = new TaskHostConfiguration( 1, Directory.GetCurrentDirectory(), null, #if FEATURE_THREAD_CULTURE Thread.CurrentThread.CurrentCulture, Thread.CurrentThread.CurrentUICulture, #else CultureInfo.CurrentCulture, CultureInfo.CurrentCulture, #endif #if FEATURE_APPDOMAIN null, #endif 1, 1, @"c:\my project\myproj.proj", _continueOnErrorDefault, "TaskName", @"c:\MyTasks\MyTask.dll", parameters); IDictionary<string, object> parameters2 = new Dictionary<string, object>(); parameters2.Add("Text", "Hello!"); parameters2.Add("MyBoolValue", true); parameters2.Add("MyITaskItem", new TaskItem("ABC")); parameters2.Add("ItemArray", new ITaskItem[] { new TaskItem("DEF"), new TaskItem("GHI"), new TaskItem("JKL") }); TaskHostConfiguration config4 = new TaskHostConfiguration( 1, Directory.GetCurrentDirectory(), null, #if FEATURE_THREAD_CULTURE Thread.CurrentThread.CurrentCulture, Thread.CurrentThread.CurrentUICulture, #else CultureInfo.CurrentCulture, CultureInfo.CurrentCulture, #endif #if FEATURE_APPDOMAIN null, #endif 1, 1, @"c:\my project\myproj.proj", _continueOnErrorDefault, "TaskName", @"c:\MyTasks\MyTask.dll", parameters2); } /// <summary> /// Test serialization / deserialization when the parameter dictionary is null. /// </summary> [Fact] public void TestTranslationWithNullDictionary() { TaskHostConfiguration config = new TaskHostConfiguration( 1, Directory.GetCurrentDirectory(), null, #if FEATURE_THREAD_CULTURE Thread.CurrentThread.CurrentCulture, Thread.CurrentThread.CurrentUICulture, #else CultureInfo.CurrentCulture, CultureInfo.CurrentCulture, #endif #if FEATURE_APPDOMAIN null, #endif 1, 1, @"c:\my project\myproj.proj", _continueOnErrorDefault, "TaskName", @"c:\MyTasks\MyTask.dll", null); ((ITranslatable)config).Translate(TranslationHelpers.GetWriteTranslator()); INodePacket packet = TaskHostConfiguration.FactoryForDeserialization(TranslationHelpers.GetReadTranslator()); TaskHostConfiguration deserializedConfig = packet as TaskHostConfiguration; Assert.Equal(config.TaskName, deserializedConfig.TaskName); #if FEATURE_ASSEMBLY_LOADFROM Assert.Equal(config.TaskLocation, config.TaskLocation); #endif Assert.Null(deserializedConfig.TaskParameters); } /// <summary> /// Test serialization / deserialization when the parameter dictionary is empty. /// </summary> [Fact] public void TestTranslationWithEmptyDictionary() { TaskHostConfiguration config = new TaskHostConfiguration( 1, Directory.GetCurrentDirectory(), null, #if FEATURE_THREAD_CULTURE Thread.CurrentThread.CurrentCulture, Thread.CurrentThread.CurrentUICulture, #else CultureInfo.CurrentCulture, CultureInfo.CurrentCulture, #endif #if FEATURE_APPDOMAIN null, #endif 1, 1, @"c:\my project\myproj.proj", _continueOnErrorDefault, "TaskName", @"c:\MyTasks\MyTask.dll", new Dictionary<string, object>()); ((ITranslatable)config).Translate(TranslationHelpers.GetWriteTranslator()); INodePacket packet = TaskHostConfiguration.FactoryForDeserialization(TranslationHelpers.GetReadTranslator()); TaskHostConfiguration deserializedConfig = packet as TaskHostConfiguration; Assert.Equal(config.TaskName, deserializedConfig.TaskName); #if FEATURE_ASSEMBLY_LOADFROM Assert.Equal(config.TaskLocation, config.TaskLocation); #endif Assert.NotNull(deserializedConfig.TaskParameters); Assert.Equal(config.TaskParameters.Count, deserializedConfig.TaskParameters.Count); } /// <summary> /// Test serialization / deserialization when the parameter dictionary contains just value types. /// </summary> [Fact] public void TestTranslationWithValueTypesInDictionary() { IDictionary<string, object> parameters = new Dictionary<string, object>(); parameters.Add("Text", "Foo"); parameters.Add("BoolValue", false); TaskHostConfiguration config = new TaskHostConfiguration( 1, Directory.GetCurrentDirectory(), null, Thread.CurrentThread.CurrentCulture, Thread.CurrentThread.CurrentUICulture, #if FEATURE_APPDOMAIN null, #endif 1, 1, @"c:\my project\myproj.proj", _continueOnErrorDefault, "TaskName", @"c:\MyTasks\MyTask.dll", parameters); ((ITranslatable)config).Translate(TranslationHelpers.GetWriteTranslator()); INodePacket packet = TaskHostConfiguration.FactoryForDeserialization(TranslationHelpers.GetReadTranslator()); TaskHostConfiguration deserializedConfig = packet as TaskHostConfiguration; Assert.Equal(config.TaskName, deserializedConfig.TaskName); #if FEATURE_ASSEMBLY_LOADFROM Assert.Equal(config.TaskLocation, config.TaskLocation); #endif Assert.NotNull(deserializedConfig.TaskParameters); Assert.Equal(config.TaskParameters.Count, deserializedConfig.TaskParameters.Count); Assert.Equal(config.TaskParameters["Text"].WrappedParameter, deserializedConfig.TaskParameters["Text"].WrappedParameter); Assert.Equal(config.TaskParameters["BoolValue"].WrappedParameter, deserializedConfig.TaskParameters["BoolValue"].WrappedParameter); } /// <summary> /// Test serialization / deserialization when the parameter dictionary contains an ITaskItem. /// </summary> [Fact] public void TestTranslationWithITaskItemInDictionary() { IDictionary<string, object> parameters = new Dictionary<string, object>(); parameters.Add("TaskItemValue", new TaskItem("Foo")); TaskHostConfiguration config = new TaskHostConfiguration( 1, Directory.GetCurrentDirectory(), null, #if FEATURE_THREAD_CULTURE Thread.CurrentThread.CurrentCulture, Thread.CurrentThread.CurrentUICulture, #else CultureInfo.CurrentCulture, CultureInfo.CurrentCulture, #endif #if FEATURE_APPDOMAIN null, #endif 1, 1, @"c:\my project\myproj.proj", _continueOnErrorDefault, "TaskName", @"c:\MyTasks\MyTask.dll", parameters); ((ITranslatable)config).Translate(TranslationHelpers.GetWriteTranslator()); INodePacket packet = TaskHostConfiguration.FactoryForDeserialization(TranslationHelpers.GetReadTranslator()); TaskHostConfiguration deserializedConfig = packet as TaskHostConfiguration; Assert.Equal(config.TaskName, deserializedConfig.TaskName); #if FEATURE_ASSEMBLY_LOADFROM Assert.Equal(config.TaskLocation, config.TaskLocation); #endif Assert.NotNull(deserializedConfig.TaskParameters); Assert.Equal(config.TaskParameters.Count, deserializedConfig.TaskParameters.Count); TaskHostPacketHelpers.AreEqual((ITaskItem)config.TaskParameters["TaskItemValue"].WrappedParameter, (ITaskItem)deserializedConfig.TaskParameters["TaskItemValue"].WrappedParameter); } /// <summary> /// Test serialization / deserialization when the parameter dictionary contains an ITaskItem array. /// </summary> [Fact] public void TestTranslationWithITaskItemArrayInDictionary() { IDictionary<string, object> parameters = new Dictionary<string, object>(); parameters.Add("TaskItemArrayValue", new ITaskItem[] { new TaskItem("Foo"), new TaskItem("Baz") }); TaskHostConfiguration config = new TaskHostConfiguration( 1, Directory.GetCurrentDirectory(), null, #if FEATURE_THREAD_CULTURE Thread.CurrentThread.CurrentCulture, Thread.CurrentThread.CurrentUICulture, #else CultureInfo.CurrentCulture, CultureInfo.CurrentCulture, #endif #if FEATURE_APPDOMAIN null, #endif 1, 1, @"c:\my project\myproj.proj", _continueOnErrorDefault, "TaskName", @"c:\MyTasks\MyTask.dll", parameters); ((ITranslatable)config).Translate(TranslationHelpers.GetWriteTranslator()); INodePacket packet = TaskHostConfiguration.FactoryForDeserialization(TranslationHelpers.GetReadTranslator()); TaskHostConfiguration deserializedConfig = packet as TaskHostConfiguration; Assert.Equal(config.TaskName, deserializedConfig.TaskName); #if FEATURE_ASSEMBLY_LOADFROM Assert.Equal(config.TaskLocation, config.TaskLocation); #endif Assert.NotNull(deserializedConfig.TaskParameters); Assert.Equal(config.TaskParameters.Count, deserializedConfig.TaskParameters.Count); ITaskItem[] itemArray = (ITaskItem[])config.TaskParameters["TaskItemArrayValue"].WrappedParameter; ITaskItem[] deserializedItemArray = (ITaskItem[])deserializedConfig.TaskParameters["TaskItemArrayValue"].WrappedParameter; TaskHostPacketHelpers.AreEqual(itemArray, deserializedItemArray); } /// <summary> /// Helper methods for testing the task host-related packets. /// </summary> internal static class TaskHostPacketHelpers { /// <summary> /// Asserts the equality (or lack thereof) of two arrays of ITaskItems. /// </summary> internal static void AreEqual(ITaskItem[] x, ITaskItem[] y) { if (x == null && y == null) { return; } if (x == null || y == null) { Assert.True(false, "The two item lists are not equal -- one of them is null"); } if (x.Length != y.Length) { Assert.True(false, "The two item lists have different lengths, so they cannot be equal"); } for (int i = 0; i < x.Length; i++) { AreEqual(x[i], y[i]); } } /// <summary> /// Asserts the equality (or lack thereof) of two ITaskItems. /// </summary> internal static void AreEqual(ITaskItem x, ITaskItem y) { if (x == null && y == null) { return; } if (x == null || y == null) { Assert.True(false, "The two items are not equal -- one of them is null"); } Assert.Equal(x.ItemSpec, y.ItemSpec); IDictionary metadataFromX = x.CloneCustomMetadata(); IDictionary metadataFromY = y.CloneCustomMetadata(); Assert.Equal(metadataFromX.Count, metadataFromY.Count); foreach (object metadataName in metadataFromX.Keys) { if (!metadataFromY.Contains(metadataName)) { Assert.True(false, string.Format("Only one item contains the '{0}' metadata", metadataName)); } else { Assert.Equal(metadataFromX[metadataName], metadataFromY[metadataName]); } } } } } }
#pragma warning disable using System.Collections.Generic; using XPT.Games.Generic.Entities; using XPT.Games.Generic.Maps; using XPT.Games.Yserbius; using XPT.Games.Yserbius.Entities; namespace XPT.Games.Yserbius.Maps { class YserMap03 : YsMap { public override int MapIndex => 3; protected override int RandomEncounterChance => 10; protected override int RandomEncounterExtraCount => 0; public YserMap03() { MapEvent01 = FnTOEXIT_01; MapEvent02 = FnTOVEST_02; MapEvent03 = FnGATEMSGA_03; MapEvent04 = FnTELEPORT_04; MapEvent05 = FnTELPORTW_05; MapEvent06 = FnTELPORTE_06; MapEvent07 = FnTELPORTS_07; MapEvent08 = FnSTAIRMSG_08; MapEvent09 = FnSTAIRSDN_09; MapEvent0A = FnLKPKDOOR_0A; MapEvent0B = FnTELEPORT_0B; MapEvent0C = FnLKPKDOOR_0C; MapEvent0D = FnGATEMSGB_0D; MapEvent0E = FnTELMESSA_0E; MapEvent0F = FnTELMESSB_0F; MapEvent10 = FnTELMESSC_10; MapEvent11 = FnTELMESSD_11; MapEvent12 = FnNPCCHATA_12; MapEvent13 = FnNPCCHATB_13; MapEvent14 = FnNPCCHATC_14; MapEvent15 = FnNPCCHATD_15; MapEvent16 = FnNPCCHATE_16; MapEvent17 = FnLOWMNSTR_17; MapEvent18 = FnLWRMNSTR_18; MapEvent19 = FnOGREENC_19; MapEvent1A = FnTUFMNSTR_1A; MapEvent1B = FnSTRMNSTR_1B; MapEvent1C = FnWEAPENC_1C; MapEvent1D = FnGOLDENC_1D; MapEvent1E = FnMAGICENC_1E; } // === Strings ================================================ private const string String03FC = "The gateway leads to THE VESTIBULE."; private const string String0420 = "Through the gateway to the west you see stairs leading down to the next level."; private const string String046F = "You successfully picked the locked door."; private const string String0498 = "The door is locked."; private const string String04AC = "You successfully picked the locked door."; private const string String04D5 = "The door is locked."; private const string String04E9 = "The gateway leads to THE MAIN DUNGEON ENTRANCE."; private const string String0519 = "There is a teleport in the west wall."; private const string String053F = "There is a teleport in the south wall."; private const string String0566 = "There is a teleport in the west wall."; private const string String058C = "There is a teleport in the north wall."; private const string String05B3 = "You encounter a Gnome Barbarian."; private const string String05D4 = "My father told me an ancient story. A Galabryan king once brought a powerful wizard to Twinion. This wizard did something very bad and caused the volcano to erupt."; private const string String0678 = "Supposedly the wizard's castle is buried deep in the bowels of this mountain. It is his anguished spirit that keeps the volcano active."; private const string String0700 = "The Gnome Barbarian ignores you as he tries to remember his own name."; private const string String0746 = "You encounter a Dwarf Wizard."; private const string String0764 = "Powerful magic once existed here. I've found scrolls and amulets and other magic charms that contain powerful spells. The Mana in these items is soon exhausted."; private const string String0805 = "The Dwarf Wizard offers to teach you the Bless spell since you didn't hurt her."; private const string String0855 = "You encounter a Halfling Ranger."; private const string String0876 = "This place is called the Hall of Doors. Most doors lead nowhere. Others lead to wonders."; private const string String08CF = "The Halfling Ranger wanders off in pursuit of friends."; private const string String0906 = "You encounter a Troll Cleric."; private const string String0924 = "Someone left a rune message on the floor. It said that to reach the King's Apartments, you must take a turn for the worse. I wonder if it means that you must be sick to find his quarters."; private const string String09E0 = "The Troll Cleric is too busy counting her blessings to speak to you."; private const string String0A25 = "You encounter a Troll Knight."; private const string String0A43 = "A wise leader knows how to organize a party. Keep your fighters in front and your magicians safely in the rear. And as much as thieves are despised in general, they can serve you well, for their skills are impressive."; private const string String0B1D = "The Troll Knight gives you 10 Gold Pieces and departs in peace."; private const string String0B5D = "You encounter Goblins."; private const string String0B74 = "You should be gracious to us Goblins, or we will tell our masters the Goblin Kings that you are cruel and deserve to die most horribly."; private const string String0BFC = "The Goblins refuse to talk."; private const string String0C18 = "They draw their weapons and attack!"; private const string String0C3C = "You encounter Rogues."; private const string String0C52 = "Bizarre creatures haunt this dungeon. Many know magic. A great evil must exist somewhere in the dungeon to spawn such a neverending host of monsters."; private const string String0CE8 = "The Rogues refuse to talk."; private const string String0D03 = "They charge at you!"; private const string String0D17 = "You encounter Rogues!"; private const string String0D2D = "The Rogues scowl at you and attack!"; private const string String0D51 = "It looks like the Rogues you encounter have already looted the room."; private const string String0D96 = "Rogues covet the Sword of the Flames and Sword of Decision you see lying on the floor."; private const string String0DED = "Goblins grab their weapons as you enter the room."; private const string String0E1F = "Goblins are pitching Gold Pieces against the wall."; private const string String0E52 = "Ogres grimace in pleasure as you walk into their ambush."; private const string String0E8B = "Ogres are playing with items you identify as the Ring of Vigor, a Cudgel Insignia, and the Wand of Radiance."; // === Functions ================================================ private void FnTOEXIT_01(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: TeleportParty(player, 0x01, 0x01, 0x3A, 0x00, type); L001D: return; // RETURN; } private void FnTOVEST_02(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: TeleportParty(player, 0x01, 0x03, YsIndexes.ItemRanbowGemYellow, 0x03, type); L001E: return; // RETURN; } private void FnGATEMSGA_03(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: ShowMessage(player, doMsgs, String03FC); // The gateway leads to THE VESTIBULE. L0010: return; // RETURN; } private void FnTELEPORT_04(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: TeleportParty(player, 0x03, 0x04, 0xF7, 0x00, type); L001D: return; // RETURN; } private void FnTELPORTW_05(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: TeleportParty(player, 0x01, 0x04, 0x57, 0x02, type); L001E: return; // RETURN; } private void FnTELPORTE_06(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: TeleportParty(player, 0x01, 0x04, 0x4F, 0x03, type); L001E: return; // RETURN; } private void FnTELPORTS_07(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: TeleportParty(player, 0x01, 0x05, 0x8F, 0x01, type); L001E: return; // RETURN; } private void FnSTAIRMSG_08(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: ShowMessage(player, doMsgs, String0420); // Through the gateway to the west you see stairs leading down to the next level. L0010: return; // RETURN; } private void FnSTAIRSDN_09(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: TeleportParty(player, 0x02, 0x01, 0x05, 0x01, type); L001E: return; // RETURN; } private void FnLKPKDOOR_0A(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: ax = HasUsedItem(player, type, ref doMsgs, 0xC0, 0xC4); L0016: if (JumpNotEqual) goto L0029; L0018: Compare(HasUsedSkill(player, type, ref doMsgs, 0x0E), 0x0004); L0027: if (JumpBelow) goto L0068; L0029: SetWallPassable(player, 0x6F, 0x03, 0x01); L003F: SetWallItem(player, 0x01, GetCurrentTile(player), 0x03); L0059: ShowMessage(player, doMsgs, String046F); // You successfully picked the locked door. L0066: goto L008A; L0068: SetWallPassable(player, 0x6F, 0x03, 0x00); L007D: ShowMessage(player, doMsgs, String0498); // The door is locked. L008A: return; // RETURN; } private void FnTELEPORT_0B(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: TeleportParty(player, 0x02, 0x01, 0x0E, 0x02, type); L001E: return; // RETURN; } private void FnLKPKDOOR_0C(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: ax = HasUsedItem(player, type, ref doMsgs, 0xC2, 0xC4); L0016: if (JumpNotEqual) goto L0029; L0018: Compare(HasUsedSkill(player, type, ref doMsgs, 0x0E), 0x0008); L0027: if (JumpBelow) goto L0068; L0029: SetWallPassable(player, 0x40, 0x03, 0x01); L003F: SetWallItem(player, 0x01, GetCurrentTile(player), 0x03); L0059: ShowMessage(player, doMsgs, String04AC); // You successfully picked the locked door. L0066: goto L008A; L0068: SetWallPassable(player, 0x40, 0x03, 0x00); L007D: ShowMessage(player, doMsgs, String04D5); // The door is locked. L008A: return; // RETURN; } private void FnGATEMSGB_0D(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: ShowMessage(player, doMsgs, String04E9); // The gateway leads to THE MAIN DUNGEON ENTRANCE. L0010: return; // RETURN; } private void FnTELMESSA_0E(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: ShowMessage(player, doMsgs, String0519); // There is a teleport in the west wall. L0010: return; // RETURN; } private void FnTELMESSB_0F(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: ShowMessage(player, doMsgs, String053F); // There is a teleport in the south wall. L0010: return; // RETURN; } private void FnTELMESSC_10(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: ShowMessage(player, doMsgs, String0566); // There is a teleport in the west wall. L0010: return; // RETURN; } private void FnTELMESSD_11(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: ShowMessage(player, doMsgs, String058C); // There is a teleport in the north wall. L0010: return; // RETURN; } private void FnNPCCHATA_12(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: ShowMessage(player, doMsgs, String05B3); // You encounter a Gnome Barbarian. L0010: ShowPortrait(player, 0x0019); L001D: Compare(GetRandom(0x000F), 0x0008); L002D: if (JumpAbove) goto L004B; L002F: ShowMessage(player, doMsgs, String05D4); // My father told me an ancient story. A Galabryan king once brought a powerful wizard to Twinion. This wizard did something very bad and caused the volcano to erupt. L003C: ShowMessage(player, doMsgs, String0678); // Supposedly the wizard's castle is buried deep in the bowels of this mountain. It is his anguished spirit that keeps the volcano active. L0049: goto L0058; L004B: ShowMessage(player, doMsgs, String0700); // The Gnome Barbarian ignores you as he tries to remember his own name. L0058: return; // RETURN; } private void FnNPCCHATB_13(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: ShowMessage(player, doMsgs, String0746); // You encounter a Dwarf Wizard. L0010: ShowPortrait(player, 0x002C); L001D: Compare(GetRandom(0x000F), 0x000C); L002D: if (JumpAbove) goto L003E; L002F: ShowMessage(player, doMsgs, String0764); // Powerful magic once existed here. I've found scrolls and amulets and other magic charms that contain powerful spells. The Mana in these items is soon exhausted. L003C: goto L005C; L003E: SetSpellLevel(player, 0x12, 0x01); L004F: ShowMessage(player, doMsgs, String0805); // The Dwarf Wizard offers to teach you the Bless spell since you didn't hurt her. L005C: return; // RETURN; } private void FnNPCCHATC_14(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: ShowMessage(player, doMsgs, String0855); // You encounter a Halfling Ranger. L0010: ShowPortrait(player, 0x0021); L001D: Compare(GetRandom(0x000F), 0x000D); L002D: if (JumpAbove) goto L003E; L002F: ShowMessage(player, doMsgs, String0876); // This place is called the Hall of Doors. Most doors lead nowhere. Others lead to wonders. L003C: goto L004B; L003E: ShowMessage(player, doMsgs, String08CF); // The Halfling Ranger wanders off in pursuit of friends. L004B: return; // RETURN; } private void FnNPCCHATD_15(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: ShowMessage(player, doMsgs, String0906); // You encounter a Troll Cleric. L0010: ShowPortrait(player, 0x0028); L001D: Compare(GetRandom(0x000F), 0x0006); L002D: if (JumpAbove) goto L003E; L002F: ShowMessage(player, doMsgs, String0924); // Someone left a rune message on the floor. It said that to reach the King's Apartments, you must take a turn for the worse. I wonder if it means that you must be sick to find his quarters. L003C: goto L004B; L003E: ShowMessage(player, doMsgs, String09E0); // The Troll Cleric is too busy counting her blessings to speak to you. L004B: return; // RETURN; } private void FnNPCCHATE_16(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: ShowMessage(player, doMsgs, String0A25); // You encounter a Troll Knight. L0010: ShowPortrait(player, 0x001B); L001D: Compare(GetRandom(0x000F), 0x000B); L002D: if (JumpAbove) goto L003E; L002F: ShowMessage(player, doMsgs, String0A43); // A wise leader knows how to organize a party. Keep your fighters in front and your magicians safely in the rear. And as much as thieves are despised in general, they can serve you well, for their skills are impressive. L003C: goto L005C; L003E: ModifyGold(player, 0x000A); L004F: ShowMessage(player, doMsgs, String0B1D); // The Troll Knight gives you 10 Gold Pieces and departs in peace. L005C: return; // RETURN; } private void FnLOWMNSTR_17(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: Compare(PartyCount(player), 0x0001); L000E: if (JumpEqual) goto L001D; L0010: Compare(PartyCount(player), 0x0002); L001B: if (JumpNotEqual) goto L0043; L001D: AddEncounter(player, 0x01, 0x1A); L002F: AddEncounter(player, 0x02, 0x1A); L0041: goto L008B; L0043: AddEncounter(player, 0x01, 0x1A); L0055: AddEncounter(player, 0x02, 0x1A); L0067: AddEncounter(player, 0x03, 0x1B); L0079: AddEncounter(player, 0x04, 0x1B); L008B: return; // RETURN; } private void FnLWRMNSTR_18(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: ShowMessage(player, doMsgs, String0B5D); // You encounter Goblins. L0010: Compare(GetRandom(0x000F), 0x0004); L0020: if (JumpAbove) goto L0031; L0022: ShowMessage(player, doMsgs, String0B74); // You should be gracious to us Goblins, or we will tell our masters the Goblin Kings that you are cruel and deserve to die most horribly. L002F: goto L004B; L0031: ShowMessage(player, doMsgs, String0BFC); // The Goblins refuse to talk. L003E: ShowMessage(player, doMsgs, String0C18); // They draw their weapons and attack! L004B: Compare(PartyCount(player), 0x0001); L0056: if (JumpNotEqual) goto L007F; L0058: AddEncounter(player, 0x01, 0x1C); L006A: AddEncounter(player, 0x02, 0x1C); L007C: goto L011E; L007F: Compare(PartyCount(player), 0x0002); L008A: if (JumpNotEqual) goto L00C4; L008C: AddEncounter(player, 0x01, 0x1D); L009E: AddEncounter(player, 0x02, 0x1C); L00B0: AddEncounter(player, 0x03, 0x1C); L00C2: goto L011E; L00C4: AddEncounter(player, 0x01, 0x1E); L00D6: AddEncounter(player, 0x02, 0x1E); L00E8: AddEncounter(player, 0x03, 0x1D); L00FA: AddEncounter(player, 0x04, 0x1D); L010C: AddEncounter(player, 0x05, 0x1E); L011E: return; // RETURN; } private void FnOGREENC_19(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: Compare(PartyCount(player), 0x0001); L000E: if (JumpEqual) goto L001D; L0010: Compare(PartyCount(player), 0x0002); L001B: if (JumpNotEqual) goto L0055; L001D: AddEncounter(player, 0x01, 0x21); L002F: AddEncounter(player, 0x02, 0x28); L0041: AddEncounter(player, 0x03, 0x23); L0053: goto L00C1; L0055: AddEncounter(player, 0x01, 0x1F); L0067: AddEncounter(player, 0x02, 0x20); L0079: AddEncounter(player, 0x03, 0x21); L008B: AddEncounter(player, 0x04, 0x21); L009D: AddEncounter(player, 0x05, 0x23); L00AF: AddEncounter(player, 0x06, 0x28); L00C1: return; // RETURN; } private void FnTUFMNSTR_1A(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: ShowMessage(player, doMsgs, String0C3C); // You encounter Rogues. L0010: Compare(GetRandom(0x000F), 0x0003); L0020: if (JumpAbove) goto L0031; L0022: ShowMessage(player, doMsgs, String0C52); // Bizarre creatures haunt this dungeon. Many know magic. A great evil must exist somewhere in the dungeon to spawn such a neverending host of monsters. L002F: goto L004B; L0031: ShowMessage(player, doMsgs, String0CE8); // The Rogues refuse to talk. L003E: ShowMessage(player, doMsgs, String0D03); // They charge at you! L004B: Compare(PartyCount(player), 0x0001); L0056: if (JumpNotEqual) goto L006C; L0058: AddEncounter(player, 0x01, 0x22); L006A: goto L00E7; L006C: Compare(PartyCount(player), 0x0002); L0077: if (JumpNotEqual) goto L009F; L0079: AddEncounter(player, 0x01, 0x23); L008B: AddEncounter(player, 0x02, 0x23); L009D: goto L00E7; L009F: AddEncounter(player, 0x01, 0x24); L00B1: AddEncounter(player, 0x02, 0x24); L00C3: AddEncounter(player, 0x03, 0x23); L00D5: AddEncounter(player, 0x04, 0x23); L00E7: return; // RETURN; } private void FnSTRMNSTR_1B(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: ShowMessage(player, doMsgs, String0D17); // You encounter Rogues! L0010: ShowMessage(player, doMsgs, String0D2D); // The Rogues scowl at you and attack! L001D: Compare(PartyCount(player), 0x0001); L0028: if (JumpNotEqual) goto L003E; L002A: AddEncounter(player, 0x01, 0x28); L003C: goto L00B9; L003E: Compare(PartyCount(player), 0x0002); L0049: if (JumpNotEqual) goto L0071; L004B: AddEncounter(player, 0x01, 0x25); L005D: AddEncounter(player, 0x02, 0x27); L006F: goto L00B9; L0071: AddEncounter(player, 0x01, 0x27); L0083: AddEncounter(player, 0x02, 0x25); L0095: AddEncounter(player, 0x03, 0x28); L00A7: AddEncounter(player, 0x05, 0x26); L00B9: return; // RETURN; } private void FnWEAPENC_1C(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: Compare(GetFlag(player, FlagTypeDungeon, YsIndexes.FlagHallOfDoorsFoundSwords), 0x0001); L0017: if (JumpNotEqual) goto L0047; L0019: AddTreasure(player, 0x0190, 0x00, 0x00, 0x00, 0x00, 0xCE); L0038: ShowMessage(player, doMsgs, String0D51); // It looks like the Rogues you encounter have already looted the room. L0045: goto L0089; L0047: AddTreasure(player, 0x05DC, 0x00, 0x00, 0x00, 0x0C, 0x05); L0067: SetFlag(player, FlagTypeDungeon, YsIndexes.FlagHallOfDoorsFoundSwords, 0x01); L007C: ShowMessage(player, doMsgs, String0D96); // Rogues covet the Sword of the Flames and Sword of Decision you see lying on the floor. L0089: Compare(PartyCount(player), 0x0001); L0094: if (JumpNotEqual) goto L00AB; L0096: AddEncounter(player, 0x01, 0x26); L00A8: goto L017E; L00AB: Compare(PartyCount(player), 0x0002); L00B6: if (JumpNotEqual) goto L00DF; L00B8: AddEncounter(player, 0x01, 0x25); L00CA: AddEncounter(player, 0x02, 0x26); L00DC: goto L017E; L00DF: Compare(PartyCount(player), 0x0003); L00EA: if (JumpNotEqual) goto L0124; L00EC: AddEncounter(player, 0x01, 0x28); L00FE: AddEncounter(player, 0x02, 0x24); L0110: AddEncounter(player, 0x03, 0x25); L0122: goto L017E; L0124: AddEncounter(player, 0x01, 0x25); L0136: AddEncounter(player, 0x02, 0x27); L0148: AddEncounter(player, 0x03, 0x26); L015A: AddEncounter(player, 0x04, 0x27); L016C: AddEncounter(player, 0x05, 0x23); L017E: return; // RETURN; } private void FnGOLDENC_1D(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: Compare(GetFlag(player, FlagTypeDungeon, YsIndexes.FlagHallOfDoorsFoundGold), 0x0001); L0017: if (JumpNotEqual) goto L0047; L0019: AddTreasure(player, 0x0064, 0x00, 0x00, 0x00, 0x00, 0xCB); L0038: ShowMessage(player, doMsgs, String0DED); // Goblins grab their weapons as you enter the room. L0045: goto L0089; L0047: AddTreasure(player, 0x03E8, 0x00, 0x00, 0x00, 0xCB, 0xB5); L0067: SetFlag(player, FlagTypeDungeon, YsIndexes.FlagHallOfDoorsFoundGold, 0x01); L007C: ShowMessage(player, doMsgs, String0E1F); // Goblins are pitching Gold Pieces against the wall. L0089: Compare(PartyCount(player), 0x0001); L0094: if (JumpEqual) goto L00A3; L0096: Compare(PartyCount(player), 0x0002); L00A1: if (JumpNotEqual) goto L00C9; L00A3: AddEncounter(player, 0x01, 0x1D); L00B5: AddEncounter(player, 0x02, 0x1C); L00C7: goto L0111; L00C9: AddEncounter(player, 0x01, 0x1C); L00DB: AddEncounter(player, 0x02, 0x1C); L00ED: AddEncounter(player, 0x03, 0x1D); L00FF: AddEncounter(player, 0x04, 0x1D); L0111: return; // RETURN; } private void FnMAGICENC_1E(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: Compare(GetFlag(player, FlagTypeDungeon, YsIndexes.FlagHallOfDoorsFoundOgreItems), 0x0001); L0017: if (JumpNotEqual) goto L0048; L0019: AddTreasure(player, 0x0078, 0x00, 0x00, 0x00, 0xCB, 0xB5); L0039: ShowMessage(player, doMsgs, String0E52); // Ogres grimace in pleasure as you walk into their ambush. L0046: goto L008B; L0048: AddTreasure(player, 0x1388, 0x00, 0x00, 0xC5, 0x8A, 0x8E); L0069: SetFlag(player, FlagTypeDungeon, YsIndexes.FlagHallOfDoorsFoundOgreItems, 0x01); L007E: ShowMessage(player, doMsgs, String0E8B); // Ogres are playing with items you identify as the Ring of Vigor, a Cudgel Insignia, and the Wand of Radiance. L008B: Compare(PartyCount(player), 0x0001); L0096: if (JumpNotEqual) goto L00AD; L0098: AddEncounter(player, 0x01, 0x1F); L00AA: goto L0180; L00AD: Compare(PartyCount(player), 0x0002); L00B8: if (JumpNotEqual) goto L00E1; L00BA: AddEncounter(player, 0x01, 0x21); L00CC: AddEncounter(player, 0x02, 0x20); L00DE: goto L0180; L00E1: Compare(PartyCount(player), 0x0003); L00EC: if (JumpNotEqual) goto L0126; L00EE: AddEncounter(player, 0x01, 0x1F); L0100: AddEncounter(player, 0x02, 0x20); L0112: AddEncounter(player, 0x03, 0x21); L0124: goto L0180; L0126: AddEncounter(player, 0x01, 0x1F); L0138: AddEncounter(player, 0x02, 0x1F); L014A: AddEncounter(player, 0x03, 0x20); L015C: AddEncounter(player, 0x04, 0x20); L016E: AddEncounter(player, 0x05, 0x21); L0180: return; // RETURN; } } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. using System.Runtime.InteropServices; using System.Diagnostics.Contracts; namespace System { // Summary: // A platform-specific type that is used to represent a pointer or a handle. public unsafe struct UIntPtr { // Summary: // A read-only field that represents a pointer or handle that has been initialized // to zero. public static readonly UIntPtr Zero; // // Summary: // Initializes a new instance of the System.UIntPtr structure using the specified // 32-bit pointer or handle. // // Parameters: // value: // A pointer or handle contained in a 32-bit unsigned integer. public UIntPtr(uint value) { // // Summary: // Initializes a new instance of System.UIntPtr using the specified 64-bit pointer // or handle. // // Parameters: // value: // A pointer or handle contained in a 64-bit unsigned integer. // // Exceptions: // System.OverflowException: // On a 32-bit platform, value is too large to represent as an System.UIntPtr. return default(UIntPtr(uint); } public UIntPtr(ulong value) { // // Summary: // Initializes a new instance of System.UIntPtr using the specified pointer // to an unspecified type. // // Parameters: // value: // A pointer to an unspecified type. return default(UIntPtr(ulong); } public UIntPtr(void* value) { // Summary: // Determines whether two specified instances of System.UIntPtr are not equal. // // Parameters: // value1: // A System.UIntPtr. // // value2: // A System.UIntPtr. // // Returns: // true if value1 does not equal value2; otherwise, false. return default(UIntPtr(void*); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public static bool operator!=(UIntPtr value1, UIntPtr value2) { // // Summary: // Determines whether two specified instances of System.UIntPtr are equal. // // Parameters: // value1: // A System.UIntPtr. // // value2: // A System.UIntPtr. // // Returns: // true if value1 equals value2; otherwise, false. return default(bool); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public static bool operator==(UIntPtr value1, UIntPtr value2) { // // Summary: // Converts the value of a 32-bit unsigned integer to an System.UIntPtr. // // Parameters: // value: // A 32-bit unsigned integer. // // Returns: // A new instance of System.UIntPtr initialized to value. return default(bool); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public static explicit operator UIntPtr(uint value) { // // Summary: // Converts the value of the specified System.UIntPtr to a 32-bit unsigned integer. // // Parameters: // value: // A System.UIntPtr. // // Returns: // The contents of value. // // Exceptions: // System.OverflowException: // On a 64-bit platform, the value of value is too large to represent as a 32-bit // unsigned integer. return default(explicit); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public static explicit operator uint(UIntPtr value) { // // Summary: // Converts the value of the specified System.UIntPtr to a 64-bit unsigned integer. // // Parameters: // value: // A System.UIntPtr. // // Returns: // The contents of value. return default(explicit); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public static explicit operator ulong(UIntPtr value) { // // Summary: // Converts the value of the specified System.UIntPtr to a pointer to an unspecified // type. // // Parameters: // value: // A System.UIntPtr. // // Returns: // The contents of value. return default(explicit); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public static explicit operator void*(UIntPtr value) { // // Summary: // Converts the value of a 64-bit unsigned integer to an System.UIntPtr. // // Parameters: // value: // A 64-bit unsigned integer. // // Returns: // A new instance of System.UIntPtr initialized to value. // // Exceptions: // System.OverflowException: // On a 32-bit platform, value is too large to represent as an System.UIntPtr. return default(explicit); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public static explicit operator UIntPtr(ulong value) { // // Summary: // Converts the specified pointer to an unspecified type to a System.UIntPtr. // // Parameters: // value: // A pointer to an unspecified type. // // Returns: // A new instance of System.UIntPtr initialized to value. return default(explicit); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public static explicit operator UIntPtr(void* value) { // Summary: // Gets the size of this instance. // // Returns: // The size of a pointer or handle on this platform, measured in bytes. The // value of this property is 4 on a 32-bit platform, and 8 on a 64-bit platform. return default(explicit); } public static int Size { get; } // Summary: // Returns a value indicating whether this instance is equal to a specified // object. // // Parameters: // obj: // An object to compare with this instance or null. // // Returns: // true if obj is an instance of System.UIntPtr and equals the value of this // instance; otherwise, false. [Pure][Reads(ReadsAttribute.Reads.Nothing)] public override bool Equals(object obj) { // // Summary: // Returns the hash code for this instance. // // Returns: // A 32-bit signed integer hash code. return default(override); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public override int GetHashCode() { // // Summary: // Converts the value of this instance to a pointer to an unspecified type. // // Returns: // A pointer to System.Void; that is, a pointer to memory containing data of // an unspecified type. return default(override); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public void* ToPointer() { // // Summary: // Converts the numeric value of this instance to its equivalent string representation. // // Returns: // The string representation of the value of this instance. return default(void*); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public override string ToString() { // // Summary: // Converts the value of this instance to a 32-bit unsigned integer. // // Returns: // A 32-bit unsigned integer equal to the value of this instance. // // Exceptions: // System.OverflowException: // On a 64-bit platform, the value of this instance is too large to represent // as a 32-bit unsigned integer. return default(override); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public uint ToUInt32() { // // Summary: // Converts the value of this instance to a 64-bit unsigned integer. // // Returns: // A 64-bit unsigned integer equal to the value of this instance. return default(uint); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public ulong ToUInt64() { return default(ulong); } } }
using TestUtils; using System.Collections.Generic; using System.Linq; using NUnit.Framework; using GitHub.Unity; namespace UnitTests { [TestFixture] class GitStatusOutputProcessorTests : BaseOutputProcessorTests { [Test] public void ShouldParseDirtyWorkingTreeUntracked() { var output = new[] { "## master", " M GitHubVS.sln", "R README.md -> README2.md", " D deploy.cmd", @"A ""something added.txt""", "?? something.txt", null }; AssertProcessOutput(output, new GitStatus { LocalBranch = "master", Entries = new List<GitStatusEntry> { new GitStatusEntry("GitHubVS.sln", TestRootPath + @"\GitHubVS.sln", null, GitFileStatus.None, GitFileStatus.Modified), new GitStatusEntry("README2.md", TestRootPath + @"\README2.md", null, GitFileStatus.Renamed, GitFileStatus.None, "README.md"), new GitStatusEntry("deploy.cmd", TestRootPath + @"\deploy.cmd", null, GitFileStatus.None, GitFileStatus.Deleted), new GitStatusEntry("something added.txt", TestRootPath + @"\something added.txt", null, GitFileStatus.Added, GitFileStatus.None), new GitStatusEntry("something.txt", TestRootPath + @"\something.txt", null, GitFileStatus.Untracked, GitFileStatus.Untracked), }.OrderBy(entry => entry.Path, GitStatusOutputProcessor.StatusOutputPathComparer.Instance).ToList() }); } [Test] public void ShouldParseUnmergedStates() { var output = new[] { "## master", "DD something1.txt", "AU something2.txt", "UD something3.txt", "UA something4.txt", "DU something5.txt", "AA something6.txt", "UU something7.txt", null }; AssertProcessOutput(output, new GitStatus { LocalBranch = "master", Entries = new List<GitStatusEntry> { new GitStatusEntry("something1.txt", TestRootPath + @"\something1.txt", null, GitFileStatus.Deleted, GitFileStatus.Deleted), new GitStatusEntry("something2.txt", TestRootPath + @"\something2.txt", null, GitFileStatus.Added, GitFileStatus.Unmerged), new GitStatusEntry("something3.txt", TestRootPath + @"\something3.txt", null, GitFileStatus.Unmerged, GitFileStatus.Deleted), new GitStatusEntry("something4.txt", TestRootPath + @"\something4.txt", null, GitFileStatus.Unmerged, GitFileStatus.Added), new GitStatusEntry("something5.txt", TestRootPath + @"\something5.txt", null, GitFileStatus.Deleted, GitFileStatus.Unmerged), new GitStatusEntry("something6.txt", TestRootPath + @"\something6.txt", null, GitFileStatus.Added, GitFileStatus.Added), new GitStatusEntry("something7.txt", TestRootPath + @"\something7.txt", null, GitFileStatus.Unmerged, GitFileStatus.Unmerged), }.OrderBy(entry => entry.Path, GitStatusOutputProcessor.StatusOutputPathComparer.Instance).ToList() }); } [Test] public void ShouldParseDirtyWorkingTreeTrackedAhead1Behind1() { var output = new[] { "## master...origin/master [ahead 1, behind 1]", " M GitHubVS.sln", "R README.md -> README2.md", " D deploy.cmd", @"A ""something added.txt""", "?? something.txt", null }; AssertProcessOutput(output, new GitStatus { LocalBranch = "master", RemoteBranch = "origin/master", Ahead = 1, Behind = 1, Entries = new List<GitStatusEntry> { new GitStatusEntry("GitHubVS.sln", TestRootPath + @"\GitHubVS.sln", null, GitFileStatus.None, GitFileStatus.Modified), new GitStatusEntry("README2.md", TestRootPath + @"\README2.md", null, GitFileStatus.Renamed, GitFileStatus.None, "README.md"), new GitStatusEntry("deploy.cmd", TestRootPath + @"\deploy.cmd", null, GitFileStatus.None, GitFileStatus.Deleted), new GitStatusEntry("something added.txt", TestRootPath + @"\something added.txt", null, GitFileStatus.Added, GitFileStatus.None), new GitStatusEntry("something.txt", TestRootPath + @"\something.txt", null, GitFileStatus.Untracked, GitFileStatus.Untracked), }.OrderBy(entry => entry.Path, GitStatusOutputProcessor.StatusOutputPathComparer.Instance).ToList() }); } [Test] public void ShouldParseDirtyWorkingTreeTrackedAhead1() { var output = new[] { "## master...origin/master [ahead 1]", " M GitHubVS.sln", "R README.md -> README2.md", " D deploy.cmd", @"A ""something added.txt""", "?? something.txt", null }; AssertProcessOutput(output, new GitStatus { LocalBranch = "master", RemoteBranch = "origin/master", Ahead = 1, Entries = new List<GitStatusEntry> { new GitStatusEntry("GitHubVS.sln", TestRootPath + @"\GitHubVS.sln", null, GitFileStatus.None, GitFileStatus.Modified), new GitStatusEntry("README2.md", TestRootPath + @"\README2.md", null, GitFileStatus.Renamed, GitFileStatus.None, "README.md"), new GitStatusEntry("deploy.cmd", TestRootPath + @"\deploy.cmd", null, GitFileStatus.None, GitFileStatus.Deleted), new GitStatusEntry("something added.txt", TestRootPath + @"\something added.txt", null, GitFileStatus.Added, GitFileStatus.None), new GitStatusEntry("something.txt", TestRootPath + @"\something.txt", null, GitFileStatus.Untracked, GitFileStatus.Untracked), }.OrderBy(entry => entry.Path, GitStatusOutputProcessor.StatusOutputPathComparer.Instance).ToList() }); } [Test] public void ShouldParseDirtyWorkingTreeTrackedBehind1() { var output = new[] { "## master...origin/master [behind 1]", " M GitHubVS.sln", "R README.md -> README2.md", " D deploy.cmd", @"A ""something added.txt""", "?? something.txt", null }; AssertProcessOutput(output, new GitStatus { LocalBranch = "master", RemoteBranch = "origin/master", Behind = 1, Entries = new List<GitStatusEntry> { new GitStatusEntry("GitHubVS.sln", TestRootPath + @"\GitHubVS.sln", null, GitFileStatus.None, GitFileStatus.Modified), new GitStatusEntry("README2.md", TestRootPath + @"\README2.md", null, GitFileStatus.Renamed, GitFileStatus.None, "README.md"), new GitStatusEntry("deploy.cmd", TestRootPath + @"\deploy.cmd", null, GitFileStatus.None, GitFileStatus.Deleted), new GitStatusEntry("something added.txt", TestRootPath + @"\something added.txt", null, GitFileStatus.Added, GitFileStatus.None), new GitStatusEntry("something.txt", TestRootPath + @"\something.txt", null, GitFileStatus.Untracked, GitFileStatus.Untracked), }.OrderBy(entry => entry.Path, GitStatusOutputProcessor.StatusOutputPathComparer.Instance).ToList() }); } [Test] public void ShouldParseDirtyWorkingTreeTracked() { var output = new[] { "## master...origin/master", " M GitHubVS.sln", "R README.md -> README2.md", " D deploy.cmd", @"A ""something added.txt""", "?? something.txt", null }; AssertProcessOutput(output, new GitStatus { LocalBranch = "master", RemoteBranch = "origin/master", Entries = new List<GitStatusEntry> { new GitStatusEntry("GitHubVS.sln", TestRootPath + @"\GitHubVS.sln", null, GitFileStatus.None, GitFileStatus.Modified), new GitStatusEntry("README2.md", TestRootPath + @"\README2.md", null, GitFileStatus.Renamed, GitFileStatus.None, "README.md"), new GitStatusEntry("deploy.cmd", TestRootPath + @"\deploy.cmd", null, GitFileStatus.None, GitFileStatus.Deleted), new GitStatusEntry("something added.txt", TestRootPath + @"\something added.txt", null, GitFileStatus.Added, GitFileStatus.None), new GitStatusEntry("something.txt", TestRootPath + @"\something.txt", null, GitFileStatus.Untracked, GitFileStatus.Untracked), }.OrderBy(entry => entry.Path, GitStatusOutputProcessor.StatusOutputPathComparer.Instance).ToList() }); } [Test] public void ShouldParseCleanWorkingTreeUntracked() { var output = new[] { "## something", null }; AssertProcessOutput(output, new GitStatus { LocalBranch = "something", Entries = new List<GitStatusEntry>() }); } [Test] public void ShouldParseCleanWorkingTreeTrackedAhead1Behind1() { var output = new[] { "## master...origin/master [ahead 1, behind 1]", null }; AssertProcessOutput(output, new GitStatus { LocalBranch = "master", RemoteBranch = "origin/master", Ahead = 1, Behind = 1, Entries = new List<GitStatusEntry>() }); } [Test] public void ShouldParseCleanWorkingTreeTrackedAhead1() { var output = new[] { "## master...origin/master [ahead 1]", null }; AssertProcessOutput(output, new GitStatus { LocalBranch = "master", RemoteBranch = "origin/master", Ahead = 1, Entries = new List<GitStatusEntry>() }); } [Test] public void ShouldParseCleanWorkingTreeTrackedBehind1() { var output = new[] { "## master...origin/master [behind 1]", null }; AssertProcessOutput(output, new GitStatus { LocalBranch = "master", RemoteBranch = "origin/master", Behind = 1, Entries = new List<GitStatusEntry>() }); } [Test] public void ShouldParseCleanWorkingTreeTracked() { var output = new[] { "## master...origin/master", null }; AssertProcessOutput(output, new GitStatus { LocalBranch = "master", RemoteBranch = "origin/master", Entries = new List<GitStatusEntry>() }); } [Test] public void ShouldSortOutputCorrectly() { var output = new[] { "## master", "?? Assets/Assets.Test.dll.meta", "?? Assets/Assets.Test.dll", "?? Plugins/GitHub.Unity.dll", "?? Plugins/GitHub.Unity.dll.mdb", "?? Plugins/GitHub.Unity.dll.mdb.meta", "?? Plugins/GitHub.Unity2.dll", "?? Plugins/GitHub.Unity2.dll.mdb", "?? Plugins/GitHub.Unity2.dll.mdb.meta", "?? Plugins/GitHub.Unity2.dll.meta", "?? Plugins/GitHub.Unity.dll.meta", "?? blah.txt", null }; AssertProcessOutput(output, new GitStatus { LocalBranch = "master", Entries = new List<GitStatusEntry> { new GitStatusEntry(@"Assets/Assets.Test.dll", TestRootPath + @"\Assets/Assets.Test.dll", null, GitFileStatus.Untracked, GitFileStatus.Untracked), new GitStatusEntry(@"Assets/Assets.Test.dll.meta", TestRootPath + @"\Assets/Assets.Test.dll.meta", null, GitFileStatus.Untracked, GitFileStatus.Untracked), new GitStatusEntry(@"blah.txt", TestRootPath + @"\blah.txt", null, GitFileStatus.Untracked, GitFileStatus.Untracked), new GitStatusEntry(@"Plugins/GitHub.Unity.dll", TestRootPath + @"\Plugins/GitHub.Unity.dll", null, GitFileStatus.Untracked, GitFileStatus.Untracked), new GitStatusEntry(@"Plugins/GitHub.Unity.dll.meta", TestRootPath + @"\Plugins/GitHub.Unity.dll.meta", null, GitFileStatus.Untracked, GitFileStatus.Untracked), new GitStatusEntry(@"Plugins/GitHub.Unity.dll.mdb", TestRootPath + @"\Plugins/GitHub.Unity.dll.mdb", null, GitFileStatus.Untracked, GitFileStatus.Untracked), new GitStatusEntry(@"Plugins/GitHub.Unity.dll.mdb.meta", TestRootPath + @"\Plugins/GitHub.Unity.dll.mdb.meta", null, GitFileStatus.Untracked, GitFileStatus.Untracked), new GitStatusEntry(@"Plugins/GitHub.Unity2.dll", TestRootPath + @"\Plugins/GitHub.Unity2.dll", null, GitFileStatus.Untracked, GitFileStatus.Untracked), new GitStatusEntry(@"Plugins/GitHub.Unity2.dll.meta", TestRootPath + @"\Plugins/GitHub.Unity2.dll.meta", null, GitFileStatus.Untracked, GitFileStatus.Untracked), new GitStatusEntry(@"Plugins/GitHub.Unity2.dll.mdb", TestRootPath + @"\Plugins/GitHub.Unity2.dll.mdb", null, GitFileStatus.Untracked, GitFileStatus.Untracked), new GitStatusEntry(@"Plugins/GitHub.Unity2.dll.mdb.meta", TestRootPath + @"\Plugins/GitHub.Unity2.dll.mdb.meta", null, GitFileStatus.Untracked, GitFileStatus.Untracked), } }); } private void AssertProcessOutput(IEnumerable<string> lines, GitStatus expected) { var gitObjectFactory = SubstituteFactory.CreateGitObjectFactory(TestRootPath); GitStatus? result = null; var outputProcessor = new GitStatusOutputProcessor(gitObjectFactory); outputProcessor.OnEntry += status => { result = status; }; foreach (var line in lines) { outputProcessor.LineReceived(line); } Assert.IsTrue(result.HasValue); result.Value.AssertEqual(expected); } } }
using CrystalDecisions.CrystalReports.Engine; using CrystalDecisions.Windows.Forms; using DpSdkEngLib; using DPSDKOPSLib; using Microsoft.VisualBasic; using System; using System.Collections; using System.Collections.Generic; using System.Drawing; using System.Diagnostics; using System.Windows.Forms; using System.Linq; using System.Xml.Linq; namespace _4PosBackOffice.NET { [Microsoft.VisualBasic.CompilerServices.DesignerGenerated()] partial class frmCustomerAllocPaymentAmount { #region "Windows Form Designer generated code " [System.Diagnostics.DebuggerNonUserCode()] public frmCustomerAllocPaymentAmount() : base() { KeyPress += frmCustomerAllocPaymentAmount_KeyPress; //This call is required by the Windows Form Designer. InitializeComponent(); } //Form overrides dispose to clean up the component list. [System.Diagnostics.DebuggerNonUserCode()] protected override void Dispose(bool Disposing) { if (Disposing) { if ((components != null)) { components.Dispose(); } } base.Dispose(Disposing); } //Required by the Windows Form Designer private System.ComponentModel.IContainer components; public System.Windows.Forms.ToolTip ToolTip1; public System.Windows.Forms.TextBox txtPack; private System.Windows.Forms.TextBox withEventsField_txtPriceS; public System.Windows.Forms.TextBox txtPriceS { get { return withEventsField_txtPriceS; } set { if (withEventsField_txtPriceS != null) { withEventsField_txtPriceS.Enter -= txtPriceS_Enter; withEventsField_txtPriceS.Leave -= txtPriceS_Leave; } withEventsField_txtPriceS = value; if (withEventsField_txtPriceS != null) { withEventsField_txtPriceS.Enter += txtPriceS_Enter; withEventsField_txtPriceS.Leave += txtPriceS_Leave; } } } private System.Windows.Forms.TextBox withEventsField_txtPrice; public System.Windows.Forms.TextBox txtPrice { get { return withEventsField_txtPrice; } set { if (withEventsField_txtPrice != null) { withEventsField_txtPrice.Enter -= txtPrice_Enter; withEventsField_txtPrice.KeyPress -= txtPrice_KeyPress; withEventsField_txtPrice.Leave -= txtPrice_Leave; } withEventsField_txtPrice = value; if (withEventsField_txtPrice != null) { withEventsField_txtPrice.Enter += txtPrice_Enter; withEventsField_txtPrice.KeyPress += txtPrice_KeyPress; withEventsField_txtPrice.Leave += txtPrice_Leave; } } } private System.Windows.Forms.Button withEventsField_cmdCancel; public System.Windows.Forms.Button cmdCancel { get { return withEventsField_cmdCancel; } set { if (withEventsField_cmdCancel != null) { withEventsField_cmdCancel.Click -= cmdCancel_Click; } withEventsField_cmdCancel = value; if (withEventsField_cmdCancel != null) { withEventsField_cmdCancel.Click += cmdCancel_Click; } } } private System.Windows.Forms.Button withEventsField_cmdClose; public System.Windows.Forms.Button cmdClose { get { return withEventsField_cmdClose; } set { if (withEventsField_cmdClose != null) { withEventsField_cmdClose.Click -= cmdClose_Click; } withEventsField_cmdClose = value; if (withEventsField_cmdClose != null) { withEventsField_cmdClose.Click += cmdClose_Click; } } } public System.Windows.Forms.Panel picButtons; public System.Windows.Forms.Label Label2; public System.Windows.Forms.Label lblPComp; public System.Windows.Forms.Label lblSComp; public System.Windows.Forms.Label lblStockItemS; public System.Windows.Forms.Label _LBL_5; public System.Windows.Forms.Label _LBL_0; public System.Windows.Forms.Label _LBL_3; public System.Windows.Forms.Label _LBL_1; public System.Windows.Forms.Label lblStockItem; public Microsoft.VisualBasic.PowerPacks.RectangleShape _Shape1_2; public Microsoft.VisualBasic.PowerPacks.RectangleShape _Shape1_0; //Public WithEvents LBL As Microsoft.VisualBasic.Compatibility.VB6.LabelArray public RectangleShapeArray Shape1; public Microsoft.VisualBasic.PowerPacks.ShapeContainer ShapeContainer1; //NOTE: The following procedure is required by the Windows Form Designer //It can be modified using the Windows Form Designer. //Do not modify it using the code editor. [System.Diagnostics.DebuggerStepThrough()] private void InitializeComponent() { System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(frmCustomerAllocPaymentAmount)); this.components = new System.ComponentModel.Container(); this.ToolTip1 = new System.Windows.Forms.ToolTip(components); this.ShapeContainer1 = new Microsoft.VisualBasic.PowerPacks.ShapeContainer(); this.txtPack = new System.Windows.Forms.TextBox(); this.txtPriceS = new System.Windows.Forms.TextBox(); this.txtPrice = new System.Windows.Forms.TextBox(); this.picButtons = new System.Windows.Forms.Panel(); this.cmdCancel = new System.Windows.Forms.Button(); this.cmdClose = new System.Windows.Forms.Button(); this.Label2 = new System.Windows.Forms.Label(); this.lblPComp = new System.Windows.Forms.Label(); this.lblSComp = new System.Windows.Forms.Label(); this.lblStockItemS = new System.Windows.Forms.Label(); this._LBL_5 = new System.Windows.Forms.Label(); this._LBL_0 = new System.Windows.Forms.Label(); this._LBL_3 = new System.Windows.Forms.Label(); this._LBL_1 = new System.Windows.Forms.Label(); this.lblStockItem = new System.Windows.Forms.Label(); this._Shape1_2 = new Microsoft.VisualBasic.PowerPacks.RectangleShape(); this._Shape1_0 = new Microsoft.VisualBasic.PowerPacks.RectangleShape(); //Me.LBL = New Microsoft.VisualBasic.Compatibility.VB6.LabelArray(components) this.Shape1 = new RectangleShapeArray(components); this.picButtons.SuspendLayout(); this.SuspendLayout(); this.ToolTip1.Active = true; //CType(Me.LBL, System.ComponentModel.ISupportInitialize).BeginInit() ((System.ComponentModel.ISupportInitialize)this.Shape1).BeginInit(); this.BackColor = System.Drawing.Color.FromArgb(224, 224, 224); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.Text = "Allocate Partial Amount"; this.ClientSize = new System.Drawing.Size(400, 134); this.Location = new System.Drawing.Point(3, 22); this.ControlBox = false; this.KeyPreview = true; this.MaximizeBox = false; this.MinimizeBox = false; this.ShowInTaskbar = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Enabled = true; this.Cursor = System.Windows.Forms.Cursors.Default; this.RightToLeft = System.Windows.Forms.RightToLeft.No; this.HelpButton = false; this.WindowState = System.Windows.Forms.FormWindowState.Normal; this.Name = "frmCustomerAllocPaymentAmount"; this.txtPack.AutoSize = false; this.txtPack.Size = new System.Drawing.Size(41, 19); this.txtPack.Location = new System.Drawing.Point(352, 136); this.txtPack.TabIndex = 14; this.txtPack.Text = "0"; this.txtPack.Visible = false; this.txtPack.AcceptsReturn = true; this.txtPack.TextAlign = System.Windows.Forms.HorizontalAlignment.Left; this.txtPack.BackColor = System.Drawing.SystemColors.Window; this.txtPack.CausesValidation = true; this.txtPack.Enabled = true; this.txtPack.ForeColor = System.Drawing.SystemColors.WindowText; this.txtPack.HideSelection = true; this.txtPack.ReadOnly = false; this.txtPack.MaxLength = 0; this.txtPack.Cursor = System.Windows.Forms.Cursors.IBeam; this.txtPack.Multiline = false; this.txtPack.RightToLeft = System.Windows.Forms.RightToLeft.No; this.txtPack.ScrollBars = System.Windows.Forms.ScrollBars.None; this.txtPack.TabStop = true; this.txtPack.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.txtPack.Name = "txtPack"; this.txtPriceS.AutoSize = false; this.txtPriceS.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this.txtPriceS.Enabled = false; this.txtPriceS.Size = new System.Drawing.Size(91, 19); this.txtPriceS.Location = new System.Drawing.Point(291, 210); this.txtPriceS.TabIndex = 6; this.txtPriceS.Text = "0.00"; this.txtPriceS.Visible = false; this.txtPriceS.AcceptsReturn = true; this.txtPriceS.BackColor = System.Drawing.SystemColors.Window; this.txtPriceS.CausesValidation = true; this.txtPriceS.ForeColor = System.Drawing.SystemColors.WindowText; this.txtPriceS.HideSelection = true; this.txtPriceS.ReadOnly = false; this.txtPriceS.MaxLength = 0; this.txtPriceS.Cursor = System.Windows.Forms.Cursors.IBeam; this.txtPriceS.Multiline = false; this.txtPriceS.RightToLeft = System.Windows.Forms.RightToLeft.No; this.txtPriceS.ScrollBars = System.Windows.Forms.ScrollBars.None; this.txtPriceS.TabStop = true; this.txtPriceS.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.txtPriceS.Name = "txtPriceS"; this.txtPrice.AutoSize = false; this.txtPrice.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this.txtPrice.Size = new System.Drawing.Size(91, 19); this.txtPrice.Location = new System.Drawing.Point(293, 79); this.txtPrice.TabIndex = 3; this.txtPrice.Text = "0.00"; this.txtPrice.AcceptsReturn = true; this.txtPrice.BackColor = System.Drawing.SystemColors.Window; this.txtPrice.CausesValidation = true; this.txtPrice.Enabled = true; this.txtPrice.ForeColor = System.Drawing.SystemColors.WindowText; this.txtPrice.HideSelection = true; this.txtPrice.ReadOnly = false; this.txtPrice.MaxLength = 0; this.txtPrice.Cursor = System.Windows.Forms.Cursors.IBeam; this.txtPrice.Multiline = false; this.txtPrice.RightToLeft = System.Windows.Forms.RightToLeft.No; this.txtPrice.ScrollBars = System.Windows.Forms.ScrollBars.None; this.txtPrice.TabStop = true; this.txtPrice.Visible = true; this.txtPrice.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.txtPrice.Name = "txtPrice"; this.picButtons.Dock = System.Windows.Forms.DockStyle.Top; this.picButtons.BackColor = System.Drawing.Color.Blue; this.picButtons.Size = new System.Drawing.Size(400, 39); this.picButtons.Location = new System.Drawing.Point(0, 0); this.picButtons.TabIndex = 0; this.picButtons.TabStop = false; this.picButtons.CausesValidation = true; this.picButtons.Enabled = true; this.picButtons.ForeColor = System.Drawing.SystemColors.ControlText; this.picButtons.Cursor = System.Windows.Forms.Cursors.Default; this.picButtons.RightToLeft = System.Windows.Forms.RightToLeft.No; this.picButtons.Visible = true; this.picButtons.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.picButtons.Name = "picButtons"; this.cmdCancel.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.cmdCancel.Text = "&Undo"; this.cmdCancel.Size = new System.Drawing.Size(73, 29); this.cmdCancel.Location = new System.Drawing.Point(8, 3); this.cmdCancel.TabIndex = 13; this.cmdCancel.TabStop = false; this.cmdCancel.BackColor = System.Drawing.SystemColors.Control; this.cmdCancel.CausesValidation = true; this.cmdCancel.Enabled = true; this.cmdCancel.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdCancel.Cursor = System.Windows.Forms.Cursors.Default; this.cmdCancel.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdCancel.Name = "cmdCancel"; this.cmdClose.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.cmdClose.Text = "E&xit"; this.cmdClose.Size = new System.Drawing.Size(73, 29); this.cmdClose.Location = new System.Drawing.Point(312, 3); this.cmdClose.TabIndex = 1; this.cmdClose.TabStop = false; this.cmdClose.BackColor = System.Drawing.SystemColors.Control; this.cmdClose.CausesValidation = true; this.cmdClose.Enabled = true; this.cmdClose.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdClose.Cursor = System.Windows.Forms.Cursors.Default; this.cmdClose.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdClose.Name = "cmdClose"; this.Label2.Text = "Please verify products from both locations"; this.Label2.ForeColor = System.Drawing.Color.FromArgb(192, 0, 0); this.Label2.Size = new System.Drawing.Size(296, 23); this.Label2.Location = new System.Drawing.Point(56, 136); this.Label2.TabIndex = 12; this.Label2.TextAlign = System.Drawing.ContentAlignment.TopLeft; this.Label2.BackColor = System.Drawing.Color.Transparent; this.Label2.Enabled = true; this.Label2.Cursor = System.Windows.Forms.Cursors.Default; this.Label2.RightToLeft = System.Windows.Forms.RightToLeft.No; this.Label2.UseMnemonic = true; this.Label2.Visible = true; this.Label2.AutoSize = false; this.Label2.BorderStyle = System.Windows.Forms.BorderStyle.None; this.Label2.Name = "Label2"; this.lblPComp.Text = "Allocate "; this.lblPComp.Size = new System.Drawing.Size(352, 24); this.lblPComp.Location = new System.Drawing.Point(16, 52); this.lblPComp.TabIndex = 11; this.lblPComp.TextAlign = System.Drawing.ContentAlignment.TopLeft; this.lblPComp.BackColor = System.Drawing.Color.Transparent; this.lblPComp.Enabled = true; this.lblPComp.ForeColor = System.Drawing.SystemColors.ControlText; this.lblPComp.Cursor = System.Windows.Forms.Cursors.Default; this.lblPComp.RightToLeft = System.Windows.Forms.RightToLeft.No; this.lblPComp.UseMnemonic = true; this.lblPComp.Visible = true; this.lblPComp.AutoSize = false; this.lblPComp.BorderStyle = System.Windows.Forms.BorderStyle.None; this.lblPComp.Name = "lblPComp"; this.lblSComp.Text = "Promotion Name:"; this.lblSComp.Size = new System.Drawing.Size(360, 24); this.lblSComp.Location = new System.Drawing.Point(16, 168); this.lblSComp.TabIndex = 10; this.lblSComp.TextAlign = System.Drawing.ContentAlignment.TopLeft; this.lblSComp.BackColor = System.Drawing.Color.Transparent; this.lblSComp.Enabled = true; this.lblSComp.ForeColor = System.Drawing.SystemColors.ControlText; this.lblSComp.Cursor = System.Windows.Forms.Cursors.Default; this.lblSComp.RightToLeft = System.Windows.Forms.RightToLeft.No; this.lblSComp.UseMnemonic = true; this.lblSComp.Visible = true; this.lblSComp.AutoSize = false; this.lblSComp.BorderStyle = System.Windows.Forms.BorderStyle.None; this.lblSComp.Name = "lblSComp"; this.lblStockItemS.Text = "Label1"; this.lblStockItemS.Size = new System.Drawing.Size(286, 17); this.lblStockItemS.Location = new System.Drawing.Point(98, 192); this.lblStockItemS.TabIndex = 9; this.lblStockItemS.TextAlign = System.Drawing.ContentAlignment.TopLeft; this.lblStockItemS.BackColor = System.Drawing.SystemColors.Control; this.lblStockItemS.Enabled = true; this.lblStockItemS.ForeColor = System.Drawing.SystemColors.ControlText; this.lblStockItemS.Cursor = System.Windows.Forms.Cursors.Default; this.lblStockItemS.RightToLeft = System.Windows.Forms.RightToLeft.No; this.lblStockItemS.UseMnemonic = true; this.lblStockItemS.Visible = true; this.lblStockItemS.AutoSize = false; this.lblStockItemS.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.lblStockItemS.Name = "lblStockItemS"; this._LBL_5.TextAlign = System.Drawing.ContentAlignment.TopRight; this._LBL_5.Text = "Stock Item Name:"; this._LBL_5.Size = new System.Drawing.Size(85, 13); this._LBL_5.Location = new System.Drawing.Point(10, 192); this._LBL_5.TabIndex = 8; this._LBL_5.BackColor = System.Drawing.Color.Transparent; this._LBL_5.Enabled = true; this._LBL_5.ForeColor = System.Drawing.SystemColors.ControlText; this._LBL_5.Cursor = System.Windows.Forms.Cursors.Default; this._LBL_5.RightToLeft = System.Windows.Forms.RightToLeft.No; this._LBL_5.UseMnemonic = true; this._LBL_5.Visible = true; this._LBL_5.AutoSize = true; this._LBL_5.BorderStyle = System.Windows.Forms.BorderStyle.None; this._LBL_5.Name = "_LBL_5"; this._LBL_0.TextAlign = System.Drawing.ContentAlignment.TopRight; this._LBL_0.Text = "Price:"; this._LBL_0.Size = new System.Drawing.Size(27, 13); this._LBL_0.Location = new System.Drawing.Point(260, 213); this._LBL_0.TabIndex = 7; this._LBL_0.Visible = false; this._LBL_0.BackColor = System.Drawing.Color.Transparent; this._LBL_0.Enabled = true; this._LBL_0.ForeColor = System.Drawing.SystemColors.ControlText; this._LBL_0.Cursor = System.Windows.Forms.Cursors.Default; this._LBL_0.RightToLeft = System.Windows.Forms.RightToLeft.No; this._LBL_0.UseMnemonic = true; this._LBL_0.AutoSize = true; this._LBL_0.BorderStyle = System.Windows.Forms.BorderStyle.None; this._LBL_0.Name = "_LBL_0"; this._LBL_3.TextAlign = System.Drawing.ContentAlignment.TopRight; this._LBL_3.Text = "Allocate :"; this._LBL_3.Size = new System.Drawing.Size(44, 13); this._LBL_3.Location = new System.Drawing.Point(245, 79); this._LBL_3.TabIndex = 5; this._LBL_3.BackColor = System.Drawing.Color.Transparent; this._LBL_3.Enabled = true; this._LBL_3.ForeColor = System.Drawing.SystemColors.ControlText; this._LBL_3.Cursor = System.Windows.Forms.Cursors.Default; this._LBL_3.RightToLeft = System.Windows.Forms.RightToLeft.No; this._LBL_3.UseMnemonic = true; this._LBL_3.Visible = true; this._LBL_3.AutoSize = true; this._LBL_3.BorderStyle = System.Windows.Forms.BorderStyle.None; this._LBL_3.Name = "_LBL_3"; this._LBL_1.TextAlign = System.Drawing.ContentAlignment.TopRight; this._LBL_1.Text = "Available :"; this._LBL_1.Size = new System.Drawing.Size(49, 13); this._LBL_1.Location = new System.Drawing.Point(46, 79); this._LBL_1.TabIndex = 4; this._LBL_1.BackColor = System.Drawing.Color.Transparent; this._LBL_1.Enabled = true; this._LBL_1.ForeColor = System.Drawing.SystemColors.ControlText; this._LBL_1.Cursor = System.Windows.Forms.Cursors.Default; this._LBL_1.RightToLeft = System.Windows.Forms.RightToLeft.No; this._LBL_1.UseMnemonic = true; this._LBL_1.Visible = true; this._LBL_1.AutoSize = true; this._LBL_1.BorderStyle = System.Windows.Forms.BorderStyle.None; this._LBL_1.Name = "_LBL_1"; this.lblStockItem.TextAlign = System.Drawing.ContentAlignment.TopRight; this.lblStockItem.Text = "Label1"; this.lblStockItem.Size = new System.Drawing.Size(110, 17); this.lblStockItem.Location = new System.Drawing.Point(98, 79); this.lblStockItem.TabIndex = 2; this.lblStockItem.BackColor = System.Drawing.SystemColors.Control; this.lblStockItem.Enabled = true; this.lblStockItem.ForeColor = System.Drawing.SystemColors.ControlText; this.lblStockItem.Cursor = System.Windows.Forms.Cursors.Default; this.lblStockItem.RightToLeft = System.Windows.Forms.RightToLeft.No; this.lblStockItem.UseMnemonic = true; this.lblStockItem.Visible = true; this.lblStockItem.AutoSize = false; this.lblStockItem.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.lblStockItem.Name = "lblStockItem"; this._Shape1_2.BackColor = System.Drawing.Color.FromArgb(192, 192, 255); this._Shape1_2.BackStyle = Microsoft.VisualBasic.PowerPacks.BackStyle.Opaque; this._Shape1_2.Size = new System.Drawing.Size(383, 80); this._Shape1_2.Location = new System.Drawing.Point(7, 48); this._Shape1_2.BorderColor = System.Drawing.SystemColors.WindowText; this._Shape1_2.BorderStyle = System.Drawing.Drawing2D.DashStyle.Solid; this._Shape1_2.BorderWidth = 1; this._Shape1_2.FillColor = System.Drawing.Color.Black; this._Shape1_2.FillStyle = Microsoft.VisualBasic.PowerPacks.FillStyle.Transparent; this._Shape1_2.Visible = true; this._Shape1_2.Name = "_Shape1_2"; this._Shape1_0.BackColor = System.Drawing.Color.FromArgb(192, 192, 255); this._Shape1_0.BackStyle = Microsoft.VisualBasic.PowerPacks.BackStyle.Opaque; this._Shape1_0.Size = new System.Drawing.Size(383, 56); this._Shape1_0.Location = new System.Drawing.Point(7, 160); this._Shape1_0.BorderColor = System.Drawing.SystemColors.WindowText; this._Shape1_0.BorderStyle = System.Drawing.Drawing2D.DashStyle.Solid; this._Shape1_0.BorderWidth = 1; this._Shape1_0.FillColor = System.Drawing.Color.Black; this._Shape1_0.FillStyle = Microsoft.VisualBasic.PowerPacks.FillStyle.Transparent; this._Shape1_0.Visible = true; this._Shape1_0.Name = "_Shape1_0"; this.Controls.Add(txtPack); this.Controls.Add(txtPriceS); this.Controls.Add(txtPrice); this.Controls.Add(picButtons); this.Controls.Add(Label2); this.Controls.Add(lblPComp); this.Controls.Add(lblSComp); this.Controls.Add(lblStockItemS); this.Controls.Add(_LBL_5); this.Controls.Add(_LBL_0); this.Controls.Add(_LBL_3); this.Controls.Add(_LBL_1); this.Controls.Add(lblStockItem); this.ShapeContainer1.Shapes.Add(_Shape1_2); this.ShapeContainer1.Shapes.Add(_Shape1_0); this.Controls.Add(ShapeContainer1); this.picButtons.Controls.Add(cmdCancel); this.picButtons.Controls.Add(cmdClose); //Me.LBL.SetIndex(_LBL_5, CType(5, Short)) //Me.LBL.SetIndex(_LBL_0, CType(0, Short)) //Me.LBL.SetIndex(_LBL_3, CType(3, Short)) //Me.LBL.SetIndex(_LBL_1, CType(1, Short)) this.Shape1.SetIndex(_Shape1_2, Convert.ToInt16(2)); this.Shape1.SetIndex(_Shape1_0, Convert.ToInt16(0)); ((System.ComponentModel.ISupportInitialize)this.Shape1).EndInit(); //CType(Me.LBL, System.ComponentModel.ISupportInitialize).EndInit() this.picButtons.ResumeLayout(false); this.ResumeLayout(false); this.PerformLayout(); } #endregion } }
using System; using System.Collections.Generic; using System.Data; using System.Linq; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Http; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Swashbuckle.AspNetCore.Annotations; using HetsApi.Authorization; using HetsApi.Helpers; using HetsApi.Model; using HetsData.Helpers; using HetsData.Model; namespace HetsApi.Controllers { /// <summary> /// Project Controller /// </summary> [Route("api/projects")] [ResponseCache(Location = ResponseCacheLocation.None, NoStore = true)] public class ProjectController : Controller { private readonly DbAppContext _context; private readonly IConfiguration _configuration; private readonly HttpContext _httpContext; public ProjectController(DbAppContext context, IConfiguration configuration, IHttpContextAccessor httpContextAccessor) { _context = context; _configuration = configuration; _httpContext = httpContextAccessor.HttpContext; // set context data HetUser user = UserAccountHelper.GetUser(context, httpContextAccessor.HttpContext); _context.SmUserId = user.SmUserId; _context.DirectoryName = user.SmAuthorizationDirectory; _context.SmUserGuid = user.Guid; } /// <summary> /// Get project by id /// </summary> /// <param name="id">id of Project to fetch</param> [HttpGet] [Route("{id}")] [SwaggerOperation("ProjectsIdGet")] [SwaggerResponse(200, type: typeof(HetProject))] [RequiresPermission(HetPermission.Login)] public virtual IActionResult ProjectsIdGet([FromRoute]int id) { return new ObjectResult(new HetsResponse(ProjectHelper.GetRecord(id, _context))); } /// <summary> /// Update project /// </summary> /// <param name="id">id of Project to update</param> /// <param name="item"></param> [HttpPut] [Route("{id}")] [SwaggerOperation("ProjectsIdPut")] [SwaggerResponse(200, type: typeof(HetProject))] [RequiresPermission(HetPermission.Login)] public virtual IActionResult ProjectsIdPut([FromRoute]int id, [FromBody]HetProject item) { if (item == null || id != item.ProjectId) { // not found return new ObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))); } bool exists = _context.HetProject.Any(a => a.ProjectId == id); // not found if (!exists) return new ObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))); // get record HetProject project = _context.HetProject.First(a => a.ProjectId == id); int? statusId = StatusHelper.GetStatusId(item.Status, "projectStatus", _context); if (statusId == null) { throw new DataException("Status Id cannot be null"); } project.ConcurrencyControlNumber = item.ConcurrencyControlNumber; project.Name = item.Name; project.ProvincialProjectNumber = item.ProvincialProjectNumber; project.ProjectStatusTypeId = (int)statusId; project.Information = item.Information; // save the changes _context.SaveChanges(); // retrieve updated project record to return to ui return new ObjectResult(new HetsResponse(ProjectHelper.GetRecord(id, _context))); } /// <summary> /// Create project /// </summary> /// <param name="item"></param> [HttpPost] [Route("")] [SwaggerOperation("ProjectsPost")] [SwaggerResponse(200, type: typeof(HetProject))] [RequiresPermission(HetPermission.Login)] public virtual IActionResult ProjectsPost([FromBody]HetProject item) { // not found if (item == null) return new ObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))); // check if this an update project if (item.ProjectId > 0) return new ObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))); int? statusId = StatusHelper.GetStatusId(item.Status, "projectStatus", _context); if (statusId == null) { throw new DataException("Status Id cannot be null"); } HetProject project = new HetProject { Name = item.Name, ProvincialProjectNumber = item.ProvincialProjectNumber, ProjectStatusTypeId = (int)statusId, Information = item.Information }; _context.HetProject.Add(project); // save record _context.SaveChanges(); int id = project.ProjectId; // retrieve updated project record to return to ui return new ObjectResult(new HetsResponse(ProjectHelper.GetRecord(id, _context))); } #region Project Search /// <summary> /// Searches Projects /// </summary> /// <remarks>Used for the project search page.</remarks> /// <param name="districts">Districts (comma separated list of id numbers)</param> /// <param name="project">name or partial name for a Project</param> /// <param name="hasRequests">if true then only include Projects with active Requests</param> /// <param name="hasHires">if true then only include Projects with active Rental Agreements</param> /// <param name="status">if included, filter the results to those with a status matching this string</param> /// <param name="projectNumber"></param> [HttpGet] [Route("search")] [SwaggerOperation("ProjectsSearchGet")] [SwaggerResponse(200, type: typeof(List<ProjectLite>))] [RequiresPermission(HetPermission.Login)] public virtual IActionResult ProjectsSearchGet([FromQuery]string districts, [FromQuery]string project, [FromQuery]bool? hasRequests, [FromQuery]bool? hasHires, [FromQuery]string status, [FromQuery]string projectNumber) { int?[] districtTokens = ArrayHelper.ParseIntArray(districts); // get initial results - must be limited to user's district int? districtId = UserAccountHelper.GetUsersDistrictId(_context, _httpContext); IQueryable<HetProject> data = _context.HetProject.AsNoTracking() .Include(x => x.ProjectStatusType) .Include(x => x.District.Region) .Include(x => x.PrimaryContact) .Include(x => x.HetRentalAgreement) .Include(x => x.HetRentalRequest) .Where(x => x.DistrictId.Equals(districtId)); if (districtTokens != null && districts.Length > 0) { data = data.Where(x => districtTokens.Contains(x.District.DistrictId)); } if (project != null) { data = data.Where(x => x.Name.ToLowerInvariant().Contains(project.ToLowerInvariant())); } if (status != null) { int? statusId = StatusHelper.GetStatusId(status, "projectStatus", _context); if (statusId != null) { data = data.Where(x => x.ProjectStatusTypeId == statusId); } } if (projectNumber != null) { // allow for case insensitive search of project name data = data.Where(x => string.Equals(x.ProvincialProjectNumber, projectNumber, StringComparison.CurrentCultureIgnoreCase)); } // convert Project Model to the "ProjectLite" Model List<ProjectLite> result = new List<ProjectLite>(); foreach (HetProject item in data) { result.Add(ProjectHelper.ToLiteModel(item)); } // return to the client return new ObjectResult(new HetsResponse(result)); } #endregion # region Clone Project Agreements /// <summary> /// Get rental agreements associated with a project by id /// </summary> /// <remarks>Gets a Projects Rental Agreements</remarks> /// <param name="id">id of Project to fetch agreements for</param> [HttpGet] [Route("{id}/rentalAgreements")] [SwaggerOperation("ProjectsIdRentalAgreementsGet")] [SwaggerResponse(200, type: typeof(List<HetRentalAgreement>))] [RequiresPermission(HetPermission.Login)] public virtual IActionResult ProjectsIdRentalAgreementsGet([FromRoute]int id) { bool exists = _context.HetProject.Any(a => a.ProjectId == id); // not found if (!exists) return new ObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))); List<HetRentalAgreement> agreements = _context.HetProject.AsNoTracking() .Include(x => x.ProjectStatusType) .Include(x => x.HetRentalAgreement) .ThenInclude(e => e.Equipment) .ThenInclude(d => d.DistrictEquipmentType) .Include(x => x.HetRentalAgreement) .ThenInclude(e => e.Equipment) .ThenInclude(a => a.HetEquipmentAttachment) .Include(x => x.HetRentalAgreement) .ThenInclude(e => e.RentalAgreementStatusType) .First(x => x.ProjectId == id) .HetRentalAgreement .ToList(); return new ObjectResult(new HetsResponse(agreements)); } /// <summary> /// Update a rental agreement by cloning a previous project rental agreement /// </summary> /// <param name="id">Project id</param> /// <param name="item"></param> [HttpPost] [Route("{id}/rentalAgreementClone")] [SwaggerOperation("ProjectsRentalAgreementClonePost")] [SwaggerResponse(200, type: typeof(HetRentalAgreement))] [RequiresPermission(HetPermission.Login)] public virtual IActionResult ProjectsRentalAgreementClonePost([FromRoute]int id, [FromBody]ProjectRentalAgreementClone item) { // not found if (item == null || id != item.ProjectId) return new ObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))); bool exists = _context.HetProject.Any(a => a.ProjectId == id); // not found if (!exists) return new ObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))); // get all agreements for this project HetProject project = _context.HetProject .Include(x => x.ProjectStatusType) .Include(x => x.HetRentalAgreement) .ThenInclude(y => y.HetRentalAgreementRate) .Include(x => x.HetRentalAgreement) .ThenInclude(y => y.HetRentalAgreementCondition) .Include(x => x.HetRentalAgreement) .ThenInclude(e => e.RentalAgreementStatusType) .Include(x => x.HetRentalAgreement) .ThenInclude(y => y.HetTimeRecord) .First(a => a.ProjectId == id); List<HetRentalAgreement> agreements = project.HetRentalAgreement.ToList(); // check that the rental agreements exist exists = agreements.Any(a => a.RentalAgreementId == item.RentalAgreementId); // (RENTAL AGREEMENT) not found if (!exists) return new ObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))); // check that the rental agreement to clone exist exists = agreements.Any(a => a.RentalAgreementId == item.AgreementToCloneId); // (RENTAL AGREEMENT) not found if (!exists) return new ObjectResult(new HetsResponse("HETS-11", ErrorViewModel.GetDescription("HETS-11", _configuration))); int agreementToCloneIndex = agreements.FindIndex(a => a.RentalAgreementId == item.AgreementToCloneId); int newRentalAgreementIndex = agreements.FindIndex(a => a.RentalAgreementId == item.RentalAgreementId); // ****************************************************************** // Business Rules in the backend: // *Can't clone into an Agreement if it isn't Active // *Can't clone into an Agreement if it has existing time records // ****************************************************************** if (!agreements[newRentalAgreementIndex].Status .Equals("Active", StringComparison.InvariantCultureIgnoreCase)) { // (RENTAL AGREEMENT) is not active return new ObjectResult(new HetsResponse("HETS-12", ErrorViewModel.GetDescription("HETS-12", _configuration))); } if (agreements[newRentalAgreementIndex].HetTimeRecord != null && agreements[newRentalAgreementIndex].HetTimeRecord.Count > 0) { // (RENTAL AGREEMENT) has time records return new ObjectResult(new HetsResponse("HETS-13", ErrorViewModel.GetDescription("HETS-13", _configuration))); } // ****************************************************************** // clone agreement // ****************************************************************** agreements[newRentalAgreementIndex].EquipmentRate = agreements[agreementToCloneIndex].EquipmentRate; agreements[newRentalAgreementIndex].Note = agreements[agreementToCloneIndex].Note; agreements[newRentalAgreementIndex].RateComment = agreements[agreementToCloneIndex].RateComment; agreements[newRentalAgreementIndex].RatePeriodTypeId = agreements[agreementToCloneIndex].RatePeriodTypeId; // update rates agreements[newRentalAgreementIndex].HetRentalAgreementRate = null; foreach (HetRentalAgreementRate rate in agreements[agreementToCloneIndex].HetRentalAgreementRate) { HetRentalAgreementRate temp = new HetRentalAgreementRate { Comment = rate.Comment, ComponentName = rate.ComponentName, Rate = rate.Rate, RatePeriodTypeId = rate.RatePeriodTypeId, IsIncludedInTotal = rate.IsIncludedInTotal, IsAttachment = rate.IsAttachment, PercentOfEquipmentRate = rate.PercentOfEquipmentRate }; if (agreements[newRentalAgreementIndex].HetRentalAgreementRate == null) { agreements[newRentalAgreementIndex].HetRentalAgreementRate = new List<HetRentalAgreementRate>(); } agreements[newRentalAgreementIndex].HetRentalAgreementRate.Add(temp); } // update conditions agreements[newRentalAgreementIndex].HetRentalAgreementCondition = null; foreach (HetRentalAgreementCondition condition in agreements[agreementToCloneIndex].HetRentalAgreementCondition) { HetRentalAgreementCondition temp = new HetRentalAgreementCondition { Comment = condition.Comment, ConditionName = condition.ConditionName }; if (agreements[newRentalAgreementIndex].HetRentalAgreementCondition == null) { agreements[newRentalAgreementIndex].HetRentalAgreementCondition = new List<HetRentalAgreementCondition>(); } agreements[newRentalAgreementIndex].HetRentalAgreementCondition.Add(temp); } // save the changes _context.SaveChanges(); // ****************************************************************** // return update rental agreement to update the screen // ****************************************************************** HetRentalAgreement result = _context.HetRentalAgreement.AsNoTracking() .Include(x => x.Equipment) .ThenInclude(y => y.Owner) .Include(x => x.Equipment) .ThenInclude(y => y.DistrictEquipmentType) .ThenInclude(d => d.EquipmentType) .Include(x => x.Equipment) .ThenInclude(y => y.HetEquipmentAttachment) .Include(x => x.Equipment) .ThenInclude(y => y.LocalArea.ServiceArea.District.Region) .Include(x => x.Project) .ThenInclude(p => p.District.Region) .Include(x => x.HetRentalAgreementCondition) .Include(x => x.HetRentalAgreementRate) .Include(x => x.HetTimeRecord) .First(a => a.RentalAgreementId == item.RentalAgreementId); return new ObjectResult(new HetsResponse(result)); } #endregion #region Project Time Records /// <summary> /// Get time records associated with a project /// </summary> /// <remarks>Gets a Projects Time Records</remarks> /// <param name="id">id of Project to fetch Time Records for</param> [HttpGet] [Route("{id}/timeRecords")] [SwaggerOperation("ProjectIdTimeRecordsGet")] [SwaggerResponse(200, type: typeof(List<HetTimeRecord>))] [RequiresPermission(HetPermission.Login)] public virtual IActionResult HetProjectIdTimeRecordsGet([FromRoute]int id) { bool exists = _context.HetProject.Any(a => a.ProjectId == id); if (!exists) return new ObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))); HetProject project = _context.HetProject.AsNoTracking() .Include(x => x.HetRentalAgreement) .ThenInclude(t => t.HetTimeRecord) .First(x => x.ProjectId == id); // create a single array of all time records List<HetTimeRecord> timeRecords = new List<HetTimeRecord>(); foreach (HetRentalAgreement rentalAgreement in project.HetRentalAgreement) { timeRecords.AddRange(rentalAgreement.HetTimeRecord); } return new ObjectResult(new HetsResponse(timeRecords)); } /// <summary> /// Add a project time record /// </summary> /// <remarks>Adds Project Time Records</remarks> /// <param name="id">id of Project to add a time record for</param> /// <param name="item">Adds to Project Time Records</param> [HttpPost] [Route("{id}/timeRecord")] [SwaggerOperation("ProjectsIdTimeRecordsPost")] [SwaggerResponse(200, type: typeof(HetTimeRecord))] [RequiresPermission(HetPermission.Login)] public virtual IActionResult ProjectsIdTimeRecordsPost([FromRoute]int id, [FromBody]HetTimeRecord item) { bool exists = _context.HetProject.Any(a => a.ProjectId == id); // not found if (!exists) return new ObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))); // get project record HetProject project = _context.HetProject.AsNoTracking() .Include(x => x.HetRentalAgreement) .ThenInclude(t => t.HetTimeRecord) .First(x => x.ProjectId == id); List<HetRentalAgreement> agreements = project.HetRentalAgreement.ToList(); // ****************************************************************** // must have a valid rental agreement id // ****************************************************************** if (item.RentalAgreement.RentalAgreementId == 0) { // (RENTAL AGREEMENT) record not found return new ObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))); } exists = agreements.Any(a => a.RentalAgreementId == item.RentalAgreement.RentalAgreementId); if (!exists) { // (RENTAL AGREEMENT) record not found return new ObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))); } // ****************************************************************** // add or update time record // ****************************************************************** int rentalAgreementId = item.RentalAgreement.RentalAgreementId; if (item.TimeRecordId > 0) { // get time record HetTimeRecord time = _context.HetTimeRecord.FirstOrDefault(x => x.TimeRecordId == item.TimeRecordId); // not found if (time == null) return new ObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))); time.ConcurrencyControlNumber = item.ConcurrencyControlNumber; time.RentalAgreementId = rentalAgreementId; time.EnteredDate = DateTime.UtcNow; time.Hours = item.Hours; // set the time period type id int? timePeriodTypeId = StatusHelper.GetTimePeriodId(item.TimePeriod, _context); if (timePeriodTypeId == null) { throw new DataException("Time Period Id cannot be null"); } time.TimePeriodTypeId = (int)timePeriodTypeId; time.WorkedDate = item.WorkedDate; } else // add time record { HetTimeRecord time = new HetTimeRecord { RentalAgreementId = rentalAgreementId, EnteredDate = DateTime.UtcNow, Hours = item.Hours, TimePeriod = item.TimePeriod, WorkedDate = item.WorkedDate }; _context.HetTimeRecord.Add(time); } // save record _context.SaveChanges(); // ************************************************************* // return updated time records // ************************************************************* project = _context.HetProject.AsNoTracking() .Include(x => x.HetRentalAgreement) .ThenInclude(t => t.HetTimeRecord) .First(x => x.ProjectId == id); // create a single array of all time records List<HetTimeRecord> timeRecords = new List<HetTimeRecord>(); foreach (HetRentalAgreement rentalAgreement in project.HetRentalAgreement) { timeRecords.AddRange(rentalAgreement.HetTimeRecord); } return new ObjectResult(new HetsResponse(timeRecords)); } /// <summary> /// Update or create an array of time records associated with a project /// </summary> /// <remarks>Adds Project Time Records</remarks> /// <param name="id">id of Project to add a time record for</param> /// <param name="items">Array of Project Time Records</param> [HttpPost] [Route("{id}/timeRecords")] [SwaggerOperation("ProjectsIdTimeRecordsBulkPostAsync")] [SwaggerResponse(200, type: typeof(HetTimeRecord))] [RequiresPermission(HetPermission.Login)] public virtual IActionResult ProjectsIdTimeRecordsBulkPostAsync([FromRoute]int id, [FromBody]HetTimeRecord[] items) { bool exists = _context.HetProject.Any(a => a.ProjectId == id); // not found if (!exists) return new ObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))); // get project record HetProject project = _context.HetProject.AsNoTracking() .Include(x => x.HetRentalAgreement) .ThenInclude(t => t.HetTimeRecord) .First(x => x.ProjectId == id); List<HetRentalAgreement> agreements = project.HetRentalAgreement.ToList(); // ****************************************************************** // process each time record // ****************************************************************** foreach (HetTimeRecord item in items) { // must have a valid rental agreement id if (item.RentalAgreement.RentalAgreementId == 0) { // (RENTAL AGREEMENT) record not found return new ObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))); } exists = agreements.Any(a => a.RentalAgreementId == item.RentalAgreement.RentalAgreementId); if (!exists) { // (RENTAL AGREEMENT) record not found return new ObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))); } // add or update time record int rentalAgreementId = item.RentalAgreement.RentalAgreementId; if (item.TimeRecordId > 0) { // get time record HetTimeRecord time = _context.HetTimeRecord.FirstOrDefault(x => x.TimeRecordId == item.TimeRecordId); // not found if (time == null) return new ObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))); time.ConcurrencyControlNumber = item.ConcurrencyControlNumber; time.RentalAgreementId = rentalAgreementId; time.EnteredDate = DateTime.UtcNow; time.Hours = item.Hours; time.TimePeriod = item.TimePeriod; time.WorkedDate = item.WorkedDate; } else // add time record { HetTimeRecord time = new HetTimeRecord { RentalAgreementId = rentalAgreementId, EnteredDate = DateTime.UtcNow, Hours = item.Hours, TimePeriod = item.TimePeriod, WorkedDate = item.WorkedDate }; _context.HetTimeRecord.Add(time); } // save record _context.SaveChanges(); } // ************************************************************* // return updated time records // ************************************************************* project = _context.HetProject.AsNoTracking() .Include(x => x.HetRentalAgreement) .ThenInclude(t => t.HetTimeRecord) .First(x => x.ProjectId == id); // create a single array of all time records List<HetTimeRecord> timeRecords = new List<HetTimeRecord>(); foreach (HetRentalAgreement rentalAgreement in project.HetRentalAgreement) { timeRecords.AddRange(rentalAgreement.HetTimeRecord); } return new ObjectResult(new HetsResponse(timeRecords)); } #endregion #region Project Equipment /// <summary> /// Get equipment associated with a project /// </summary> /// <remarks>Gets a Projects Equipment</remarks> /// <param name="id">id of Project to fetch Equipment for</param> [HttpGet] [Route("{id}/equipment")] [SwaggerOperation("ProjectsIdEquipmentGet")] [SwaggerResponse(200, type: typeof(List<HetRentalAgreement>))] [RequiresPermission(HetPermission.Login)] public virtual IActionResult ProjectsIdEquipmentGet([FromRoute]int id) { bool exists = _context.HetProject.Any(a => a.ProjectId == id); if (!exists) return new ObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))); HetProject project = _context.HetProject.AsNoTracking() .Include(x => x.HetRentalAgreement) .ThenInclude(e => e.Equipment) .ThenInclude(o => o.Owner) .ThenInclude(c => c.PrimaryContact) .First(x => x.ProjectId == id); return new ObjectResult(new HetsResponse(project.HetRentalAgreement)); } #endregion #region Project Attachments /// <summary> /// Get attachments associated with a project /// </summary> /// <remarks>Returns attachments for a particular Project</remarks> /// <param name="id">id of Project to fetch attachments for</param> [HttpGet] [Route("{id}/attachments")] [SwaggerOperation("ProjectsIdAttachmentsGet")] [SwaggerResponse(200, type: typeof(List<HetDigitalFile>))] [RequiresPermission(HetPermission.Login)] public virtual IActionResult ProjectsIdAttachmentsGet([FromRoute]int id) { bool exists = _context.HetProject.Any(a => a.ProjectId == id); // not found if (!exists) return new ObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))); HetProject project = _context.HetProject.AsNoTracking() .Include(x => x.HetDigitalFile) .First(a => a.ProjectId == id); // extract the attachments and update properties for UI List<HetDigitalFile> attachments = new List<HetDigitalFile>(); foreach (HetDigitalFile attachment in project.HetDigitalFile) { if (attachment != null) { attachment.FileSize = attachment.FileContents.Length; attachment.LastUpdateTimestamp = attachment.AppLastUpdateTimestamp; attachment.LastUpdateUserid = attachment.AppLastUpdateUserid; attachments.Add(attachment); } } return new ObjectResult(new HetsResponse(attachments)); } #endregion #region Project Contacts /// <summary> /// Get contacts associated with a project /// </summary> /// <remarks>Gets an Projects Contacts</remarks> /// <param name="id">id of Project to fetch Contacts for</param> [HttpGet] [Route("{id}/contacts")] [SwaggerOperation("ProjectsIdContactsGet")] [SwaggerResponse(200, type: typeof(List<HetContact>))] [RequiresPermission(HetPermission.Login)] public virtual IActionResult ProjectsIdContactsGet([FromRoute]int id) { bool exists = _context.HetProject.Any(a => a.ProjectId == id); // not found if (!exists) return new ObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))); HetProject project = _context.HetProject.AsNoTracking() .Include(x => x.HetContact) .First(a => a.ProjectId == id); return new ObjectResult(new HetsResponse(project.HetContact.ToList())); } /// <summary> /// Add a project contact /// </summary> /// <remarks>Adds Project Contact</remarks> /// <param name="id">id of Project to add a contact for</param> /// <param name="primary">is this the primary contact</param> /// <param name="item">Adds to Project Contact</param> [HttpPost] [Route("{id}/contacts/{primary}")] [SwaggerOperation("ProjectsIdContactsPost")] [SwaggerResponse(200, type: typeof(HetContact))] [RequiresPermission(HetPermission.Login)] public virtual IActionResult ProjectsIdContactsPost([FromRoute]int id, [FromBody]HetContact item, bool primary) { bool exists = _context.HetProject.Any(a => a.ProjectId == id); // not found if (!exists || item == null) return new ObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))); int contactId; // get project record HetProject project = _context.HetProject .Include(x => x.HetContact) .First(a => a.ProjectId == id); // add or update contact if (item.ContactId > 0) { HetContact contact = project.HetContact.FirstOrDefault(a => a.ContactId == item.ContactId); // not found if (contact == null) return new ObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))); contactId = item.ContactId; contact.ConcurrencyControlNumber = item.ConcurrencyControlNumber; contact.ProjectId = project.ProjectId; contact.Notes = item.Notes; contact.Address1 = item.Address1; contact.Address2 = item.Address2; contact.City = item.City; contact.EmailAddress = item.EmailAddress; contact.FaxPhoneNumber = item.FaxPhoneNumber; contact.GivenName = item.GivenName; contact.MobilePhoneNumber = item.MobilePhoneNumber; contact.PostalCode = item.PostalCode; contact.Province = item.Province; contact.Surname = item.Surname; contact.Role = item.Role; if (primary) { project.PrimaryContactId = contactId; } } else // add contact { HetContact contact = new HetContact { ProjectId = project.ProjectId, Notes = item.Notes, Address1 = item.Address1, Address2 = item.Address2, City = item.City, EmailAddress = item.EmailAddress, FaxPhoneNumber = item.FaxPhoneNumber, GivenName = item.GivenName, MobilePhoneNumber = item.MobilePhoneNumber, PostalCode = item.PostalCode, Province = item.Province, Surname = item.Surname, Role = item.Role }; _context.HetContact.Add(contact); _context.SaveChanges(); contactId = contact.ContactId; if (primary) { project.PrimaryContactId = contactId; } } _context.SaveChanges(); // get updated contact record HetProject updatedProject = _context.HetProject.AsNoTracking() .Include(x => x.HetContact) .First(a => a.ProjectId == id); HetContact updatedContact = updatedProject.HetContact .FirstOrDefault(a => a.ContactId == contactId); return new ObjectResult(new HetsResponse(updatedContact)); } /// <summary> /// Update all project contacts /// </summary> /// <remarks>Replaces an Project&#39;s Contacts</remarks> /// <param name="id">id of Project to replace Contacts for</param> /// <param name="items">Replacement Project contacts.</param> [HttpPut] [Route("{id}/contacts")] [SwaggerOperation("ProjectsIdContactsPut")] [SwaggerResponse(200, type: typeof(List<HetContact>))] [RequiresPermission(HetPermission.Login)] public virtual IActionResult ProjectsIdContactsPut([FromRoute]int id, [FromBody]HetContact[] items) { bool exists = _context.HetProject.Any(a => a.ProjectId == id); // not found if (!exists || items == null) return new ObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))); // get project record HetProject project = _context.HetProject.AsNoTracking() .Include(x => x.HetContact) .First(a => a.ProjectId == id); // adjust the incoming list for (int i = 0; i < items.Length; i++) { HetContact item = items[i]; if (item != null) { bool contactExists = _context.HetContact.Any(x => x.ContactId == item.ContactId); if (contactExists) { HetContact temp = _context.HetContact.First(x => x.ContactId == item.ContactId); temp.ConcurrencyControlNumber = item.ConcurrencyControlNumber; temp.ProjectId = id; temp.Notes = item.Notes; temp.Address1 = item.Address1; temp.Address2 = item.Address2; temp.City = item.City; temp.EmailAddress = item.EmailAddress; temp.FaxPhoneNumber = item.FaxPhoneNumber; temp.GivenName = item.GivenName; temp.MobilePhoneNumber = item.MobilePhoneNumber; temp.PostalCode = item.PostalCode; temp.Province = item.Province; temp.Surname = item.Surname; temp.Role = item.Role; items[i] = temp; } else { HetContact temp = new HetContact { ProjectId = id, Notes = item.Notes, Address1 = item.Address1, Address2 = item.Address2, City = item.City, EmailAddress = item.EmailAddress, FaxPhoneNumber = item.FaxPhoneNumber, GivenName = item.GivenName, MobilePhoneNumber = item.MobilePhoneNumber, PostalCode = item.PostalCode, Province = item.Province, Surname = item.Surname, Role = item.Role }; project.HetContact.Add(temp); items[i] = temp; } } } // remove contacts that are no longer attached. foreach (HetContact contact in project.HetContact) { if (contact != null && items.All(x => x.ContactId != contact.ContactId)) { _context.HetContact.Remove(contact); } } // save changes _context.SaveChanges(); // get updated contact records HetProject updatedProject = _context.HetProject.AsNoTracking() .Include(x => x.HetContact) .First(a => a.ProjectId == id); return new ObjectResult(new HetsResponse(updatedProject.HetContact.ToList())); } #endregion #region Project History /// <summary> /// Get history associated with a project /// </summary> /// <remarks>Returns History for a particular Project</remarks> /// <param name="id">id of Project to fetch History for</param> /// <param name="offset">offset for records that are returned</param> /// <param name="limit">limits the number of records returned.</param> [HttpGet] [Route("{id}/history")] [SwaggerOperation("ProjectsIdHistoryGet")] [SwaggerResponse(200, type: typeof(List<HetHistory>))] [RequiresPermission(HetPermission.Login)] public virtual IActionResult ProjectsIdHistoryGet([FromRoute]int id, [FromQuery]int? offset, [FromQuery]int? limit) { bool exists = _context.HetProject.Any(a => a.ProjectId == id); // not found if (!exists) return new ObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))); return new ObjectResult(new HetsResponse(ProjectHelper.GetHistoryRecords(id, offset, limit, _context))); } /// <summary> /// Create project history /// </summary> /// <remarks>Add a History record to the Project</remarks> /// <param name="id">id of Project to fetch History for</param> /// <param name="item"></param> [HttpPost] [Route("{id}/history")] [SwaggerOperation("ProjectsIdHistoryPost")] [RequiresPermission(HetPermission.Login)] public virtual IActionResult ProjectsIdHistoryPost([FromRoute]int id, [FromBody]HetHistory item) { bool exists = _context.HetProject.Any(a => a.ProjectId == id); if (exists) { HetProject project = _context.HetProject.AsNoTracking() .First(a => a.ProjectId == id); HetHistory history = new HetHistory { HistoryId = 0, HistoryText = item.HistoryText, CreatedDate = item.CreatedDate, ProjectId = project.ProjectId }; _context.HetHistory.Add(history); _context.SaveChanges(); } return new ObjectResult(new HetsResponse(EquipmentHelper.GetHistoryRecords(id, null, null, _context))); } #endregion #region Project Note Records /// <summary> /// Get note records associated with project /// </summary> /// <param name="id">id of Project to fetch Notes for</param> [HttpGet] [Route("{id}/notes")] [SwaggerOperation("ProjectsIdNotesGet")] [SwaggerResponse(200, type: typeof(List<HetNote>))] [RequiresPermission(HetPermission.Login)] public virtual IActionResult ProjectsIdNotesGet([FromRoute]int id) { bool exists = _context.HetProject.Any(a => a.ProjectId == id); // not found if (!exists) return new ObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))); HetProject project = _context.HetProject.AsNoTracking() .Include(x => x.HetNote) .First(x => x.ProjectId == id); List<HetNote> notes = new List<HetNote>(); foreach (HetNote note in project.HetNote) { if (note.IsNoLongerRelevant == false) { notes.Add(note); } } return new ObjectResult(new HetsResponse(notes)); } /// <summary> /// Update or create a note associated with a project /// </summary> /// <remarks>Update a Projects Notes</remarks> /// <param name="id">id of Project to update Notes for</param> /// <param name="item">Project Note</param> [HttpPost] [Route("{id}/note")] [SwaggerOperation("ProjectsIdNotePost")] [SwaggerResponse(200, type: typeof(HetNote))] [RequiresPermission(HetPermission.Login)] public virtual IActionResult ProjectsIdNotePost([FromRoute]int id, [FromBody]HetNote item) { bool exists = _context.HetProject.Any(a => a.ProjectId == id); // not found if (!exists) return new ObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))); HetProject project = _context.HetProject.AsNoTracking() .Include(x => x.HetNote) .First(x => x.ProjectId == id); // add or update note if (item.NoteId > 0) { // get note HetNote note = _context.HetNote.FirstOrDefault(a => a.NoteId == item.NoteId); // not found if (note == null) return new ObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))); note.ConcurrencyControlNumber = item.ConcurrencyControlNumber; note.ProjectId = project.ProjectId; note.Text = item.Text; note.IsNoLongerRelevant = item.IsNoLongerRelevant; } else // add note { HetNote note = new HetNote { ProjectId = project.ProjectId, Text = item.Text, IsNoLongerRelevant = item.IsNoLongerRelevant }; _context.HetNote.Add(note); } _context.SaveChanges(); // return updated note records project = _context.HetProject.AsNoTracking() .Include(x => x.HetNote) .First(x => x.ProjectId == id); List<HetNote> notes = new List<HetNote>(); foreach (HetNote note in project.HetNote) { if (note.IsNoLongerRelevant == false) { notes.Add(note); } } return new ObjectResult(new HetsResponse(notes)); } #endregion } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace IoTService.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); } } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using bstrkr.core; using bstrkr.core.config; using bstrkr.core.consts; using bstrkr.core.services.location; using bstrkr.mvvm.messages; using Cirrious.MvvmCross.Plugins.Messenger; using Cirrious.MvvmCross.ViewModels; namespace bstrkr.mvvm.viewmodels { public class HomeViewModel : BusTrackerViewModelBase { private readonly IBusTrackerLocationService _locationService; private readonly IAreaPositioningService _areaPositioningService; private readonly IMvxMessenger _messenger; private readonly MvxSubscriptionToken _taskChangedMessagesSubscription; private readonly IConfigManager _configManager; private readonly IList<AreaViewModel> _areas = new List<AreaViewModel>(); private readonly IDictionary<Type, MenuSection> _menuSection2ViewModel = new Dictionary<Type, MenuSection> { { typeof(MapViewModel), MenuSection.Map }, { typeof(RoutesViewModel), MenuSection.Routes }, { typeof(RouteStopsViewModel), MenuSection.RouteStops }, { typeof(PreferencesViewModel), MenuSection.Preferences }, { typeof(AboutViewModel), MenuSection.About } }; private AreaViewModel _currentArea; private MenuSection _selectedMenuSection; private string _title = AppResources.map_view_title; public HomeViewModel( IMvxMessenger messenger, IBusTrackerLocationService busTrackerLocationService, IAreaPositioningService areaPositioningService, IConfigManager configManager) { this.MenuItems = new ReadOnlyObservableCollection<MenuViewModel>(this.CreateMenuViewModels()); this.SelectMenuItemCommand = new MvxCommand<MenuSection>(this.SelectMenuItem); _messenger = messenger; _configManager = configManager; _areaPositioningService = areaPositioningService; _locationService = busTrackerLocationService; _locationService.AreaChanged += (s, a) => this.UpdateSelectedArea(a.Area); _taskChangedMessagesSubscription = _messenger.Subscribe<BackgroundTaskStateChangedMessage>(this.OnBackgroundTaskStateChanged); Areas = new ReadOnlyCollection<AreaViewModel>(_areas); this.UpdateVehicleLocationsCommand = new MvxCommand(this.UpdateVehicleLocations); this.SelectAreaCommand = new MvxCommand<int>(this.SelectArea); } public MvxCommand UpdateVehicleLocationsCommand { get; private set; } public MvxCommand<int> SelectAreaCommand { get; private set; } public ReadOnlyObservableCollection<MenuViewModel> MenuItems { get; private set; } public IReadOnlyList<AreaViewModel> Areas { get; } public AreaViewModel CurrentArea { get { return _currentArea; } private set { if (_currentArea != value) { _currentArea = value; this.RaisePropertyChanged(() => this.CurrentArea); this.RaisePropertyChanged(() => this.CurrentAreaIndex); } } } public int CurrentAreaIndex { get { if (this.CurrentArea == null) { return -1; } var area = _areas.FirstOrDefault(x => x.Area.Id.Equals(this.CurrentArea.Area.Id)); if (area == null) { return -1; } return _areas.IndexOf(area); } } public MvxCommand<MenuSection> SelectMenuItemCommand { get; private set; } public string Title { get { return _title; } private set { this.RaiseAndSetIfChanged(ref _title, value, () => this.Title); } } public MenuSection GetSectionForViewModelType(Type type) { if (_menuSection2ViewModel.ContainsKey(type)) { return _menuSection2ViewModel[type]; } return MenuSection.Unknown; } public override void Start() { base.Start(); this.FillAreas(); this.UpdateSelectedArea(_locationService.CurrentArea); } private void FillAreas() { var areaVMs = _configManager.GetConfig() .Areas .Select(a => new AreaViewModel(a, this[string.Format(AppConsts.AreaLocalizedNameStringKeyFormat, a.Id)])) .ToList(); foreach (var vm in areaVMs) { _areas.Add(vm); } } private ObservableCollection<MenuViewModel> CreateMenuViewModels() { return new ObservableCollection<MenuViewModel> { new MenuViewModel { Title = AppResources.map_view_title, Section = MenuSection.Map }, new MenuViewModel { Title = AppResources.routes_view_title, Section = MenuSection.Routes }, new MenuViewModel { Title = AppResources.route_stops_view_title, Section = MenuSection.RouteStops }, new MenuViewModel { Title = AppResources.preferences_view_title, Section = MenuSection.Preferences }, new MenuViewModel { Title = AppResources.about_view_title, Section = MenuSection.About } }; } private void SelectMenuItem(MenuSection menuSection) { switch (menuSection) { case MenuSection.Map: this.ShowViewModel<MapViewModel>(); _selectedMenuSection = MenuSection.Map; break; case MenuSection.Routes: this.ShowViewModel<RoutesViewModel>(); _selectedMenuSection = MenuSection.Routes; this.IsBusy = false; break; case MenuSection.RouteStops: this.ShowViewModel<RouteStopsViewModel>(); _selectedMenuSection = MenuSection.RouteStops; this.IsBusy = false; break; case MenuSection.Preferences: this.ShowViewModel<PreferencesViewModel>(); _selectedMenuSection = MenuSection.Preferences; this.IsBusy = false; break; case MenuSection.About: this.ShowViewModel<AboutViewModel>(); _selectedMenuSection = MenuSection.About; this.IsBusy = false; break; } } private void UpdateSelectedArea(Area area) { if (area == null) { this.CurrentArea = null; this.Title = AppResources.map_view_title; } else { this.CurrentArea = _areas.FirstOrDefault(a => a.Area.Id.Equals(area.Id)); if (this.CurrentArea != null) { this.Title = this.CurrentArea.Name; } } } private void OnBackgroundTaskStateChanged(BackgroundTaskStateChangedMessage message) { if (_selectedMenuSection == MenuSection.Map) { this.IsBusy = message.TaskState == BackgroundTaskState.Running; } } private void UpdateVehicleLocations() { _messenger.Publish(new VehicleLocationsUpdateRequestMessage(this)); } private void SelectArea(int areaIndex) { if (areaIndex != this.CurrentAreaIndex && areaIndex >= 0 && areaIndex < _areas.Count) { _areaPositioningService.SelectArea(_areas[areaIndex].Area); } } } }
// 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.ComponentModel; using System.Globalization; using System.Runtime.InteropServices; using System.Threading; using Microsoft.Win32.SafeHandles; namespace System.Diagnostics { internal static partial class ProcessManager { /// <summary>Gets whether the process with the specified ID is currently running.</summary> /// <param name="processId">The process ID.</param> /// <returns>true if the process is running; otherwise, false.</returns> public static bool IsProcessRunning(int processId) { return IsProcessRunning(processId, "."); } /// <summary>Gets whether the process with the specified ID on the specified machine is currently running.</summary> /// <param name="processId">The process ID.</param> /// <param name="machineName">The machine name.</param> /// <returns>true if the process is running; otherwise, false.</returns> public static bool IsProcessRunning(int processId, string machineName) { // Performance optimization for the local machine: // First try to OpenProcess by id, if valid handle is returned, the process is definitely running // Otherwise enumerate all processes and compare ids if (!IsRemoteMachine(machineName)) { using (SafeProcessHandle processHandle = Interop.Kernel32.OpenProcess(Interop.Advapi32.ProcessOptions.PROCESS_QUERY_INFORMATION, false, processId)) { if (!processHandle.IsInvalid) { return true; } } } return Array.IndexOf(GetProcessIds(machineName), processId) >= 0; } /// <summary>Gets the ProcessInfo for the specified process ID on the specified machine.</summary> /// <param name="processId">The process ID.</param> /// <param name="machineName">The machine name.</param> /// <returns>The ProcessInfo for the process if it could be found; otherwise, null.</returns> public static ProcessInfo GetProcessInfo(int processId, string machineName) { ProcessInfo[] processInfos = ProcessManager.GetProcessInfos(machineName); foreach (ProcessInfo processInfo in processInfos) { if (processInfo.ProcessId == processId) { return processInfo; } } return null; } /// <summary>Gets process infos for each process on the specified machine.</summary> /// <param name="machineName">The target machine.</param> /// <returns>An array of process infos, one per found process.</returns> public static ProcessInfo[] GetProcessInfos(string machineName) { return IsRemoteMachine(machineName) ? NtProcessManager.GetProcessInfos(machineName, true) : NtProcessInfoHelper.GetProcessInfos(); // Do not use performance counter for local machine } /// <summary>Gets the IDs of all processes on the specified machine.</summary> /// <param name="machineName">The machine to examine.</param> /// <returns>An array of process IDs from the specified machine.</returns> public static int[] GetProcessIds(string machineName) { // Due to the lack of support for EnumModules() on coresysserver, we rely // on PerformanceCounters to get the ProcessIds for both remote desktop // and the local machine, unlike Desktop on which we rely on PCs only for // remote machines. return IsRemoteMachine(machineName) ? NtProcessManager.GetProcessIds(machineName, true) : GetProcessIds(); } /// <summary>Gets the IDs of all processes on the current machine.</summary> public static int[] GetProcessIds() { return NtProcessManager.GetProcessIds(); } /// <summary>Gets the ID of a process from a handle to the process.</summary> /// <param name="processHandle">The handle.</param> /// <returns>The process ID.</returns> public static int GetProcessIdFromHandle(SafeProcessHandle processHandle) { return NtProcessManager.GetProcessIdFromHandle(processHandle); } /// <summary>Gets an array of module infos for the specified process.</summary> /// <param name="processId">The ID of the process whose modules should be enumerated.</param> /// <returns>The array of modules.</returns> public static ProcessModuleCollection GetModules(int processId) { return NtProcessManager.GetModules(processId); } private static bool IsRemoteMachineCore(string machineName) { string baseName; if (machineName.StartsWith("\\", StringComparison.Ordinal)) baseName = machineName.Substring(2); else baseName = machineName; if (baseName.Equals(".")) return false; return !string.Equals(Interop.Kernel32.GetComputerName(), baseName, StringComparison.OrdinalIgnoreCase); } public static IntPtr GetMainWindowHandle(int processId) { MainWindowFinder finder = new MainWindowFinder(); return finder.FindMainWindow(processId); } // ----------------------------- // ---- PAL layer ends here ---- // ----------------------------- static ProcessManager() { // In order to query information (OpenProcess) on some protected processes // like csrss, we need SeDebugPrivilege privilege. // After removing the dependency on Performance Counter, we don't have a chance // to run the code in CLR performance counter to ask for this privilege. // So we will try to get the privilege here. // We could fail if the user account doesn't have right to do this, but that's fair. Interop.Advapi32.LUID luid = new Interop.Advapi32.LUID(); if (!Interop.Advapi32.LookupPrivilegeValue(null, Interop.Advapi32.SeDebugPrivilege, out luid)) { return; } SafeTokenHandle tokenHandle = null; try { if (!Interop.Advapi32.OpenProcessToken( Interop.Kernel32.GetCurrentProcess(), Interop.Kernel32.HandleOptions.TOKEN_ADJUST_PRIVILEGES, out tokenHandle)) { return; } Interop.Advapi32.TokenPrivileges tp = new Interop.Advapi32.TokenPrivileges(); tp.Luid = luid; tp.Attributes = Interop.Advapi32.SEPrivileges.SE_PRIVILEGE_ENABLED; // AdjustTokenPrivileges can return true even if it didn't succeed (when ERROR_NOT_ALL_ASSIGNED is returned). Interop.Advapi32.AdjustTokenPrivileges(tokenHandle, false, tp, 0, IntPtr.Zero, IntPtr.Zero); } finally { if (tokenHandle != null) { tokenHandle.Dispose(); } } } public static SafeProcessHandle OpenProcess(int processId, int access, bool throwIfExited) { SafeProcessHandle processHandle = Interop.Kernel32.OpenProcess(access, false, processId); int result = Marshal.GetLastWin32Error(); if (!processHandle.IsInvalid) { return processHandle; } if (processId == 0) { throw new Win32Exception(5); } // If the handle is invalid because the process has exited, only throw an exception if throwIfExited is true. if (!IsProcessRunning(processId)) { if (throwIfExited) { throw new InvalidOperationException(SR.Format(SR.ProcessHasExited, processId.ToString(CultureInfo.CurrentCulture))); } else { return SafeProcessHandle.InvalidHandle; } } throw new Win32Exception(result); } public static SafeThreadHandle OpenThread(int threadId, int access) { SafeThreadHandle threadHandle = Interop.Kernel32.OpenThread(access, false, threadId); int result = Marshal.GetLastWin32Error(); if (threadHandle.IsInvalid) { if (result == Interop.Errors.ERROR_INVALID_PARAMETER) throw new InvalidOperationException(SR.Format(SR.ThreadExited, threadId.ToString(CultureInfo.CurrentCulture))); throw new Win32Exception(result); } return threadHandle; } } /// <devdoc> /// This static class provides the process api for the WinNt platform. /// We use the performance counter api to query process and thread /// information. Module information is obtained using PSAPI. /// </devdoc> /// <internalonly/> internal static class NtProcessManager { private const int ProcessPerfCounterId = 230; private const int ThreadPerfCounterId = 232; private const string PerfCounterQueryString = "230 232"; internal const int IdleProcessID = 0; private static readonly Dictionary<String, ValueId> s_valueIds = new Dictionary<string, ValueId>(19) { { "Pool Paged Bytes", ValueId.PoolPagedBytes }, { "Pool Nonpaged Bytes", ValueId.PoolNonpagedBytes }, { "Elapsed Time", ValueId.ElapsedTime }, { "Virtual Bytes Peak", ValueId.VirtualBytesPeak }, { "Virtual Bytes", ValueId.VirtualBytes }, { "Private Bytes", ValueId.PrivateBytes }, { "Page File Bytes", ValueId.PageFileBytes }, { "Page File Bytes Peak", ValueId.PageFileBytesPeak }, { "Working Set Peak", ValueId.WorkingSetPeak }, { "Working Set", ValueId.WorkingSet }, { "ID Thread", ValueId.ThreadId }, { "ID Process", ValueId.ProcessId }, { "Priority Base", ValueId.BasePriority }, { "Priority Current", ValueId.CurrentPriority }, { "% User Time", ValueId.UserTime }, { "% Privileged Time", ValueId.PrivilegedTime }, { "Start Address", ValueId.StartAddress }, { "Thread State", ValueId.ThreadState }, { "Thread Wait Reason", ValueId.ThreadWaitReason } }; internal static int SystemProcessID { get { const int systemProcessIDOnXP = 4; return systemProcessIDOnXP; } } public static int[] GetProcessIds(string machineName, bool isRemoteMachine) { ProcessInfo[] infos = GetProcessInfos(machineName, isRemoteMachine); int[] ids = new int[infos.Length]; for (int i = 0; i < infos.Length; i++) ids[i] = infos[i].ProcessId; return ids; } public static int[] GetProcessIds() { int[] processIds = new int[256]; int size; for (; ; ) { if (!Interop.Kernel32.EnumProcesses(processIds, processIds.Length * 4, out size)) throw new Win32Exception(); if (size == processIds.Length * 4) { processIds = new int[processIds.Length * 2]; continue; } break; } int[] ids = new int[size / 4]; Array.Copy(processIds, 0, ids, 0, ids.Length); return ids; } public static ProcessModuleCollection GetModules(int processId) { return GetModules(processId, firstModuleOnly: false); } public static ProcessModule GetFirstModule(int processId) { ProcessModuleCollection modules = GetModules(processId, firstModuleOnly: true); return modules.Count == 0 ? null : modules[0]; } private static ProcessModuleCollection GetModules(int processId, bool firstModuleOnly) { // preserving Everett behavior. if (processId == SystemProcessID || processId == IdleProcessID) { // system process and idle process doesn't have any modules throw new Win32Exception(Interop.Errors.EFail, SR.EnumProcessModuleFailed); } SafeProcessHandle processHandle = SafeProcessHandle.InvalidHandle; try { processHandle = ProcessManager.OpenProcess(processId, Interop.Advapi32.ProcessOptions.PROCESS_QUERY_INFORMATION | Interop.Advapi32.ProcessOptions.PROCESS_VM_READ, true); IntPtr[] moduleHandles = new IntPtr[64]; GCHandle moduleHandlesArrayHandle = new GCHandle(); int moduleCount = 0; for (; ; ) { bool enumResult = false; try { moduleHandlesArrayHandle = GCHandle.Alloc(moduleHandles, GCHandleType.Pinned); enumResult = Interop.Kernel32.EnumProcessModules(processHandle, moduleHandlesArrayHandle.AddrOfPinnedObject(), moduleHandles.Length * IntPtr.Size, ref moduleCount); // The API we need to use to enumerate process modules differs on two factors: // 1) If our process is running in WOW64. // 2) The bitness of the process we wish to introspect. // // If we are not running in WOW64 or we ARE in WOW64 but want to inspect a 32 bit process // we can call psapi!EnumProcessModules. // // If we are running in WOW64 and we want to inspect the modules of a 64 bit process then // psapi!EnumProcessModules will return false with ERROR_PARTIAL_COPY (299). In this case we can't // do the enumeration at all. So we'll detect this case and bail out. // // Also, EnumProcessModules is not a reliable method to get the modules for a process. // If OS loader is touching module information, this method might fail and copy part of the data. // This is no easy solution to this problem. The only reliable way to fix this is to // suspend all the threads in target process. Of course we don't want to do this in Process class. // So we just to try avoid the race by calling the same method 50 (an arbitrary number) times. // if (!enumResult) { bool sourceProcessIsWow64 = false; bool targetProcessIsWow64 = false; SafeProcessHandle hCurProcess = SafeProcessHandle.InvalidHandle; try { hCurProcess = ProcessManager.OpenProcess(unchecked((int)Interop.Kernel32.GetCurrentProcessId()), Interop.Advapi32.ProcessOptions.PROCESS_QUERY_INFORMATION, true); bool wow64Ret; wow64Ret = Interop.Kernel32.IsWow64Process(hCurProcess, ref sourceProcessIsWow64); if (!wow64Ret) { throw new Win32Exception(); } wow64Ret = Interop.Kernel32.IsWow64Process(processHandle, ref targetProcessIsWow64); if (!wow64Ret) { throw new Win32Exception(); } if (sourceProcessIsWow64 && !targetProcessIsWow64) { // Wow64 isn't going to allow this to happen, the best we can do is give a descriptive error to the user. throw new Win32Exception(Interop.Errors.ERROR_PARTIAL_COPY, SR.EnumProcessModuleFailedDueToWow); } } finally { if (hCurProcess != SafeProcessHandle.InvalidHandle) { hCurProcess.Dispose(); } } // If the failure wasn't due to Wow64, try again. for (int i = 0; i < 50; i++) { enumResult = Interop.Kernel32.EnumProcessModules(processHandle, moduleHandlesArrayHandle.AddrOfPinnedObject(), moduleHandles.Length * IntPtr.Size, ref moduleCount); if (enumResult) { break; } Thread.Sleep(1); } } } finally { moduleHandlesArrayHandle.Free(); } if (!enumResult) { throw new Win32Exception(); } moduleCount /= IntPtr.Size; if (moduleCount <= moduleHandles.Length) break; moduleHandles = new IntPtr[moduleHandles.Length * 2]; } var modules = new ProcessModuleCollection(firstModuleOnly ? 1 : moduleCount); char[] chars = new char[1024]; for (int i = 0; i < moduleCount; i++) { if (i > 0) { // If the user is only interested in the main module, break now. // This avoid some waste of time. In addition, if the application unloads a DLL // we will not get an exception. if (firstModuleOnly) { break; } } IntPtr moduleHandle = moduleHandles[i]; Interop.Kernel32.NtModuleInfo ntModuleInfo; if (!Interop.Kernel32.GetModuleInformation(processHandle, moduleHandle, out ntModuleInfo)) { HandleError(); continue; } var module = new ProcessModule() { ModuleMemorySize = ntModuleInfo.SizeOfImage, EntryPointAddress = ntModuleInfo.EntryPoint, BaseAddress = ntModuleInfo.BaseOfDll }; int length = Interop.Kernel32.GetModuleBaseName(processHandle, moduleHandle, chars, chars.Length); if (length == 0) { HandleError(); continue; } module.ModuleName = new string(chars, 0, length); length = Interop.Kernel32.GetModuleFileNameEx(processHandle, moduleHandle, chars, chars.Length); if (length == 0) { HandleError(); continue; } module.FileName = (length >= 4 && chars[0] == '\\' && chars[1] == '\\' && chars[2] == '?' && chars[3] == '\\') ? new string(chars, 4, length - 4) : new string(chars, 0, length); modules.Add(module); } return modules; } finally { #if FEATURE_TRACESWITCH Debug.WriteLineIf(Process._processTracing.TraceVerbose, "Process - CloseHandle(process)"); #endif if (!processHandle.IsInvalid) { processHandle.Dispose(); } } } private static void HandleError() { int lastError = Marshal.GetLastWin32Error(); switch (lastError) { case Interop.Errors.ERROR_INVALID_HANDLE: case Interop.Errors.ERROR_PARTIAL_COPY: // It's possible that another thread caused this module to become // unloaded (e.g FreeLibrary was called on the module). Ignore it and // move on. break; default: throw new Win32Exception(lastError); } } public static int GetProcessIdFromHandle(SafeProcessHandle processHandle) { Interop.NtDll.NtProcessBasicInfo info = new Interop.NtDll.NtProcessBasicInfo(); int status = Interop.NtDll.NtQueryInformationProcess(processHandle, Interop.NtDll.NtQueryProcessBasicInfo, info, (int)Marshal.SizeOf(info), null); if (status != 0) { throw new InvalidOperationException(SR.CantGetProcessId, new Win32Exception(status)); } // We should change the signature of this function and ID property in process class. return info.UniqueProcessId.ToInt32(); } public static ProcessInfo[] GetProcessInfos(string machineName, bool isRemoteMachine) { PerformanceCounterLib library = null; try { library = PerformanceCounterLib.GetPerformanceCounterLib(machineName, new CultureInfo("en")); return GetProcessInfos(library); } catch (Exception e) { if (isRemoteMachine) { throw new InvalidOperationException(SR.CouldntConnectToRemoteMachine, e); } else { throw e; } } // We don't want to call library.Close() here because that would cause us to unload all of the perflibs. // On the next call to GetProcessInfos, we'd have to load them all up again, which is SLOW! } static ProcessInfo[] GetProcessInfos(PerformanceCounterLib library) { ProcessInfo[] processInfos; int retryCount = 5; do { try { byte[] dataPtr = library.GetPerformanceData(PerfCounterQueryString); processInfos = GetProcessInfos(library, ProcessPerfCounterId, ThreadPerfCounterId, dataPtr); } catch (Exception e) { throw new InvalidOperationException(SR.CouldntGetProcessInfos, e); } --retryCount; } while (processInfos.Length == 0 && retryCount != 0); if (processInfos.Length == 0) throw new InvalidOperationException(SR.ProcessDisabled); return processInfos; } static ProcessInfo[] GetProcessInfos(PerformanceCounterLib library, int processIndex, int threadIndex, byte[] data) { #if FEATURE_TRACESWITCH Debug.WriteLineIf(Process._processTracing.TraceVerbose, "GetProcessInfos()"); #endif Dictionary<int, ProcessInfo> processInfos = new Dictionary<int, ProcessInfo>(); List<ThreadInfo> threadInfos = new List<ThreadInfo>(); GCHandle dataHandle = new GCHandle(); try { dataHandle = GCHandle.Alloc(data, GCHandleType.Pinned); IntPtr dataBlockPtr = dataHandle.AddrOfPinnedObject(); Interop.Advapi32.PERF_DATA_BLOCK dataBlock = new Interop.Advapi32.PERF_DATA_BLOCK(); Marshal.PtrToStructure(dataBlockPtr, dataBlock); IntPtr typePtr = (IntPtr)((long)dataBlockPtr + dataBlock.HeaderLength); Interop.Advapi32.PERF_INSTANCE_DEFINITION instance = new Interop.Advapi32.PERF_INSTANCE_DEFINITION(); Interop.Advapi32.PERF_COUNTER_BLOCK counterBlock = new Interop.Advapi32.PERF_COUNTER_BLOCK(); for (int i = 0; i < dataBlock.NumObjectTypes; i++) { Interop.Advapi32.PERF_OBJECT_TYPE type = new Interop.Advapi32.PERF_OBJECT_TYPE(); Marshal.PtrToStructure(typePtr, type); IntPtr instancePtr = (IntPtr)((long)typePtr + type.DefinitionLength); IntPtr counterPtr = (IntPtr)((long)typePtr + type.HeaderLength); List<Interop.Advapi32.PERF_COUNTER_DEFINITION> counterList = new List<Interop.Advapi32.PERF_COUNTER_DEFINITION>(); for (int j = 0; j < type.NumCounters; j++) { Interop.Advapi32.PERF_COUNTER_DEFINITION counter = new Interop.Advapi32.PERF_COUNTER_DEFINITION(); Marshal.PtrToStructure(counterPtr, counter); string counterName = library.GetCounterName(counter.CounterNameTitleIndex); if (type.ObjectNameTitleIndex == processIndex) counter.CounterNameTitlePtr = (int)GetValueId(counterName); else if (type.ObjectNameTitleIndex == threadIndex) counter.CounterNameTitlePtr = (int)GetValueId(counterName); counterList.Add(counter); counterPtr = (IntPtr)((long)counterPtr + counter.ByteLength); } Interop.Advapi32.PERF_COUNTER_DEFINITION[] counters = counterList.ToArray(); for (int j = 0; j < type.NumInstances; j++) { Marshal.PtrToStructure(instancePtr, instance); IntPtr namePtr = (IntPtr)((long)instancePtr + instance.NameOffset); string instanceName = Marshal.PtrToStringUni(namePtr); if (instanceName.Equals("_Total")) continue; IntPtr counterBlockPtr = (IntPtr)((long)instancePtr + instance.ByteLength); Marshal.PtrToStructure(counterBlockPtr, counterBlock); if (type.ObjectNameTitleIndex == processIndex) { ProcessInfo processInfo = GetProcessInfo(type, (IntPtr)((long)instancePtr + instance.ByteLength), counters); if (processInfo.ProcessId == 0 && string.Compare(instanceName, "Idle", StringComparison.OrdinalIgnoreCase) != 0) { // Sometimes we'll get a process structure that is not completely filled in. // We can catch some of these by looking for non-"idle" processes that have id 0 // and ignoring those. #if FEATURE_TRACESWITCH Debug.WriteLineIf(Process._processTracing.TraceVerbose, "GetProcessInfos() - found a non-idle process with id 0; ignoring."); #endif } else { if (processInfos.ContainsKey(processInfo.ProcessId)) { // We've found two entries in the perfcounters that claim to be the // same process. We throw an exception. Is this really going to be // helpful to the user? Should we just ignore? #if FEATURE_TRACESWITCH Debug.WriteLineIf(Process._processTracing.TraceVerbose, "GetProcessInfos() - found a duplicate process id"); #endif } else { // the performance counters keep a 15 character prefix of the exe name, and then delete the ".exe", // if it's in the first 15. The problem is that sometimes that will leave us with part of ".exe" // at the end. If instanceName ends in ".", ".e", or ".ex" we remove it. string processName = instanceName; if (processName.Length == 15) { if (instanceName.EndsWith(".", StringComparison.Ordinal)) processName = instanceName.Substring(0, 14); else if (instanceName.EndsWith(".e", StringComparison.Ordinal)) processName = instanceName.Substring(0, 13); else if (instanceName.EndsWith(".ex", StringComparison.Ordinal)) processName = instanceName.Substring(0, 12); } processInfo.ProcessName = processName; processInfos.Add(processInfo.ProcessId, processInfo); } } } else if (type.ObjectNameTitleIndex == threadIndex) { ThreadInfo threadInfo = GetThreadInfo(type, (IntPtr)((long)instancePtr + instance.ByteLength), counters); if (threadInfo._threadId != 0) threadInfos.Add(threadInfo); } instancePtr = (IntPtr)((long)instancePtr + instance.ByteLength + counterBlock.ByteLength); } typePtr = (IntPtr)((long)typePtr + type.TotalByteLength); } } finally { if (dataHandle.IsAllocated) dataHandle.Free(); } for (int i = 0; i < threadInfos.Count; i++) { ThreadInfo threadInfo = (ThreadInfo)threadInfos[i]; ProcessInfo processInfo; if (processInfos.TryGetValue(threadInfo._processId, out processInfo)) { processInfo._threadInfoList.Add(threadInfo); } } ProcessInfo[] temp = new ProcessInfo[processInfos.Values.Count]; processInfos.Values.CopyTo(temp, 0); return temp; } static ThreadInfo GetThreadInfo(Interop.Advapi32.PERF_OBJECT_TYPE type, IntPtr instancePtr, Interop.Advapi32.PERF_COUNTER_DEFINITION[] counters) { ThreadInfo threadInfo = new ThreadInfo(); for (int i = 0; i < counters.Length; i++) { Interop.Advapi32.PERF_COUNTER_DEFINITION counter = counters[i]; long value = ReadCounterValue(counter.CounterType, (IntPtr)((long)instancePtr + counter.CounterOffset)); switch ((ValueId)counter.CounterNameTitlePtr) { case ValueId.ProcessId: threadInfo._processId = (int)value; break; case ValueId.ThreadId: threadInfo._threadId = (ulong)value; break; case ValueId.BasePriority: threadInfo._basePriority = (int)value; break; case ValueId.CurrentPriority: threadInfo._currentPriority = (int)value; break; case ValueId.StartAddress: threadInfo._startAddress = (IntPtr)value; break; case ValueId.ThreadState: threadInfo._threadState = (ThreadState)value; break; case ValueId.ThreadWaitReason: threadInfo._threadWaitReason = GetThreadWaitReason((int)value); break; } } return threadInfo; } internal static ThreadWaitReason GetThreadWaitReason(int value) { switch (value) { case 0: case 7: return ThreadWaitReason.Executive; case 1: case 8: return ThreadWaitReason.FreePage; case 2: case 9: return ThreadWaitReason.PageIn; case 3: case 10: return ThreadWaitReason.SystemAllocation; case 4: case 11: return ThreadWaitReason.ExecutionDelay; case 5: case 12: return ThreadWaitReason.Suspended; case 6: case 13: return ThreadWaitReason.UserRequest; case 14: return ThreadWaitReason.EventPairHigh; ; case 15: return ThreadWaitReason.EventPairLow; case 16: return ThreadWaitReason.LpcReceive; case 17: return ThreadWaitReason.LpcReply; case 18: return ThreadWaitReason.VirtualMemory; case 19: return ThreadWaitReason.PageOut; default: return ThreadWaitReason.Unknown; } } static ProcessInfo GetProcessInfo(Interop.Advapi32.PERF_OBJECT_TYPE type, IntPtr instancePtr, Interop.Advapi32.PERF_COUNTER_DEFINITION[] counters) { ProcessInfo processInfo = new ProcessInfo(); for (int i = 0; i < counters.Length; i++) { Interop.Advapi32.PERF_COUNTER_DEFINITION counter = counters[i]; long value = ReadCounterValue(counter.CounterType, (IntPtr)((long)instancePtr + counter.CounterOffset)); switch ((ValueId)counter.CounterNameTitlePtr) { case ValueId.ProcessId: processInfo.ProcessId = (int)value; break; case ValueId.PoolPagedBytes: processInfo.PoolPagedBytes = value; break; case ValueId.PoolNonpagedBytes: processInfo.PoolNonPagedBytes = value; break; case ValueId.VirtualBytes: processInfo.VirtualBytes = value; break; case ValueId.VirtualBytesPeak: processInfo.VirtualBytesPeak = value; break; case ValueId.WorkingSetPeak: processInfo.WorkingSetPeak = value; break; case ValueId.WorkingSet: processInfo.WorkingSet = value; break; case ValueId.PageFileBytesPeak: processInfo.PageFileBytesPeak = value; break; case ValueId.PageFileBytes: processInfo.PageFileBytes = value; break; case ValueId.PrivateBytes: processInfo.PrivateBytes = value; break; case ValueId.BasePriority: processInfo.BasePriority = (int)value; break; case ValueId.HandleCount: processInfo.HandleCount = (int)value; break; } } return processInfo; } static ValueId GetValueId(string counterName) { if (counterName != null) { ValueId id; if (s_valueIds.TryGetValue(counterName, out id)) return id; } return ValueId.Unknown; } static long ReadCounterValue(int counterType, IntPtr dataPtr) { if ((counterType & Interop.Advapi32.PerfCounterOptions.NtPerfCounterSizeLarge) != 0) return Marshal.ReadInt64(dataPtr); else return (long)Marshal.ReadInt32(dataPtr); } enum ValueId { Unknown = -1, HandleCount, PoolPagedBytes, PoolNonpagedBytes, ElapsedTime, VirtualBytesPeak, VirtualBytes, PrivateBytes, PageFileBytes, PageFileBytesPeak, WorkingSetPeak, WorkingSet, ThreadId, ProcessId, BasePriority, CurrentPriority, UserTime, PrivilegedTime, StartAddress, ThreadState, ThreadWaitReason } } internal static class NtProcessInfoHelper { private static int GetNewBufferSize(int existingBufferSize, int requiredSize) { if (requiredSize == 0) { // // On some old OS like win2000, requiredSize will not be set if the buffer // passed to NtQuerySystemInformation is not enough. // int newSize = existingBufferSize * 2; if (newSize < existingBufferSize) { // In reality, we should never overflow. // Adding the code here just in case it happens. throw new OutOfMemoryException(); } return newSize; } else { // allocating a few more kilo bytes just in case there are some new process // kicked in since new call to NtQuerySystemInformation int newSize = requiredSize + 1024 * 10; if (newSize < requiredSize) { throw new OutOfMemoryException(); } return newSize; } } public static ProcessInfo[] GetProcessInfos() { int requiredSize = 0; int status; ProcessInfo[] processInfos; GCHandle bufferHandle = new GCHandle(); // Start with the default buffer size. int bufferSize = DefaultCachedBufferSize; // Get the cached buffer. long[] buffer = Interlocked.Exchange(ref CachedBuffer, null); try { do { if (buffer == null) { // Allocate buffer of longs since some platforms require the buffer to be 64-bit aligned. buffer = new long[(bufferSize + 7) / 8]; } else { // If we have cached buffer, set the size properly. bufferSize = buffer.Length * sizeof(long); } bufferHandle = GCHandle.Alloc(buffer, GCHandleType.Pinned); status = Interop.NtDll.NtQuerySystemInformation( Interop.NtDll.NtQuerySystemProcessInformation, bufferHandle.AddrOfPinnedObject(), bufferSize, out requiredSize); if (unchecked((uint)status) == Interop.NtDll.STATUS_INFO_LENGTH_MISMATCH) { if (bufferHandle.IsAllocated) bufferHandle.Free(); buffer = null; bufferSize = GetNewBufferSize(bufferSize, requiredSize); } } while (unchecked((uint)status) == Interop.NtDll.STATUS_INFO_LENGTH_MISMATCH); if (status < 0) { // see definition of NT_SUCCESS(Status) in SDK throw new InvalidOperationException(SR.CouldntGetProcessInfos, new Win32Exception(status)); } // Parse the data block to get process information processInfos = GetProcessInfos(bufferHandle.AddrOfPinnedObject()); } finally { // Cache the final buffer for use on the next call. Interlocked.Exchange(ref CachedBuffer, buffer); if (bufferHandle.IsAllocated) bufferHandle.Free(); } return processInfos; } // Use a smaller buffer size on debug to ensure we hit the retry path. #if DEBUG private const int DefaultCachedBufferSize = 1024; #else private const int DefaultCachedBufferSize = 128 * 1024; #endif // Cache a single buffer for use in GetProcessInfos(). private static long[] CachedBuffer; static ProcessInfo[] GetProcessInfos(IntPtr dataPtr) { // 60 is a reasonable number for processes on a normal machine. Dictionary<int, ProcessInfo> processInfos = new Dictionary<int, ProcessInfo>(60); long totalOffset = 0; while (true) { IntPtr currentPtr = (IntPtr)((long)dataPtr + totalOffset); SystemProcessInformation pi = new SystemProcessInformation(); Marshal.PtrToStructure(currentPtr, pi); // get information for a process ProcessInfo processInfo = new ProcessInfo(); // Process ID shouldn't overflow. OS API GetCurrentProcessID returns DWORD. processInfo.ProcessId = pi.UniqueProcessId.ToInt32(); processInfo.SessionId = (int)pi.SessionId; processInfo.PoolPagedBytes = (long)pi.QuotaPagedPoolUsage; ; processInfo.PoolNonPagedBytes = (long)pi.QuotaNonPagedPoolUsage; processInfo.VirtualBytes = (long)pi.VirtualSize; processInfo.VirtualBytesPeak = (long)pi.PeakVirtualSize; processInfo.WorkingSetPeak = (long)pi.PeakWorkingSetSize; processInfo.WorkingSet = (long)pi.WorkingSetSize; processInfo.PageFileBytesPeak = (long)pi.PeakPagefileUsage; processInfo.PageFileBytes = (long)pi.PagefileUsage; processInfo.PrivateBytes = (long)pi.PrivatePageCount; processInfo.BasePriority = pi.BasePriority; processInfo.HandleCount = (int)pi.HandleCount; if (pi.NamePtr == IntPtr.Zero) { if (processInfo.ProcessId == NtProcessManager.SystemProcessID) { processInfo.ProcessName = "System"; } else if (processInfo.ProcessId == NtProcessManager.IdleProcessID) { processInfo.ProcessName = "Idle"; } else { // for normal process without name, using the process ID. processInfo.ProcessName = processInfo.ProcessId.ToString(CultureInfo.InvariantCulture); } } else { string processName = GetProcessShortName(Marshal.PtrToStringUni(pi.NamePtr, pi.NameLength / sizeof(char))); processInfo.ProcessName = processName; } // get the threads for current process processInfos[processInfo.ProcessId] = processInfo; currentPtr = (IntPtr)((long)currentPtr + Marshal.SizeOf(pi)); int i = 0; while (i < pi.NumberOfThreads) { SystemThreadInformation ti = new SystemThreadInformation(); Marshal.PtrToStructure(currentPtr, ti); ThreadInfo threadInfo = new ThreadInfo(); threadInfo._processId = (int)ti.UniqueProcess; threadInfo._threadId = (ulong)ti.UniqueThread; threadInfo._basePriority = ti.BasePriority; threadInfo._currentPriority = ti.Priority; threadInfo._startAddress = ti.StartAddress; threadInfo._threadState = (ThreadState)ti.ThreadState; threadInfo._threadWaitReason = NtProcessManager.GetThreadWaitReason((int)ti.WaitReason); processInfo._threadInfoList.Add(threadInfo); currentPtr = (IntPtr)((long)currentPtr + Marshal.SizeOf(ti)); i++; } if (pi.NextEntryOffset == 0) { break; } totalOffset += pi.NextEntryOffset; } ProcessInfo[] temp = new ProcessInfo[processInfos.Values.Count]; processInfos.Values.CopyTo(temp, 0); return temp; } // This function generates the short form of process name. // // This is from GetProcessShortName in NT code base. // Check base\screg\winreg\perfdlls\process\perfsprc.c for details. internal static string GetProcessShortName(String name) { if (String.IsNullOrEmpty(name)) { #if FEATURE_TRACESWITCH Debug.WriteLineIf(Process._processTracing.TraceVerbose, "GetProcessInfos() - unexpected blank ProcessName"); #endif return String.Empty; } int slash = -1; int period = -1; for (int i = 0; i < name.Length; i++) { if (name[i] == '\\') slash = i; else if (name[i] == '.') period = i; } if (period == -1) period = name.Length - 1; // set to end of string else { // if a period was found, then see if the extension is // .EXE, if so drop it, if not, then use end of string // (i.e. include extension in name) String extension = name.Substring(period); if (String.Equals(".exe", extension, StringComparison.OrdinalIgnoreCase)) period--; // point to character before period else period = name.Length - 1; // set to end of string } if (slash == -1) slash = 0; // set to start of string else slash++; // point to character next to slash // copy characters between period (or end of string) and // slash (or start of string) to make image name return name.Substring(slash, period - slash + 1); } // native struct defined in ntexapi.h [StructLayout(LayoutKind.Sequential)] internal class SystemProcessInformation { internal uint NextEntryOffset; internal uint NumberOfThreads; private long _SpareLi1; private long _SpareLi2; private long _SpareLi3; private long _CreateTime; private long _UserTime; private long _KernelTime; internal ushort NameLength; // UNICODE_STRING internal ushort MaximumNameLength; internal IntPtr NamePtr; // This will point into the data block returned by NtQuerySystemInformation internal int BasePriority; internal IntPtr UniqueProcessId; internal IntPtr InheritedFromUniqueProcessId; internal uint HandleCount; internal uint SessionId; internal UIntPtr PageDirectoryBase; internal UIntPtr PeakVirtualSize; // SIZE_T internal UIntPtr VirtualSize; internal uint PageFaultCount; internal UIntPtr PeakWorkingSetSize; internal UIntPtr WorkingSetSize; internal UIntPtr QuotaPeakPagedPoolUsage; internal UIntPtr QuotaPagedPoolUsage; internal UIntPtr QuotaPeakNonPagedPoolUsage; internal UIntPtr QuotaNonPagedPoolUsage; internal UIntPtr PagefileUsage; internal UIntPtr PeakPagefileUsage; internal UIntPtr PrivatePageCount; private long _ReadOperationCount; private long _WriteOperationCount; private long _OtherOperationCount; private long _ReadTransferCount; private long _WriteTransferCount; private long _OtherTransferCount; } [StructLayout(LayoutKind.Sequential)] internal class SystemThreadInformation { private long _KernelTime; private long _UserTime; private long _CreateTime; private uint _WaitTime; internal IntPtr StartAddress; internal IntPtr UniqueProcess; internal IntPtr UniqueThread; internal int Priority; internal int BasePriority; internal uint ContextSwitches; internal uint ThreadState; internal uint WaitReason; } } internal sealed class MainWindowFinder { private const int GW_OWNER = 4; private IntPtr _bestHandle; private int _processId; public IntPtr FindMainWindow(int processId) { _bestHandle = (IntPtr)0; _processId = processId; Interop.User32.EnumThreadWindowsCallback callback = new Interop.User32.EnumThreadWindowsCallback(EnumWindowsCallback); Interop.User32.EnumWindows(callback, IntPtr.Zero); GC.KeepAlive(callback); return _bestHandle; } private bool IsMainWindow(IntPtr handle) { if (Interop.User32.GetWindow(handle, GW_OWNER) != (IntPtr)0 || !Interop.User32.IsWindowVisible(handle)) return false; return true; } private bool EnumWindowsCallback(IntPtr handle, IntPtr extraParameter) { int processId; Interop.User32.GetWindowThreadProcessId(handle, out processId); if (processId == _processId) { if (IsMainWindow(handle)) { _bestHandle = handle; return false; } } return true; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using System.Linq; using System.Web; using System.Web.Security; using Umbraco.Core; using Umbraco.Core.Configuration; using Umbraco.Core.Configuration.UmbracoSettings; using Umbraco.Core.Models; using umbraco; using umbraco.cms.businesslogic.web; using RenderingEngine = Umbraco.Core.RenderingEngine; namespace Umbraco.Web.Routing { /// <summary> /// Represents a request for one specified Umbraco IPublishedContent to be rendered /// by one specified template, using one specified Culture and RenderingEngine. /// </summary> public class PublishedContentRequest { private bool _readonly; private bool _readonlyUri; /// <summary> /// Triggers before the published content request is prepared. /// </summary> /// <remarks>When the event triggers, no preparation has been done. It is still possible to /// modify the request's Uri property, for example to restore its original, public-facing value /// that might have been modified by an in-between equipement such as a load-balancer.</remarks> public static event EventHandler<EventArgs> Preparing; /// <summary> /// Triggers once the published content request has been prepared, but before it is processed. /// </summary> /// <remarks>When the event triggers, preparation is done ie domain, culture, document, template, /// rendering engine, etc. have been setup. It is then possible to change anything, before /// the request is actually processed and rendered by Umbraco.</remarks> public static event EventHandler<EventArgs> Prepared; // the engine that does all the processing // because in order to keep things clean and separated, // the content request is just a data holder private readonly PublishedContentRequestEngine _engine; // the cleaned up uri // the cleaned up Uri has no virtual directory, no trailing slash, no .aspx extension, etc. private Uri _uri; /// <summary> /// Initializes a new instance of the <see cref="PublishedContentRequest"/> class with a specific Uri and routing context. /// </summary> /// <param name="uri">The request <c>Uri</c>.</param> /// <param name="routingContext">A routing context.</param> /// <param name="getRolesForLogin">A callback method to return the roles for the provided login name when required</param> /// <param name="routingConfig"></param> public PublishedContentRequest(Uri uri, RoutingContext routingContext, IWebRoutingSection routingConfig, Func<string, IEnumerable<string>> getRolesForLogin) { if (uri == null) throw new ArgumentNullException("uri"); if (routingContext == null) throw new ArgumentNullException("routingContext"); Uri = uri; RoutingContext = routingContext; _getRolesForLoginCallback = getRolesForLogin; _engine = new PublishedContentRequestEngine( routingConfig, this); RenderingEngine = RenderingEngine.Unknown; } [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("Use the constructor specifying all dependencies instead")] public PublishedContentRequest(Uri uri, RoutingContext routingContext) : this(uri, routingContext, UmbracoConfig.For.UmbracoSettings().WebRouting, s => Roles.Provider.GetRolesForUser(s)) { } /// <summary> /// Gets the engine associated to the request. /// </summary> internal PublishedContentRequestEngine Engine { get { return _engine; } } /// <summary> /// Prepares the request. /// </summary> public void Prepare() { _engine.PrepareRequest(); } /// <summary> /// Called to configure the request /// </summary> /// <remarks> /// This public method is legacy, Prepare() has been made public now which should be used and ensures the domains are assigned and /// if a public content item is already assigned Prepare() now ensures that the finders are not executed. /// </remarks> [Obsolete("Use Prepare() instead which configures the request and wires up everything correctly")] public void ConfigureRequest() { _engine.ConfigureRequest(); } /// <summary> /// Updates the request when there is no template to render the content. /// </summary> internal void UpdateOnMissingTemplate() { var __readonly = _readonly; _readonly = false; _engine.UpdateRequestOnMissingTemplate(); _readonly = __readonly; } /// <summary> /// Triggers the Preparing event. /// </summary> internal void OnPreparing() { var handler = Preparing; if (handler != null) handler(this, EventArgs.Empty); _readonlyUri = true; } /// <summary> /// Triggers the Prepared event. /// </summary> internal void OnPrepared() { var handler = Prepared; if (handler != null) handler(this, EventArgs.Empty); if (HasPublishedContent == false) Is404 = true; // safety _readonly = true; } /// <summary> /// Gets or sets the cleaned up Uri used for routing. /// </summary> /// <remarks>The cleaned up Uri has no virtual directory, no trailing slash, no .aspx extension, etc.</remarks> public Uri Uri { get { return _uri; } set { if (_readonlyUri) throw new InvalidOperationException("Cannot modify Uri after Preparing has triggered."); _uri = value; } } private void EnsureWriteable() { if (_readonly) throw new InvalidOperationException("Cannot modify a PublishedContentRequest once it is read-only."); } #region PublishedContent /// <summary> /// The requested IPublishedContent, if any, else <c>null</c>. /// </summary> private IPublishedContent _publishedContent; /// <summary> /// The initial requested IPublishedContent, if any, else <c>null</c>. /// </summary> /// <remarks>The initial requested content is the content that was found by the finders, /// before anything such as 404, redirect... took place.</remarks> private IPublishedContent _initialPublishedContent; /// <summary> /// Gets or sets the requested content. /// </summary> /// <remarks>Setting the requested content clears <c>Template</c>.</remarks> public IPublishedContent PublishedContent { get { return _publishedContent; } set { EnsureWriteable(); _publishedContent = value; IsInternalRedirectPublishedContent = false; TemplateModel = null; } } /// <summary> /// Sets the requested content, following an internal redirect. /// </summary> /// <param name="content">The requested content.</param> /// <remarks>Depending on <c>UmbracoSettings.InternalRedirectPreservesTemplate</c>, will /// preserve or reset the template, if any.</remarks> public void SetInternalRedirectPublishedContent(IPublishedContent content) { if (content == null) throw new ArgumentNullException("content"); EnsureWriteable(); // unless a template has been set already by the finder, // template should be null at that point. // IsInternalRedirect if IsInitial, or already IsInternalRedirect var isInternalRedirect = IsInitialPublishedContent || IsInternalRedirectPublishedContent; // redirecting to self if (content.Id == PublishedContent.Id) // neither can be null { // no need to set PublishedContent, we're done IsInternalRedirectPublishedContent = isInternalRedirect; return; } // else // save var template = _template; var renderingEngine = RenderingEngine; // set published content - this resets the template, and sets IsInternalRedirect to false PublishedContent = content; IsInternalRedirectPublishedContent = isInternalRedirect; // must restore the template if it's an internal redirect & the config option is set if (isInternalRedirect && UmbracoConfig.For.UmbracoSettings().WebRouting.InternalRedirectPreservesTemplate) { // restore _template = template; RenderingEngine = renderingEngine; } } /// <summary> /// Gets the initial requested content. /// </summary> /// <remarks>The initial requested content is the content that was found by the finders, /// before anything such as 404, redirect... took place.</remarks> public IPublishedContent InitialPublishedContent { get { return _initialPublishedContent; } } /// <summary> /// Gets value indicating whether the current published content is the initial one. /// </summary> public bool IsInitialPublishedContent { get { return _initialPublishedContent != null && _initialPublishedContent == _publishedContent; } } /// <summary> /// Indicates that the current PublishedContent is the initial one. /// </summary> public void SetIsInitialPublishedContent() { EnsureWriteable(); // note: it can very well be null if the initial content was not found _initialPublishedContent = _publishedContent; IsInternalRedirectPublishedContent = false; } /// <summary> /// Gets or sets a value indicating whether the current published content has been obtained /// from the initial published content following internal redirections exclusively. /// </summary> /// <remarks>Used by PublishedContentRequestEngine.FindTemplate() to figure out whether to /// apply the internal redirect or not, when content is not the initial content.</remarks> public bool IsInternalRedirectPublishedContent { get; private set; } /// <summary> /// Gets a value indicating whether the content request has a content. /// </summary> public bool HasPublishedContent { get { return PublishedContent != null; } } #endregion #region Template /// <summary> /// The template model, if any, else <c>null</c>. /// </summary> private ITemplate _template; /// <summary> /// Gets or sets the template model to use to display the requested content. /// </summary> internal ITemplate TemplateModel { get { return _template; } set { _template = value; RenderingEngine = RenderingEngine.Unknown; // reset if (_template != null) RenderingEngine = _engine.FindTemplateRenderingEngine(_template.Alias); } } /// <summary> /// Gets the alias of the template to use to display the requested content. /// </summary> public string TemplateAlias { get { return _template == null ? null : _template.Alias; } } /// <summary> /// Tries to set the template to use to display the requested content. /// </summary> /// <param name="alias">The alias of the template.</param> /// <returns>A value indicating whether a valid template with the specified alias was found.</returns> /// <remarks> /// <para>Successfully setting the template does refresh <c>RenderingEngine</c>.</para> /// <para>If setting the template fails, then the previous template (if any) remains in place.</para> /// </remarks> public bool TrySetTemplate(string alias) { EnsureWriteable(); if (string.IsNullOrWhiteSpace(alias)) { TemplateModel = null; return true; } // NOTE - can we stil get it with whitespaces in it due to old legacy bugs? alias = alias.Replace(" ", ""); var model = ApplicationContext.Current.Services.FileService.GetTemplate(alias); if (model == null) return false; TemplateModel = model; return true; } /// <summary> /// Sets the template to use to display the requested content. /// </summary> /// <param name="template">The template.</param> /// <remarks>Setting the template does refresh <c>RenderingEngine</c>.</remarks> public void SetTemplate(ITemplate template) { EnsureWriteable(); TemplateModel = template; } /// <summary> /// Resets the template. /// </summary> /// <remarks>The <c>RenderingEngine</c> becomes unknown.</remarks> public void ResetTemplate() { EnsureWriteable(); TemplateModel = null; } /// <summary> /// Gets a value indicating whether the content request has a template. /// </summary> public bool HasTemplate { get { return _template != null; } } #endregion #region Domain and Culture [Obsolete("Do not use this property, use the non-legacy UmbracoDomain property instead")] public Domain Domain { get { return new Domain(UmbracoDomain); } } //TODO: Should we publicize the setter now that we are using a non-legacy entity?? /// <summary> /// Gets or sets the content request's domain. /// </summary> public IDomain UmbracoDomain { get; internal set; } /// <summary> /// Gets or sets the content request's domain Uri. /// </summary> /// <remarks>The <c>Domain</c> may contain "example.com" whereas the <c>Uri</c> will be fully qualified eg "http://example.com/".</remarks> public Uri DomainUri { get; internal set; } /// <summary> /// Gets a value indicating whether the content request has a domain. /// </summary> public bool HasDomain { get { return UmbracoDomain != null; } } private CultureInfo _culture; /// <summary> /// Gets or sets the content request's culture. /// </summary> public CultureInfo Culture { get { return _culture; } set { EnsureWriteable(); _culture = value; } } // note: do we want to have an ordered list of alternate cultures, // to allow for fallbacks when doing dictionnary lookup and such? #endregion #region Rendering /// <summary> /// Gets or sets whether the rendering engine is MVC or WebForms. /// </summary> public RenderingEngine RenderingEngine { get; internal set; } #endregion /// <summary> /// Gets or sets the current RoutingContext. /// </summary> public RoutingContext RoutingContext { get; private set; } /// <summary> /// Returns the current members roles if a member is logged in /// </summary> /// <param name="username"></param> /// <returns></returns> /// <remarks> /// This ensures that the callback is only executed once in case this method is accessed a few times /// </remarks> public IEnumerable<string> GetRolesForLogin(string username) { string[] roles; if (_rolesForLogin.TryGetValue(username, out roles)) return roles; roles = _getRolesForLoginCallback(username).ToArray(); _rolesForLogin[username] = roles; return roles; } private readonly IDictionary<string, string[]> _rolesForLogin = new Dictionary<string, string[]>(); private readonly Func<string, IEnumerable<string>> _getRolesForLoginCallback; /// <summary> /// The "umbraco page" object. /// </summary> private page _umbracoPage; /// <summary> /// Gets or sets the "umbraco page" object. /// </summary> /// <remarks> /// This value is only used for legacy/webforms code. /// </remarks> internal page UmbracoPage { get { if (_umbracoPage == null) throw new InvalidOperationException("The UmbracoPage object has not been initialized yet."); return _umbracoPage; } set { _umbracoPage = value; } } #region Status /// <summary> /// Gets or sets a value indicating whether the requested content could not be found. /// </summary> /// <remarks>This is set in the <c>PublishedContentRequestBuilder</c>.</remarks> public bool Is404 { get; internal set; } /// <summary> /// Indicates that the requested content could not be found. /// </summary> /// <remarks>This is for public access, in custom content finders or <c>Prepared</c> event handlers, /// where we want to allow developers to indicate a request is 404 but not to cancel it.</remarks> public void SetIs404() { EnsureWriteable(); Is404 = true; } /// <summary> /// Gets a value indicating whether the content request triggers a redirect (permanent or not). /// </summary> public bool IsRedirect { get { return string.IsNullOrWhiteSpace(RedirectUrl) == false; } } /// <summary> /// Gets or sets a value indicating whether the redirect is permanent. /// </summary> public bool IsRedirectPermanent { get; private set; } /// <summary> /// Gets or sets the url to redirect to, when the content request triggers a redirect. /// </summary> public string RedirectUrl { get; private set; } /// <summary> /// Indicates that the content request should trigger a redirect (302). /// </summary> /// <param name="url">The url to redirect to.</param> /// <remarks>Does not actually perform a redirect, only registers that the response should /// redirect. Redirect will or will not take place in due time.</remarks> public void SetRedirect(string url) { EnsureWriteable(); RedirectUrl = url; IsRedirectPermanent = false; } /// <summary> /// Indicates that the content request should trigger a permanent redirect (301). /// </summary> /// <param name="url">The url to redirect to.</param> /// <remarks>Does not actually perform a redirect, only registers that the response should /// redirect. Redirect will or will not take place in due time.</remarks> public void SetRedirectPermanent(string url) { EnsureWriteable(); RedirectUrl = url; IsRedirectPermanent = true; } /// <summary> /// Indicates that the content requet should trigger a redirect, with a specified status code. /// </summary> /// <param name="url">The url to redirect to.</param> /// <param name="status">The status code (300-308).</param> /// <remarks>Does not actually perform a redirect, only registers that the response should /// redirect. Redirect will or will not take place in due time.</remarks> public void SetRedirect(string url, int status) { EnsureWriteable(); if (status < 300 || status > 308) throw new ArgumentOutOfRangeException("status", "Valid redirection status codes 300-308."); RedirectUrl = url; IsRedirectPermanent = (status == 301 || status == 308); if (status != 301 && status != 302) // default redirect statuses ResponseStatusCode = status; } /// <summary> /// Gets or sets the content request http response status code. /// </summary> /// <remarks>Does not actually set the http response status code, only registers that the response /// should use the specified code. The code will or will not be used, in due time.</remarks> public int ResponseStatusCode { get; private set; } /// <summary> /// Gets or sets the content request http response status description. /// </summary> /// <remarks>Does not actually set the http response status description, only registers that the response /// should use the specified description. The description will or will not be used, in due time.</remarks> public string ResponseStatusDescription { get; private set; } /// <summary> /// Sets the http response status code, along with an optional associated description. /// </summary> /// <param name="code">The http status code.</param> /// <param name="description">The description.</param> /// <remarks>Does not actually set the http response status code and description, only registers that /// the response should use the specified code and description. The code and description will or will /// not be used, in due time.</remarks> public void SetResponseStatus(int code, string description = null) { EnsureWriteable(); // .Status is deprecated // .SubStatusCode is IIS 7+ internal, ignore ResponseStatusCode = code; ResponseStatusDescription = description; } #endregion /// <summary> /// Gets or sets the <c>System.Web.HttpCacheability</c> /// </summary> // Note: we used to set a default value here but that would then be the default // for ALL requests, we shouldn't overwrite it though if people are using [OutputCache] for example // see: https://our.umbraco.com/forum/using-umbraco-and-getting-started/79715-output-cache-in-umbraco-752 internal HttpCacheability Cacheability { get; set; } /// <summary> /// Gets or sets a list of Extensions to append to the Response.Cache object /// </summary> private List<string> _cacheExtensions = new List<string>(); internal List<string> CacheExtensions { get { return _cacheExtensions; } set { _cacheExtensions = value; } } /// <summary> /// Gets or sets a dictionary of Headers to append to the Response object /// </summary> private Dictionary<string, string> _headers = new Dictionary<string, string>(); internal Dictionary<string, string> Headers { get { return _headers; } set { _headers = value; } } /// <summary> /// Gets of sets a value indicating whether the Umbraco Backoffice should ignore a collision for this request. /// </summary> public bool IgnorePublishedContentCollisions { get; set; } } }
using System; using System.IO; using System.Text; using Microsoft.SPOT; using Microsoft.SPOT.Hardware; namespace Nwazet.Go.Helpers { public class BasicTypeSerializerContext : IDisposable { public delegate void OnHighWatermarkEvent(); public int ContentSize { get { return _currentIndex; } } public const int MinimumBufferSize = 100; private bool _isLittleEndian = Utility.ExtractValueFromArray(new byte[] { 0xDE, 0xAD }, 0, 2) == 0xADDE; public bool IsLittleEndian { get { return _isLittleEndian; } } public int HighWatermark { get; set; } public bool ByteLevelWaterMark { get; set; } protected OnHighWatermarkEvent HighWatermarkEvent; public BasicTypeSerializerContext(int defaultBufferSize = 1024, int highWatermark = 0, OnHighWatermarkEvent highWatermarkEvent = null, bool byteLevelWatermark = false) { if (defaultBufferSize < MinimumBufferSize) throw new ArgumentOutOfRangeException("defaultBufferSize"); _serializeBuffer = new byte[defaultBufferSize]; _storeFunction = StoreToBuffer; HighWatermarkEvent = highWatermarkEvent; HighWatermark = highWatermark; ByteLevelWaterMark = byteLevelWatermark; InitializeHeader(); } public BasicTypeSerializerContext(FileStream file) { if (file == null) throw new ArgumentNullException("file"); _file = file; if (_file.CanWrite == false) throw new ApplicationException("file"); _storeFunction = StoreToFile; InitializeHeader(); } private const int BufferStartOffset = 2; private const int NwazetLibSerializerHeaderVersionOffset = BufferStartOffset + 0; private const int NwazetLibSerializerHeaderContentSizeOffset = BufferStartOffset + 1; private const byte _headerVersion = 3; private void InitializeHeader() { _currentIndex = BufferStartOffset; if (BufferStartOffset > 0 && _file != null) { _file.SetLength(BufferStartOffset); } // Store the version byte Store((byte)_headerVersion); // Reserve two bytes to track the length of the data in the buffer. Not used with the FileStream. Store(0); Store(0); } public void Store(byte data) { _storeFunction(data); if (ByteLevelWaterMark == true) { CheckHighWatermark(); } } public void Store(byte[] bytes, ushort offset, ushort count) { if (_file == null) { var currentSerializeBufferLength = _serializeBuffer.Length; if (currentSerializeBufferLength < _currentIndex + count) { var buffer = new byte[(currentSerializeBufferLength * 2) + count]; Array.Copy(_serializeBuffer, buffer, currentSerializeBufferLength); _serializeBuffer = buffer; buffer = null; Debug.GC(true); } Array.Copy(bytes, offset, _serializeBuffer, _currentIndex, count); } else { _file.Write(bytes, offset, count); } _currentIndex += count; if (ByteLevelWaterMark == true) { CheckHighWatermark(); } } private void StoreToBuffer(byte data) { if (_currentIndex < _serializeBuffer.Length) { _serializeBuffer[_currentIndex++] = data; return; } else { // Attempt to grow the buffer... var buffer = new byte[_serializeBuffer.Length * 2]; Array.Copy(_serializeBuffer, buffer, _serializeBuffer.Length); _serializeBuffer = buffer; _serializeBuffer[_currentIndex++] = data; buffer = null; Debug.GC(true); } } private void StoreToFile(byte data) { _file.WriteByte(data); _currentIndex++; } public void CheckHighWatermark() { if (HighWatermark != 0 && _currentIndex >= HighWatermark) { HighWatermarkEvent(); } } public byte[] GetBuffer(out int contentSize) { if (_serializeBuffer == null) { contentSize = 0; return null; } // Finalize the content size in the header _serializeBuffer[NwazetLibSerializerHeaderContentSizeOffset] = (byte)(ContentSize >> 8); _serializeBuffer[NwazetLibSerializerHeaderContentSizeOffset+1] = (byte)(ContentSize); contentSize = _currentIndex; _currentIndex = BufferStartOffset + _headerVersion; return _serializeBuffer; } public void Wipe() { var length = _serializeBuffer.Length; for (var i = 0; i < length; i++) { _serializeBuffer[i] = 0; } InitializeHeader(); } public void Dispose() { if (_file != null) { _file.Dispose(); } _encoding = null; _file = null; _serializeBuffer = null; _storeFunction = null; } private delegate void StoreByte(byte data); private UTF8Encoding _encoding = new UTF8Encoding(); private FileStream _file; private byte[] _serializeBuffer; private int _currentIndex; private StoreByte _storeFunction; } public static class BasicTypeSerializer { public static void Put(BasicTypeSerializerContext context, UInt16 data) { Put(context, (Int16) data); } public static void Put(BasicTypeSerializerContext context, Int16 data) { Put(context, (byte)(data >> 8)); Put(context, (byte)data); } public static void Put(BasicTypeSerializerContext context, UInt32 data) { Put(context, (byte)(data >> 24)); Put(context, (byte)(data >> 16)); Put(context, (byte)(data >> 8)); Put(context, (byte)data); } public static void Put(BasicTypeSerializerContext context, Int32 data) { Put(context, (UInt32)data); } public static void Put(BasicTypeSerializerContext context, UInt64 data) { Put(context, (byte)(data >> 56)); Put(context, (byte)(data >> 48)); Put(context, (byte)(data >> 40)); Put(context, (byte)(data >> 32)); Put(context, (byte)(data >> 24)); Put(context, (byte)(data >> 16)); Put(context, (byte)(data >> 8)); Put(context, (byte)data); } public static void Put(BasicTypeSerializerContext context, Int64 data) { Put(context, (UInt64)data); } public static unsafe void Put(BasicTypeSerializerContext context, float data) { var temp = new byte[4]; Utility.InsertValueIntoArray(temp, 0, 4, *((uint*)&data)); if (context.IsLittleEndian) { // Store the float in network byte order (Big Endian) Put(context, temp[3]); Put(context, temp[2]); Put(context, temp[1]); Put(context, temp[0]); } else { // Already in network byte order Put(context, temp[0]); Put(context, temp[1]); Put(context, temp[2]); Put(context, temp[3]); } } public static void Put(BasicTypeSerializerContext context, string text, bool ConvertToASCII = false) { Put(context, (byte)(ConvertToASCII ? 1 : 0)); if (ConvertToASCII) { Put(context, Encoding.UTF8.GetBytes(text)); Put(context, (byte) 0); // terminate the string with a null byte } else { Put(context, (ushort)text.Length); foreach (var c in text) { Put(context, c); } Put(context, (ushort)0); // terminate the unicode string with a null short } } public static void Put(BasicTypeSerializerContext context, byte[] bytes) { Put(context, (ushort)bytes.Length); foreach (var b in bytes) { Put(context, b); } } public static void Put(BasicTypeSerializerContext context, byte[] bytes, ushort offset, ushort count) { Put(context, (ushort)count); context.Store(bytes, offset, count); } public static void Put(BasicTypeSerializerContext context, ushort[] array) { Put(context, (ushort)array.Length); foreach (var e in array) { Put(context, e); } } public static void Put(BasicTypeSerializerContext context, UInt32[] array) { Put(context, (ushort)array.Length); foreach (var e in array) { Put(context, e); } } public static void Put(BasicTypeSerializerContext context, UInt64[] array) { Put(context, (ushort)array.Length); foreach (var e in array) { Put(context, e); } } public static void Put(BasicTypeSerializerContext context, byte data) { context.Store(data); } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using BenchmarkDotNet.Running; using Benchmarks.MapReduce; using Benchmarks.Serialization; using Benchmarks.Ping; using Benchmarks.Transactions; using Benchmarks.GrainStorage; using BenchmarkDotNet.Configs; using BenchmarkDotNet.Jobs; using BenchmarkDotNet.Toolchains.CsProj; namespace Benchmarks { class Program { private static readonly Dictionary<string, Action> _benchmarks = new Dictionary<string, Action> { ["MapReduce"] = () => { RunBenchmark( "Running MapReduce benchmark", () => { var mapReduceBenchmark = new MapReduceBenchmark(); mapReduceBenchmark.BenchmarkSetup(); return mapReduceBenchmark; }, benchmark => benchmark.Bench().GetAwaiter().GetResult(), benchmark => benchmark.Teardown()); }, ["Serialization"] = () => { BenchmarkRunner.Run<SerializationBenchmarks>(); }, ["Transactions.Memory"] = () => { RunBenchmark( "Running Transactions benchmark", () => { var benchmark = new TransactionBenchmark(2, 20000, 5000); benchmark.MemorySetup(); return benchmark; }, benchmark => benchmark.RunAsync().GetAwaiter().GetResult(), benchmark => benchmark.Teardown()); }, ["Transactions.Memory.Throttled"] = () => { RunBenchmark( "Running Transactions benchmark", () => { var benchmark = new TransactionBenchmark(2, 200000, 15000); benchmark.MemoryThrottledSetup(); return benchmark; }, benchmark => benchmark.RunAsync().GetAwaiter().GetResult(), benchmark => benchmark.Teardown()); }, ["Transactions.Azure"] = () => { RunBenchmark( "Running Transactions benchmark", () => { var benchmark = new TransactionBenchmark(2, 20000, 5000); benchmark.AzureSetup(); return benchmark; }, benchmark => benchmark.RunAsync().GetAwaiter().GetResult(), benchmark => benchmark.Teardown()); }, ["Transactions.Azure.Throttled"] = () => { RunBenchmark( "Running Transactions benchmark", () => { var benchmark = new TransactionBenchmark(2, 200000, 15000); benchmark.AzureThrottledSetup(); return benchmark; }, benchmark => benchmark.RunAsync().GetAwaiter().GetResult(), benchmark => benchmark.Teardown()); }, ["Transactions.Azure.Overloaded"] = () => { RunBenchmark( "Running Transactions benchmark", () => { var benchmark = new TransactionBenchmark(2, 200000, 15000); benchmark.AzureSetup(); return benchmark; }, benchmark => benchmark.RunAsync().GetAwaiter().GetResult(), benchmark => benchmark.Teardown()); }, ["SequentialPing"] = () => { BenchmarkRunner.Run<PingBenchmark>(); }, ["ConcurrentPing"] = () => { { Console.WriteLine("## Client to Silo ##"); var test = new PingBenchmark(numSilos: 1, startClient: true); test.PingConcurrent().GetAwaiter().GetResult(); test.Shutdown().GetAwaiter().GetResult(); } GC.Collect(); { Console.WriteLine("## Client to 2 Silos ##"); var test = new PingBenchmark(numSilos: 2, startClient: true); test.PingConcurrent().GetAwaiter().GetResult(); test.Shutdown().GetAwaiter().GetResult(); } GC.Collect(); { Console.WriteLine("## Hosted Client ##"); var test = new PingBenchmark(numSilos: 1, startClient: false); test.PingConcurrentHostedClient().GetAwaiter().GetResult(); test.Shutdown().GetAwaiter().GetResult(); } GC.Collect(); { // All calls are cross-silo because the calling silo doesn't have any grain classes. Console.WriteLine("## Silo to Silo ##"); var test = new PingBenchmark(numSilos: 2, startClient: false, grainsOnSecondariesOnly: true); test.PingConcurrentHostedClient(blocksPerWorker: 10).GetAwaiter().GetResult(); test.Shutdown().GetAwaiter().GetResult(); } }, ["ConcurrentPing_OneSilo"] = () => { new PingBenchmark(numSilos: 1, startClient: true).PingConcurrent().GetAwaiter().GetResult(); }, ["ConcurrentPing_TwoSilos"] = () => { new PingBenchmark(numSilos: 2, startClient: true).PingConcurrent().GetAwaiter().GetResult(); }, ["ConcurrentPing_HostedClient"] = () => { new PingBenchmark(numSilos: 1, startClient: false).PingConcurrentHostedClient().GetAwaiter().GetResult(); }, ["ConcurrentPing_SiloToSilo"] = () => { new PingBenchmark(numSilos: 2, startClient: false, grainsOnSecondariesOnly: true).PingConcurrentHostedClient(blocksPerWorker: 10).GetAwaiter().GetResult(); }, ["ConcurrentPing_SiloToSilo_Long"] = () => { new PingBenchmark(numSilos: 2, startClient: false, grainsOnSecondariesOnly: true).PingConcurrentHostedClient(blocksPerWorker: 1000).GetAwaiter().GetResult(); }, ["PingForever"] = () => { new PingBenchmark().PingForever().GetAwaiter().GetResult(); }, ["PingPongForever"] = () => { new PingBenchmark().PingPongForever().GetAwaiter().GetResult(); }, ["GrainStorage.Memory"] = () => { RunBenchmark( "Running grain storage benchmark against memory", () => { var benchmark = new GrainStorageBenchmark(); benchmark.MemorySetup(); return benchmark; }, benchmark => benchmark.RunAsync().GetAwaiter().GetResult(), benchmark => benchmark.Teardown()); }, ["GrainStorage.AzureTable"] = () => { RunBenchmark( "Running grain storage benchmark against Azure Table", () => { var benchmark = new GrainStorageBenchmark(); benchmark.AzureTableSetup(); return benchmark; }, benchmark => benchmark.RunAsync().GetAwaiter().GetResult(), benchmark => benchmark.Teardown()); }, ["GrainStorage.AzureBlob"] = () => { RunBenchmark( "Running grain storage benchmark against Azure Blob", () => { var benchmark = new GrainStorageBenchmark(); benchmark.AzureBlobSetup(); return benchmark; }, benchmark => benchmark.RunAsync().GetAwaiter().GetResult(), benchmark => benchmark.Teardown()); }, }; // requires benchmark name or 'All' word as first parameter public static void Main(string[] args) { if (args.Length > 0 && args[0].Equals("all", StringComparison.InvariantCultureIgnoreCase)) { Console.WriteLine("Running full benchmarks suite"); _benchmarks.Select(pair => pair.Value).ToList().ForEach(action => action()); return; } if (args.Length == 0 || !_benchmarks.ContainsKey(args[0])) { Console.WriteLine("Please, select benchmark, list of available:"); _benchmarks .Select(pair => pair.Key) .ToList() .ForEach(Console.WriteLine); Console.WriteLine("All"); return; } _benchmarks[args[0]](); } private static void RunBenchmark<T>(string name, Func<T> init, Action<T> benchmarkAction, Action<T> tearDown) { Console.WriteLine(name); var bench = init(); var stopWatch = Stopwatch.StartNew(); benchmarkAction(bench); Console.WriteLine($"Elapsed milliseconds: {stopWatch.ElapsedMilliseconds}"); Console.WriteLine("Press any key to continue ..."); tearDown(bench); Console.ReadLine(); } } }
// 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 { using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Globalization; using System.Runtime; using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; using System.Runtime.InteropServices; #if FEATURE_REMOTING using System.Runtime.Remoting.Metadata; #endif //FEATURE_REMOTING using System.Runtime.Serialization; using System.Security.Permissions; using System.Threading; using RuntimeTypeCache = System.RuntimeType.RuntimeTypeCache; [Serializable] [ClassInterface(ClassInterfaceType.None)] [ComDefaultInterface(typeof(_FieldInfo))] #pragma warning disable 618 [PermissionSetAttribute(SecurityAction.InheritanceDemand, Name = "FullTrust")] #pragma warning restore 618 [System.Runtime.InteropServices.ComVisible(true)] public abstract class FieldInfo : MemberInfo, _FieldInfo { #region Static Members public static FieldInfo GetFieldFromHandle(RuntimeFieldHandle handle) { if (handle.IsNullHandle()) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidHandle"), "handle"); FieldInfo f = RuntimeType.GetFieldInfo(handle.GetRuntimeFieldInfo()); Type declaringType = f.DeclaringType; if (declaringType != null && declaringType.IsGenericType) throw new ArgumentException(String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("Argument_FieldDeclaringTypeGeneric"), f.Name, declaringType.GetGenericTypeDefinition())); return f; } [System.Runtime.InteropServices.ComVisible(false)] public static FieldInfo GetFieldFromHandle(RuntimeFieldHandle handle, RuntimeTypeHandle declaringType) { if (handle.IsNullHandle()) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidHandle")); return RuntimeType.GetFieldInfo(declaringType.GetRuntimeType(), handle.GetRuntimeFieldInfo()); } #endregion #region Constructor protected FieldInfo() { } #endregion public static bool operator ==(FieldInfo left, FieldInfo right) { if (ReferenceEquals(left, right)) return true; if ((object)left == null || (object)right == null || left is RuntimeFieldInfo || right is RuntimeFieldInfo) { return false; } return left.Equals(right); } public static bool operator !=(FieldInfo left, FieldInfo right) { return !(left == right); } public override bool Equals(object obj) { return base.Equals(obj); } public override int GetHashCode() { return base.GetHashCode(); } #region MemberInfo Overrides public override MemberTypes MemberType { get { return System.Reflection.MemberTypes.Field; } } #endregion #region Public Abstract\Virtual Members public virtual Type[] GetRequiredCustomModifiers() { throw new NotImplementedException(); } public virtual Type[] GetOptionalCustomModifiers() { throw new NotImplementedException(); } [CLSCompliant(false)] public virtual void SetValueDirect(TypedReference obj, Object value) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_AbstractNonCLS")); } [CLSCompliant(false)] public virtual Object GetValueDirect(TypedReference obj) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_AbstractNonCLS")); } public abstract RuntimeFieldHandle FieldHandle { get; } public abstract Type FieldType { get; } public abstract Object GetValue(Object obj); public virtual Object GetRawConstantValue() { throw new NotSupportedException(Environment.GetResourceString("NotSupported_AbstractNonCLS")); } public abstract void SetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, CultureInfo culture); public abstract FieldAttributes Attributes { get; } #endregion #region Public Members [DebuggerStepThroughAttribute] [Diagnostics.DebuggerHidden] public void SetValue(Object obj, Object value) { // Theoretically we should set up a LookForMyCaller stack mark here and pass that along. // But to maintain backward compatibility we can't switch to calling an // internal overload that takes a stack mark. // Fortunately the stack walker skips all the reflection invocation frames including this one. // So this method will never be returned by the stack walker as the caller. // See SystemDomain::CallersMethodCallbackWithStackMark in AppDomain.cpp. SetValue(obj, value, BindingFlags.Default, Type.DefaultBinder, null); } public bool IsPublic { get { return(Attributes & FieldAttributes.FieldAccessMask) == FieldAttributes.Public; } } public bool IsPrivate { get { return(Attributes & FieldAttributes.FieldAccessMask) == FieldAttributes.Private; } } public bool IsFamily { get { return(Attributes & FieldAttributes.FieldAccessMask) == FieldAttributes.Family; } } public bool IsAssembly { get { return(Attributes & FieldAttributes.FieldAccessMask) == FieldAttributes.Assembly; } } public bool IsFamilyAndAssembly { get { return(Attributes & FieldAttributes.FieldAccessMask) == FieldAttributes.FamANDAssem; } } public bool IsFamilyOrAssembly { get { return(Attributes & FieldAttributes.FieldAccessMask) == FieldAttributes.FamORAssem; } } public bool IsStatic { get { return(Attributes & FieldAttributes.Static) != 0; } } public bool IsInitOnly { get { return(Attributes & FieldAttributes.InitOnly) != 0; } } public bool IsLiteral { get { return(Attributes & FieldAttributes.Literal) != 0; } } public bool IsNotSerialized { get { return(Attributes & FieldAttributes.NotSerialized) != 0; } } public bool IsSpecialName { get { return(Attributes & FieldAttributes.SpecialName) != 0; } } public bool IsPinvokeImpl { get { return(Attributes & FieldAttributes.PinvokeImpl) != 0; } } public virtual bool IsSecurityCritical { get { return FieldHandle.IsSecurityCritical(); } } public virtual bool IsSecuritySafeCritical { get { return FieldHandle.IsSecuritySafeCritical(); } } public virtual bool IsSecurityTransparent { get { return FieldHandle.IsSecurityTransparent(); } } #endregion #if !FEATURE_CORECLR Type _FieldInfo.GetType() { return base.GetType(); } void _FieldInfo.GetTypeInfoCount(out uint pcTInfo) { throw new NotImplementedException(); } void _FieldInfo.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo) { throw new NotImplementedException(); } void _FieldInfo.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId) { throw new NotImplementedException(); } // If you implement this method, make sure to include _FieldInfo.Invoke in VM\DangerousAPIs.h and // include _FieldInfo in SystemDomain::IsReflectionInvocationMethod in AppDomain.cpp. void _FieldInfo.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr) { throw new NotImplementedException(); } #endif } [Serializable] internal abstract class RuntimeFieldInfo : FieldInfo, ISerializable { #region Private Data Members private BindingFlags m_bindingFlags; protected RuntimeTypeCache m_reflectedTypeCache; protected RuntimeType m_declaringType; #endregion #region Constructor protected RuntimeFieldInfo() { // Used for dummy head node during population } protected RuntimeFieldInfo(RuntimeTypeCache reflectedTypeCache, RuntimeType declaringType, BindingFlags bindingFlags) { m_bindingFlags = bindingFlags; m_declaringType = declaringType; m_reflectedTypeCache = reflectedTypeCache; } #endregion #if FEATURE_REMOTING #region Legacy Remoting Cache // The size of CachedData is accounted for by BaseObjectWithCachedData in object.h. // This member is currently being used by Remoting for caching remoting data. If you // need to cache data here, talk to the Remoting team to work out a mechanism, so that // both caching systems can happily work together. private RemotingFieldCachedData m_cachedData; internal RemotingFieldCachedData RemotingCache { get { // This grabs an internal copy of m_cachedData and uses // that instead of looking at m_cachedData directly because // the cache may get cleared asynchronously. This prevents // us from having to take a lock. RemotingFieldCachedData cache = m_cachedData; if (cache == null) { cache = new RemotingFieldCachedData(this); RemotingFieldCachedData ret = Interlocked.CompareExchange(ref m_cachedData, cache, null); if (ret != null) cache = ret; } return cache; } } #endregion #endif //FEATURE_REMOTING #region NonPublic Members internal BindingFlags BindingFlags { get { return m_bindingFlags; } } private RuntimeType ReflectedTypeInternal { get { return m_reflectedTypeCache.GetRuntimeType(); } } internal RuntimeType GetDeclaringTypeInternal() { return m_declaringType; } internal RuntimeType GetRuntimeType() { return m_declaringType; } internal abstract RuntimeModule GetRuntimeModule(); #endregion #region MemberInfo Overrides public override MemberTypes MemberType { get { return MemberTypes.Field; } } public override Type ReflectedType { get { return m_reflectedTypeCache.IsGlobal ? null : ReflectedTypeInternal; } } public override Type DeclaringType { get { return m_reflectedTypeCache.IsGlobal ? null : m_declaringType; } } public override Module Module { get { return GetRuntimeModule(); } } #endregion #region Object Overrides public unsafe override String ToString() { return FieldType.FormatTypeName() + " " + Name; } #endregion #region ICustomAttributeProvider public override Object[] GetCustomAttributes(bool inherit) { return CustomAttribute.GetCustomAttributes(this, typeof(object) as RuntimeType); } public override Object[] GetCustomAttributes(Type attributeType, bool inherit) { if (attributeType == null) throw new ArgumentNullException("attributeType"); Contract.EndContractBlock(); RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; if (attributeRuntimeType == null) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),"attributeType"); return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType); } [System.Security.SecuritySafeCritical] // auto-generated public override bool IsDefined(Type attributeType, bool inherit) { if (attributeType == null) throw new ArgumentNullException("attributeType"); Contract.EndContractBlock(); RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; if (attributeRuntimeType == null) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),"attributeType"); return CustomAttribute.IsDefined(this, attributeRuntimeType); } public override IList<CustomAttributeData> GetCustomAttributesData() { return CustomAttributeData.GetCustomAttributesInternal(this); } #endregion #region FieldInfo Overrides // All implemented on derived classes #endregion #region ISerializable Implementation [System.Security.SecurityCritical] // auto-generated public void GetObjectData(SerializationInfo info, StreamingContext context) { if (info == null) throw new ArgumentNullException("info"); Contract.EndContractBlock(); MemberInfoSerializationHolder.GetSerializationInfo( info, Name, ReflectedTypeInternal, ToString(), MemberTypes.Field); } #endregion } [Serializable] internal unsafe sealed class RtFieldInfo : RuntimeFieldInfo, IRuntimeFieldInfo { #region FCalls [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] static private extern void PerformVisibilityCheckOnField(IntPtr field, Object target, RuntimeType declaringType, FieldAttributes attr, uint invocationFlags); #endregion #region Private Data Members // agressive caching private IntPtr m_fieldHandle; private FieldAttributes m_fieldAttributes; // lazy caching private string m_name; private RuntimeType m_fieldType; private INVOCATION_FLAGS m_invocationFlags; #if FEATURE_APPX private bool IsNonW8PFrameworkAPI() { if (GetRuntimeType().IsNonW8PFrameworkAPI()) return true; // Allow "value__" if (m_declaringType.IsEnum) return false; RuntimeAssembly rtAssembly = GetRuntimeAssembly(); if (rtAssembly.IsFrameworkAssembly()) { int ctorToken = rtAssembly.InvocableAttributeCtorToken; if (System.Reflection.MetadataToken.IsNullToken(ctorToken) || !CustomAttribute.IsAttributeDefined(GetRuntimeModule(), MetadataToken, ctorToken)) return true; } return false; } #endif internal INVOCATION_FLAGS InvocationFlags { get { if ((m_invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_INITIALIZED) == 0) { Type declaringType = DeclaringType; bool fIsReflectionOnlyType = (declaringType is ReflectionOnlyType); INVOCATION_FLAGS invocationFlags = 0; // first take care of all the NO_INVOKE cases if ( (declaringType != null && declaringType.ContainsGenericParameters) || (declaringType == null && Module.Assembly.ReflectionOnly) || (fIsReflectionOnlyType) ) { invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_NO_INVOKE; } // If the invocationFlags are still 0, then // this should be an usable field, determine the other flags if (invocationFlags == 0) { if ((m_fieldAttributes & FieldAttributes.InitOnly) != (FieldAttributes)0) invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_SPECIAL_FIELD; if ((m_fieldAttributes & FieldAttributes.HasFieldRVA) != (FieldAttributes)0) invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_SPECIAL_FIELD; // A public field is inaccesible to Transparent code if the field is Critical. bool needsTransparencySecurityCheck = IsSecurityCritical && !IsSecuritySafeCritical; bool needsVisibilitySecurityCheck = ((m_fieldAttributes & FieldAttributes.FieldAccessMask) != FieldAttributes.Public) || (declaringType != null && declaringType.NeedsReflectionSecurityCheck); if (needsTransparencySecurityCheck || needsVisibilitySecurityCheck) invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY; // find out if the field type is one of the following: Primitive, Enum or Pointer Type fieldType = FieldType; if (fieldType.IsPointer || fieldType.IsEnum || fieldType.IsPrimitive) invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_FIELD_SPECIAL_CAST; } #if FEATURE_APPX if (AppDomain.ProfileAPICheck && IsNonW8PFrameworkAPI()) invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API; #endif // FEATURE_APPX // must be last to avoid threading problems m_invocationFlags = invocationFlags | INVOCATION_FLAGS.INVOCATION_FLAGS_INITIALIZED; } return m_invocationFlags; } } #endregion private RuntimeAssembly GetRuntimeAssembly() { return m_declaringType.GetRuntimeAssembly(); } #region Constructor [System.Security.SecurityCritical] // auto-generated internal RtFieldInfo( RuntimeFieldHandleInternal handle, RuntimeType declaringType, RuntimeTypeCache reflectedTypeCache, BindingFlags bindingFlags) : base(reflectedTypeCache, declaringType, bindingFlags) { m_fieldHandle = handle.Value; m_fieldAttributes = RuntimeFieldHandle.GetAttributes(handle); } #endregion #region Private Members RuntimeFieldHandleInternal IRuntimeFieldInfo.Value { [System.Security.SecuritySafeCritical] get { return new RuntimeFieldHandleInternal(m_fieldHandle); } } #endregion #region Internal Members internal void CheckConsistency(Object target) { // only test instance fields if ((m_fieldAttributes & FieldAttributes.Static) != FieldAttributes.Static) { if (!m_declaringType.IsInstanceOfType(target)) { if (target == null) { throw new TargetException(Environment.GetResourceString("RFLCT.Targ_StatFldReqTarg")); } else { throw new ArgumentException( String.Format(CultureInfo.CurrentUICulture, Environment.GetResourceString("Arg_FieldDeclTarget"), Name, m_declaringType, target.GetType())); } } } } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] internal override bool CacheEquals(object o) { RtFieldInfo m = o as RtFieldInfo; if ((object)m == null) return false; return m.m_fieldHandle == m_fieldHandle; } [System.Security.SecurityCritical] [DebuggerStepThroughAttribute] [Diagnostics.DebuggerHidden] internal void InternalSetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, CultureInfo culture, ref StackCrawlMark stackMark) { INVOCATION_FLAGS invocationFlags = InvocationFlags; RuntimeType declaringType = DeclaringType as RuntimeType; if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NO_INVOKE) != 0) { if (declaringType != null && declaringType.ContainsGenericParameters) throw new InvalidOperationException(Environment.GetResourceString("Arg_UnboundGenField")); if ((declaringType == null && Module.Assembly.ReflectionOnly) || declaringType is ReflectionOnlyType) throw new InvalidOperationException(Environment.GetResourceString("Arg_ReflectionOnlyField")); throw new FieldAccessException(); } CheckConsistency(obj); RuntimeType fieldType = (RuntimeType)FieldType; value = fieldType.CheckValue(value, binder, culture, invokeAttr); #region Security Check #if FEATURE_APPX if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0) { RuntimeAssembly caller = RuntimeAssembly.GetExecutingAssembly(ref stackMark); if (caller != null && !caller.IsSafeForReflection()) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", FullName)); } #endif if ((invocationFlags & (INVOCATION_FLAGS.INVOCATION_FLAGS_SPECIAL_FIELD | INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY)) != 0) PerformVisibilityCheckOnField(m_fieldHandle, obj, m_declaringType, m_fieldAttributes, (uint)m_invocationFlags); #endregion bool domainInitialized = false; if (declaringType == null) { RuntimeFieldHandle.SetValue(this, obj, value, fieldType, m_fieldAttributes, null, ref domainInitialized); } else { domainInitialized = declaringType.DomainInitialized; RuntimeFieldHandle.SetValue(this, obj, value, fieldType, m_fieldAttributes, declaringType, ref domainInitialized); declaringType.DomainInitialized = domainInitialized; } } // UnsafeSetValue doesn't perform any consistency or visibility check. // It is the caller's responsibility to ensure the operation is safe. // When the caller needs to perform visibility checks they should call // InternalSetValue() instead. When the caller needs to perform // consistency checks they should call CheckConsistency() before // calling this method. [System.Security.SecurityCritical] // auto-generated [DebuggerStepThroughAttribute] [Diagnostics.DebuggerHidden] internal void UnsafeSetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, CultureInfo culture) { RuntimeType declaringType = DeclaringType as RuntimeType; RuntimeType fieldType = (RuntimeType)FieldType; value = fieldType.CheckValue(value, binder, culture, invokeAttr); bool domainInitialized = false; if (declaringType == null) { RuntimeFieldHandle.SetValue(this, obj, value, fieldType, m_fieldAttributes, null, ref domainInitialized); } else { domainInitialized = declaringType.DomainInitialized; RuntimeFieldHandle.SetValue(this, obj, value, fieldType, m_fieldAttributes, declaringType, ref domainInitialized); declaringType.DomainInitialized = domainInitialized; } } [System.Security.SecuritySafeCritical] [DebuggerStepThroughAttribute] [Diagnostics.DebuggerHidden] internal Object InternalGetValue(Object obj, ref StackCrawlMark stackMark) { INVOCATION_FLAGS invocationFlags = InvocationFlags; RuntimeType declaringType = DeclaringType as RuntimeType; if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NO_INVOKE) != 0) { if (declaringType != null && DeclaringType.ContainsGenericParameters) throw new InvalidOperationException(Environment.GetResourceString("Arg_UnboundGenField")); if ((declaringType == null && Module.Assembly.ReflectionOnly) || declaringType is ReflectionOnlyType) throw new InvalidOperationException(Environment.GetResourceString("Arg_ReflectionOnlyField")); throw new FieldAccessException(); } CheckConsistency(obj); #if FEATURE_APPX if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0) { RuntimeAssembly caller = RuntimeAssembly.GetExecutingAssembly(ref stackMark); if (caller != null && !caller.IsSafeForReflection()) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", FullName)); } #endif RuntimeType fieldType = (RuntimeType)FieldType; if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY) != 0) PerformVisibilityCheckOnField(m_fieldHandle, obj, m_declaringType, m_fieldAttributes, (uint)(m_invocationFlags & ~INVOCATION_FLAGS.INVOCATION_FLAGS_SPECIAL_FIELD)); return UnsafeGetValue(obj); } // UnsafeGetValue doesn't perform any consistency or visibility check. // It is the caller's responsibility to ensure the operation is safe. // When the caller needs to perform visibility checks they should call // InternalGetValue() instead. When the caller needs to perform // consistency checks they should call CheckConsistency() before // calling this method. [System.Security.SecurityCritical] [DebuggerStepThroughAttribute] [Diagnostics.DebuggerHidden] internal Object UnsafeGetValue(Object obj) { RuntimeType declaringType = DeclaringType as RuntimeType; RuntimeType fieldType = (RuntimeType)FieldType; bool domainInitialized = false; if (declaringType == null) { return RuntimeFieldHandle.GetValue(this, obj, fieldType, null, ref domainInitialized); } else { domainInitialized = declaringType.DomainInitialized; object retVal = RuntimeFieldHandle.GetValue(this, obj, fieldType, declaringType, ref domainInitialized); declaringType.DomainInitialized = domainInitialized; return retVal; } } #endregion #region MemberInfo Overrides public override String Name { [System.Security.SecuritySafeCritical] // auto-generated get { if (m_name == null) m_name = RuntimeFieldHandle.GetName(this); return m_name; } } internal String FullName { get { return String.Format("{0}.{1}", DeclaringType.FullName, Name); } } public override int MetadataToken { [System.Security.SecuritySafeCritical] // auto-generated get { return RuntimeFieldHandle.GetToken(this); } } [System.Security.SecuritySafeCritical] // auto-generated internal override RuntimeModule GetRuntimeModule() { return RuntimeTypeHandle.GetModule(RuntimeFieldHandle.GetApproxDeclaringType(this)); } #endregion #region FieldInfo Overrides public override Object GetValue(Object obj) { StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; return InternalGetValue(obj, ref stackMark); } public override object GetRawConstantValue() { throw new InvalidOperationException(); } [System.Security.SecuritySafeCritical] // auto-generated [DebuggerStepThroughAttribute] [Diagnostics.DebuggerHidden] public override Object GetValueDirect(TypedReference obj) { if (obj.IsNull) throw new ArgumentException(Environment.GetResourceString("Arg_TypedReference_Null")); Contract.EndContractBlock(); unsafe { // Passing TypedReference by reference is easier to make correct in native code return RuntimeFieldHandle.GetValueDirect(this, (RuntimeType)FieldType, &obj, (RuntimeType)DeclaringType); } } [System.Security.SecuritySafeCritical] // auto-generated [DebuggerStepThroughAttribute] [Diagnostics.DebuggerHidden] public override void SetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, CultureInfo culture) { StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; InternalSetValue(obj, value, invokeAttr, binder, culture, ref stackMark); } [System.Security.SecuritySafeCritical] // auto-generated [DebuggerStepThroughAttribute] [Diagnostics.DebuggerHidden] public override void SetValueDirect(TypedReference obj, Object value) { if (obj.IsNull) throw new ArgumentException(Environment.GetResourceString("Arg_TypedReference_Null")); Contract.EndContractBlock(); unsafe { // Passing TypedReference by reference is easier to make correct in native code RuntimeFieldHandle.SetValueDirect(this, (RuntimeType)FieldType, &obj, value, (RuntimeType)DeclaringType); } } public override RuntimeFieldHandle FieldHandle { get { Type declaringType = DeclaringType; if ((declaringType == null && Module.Assembly.ReflectionOnly) || declaringType is ReflectionOnlyType) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotAllowedInReflectionOnly")); return new RuntimeFieldHandle(this); } } internal IntPtr GetFieldHandle() { return m_fieldHandle; } public override FieldAttributes Attributes { get { return m_fieldAttributes; } } public override Type FieldType { [System.Security.SecuritySafeCritical] // auto-generated get { if (m_fieldType == null) m_fieldType = new Signature(this, m_declaringType).FieldType; return m_fieldType; } } [System.Security.SecuritySafeCritical] // auto-generated public override Type[] GetRequiredCustomModifiers() { return new Signature(this, m_declaringType).GetCustomModifiers(1, true); } [System.Security.SecuritySafeCritical] // auto-generated public override Type[] GetOptionalCustomModifiers() { return new Signature(this, m_declaringType).GetCustomModifiers(1, false); } #endregion } [Serializable] internal sealed unsafe class MdFieldInfo : RuntimeFieldInfo, ISerializable { #region Private Data Members private int m_tkField; private string m_name; private RuntimeType m_fieldType; private FieldAttributes m_fieldAttributes; #endregion #region Constructor internal MdFieldInfo( int tkField, FieldAttributes fieldAttributes, RuntimeTypeHandle declaringTypeHandle, RuntimeTypeCache reflectedTypeCache, BindingFlags bindingFlags) : base(reflectedTypeCache, declaringTypeHandle.GetRuntimeType(), bindingFlags) { m_tkField = tkField; m_name = null; m_fieldAttributes = fieldAttributes; } #endregion #region Internal Members [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] internal override bool CacheEquals(object o) { MdFieldInfo m = o as MdFieldInfo; if ((object)m == null) return false; return m.m_tkField == m_tkField && m_declaringType.GetTypeHandleInternal().GetModuleHandle().Equals( m.m_declaringType.GetTypeHandleInternal().GetModuleHandle()); } #endregion #region MemberInfo Overrides public override String Name { [System.Security.SecuritySafeCritical] // auto-generated get { if (m_name == null) m_name = GetRuntimeModule().MetadataImport.GetName(m_tkField).ToString(); return m_name; } } public override int MetadataToken { get { return m_tkField; } } internal override RuntimeModule GetRuntimeModule() { return m_declaringType.GetRuntimeModule(); } #endregion #region FieldInfo Overrides public override RuntimeFieldHandle FieldHandle { get { throw new NotSupportedException(); } } public override FieldAttributes Attributes { get { return m_fieldAttributes; } } public override bool IsSecurityCritical { get { return DeclaringType.IsSecurityCritical; } } public override bool IsSecuritySafeCritical { get { return DeclaringType.IsSecuritySafeCritical; } } public override bool IsSecurityTransparent { get { return DeclaringType.IsSecurityTransparent; } } [DebuggerStepThroughAttribute] [Diagnostics.DebuggerHidden] public override Object GetValueDirect(TypedReference obj) { return GetValue(null); } [DebuggerStepThroughAttribute] [Diagnostics.DebuggerHidden] public override void SetValueDirect(TypedReference obj,Object value) { throw new FieldAccessException(Environment.GetResourceString("Acc_ReadOnly")); } [DebuggerStepThroughAttribute] [Diagnostics.DebuggerHidden] public unsafe override Object GetValue(Object obj) { return GetValue(false); } public unsafe override Object GetRawConstantValue() { return GetValue(true); } [System.Security.SecuritySafeCritical] // auto-generated private unsafe Object GetValue(bool raw) { // Cannot cache these because they could be user defined non-agile enumerations Object value = MdConstant.GetValue(GetRuntimeModule().MetadataImport, m_tkField, FieldType.GetTypeHandleInternal(), raw); if (value == DBNull.Value) throw new NotSupportedException(Environment.GetResourceString("Arg_EnumLitValueNotFound")); return value; } [DebuggerStepThroughAttribute] [Diagnostics.DebuggerHidden] public override void SetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, CultureInfo culture) { throw new FieldAccessException(Environment.GetResourceString("Acc_ReadOnly")); } public override Type FieldType { [System.Security.SecuritySafeCritical] // auto-generated get { if (m_fieldType == null) { ConstArray fieldMarshal = GetRuntimeModule().MetadataImport.GetSigOfFieldDef(m_tkField); m_fieldType = new Signature(fieldMarshal.Signature.ToPointer(), (int)fieldMarshal.Length, m_declaringType).FieldType; } return m_fieldType; } } public override Type[] GetRequiredCustomModifiers() { return EmptyArray<Type>.Value; } public override Type[] GetOptionalCustomModifiers() { return EmptyArray<Type>.Value; } #endregion } }
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using FluentAssertions; using Microsoft.Build.Construction; using Microsoft.DotNet.Tools.Test.Utilities; using Msbuild.Tests.Utilities; using System; using System.IO; using Xunit; namespace Microsoft.DotNet.Cli.List.Reference.Tests { public class GivenDotnetListReference : TestBase { private const string HelpText = @".NET Core Project-to-Project dependency viewer Usage: dotnet list <PROJECT> reference [options] Arguments: <PROJECT> The project file to operate on. If a file is not specified, the command will search the current directory for one. Options: -h, --help Show help information "; const string FrameworkNet451Arg = "-f net451"; const string ConditionFrameworkNet451 = "== 'net451'"; const string FrameworkNetCoreApp10Arg = "-f netcoreapp1.0"; const string ConditionFrameworkNetCoreApp10 = "== 'netcoreapp1.0'"; [Theory] [InlineData("--help")] [InlineData("-h")] public void WhenHelpOptionIsPassedItPrintsUsage(string helpArg) { var cmd = new ListReferenceCommand().Execute(helpArg); cmd.Should().Pass(); cmd.StdOut.Should().BeVisuallyEquivalentTo(HelpText); } [Theory] [InlineData("")] [InlineData("unknownCommandName")] public void WhenNoCommandIsPassedItPrintsError(string commandName) { var cmd = new DotnetCommand() .ExecuteWithCapturedOutput($"list {commandName}"); cmd.Should().Fail(); cmd.StdErr.Should().Be("Required command was not provided."); } [Fact] public void WhenTooManyArgumentsArePassedItPrintsError() { var cmd = new ListReferenceCommand() .WithProject("one two three") .Execute("proj.csproj"); cmd.ExitCode.Should().NotBe(0); cmd.StdErr.Should().BeVisuallyEquivalentTo( "Unrecognized command or argument 'two'\r\nUnrecognized command or argument 'three'"); } [Theory] [InlineData("idontexist.csproj")] [InlineData("ihave?inv@lid/char\\acters")] public void WhenNonExistingProjectIsPassedItPrintsErrorAndUsage(string projName) { var setup = Setup(); var cmd = new ListReferenceCommand() .WithWorkingDirectory(setup.TestRoot) .WithProject(projName) .Execute($"\"{setup.ValidRefCsprojPath}\""); cmd.ExitCode.Should().NotBe(0); cmd.StdErr.Should().Be($"Could not find project or directory `{projName}`."); cmd.StdOut.Should().BeVisuallyEquivalentTo(HelpText); } [Fact] public void WhenBrokenProjectIsPassedItPrintsErrorAndUsage() { string projName = "Broken/Broken.csproj"; var setup = Setup(); var cmd = new ListReferenceCommand() .WithWorkingDirectory(setup.TestRoot) .WithProject(projName) .Execute($"\"{setup.ValidRefCsprojPath}\""); cmd.ExitCode.Should().NotBe(0); cmd.StdErr.Should().Be("Project `Broken/Broken.csproj` is invalid."); cmd.StdOut.Should().BeVisuallyEquivalentTo(HelpText); } [Fact] public void WhenMoreThanOneProjectExistsInTheDirectoryItPrintsErrorAndUsage() { var setup = Setup(); var workingDir = Path.Combine(setup.TestRoot, "MoreThanOne"); var cmd = new ListReferenceCommand() .WithWorkingDirectory(workingDir) .Execute($"\"{setup.ValidRefCsprojRelToOtherProjPath}\""); cmd.ExitCode.Should().NotBe(0); cmd.StdErr.Should().Be($"Found more than one project in `{workingDir + Path.DirectorySeparatorChar}`. Please specify which one to use."); cmd.StdOut.Should().BeVisuallyEquivalentTo(HelpText); } [Fact] public void WhenNoProjectsExistsInTheDirectoryItPrintsErrorAndUsage() { var setup = Setup(); var cmd = new ListReferenceCommand() .WithWorkingDirectory(setup.TestRoot) .Execute($"\"{setup.ValidRefCsprojPath}\""); cmd.ExitCode.Should().NotBe(0); cmd.StdErr.Should().Be($"Could not find any project in `{setup.TestRoot + Path.DirectorySeparatorChar}`."); cmd.StdOut.Should().BeVisuallyEquivalentTo(HelpText); } [Fact] public void WhenNoProjectReferencesArePresentInTheProjectItPrintsError() { var lib = NewLib(); var cmd = new ListReferenceCommand() .WithProject(lib.CsProjPath) .Execute(); cmd.Should().Pass(); cmd.StdOut.Should().Be($"There are no Project to Project references in project {lib.CsProjPath}. ;; Project to Project is the type of the item being requested (project, package, p2p) and {lib.CsProjPath} is the object operated on (a project file or a solution file). "); } [Fact] public void ItPrintsSingleReference() { const string OutputText = @"Project reference(s) -------------------- ..\ref\ref.csproj"; var lib = NewLib("lib"); string ref1 = NewLib("ref").CsProjPath; AddValidRef(ref1, lib); var cmd = new ListReferenceCommand() .WithProject(lib.CsProjPath) .Execute(); cmd.Should().Pass(); cmd.StdOut.Should().BeVisuallyEquivalentTo(OutputText); } [Fact] public void ItPrintsMultipleReferences() { const string OutputText = @"Project reference(s) -------------------- ..\ref1\ref1.csproj ..\ref2\ref2.csproj ..\ref3\ref3.csproj"; var lib = NewLib("lib"); string ref1 = NewLib("ref1").CsProjPath; string ref2 = NewLib("ref2").CsProjPath; string ref3 = NewLib("ref3").CsProjPath; AddValidRef(ref1, lib); AddValidRef(ref2, lib); AddValidRef(ref3, lib); var cmd = new ListReferenceCommand() .WithProject(lib.CsProjPath) .Execute(); cmd.Should().Pass(); cmd.StdOut.Should().BeVisuallyEquivalentTo(OutputText); } private TestSetup Setup([System.Runtime.CompilerServices.CallerMemberName] string callingMethod = nameof(Setup), string identifier = "") { return new TestSetup( TestAssets.Get(TestSetup.TestGroup, TestSetup.ProjectName) .CreateInstance(callingMethod: callingMethod, identifier: identifier) .WithSourceFiles() .Root .FullName); } private ProjDir NewDir(string testProjectName = "temp", [System.Runtime.CompilerServices.CallerMemberName] string callingMethod = nameof(NewDir), string identifier = "") { return new ProjDir(TestAssets.CreateTestDirectory(testProjectName: testProjectName, callingMethod: callingMethod, identifier: identifier).FullName); } private ProjDir NewLib(string testProjectName = "temp", [System.Runtime.CompilerServices.CallerMemberName] string callingMethod = nameof(NewDir), string identifier = "") { var dir = NewDir(testProjectName: testProjectName, callingMethod: callingMethod, identifier: identifier); try { string newArgs = $"classlib -o \"{dir.Path}\" --debug:ephemeral-hive --no-restore"; new NewCommandShim() .WithWorkingDirectory(dir.Path) .ExecuteWithCapturedOutput(newArgs) .Should().Pass(); } catch (System.ComponentModel.Win32Exception e) { throw new Exception($"Intermittent error in `dotnet new` occurred when running it in dir `{dir.Path}`\nException:\n{e}"); } return dir; } private void AddValidRef(string path, ProjDir proj) { new AddReferenceCommand() .WithProject(proj.CsProjPath) .Execute($"\"{path}\"") .Should().Pass(); } } }
#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) using System; using Org.BouncyCastle.Crypto.Modes; using Org.BouncyCastle.Crypto.Paddings; using Org.BouncyCastle.Crypto.Parameters; namespace Org.BouncyCastle.Crypto.Macs { /** * implements a Cipher-FeedBack (CFB) mode on top of a simple cipher. */ class MacCFBBlockCipher : IBlockCipher { private byte[] IV; private byte[] cfbV; private byte[] cfbOutV; private readonly int blockSize; private readonly IBlockCipher cipher; /** * Basic constructor. * * @param cipher the block cipher to be used as the basis of the * feedback mode. * @param blockSize the block size in bits (note: a multiple of 8) */ public MacCFBBlockCipher( IBlockCipher cipher, int bitBlockSize) { this.cipher = cipher; this.blockSize = bitBlockSize / 8; this.IV = new byte[cipher.GetBlockSize()]; this.cfbV = new byte[cipher.GetBlockSize()]; this.cfbOutV = new byte[cipher.GetBlockSize()]; } /** * Initialise the cipher and, possibly, the initialisation vector (IV). * If an IV isn't passed as part of the parameter, the IV will be all zeros. * An IV which is too short is handled in FIPS compliant fashion. * * @param param the key and other data required by the cipher. * @exception ArgumentException if the parameters argument is * inappropriate. */ public void Init( bool forEncryption, ICipherParameters parameters) { if (parameters is ParametersWithIV) { ParametersWithIV ivParam = (ParametersWithIV)parameters; byte[] iv = ivParam.GetIV(); if (iv.Length < IV.Length) { Array.Copy(iv, 0, IV, IV.Length - iv.Length, iv.Length); } else { Array.Copy(iv, 0, IV, 0, IV.Length); } parameters = ivParam.Parameters; } Reset(); cipher.Init(true, parameters); } /** * return the algorithm name and mode. * * @return the name of the underlying algorithm followed by "/CFB" * and the block size in bits. */ public string AlgorithmName { get { return cipher.AlgorithmName + "/CFB" + (blockSize * 8); } } public bool IsPartialBlockOkay { get { return true; } } /** * return the block size we are operating at. * * @return the block size we are operating at (in bytes). */ public int GetBlockSize() { return blockSize; } /** * Process one block of input from the array in and write it to * the out array. * * @param in the array containing the input data. * @param inOff offset into the in array the data starts at. * @param out the array the output data will be copied into. * @param outOff the offset into the out array the output will start at. * @exception DataLengthException if there isn't enough data in in, or * space in out. * @exception InvalidOperationException if the cipher isn't initialised. * @return the number of bytes processed and produced. */ public int ProcessBlock( byte[] input, int inOff, byte[] outBytes, int outOff) { if ((inOff + blockSize) > input.Length) throw new DataLengthException("input buffer too short"); if ((outOff + blockSize) > outBytes.Length) throw new DataLengthException("output buffer too short"); cipher.ProcessBlock(cfbV, 0, cfbOutV, 0); // // XOR the cfbV with the plaintext producing the cipher text // for (int i = 0; i < blockSize; i++) { outBytes[outOff + i] = (byte)(cfbOutV[i] ^ input[inOff + i]); } // // change over the input block. // Array.Copy(cfbV, blockSize, cfbV, 0, cfbV.Length - blockSize); Array.Copy(outBytes, outOff, cfbV, cfbV.Length - blockSize, blockSize); return blockSize; } /** * reset the chaining vector back to the IV and reset the underlying * cipher. */ public void Reset() { IV.CopyTo(cfbV, 0); cipher.Reset(); } public void GetMacBlock( byte[] mac) { cipher.ProcessBlock(cfbV, 0, mac, 0); } } public class CfbBlockCipherMac : IMac { private byte[] mac; private byte[] Buffer; private int bufOff; private MacCFBBlockCipher cipher; private IBlockCipherPadding padding; private int macSize; /** * create a standard MAC based on a CFB block cipher. This will produce an * authentication code half the length of the block size of the cipher, with * the CFB mode set to 8 bits. * * @param cipher the cipher to be used as the basis of the MAC generation. */ public CfbBlockCipherMac( IBlockCipher cipher) : this(cipher, 8, (cipher.GetBlockSize() * 8) / 2, null) { } /** * create a standard MAC based on a CFB block cipher. This will produce an * authentication code half the length of the block size of the cipher, with * the CFB mode set to 8 bits. * * @param cipher the cipher to be used as the basis of the MAC generation. * @param padding the padding to be used. */ public CfbBlockCipherMac( IBlockCipher cipher, IBlockCipherPadding padding) : this(cipher, 8, (cipher.GetBlockSize() * 8) / 2, padding) { } /** * create a standard MAC based on a block cipher with the size of the * MAC been given in bits. This class uses CFB mode as the basis for the * MAC generation. * <p> * Note: the size of the MAC must be at least 24 bits (FIPS Publication 81), * or 16 bits if being used as a data authenticator (FIPS Publication 113), * and in general should be less than the size of the block cipher as it reduces * the chance of an exhaustive attack (see Handbook of Applied Cryptography). * </p> * @param cipher the cipher to be used as the basis of the MAC generation. * @param cfbBitSize the size of an output block produced by the CFB mode. * @param macSizeInBits the size of the MAC in bits, must be a multiple of 8. */ public CfbBlockCipherMac( IBlockCipher cipher, int cfbBitSize, int macSizeInBits) : this(cipher, cfbBitSize, macSizeInBits, null) { } /** * create a standard MAC based on a block cipher with the size of the * MAC been given in bits. This class uses CFB mode as the basis for the * MAC generation. * <p> * Note: the size of the MAC must be at least 24 bits (FIPS Publication 81), * or 16 bits if being used as a data authenticator (FIPS Publication 113), * and in general should be less than the size of the block cipher as it reduces * the chance of an exhaustive attack (see Handbook of Applied Cryptography). * </p> * @param cipher the cipher to be used as the basis of the MAC generation. * @param cfbBitSize the size of an output block produced by the CFB mode. * @param macSizeInBits the size of the MAC in bits, must be a multiple of 8. * @param padding a padding to be used. */ public CfbBlockCipherMac( IBlockCipher cipher, int cfbBitSize, int macSizeInBits, IBlockCipherPadding padding) { if ((macSizeInBits % 8) != 0) throw new ArgumentException("MAC size must be multiple of 8"); mac = new byte[cipher.GetBlockSize()]; this.cipher = new MacCFBBlockCipher(cipher, cfbBitSize); this.padding = padding; this.macSize = macSizeInBits / 8; Buffer = new byte[this.cipher.GetBlockSize()]; bufOff = 0; } public string AlgorithmName { get { return cipher.AlgorithmName; } } public void Init( ICipherParameters parameters) { Reset(); cipher.Init(true, parameters); } public int GetMacSize() { return macSize; } public void Update( byte input) { if (bufOff == Buffer.Length) { cipher.ProcessBlock(Buffer, 0, mac, 0); bufOff = 0; } Buffer[bufOff++] = input; } public void BlockUpdate( byte[] input, int inOff, int len) { if (len < 0) throw new ArgumentException("Can't have a negative input length!"); int blockSize = cipher.GetBlockSize(); int resultLen = 0; int gapLen = blockSize - bufOff; if (len > gapLen) { Array.Copy(input, inOff, Buffer, bufOff, gapLen); resultLen += cipher.ProcessBlock(Buffer, 0, mac, 0); bufOff = 0; len -= gapLen; inOff += gapLen; while (len > blockSize) { resultLen += cipher.ProcessBlock(input, inOff, mac, 0); len -= blockSize; inOff += blockSize; } } Array.Copy(input, inOff, Buffer, bufOff, len); bufOff += len; } public int DoFinal( byte[] output, int outOff) { int blockSize = cipher.GetBlockSize(); // pad with zeroes if (this.padding == null) { while (bufOff < blockSize) { Buffer[bufOff++] = 0; } } else { padding.AddPadding(Buffer, bufOff); } cipher.ProcessBlock(Buffer, 0, mac, 0); cipher.GetMacBlock(mac); Array.Copy(mac, 0, output, outOff, macSize); Reset(); return macSize; } /** * Reset the mac generator. */ public void Reset() { // Clear the buffer. Array.Clear(Buffer, 0, Buffer.Length); bufOff = 0; // Reset the underlying cipher. cipher.Reset(); } } } #endif
using System; using System.Data; using System.Data.OleDb; namespace MyMeta.Sql { #if ENTERPRISE using System.Runtime.InteropServices; [ComVisible(true), ClassInterface(ClassInterfaceType.AutoDual), ComDefaultInterface(typeof(IColumns))] #endif public class SqlColumns : Columns { public SqlColumns() { } internal DataColumn f_TypeName = null; internal DataColumn f_AutoKey = null; override internal void LoadForTable() { DataTable metaData = this.LoadData(OleDbSchemaGuid.Columns, new Object[] {this.Table.Database.Name, this.Table.Schema, this.Table.Name}); PopulateArray(metaData); LoadExtraData(this.Table.Name, "T"); LoadAutoKeyInfo(); LoadDescriptions(); } override internal void LoadForView() { DataTable metaData = this.LoadData(OleDbSchemaGuid.Columns, new Object[] {this.View.Database.Name, this.View.Schema, this.View.Name}); PopulateArray(metaData); LoadExtraData(this.View.Name, "V"); } private void LoadExtraData(string name, string type) { try { string dbName = ("T" == type) ? this.Table.Database.Name : this.View.Database.Name; string schema = ("T" == type) ? this.Table.Schema : this.View.Schema; string select = "EXEC [" + dbName + "].dbo.sp_columns '" + name + "', '" + schema + "'"; using (OleDbConnection cn = new OleDbConnection(dbRoot.ConnectionString)) { cn.Open(); cn.ChangeDatabase("[" + dbName + "]"); OleDbDataAdapter adapter = new OleDbDataAdapter(select, cn); DataTable dataTable = new DataTable(); adapter.Fill(dataTable); if (this._array.Count > 0) { Column col = this._array[0] as Column; f_TypeName = new DataColumn("TYPE_NAME", typeof(string)); col._row.Table.Columns.Add(f_TypeName); string typeName = ""; DataRowCollection rows = dataTable.Rows; int count = this._array.Count; Column c = null; for (int index = 0; index < count; index++) { c = (Column)this[index]; typeName = rows[index]["TYPE_NAME"] as string; if (typeName.EndsWith(" identity")) { typeName = typeName.Replace(" identity", ""); typeName = typeName.Replace("()", ""); c._row["TYPE_NAME"] = typeName; } else { c._row["TYPE_NAME"] = typeName; } } } select = @"select COLUMN_NAME, DATA_TYPE from INFORMATION_SCHEMA.COLUMNS where table_schema = '" + schema + @"' and table_catalog='" + dbName + @"' and table_name='" + name + @"' and DATA_TYPE in ('nvarchar', 'varchar', 'varbinary') and character_maximum_length=-1 and character_octet_length=-1;"; adapter = new OleDbDataAdapter(select, cn); dataTable = new DataTable(); adapter.Fill(dataTable); Column colz = null; foreach (DataRow row in dataTable.Rows) { colz = this[row["COLUMN_NAME"] as string] as Column; if (null != colz) { colz._row["TYPE_NAME"] = row["DATA_TYPE"] as string; } } cn.Close(); } } catch {} } private void LoadDescriptions() { try { string select = @"SELECT objName, value FROM ::fn_listextendedproperty ('MS_Description', 'user', '" + this.Table.Schema + @"', 'table', '" + this.Table.Name + @"', 'column', null) UNION SELECT objName, value FROM ::fn_listextendedproperty ('MS_Description', 'schema', '" + this.Table.Schema + @"', 'table', '" + this.Table.Name + @"', 'column', null)"; OleDbConnection cn = new OleDbConnection(dbRoot.ConnectionString); cn.Open(); cn.ChangeDatabase("[" + this.Table.Database.Name + "]"); OleDbDataAdapter adapter = new OleDbDataAdapter(select, cn); DataTable dataTable = new DataTable(); adapter.Fill(dataTable); cn.Close(); Column c; foreach(DataRow row in dataTable.Rows) { c = this[row["objName"] as string] as Column; if(null != c) { c._row["DESCRIPTION"] = row["value"] as string; } } } catch(Exception ex) { string s = ex.Message; } } private void LoadAutoKeyInfo() { try { string select = @"SELECT TABLE_NAME, COLUMN_NAME, IDENT_SEED('[" + this.Table.Name + "]') AS AUTO_KEY_SEED, IDENT_INCR('[" + this.Table.Name + "]') AS AUTO_KEY_INCREMENT " + "FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '" + this.Table.Name + "' AND TABLE_SCHEMA = '" + this.Table.Schema + "' AND " + "columnproperty(object_id('[" + this.Table.Schema + "].[" + this.Table.Name + "]'), COLUMN_NAME, 'IsIdentity') = 1"; OleDbConnection cn = new OleDbConnection(dbRoot.ConnectionString); cn.Open(); cn.ChangeDatabase("[" + this.Table.Database.Name + "]"); OleDbDataAdapter adapter = new OleDbDataAdapter(select, cn); DataTable dataTable = new DataTable(); adapter.Fill(dataTable); cn.Close(); if(dataTable.Rows.Count > 0) { f_AutoKeySeed = new DataColumn("AUTO_KEY_SEED", typeof(System.Int32)); f_AutoKeyIncrement = new DataColumn("AUTO_KEY_INCREMENT", typeof(System.Int32)); f_AutoKey = new DataColumn("AUTO_INCREMENT", typeof(Boolean)); Column col = this._array[0] as Column; col._row.Table.Columns.Add(f_AutoKeySeed); col._row.Table.Columns.Add(f_AutoKeyIncrement); col._row.Table.Columns.Add(f_AutoKey); DataRowCollection rows = dataTable.Rows; DataRow row; for(int i = 0; i < rows.Count; i++) { row = rows[i]; col = this[row["COLUMN_NAME"]] as Column; col._row["AUTO_KEY_SEED"] = row["AUTO_KEY_SEED"]; col._row["AUTO_KEY_INCREMENT"] = row["AUTO_KEY_INCREMENT"]; col._row["AUTO_INCREMENT"] = true; } } } catch(Exception ex) { string s = ex.Message; } } } }
/* Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved. */ /****************************************************************************** * * You may not use the identified files except in compliance with The MIT * License (the "License.") * * You may obtain a copy of the License at * https://github.com/oracle/Oracle.NET/blob/master/LICENSE * * 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.Data; using System.Text; using Oracle.ManagedDataAccess.Client; namespace Sample1 { /// <summary> /// Sample 1: Demonstrates how a REF Cursor is obtained as an /// OracleDataReader /// </summary> class Sample1 { /// <summary> /// The main entry point for the application. /// </summary> static void Main(string[] args) { string constr = "User Id=scott;Password=<PASSWORD>;Data Source=oracle"; // Connect OracleConnection con = Connect(constr); // Setup the necessary Table Setup(con); // Set the command OracleCommand cmd = new OracleCommand("TEST.Get1CurOut", con); cmd.CommandType = CommandType.StoredProcedure; // Bind OracleParameter oparam = cmd.Parameters.Add("refcursor", OracleDbType.RefCursor); oparam.Direction = ParameterDirection.Output; // Execute command OracleDataReader reader; try { reader = cmd.ExecuteReader(); // show the first row reader.Read(); // Print out SCOTT.EMP EMPNO column Console.WriteLine("EMPNO: {0}", reader.GetDecimal(0)); // Print out SCOTT.EMP ENAME column Console.WriteLine("ENAME: {0}", reader.GetString(1)); } catch (Exception e) { Console.WriteLine("Error: {0}", e.Message); } finally { // Dispose OracleCommand object cmd.Dispose(); // Close and Dispose OracleConnection object con.Close(); con.Dispose(); } } /// <summary> /// Wrapper for Opening a new Connection /// </summary> /// <param name="connectStr"></param> /// <returns></returns> public static OracleConnection Connect(string connectStr) { OracleConnection con = new OracleConnection(connectStr); try { con.Open(); } catch (Exception e) { Console.WriteLine("Error: {0}", e.Message); } return con; } /// <summary> /// Setup the necessary Tables & Test Data /// </summary> /// <param name="connectStr"></param> public static void Setup(OracleConnection con) { StringBuilder blr; OracleCommand cmd = new OracleCommand("",con); // Create multimedia table blr = new StringBuilder(); blr.Append("DROP TABLE multimedia_tab"); cmd.CommandText = blr.ToString(); try { cmd.ExecuteNonQuery(); } catch (Exception e) { Console.WriteLine("Warning: {0}", e.Message); } blr = new StringBuilder(); blr.Append("CREATE TABLE multimedia_tab(thekey NUMBER(4) PRIMARY KEY,"); blr.Append("story CLOB, sound BLOB)"); cmd.CommandText = blr.ToString(); try { cmd.ExecuteNonQuery(); } catch (Exception e) { Console.WriteLine("Error: {0}", e.Message); } blr = new StringBuilder(); blr.Append("INSERT INTO multimedia_tab values("); blr.Append("1,"); blr.Append("'This is a long story. Once upon a time ...',"); blr.Append("'656667686970717273747576777879808182838485')"); cmd.CommandText = blr.ToString(); try { cmd.ExecuteNonQuery(); } catch (Exception e) { Console.WriteLine("Error: {0}", e.Message); } // Create Package Header blr = new StringBuilder(); blr.Append("CREATE OR REPLACE PACKAGE TEST is "); blr.Append("TYPE refcursor is ref cursor;"); blr.Append("FUNCTION Ret1Cur return refCursor;"); blr.Append("PROCEDURE Get1CurOut(p_cursor1 out refCursor);"); blr.Append("FUNCTION Get3Cur (p_cursor1 out refCursor,"); blr.Append("p_cursor2 out refCursor)"); blr.Append("return refCursor;"); blr.Append("FUNCTION Get1Cur return refCursor;"); blr.Append("PROCEDURE UpdateRefCur(new_story in VARCHAR,"); blr.Append("clipid in NUMBER);"); blr.Append("PROCEDURE GetStoryForClip1(p_cursor out refCursor);"); blr.Append("PROCEDURE GetRefCurData (p_cursor out refCursor,myStory out VARCHAR2);"); blr.Append("end TEST;"); cmd.CommandText = blr.ToString(); try { cmd.ExecuteNonQuery(); } catch (Exception e) { Console.WriteLine("Error: {0}", e.Message); } // Create Package Body blr = new StringBuilder(); blr.Append("create or replace package body TEST is "); blr.Append("FUNCTION Ret1Cur return refCursor is "); blr.Append("p_cursor refCursor; "); blr.Append("BEGIN "); blr.Append("open p_cursor for select * from multimedia_tab; "); blr.Append("return (p_cursor); "); blr.Append("END Ret1Cur; "); blr.Append("PROCEDURE Get1CurOut(p_cursor1 out refCursor) is "); blr.Append("BEGIN "); blr.Append("OPEN p_cursor1 for select * from emp; "); blr.Append("END Get1CurOut; "); blr.Append("FUNCTION Get3Cur (p_cursor1 out refCursor, "); blr.Append("p_cursor2 out refCursor)"); blr.Append("return refCursor is "); blr.Append("p_cursor refCursor; "); blr.Append("BEGIN "); blr.Append("open p_cursor for select * from multimedia_tab; "); blr.Append("open p_cursor1 for select * from emp; "); blr.Append("open p_cursor2 for select * from dept; "); blr.Append("return (p_cursor); "); blr.Append("END Get3Cur; "); blr.Append("FUNCTION Get1Cur return refCursor is "); blr.Append("p_cursor refCursor; "); blr.Append("BEGIN "); blr.Append("open p_cursor for select * from multimedia_tab; "); blr.Append("return (p_cursor); "); blr.Append("END Get1Cur; "); blr.Append("PROCEDURE UpdateRefCur(new_story in VARCHAR, "); blr.Append("clipid in NUMBER) is "); blr.Append("BEGIN "); blr.Append("Update multimedia_tab set story = new_story where thekey = clipid; "); blr.Append("END UpdateRefCur; "); blr.Append("PROCEDURE GetStoryForClip1(p_cursor out refCursor) is "); blr.Append("BEGIN "); blr.Append("open p_cursor for "); blr.Append("Select story from multimedia_tab where thekey = 1; "); blr.Append("END GetStoryForClip1; "); blr.Append("PROCEDURE GetRefCurData (p_cursor out refCursor,"); blr.Append("myStory out VARCHAR2) is "); blr.Append("BEGIN "); blr.Append("FETCH p_cursor into myStory; "); blr.Append("END GetRefCurData; "); blr.Append("end TEST;"); cmd.CommandText = blr.ToString(); try { cmd.ExecuteNonQuery(); } catch (Exception e) { Console.WriteLine("Error: {0}", e.Message); } } } }
// 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; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Reflection; using System.Runtime.InteropServices; using System.Text; using System.Threading; namespace System { public static partial class Environment { private static Func<string, object>? s_directoryCreateDirectory; private static string CurrentDirectoryCore { get => Interop.Sys.GetCwd(); set => Interop.CheckIo(Interop.Sys.ChDir(value), value, isDirectory: true); } private static string ExpandEnvironmentVariablesCore(string name) { var result = new ValueStringBuilder(stackalloc char[128]); int lastPos = 0, pos; while (lastPos < name.Length && (pos = name.IndexOf('%', lastPos + 1)) >= 0) { if (name[lastPos] == '%') { string key = name.Substring(lastPos + 1, pos - lastPos - 1); string? value = GetEnvironmentVariable(key); if (value != null) { result.Append(value); lastPos = pos + 1; continue; } } result.Append(name.AsSpan(lastPos, pos - lastPos)); lastPos = pos; } result.Append(name.AsSpan(lastPos)); return result.ToString(); } private static string GetFolderPathCore(SpecialFolder folder, SpecialFolderOption option) { // Get the path for the SpecialFolder string path = GetFolderPathCoreWithoutValidation(folder); Debug.Assert(path != null); // If we didn't get one, or if we got one but we're not supposed to verify it, // or if we're supposed to verify it and it passes verification, return the path. if (path.Length == 0 || option == SpecialFolderOption.DoNotVerify || Interop.Sys.Access(path, Interop.Sys.AccessMode.R_OK) == 0) { return path; } // Failed verification. If None, then we're supposed to return an empty string. // If Create, we're supposed to create it and then return the path. if (option == SpecialFolderOption.None) { return string.Empty; } else { Debug.Assert(option == SpecialFolderOption.Create); // TODO #11151: Replace with Directory.CreateDirectory once we have access to System.IO.FileSystem here. Func<string, object> createDirectory = LazyInitializer.EnsureInitialized(ref s_directoryCreateDirectory, () => { Type dirType = Type.GetType("System.IO.Directory, System.IO.FileSystem, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", throwOnError: true)!; MethodInfo mi = dirType.GetTypeInfo().GetDeclaredMethod("CreateDirectory")!; return (Func<string, object>)mi.CreateDelegate(typeof(Func<string, object>)); }); createDirectory(path); return path; } } private static string GetFolderPathCoreWithoutValidation(SpecialFolder folder) { // First handle any paths that involve only static paths, avoiding the overheads of getting user-local paths. // https://www.freedesktop.org/software/systemd/man/file-hierarchy.html switch (folder) { case SpecialFolder.CommonApplicationData: return "/usr/share"; case SpecialFolder.CommonTemplates: return "/usr/share/templates"; #if PLATFORM_OSX case SpecialFolder.ProgramFiles: return "/Applications"; case SpecialFolder.System: return "/System"; #endif } // All other paths are based on the XDG Base Directory Specification: // https://specifications.freedesktop.org/basedir-spec/latest/ string? home = null; try { home = PersistedFiles.GetHomeDirectory(); } catch (Exception exc) { Debug.Fail($"Unable to get home directory: {exc}"); } // Fall back to '/' when we can't determine the home directory. // This location isn't writable by non-root users which provides some safeguard // that the application doesn't write data which is meant to be private. if (string.IsNullOrEmpty(home)) { home = "/"; } // TODO: Consider caching (or precomputing and caching) all subsequent results. // This would significantly improve performance for repeated access, at the expense // of not being responsive to changes in the underlying environment variables, // configuration files, etc. switch (folder) { case SpecialFolder.UserProfile: case SpecialFolder.MyDocuments: // same value as Personal return home; case SpecialFolder.ApplicationData: return GetXdgConfig(home); case SpecialFolder.LocalApplicationData: // "$XDG_DATA_HOME defines the base directory relative to which user specific data files should be stored." // "If $XDG_DATA_HOME is either not set or empty, a default equal to $HOME/.local/share should be used." string? data = GetEnvironmentVariable("XDG_DATA_HOME"); if (string.IsNullOrEmpty(data) || data[0] != '/') { data = Path.Combine(home, ".local", "share"); } return data; case SpecialFolder.Desktop: case SpecialFolder.DesktopDirectory: return ReadXdgDirectory(home, "XDG_DESKTOP_DIR", "Desktop"); case SpecialFolder.Templates: return ReadXdgDirectory(home, "XDG_TEMPLATES_DIR", "Templates"); case SpecialFolder.MyVideos: return ReadXdgDirectory(home, "XDG_VIDEOS_DIR", "Videos"); #if PLATFORM_OSX case SpecialFolder.MyMusic: return Path.Combine(home, "Music"); case SpecialFolder.MyPictures: return Path.Combine(home, "Pictures"); case SpecialFolder.Fonts: return Path.Combine(home, "Library", "Fonts"); case SpecialFolder.Favorites: return Path.Combine(home, "Library", "Favorites"); case SpecialFolder.InternetCache: return Path.Combine(home, "Library", "Caches"); #else case SpecialFolder.MyMusic: return ReadXdgDirectory(home, "XDG_MUSIC_DIR", "Music"); case SpecialFolder.MyPictures: return ReadXdgDirectory(home, "XDG_PICTURES_DIR", "Pictures"); case SpecialFolder.Fonts: return Path.Combine(home, ".fonts"); #endif } // No known path for the SpecialFolder return string.Empty; } private static string GetXdgConfig(string home) { // "$XDG_CONFIG_HOME defines the base directory relative to which user specific configuration files should be stored." // "If $XDG_CONFIG_HOME is either not set or empty, a default equal to $HOME/.config should be used." string? config = GetEnvironmentVariable("XDG_CONFIG_HOME"); if (string.IsNullOrEmpty(config) || config[0] != '/') { config = Path.Combine(home, ".config"); } return config; } private static string ReadXdgDirectory(string homeDir, string key, string fallback) { Debug.Assert(!string.IsNullOrEmpty(homeDir), $"Expected non-empty homeDir"); Debug.Assert(!string.IsNullOrEmpty(key), $"Expected non-empty key"); Debug.Assert(!string.IsNullOrEmpty(fallback), $"Expected non-empty fallback"); string? envPath = GetEnvironmentVariable(key); if (!string.IsNullOrEmpty(envPath) && envPath[0] == '/') { return envPath; } // Use the user-dirs.dirs file to look up the right config. // Note that the docs also highlight a list of directories in which to look for this file: // "$XDG_CONFIG_DIRS defines the preference-ordered set of base directories to search for configuration files in addition // to the $XDG_CONFIG_HOME base directory. The directories in $XDG_CONFIG_DIRS should be separated with a colon ':'. If // $XDG_CONFIG_DIRS is either not set or empty, a value equal to / etc / xdg should be used." // For simplicity, we don't currently do that. We can add it if/when necessary. string userDirsPath = Path.Combine(GetXdgConfig(homeDir), "user-dirs.dirs"); if (Interop.Sys.Access(userDirsPath, Interop.Sys.AccessMode.R_OK) == 0) { try { using (var reader = new StreamReader(userDirsPath)) { string? line; while ((line = reader.ReadLine()) != null) { // Example lines: // XDG_DESKTOP_DIR="$HOME/Desktop" // XDG_PICTURES_DIR = "/absolute/path" // Skip past whitespace at beginning of line int pos = 0; SkipWhitespace(line, ref pos); if (pos >= line.Length) continue; // Skip past requested key name if (string.CompareOrdinal(line, pos, key, 0, key.Length) != 0) continue; pos += key.Length; // Skip past whitespace and past '=' SkipWhitespace(line, ref pos); if (pos >= line.Length - 4 || line[pos] != '=') continue; // 4 for ="" and at least one char between quotes pos++; // skip past '=' // Skip past whitespace and past first quote SkipWhitespace(line, ref pos); if (pos >= line.Length - 3 || line[pos] != '"') continue; // 3 for "" and at least one char between quotes pos++; // skip past opening '"' // Skip past relative prefix if one exists bool relativeToHome = false; const string RelativeToHomePrefix = "$HOME/"; if (string.CompareOrdinal(line, pos, RelativeToHomePrefix, 0, RelativeToHomePrefix.Length) == 0) { relativeToHome = true; pos += RelativeToHomePrefix.Length; } else if (line[pos] != '/') // if not relative to home, must be absolute path { continue; } // Find end of path int endPos = line.IndexOf('"', pos); if (endPos <= pos) continue; // Got we need. Now extract it. string path = line.Substring(pos, endPos - pos); return relativeToHome ? Path.Combine(homeDir, path) : path; } } } catch (Exception exc) { // assembly not found, file not found, errors reading file, etc. Just eat everything. Debug.Fail($"Failed reading {userDirsPath}: {exc}"); } } return Path.Combine(homeDir, fallback); } private static void SkipWhitespace(string line, ref int pos) { while (pos < line.Length && char.IsWhiteSpace(line[pos])) pos++; } public static string[] GetLogicalDrives() => Interop.Sys.GetAllMountPoints(); private static bool Is64BitOperatingSystemWhen32BitProcess => false; public static string MachineName { get { string hostName = Interop.Sys.GetHostName(); int dotPos = hostName.IndexOf('.'); return dotPos == -1 ? hostName : hostName.Substring(0, dotPos); } } internal const string NewLineConst = "\n"; private static OperatingSystem GetOSVersion() => GetOperatingSystem(Interop.Sys.GetUnixRelease()); // Tests exercise this method for corner cases via private reflection private static OperatingSystem GetOperatingSystem(string release) { int major = 0, minor = 0, build = 0, revision = 0; // Parse the uname's utsname.release for the first four numbers found. // This isn't perfect, but Version already doesn't map exactly to all possible release // formats, e.g. 2.6.19-1.2895.fc6 if (release != null) { int i = 0; major = FindAndParseNextNumber(release, ref i); minor = FindAndParseNextNumber(release, ref i); build = FindAndParseNextNumber(release, ref i); revision = FindAndParseNextNumber(release, ref i); } // For compatibility reasons with Mono, PlatformID.Unix is returned on MacOSX. PlatformID.MacOSX // is hidden from the editor and shouldn't be used. return new OperatingSystem(PlatformID.Unix, new Version(major, minor, build, revision)); } private static int FindAndParseNextNumber(string text, ref int pos) { // Move to the beginning of the number for (; pos < text.Length; pos++) { char c = text[pos]; if ('0' <= c && c <= '9') { break; } } // Parse the number; int num = 0; for (; pos < text.Length; pos++) { char c = text[pos]; if ('0' > c || c > '9') break; try { num = checked((num * 10) + (c - '0')); } // Integer overflow can occur for example with: // Linux nelknet 4.15.0-24201807041620-generic // To form a valid Version, num must be positive. catch (OverflowException) { return int.MaxValue; } } return num; } public static string SystemDirectory => GetFolderPathCore(SpecialFolder.System, SpecialFolderOption.None); public static int SystemPageSize => CheckedSysConf(Interop.Sys.SysConfName._SC_PAGESIZE); public static unsafe string UserName { get { // First try with a buffer that should suffice for 99% of cases. string? username; const int BufLen = Interop.Sys.Passwd.InitialBufferSize; byte* stackBuf = stackalloc byte[BufLen]; if (TryGetUserNameFromPasswd(stackBuf, BufLen, out username)) { return username ?? string.Empty; } // Fallback to heap allocations if necessary, growing the buffer until // we succeed. TryGetUserNameFromPasswd will throw if there's an unexpected error. int lastBufLen = BufLen; while (true) { lastBufLen *= 2; byte[] heapBuf = new byte[lastBufLen]; fixed (byte* buf = &heapBuf[0]) { if (TryGetUserNameFromPasswd(buf, heapBuf.Length, out username)) { return username ?? string.Empty; } } } } } private static unsafe bool TryGetUserNameFromPasswd(byte* buf, int bufLen, out string? username) { // Call getpwuid_r to get the passwd struct Interop.Sys.Passwd passwd; int error = Interop.Sys.GetPwUidR(Interop.Sys.GetEUid(), out passwd, buf, bufLen); // If the call succeeds, give back the user name retrieved if (error == 0) { Debug.Assert(passwd.Name != null); username = Marshal.PtrToStringAnsi((IntPtr)passwd.Name); return true; } // If the current user's entry could not be found, give back null, // but still return true (false indicates the buffer was too small). if (error == -1) { username = null; return true; } var errorInfo = new Interop.ErrorInfo(error); // If the call failed because the buffer was too small, return false to // indicate the caller should try again with a larger buffer. if (errorInfo.Error == Interop.Error.ERANGE) { username = null; return false; } // Otherwise, fail. throw new IOException(errorInfo.GetErrorMessage(), errorInfo.RawErrno); } public static string UserDomainName => MachineName; /// <summary>Invoke <see cref="Interop.Sys.SysConf"/>, throwing if it fails.</summary> private static int CheckedSysConf(Interop.Sys.SysConfName name) { long result = Interop.Sys.SysConf(name); if (result == -1) { Interop.ErrorInfo errno = Interop.Sys.GetLastErrorInfo(); throw errno.Error == Interop.Error.EINVAL ? new ArgumentOutOfRangeException(nameof(name), name, errno.GetErrorMessage()) : Interop.GetIOException(errno); } return (int)result; } public static long WorkingSet { get { Type? processType = Type.GetType("System.Diagnostics.Process, System.Diagnostics.Process, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", throwOnError: false); if (processType?.GetMethod("GetCurrentProcess")?.Invoke(null, BindingFlags.DoNotWrapExceptions, null, null, null) is IDisposable currentProcess) { using (currentProcess) { object? result = processType!.GetMethod("get_WorkingSet64")?.Invoke(currentProcess, BindingFlags.DoNotWrapExceptions, null, null, null); if (result is long) return (long)result; } } // Could not get the current working set. return 0; } } } }
/* * DocuSign REST API * * The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign. * * OpenAPI spec version: v2.1 * Contact: devcenter@docusign.com * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; using SwaggerDateConverter = DocuSign.eSign.Client.SwaggerDateConverter; namespace DocuSign.eSign.Model { /// <summary> /// AccountSignatureDefinition /// </summary> [DataContract] public partial class AccountSignatureDefinition : IEquatable<AccountSignatureDefinition>, IValidatableObject { public AccountSignatureDefinition() { // Empty Constructor } /// <summary> /// Initializes a new instance of the <see cref="AccountSignatureDefinition" /> class. /// </summary> /// <param name="DateStampProperties">DateStampProperties.</param> /// <param name="DisallowUserResizeStamp">DisallowUserResizeStamp.</param> /// <param name="ExternalID">ExternalID.</param> /// <param name="ImageType">ImageType.</param> /// <param name="IsDefault">IsDefault.</param> /// <param name="NrdsId">NrdsId.</param> /// <param name="NrdsLastName">NrdsLastName.</param> /// <param name="PhoneticName">PhoneticName.</param> /// <param name="SignatureFont">SignatureFont.</param> /// <param name="SignatureGroups">SignatureGroups.</param> /// <param name="SignatureId">Specifies the signature ID associated with the signature name. You can use the signature ID in the URI in place of the signature name, and the value stored in the &#x60;signatureName&#x60; property in the body is used. This allows the use of special characters (such as \&quot;&amp;\&quot;, \&quot;&lt;\&quot;, \&quot;&gt;\&quot;) in a the signature name. Note that with each update to signatures, the returned signature ID might change, so the caller will need to trigger off the signature name to get the new signature ID..</param> /// <param name="SignatureInitials">SignatureInitials.</param> /// <param name="SignatureName">Specifies the user signature name..</param> /// <param name="SignatureType">SignatureType.</param> /// <param name="SignatureUsers">SignatureUsers.</param> /// <param name="StampFormat">StampFormat.</param> /// <param name="StampSizeMM">StampSizeMM.</param> public AccountSignatureDefinition(DateStampProperties DateStampProperties = default(DateStampProperties), string DisallowUserResizeStamp = default(string), string ExternalID = default(string), string ImageType = default(string), string IsDefault = default(string), string NrdsId = default(string), string NrdsLastName = default(string), string PhoneticName = default(string), string SignatureFont = default(string), List<SignatureGroupDef> SignatureGroups = default(List<SignatureGroupDef>), string SignatureId = default(string), string SignatureInitials = default(string), string SignatureName = default(string), string SignatureType = default(string), List<SignatureUserDef> SignatureUsers = default(List<SignatureUserDef>), string StampFormat = default(string), string StampSizeMM = default(string)) { this.DateStampProperties = DateStampProperties; this.DisallowUserResizeStamp = DisallowUserResizeStamp; this.ExternalID = ExternalID; this.ImageType = ImageType; this.IsDefault = IsDefault; this.NrdsId = NrdsId; this.NrdsLastName = NrdsLastName; this.PhoneticName = PhoneticName; this.SignatureFont = SignatureFont; this.SignatureGroups = SignatureGroups; this.SignatureId = SignatureId; this.SignatureInitials = SignatureInitials; this.SignatureName = SignatureName; this.SignatureType = SignatureType; this.SignatureUsers = SignatureUsers; this.StampFormat = StampFormat; this.StampSizeMM = StampSizeMM; } /// <summary> /// Gets or Sets DateStampProperties /// </summary> [DataMember(Name="dateStampProperties", EmitDefaultValue=false)] public DateStampProperties DateStampProperties { get; set; } /// <summary> /// Gets or Sets DisallowUserResizeStamp /// </summary> [DataMember(Name="disallowUserResizeStamp", EmitDefaultValue=false)] public string DisallowUserResizeStamp { get; set; } /// <summary> /// Gets or Sets ExternalID /// </summary> [DataMember(Name="externalID", EmitDefaultValue=false)] public string ExternalID { get; set; } /// <summary> /// Gets or Sets ImageType /// </summary> [DataMember(Name="imageType", EmitDefaultValue=false)] public string ImageType { get; set; } /// <summary> /// Gets or Sets IsDefault /// </summary> [DataMember(Name="isDefault", EmitDefaultValue=false)] public string IsDefault { get; set; } /// <summary> /// Gets or Sets NrdsId /// </summary> [DataMember(Name="nrdsId", EmitDefaultValue=false)] public string NrdsId { get; set; } /// <summary> /// Gets or Sets NrdsLastName /// </summary> [DataMember(Name="nrdsLastName", EmitDefaultValue=false)] public string NrdsLastName { get; set; } /// <summary> /// Gets or Sets PhoneticName /// </summary> [DataMember(Name="phoneticName", EmitDefaultValue=false)] public string PhoneticName { get; set; } /// <summary> /// Gets or Sets SignatureFont /// </summary> [DataMember(Name="signatureFont", EmitDefaultValue=false)] public string SignatureFont { get; set; } /// <summary> /// Gets or Sets SignatureGroups /// </summary> [DataMember(Name="signatureGroups", EmitDefaultValue=false)] public List<SignatureGroupDef> SignatureGroups { get; set; } /// <summary> /// Specifies the signature ID associated with the signature name. You can use the signature ID in the URI in place of the signature name, and the value stored in the &#x60;signatureName&#x60; property in the body is used. This allows the use of special characters (such as \&quot;&amp;\&quot;, \&quot;&lt;\&quot;, \&quot;&gt;\&quot;) in a the signature name. Note that with each update to signatures, the returned signature ID might change, so the caller will need to trigger off the signature name to get the new signature ID. /// </summary> /// <value>Specifies the signature ID associated with the signature name. You can use the signature ID in the URI in place of the signature name, and the value stored in the &#x60;signatureName&#x60; property in the body is used. This allows the use of special characters (such as \&quot;&amp;\&quot;, \&quot;&lt;\&quot;, \&quot;&gt;\&quot;) in a the signature name. Note that with each update to signatures, the returned signature ID might change, so the caller will need to trigger off the signature name to get the new signature ID.</value> [DataMember(Name="signatureId", EmitDefaultValue=false)] public string SignatureId { get; set; } /// <summary> /// Gets or Sets SignatureInitials /// </summary> [DataMember(Name="signatureInitials", EmitDefaultValue=false)] public string SignatureInitials { get; set; } /// <summary> /// Specifies the user signature name. /// </summary> /// <value>Specifies the user signature name.</value> [DataMember(Name="signatureName", EmitDefaultValue=false)] public string SignatureName { get; set; } /// <summary> /// Gets or Sets SignatureType /// </summary> [DataMember(Name="signatureType", EmitDefaultValue=false)] public string SignatureType { get; set; } /// <summary> /// Gets or Sets SignatureUsers /// </summary> [DataMember(Name="signatureUsers", EmitDefaultValue=false)] public List<SignatureUserDef> SignatureUsers { get; set; } /// <summary> /// Gets or Sets StampFormat /// </summary> [DataMember(Name="stampFormat", EmitDefaultValue=false)] public string StampFormat { get; set; } /// <summary> /// Gets or Sets StampSizeMM /// </summary> [DataMember(Name="stampSizeMM", EmitDefaultValue=false)] public string StampSizeMM { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class AccountSignatureDefinition {\n"); sb.Append(" DateStampProperties: ").Append(DateStampProperties).Append("\n"); sb.Append(" DisallowUserResizeStamp: ").Append(DisallowUserResizeStamp).Append("\n"); sb.Append(" ExternalID: ").Append(ExternalID).Append("\n"); sb.Append(" ImageType: ").Append(ImageType).Append("\n"); sb.Append(" IsDefault: ").Append(IsDefault).Append("\n"); sb.Append(" NrdsId: ").Append(NrdsId).Append("\n"); sb.Append(" NrdsLastName: ").Append(NrdsLastName).Append("\n"); sb.Append(" PhoneticName: ").Append(PhoneticName).Append("\n"); sb.Append(" SignatureFont: ").Append(SignatureFont).Append("\n"); sb.Append(" SignatureGroups: ").Append(SignatureGroups).Append("\n"); sb.Append(" SignatureId: ").Append(SignatureId).Append("\n"); sb.Append(" SignatureInitials: ").Append(SignatureInitials).Append("\n"); sb.Append(" SignatureName: ").Append(SignatureName).Append("\n"); sb.Append(" SignatureType: ").Append(SignatureType).Append("\n"); sb.Append(" SignatureUsers: ").Append(SignatureUsers).Append("\n"); sb.Append(" StampFormat: ").Append(StampFormat).Append("\n"); sb.Append(" StampSizeMM: ").Append(StampSizeMM).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { // credit: http://stackoverflow.com/a/10454552/677735 return this.Equals(obj as AccountSignatureDefinition); } /// <summary> /// Returns true if AccountSignatureDefinition instances are equal /// </summary> /// <param name="other">Instance of AccountSignatureDefinition to be compared</param> /// <returns>Boolean</returns> public bool Equals(AccountSignatureDefinition other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.DateStampProperties == other.DateStampProperties || this.DateStampProperties != null && this.DateStampProperties.Equals(other.DateStampProperties) ) && ( this.DisallowUserResizeStamp == other.DisallowUserResizeStamp || this.DisallowUserResizeStamp != null && this.DisallowUserResizeStamp.Equals(other.DisallowUserResizeStamp) ) && ( this.ExternalID == other.ExternalID || this.ExternalID != null && this.ExternalID.Equals(other.ExternalID) ) && ( this.ImageType == other.ImageType || this.ImageType != null && this.ImageType.Equals(other.ImageType) ) && ( this.IsDefault == other.IsDefault || this.IsDefault != null && this.IsDefault.Equals(other.IsDefault) ) && ( this.NrdsId == other.NrdsId || this.NrdsId != null && this.NrdsId.Equals(other.NrdsId) ) && ( this.NrdsLastName == other.NrdsLastName || this.NrdsLastName != null && this.NrdsLastName.Equals(other.NrdsLastName) ) && ( this.PhoneticName == other.PhoneticName || this.PhoneticName != null && this.PhoneticName.Equals(other.PhoneticName) ) && ( this.SignatureFont == other.SignatureFont || this.SignatureFont != null && this.SignatureFont.Equals(other.SignatureFont) ) && ( this.SignatureGroups == other.SignatureGroups || this.SignatureGroups != null && this.SignatureGroups.SequenceEqual(other.SignatureGroups) ) && ( this.SignatureId == other.SignatureId || this.SignatureId != null && this.SignatureId.Equals(other.SignatureId) ) && ( this.SignatureInitials == other.SignatureInitials || this.SignatureInitials != null && this.SignatureInitials.Equals(other.SignatureInitials) ) && ( this.SignatureName == other.SignatureName || this.SignatureName != null && this.SignatureName.Equals(other.SignatureName) ) && ( this.SignatureType == other.SignatureType || this.SignatureType != null && this.SignatureType.Equals(other.SignatureType) ) && ( this.SignatureUsers == other.SignatureUsers || this.SignatureUsers != null && this.SignatureUsers.SequenceEqual(other.SignatureUsers) ) && ( this.StampFormat == other.StampFormat || this.StampFormat != null && this.StampFormat.Equals(other.StampFormat) ) && ( this.StampSizeMM == other.StampSizeMM || this.StampSizeMM != null && this.StampSizeMM.Equals(other.StampSizeMM) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks etc, of course :) if (this.DateStampProperties != null) hash = hash * 59 + this.DateStampProperties.GetHashCode(); if (this.DisallowUserResizeStamp != null) hash = hash * 59 + this.DisallowUserResizeStamp.GetHashCode(); if (this.ExternalID != null) hash = hash * 59 + this.ExternalID.GetHashCode(); if (this.ImageType != null) hash = hash * 59 + this.ImageType.GetHashCode(); if (this.IsDefault != null) hash = hash * 59 + this.IsDefault.GetHashCode(); if (this.NrdsId != null) hash = hash * 59 + this.NrdsId.GetHashCode(); if (this.NrdsLastName != null) hash = hash * 59 + this.NrdsLastName.GetHashCode(); if (this.PhoneticName != null) hash = hash * 59 + this.PhoneticName.GetHashCode(); if (this.SignatureFont != null) hash = hash * 59 + this.SignatureFont.GetHashCode(); if (this.SignatureGroups != null) hash = hash * 59 + this.SignatureGroups.GetHashCode(); if (this.SignatureId != null) hash = hash * 59 + this.SignatureId.GetHashCode(); if (this.SignatureInitials != null) hash = hash * 59 + this.SignatureInitials.GetHashCode(); if (this.SignatureName != null) hash = hash * 59 + this.SignatureName.GetHashCode(); if (this.SignatureType != null) hash = hash * 59 + this.SignatureType.GetHashCode(); if (this.SignatureUsers != null) hash = hash * 59 + this.SignatureUsers.GetHashCode(); if (this.StampFormat != null) hash = hash * 59 + this.StampFormat.GetHashCode(); if (this.StampSizeMM != null) hash = hash * 59 + this.StampSizeMM.GetHashCode(); return hash; } } public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { yield break; } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace SwaggerEx.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using System.Web.Http; using System.Web.Http.Description; using System.Xml.Serialization; using Newtonsoft.Json; namespace Aurora.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
#region Copyright /*Copyright (C) 2015 Konstantin Udilovich Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #endregion using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Text; using Kodestruct.Common.Entities; using Kodestruct.Common.Section.Interfaces; using Kodestruct.Steel.AISC.Interfaces; using Kodestruct.Common.CalculationLogger; using Kodestruct.Common.CalculationLogger.Interfaces; using Kodestruct.Steel.AISC.Interfaces; using Kodestruct.Common.Data; using Kodestruct.Common.Entities; using Kodestruct.Steel.AISC.Interfaces; using Kodestruct.Steel.Properties; namespace Kodestruct.Steel.AISC.SteelEntities.Materials { public class SteelMaterialCatalog: AnalyticalElement, ISteelMaterial { public SteelMaterialCatalog(string SteelMaterialId, ICalcLog Log): base(Log) { this.SteelMaterialId = SteelMaterialId; PropertiesWereCalculated = false; } public SteelMaterialCatalog(string SteelMaterialId, double FastenerDiameter, ICalcLog Log) : this(SteelMaterialId, Log) { this.FastenerDiameter = FastenerDiameter; } private string steelMaterialId; public string SteelMaterialId { get { return steelMaterialId; } set { steelMaterialId = value; PropertiesWereCalculated = false; } } bool PropertiesWereCalculated; private void CalculateProperties() { if (PropertiesWereCalculated == false) { #region Read Table Data var Tv11 = new { Id = "", Fy = 0.0, Fu = 0.0, MinDiam = 0.0, MaxDiam = 0.0 }; // sample var AllMaterialsList = ListFactory.MakeList(Tv11); using (StringReader reader = new StringReader(Resources.AISC360_10_MaterialProperties)) { string line; while ((line = reader.ReadLine()) != null) { string[] Vals = line.Split(','); if (Vals.Count() == 3) { string MatKey = Vals[0]; double V1 = double.Parse(Vals[1], CultureInfo.InvariantCulture); double V2 = double.Parse(Vals[2], CultureInfo.InvariantCulture); AllMaterialsList.Add(new { Id = MatKey, Fy = V1, Fu = V2, MinDiam = 0.0, MaxDiam = 0.0 }); } if (Vals.Count() == 5) { string MatKey = Vals[0]; double V1 = double.Parse(Vals[1], CultureInfo.InvariantCulture); double V2 = double.Parse(Vals[2], CultureInfo.InvariantCulture); double V3 = double.Parse(Vals[3], CultureInfo.InvariantCulture); double V4 = double.Parse(Vals[4], CultureInfo.InvariantCulture); AllMaterialsList.Add(new { Id = MatKey, Fy = V1, Fu = V2, MinDiam = V3, MaxDiam = V4 }); } } } #endregion var Materials = AllMaterialsList.Where(v => v.Id == SteelMaterialId).ToList(); if (Materials.Count > 1 && FastenerDiameter != 0) { var MatPropList = Materials.Where(m => { if (m.MaxDiam!=0) { if (FastenerDiameter > m.MinDiam && FastenerDiameter <= m.MaxDiam) { return true; } else { return false; } } else { return true; } }).ToList(); if (MatPropList.Any()) { var MatProp = MatPropList.FirstOrDefault(); this.YieldStress = MatProp.Fy; this.UltimateStress = MatProp.Fu; } } else { var MatProp = Materials.FirstOrDefault(); this.YieldStress = MatProp.Fy; this.UltimateStress = MatProp.Fu; } PropertiesWereCalculated = true; double Fy = YieldStress; double Fu = UltimateStress; double E = ModulusOfElasticity; double G = ShearModulus; #region Fy ICalcLogEntry FyEntry = new CalcLogEntry(); FyEntry.ValueName = "Fy"; FyEntry.AddDependencyValue("Fu", Math.Round(Fu, 3)); FyEntry.AddDependencyValue("SteelMaterialId", SteelMaterialId); FyEntry.AddDependencyValue("E", Math.Round(E, 0)); FyEntry.AddDependencyValue("G", Math.Round(G, 0)); FyEntry.Reference = ""; FyEntry.DescriptionReference = "/Templates/Steel/General/MaterialProperties.docx"; FyEntry.FormulaID = null; //reference to formula from code FyEntry.VariableValue = Math.Round(Fy, 3).ToString(); #endregion this.AddToLog(FyEntry); } } private double fastenerDiameter; public double FastenerDiameter { get { return fastenerDiameter; } set { fastenerDiameter = value; PropertiesWereCalculated = false; } } private double yieldStress; public double YieldStress { get { CalculateProperties(); return yieldStress; } set { yieldStress = value; } } private double ultimateStress; public double UltimateStress { get { CalculateProperties(); return ultimateStress; } set { ultimateStress = value; } } public double ModulusOfElasticity { get { return SteelConstants.ModulusOfElasticity; } } public double ShearModulus { get { return SteelConstants.ShearModulus; } } } }
/****************************************************************************** * The MIT License * Copyright (c) 2003 Novell Inc. 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. *******************************************************************************/ // // Novell.Directory.Ldap.Asn1.Asn1Identifier.cs // // Author: // Sunil Kumar (Sunilk@novell.com) // // (C) 2003 Novell, Inc (http://www.novell.com) // using System; using System.IO; namespace Novell.Directory.Ldap.Asn1 { /// <summary> This class is used to encapsulate an ASN.1 Identifier. /// /// An Asn1Identifier is composed of three parts: /// <li> a class type,</li> /// <li> a form, and</li> /// <li> a tag.</li> /// /// The class type is defined as: /// <pre> /// bit 8 7 TAG CLASS /// ------- ----------- /// 0 0 UNIVERSAL /// 0 1 APPLICATION /// 1 0 CONTEXT /// 1 1 PRIVATE /// </pre> /// The form is defined as: /// <pre> /// bit 6 FORM /// ----- -------- /// 0 PRIMITIVE /// 1 CONSTRUCTED /// </pre> /// /// Note: CONSTRUCTED types are made up of other CONSTRUCTED or PRIMITIVE /// types. /// /// The tag is defined as: /// <pre> /// bit 5 4 3 2 1 TAG /// ------------- --------------------------------------------- /// 0 0 0 0 0 /// . . . . . /// 1 1 1 1 0 (0-30) single octet tag /// /// 1 1 1 1 1 (> 30) multiple octet tag, more octets follow /// </pre> /// </summary> [CLSCompliantAttribute(true)] public class Asn1Identifier { /// <summary> Returns the CLASS of this Asn1Identifier as an int value. /// /// </summary> /// <seealso cref="UNIVERSAL"> /// </seealso> /// <seealso cref="APPLICATION"> /// </seealso> /// <seealso cref="CONTEXT"> /// </seealso> /// <seealso cref="PRIVATE"> /// </seealso> virtual public int Asn1Class { get { return tagClass; } } /// <summary> Return a boolean indicating if the constructed bit is set. /// /// </summary> /// <returns> true if constructed and false if primitive. /// </returns> virtual public bool Constructed { get { return constructed; } } /// <summary> Returns the TAG of this Asn1Identifier.</summary> virtual public int Tag { get { return tag; } } /// <summary> Returns the encoded length of this Asn1Identifier.</summary> virtual public int EncodedLength { get { return encodedLength; } } /// <summary> Returns a boolean value indicating whether or not this Asn1Identifier /// has a TAG CLASS of UNIVERSAL. /// /// </summary> /// <seealso cref="UNIVERSAL"> /// </seealso> [CLSCompliantAttribute(false)] virtual public bool Universal { get { return tagClass == UNIVERSAL; } } /// <summary> Returns a boolean value indicating whether or not this Asn1Identifier /// has a TAG CLASS of APPLICATION. /// /// </summary> /// <seealso cref="APPLICATION"> /// </seealso> [CLSCompliantAttribute(false)] virtual public bool Application { get { return tagClass == APPLICATION; } } /// <summary> Returns a boolean value indicating whether or not this Asn1Identifier /// has a TAG CLASS of CONTEXT-SPECIFIC. /// /// </summary> /// <seealso cref="CONTEXT"> /// </seealso> [CLSCompliantAttribute(false)] virtual public bool Context { get { return tagClass == CONTEXT; } } /// <summary> Returns a boolean value indicating whether or not this Asn1Identifier /// has a TAG CLASS of PRIVATE. /// /// </summary> /// <seealso cref="PRIVATE"></seealso> [CLSCompliantAttribute(false)] virtual public bool Private { get { return tagClass == PRIVATE; } } /// <summary> Universal tag class. /// /// UNIVERSAL = 0 /// </summary> public const int UNIVERSAL = 0; /// <summary> Application-wide tag class. /// /// APPLICATION = 1 /// </summary> public const int APPLICATION = 1; /// <summary> Context-specific tag class. /// /// CONTEXT = 2 /// </summary> public const int CONTEXT = 2; /// <summary> Private-use tag class. /// /// PRIVATE = 3 /// </summary> public const int PRIVATE = 3; /* Private variables */ private int tagClass; private bool constructed; private int tag; private int encodedLength; /* Constructors for Asn1Identifier */ /// <summary> Constructs an Asn1Identifier using the classtype, form and tag. /// /// </summary> /// <param name="tagClass">As defined above. /// /// </param> /// <param name="constructed">Set to true if constructed and false if primitive. /// /// </param> /// <param name="tag">The tag of this identifier /// </param> public Asn1Identifier(int tagClass, bool constructed, int tag) { this.tagClass = tagClass; this.constructed = constructed; this.tag = tag; } /// <summary> Decode an Asn1Identifier directly from an InputStream and /// save the encoded length of the Asn1Identifier. /// /// </summary> /// <param name="in">The input stream to decode from. /// </param> public Asn1Identifier(Stream in_Renamed) { int r = in_Renamed.ReadByte(); encodedLength++; if (r < 0) throw new EndOfStreamException("BERDecoder: decode: EOF in Identifier"); tagClass = r >> 6; constructed = (r & 0x20) != 0; tag = r & 0x1F; // if tag < 30 then its a single octet identifier. if (tag == 0x1F) // if true, its a multiple octet identifier. tag = decodeTagNumber(in_Renamed); } public Asn1Identifier() { } /// <summary> Decode an Asn1Identifier directly from an InputStream and /// save the encoded length of the Asn1Identifier, but reuse the object. /// /// </summary> /// <param name="in">The input stream to decode from. /// </param> public void reset(Stream in_Renamed) { encodedLength = 0; int r = in_Renamed.ReadByte(); encodedLength++; if (r < 0) throw new EndOfStreamException("BERDecoder: decode: EOF in Identifier"); tagClass = r >> 6; constructed = (r & 0x20) != 0; tag = r & 0x1F; // if tag < 30 then its a single octet identifier. if (tag == 0x1F) // if true, its a multiple octet identifier. tag = decodeTagNumber(in_Renamed); } /// <summary> In the case that we have a tag number that is greater than 30, we need /// to decode a multiple octet tag number. /// </summary> private int decodeTagNumber(Stream in_Renamed) { int n = 0; while (true) { int r = in_Renamed.ReadByte(); encodedLength++; if (r < 0) throw new EndOfStreamException("BERDecoder: decode: EOF in tag number"); n = (n << 7) + (r & 0x7F); if ((r & 0x80) == 0) break; } return n; } /* Convenience methods */ /// <summary> Creates a duplicate, not a true clone, of this object and returns /// a reference to the duplicate. /// /// </summary> public object Clone() { try { return MemberwiseClone(); } catch (Exception ce) { throw new Exception("Internal error, cannot create clone"); } } } }
using MathNet.Spatial.Euclidean; using Shouldly; using UnitsNet; using Xunit; namespace Pk.Spatial.Tests.ThreeDimensional.Displacement { [Trait(TestConstants.CategoryName, TestConstants.UnitTestsTag)] public class Displacement3DOperatorTests { [Fact] public void AngleTo() { var angle = Displacement3D.From(1, 1, 0, Length.BaseUnit).AngleTo(Displacement3D.From(10, 0, 0, Length.BaseUnit)); angle.Degrees.ShouldBe(45, Tolerance.ToWithinOneHundredth); angle = Displacement3D.From(0, 1, 1, Length.BaseUnit).AngleTo(UnitVector3D.ZAxis); angle.Degrees.ShouldBe(45, Tolerance.ToWithinOneHundredth); } [Fact] public void DifferentLengthDisplacementsAreUnequal() { var some = new Displacement3D(); var other = Displacement3D.From(1, 0, 0, Length.BaseUnit); (some != other).ShouldBeTrue(); (some == other).ShouldBeFalse(); } [Fact] public void Displacement3DLessDisplacement3DisADisplacement3D() { var some = Displacement3D.From(3, 7, 8, Length.BaseUnit); var other = Displacement3D.From(2, 5, 10, Length.BaseUnit); var result = some - other; result.ShouldBeOfType<Displacement3D>(); result.X.As(Length.BaseUnit).ShouldBe(1); result.Y.As(Length.BaseUnit).ShouldBe(2); result.Z.As(Length.BaseUnit).ShouldBe(-2); } [Fact] public void Displacement3DPlusDisplacement3DisADisplacement3D() { var some = Displacement3D.From(2, 5, 10, Length.BaseUnit); var other = Displacement3D.From(3, 7, 8, Length.BaseUnit); var result = some + other; result.ShouldBeOfType<Displacement3D>(); result.X.As(Length.BaseUnit).ShouldBe(5); result.Y.As(Length.BaseUnit).ShouldBe(12); result.Z.As(Length.BaseUnit).ShouldBe(18); } [Fact] public void NegationInvertsSignOfXYZ() { var displacement = Displacement3D.FromMeters(3, -4, 5); var result = displacement.Negate(); result.X.Meters.ShouldBe(-3); result.Y.Meters.ShouldBe(4); result.Z.Meters.ShouldBe(-5); result.Magnitude.Meters.ShouldBe(displacement.Magnitude.Meters, Tolerance.ToWithinUnitsNetError); var displacement2 = Displacement3D.FromMeters(-5, 4, 3); var result2 = -displacement2; result2.X.Meters.ShouldBe(5); result2.Y.Meters.ShouldBe(-4); result2.Z.Meters.ShouldBe(-3); result2.Magnitude.Meters.ShouldBe(displacement2.Magnitude.Meters, Tolerance.ToWithinUnitsNetError); } [Fact] public void DividingByAScalarDecreasesMagnitude() { var displacement = Displacement3D.FromMeters(3, 4, 5); var result = displacement/3.2; result.Magnitude.Meters.ShouldBe(displacement.Magnitude.Meters/3.2, Tolerance.ToWithinOneHundredth); var normalized1 = displacement.NormalizeToMeters(); var normalized2 = result.NormalizeToMeters(); normalized2.X.ShouldBe(normalized1.X, Tolerance.ToWithinUnitsNetError); normalized2.Y.ShouldBe(normalized1.Y, Tolerance.ToWithinUnitsNetError); normalized2.Z.ShouldBe(normalized1.Z, Tolerance.ToWithinUnitsNetError); } [Fact] public void DividingByALengthDecreasesMagnitude() { var displacement = Displacement3D.FromMeters(3, 4, 5); var result = displacement / Length.FromMeters(5); result.Magnitude.Meters.ShouldBe(displacement.Magnitude.Meters / 5, Tolerance.ToWithinOneHundredth); var normalized1 = displacement.NormalizeToMeters(); var normalized2 = result.NormalizeToMeters(); normalized2.X.ShouldBe(normalized1.X, Tolerance.ToWithinUnitsNetError); normalized2.Y.ShouldBe(normalized1.Y, Tolerance.ToWithinUnitsNetError); normalized2.Z.ShouldBe(normalized1.Z, Tolerance.ToWithinUnitsNetError); } [Fact] public void EqualDisplacementsShouldHaveSameHashCode() { var some = new Displacement3D(); var other = new Displacement3D(); some.GetHashCode().ShouldBe(other.GetHashCode()); } [Fact] public void EqualityAgainstObject() { new Displacement3D().Equals(new Location3D()).ShouldBeFalse(); var d = new Displacement3D(); d.Equals((object) d).ShouldBeTrue(); var other = Displacement3D.From(1, 2, 3, Length.BaseUnit); d.Equals((object) other).ShouldBeFalse(); d.Equals(null).ShouldBeFalse(); } [Fact] public void MultiplyingByALengthIncreasesMagnitude() { var displacement = Displacement3D.FromMeters(1, 1, 1); var result = Length.FromMeters(6) * displacement; result.Magnitude.Meters.ShouldBe(displacement.Magnitude.Meters * 6, Tolerance.ToWithinOneHundredth); var normalized1 = displacement.NormalizeToMeters(); var normalized2 = result.NormalizeToMeters(); normalized2.X.ShouldBe(normalized1.X, Tolerance.ToWithinUnitsNetError); normalized2.Y.ShouldBe(normalized1.Y, Tolerance.ToWithinUnitsNetError); normalized2.Z.ShouldBe(normalized1.Z, Tolerance.ToWithinUnitsNetError); } [Fact] public void MultiplyingByAScalarIncreasesMagnitude() { var displacement = Displacement3D.FromMeters(1, 1, 1); var result = 4.3*displacement; result.Magnitude.Meters.ShouldBe(displacement.Magnitude.Meters*4.3, Tolerance.ToWithinOneHundredth); var normalized1 = displacement.NormalizeToMeters(); var normalized2 = result.NormalizeToMeters(); normalized2.X.ShouldBe(normalized1.X, Tolerance.ToWithinUnitsNetError); normalized2.Y.ShouldBe(normalized1.Y, Tolerance.ToWithinUnitsNetError); normalized2.Z.ShouldBe(normalized1.Z, Tolerance.ToWithinUnitsNetError); } [Fact] public void RotatesAboutAxisByNegativeAngle() { //Starting from a displacement pointing purely in the X direction var displacementUnderTest = Displacement3D.From(UnitVector3D.XAxis, Length.FromMeters(1.0)); //Rotation by 90 degrees about z axis gives new vector pointing in Y direction var result1 = displacementUnderTest.Rotate(UnitVector3D.ZAxis, Angle.FromDegrees(-90)); result1.X.Meters.ShouldBe(0, Tolerance.ToWithinOneTenth); result1.Y.Meters.ShouldBe(-1, Tolerance.ToWithinOneTenth); result1.Z.Meters.ShouldBe(0, Tolerance.ToWithinOneTenth); //Rotation again by 90 degrees about x axis gives new vector pointing in Z direction var result2 = result1.Rotate(UnitVector3D.XAxis, Angle.FromDegrees(-90)); result2.X.Meters.ShouldBe(0, Tolerance.ToWithinOneTenth); result2.Y.Meters.ShouldBe(0, Tolerance.ToWithinOneTenth); result2.Z.Meters.ShouldBe(1, Tolerance.ToWithinOneTenth); //Finally rotation again by 90 degrees about y axis gives new vector pointing in X direction var result3 = result2.Rotate(UnitVector3D.YAxis, Angle.FromDegrees(-90)); result3.X.Meters.ShouldBe(-1, Tolerance.ToWithinOneTenth); result3.Y.Meters.ShouldBe(0, Tolerance.ToWithinOneTenth); result3.Z.Meters.ShouldBe(0, Tolerance.ToWithinOneTenth); } [Fact] public void RotatesAboutAxisByPositiveAngle() { //Starting from a displacement pointing purely in the X direction var displacementUnderTest = Displacement3D.From(UnitVector3D.XAxis, Length.FromMeters(1.0)); //Rotation by 90 degrees about z axis gives new vector pointing in Y direction var result1 = displacementUnderTest.Rotate(UnitVector3D.ZAxis, Angle.FromDegrees(90)); result1.X.Meters.ShouldBe(0, Tolerance.ToWithinOneTenth); result1.Y.Meters.ShouldBe(1, Tolerance.ToWithinOneTenth); result1.Z.Meters.ShouldBe(0, Tolerance.ToWithinOneTenth); //Rotation again by 90 degrees about x axis gives new vector pointing in Z direction var result2 = result1.Rotate(UnitVector3D.XAxis, Angle.FromDegrees(90)); result2.X.Meters.ShouldBe(0, Tolerance.ToWithinOneTenth); result2.Y.Meters.ShouldBe(0, Tolerance.ToWithinOneTenth); result2.Z.Meters.ShouldBe(1, Tolerance.ToWithinOneTenth); //Finally rotation again by 90 degrees about y axis gives new vector pointing in X direction var result3 = result2.Rotate(UnitVector3D.YAxis, Angle.FromDegrees(90)); result3.X.Meters.ShouldBe(1, Tolerance.ToWithinOneTenth); result3.Y.Meters.ShouldBe(0, Tolerance.ToWithinOneTenth); result3.Z.Meters.ShouldBe(0, Tolerance.ToWithinOneTenth); } [Fact] public void UnequalDisplacementsShouldHaveDifferentHashCode() { var some = new Displacement3D(); var other = Displacement3D.From(1, 0, 0, Length.BaseUnit); some.GetHashCode().ShouldNotBe(other.GetHashCode()); } [Fact] public void ZeroLengthDisplacementsAreEqual() { var some = new Displacement3D(); var other = new Displacement3D(); (some == other).ShouldBeTrue(); (some != other).ShouldBeFalse(); } } }
/* * 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 System.Data; using System.Reflection; using log4net; using OpenMetaverse; using OpenSim.Framework; #if CSharpSqlite using Community.CsharpSqlite.Sqlite; #else using Mono.Data.Sqlite; #endif namespace OpenSim.Data.SQLite { public class SQLiteAuthenticationData : SQLiteFramework, IAuthenticationData { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private string m_Realm; private List<string> m_ColumnNames; private int m_LastExpire; protected static SqliteConnection m_Connection; private static bool m_initialized = false; protected virtual Assembly Assembly { get { return GetType().Assembly; } } public SQLiteAuthenticationData(string connectionString, string realm) : base(connectionString) { m_Realm = realm; if (!m_initialized) { if (Util.IsWindows()) Util.LoadArchSpecificWindowsDll("sqlite3.dll"); m_Connection = new SqliteConnection(connectionString); m_Connection.Open(); Migration m = new Migration(m_Connection, Assembly, "AuthStore"); m.Update(); m_initialized = true; } } public AuthenticationData Get(UUID principalID) { AuthenticationData ret = new AuthenticationData(); ret.Data = new Dictionary<string, object>(); IDataReader result; using (SqliteCommand cmd = new SqliteCommand("select * from `" + m_Realm + "` where UUID = :PrincipalID")) { cmd.Parameters.Add(new SqliteParameter(":PrincipalID", principalID.ToString())); result = ExecuteReader(cmd, m_Connection); } try { if (result.Read()) { ret.PrincipalID = principalID; if (m_ColumnNames == null) { m_ColumnNames = new List<string>(); DataTable schemaTable = result.GetSchemaTable(); foreach (DataRow row in schemaTable.Rows) m_ColumnNames.Add(row["ColumnName"].ToString()); } foreach (string s in m_ColumnNames) { if (s == "UUID") continue; ret.Data[s] = result[s].ToString(); } return ret; } else { return null; } } catch { } return null; } public bool Store(AuthenticationData data) { if (data.Data.ContainsKey("UUID")) data.Data.Remove("UUID"); string[] fields = new List<string>(data.Data.Keys).ToArray(); string[] values = new string[data.Data.Count]; int i = 0; foreach (object o in data.Data.Values) values[i++] = o.ToString(); using (SqliteCommand cmd = new SqliteCommand()) { if (Get(data.PrincipalID) != null) { string update = "update `" + m_Realm + "` set "; bool first = true; foreach (string field in fields) { if (!first) update += ", "; update += "`" + field + "` = :" + field; cmd.Parameters.Add(new SqliteParameter(":" + field, data.Data[field])); first = false; } update += " where UUID = :UUID"; cmd.Parameters.Add(new SqliteParameter(":UUID", data.PrincipalID.ToString())); cmd.CommandText = update; try { if (ExecuteNonQuery(cmd, m_Connection) < 1) { //CloseCommand(cmd); return false; } } catch (Exception e) { m_log.Error("[SQLITE]: Exception storing authentication data", e); //CloseCommand(cmd); return false; } } else { string insert = "insert into `" + m_Realm + "` (`UUID`, `" + String.Join("`, `", fields) + "`) values (:UUID, :" + String.Join(", :", fields) + ")"; cmd.Parameters.Add(new SqliteParameter(":UUID", data.PrincipalID.ToString())); foreach (string field in fields) cmd.Parameters.Add(new SqliteParameter(":" + field, data.Data[field])); cmd.CommandText = insert; try { if (ExecuteNonQuery(cmd, m_Connection) < 1) { return false; } } catch (Exception e) { Console.WriteLine(e.ToString()); return false; } } } return true; } public bool SetDataItem(UUID principalID, string item, string value) { using (SqliteCommand cmd = new SqliteCommand("update `" + m_Realm + "` set `" + item + "` = " + value + " where UUID = '" + principalID.ToString() + "'")) { if (ExecuteNonQuery(cmd, m_Connection) > 0) return true; } return false; } public bool SetToken(UUID principalID, string token, int lifetime) { if (System.Environment.TickCount - m_LastExpire > 30000) DoExpire(); using (SqliteCommand cmd = new SqliteCommand("insert into tokens (UUID, token, validity) values ('" + principalID.ToString() + "', '" + token + "', datetime('now', 'localtime', '+" + lifetime.ToString() + " minutes'))")) { if (ExecuteNonQuery(cmd, m_Connection) > 0) return true; } return false; } public bool CheckToken(UUID principalID, string token, int lifetime) { if (System.Environment.TickCount - m_LastExpire > 30000) DoExpire(); using (SqliteCommand cmd = new SqliteCommand("update tokens set validity = datetime('now', 'localtime', '+" + lifetime.ToString() + " minutes') where UUID = '" + principalID.ToString() + "' and token = '" + token + "' and validity > datetime('now', 'localtime')")) { if (ExecuteNonQuery(cmd, m_Connection) > 0) return true; } return false; } private void DoExpire() { using (SqliteCommand cmd = new SqliteCommand("delete from tokens where validity < datetime('now', 'localtime')")) ExecuteNonQuery(cmd, m_Connection); m_LastExpire = System.Environment.TickCount; } } }
using System; using System.Globalization; using System.Collections.Generic; using Sasoma.Utils; using Sasoma.Microdata.Interfaces; using Sasoma.Languages.Core; using Sasoma.Microdata.Properties; namespace Sasoma.Microdata.Types { /// <summary> /// A landform or physical feature. Landform elements include mountains, plains, lakes, rivers, seascape and oceanic waterbody interface features such as bays, peninsulas, seas and so forth, including sub-aqueous terrain features such as submersed mountain ranges, volcanoes, and the great ocean basins. /// </summary> public class Landform_Core : TypeCore, IPlace { public Landform_Core() { this._TypeId = 146; this._Id = "Landform"; this._Schema_Org_Url = "http://schema.org/Landform"; string label = ""; GetLabel(out label, "Landform", typeof(Landform_Core)); this._Label = label; this._Ancestors = new int[]{266,206}; this._SubTypes = new int[]{40,71,168,287}; this._SuperTypes = new int[]{206}; this._Properties = new int[]{67,108,143,229,5,10,49,85,91,98,115,135,159,199,196}; } /// <summary> /// Physical address of the item. /// </summary> private Address_Core address; public Address_Core Address { get { return address; } set { address = value; SetPropertyInstance(address); } } /// <summary> /// The overall rating, based on a collection of reviews or ratings, of the item. /// </summary> private Properties.AggregateRating_Core aggregateRating; public Properties.AggregateRating_Core AggregateRating { get { return aggregateRating; } set { aggregateRating = value; SetPropertyInstance(aggregateRating); } } /// <summary> /// The basic containment relation between places. /// </summary> private ContainedIn_Core containedIn; public ContainedIn_Core ContainedIn { get { return containedIn; } set { containedIn = value; SetPropertyInstance(containedIn); } } /// <summary> /// A short description of the item. /// </summary> private Description_Core description; public Description_Core Description { get { return description; } set { description = value; SetPropertyInstance(description); } } /// <summary> /// Upcoming or past events associated with this place or organization. /// </summary> private Events_Core events; public Events_Core Events { get { return events; } set { events = value; SetPropertyInstance(events); } } /// <summary> /// The fax number. /// </summary> private FaxNumber_Core faxNumber; public FaxNumber_Core FaxNumber { get { return faxNumber; } set { faxNumber = value; SetPropertyInstance(faxNumber); } } /// <summary> /// The geo coordinates of the place. /// </summary> private Geo_Core geo; public Geo_Core Geo { get { return geo; } set { geo = value; SetPropertyInstance(geo); } } /// <summary> /// URL of an image of the item. /// </summary> private Image_Core image; public Image_Core Image { get { return image; } set { image = value; SetPropertyInstance(image); } } /// <summary> /// A count of a specific user interactions with this item\u2014for example, <code>20 UserLikes</code>, <code>5 UserComments</code>, or <code>300 UserDownloads</code>. The user interaction type should be one of the sub types of <a href=\http://schema.org/UserInteraction\>UserInteraction</a>. /// </summary> private InteractionCount_Core interactionCount; public InteractionCount_Core InteractionCount { get { return interactionCount; } set { interactionCount = value; SetPropertyInstance(interactionCount); } } /// <summary> /// A URL to a map of the place. /// </summary> private Maps_Core maps; public Maps_Core Maps { get { return maps; } set { maps = value; SetPropertyInstance(maps); } } /// <summary> /// The name of the item. /// </summary> private Name_Core name; public Name_Core Name { get { return name; } set { name = value; SetPropertyInstance(name); } } /// <summary> /// Photographs of this place. /// </summary> private Photos_Core photos; public Photos_Core Photos { get { return photos; } set { photos = value; SetPropertyInstance(photos); } } /// <summary> /// Review of the item. /// </summary> private Reviews_Core reviews; public Reviews_Core Reviews { get { return reviews; } set { reviews = value; SetPropertyInstance(reviews); } } /// <summary> /// The telephone number. /// </summary> private Telephone_Core telephone; public Telephone_Core Telephone { get { return telephone; } set { telephone = value; SetPropertyInstance(telephone); } } /// <summary> /// URL of the item. /// </summary> private Properties.URL_Core uRL; public Properties.URL_Core URL { get { return uRL; } set { uRL = value; SetPropertyInstance(uRL); } } } }
namespace Ocelot.AcceptanceTests { using System; using System.Collections.Generic; using System.Net; using Microsoft.AspNetCore.Http; using Ocelot.Configuration.File; using TestStack.BDDfy; using Xunit; public class UpstreamHostTests : IDisposable { private readonly Steps _steps; private string _downstreamPath; private readonly ServiceHandler _serviceHandler; public UpstreamHostTests() { _serviceHandler = new ServiceHandler(); _steps = new Steps(); } [Fact] public void should_return_response_200_with_simple_url_and_hosts_match() { int port = 64905; var configuration = new FileConfiguration { ReRoutes = new List<FileReRoute> { new FileReRoute { DownstreamPathTemplate = "/", DownstreamScheme = "http", DownstreamHostAndPorts = new List<FileHostAndPort> { new FileHostAndPort { Host = "localhost", Port = port, } }, UpstreamPathTemplate = "/", UpstreamHttpMethod = new List<string> { "Get" }, UpstreamHost = "localhost" } } }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", "/", 200, "Hello from Laura")) .And(x => _steps.GivenThereIsAConfiguration(configuration)) .And(x => _steps.GivenOcelotIsRunning()) .When(x => _steps.WhenIGetUrlOnTheApiGateway("/")) .Then(x => _steps.ThenTheStatusCodeShouldBe(HttpStatusCode.OK)) .And(x => _steps.ThenTheResponseBodyShouldBe("Hello from Laura")) .BDDfy(); } [Fact] public void should_return_response_200_with_simple_url_and_hosts_match_multiple_re_routes() { int port = 64904; var configuration = new FileConfiguration { ReRoutes = new List<FileReRoute> { new FileReRoute { DownstreamPathTemplate = "/", DownstreamScheme = "http", DownstreamHostAndPorts = new List<FileHostAndPort> { new FileHostAndPort { Host = "localhost", Port = port, } }, UpstreamPathTemplate = "/", UpstreamHttpMethod = new List<string> { "Get" }, UpstreamHost = "localhost" }, new FileReRoute { DownstreamPathTemplate = "/", DownstreamScheme = "http", DownstreamHostAndPorts = new List<FileHostAndPort> { new FileHostAndPort { Host = "localhost", Port = 50000, } }, UpstreamPathTemplate = "/", UpstreamHttpMethod = new List<string> { "Get" }, UpstreamHost = "DONTMATCH" } } }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", "/", 200, "Hello from Laura")) .And(x => _steps.GivenThereIsAConfiguration(configuration)) .And(x => _steps.GivenOcelotIsRunning()) .When(x => _steps.WhenIGetUrlOnTheApiGateway("/")) .Then(x => _steps.ThenTheStatusCodeShouldBe(HttpStatusCode.OK)) .And(x => _steps.ThenTheResponseBodyShouldBe("Hello from Laura")) .BDDfy(); } [Fact] public void should_return_response_200_with_simple_url_and_hosts_match_multiple_re_routes_reversed() { int port = 64903; var configuration = new FileConfiguration { ReRoutes = new List<FileReRoute> { new FileReRoute { DownstreamPathTemplate = "/", DownstreamScheme = "http", DownstreamHostAndPorts = new List<FileHostAndPort> { new FileHostAndPort { Host = "localhost", Port = 50000, } }, UpstreamPathTemplate = "/", UpstreamHttpMethod = new List<string> { "Get" }, UpstreamHost = "DONTMATCH" }, new FileReRoute { DownstreamPathTemplate = "/", DownstreamScheme = "http", DownstreamHostAndPorts = new List<FileHostAndPort> { new FileHostAndPort { Host = "localhost", Port = port, } }, UpstreamPathTemplate = "/", UpstreamHttpMethod = new List<string> { "Get" }, UpstreamHost = "localhost" } } }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", "/", 200, "Hello from Laura")) .And(x => _steps.GivenThereIsAConfiguration(configuration)) .And(x => _steps.GivenOcelotIsRunning()) .When(x => _steps.WhenIGetUrlOnTheApiGateway("/")) .Then(x => _steps.ThenTheStatusCodeShouldBe(HttpStatusCode.OK)) .And(x => _steps.ThenTheResponseBodyShouldBe("Hello from Laura")) .BDDfy(); } [Fact] public void should_return_response_200_with_simple_url_and_hosts_match_multiple_re_routes_reversed_with_no_host_first() { int port = 64902; var configuration = new FileConfiguration { ReRoutes = new List<FileReRoute> { new FileReRoute { DownstreamPathTemplate = "/", DownstreamScheme = "http", DownstreamHostAndPorts = new List<FileHostAndPort> { new FileHostAndPort { Host = "localhost", Port = 50000, } }, UpstreamPathTemplate = "/", UpstreamHttpMethod = new List<string> { "Get" }, }, new FileReRoute { DownstreamPathTemplate = "/", DownstreamScheme = "http", DownstreamHostAndPorts = new List<FileHostAndPort> { new FileHostAndPort { Host = "localhost", Port = port, } }, UpstreamPathTemplate = "/", UpstreamHttpMethod = new List<string> { "Get" }, UpstreamHost = "localhost" } } }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", "/", 200, "Hello from Laura")) .And(x => _steps.GivenThereIsAConfiguration(configuration)) .And(x => _steps.GivenOcelotIsRunning()) .When(x => _steps.WhenIGetUrlOnTheApiGateway("/")) .Then(x => _steps.ThenTheStatusCodeShouldBe(HttpStatusCode.OK)) .And(x => _steps.ThenTheResponseBodyShouldBe("Hello from Laura")) .BDDfy(); } [Fact] public void should_return_response_404_with_simple_url_and_hosts_dont_match() { int port = 64901; var configuration = new FileConfiguration { ReRoutes = new List<FileReRoute> { new FileReRoute { DownstreamPathTemplate = "/", DownstreamScheme = "http", DownstreamHostAndPorts = new List<FileHostAndPort> { new FileHostAndPort { Host = "localhost", Port = port, } }, UpstreamPathTemplate = "/", UpstreamHttpMethod = new List<string> { "Get" }, UpstreamHost = "127.0.0.20:5000" } } }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", "/", 200, "Hello from Laura")) .And(x => _steps.GivenThereIsAConfiguration(configuration)) .And(x => _steps.GivenOcelotIsRunning()) .When(x => _steps.WhenIGetUrlOnTheApiGateway("/")) .Then(x => _steps.ThenTheStatusCodeShouldBe(HttpStatusCode.NotFound)) .BDDfy(); } private void GivenThereIsAServiceRunningOn(string baseUrl, string basePath, int statusCode, string responseBody) { _serviceHandler.GivenThereIsAServiceRunningOn(baseUrl, basePath, async context => { _downstreamPath = !string.IsNullOrEmpty(context.Request.PathBase.Value) ? context.Request.PathBase.Value : context.Request.Path.Value; if (_downstreamPath != basePath) { context.Response.StatusCode = statusCode; await context.Response.WriteAsync("downstream path didnt match base path"); } else { context.Response.StatusCode = statusCode; await context.Response.WriteAsync(responseBody); } }); } public void Dispose() { _serviceHandler?.Dispose(); _steps.Dispose(); } } }
#if UNITY_EDITOR using UnityEditor; using UnityEngine; using System.Collections; using System.Collections.Generic; public class Uni2DAssetPostprocessor : AssetPostprocessor { private static bool ms_bEnabled = true; private static bool ms_bLocked = false; private static HashSet<string> ms_oImportedTextureGUIDs = new HashSet<string>( ); private static HashSet<string> ms_oAtlasGUIDsToUpdate = new HashSet<string>( ); private static HashSet<string> ms_oAnimationClipGUIDsToUpdate = new HashSet<string>( ); private static HashSet<string> ms_oSpritePrefabGUIDsToUpdate = new HashSet<string>( ); private static List<string> ms_oGameObjectGUIDsToPostProcess = new List<string>( ); public static bool Enabled { get { return ms_bEnabled; } set { if( !ms_bLocked ) { if( value ) { ms_oImportedTextureGUIDs.Clear( ); } ms_bEnabled = value; } } } public static bool IsLocked { get { return ms_bLocked; } } private static void LockTo( bool a_bValue ) { ms_bLocked = false; Uni2DAssetPostprocessor.Enabled = a_bValue; ms_bLocked = true; } private static void Unlock( ) { ms_bLocked = false; } private static void OnPostprocessAllAssets( string[ ] a_rImportedAssets, string[ ] a_rDeletedAssets, string[ ] a_rMovedAssets, string[ ] a_rMovedFromPath ) { if( ms_bEnabled ) { bool bUpdateAssets = false; bool bPostprocessPrefabs = false; bool bSaveTable = false; Uni2DEditorAssetTable rAssetTable = Uni2DEditorAssetTable.Instance; foreach( string rImportedAssetPath in a_rImportedAssets ) { Texture2D rImportedTexture = (Texture2D) AssetDatabase.LoadAssetAtPath( rImportedAssetPath, typeof( Texture2D ) ); if( rImportedTexture != null ) { if(Uni2DEditorUtils.IsMarkedAsSourceTexture(rImportedTexture)) { //Debug.Log ( "Imported " + rImportedAssetPath ); string rImportedTextureGUID = AssetDatabase.AssetPathToGUID( rImportedAssetPath ); ms_oImportedTextureGUIDs.Add( rImportedTextureGUID ); Uni2DEditorUtils.GenerateTextureImportGUID(rImportedTexture); bUpdateAssets = true; rImportedTexture = null; EditorUtility.UnloadUnusedAssets( ); continue; } } Uni2DTextureAtlas rImportedAtlas = (Uni2DTextureAtlas) AssetDatabase.LoadAssetAtPath( rImportedAssetPath, typeof( Uni2DTextureAtlas ) ); if( rImportedAtlas != null ) { //Debug.Log ( "Imported atlas " + rImportedAssetPath ); bSaveTable = true; rAssetTable.AddAtlasPath( rImportedAssetPath, AssetDatabase.AssetPathToGUID( rImportedAssetPath ) ); rImportedAtlas = null; EditorUtility.UnloadUnusedAssets( ); continue; } Uni2DAnimationClip rImportedClip = (Uni2DAnimationClip) AssetDatabase.LoadAssetAtPath( rImportedAssetPath, typeof( Uni2DAnimationClip ) ); if( rImportedClip != null ) { //Debug.Log ( "Imported clip " + rImportedClip ); bSaveTable = true; rAssetTable.AddClipPath( rImportedAssetPath, AssetDatabase.AssetPathToGUID( rImportedAssetPath ) ); rImportedClip = null; EditorUtility.UnloadUnusedAssets( ); continue; } GameObject rImportedGameObject = (GameObject) AssetDatabase.LoadAssetAtPath( rImportedAssetPath, typeof( GameObject ) ); if( rImportedGameObject != null ) { //Debug.Log ( "Imported game object " + rImportedAssetPath ); ms_oGameObjectGUIDsToPostProcess.Add( AssetDatabase.AssetPathToGUID( rImportedAssetPath ) ); bPostprocessPrefabs = true; rImportedGameObject = null; EditorUtility.UnloadUnusedAssets( ); } } // Moved assets for( int iIndex = 0, iCount = a_rMovedAssets.Length; iIndex < iCount; ++iIndex ) { //Debug.Log ( "Importing moved asset" ); Uni2DTextureAtlas rMovedAtlas = (Uni2DTextureAtlas) AssetDatabase.LoadAssetAtPath( a_rMovedAssets[ iIndex ], typeof( Uni2DTextureAtlas ) ); if( rMovedAtlas != null ) { rAssetTable.RemoveAtlasFromPath( a_rMovedFromPath[ iIndex ], false ); rAssetTable.AddAtlasPath( a_rMovedAssets[ iIndex ], AssetDatabase.AssetPathToGUID( a_rMovedAssets[ iIndex ] ) ); bSaveTable = true; rMovedAtlas = null; EditorUtility.UnloadUnusedAssets( ); continue; } Uni2DAnimationClip rMovedClip = (Uni2DAnimationClip) AssetDatabase.LoadAssetAtPath( a_rMovedAssets[ iIndex ], typeof( Uni2DAnimationClip ) ); if( rMovedClip != null ) { rAssetTable.RemoveClipFromPath( a_rMovedFromPath[ iIndex ], false ); rAssetTable.AddClipPath( a_rMovedAssets[ iIndex ], AssetDatabase.AssetPathToGUID( a_rMovedAssets[ iIndex ] ) ); bSaveTable = true; rMovedClip = null; EditorUtility.UnloadUnusedAssets( ); } } // Deleted assets foreach( string rDeletedAsset in a_rDeletedAssets ) { string[ ] rSpritePrefabGUIDs = rAssetTable.GetSpritePrefabGUIDsUsingThisAtlasPath( rDeletedAsset ); if( rSpritePrefabGUIDs.Length > 0 ) { bUpdateAssets = true; ms_oSpritePrefabGUIDsToUpdate.UnionWith( rSpritePrefabGUIDs ); } /* // TODO: mettre des paths au lieu d'IDs string[ ] rClipGUIDs = rAssetTable.GetClipGUIDsUsingThisTexturePath( rDeletedAsset ); if( rClipGUIDs.Length > 0 ) { bUpdateAssets = true; ms_oAnimationClipGUIDsToUpdate.UnionWith( rClipGUIDs ); } */ bSaveTable = rAssetTable.RemoveAtlasFromPath( rDeletedAsset, true ) || bSaveTable; bSaveTable = rAssetTable.RemoveClipFromPath( rDeletedAsset, true ) || bSaveTable; } if( bSaveTable ) { rAssetTable.Save( ); } if( bUpdateAssets ) { ms_oAtlasGUIDsToUpdate.UnionWith( rAssetTable.GetAtlasGUIDsUsingTheseTextures( ms_oImportedTextureGUIDs ) ); ms_oAnimationClipGUIDsToUpdate.UnionWith( rAssetTable.GetClipGUIDsUsingTheseTextures( ms_oImportedTextureGUIDs ) ); ms_oSpritePrefabGUIDsToUpdate.UnionWith( rAssetTable.GetSpritePrefabGUIDsUsingTheseTextures( ms_oImportedTextureGUIDs ) ); ms_oSpritePrefabGUIDsToUpdate.UnionWith( rAssetTable.GetSpritePrefabGUIDsUsingTheseAtlases( ms_oAtlasGUIDsToUpdate ) ); EditorApplication.delayCall += UpdateUni2DAssets; } if( bPostprocessPrefabs ) { EditorApplication.delayCall += OnSpritePrefabPostprocess; } } } private static void OnSpritePrefabPostprocess( ) { EditorApplication.delayCall -= OnSpritePrefabPostprocess; try { Uni2DAssetPostprocessor.LockTo( false ); foreach( string rGameObjectPrefabGUID in ms_oGameObjectGUIDsToPostProcess ) { GameObject rGameObjectPrefab = Uni2DEditorUtils.GetAssetFromUnityGUID<GameObject>( rGameObjectPrefabGUID ); if( rGameObjectPrefab != null ) { //Debug.Log ( "Post processing game object prefab " + rGameObjectPrefabGUID ); Uni2DEditorSpriteBuilderUtils.OnPrefabPostProcess( rGameObjectPrefab ); rGameObjectPrefab = null; EditorUtility.UnloadUnusedAssets( ); } } } finally { ms_oGameObjectGUIDsToPostProcess.Clear( ); Uni2DAssetPostprocessor.Unlock( ); Uni2DAssetPostprocessor.Enabled = true; } } private static void UpdateUni2DAssets( ) { EditorApplication.delayCall -= UpdateUni2DAssets; Uni2DEditorAssetTable rAssetTable = Uni2DEditorAssetTable.Instance; try { Uni2DAssetPostprocessor.LockTo( false ); // Update animation clips first, because they can change the atlases foreach( string rAnimationClipGUID in ms_oAnimationClipGUIDsToUpdate ) { Uni2DAnimationClip rAnimationClip = Uni2DEditorUtils.GetAssetFromUnityGUID<Uni2DAnimationClip>( rAnimationClipGUID ); if( rAnimationClip != null ) { //Debug.Log ( "Updating clip " + rAnimationClipGUID ); rAnimationClip.OnTexturesChange( ms_oImportedTextureGUIDs ); rAnimationClip = null; EditorUtility.UnloadUnusedAssets( ); } else { // Clean asset table foreach( string rTextureGUID in ms_oImportedTextureGUIDs ) { rAssetTable.RemoveClipUsingTexture( rAnimationClipGUID, rTextureGUID ); } } } foreach( string rAtlasGUID in ms_oAtlasGUIDsToUpdate ) { Uni2DTextureAtlas rAtlas = Uni2DEditorUtils.GetAssetFromUnityGUID<Uni2DTextureAtlas>( rAtlasGUID ); if( rAtlas != null ) { //Debug.Log( "Updating atlas " + rAtlasGUID ); rAtlas.OnTextureChange( ); rAtlas = null; EditorUtility.UnloadUnusedAssets( ); } else { // Clean foreach( string rTextureGUID in ms_oImportedTextureGUIDs ) { rAssetTable.RemoveAtlasUsingTexture( rAtlasGUID, rTextureGUID ); } } } foreach( string rSpritePrefabGUID in ms_oSpritePrefabGUIDsToUpdate ) { GameObject rSpritePrefab = Uni2DEditorUtils.GetAssetFromUnityGUID<GameObject>( rSpritePrefabGUID ); if( rSpritePrefab != null ) { //Debug.Log( "Updating sprite prefab " + rSpritePrefabGUID ); foreach( Uni2DSprite rSpritePrefabComponent in rSpritePrefab.GetComponentsInChildren<Uni2DSprite>( true ) ) { Uni2DEditorSpriteSettings rSpriteSettings = rSpritePrefabComponent.SpriteSettings; string rSpriteTextureGUID = rSpriteSettings.textureContainer.GUID; string rSpriteAtlasGUID = rSpriteSettings.atlas != null ? Uni2DEditorUtils.GetUnityAssetGUID( rSpriteSettings.atlas ) : null; if( ms_oImportedTextureGUIDs.Contains( rSpriteTextureGUID ) || ( !string.IsNullOrEmpty( rSpriteAtlasGUID ) && ms_oAtlasGUIDsToUpdate.Contains( rSpriteAtlasGUID ) ) ) { rSpritePrefabComponent.Regenerate( true ); } EditorUtility.UnloadUnusedAssets( ); } rSpritePrefab = null; EditorUtility.UnloadUnusedAssets( ); } else { // Clean foreach( string rTextureGUID in ms_oImportedTextureGUIDs ) { rAssetTable.RemoveSpritePrefabUsingTexture( rSpritePrefabGUID, rTextureGUID ); } foreach( string rAtlasGUID in ms_oAtlasGUIDsToUpdate ) { rAssetTable.RemoveSpritePrefabUsingAtlas( rSpritePrefabGUID, rAtlasGUID ); } } } } finally { ms_oImportedTextureGUIDs.Clear( ); ms_oAtlasGUIDsToUpdate.Clear( ); ms_oAnimationClipGUIDsToUpdate.Clear( ); ms_oSpritePrefabGUIDsToUpdate.Clear( ); rAssetTable.Save( ); Uni2DAssetPostprocessor.Unlock( ); Uni2DAssetPostprocessor.Enabled = true; } } public static void ForceImportAssetIfLocked( string a_rAssetPath, ImportAssetOptions a_eImportOptions ) { bool bWasLocked = ms_bLocked; bool bPreviousValue = ms_bEnabled; if( bWasLocked ) { Uni2DAssetPostprocessor.Unlock( ); } Uni2DAssetPostprocessor.Enabled = true; { AssetDatabase.ImportAsset( a_rAssetPath, a_eImportOptions ); } if( bWasLocked ) { Uni2DAssetPostprocessor.LockTo( bPreviousValue ); } else { Uni2DAssetPostprocessor.Enabled = bPreviousValue; } } } #endif
using System; using System.Collections; using System.Collections.Generic; using System.Text; /* * Copyright 2008 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace com.google.zxing.oned { using BarcodeFormat = com.google.zxing.BarcodeFormat; using DecodeHintType = com.google.zxing.DecodeHintType; using FormatException = com.google.zxing.FormatException; using NotFoundException = com.google.zxing.NotFoundException; using Result = com.google.zxing.Result; using ResultPoint = com.google.zxing.ResultPoint; using BitArray = com.google.zxing.common.BitArray; /// <summary> /// <p>Implements decoding of the ITF format, or Interleaved Two of Five.</p> /// /// <p>This Reader will scan ITF barcodes of certain lengths only. /// At the moment it reads length 6, 10, 12, 14, 16, 24, and 44 as these have appeared "in the wild". Not all /// lengths are scanned, especially shorter ones, to avoid false positives. This in turn is due to a lack of /// required checksum function.</p> /// /// <p>The checksum is optional and is not applied by this Reader. The consumer of the decoded /// value will have to apply a checksum if required.</p> /// /// <p><a href="http://en.wikipedia.org/wiki/Interleaved_2_of_5">http://en.wikipedia.org/wiki/Interleaved_2_of_5</a> /// is a great reference for Interleaved 2 of 5 information.</p> /// /// @author kevin.osullivan@sita.aero, SITA Lab. /// </summary> public sealed class ITFReader : OneDReader { private static readonly int MAX_AVG_VARIANCE = (int)(PATTERN_MATCH_RESULT_SCALE_FACTOR * 0.42f); private static readonly int MAX_INDIVIDUAL_VARIANCE = (int)(PATTERN_MATCH_RESULT_SCALE_FACTOR * 0.8f); private const int W = 3; // Pixel width of a wide line private const int N = 1; // Pixed width of a narrow line private static readonly int[] DEFAULT_ALLOWED_LENGTHS = {44, 24, 20, 18, 16, 14, 12, 10, 8, 6}; // Stores the actual narrow line width of the image being decoded. private int narrowLineWidth = -1; /// <summary> /// Start/end guard pattern. /// /// Note: The end pattern is reversed because the row is reversed before /// searching for the END_PATTERN /// </summary> private static readonly int[] START_PATTERN = {N, N, N, N}; private static readonly int[] END_PATTERN_REVERSED = {N, N, W}; /// <summary> /// Patterns of Wide / Narrow lines to indicate each digit /// </summary> internal static readonly int[][] PATTERNS = {new int[] {N, N, W, W, N}, new int[] {W, N, N, N, W}, new int[] {N, W, N, N, W}, new int[] {W, W, N, N, N}, new int[] {N, N, W, N, W}, new int[] {W, N, W, N, N}, new int[] {N, W, W, N, N}, new int[] {N, N, N, W, W}, new int[] {W, N, N, W, N}, new int[] {N, W, N, W, N}}; //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: public com.google.zxing.Result decodeRow(int rowNumber, com.google.zxing.common.BitArray row, java.util.Map<com.google.zxing.DecodeHintType,?> hints) throws com.google.zxing.FormatException, com.google.zxing.NotFoundException public override Result decodeRow(int rowNumber, BitArray row, IDictionary<DecodeHintType, object> hints) { // Find out where the Middle section (payload) starts & ends int[] startRange = decodeStart(row); int[] endRange = decodeEnd(row); StringBuilder result = new StringBuilder(20); decodeMiddle(row, startRange[1], endRange[0], result); string resultString = result.ToString(); int[] allowedLengths = null; if (hints != null && hints.ContainsKey(DecodeHintType.ALLOWED_LENGTHS)) { allowedLengths = (int[]) hints[DecodeHintType.ALLOWED_LENGTHS]; } if (allowedLengths == null) { allowedLengths = DEFAULT_ALLOWED_LENGTHS; } // To avoid false positives with 2D barcodes (and other patterns), make // an assumption that the decoded string must be 6, 10 or 14 digits. int length = resultString.Length; bool lengthOK = false; foreach (int allowedLength in allowedLengths) { if (length == allowedLength) { lengthOK = true; break; } } if (!lengthOK) { throw FormatException.FormatInstance; } return new Result(resultString, null, new ResultPoint[] {new ResultPoint(startRange[1], (float) rowNumber), new ResultPoint(endRange[0], (float) rowNumber)}, BarcodeFormat.ITF); // no natural byte representation for these barcodes } /// <param name="row"> row of black/white values to search </param> /// <param name="payloadStart"> offset of start pattern </param> /// <param name="resultString"> <seealso cref="StringBuilder"/> to append decoded chars to </param> /// <exception cref="NotFoundException"> if decoding could not complete successfully </exception> //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: private static void decodeMiddle(com.google.zxing.common.BitArray row, int payloadStart, int payloadEnd, StringBuilder resultString) throws com.google.zxing.NotFoundException private static void decodeMiddle(BitArray row, int payloadStart, int payloadEnd, StringBuilder resultString) { // Digits are interleaved in pairs - 5 black lines for one digit, and the // 5 // interleaved white lines for the second digit. // Therefore, need to scan 10 lines and then // split these into two arrays int[] counterDigitPair = new int[10]; int[] counterBlack = new int[5]; int[] counterWhite = new int[5]; while (payloadStart < payloadEnd) { // Get 10 runs of black/white. recordPattern(row, payloadStart, counterDigitPair); // Split them into each array for (int k = 0; k < 5; k++) { int twoK = k << 1; counterBlack[k] = counterDigitPair[twoK]; counterWhite[k] = counterDigitPair[twoK + 1]; } int bestMatch = decodeDigit(counterBlack); resultString.Append((char)('0' + bestMatch)); bestMatch = decodeDigit(counterWhite); resultString.Append((char)('0' + bestMatch)); foreach (int counterDigit in counterDigitPair) { payloadStart += counterDigit; } } } /// <summary> /// Identify where the start of the middle / payload section starts. /// </summary> /// <param name="row"> row of black/white values to search </param> /// <returns> Array, containing index of start of 'start block' and end of /// 'start block' </returns> /// <exception cref="NotFoundException"> </exception> //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: int[] decodeStart(com.google.zxing.common.BitArray row) throws com.google.zxing.NotFoundException internal int[] decodeStart(BitArray row) { int endStart = skipWhiteSpace(row); int[] startPattern = findGuardPattern(row, endStart, START_PATTERN); // Determine the width of a narrow line in pixels. We can do this by // getting the width of the start pattern and dividing by 4 because its // made up of 4 narrow lines. this.narrowLineWidth = (startPattern[1] - startPattern[0]) >> 2; validateQuietZone(row, startPattern[0]); return startPattern; } /// <summary> /// The start & end patterns must be pre/post fixed by a quiet zone. This /// zone must be at least 10 times the width of a narrow line. Scan back until /// we either get to the start of the barcode or match the necessary number of /// quiet zone pixels. /// /// Note: Its assumed the row is reversed when using this method to find /// quiet zone after the end pattern. /// /// ref: http://www.barcode-1.net/i25code.html /// </summary> /// <param name="row"> bit array representing the scanned barcode. </param> /// <param name="startPattern"> index into row of the start or end pattern. </param> /// <exception cref="NotFoundException"> if the quiet zone cannot be found, a ReaderException is thrown. </exception> //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: private void validateQuietZone(com.google.zxing.common.BitArray row, int startPattern) throws com.google.zxing.NotFoundException private void validateQuietZone(BitArray row, int startPattern) { int quietCount = this.narrowLineWidth * 10; // expect to find this many pixels of quiet zone for (int i = startPattern - 1; quietCount > 0 && i >= 0; i--) { if (row.get(i)) { break; } quietCount--; } if (quietCount != 0) { // Unable to find the necessary number of quiet zone pixels. throw NotFoundException.NotFoundInstance; } } /// <summary> /// Skip all whitespace until we get to the first black line. /// </summary> /// <param name="row"> row of black/white values to search </param> /// <returns> index of the first black line. </returns> /// <exception cref="NotFoundException"> Throws exception if no black lines are found in the row </exception> //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: private static int skipWhiteSpace(com.google.zxing.common.BitArray row) throws com.google.zxing.NotFoundException private static int skipWhiteSpace(BitArray row) { int width = row.Size; int endStart = row.getNextSet(0); if (endStart == width) { throw NotFoundException.NotFoundInstance; } return endStart; } /// <summary> /// Identify where the end of the middle / payload section ends. /// </summary> /// <param name="row"> row of black/white values to search </param> /// <returns> Array, containing index of start of 'end block' and end of 'end /// block' </returns> /// <exception cref="NotFoundException"> </exception> //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: int[] decodeEnd(com.google.zxing.common.BitArray row) throws com.google.zxing.NotFoundException internal int[] decodeEnd(BitArray row) { // For convenience, reverse the row and then // search from 'the start' for the end block row.reverse(); try { int endStart = skipWhiteSpace(row); int[] endPattern = findGuardPattern(row, endStart, END_PATTERN_REVERSED); // The start & end patterns must be pre/post fixed by a quiet zone. This // zone must be at least 10 times the width of a narrow line. // ref: http://www.barcode-1.net/i25code.html validateQuietZone(row, endPattern[0]); // Now recalculate the indices of where the 'endblock' starts & stops to // accommodate // the reversed nature of the search int temp = endPattern[0]; endPattern[0] = row.Size - endPattern[1]; endPattern[1] = row.Size - temp; return endPattern; } finally { // Put the row back the right way. row.reverse(); } } /// <param name="row"> row of black/white values to search </param> /// <param name="rowOffset"> position to start search </param> /// <param name="pattern"> pattern of counts of number of black and white pixels that are /// being searched for as a pattern </param> /// <returns> start/end horizontal offset of guard pattern, as an array of two /// ints </returns> /// <exception cref="NotFoundException"> if pattern is not found </exception> //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: private static int[] findGuardPattern(com.google.zxing.common.BitArray row, int rowOffset, int[] pattern) throws com.google.zxing.NotFoundException private static int[] findGuardPattern(BitArray row, int rowOffset, int[] pattern) { // TODO: This is very similar to implementation in UPCEANReader. Consider if they can be // merged to a single method. int patternLength = pattern.Length; int[] counters = new int[patternLength]; int width = row.Size; bool isWhite = false; int counterPosition = 0; int patternStart = rowOffset; for (int x = rowOffset; x < width; x++) { if (row.get(x) ^ isWhite) { counters[counterPosition]++; } else { if (counterPosition == patternLength - 1) { if (patternMatchVariance(counters, pattern, MAX_INDIVIDUAL_VARIANCE) < MAX_AVG_VARIANCE) { return new int[]{patternStart, x}; } patternStart += counters[0] + counters[1]; Array.Copy(counters, 2, counters, 0, patternLength - 2); counters[patternLength - 2] = 0; counters[patternLength - 1] = 0; counterPosition--; } else { counterPosition++; } counters[counterPosition] = 1; isWhite = !isWhite; } } throw NotFoundException.NotFoundInstance; } /// <summary> /// Attempts to decode a sequence of ITF black/white lines into single /// digit. /// </summary> /// <param name="counters"> the counts of runs of observed black/white/black/... values </param> /// <returns> The decoded digit </returns> /// <exception cref="NotFoundException"> if digit cannot be decoded </exception> //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: private static int decodeDigit(int[] counters) throws com.google.zxing.NotFoundException private static int decodeDigit(int[] counters) { int bestVariance = MAX_AVG_VARIANCE; // worst variance we'll accept int bestMatch = -1; int max = PATTERNS.Length; for (int i = 0; i < max; i++) { int[] pattern = PATTERNS[i]; int variance = patternMatchVariance(counters, pattern, MAX_INDIVIDUAL_VARIANCE); if (variance < bestVariance) { bestVariance = variance; bestMatch = i; } } if (bestMatch >= 0) { return bestMatch; } else { throw NotFoundException.NotFoundInstance; } } } }
// 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. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // WriteOnceBlock.cs // // // A propagator block capable of receiving and storing only one message, ever. // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; using System.Security; using System.Threading.Tasks.Dataflow.Internal; namespace System.Threading.Tasks.Dataflow { /// <summary>Provides a buffer for receiving and storing at most one element in a network of dataflow blocks.</summary> /// <typeparam name="T">Specifies the type of the data buffered by this dataflow block.</typeparam> [DebuggerDisplay("{DebuggerDisplayContent,nq}")] [DebuggerTypeProxy(typeof(WriteOnceBlock<>.DebugView))] public sealed class WriteOnceBlock<T> : IPropagatorBlock<T, T>, IReceivableSourceBlock<T>, IDebuggerDisplay { /// <summary>A registry used to store all linked targets and information about them.</summary> private readonly TargetRegistry<T> _targetRegistry; /// <summary>The cloning function.</summary> private readonly Func<T, T> _cloningFunction; /// <summary>The options used to configure this block's execution.</summary> private readonly DataflowBlockOptions _dataflowBlockOptions; /// <summary>Lazily initialized task completion source that produces the actual completion task when needed.</summary> private TaskCompletionSource<VoidResult> _lazyCompletionTaskSource; /// <summary>Whether all future messages should be declined.</summary> private bool _decliningPermanently; /// <summary>Whether block completion is disallowed.</summary> private bool _completionReserved; /// <summary>The header of the singly-assigned value.</summary> private DataflowMessageHeader _header; /// <summary>The singly-assigned value.</summary> private T _value; /// <summary>Gets the object used as the value lock.</summary> private object ValueLock { get { return _targetRegistry; } } /// <summary>Initializes the <see cref="WriteOnceBlock{T}"/>.</summary> /// <param name="cloningFunction"> /// The function to use to clone the data when offered to other blocks. /// This may be null to indicate that no cloning need be performed. /// </param> public WriteOnceBlock(Func<T, T> cloningFunction) : this(cloningFunction, DataflowBlockOptions.Default) { } /// <summary>Initializes the <see cref="WriteOnceBlock{T}"/> with the specified <see cref="DataflowBlockOptions"/>.</summary> /// <param name="cloningFunction"> /// The function to use to clone the data when offered to other blocks. /// This may be null to indicate that no cloning need be performed. /// </param> /// <param name="dataflowBlockOptions">The options with which to configure this <see cref="WriteOnceBlock{T}"/>.</param> /// <exception cref="System.ArgumentNullException">The <paramref name="dataflowBlockOptions"/> is null (Nothing in Visual Basic).</exception> public WriteOnceBlock(Func<T, T> cloningFunction, DataflowBlockOptions dataflowBlockOptions) { // Validate arguments if (dataflowBlockOptions == null) throw new ArgumentNullException("dataflowBlockOptions"); Contract.EndContractBlock(); // Store the option _cloningFunction = cloningFunction; _dataflowBlockOptions = dataflowBlockOptions.DefaultOrClone(); // The target registry also serves as our ValueLock, // and thus must always be initialized, even if the block is pre-canceled, as // subsequent usage of the block may run through code paths that try to take this lock. _targetRegistry = new TargetRegistry<T>(this); // If a cancelable CancellationToken has been passed in, // we need to initialize the completion task's TCS now. if (dataflowBlockOptions.CancellationToken.CanBeCanceled) { _lazyCompletionTaskSource = new TaskCompletionSource<VoidResult>(); // If we've already had cancellation requested, do as little work as we have to // in order to be done. if (dataflowBlockOptions.CancellationToken.IsCancellationRequested) { _completionReserved = _decliningPermanently = true; // Cancel the completion task's TCS _lazyCompletionTaskSource.SetCanceled(); } else { // Handle async cancellation requests by declining on the target Common.WireCancellationToComplete( dataflowBlockOptions.CancellationToken, _lazyCompletionTaskSource.Task, state => ((WriteOnceBlock<T>)state).Complete(), this); } } #if FEATURE_TRACING DataflowEtwProvider etwLog = DataflowEtwProvider.Log; if (etwLog.IsEnabled()) { etwLog.DataflowBlockCreated(this, dataflowBlockOptions); } #endif } /// <summary>Asynchronously completes the block on another task.</summary> /// <remarks> /// This must only be called once all of the completion conditions are met. /// </remarks> [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] private void CompleteBlockAsync(IList<Exception> exceptions) { Contract.Requires(_decliningPermanently, "We may get here only after we have started to decline permanently."); Contract.Requires(_completionReserved, "We may get here only after we have reserved completion."); Common.ContractAssertMonitorStatus(ValueLock, held: false); // If there is no exceptions list, we offer the message around, and then complete. // If there is an exception list, we complete without offering the message. if (exceptions == null) { // Offer the message to any linked targets and complete the block asynchronously to avoid blocking the caller var taskForOutputProcessing = new Task(state => ((WriteOnceBlock<T>)state).OfferToTargetsAndCompleteBlock(), this, Common.GetCreationOptionsForTask()); #if FEATURE_TRACING DataflowEtwProvider etwLog = DataflowEtwProvider.Log; if (etwLog.IsEnabled()) { etwLog.TaskLaunchedForMessageHandling( this, taskForOutputProcessing, DataflowEtwProvider.TaskLaunchedReason.OfferingOutputMessages, _header.IsValid ? 1 : 0); } #endif // Start the task handling scheduling exceptions Exception exception = Common.StartTaskSafe(taskForOutputProcessing, _dataflowBlockOptions.TaskScheduler); if (exception != null) CompleteCore(exception, storeExceptionEvenIfAlreadyCompleting: true); } else { // Complete the block asynchronously to avoid blocking the caller Task.Factory.StartNew(state => { Tuple<WriteOnceBlock<T>, IList<Exception>> blockAndList = (Tuple<WriteOnceBlock<T>, IList<Exception>>)state; blockAndList.Item1.CompleteBlock(blockAndList.Item2); }, Tuple.Create(this, exceptions), CancellationToken.None, Common.GetCreationOptionsForTask(), TaskScheduler.Default); } } /// <summary>Offers the message and completes the block.</summary> /// <remarks> /// This is called only once. /// </remarks> private void OfferToTargetsAndCompleteBlock() { // OfferToTargets calls to potentially multiple targets, each of which // could be faulty and throw an exception. OfferToTargets creates a // list of all such exceptions and returns it. // If _value is null, OfferToTargets does nothing. List<Exception> exceptions = OfferToTargets(); CompleteBlock(exceptions); } /// <summary>Completes the block.</summary> /// <remarks> /// This is called only once. /// </remarks> private void CompleteBlock(IList<Exception> exceptions) { // Do not invoke the CompletionTaskSource property if there is a chance that _lazyCompletionTaskSource // has not been initialized yet and we may have to complete normally, because that would defeat the // sole purpose of the TCS being lazily initialized. Contract.Requires(_lazyCompletionTaskSource == null || !_lazyCompletionTaskSource.Task.IsCompleted, "The task completion source must not be completed. This must be the only thread that ever completes the block."); // Save the linked list of targets so that it could be traversed later to propagate completion TargetRegistry<T>.LinkedTargetInfo linkedTargets = _targetRegistry.ClearEntryPoints(); // Complete the block's completion task if (exceptions != null && exceptions.Count > 0) { CompletionTaskSource.TrySetException(exceptions); } else if (_dataflowBlockOptions.CancellationToken.IsCancellationRequested) { CompletionTaskSource.TrySetCanceled(); } else { // Safely try to initialize the completion task's TCS with a cached completed TCS. // If our attempt succeeds (CompareExchange returns null), we have nothing more to do. // If the completion task's TCS was already initialized (CompareExchange returns non-null), // we have to complete that TCS instance. if (Interlocked.CompareExchange(ref _lazyCompletionTaskSource, Common.CompletedVoidResultTaskCompletionSource, null) != null) { _lazyCompletionTaskSource.TrySetResult(default(VoidResult)); } } // Now that the completion task is completed, we may propagate completion to the linked targets _targetRegistry.PropagateCompletion(linkedTargets); #if FEATURE_TRACING DataflowEtwProvider etwLog = DataflowEtwProvider.Log; if (etwLog.IsEnabled()) { etwLog.DataflowBlockCompleted(this); } #endif } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Blocks/Member[@name="Fault"]/*' /> void IDataflowBlock.Fault(Exception exception) { if (exception == null) throw new ArgumentNullException("exception"); Contract.EndContractBlock(); CompleteCore(exception, storeExceptionEvenIfAlreadyCompleting: false); } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Blocks/Member[@name="Complete"]/*' /> public void Complete() { CompleteCore(exception: null, storeExceptionEvenIfAlreadyCompleting: false); } private void CompleteCore(Exception exception, bool storeExceptionEvenIfAlreadyCompleting) { Contract.Requires(exception != null || !storeExceptionEvenIfAlreadyCompleting, "When storeExceptionEvenIfAlreadyCompleting is set to true, an exception must be provided."); Contract.EndContractBlock(); bool thisThreadReservedCompletion = false; lock (ValueLock) { // Faulting from outside is allowed until we start declining permanently if (_decliningPermanently && !storeExceptionEvenIfAlreadyCompleting) return; // Decline further messages _decliningPermanently = true; // Reserve Completion. // If storeExceptionEvenIfAlreadyCompleting is true, we are here to fault the block, // because we couldn't launch the offer-and-complete task. // We have to retry to just complete. We do that by pretending completion wasn't reserved. if (!_completionReserved || storeExceptionEvenIfAlreadyCompleting) thisThreadReservedCompletion = _completionReserved = true; } // This call caused us to start declining further messages, // there's nothing more this block needs to do... complete it if we just reserved completion. if (thisThreadReservedCompletion) { List<Exception> exceptions = null; if (exception != null) { exceptions = new List<Exception>(); exceptions.Add(exception); } CompleteBlockAsync(exceptions); } } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Sources/Member[@name="TryReceive"]/*' /> public Boolean TryReceive(Predicate<T> filter, out T item) { // No need to take the outgoing lock, as we don't need to synchronize with other // targets, and _value only ever goes from null to non-null, not the other way around. // If we have a value, give it up. All receives on a successfully // completed WriteOnceBlock will return true, as long as the message // passes the filter (all messages pass a null filter). if (_header.IsValid && (filter == null || filter(_value))) { item = CloneItem(_value); return true; } // Otherwise, nothing to receive else { item = default(T); return false; } } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Sources/Member[@name="TryReceiveAll"]/*' /> Boolean IReceivableSourceBlock<T>.TryReceiveAll(out IList<T> items) { // Try to receive the one item this block may have. // If we can, give back an array of one item. Otherwise, // give back null. T item; if (TryReceive(null, out item)) { items = new T[] { item }; return true; } else { items = null; return false; } } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Sources/Member[@name="LinkTo"]/*' /> [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] public IDisposable LinkTo(ITargetBlock<T> target, DataflowLinkOptions linkOptions) { // Validate arguments if (target == null) throw new ArgumentNullException("target"); if (linkOptions == null) throw new ArgumentNullException("linkOptions"); Contract.EndContractBlock(); bool hasValue; bool isCompleted; lock (ValueLock) { hasValue = HasValue; isCompleted = _completionReserved; // If we haven't gotten a value yet and the block is not complete, add the target and bail if (!hasValue && !isCompleted) { _targetRegistry.Add(ref target, linkOptions); return Common.CreateUnlinker(ValueLock, _targetRegistry, target); } } // If we already have a value, send it along to the linking target if (hasValue) { bool useCloning = _cloningFunction != null; target.OfferMessage(_header, _value, this, consumeToAccept: useCloning); } // If completion propagation has been requested, do it safely. // The Completion property will ensure the lazy TCS is initialized. if (linkOptions.PropagateCompletion) Common.PropagateCompletionOnceCompleted(Completion, target); return Disposables.Nop; } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Blocks/Member[@name="Completion"]/*' /> public Task Completion { get { return CompletionTaskSource.Task; } } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Targets/Member[@name="OfferMessage"]/*' /> DataflowMessageStatus ITargetBlock<T>.OfferMessage(DataflowMessageHeader messageHeader, T messageValue, ISourceBlock<T> source, Boolean consumeToAccept) { // Validate arguments if (!messageHeader.IsValid) throw new ArgumentException(SR.Argument_InvalidMessageHeader, "messageHeader"); if (source == null && consumeToAccept) throw new ArgumentException(SR.Argument_CantConsumeFromANullSource, "consumeToAccept"); Contract.EndContractBlock(); bool thisThreadReservedCompletion = false; lock (ValueLock) { // If we are declining messages, bail if (_decliningPermanently) return DataflowMessageStatus.DecliningPermanently; // Consume the message from the source if necessary. We do this while holding ValueLock to prevent multiple concurrent // offers from all succeeding. if (consumeToAccept) { bool consumed; messageValue = source.ConsumeMessage(messageHeader, this, out consumed); if (!consumed) return DataflowMessageStatus.NotAvailable; } // Update the header and the value _header = Common.SingleMessageHeader; _value = messageValue; // We got what we needed. Start declining permanently. _decliningPermanently = true; // Reserve Completion if (!_completionReserved) thisThreadReservedCompletion = _completionReserved = true; } // Since this call to OfferMessage succeeded (and only one can ever), complete the block // (but asynchronously so as not to block the Post call while offering to // targets, running synchronous continuations off of the completion task, etc.) if (thisThreadReservedCompletion) CompleteBlockAsync(exceptions: null); return DataflowMessageStatus.Accepted; } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Sources/Member[@name="ConsumeMessage"]/*' /> T ISourceBlock<T>.ConsumeMessage(DataflowMessageHeader messageHeader, ITargetBlock<T> target, out Boolean messageConsumed) { // Validate arguments if (!messageHeader.IsValid) throw new ArgumentException(SR.Argument_InvalidMessageHeader, "messageHeader"); if (target == null) throw new ArgumentNullException("target"); Contract.EndContractBlock(); // As long as the message being requested is the one we have, allow it to be consumed, // but make a copy using the provided cloning function. if (_header.Id == messageHeader.Id) { messageConsumed = true; return CloneItem(_value); } else { messageConsumed = false; return default(T); } } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Sources/Member[@name="ReserveMessage"]/*' /> Boolean ISourceBlock<T>.ReserveMessage(DataflowMessageHeader messageHeader, ITargetBlock<T> target) { // Validate arguments if (!messageHeader.IsValid) throw new ArgumentException(SR.Argument_InvalidMessageHeader, "messageHeader"); if (target == null) throw new ArgumentNullException("target"); Contract.EndContractBlock(); // As long as the message is the one we have, it can be "reserved." // Reservations on a WriteOnceBlock are not exclusive, because // everyone who wants a copy can get one. return _header.Id == messageHeader.Id; } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Sources/Member[@name="ReleaseReservation"]/*' /> void ISourceBlock<T>.ReleaseReservation(DataflowMessageHeader messageHeader, ITargetBlock<T> target) { // Validate arguments if (!messageHeader.IsValid) throw new ArgumentException(SR.Argument_InvalidMessageHeader, "messageHeader"); if (target == null) throw new ArgumentNullException("target"); Contract.EndContractBlock(); // As long as the message is the one we have, everything's fine. if (_header.Id != messageHeader.Id) throw new InvalidOperationException(SR.InvalidOperation_MessageNotReservedByTarget); // In other blocks, upon release we typically re-offer the message to all linked targets. // We need to do the same thing for WriteOnceBlock, in order to account for cases where the block // may be linked to a join or similar block, such that the join could never again be satisfied // if it didn't receive another offer from this source. However, since the message is broadcast // and all targets can get a copy, we don't need to broadcast to all targets, only to // the target that released the message. Note that we don't care whether it's accepted // or not, nor do we care about any exceptions which may emerge (they should just propagate). Debug.Assert(_header.IsValid, "A valid header is required."); bool useCloning = _cloningFunction != null; target.OfferMessage(_header, _value, this, consumeToAccept: useCloning); } /// <summary>Clones the item.</summary> /// <param name="item">The item to clone.</param> /// <returns>The cloned item.</returns> private T CloneItem(T item) { return _cloningFunction != null ? _cloningFunction(item) : item; } /// <summary>Offers the WriteOnceBlock's message to all targets.</summary> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] private List<Exception> OfferToTargets() { Common.ContractAssertMonitorStatus(ValueLock, held: false); // If there is a message, offer it to everyone. Return values // don't matter, because we only get one message and then complete, // and everyone who wants a copy can get a copy. List<Exception> exceptions = null; if (HasValue) { TargetRegistry<T>.LinkedTargetInfo cur = _targetRegistry.FirstTargetNode; while (cur != null) { TargetRegistry<T>.LinkedTargetInfo next = cur.Next; ITargetBlock<T> target = cur.Target; try { // Offer the message. If there's a cloning function, we force the target to // come back to us to consume the message, allowing us the opportunity to run // the cloning function once we know they want the data. If there is no cloning // function, there's no reason for them to call back here. bool useCloning = _cloningFunction != null; target.OfferMessage(_header, _value, this, consumeToAccept: useCloning); } catch (Exception exc) { // Track any erroneous exceptions that may occur // and return them to the caller so that they may // be logged in the completion task. Common.StoreDataflowMessageValueIntoExceptionData(exc, _value); Common.AddException(ref exceptions, exc); } cur = next; } } return exceptions; } /// <summary>Ensures the completion task's TCS is initialized.</summary> /// <returns>The completion task's TCS.</returns> private TaskCompletionSource<VoidResult> CompletionTaskSource { get { // If the completion task's TCS has not been initialized by now, safely try to initialize it. // It is very important that once a completion task/source instance has been handed out, // it remains the block's completion task. if (_lazyCompletionTaskSource == null) { Interlocked.CompareExchange(ref _lazyCompletionTaskSource, new TaskCompletionSource<VoidResult>(), null); } return _lazyCompletionTaskSource; } } /// <summary>Gets whether the block is storing a value.</summary> private bool HasValue { get { return _header.IsValid; } } /// <summary>Gets the value being stored by the block.</summary> private T Value { get { return _header.IsValid ? _value : default(T); } } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Blocks/Member[@name="ToString"]/*' /> public override string ToString() { return Common.GetNameForDebugger(this, _dataflowBlockOptions); } /// <summary>The data to display in the debugger display attribute.</summary> [SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider")] private object DebuggerDisplayContent { get { return string.Format("{0}, HasValue={1}, Value={2}", Common.GetNameForDebugger(this, _dataflowBlockOptions), HasValue, Value); } } /// <summary>Gets the data to display in the debugger display attribute for this instance.</summary> object IDebuggerDisplay.Content { get { return DebuggerDisplayContent; } } /// <summary>Provides a debugger type proxy for WriteOnceBlock.</summary> private sealed class DebugView { /// <summary>The WriteOnceBlock being viewed.</summary> private readonly WriteOnceBlock<T> _writeOnceBlock; /// <summary>Initializes the debug view.</summary> /// <param name="writeOnceBlock">The WriteOnceBlock to view.</param> public DebugView(WriteOnceBlock<T> writeOnceBlock) { Contract.Requires(writeOnceBlock != null, "Need a block with which to construct the debug view."); _writeOnceBlock = writeOnceBlock; } /// <summary>Gets whether the WriteOnceBlock has completed.</summary> public bool IsCompleted { get { return _writeOnceBlock.Completion.IsCompleted; } } /// <summary>Gets the block's Id.</summary> public int Id { get { return Common.GetBlockId(_writeOnceBlock); } } /// <summary>Gets whether the WriteOnceBlock has a value.</summary> public bool HasValue { get { return _writeOnceBlock.HasValue; } } /// <summary>Gets the WriteOnceBlock's value if it has one, or default(T) if it doesn't.</summary> public T Value { get { return _writeOnceBlock.Value; } } /// <summary>Gets the DataflowBlockOptions used to configure this block.</summary> public DataflowBlockOptions DataflowBlockOptions { get { return _writeOnceBlock._dataflowBlockOptions; } } /// <summary>Gets the set of all targets linked from this block.</summary> public TargetRegistry<T> LinkedTargets { get { return _writeOnceBlock._targetRegistry; } } } } }
// Copyright (c) 2015-present, Parse, LLC. All rights reserved. This source code is licensed under the BSD-style license found in the LICENSE file in the root directory of this source tree. An additional grant of patent rights can be found in the PATENTS file in the same directory. using Microsoft.Phone.Notification; using Parse.Internal; using System; using System.Linq; using System.Collections.Generic; using System.Globalization; using System.IO.IsolatedStorage; using System.Threading; using System.Threading.Tasks; using System.Xml; namespace Parse { partial class PlatformHooks : IPlatformHooks { /// <summary> /// Future proofing: Right now there's only one valid channel for the app, but we will likely /// want to allow additional channels for auxiliary tiles (i.e. a contacts app can have a new /// channel for each contact and the UI needs to pop up on the right tile). The expansion job /// generically has one _Installation field it passes to device-specific code, so we store a map /// of tag -> channel URI. Right now, there is only one valid tag and it is automatic. /// Unused variable warnings are suppressed because this const is used in WinRT and WinPhone but not NetFx. /// </summary> static readonly string toastChannelTag = "_Toast"; private static Lazy<Task<HttpNotificationChannel>> getToastChannelTask = new Lazy<Task<HttpNotificationChannel>>(() => Task.Run(() => { try { HttpNotificationChannel toastChannel = HttpNotificationChannel.Find(toastChannelTag); if (toastChannel == null) { toastChannel = new HttpNotificationChannel(toastChannelTag); // Note: We could bind to the ChannelUriUpdated event & automatically save instead of checking // whether the channel has changed on demand. This is more seamless but adds API requests for a // feature that may not be in use. Maybe we should build an auto-update feature in the future? // Or maybe Push.subscribe calls will always be a save & that should be good enough for us. toastChannel.Open(); } // You cannot call BindToShellToast willy nilly across restarts. This was somehow built in a non-idempotent way. if (!toastChannel.IsShellToastBound) { toastChannel.BindToShellToast(); } return toastChannel; // If the app manifest does not declare ID_CAP_PUSH_NOTIFICATION } catch (UnauthorizedAccessException) { return null; } }) ); private static Lazy<Task<string>> getToastUriTask = new Lazy<Task<string>>(async () => { var channel = await getToastChannelTask.Value; if (channel == null) { return null; } var source = new TaskCompletionSource<string>(); EventHandler<NotificationChannelUriEventArgs> handler = null; EventHandler<NotificationChannelErrorEventArgs> errorHandler = null; handler = (sender, args) => { // Prevent NullReferenceException if (args.ChannelUri == null) { source.TrySetResult(null); } else { source.TrySetResult(args.ChannelUri.AbsoluteUri); } }; errorHandler = (sender, args) => { source.TrySetException(new ApplicationException(args.Message)); }; channel.ChannelUriUpdated += handler; channel.ErrorOccurred += errorHandler; // Sometimes the channel isn't ready yet. Sometimes it is. if (channel.ChannelUri != null && !source.Task.IsCompleted) { source.TrySetResult(channel.ChannelUri.AbsoluteUri); } return await source.Task.ContinueWith(t => { // Cleanup the handler. channel.ChannelUriUpdated -= handler; channel.ErrorOccurred -= errorHandler; return t; }).Unwrap(); }); internal static Task<HttpNotificationChannel> GetToastChannelTask { get { return getToastChannelTask.Value; } } static PlatformHooks() { var _ = GetToastChannelTask; } private IHttpClient httpClient = null; public IHttpClient HttpClient { get { httpClient = httpClient ?? new HttpClient(); return httpClient; } } public string SDKName { get { return "wp"; } } public string AppName { get { return GetAppAttribute("Title"); } } public string AppBuildVersion { get { return GetAppAttribute("Version"); } } public string AppDisplayVersion { get { return GetAppAttribute("Version"); } } public string AppIdentifier { get { return GetAppAttribute("ProductID"); } } public string OSVersion { get { return Environment.OSVersion.ToString(); } } public string DeviceType { get { return "winphone"; } } public string DeviceTimeZone { get { // We need the system string to be in english so we'll have the proper key in our lookup table. // If it's not in english then we will attempt to fallback to the closest Time Zone we can find. TimeZoneInfo tzInfo = TimeZoneInfo.Local; string deviceTimeZone = null; if (ParseInstallation.TimeZoneNameMap.TryGetValue(tzInfo.StandardName, out deviceTimeZone)) { return deviceTimeZone; } TimeSpan utcOffset = tzInfo.BaseUtcOffset; // If we have an offset that is not a round hour, then use our second map to see if we can // convert it or not. if (ParseInstallation.TimeZoneOffsetMap.TryGetValue(utcOffset, out deviceTimeZone)) { return deviceTimeZone; } // NOTE: Etc/GMT{+/-} format is inverted from the UTC offset we use as normal people - // a negative value means ahead of UTC, a positive value means behind UTC. bool negativeOffset = utcOffset.Ticks < 0; return String.Format("Etc/GMT{0}{1}", negativeOffset ? "+" : "-", Math.Abs(utcOffset.Hours)); } } public void Initialize() { // Do nothing. } public Task ExecuteParseInstallationSaveHookAsync(ParseInstallation installation) { return getToastUriTask.Value.ContinueWith(t => { installation.SetIfDifferent("deviceUris", t.Result == null ? null : new Dictionary<string, string> { { toastChannelTag, t.Result } }); }); } /// <summary> /// Gets an attribute from the Windows Phone App Manifest App element /// </summary> /// <param name="attributeName">the attribute name</param> /// <returns>the attribute value</returns> /// This is a duplicate of what we have in ParseInstallation. We do it because /// it's easier to maintain this way (rather than referencing <c>PlatformHooks</c> everywhere). private string GetAppAttribute(string attributeName) { string appManifestName = "WMAppManifest.xml"; string appNodeName = "App"; var settings = new XmlReaderSettings(); settings.XmlResolver = new XmlXapResolver(); using (XmlReader rdr = XmlReader.Create(appManifestName, settings)) { rdr.ReadToDescendant(appNodeName); if (!rdr.IsStartElement()) { throw new System.FormatException(appManifestName + " is missing " + appNodeName); } return rdr.GetAttribute(attributeName); } } /// <summary> /// Wraps the custom settings object for Parse so that it can be exposed as ApplicationSettings. /// </summary> private class SettingsWrapper : IDictionary<string, object> { private static readonly string prefix = "Parse."; private static SettingsWrapper wrapper; public static SettingsWrapper Wrapper { get { wrapper = wrapper ?? new SettingsWrapper(); return wrapper; } } private IDictionary<string, object> data; private SettingsWrapper() { try { data = Windows.Storage.ApplicationData.Current.LocalSettings.Values; } catch (System.NotImplementedException) { data = IsolatedStorageSettings.ApplicationSettings; } } public void Add(string key, object value) { data.Add(prefix + key, value); } public bool ContainsKey(string key) { return data.ContainsKey(prefix + key); } public ICollection<string> Keys { get { return this.Select(kvp => kvp.Key).ToList(); } } public bool Remove(string key) { return data.Remove(prefix + key); } public bool TryGetValue(string key, out object value) { return data.TryGetValue(prefix + key, out value); } public ICollection<object> Values { get { return this.Select(kvp => kvp.Value).ToList(); } } public object this[string key] { get { return data[prefix + key]; } set { data[prefix + key] = value; } } public void Add(KeyValuePair<string, object> item) { data.Add(new KeyValuePair<string, object>(prefix + item.Key, item.Value)); } public void Clear() { foreach (var key in Keys) { data.Remove(key); } } public bool Contains(KeyValuePair<string, object> item) { return data.Contains(new KeyValuePair<string, object>(prefix + item.Key, item.Value)); } public void CopyTo(KeyValuePair<string, object>[] array, int arrayIndex) { this.ToList().CopyTo(array, arrayIndex); } public int Count { get { return Keys.Count; } } public bool IsReadOnly { get { return data.IsReadOnly; } } public bool Remove(KeyValuePair<string, object> item) { return data.Remove(new KeyValuePair<string, object>(prefix + item.Key, item.Value)); } public IEnumerator<KeyValuePair<string, object>> GetEnumerator() { return data .Where(kvp => kvp.Key.StartsWith(prefix)) .Select(kvp => new KeyValuePair<string, object>(kvp.Key.Substring(prefix.Length), kvp.Value)) .GetEnumerator(); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return this.GetEnumerator(); } } /// <summary> /// Provides a dictionary that gets persisted on the filesystem between runs of the app. /// This is analogous to NSUserDefaults in iOS. /// </summary> public IDictionary<string, object> ApplicationSettings { get { return SettingsWrapper.Wrapper; } } } }
using System; using System.Linq; using System.Threading.Tasks; using Abp.Collections.Extensions; using Abp.Dependency; using Abp.Localization; using Abp.Threading; namespace Abp.Authorization { /// <summary> /// Extension methods for <see cref="IPermissionChecker"/> /// </summary> public static class PermissionCheckerExtensions { /// <summary> /// Checks if given user is granted for given permission. /// </summary> /// <param name="permissionChecker">Permission checker</param> /// <param name="user">User</param> /// <param name="requiresAll">True, to require all given permissions are granted. False, to require one or more.</param> /// <param name="permissionNames">Name of the permissions</param> public static async Task<bool> IsGrantedAsync(this IPermissionChecker permissionChecker, UserIdentifier user, bool requiresAll, params string[] permissionNames) { if (permissionNames.IsNullOrEmpty()) { return true; } if (requiresAll) { foreach (var permissionName in permissionNames) { if (!(await permissionChecker.IsGrantedAsync(user, permissionName))) { return false; } } return true; } else { foreach (var permissionName in permissionNames) { if (await permissionChecker.IsGrantedAsync(user, permissionName)) { return true; } } return false; } } /// <summary> /// Checks if given user is granted for given permission. /// </summary> /// <param name="permissionChecker">Permission checker</param> /// <param name="user">User</param> /// <param name="requiresAll">True, to require all given permissions are granted. False, to require one or more.</param> /// <param name="permissionNames">Name of the permissions</param> public static bool IsGranted(this IPermissionChecker permissionChecker, UserIdentifier user, bool requiresAll, params string[] permissionNames) { if (permissionNames.IsNullOrEmpty()) { return true; } if (requiresAll) { foreach (var permissionName in permissionNames) { if (!(permissionChecker.IsGranted(user, permissionName))) { return false; } } return true; } else { foreach (var permissionName in permissionNames) { if (permissionChecker.IsGranted(user, permissionName)) { return true; } } return false; } } /// <summary> /// Checks if current user is granted for given permission. /// </summary> /// <param name="permissionChecker">Permission checker</param> /// <param name="requiresAll">True, to require all given permissions are granted. False, to require one or more.</param> /// <param name="permissionNames">Name of the permissions</param> public static async Task<bool> IsGrantedAsync(this IPermissionChecker permissionChecker, bool requiresAll, params string[] permissionNames) { if (permissionNames.IsNullOrEmpty()) { return true; } if (requiresAll) { foreach (var permissionName in permissionNames) { if (!(await permissionChecker.IsGrantedAsync(permissionName))) { return false; } } return true; } else { foreach (var permissionName in permissionNames) { if (await permissionChecker.IsGrantedAsync(permissionName)) { return true; } } return false; } } /// <summary> /// Checks if current user is granted for given permission. /// </summary> /// <param name="permissionChecker">Permission checker</param> /// <param name="requiresAll">True, to require all given permissions are granted. False, to require one or more.</param> /// <param name="permissionNames">Name of the permissions</param> public static bool IsGranted(this IPermissionChecker permissionChecker, bool requiresAll, params string[] permissionNames) { if (permissionNames.IsNullOrEmpty()) { return true; } if (requiresAll) { foreach (var permissionName in permissionNames) { if (!(permissionChecker.IsGranted(permissionName))) { return false; } } return true; } else { foreach (var permissionName in permissionNames) { if (permissionChecker.IsGranted(permissionName)) { return true; } } return false; } } /// <summary> /// Authorizes current user for given permission or permissions, /// throws <see cref="AbpAuthorizationException"/> if not authorized. /// User it authorized if any of the <see cref="permissionNames"/> are granted. /// </summary> /// <param name="permissionChecker">Permission checker</param> /// <param name="permissionNames">Name of the permissions to authorize</param> /// <exception cref="AbpAuthorizationException">Throws authorization exception if</exception> public static Task AuthorizeAsync(this IPermissionChecker permissionChecker, params string[] permissionNames) { return AuthorizeAsync(permissionChecker, false, permissionNames); } /// <summary> /// Authorizes current user for given permission or permissions, /// throws <see cref="AbpAuthorizationException"/> if not authorized. /// User it authorized if any of the <see cref="permissionNames"/> are granted. /// </summary> /// <param name="permissionChecker">Permission checker</param> /// <param name="permissionNames">Name of the permissions to authorize</param> /// <exception cref="AbpAuthorizationException">Throws authorization exception if</exception> public static void Authorize(this IPermissionChecker permissionChecker, params string[] permissionNames) { Authorize(permissionChecker, false, permissionNames); } /// <summary> /// Authorizes current user for given permission or permissions, /// throws <see cref="AbpAuthorizationException"/> if not authorized. /// </summary> /// <param name="permissionChecker">Permission checker</param> /// <param name="requireAll"> /// If this is set to true, all of the <see cref="permissionNames"/> must be granted. /// If it's false, at least one of the <see cref="permissionNames"/> must be granted. /// </param> /// <param name="permissionNames">Name of the permissions to authorize</param> /// <exception cref="AbpAuthorizationException">Throws authorization exception if</exception> public static async Task AuthorizeAsync(this IPermissionChecker permissionChecker, bool requireAll, params string[] permissionNames) { if (await IsGrantedAsync(permissionChecker, requireAll, permissionNames)) { return; } var localizedPermissionNames = LocalizePermissionNames(permissionChecker, permissionNames); if (requireAll) { throw new AbpAuthorizationException( string.Format( L( permissionChecker, "AllOfThesePermissionsMustBeGranted", "Required permissions are not granted. All of these permissions must be granted: {0}" ), string.Join(", ", localizedPermissionNames) ) ); } else { throw new AbpAuthorizationException( string.Format( L( permissionChecker, "AtLeastOneOfThesePermissionsMustBeGranted", "Required permissions are not granted. At least one of these permissions must be granted: {0}" ), string.Join(", ", localizedPermissionNames) ) ); } } /// <summary> /// Authorizes current user for given permission or permissions, /// throws <see cref="AbpAuthorizationException"/> if not authorized. /// </summary> /// <param name="permissionChecker">Permission checker</param> /// <param name="requireAll"> /// If this is set to true, all of the <see cref="permissionNames"/> must be granted. /// If it's false, at least one of the <see cref="permissionNames"/> must be granted. /// </param> /// <param name="permissionNames">Name of the permissions to authorize</param> /// <exception cref="AbpAuthorizationException">Throws authorization exception if</exception> public static void Authorize(this IPermissionChecker permissionChecker, bool requireAll, params string[] permissionNames) { if (IsGranted(permissionChecker, requireAll, permissionNames)) { return; } var localizedPermissionNames = LocalizePermissionNames(permissionChecker, permissionNames); if (requireAll) { throw new AbpAuthorizationException( string.Format( L( permissionChecker, "AllOfThesePermissionsMustBeGranted", "Required permissions are not granted. All of these permissions must be granted: {0}" ), string.Join(", ", localizedPermissionNames) ) ); } else { throw new AbpAuthorizationException( string.Format( L( permissionChecker, "AtLeastOneOfThesePermissionsMustBeGranted", "Required permissions are not granted. At least one of these permissions must be granted: {0}" ), string.Join(", ", localizedPermissionNames) ) ); } } public static string L(IPermissionChecker permissionChecker, string name, string defaultValue) { if (!(permissionChecker is IIocManagerAccessor)) { return defaultValue; } var iocManager = (permissionChecker as IIocManagerAccessor).IocManager; using (var localizationManager = iocManager.ResolveAsDisposable<ILocalizationManager>()) { return localizationManager.Object.GetString(AbpConsts.LocalizationSourceName, name); } } public static string[] LocalizePermissionNames(IPermissionChecker permissionChecker, string[] permissionNames) { if (!(permissionChecker is IIocManagerAccessor)) { return permissionNames; } var iocManager = (permissionChecker as IIocManagerAccessor).IocManager; using (var localizationContext = iocManager.ResolveAsDisposable<ILocalizationContext>()) { using (var permissionManager = iocManager.ResolveAsDisposable<IPermissionManager>()) { return permissionNames.Select(permissionName => { var permission = permissionManager.Object.GetPermissionOrNull(permissionName); return permission?.DisplayName == null ? permissionName : permission.DisplayName.Localize(localizationContext.Object); }).ToArray(); } } } } }
namespace Gu.Wpf.Geometry { using System; using System.Diagnostics; using System.Windows; using System.Windows.Data; using System.Windows.Media; using System.Windows.Shapes; using System.Windows.Threading; /// <summary> /// Base class for balloon shapes. /// </summary> public abstract class BalloonBase : Shape { /// <summary>Identifies the <see cref="ConnectorOffset"/> dependency property.</summary> public static readonly DependencyProperty ConnectorOffsetProperty = DependencyProperty.Register( nameof(ConnectorOffset), typeof(Vector), typeof(BalloonBase), new FrameworkPropertyMetadata( default(Vector), FrameworkPropertyMetadataOptions.AffectsRender, OnConnectorChanged)); /// <summary>Identifies the <see cref="ConnectorAngle"/> dependency property.</summary> public static readonly DependencyProperty ConnectorAngleProperty = DependencyProperty.Register( nameof(ConnectorAngle), typeof(double), typeof(BalloonBase), new FrameworkPropertyMetadata( 15.0, FrameworkPropertyMetadataOptions.AffectsRender, OnConnectorChanged)); /// <summary>Identifies the <see cref="PlacementTarget"/> dependency property.</summary> public static readonly DependencyProperty PlacementTargetProperty = DependencyProperty.Register( nameof(PlacementTarget), typeof(UIElement), typeof(BalloonBase), new PropertyMetadata( default(UIElement), OnPlacementTargetChanged)); /// <summary>Identifies the <see cref="PlacementRectangle"/> dependency property.</summary> public static readonly DependencyProperty PlacementRectangleProperty = DependencyProperty.Register( nameof(PlacementRectangle), typeof(Rect), typeof(BalloonBase), new PropertyMetadata( Rect.Empty, (d, e) => ((BalloonBase)d).UpdateConnectorOffset())); /// <summary>Identifies the <see cref="PlacementOptions"/> dependency property.</summary> public static readonly DependencyProperty PlacementOptionsProperty = DependencyProperty.Register( nameof(PlacementOptions), typeof(PlacementOptions), typeof(BalloonBase), new PropertyMetadata( PlacementOptions.Auto, (d, e) => ((BalloonBase)d).OnLayoutUpdated(null, EventArgs.Empty))); /// <summary>Identifies the ConnectorVertexPoint dependency property.</summary> protected static readonly DependencyProperty ConnectorVertexPointProperty = DependencyProperty.Register( "ConnectorVertexPoint", typeof(Point), typeof(BalloonBase), new PropertyMetadata(default(Point))); /// <summary>Identifies the ConnectorPoint1 dependency property.</summary> protected static readonly DependencyProperty ConnectorPoint1Property = DependencyProperty.Register( "ConnectorPoint1", typeof(Point), typeof(BalloonBase), new PropertyMetadata(default(Point))); /// <summary>Identifies the ConnectorPoint2 dependency property.</summary> protected static readonly DependencyProperty ConnectorPoint2Property = DependencyProperty.Register( "ConnectorPoint2", typeof(Point), typeof(BalloonBase), new PropertyMetadata(default(Point))); private readonly PenCache penCache = new PenCache(); private Geometry? balloonGeometry; static BalloonBase() { StretchProperty.OverrideMetadata(typeof(BalloonBase), new FrameworkPropertyMetadata(Stretch.Fill)); } /// <summary> /// Gets or sets the <see cref="Vector"/> specifying the connector of the <see cref="BalloonBase"/>. /// </summary> public Vector ConnectorOffset { get => (Vector)this.GetValue(ConnectorOffsetProperty); set => this.SetValue(ConnectorOffsetProperty, value); } /// <summary> /// Gets or sets the angle of the connector of the <see cref="BalloonBase"/>. /// </summary> public double ConnectorAngle { get => (double)this.GetValue(ConnectorAngleProperty); set => this.SetValue(ConnectorAngleProperty, value); } /// <summary> /// Gets or sets PlacementTarget property of the <see cref="BalloonBase"/>. /// </summary> public UIElement? PlacementTarget { get => (UIElement?)this.GetValue(PlacementTargetProperty); set => this.SetValue(PlacementTargetProperty, value); } /// <summary> /// Gets or sets PlacementRectangle property of the balloon. /// </summary> public Rect PlacementRectangle { get => (Rect)this.GetValue(PlacementRectangleProperty); set => this.SetValue(PlacementRectangleProperty, value); } /// <summary> /// Gets or sets <see cref="PlacementOptions"/> property of the <see cref="BalloonBase"/>. /// </summary> public PlacementOptions PlacementOptions { get => (PlacementOptions)this.GetValue(PlacementOptionsProperty); set => this.SetValue(PlacementOptionsProperty, value); } /// <summary> /// Gets the <see cref="Geometry"/> that defines the balloon. /// </summary> protected override Geometry DefiningGeometry => this.BoxGeometry ?? Geometry.Empty; /// <summary> /// Gets the <see cref="Geometry"/> that defines the connector. /// </summary> protected Geometry? ConnectorGeometry { get; private set; } /// <summary> /// Gets the <see cref="Geometry"/> that defines the box. /// </summary> protected Geometry? BoxGeometry { get; private set; } /// <inheritdoc /> protected override Size MeasureOverride(Size constraint) { return new Size(this.StrokeThickness, this.StrokeThickness); } /// <inheritdoc /> protected override Size ArrangeOverride(Size finalSize) { if (finalSize.Width > this.StrokeThickness && finalSize.Height > this.StrokeThickness) { finalSize = new Size(finalSize.Width - this.StrokeThickness, finalSize.Height - this.StrokeThickness); } return finalSize; } /// <inheritdoc /> protected override void OnRender(DrawingContext drawingContext) { if (drawingContext is null) { throw new ArgumentNullException(nameof(drawingContext)); } var pen = this.penCache.GetPen(this.Stroke, this.StrokeThickness); drawingContext.DrawGeometry(this.Fill, pen, this.balloonGeometry); } /// <inheritdoc /> protected override void OnRenderSizeChanged(SizeChangedInfo sizeInfo) { base.OnRenderSizeChanged(sizeInfo); this.UpdateConnectorOffset(); this.UpdateCachedGeometries(); this.InvalidateVisual(); } /// <summary> /// Updates <see cref="BoxGeometry"/> and <see cref="ConnectorGeometry"/>. /// </summary> protected virtual void UpdateCachedGeometries() { if (this.RenderSize == Size.Empty) { if (this.BoxGeometry != null) { BindingOperations.ClearAllBindings(this.BoxGeometry); } this.BoxGeometry = Geometry.Empty; if (this.ConnectorGeometry != null) { BindingOperations.ClearAllBindings(this.ConnectorGeometry); } this.ConnectorGeometry = Geometry.Empty; this.balloonGeometry = Geometry.Empty; return; } var boxGeometry = this.GetOrCreateBoxGeometry(this.RenderSize); var connectorGeometry = this.CanCreateConnectorGeometry() ? this.GetOrCreateConnectorGeometry(this.RenderSize) : Geometry.Empty; if (ReferenceEquals(boxGeometry, this.BoxGeometry) && ReferenceEquals(connectorGeometry, this.ConnectorGeometry)) { return; } if (this.BoxGeometry != null && !ReferenceEquals(boxGeometry, this.BoxGeometry)) { BindingOperations.ClearAllBindings(this.BoxGeometry); } this.BoxGeometry = boxGeometry; if (this.ConnectorGeometry != null && !ReferenceEquals(connectorGeometry, this.ConnectorGeometry)) { BindingOperations.ClearAllBindings(this.ConnectorGeometry); } this.ConnectorGeometry = connectorGeometry; this.balloonGeometry = this.CreateGeometry(this.BoxGeometry, this.ConnectorGeometry); } /// <summary> /// Check if connector c an be created. /// </summary> /// <returns>True if conditions are satisfied.</returns> protected bool CanCreateConnectorGeometry() { return this.ConnectorOffset != default && this.RenderSize.Width > 0 && this.RenderSize.Height > 0; } /// <summary> /// Get or create the box geometry. /// </summary> /// <param name="renderSize">The <see cref="Size"/>.</param> /// <returns>The <see cref="Geometry"/>.</returns> protected abstract Geometry GetOrCreateBoxGeometry(Size renderSize); /// <summary> /// Get or create the connector geometry. /// </summary> /// <param name="renderSize">The <see cref="Size"/>.</param> /// <returns>The <see cref="Geometry"/>.</returns> protected abstract Geometry GetOrCreateConnectorGeometry(Size renderSize); /// <summary> /// Get or create the geometry. /// </summary> /// <param name="box">The box <see cref="Geometry"/>.</param> /// <param name="connector">The connector <see cref="Geometry"/>.</param> /// <returns>The <see cref="Geometry"/>.</returns> protected virtual Geometry CreateGeometry(Geometry box, Geometry connector) { return new CombinedGeometry(GeometryCombineMode.Union, box, connector); } /// <summary> /// Update the connector offset. /// </summary> protected virtual void UpdateConnectorOffset() { var hasTarget = this.PlacementTarget?.IsVisible == true || !this.PlacementRectangle.IsEmpty; if (this.IsVisible && this.RenderSize.Width > 0 && hasTarget) { if (!this.IsLoaded) { #pragma warning disable VSTHRD001 // Avoid legacy thread switching APIs _ = this.Dispatcher.BeginInvoke(new Action(this.UpdateConnectorOffset), DispatcherPriority.Loaded); #pragma warning restore VSTHRD001 // Avoid legacy thread switching APIs return; } var selfRect = new Rect(new Point(0, 0).ToScreen(this), this.RenderSize).ToScreen(this); var targetRect = this.GetTargetRect(); var tp = this.PlacementOptions?.GetPointOnTarget(selfRect, targetRect); if (tp is null || selfRect.Contains(tp.Value)) { this.InvalidateProperty(ConnectorOffsetProperty); return; } var mp = selfRect.CenterPoint(); var ip = new Line(mp, tp.Value).ClosestIntersection(selfRect); Debug.Assert(ip != null, "Did not find an intersection, bug in the library"); //// ReSharper disable once ConditionIsAlwaysTrueOrFalse I think we want it weird like this. if (ip is null) { // failing silently in release this.InvalidateProperty(ConnectorOffsetProperty); } else { var v = tp.Value - ip.Value; //// ReSharper disable once CompareOfFloatsByEqualityOperator if (this.PlacementOptions != null && v.Length > 0 && this.PlacementOptions.Offset != 0) { v -= this.PlacementOptions.Offset * v.Normalized(); } this.SetCurrentValue(ConnectorOffsetProperty, v); } } else { this.InvalidateProperty(ConnectorOffsetProperty); } } /// <summary> /// Called when properties causing layout update changes. /// </summary> /// <param name="sender">The <see cref="BalloonBase"/> that the change happened on.</param> /// <param name="e">The <see cref="EventArgs"/>.</param> #pragma warning disable CA2109 // Review visible event handlers protected virtual void OnLayoutUpdated(object? sender, EventArgs e) #pragma warning restore CA2109 // Review visible event handlers { this.UpdateConnectorOffset(); } /// <summary> /// Gets <see cref="PlacementTarget"/> if set or GetVisualParent(). /// </summary> /// <returns>The target <see cref="UIElement"/>.</returns> protected virtual UIElement? GetTarget() { return this.PlacementTarget ?? this.GetVisualParent(); } /// <summary> /// Get the target <see cref="Rect"/>. /// </summary> /// <returns>The <see cref="Rect"/>.</returns> protected virtual Rect GetTargetRect() { var targetRect = Rect.Empty; if (this.PlacementRectangle.IsEmpty && this.PlacementTarget is { } placementTarget) { targetRect = new Rect(new Point(0, 0).ToScreen(placementTarget), placementTarget.RenderSize).ToScreen(this); } else { var target = this.GetTarget(); if (target != null) { targetRect = this.PlacementRectangle.ToScreen(target).ToScreen(this); } } return targetRect; } private static void OnConnectorChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var balloon = (BalloonBase)d; if (balloon.IsInitialized) { balloon.UpdateCachedGeometries(); } } private static void OnPlacementTargetChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var balloon = (BalloonBase)d; balloon.UpdateConnectorOffset(); // unsubscribing and subscribing here to have only one subscription balloon.LayoutUpdated -= balloon.OnLayoutUpdated; balloon.LayoutUpdated += balloon.OnLayoutUpdated; if (e.OldValue is UIElement oldTarget) { WeakEventManager<UIElement, EventArgs>.RemoveHandler(oldTarget, nameof(LayoutUpdated), balloon.OnLayoutUpdated); } if (e.NewValue is UIElement newTarget) { WeakEventManager<UIElement, EventArgs>.AddHandler(newTarget, nameof(LayoutUpdated), balloon.OnLayoutUpdated); } } private class PenCache { private Brush? cachedBrush; private double cachedStrokeThickness; private Pen? pen; internal Pen GetPen(Brush brush, double strokeThickness) { // ReSharper disable once CompareOfFloatsByEqualityOperator if (Equals(this.cachedBrush, brush) && this.cachedStrokeThickness == strokeThickness) { return this.pen ?? throw new InvalidOperationException("Failed getting pen."); } this.cachedBrush = brush; this.cachedStrokeThickness = strokeThickness; this.pen = new Pen(brush, strokeThickness); return this.pen; } } } }
//----------------------------------------------------------------------------- // Copyright (c) 2012 GarageGames, LLC // // 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. //----------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Sounds //-------------------------------------------------------------------------- // Added for Lesson 5 - Adding Weapons - 23 Sep 11 datablock SFXProfile(WeaponTemplateFireSound) { filename = "art/sound/weapons/wpn_fire"; description = AudioClose3D; preload = true; }; datablock SFXProfile(WeaponTemplateReloadSound) { filename = "art/sound/weapons/wpn_reload"; description = AudioClose3D; preload = true; }; datablock SFXProfile(WeaponTemplateSwitchinSound) { filename = "art/sound/weapons/wpn_switchin"; description = AudioClose3D; preload = true; }; datablock SFXProfile(WeaponTemplateIdleSound) { filename = "art/sound/weapons/wpn_idle"; description = AudioClose3D; preload = true; }; datablock SFXProfile(WeaponTemplateGrenadeSound) { filename = "art/sound/weapons/wpn_grenadelaunch"; description = AudioClose3D; preload = true; }; datablock SFXProfile(WeaponTemplateMineSwitchinSound) { filename = "art/sound/weapons/wpn_mine_switchin"; description = AudioClose3D; preload = true; }; //----------------------------------------------------------------------------- // Added 28 Sep 11 datablock LightDescription( BulletProjectileLightDesc ) { color = "0.0 0.5 0.7"; range = 3.0; }; datablock ProjectileData( BulletProjectile ) { projectileShapeName = ""; directDamage = 5; radiusDamage = 0; damageRadius = 0.5; areaImpulse = 0.5; impactForce = 1; explosion = BulletDirtExplosion; decal = BulletHoleDecal; muzzleVelocity = 120; velInheritFactor = 1; armingDelay = 0; lifetime = 992; fadeDelay = 1472; bounceElasticity = 0; bounceFriction = 0; isBallistic = false; gravityMod = 1; }; function BulletProjectile::onCollision(%this,%obj,%col,%fade,%pos,%normal) { // Apply impact force from the projectile. // Apply damage to the object all shape base objects if ( %col.getType() & $TypeMasks::GameBaseObjectType ) %col.damage(%obj,%pos,%this.directDamage,"BulletProjectile"); } //----------------------------------------------------------------------------- datablock ProjectileData( WeaponTemplateProjectile ) { projectileShapeName = ""; directDamage = 5; radiusDamage = 0; damageRadius = 0.5; areaImpulse = 0.5; impactForce = 1; muzzleVelocity = 120; velInheritFactor = 1; armingDelay = 0; lifetime = 992; fadeDelay = 1472; bounceElasticity = 0; bounceFriction = 0; isBallistic = false; gravityMod = 1; }; function WeaponTemplateProjectile::onCollision(%this,%obj,%col,%fade,%pos,%normal) { // Apply impact force from the projectile. // Apply damage to the object all shape base objects if ( %col.getType() & $TypeMasks::GameBaseObjectType ) %col.damage(%obj,%pos,%this.directDamage,"WeaponTemplateProjectile"); } //----------------------------------------------------------------------------- // Ammo Item //----------------------------------------------------------------------------- datablock ItemData(WeaponTemplateAmmo) { // Mission editor category category = "Ammo"; // Add the Ammo namespace as a parent. The ammo namespace provides // common ammo related functions and hooks into the inventory system. className = "Ammo"; // Basic Item properties shapeFile = ""; mass = 1; elasticity = 0.2; friction = 0.6; // Dynamic properties defined by the scripts pickUpName = ""; maxInventory = 1000; }; //-------------------------------------------------------------------------- // Weapon Item. This is the item that exists in the world, i.e. when it's // been dropped, thrown or is acting as re-spawnable item. When the weapon // is mounted onto a shape, the NewWeaponTemplate is used. //----------------------------------------------------------------------------- datablock ItemData(WeaponTemplateItem) { // Mission editor category category = "Weapon"; // Hook into Item Weapon class hierarchy. The weapon namespace // provides common weapon handling functions in addition to hooks // into the inventory system. className = "Weapon"; // Basic Item properties shapeFile = ""; mass = 1; elasticity = 0.2; friction = 0.6; emap = true; // Dynamic properties defined by the scripts pickUpName = "A basic weapon"; description = "Weapon"; image = WeaponTemplateImage; reticle = "crossHair"; }; datablock ShapeBaseImageData(WeaponTemplateImage) { // FP refers to first person specific features // Defines what art file to use. shapeFile = "art/shapes/weapons/Lurker/TP_Lurker.DAE"; shapeFileFP = "art/shapes/weapons/Lurker/FP_Lurker.DAE"; // Whether or not to enable environment mapping //emap = true; //imageAnimPrefixFP = ""; // Specify mount point & offset for 3rd person, and eye offset // for first person rendering. mountPoint = 0; //firstPerson = true; //eyeOffset = "0.001 -0.05 -0.065"; // When firing from a point offset from the eye, muzzle correction // will adjust the muzzle vector to point to the eye LOS point. // Since this weapon doesn't actually fire from the muzzle point, // we need to turn this off. //correctMuzzleVector = true; // Add the WeaponImage namespace as a parent, WeaponImage namespace // provides some hooks into the inventory system. class = "WeaponImage"; className = "WeaponImage"; // Projectiles and Ammo. item = WeaponTemplateItem; ammo = WeaponTemplateAmmo; //projectile = BulletProjectile; //projectileType = Projectile; //projectileSpread = "0.005"; // Properties associated with the shell casing that gets ejected during firing //casing = BulletShell; //shellExitDir = "1.0 0.3 1.0"; //shellExitOffset = "0.15 -0.56 -0.1"; //shellExitVariance = 15.0; //shellVelocity = 3.0; // Properties associated with a light that occurs when the weapon fires //lightType = ""; //lightColor = "0.992126 0.968504 0.708661 1"; //lightRadius = "4"; //lightDuration = "100"; //lightBrightness = 2; // Properties associated with shaking the camera during firing //shakeCamera = false; //camShakeFreq = "0 0 0"; //camShakeAmp = "0 0 0"; // Images have a state system which controls how the animations // are run, which sounds are played, script callbacks, etc. This // state system is downloaded to the client so that clients can // predict state changes and animate accordingly. The following // system supports basic ready->fire->reload transitions as // well as a no-ammo->dryfire idle state. // If true, allow multiple timeout transitions to occur within a single tick // useful if states have a very small timeout //useRemainderDT = true; // Initial start up state stateName[0] = "Preactivate"; stateTransitionOnLoaded[0] = "Activate"; stateTransitionOnNoAmmo[0] = "NoAmmo"; // Activating the gun. Called when the weapon is first // mounted and there is ammo. stateName[1] = "Activate"; stateTransitionGeneric0In[1] = "SprintEnter"; stateTransitionOnTimeout[1] = "Ready"; stateTimeoutValue[1] = 0.5; stateSequence[1] = "switch_in"; // Ready to fire, just waiting for the trigger stateName[2] = "Ready"; stateTransitionGeneric0In[2] = "SprintEnter"; stateTransitionOnMotion[2] = "ReadyMotion"; stateTransitionOnTimeout[2] = "ReadyFidget"; stateTimeoutValue[2] = 10; stateWaitForTimeout[2] = false; stateScaleAnimation[2] = false; stateScaleAnimationFP[2] = false; stateTransitionOnNoAmmo[2] = "NoAmmo"; stateTransitionOnTriggerDown[2] = "Fire"; stateSequence[2] = "idle"; // Same as Ready state but plays a fidget sequence stateName[3] = "ReadyFidget"; stateTransitionGeneric0In[3] = "SprintEnter"; stateTransitionOnMotion[3] = "ReadyMotion"; stateTransitionOnTimeout[3] = "Ready"; stateTimeoutValue[3] = 6; stateWaitForTimeout[3] = false; stateTransitionOnNoAmmo[3] = "NoAmmo"; stateTransitionOnTriggerDown[3] = "Fire"; stateSequence[3] = "idle_fidget1"; // Ready to fire with player moving stateName[4] = "ReadyMotion"; stateTransitionGeneric0In[4] = "SprintEnter"; stateTransitionOnNoMotion[4] = "Ready"; stateWaitForTimeout[4] = false; stateScaleAnimation[4] = false; stateScaleAnimationFP[4] = false; stateSequenceTransitionIn[4] = true; stateSequenceTransitionOut[4] = true; stateTransitionOnNoAmmo[4] = "NoAmmo"; stateTransitionOnTriggerDown[4] = "Fire"; stateSequence[4] = "run"; // Fire the weapon. Calls the fire script which does // the actual work. stateName[5] = "Fire"; stateTransitionGeneric0In[5] = "SprintEnter"; stateTransitionOnTimeout[5] = "Reload"; stateTimeoutValue[5] = 0.15; stateFire[5] = true; stateRecoil[5] = ""; stateAllowImageChange[5] = false; stateSequence[5] = "fire"; stateScaleAnimation[5] = false; stateSequenceNeverTransition[5] = true; stateSequenceRandomFlash[5] = true; // use muzzle flash sequence stateScript[5] = "onFire"; stateSound[5] = WeaponTemplateFireSound; stateEmitter[5] = GunFireSmokeEmitter; stateEmitterTime[5] = 0.025; // Play the reload animation, and transition into stateName[6] = "Reload"; stateTransitionGeneric0In[6] = "SprintEnter"; stateTransitionOnNoAmmo[6] = "NoAmmo"; stateTransitionOnTimeout[6] = "Ready"; stateWaitForTimeout[6] = "0"; stateTimeoutValue[6] = 0.05; stateAllowImageChange[6] = false; //stateSequence[6] = "reload"; stateEjectShell[6] = true; // No ammo in the weapon, just idle until something // shows up. Play the dry fire sound if the trigger is // pulled. stateName[7] = "NoAmmo"; stateTransitionGeneric0In[7] = "SprintEnter"; stateTransitionOnAmmo[7] = "ReloadClip"; stateScript[7] = "onClipEmpty"; // No ammo dry fire stateName[8] = "DryFire"; stateTransitionGeneric0In[8] = "SprintEnter"; stateTimeoutValue[8] = 1.0; stateTransitionOnTimeout[8] = "NoAmmo"; stateScript[8] = "onDryFire"; // Play the reload clip animation stateName[9] = "ReloadClip"; stateTransitionGeneric0In[9] = "SprintEnter"; stateTransitionOnTimeout[9] = "Ready"; stateWaitForTimeout[9] = true; stateTimeoutValue[9] = 3.0; stateReload[9] = true; stateSequence[9] = "reload"; stateShapeSequence[9] = "Reload"; stateScaleShapeSequence[9] = true; // Start Sprinting stateName[10] = "SprintEnter"; stateTransitionGeneric0Out[10] = "SprintExit"; stateTransitionOnTimeout[10] = "Sprinting"; stateWaitForTimeout[10] = false; stateTimeoutValue[10] = 0.5; stateWaitForTimeout[10] = false; stateScaleAnimation[10] = false; stateScaleAnimationFP[10] = false; stateSequenceTransitionIn[10] = true; stateSequenceTransitionOut[10] = true; stateAllowImageChange[10] = false; stateSequence[10] = "sprint"; // Sprinting stateName[11] = "Sprinting"; stateTransitionGeneric0Out[11] = "SprintExit"; stateWaitForTimeout[11] = false; stateScaleAnimation[11] = false; stateScaleAnimationFP[11] = false; stateSequenceTransitionIn[11] = true; stateSequenceTransitionOut[11] = true; stateAllowImageChange[11] = false; stateSequence[11] = "sprint"; // Stop Sprinting stateName[12] = "SprintExit"; stateTransitionGeneric0In[12] = "SprintEnter"; stateTransitionOnTimeout[12] = "Ready"; stateWaitForTimeout[12] = false; stateTimeoutValue[12] = 0.5; stateSequenceTransitionIn[12] = true; stateSequenceTransitionOut[12] = true; stateAllowImageChange[12] = false; stateSequence[12] = "sprint"; };
// 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. // ------------------------------------------------------------------------------ // Changes to this file must follow the http://aka.ms/api-review process. // ------------------------------------------------------------------------------ namespace System { public readonly ref struct ReadOnlySpan<T> { public static ReadOnlySpan<T> Empty { get { throw null; } } public ReadOnlySpan(T[] array) { throw null;} public ReadOnlySpan(T[] array, int start, int length) { throw null;} public unsafe ReadOnlySpan(void* pointer, int length) { throw null;} public bool IsEmpty { get { throw null; } } public T this[int index] { get { throw null; }} public int Length { get { throw null; } } public void CopyTo(Span<T> destination) { } [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static ReadOnlySpan<T> DangerousCreate(object obj, ref T objectData, int length) { throw null; } [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public ref T DangerousGetPinnableReference() { throw null; } #pragma warning disable 0809 //warning CS0809: Obsolete member 'Span<T>.Equals(object)' overrides non-obsolete member 'object.Equals(object)' [System.ObsoleteAttribute("Equals() on ReadOnlySpan will always throw an exception. Use == instead.")] [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ObsoleteAttribute("GetHashCode() on ReadOnlySpan will always throw an exception.")] [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } #pragma warning restore 0809 public static bool operator ==(ReadOnlySpan<T> left, ReadOnlySpan<T> right) { throw null; } public static implicit operator ReadOnlySpan<T> (T[] array) { throw null; } public static implicit operator ReadOnlySpan<T> (ArraySegment<T> arraySegment) { throw null; } public static bool operator !=(ReadOnlySpan<T> left, ReadOnlySpan<T> right) { throw null; } public ReadOnlySpan<T> Slice(int start) { throw null; } public ReadOnlySpan<T> Slice(int start, int length) { throw null; } public T[] ToArray() { throw null; } public bool TryCopyTo(Span<T> destination) { throw null; } } public readonly ref struct Span<T> { public static Span<T> Empty { get { throw null; } } public Span(T[] array) { throw null;} public Span(T[] array, int start, int length) { throw null;} public unsafe Span(void* pointer, int length) { throw null;} public bool IsEmpty { get { throw null; } } public ref T this[int index] { get { throw null; } } public int Length { get { throw null; } } public void Clear() { } public void Fill(T value) { } public void CopyTo(Span<T> destination) { } [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static Span<T> DangerousCreate(object obj, ref T objectData, int length) { throw null; } [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public ref T DangerousGetPinnableReference() { throw null; } #pragma warning disable 0809 //warning CS0809: Obsolete member 'Span<T>.Equals(object)' overrides non-obsolete member 'object.Equals(object)' [System.ObsoleteAttribute("Equals() on Span will always throw an exception. Use == instead.")] [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ObsoleteAttribute("GetHashCode() on Span will always throw an exception.")] [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } #pragma warning restore 0809 public static bool operator ==(Span<T> left, Span<T> right) { throw null; } public static implicit operator Span<T> (T[] array) { throw null; } public static implicit operator Span<T> (ArraySegment<T> arraySegment) { throw null; } public static implicit operator ReadOnlySpan<T> (Span<T> span) { throw null; } public static bool operator !=(Span<T> left, Span<T> right) { throw null; } public Span<T> Slice(int start) { throw null; } public Span<T> Slice(int start, int length) { throw null; } public T[] ToArray() { throw null; } public bool TryCopyTo(Span<T> destination) { throw null; } } public static class SpanExtensions { public static int IndexOf<T>(this Span<T> span, T value) where T:struct, IEquatable<T> { throw null; } public static int IndexOf<T>(this Span<T> span, ReadOnlySpan<T> value) where T : struct, IEquatable<T> { throw null; } public static int IndexOf(this Span<byte> span, byte value) { throw null; } public static int IndexOf(this Span<byte> span, ReadOnlySpan<byte> value) { throw null; } public static int IndexOfAny(this Span<byte> span, byte value0, byte value1) { throw null; } public static int IndexOfAny(this Span<byte> span, byte value0, byte value1, byte value2) { throw null; } public static int IndexOfAny(this Span<byte> span, ReadOnlySpan<byte> values) { throw null; } public static bool SequenceEqual<T>(this Span<T> first, ReadOnlySpan<T> second) where T:struct, IEquatable<T> { throw null; } public static bool SequenceEqual(this Span<byte> first, ReadOnlySpan<byte> second) { throw null; } public static bool StartsWith<T>(this Span<T> span, ReadOnlySpan<T> value) where T : struct, IEquatable<T> { throw null; } public static bool StartsWith(this Span<byte> span, ReadOnlySpan<byte> value) { throw null; } public static Span<byte> AsBytes<T>(this Span<T> source) where T : struct { throw null; } public static Span<TTo> NonPortableCast<TFrom, TTo>(this Span<TFrom> source) where TFrom : struct where TTo : struct { throw null; } public static ReadOnlySpan<char> AsReadOnlySpan(this string text) { throw null; } public static Span<T> AsSpan<T>(this T[] array) { throw null; } public static Span<T> AsSpan<T>(this ArraySegment<T> arraySegment) { throw null; } public static ReadOnlySpan<T> AsReadOnlySpan<T>(this T[] array) { throw null; } public static ReadOnlySpan<T> AsReadOnlySpan<T>(this ArraySegment<T> arraySegment) { throw null; } public static void CopyTo<T>(this T[] array, Span<T> destination) { throw null; } public static int IndexOf<T>(this ReadOnlySpan<T> span, T value) where T : struct, IEquatable<T> { throw null; } public static int IndexOf<T>(this ReadOnlySpan<T> span, ReadOnlySpan<T> value) where T : struct, IEquatable<T> { throw null; } public static int IndexOf(this ReadOnlySpan<byte> span, byte value) { throw null; } public static int IndexOf(this ReadOnlySpan<byte> span, ReadOnlySpan<byte> value) { throw null; } public static int IndexOfAny(this ReadOnlySpan<byte> span, byte value0, byte value1) { throw null; } public static int IndexOfAny(this ReadOnlySpan<byte> span, byte value0, byte value1, byte value2) { throw null; } public static int IndexOfAny(this ReadOnlySpan<byte> span, ReadOnlySpan<byte> values) { throw null; } public static bool SequenceEqual<T>(this ReadOnlySpan<T> first, ReadOnlySpan<T> second) where T : struct, IEquatable<T> { throw null; } public static bool SequenceEqual(this ReadOnlySpan<byte> first, ReadOnlySpan<byte> second) { throw null; } public static bool StartsWith<T>(this ReadOnlySpan<T> span, ReadOnlySpan<T> value) where T : struct, IEquatable<T> { throw null; } public static bool StartsWith(this ReadOnlySpan<byte> span, ReadOnlySpan<byte> value) { throw null; } public static ReadOnlySpan<byte> AsBytes<T>(this ReadOnlySpan<T> source) where T : struct { throw null; } public static ReadOnlySpan<TTo> NonPortableCast<TFrom, TTo>(this ReadOnlySpan<TFrom> source) where TFrom : struct where TTo : struct { throw null; } } public readonly struct ReadOnlyMemory<T> { public static ReadOnlyMemory<T> Empty { get { throw null; } } public ReadOnlyMemory(T[] array) { throw null;} public ReadOnlyMemory(T[] array, int start, int length) { throw null;} internal ReadOnlyMemory(Buffers.OwnedMemory<T> owner, int index, int length) { throw null;} public bool IsEmpty { get { throw null; } } public int Length { get { throw null; } } [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } public bool Equals(ReadOnlyMemory<T> other) { throw null; } [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } public static implicit operator ReadOnlyMemory<T>(T[] array) { throw null; } public static implicit operator ReadOnlyMemory<T>(ArraySegment<T> arraySegment) { throw null; } public ReadOnlyMemory<T> Slice(int start) { throw null; } public ReadOnlyMemory<T> Slice(int start, int length) { throw null; } public ReadOnlySpan<T> Span { get { throw null; } } public unsafe Buffers.MemoryHandle Retain(bool pin = false) { throw null; } public T[] ToArray() { throw null; } [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public bool DangerousTryGetArray(out ArraySegment<T> arraySegment) { throw null; } } public readonly struct Memory<T> { public static Memory<T> Empty { get { throw null; } } public Memory(T[] array) { throw null;} public Memory(T[] array, int start, int length) { throw null;} internal Memory(Buffers.OwnedMemory<T> owner, int index, int length) { throw null;} public bool IsEmpty { get { throw null; } } public int Length { get { throw null; } } [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } public bool Equals(Memory<T> other) { throw null; } [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } public static implicit operator Memory<T>(T[] array) { throw null; } public static implicit operator Memory<T>(ArraySegment<T> arraySegment) { throw null; } public static implicit operator ReadOnlyMemory<T>(Memory<T> memory) { throw null; } public Memory<T> Slice(int start) { throw null; } public Memory<T> Slice(int start, int length) { throw null; } public Span<T> Span { get { throw null; } } public unsafe Buffers.MemoryHandle Retain(bool pin = false) { throw null; } public T[] ToArray() { throw null; } public bool TryGetArray(out ArraySegment<T> arraySegment) { throw null; } } } namespace System.Buffers { public unsafe struct MemoryHandle : IDisposable { public MemoryHandle(IRetainable owner, void* pinnedPointer = null, System.Runtime.InteropServices.GCHandle handle = default(System.Runtime.InteropServices.GCHandle)) { throw null; } public void* PinnedPointer { get { throw null; } } internal void AddOffset(int offset) { throw null; } public void Dispose() { throw null; } } public interface IRetainable { bool Release(); void Retain(); } public abstract class OwnedMemory<T> : IDisposable, IRetainable { public Memory<T> Memory { get { throw null; } } public abstract bool IsDisposed { get; } protected abstract bool IsRetained { get; } public abstract int Length { get; } public abstract Span<T> Span { get; } public void Dispose() { throw null; } protected abstract void Dispose(bool disposing); public abstract MemoryHandle Pin(); public abstract bool Release(); public abstract void Retain(); protected internal abstract bool TryGetArray(out ArraySegment<T> arraySegment); } }
// Copyright (c) Microsoft Corporation. All rights reserved. // // Licensed under the MIT License. See LICENSE.txt in the project root for license information. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text.RegularExpressions; using System.Xml.Linq; namespace exportsample { class ProjectProcessor { public static XNamespace NS = "http://schemas.microsoft.com/developer/msbuild/2003"; public Dictionary<string, string> FilesToCopy = new Dictionary<string, string>(); public bool ReferencesWin2DNuGetPackage { get; private set; } string fileName; public string SourceDirectory { get; private set; } public string DestinationDirectory { get; private set; } string relativePackagesDirectory; Configuration config; SampleDirectory sample; XDocument doc; public static ProjectProcessor Export(string projectFileName, Configuration config, SampleDirectory sample, string destination) { var project = new ProjectProcessor(projectFileName, config, sample); project.Process(); project.Save(destination); return project; } ProjectProcessor(string projectFileName, Configuration config, SampleDirectory sample) { this.fileName = projectFileName; this.SourceDirectory = Path.GetDirectoryName(fileName); this.DestinationDirectory = config.GetDestination(SourceDirectory); this.config = config; this.sample = sample; var relativeSolutionDirectory = GetRelativePath(sample.Destination + "\\", DestinationDirectory); this.relativePackagesDirectory = Path.Combine(relativeSolutionDirectory, "packages\\"); doc = XDocument.Load(projectFileName); } public void Save(string dest) { Directory.CreateDirectory(Path.GetDirectoryName(dest)); doc.Save(dest); } // Pull out a list of names of projects that are imported by this project public List<string> FindImportedProjectsThatNeedExporting() { var imports = doc.Descendants(NS + "Import"); List<string> importPaths = new List<string>(); foreach (var import in imports) { var importPath = import.Attribute("Project").Value; importPath = Expand(importPath); // After we've expanded variables we know about, anything that still starts with a $ we leave unmodified if (!importPath.StartsWith("$")) { // Everything else we convert into a full path importPath = Path.GetFullPath(Path.Combine(SourceDirectory, importPath)); } if (config.ShouldExport(importPath)) importPaths.Add(importPath); } return importPaths; } public static bool IsValidPathName(string includeFile) { return !Path.GetInvalidPathChars().Any(includeFile.Contains); } // Expand variables we know about string Expand(string path) { path = path.Replace("$(MSBuildThisFileDirectory)", SourceDirectory + "\\"); foreach (var property in config.Properties) { string prop = string.Format("$({0})", property.Key); path = path.Replace(prop, property.Value); } return path; } void Process() { ProcessInlineImports(); ProcessFileReferences(); RelocateNuGetReferences(); ConvertWin2DProjectReferences(); } #region Inline Imports void ProcessInlineImports() { while (ProcessNextInlinedImport()) ; } bool ProcessNextInlinedImport() { var imports = doc.Descendants(NS + "Import"); foreach (var import in imports) { var importPath = import.Attribute("Project").Value; var inlineImport = config.FindInlineImportFor(importPath); if (inlineImport != null) { DoInlineImport(import, inlineImport); return true; } } return false; } void DoInlineImport(XElement import, InlineImport inlineImport) { var importPath = ExpandPath(SourceDirectory, import.Attribute("Project").Value); var inlinedDoc = XDocument.Load(importPath); RelocateImports(Path.GetDirectoryName(importPath), inlinedDoc); var project = inlinedDoc.Root; List<XNode> filteredNodes = new List<XNode>(); bool inSample = true; foreach (var node in project.Nodes()) { if (node is XComment) { var comment = (XComment)node; if (comment.Value.Contains("[[NOT IN SAMPLE]]")) { inSample = false; continue; } else if (comment.Value.Contains("[[IN SAMPLE]]")) { inSample = true; continue; } } if (inSample) filteredNodes.Add(node); } import.AddBeforeSelf(filteredNodes); if (inlineImport.Elements.Count > 0) { import.AddBeforeSelf(inlineImport.Elements); } import.Remove(); } void RelocateImports(string directory, XDocument doc) { foreach (var import in doc.Descendants(NS + "Import")) { import.SetAttributeValue("Project", ExpandPath(directory, import.Attribute("Project").Value)); } } #endregion #region File References const string MSBuildThisFileDirectory = "$(MSBuildThisFileDirectory)"; void ProcessFileReferences() { foreach (var element in doc.Descendants()) { var includeAttribute = element.Attribute("Include"); if (includeAttribute == null) continue; includeAttribute.Value = ProcessFileReference(includeAttribute.Value); } foreach (var propertyThatIsFileReference in config.FileReferenceProperties) { foreach (var element in doc.Descendants(NS + propertyThatIsFileReference)) { element.Value = ProcessFileReference(element.Value); } } } string ProcessFileReference(string originalValue) { string includedFile = originalValue; // If this is a reference in a Shared project then it'll start with $(MSBuildThisFileDirectory). // Strip this off while we're looking at this. if (includedFile.StartsWith(MSBuildThisFileDirectory)) { includedFile = includedFile.Substring(MSBuildThisFileDirectory.Length); } // Expand properties (eg $(AssetDir)) includedFile = Expand(includedFile); // Ignore anything that isn't a valid path name if (!IsValidPathName(includedFile)) return originalValue; // Ignore anything that doesn't exist var fullPath = Path.GetFullPath(Path.Combine(SourceDirectory, includedFile)); if (!File.Exists(fullPath)) return originalValue; // If the file is part of this sample then we can reference it unmodified if (fullPath.StartsWith(sample.Source)) { var dest = config.GetDestination(fullPath); FilesToCopy.Add(fullPath, dest); return originalValue; } // Otherwise we'll need to copy it somewhere to reference it, and update our element to point to the new location foreach (var entry in config.DuplicateDirectories) { if (fullPath.StartsWith(entry.Key)) { var dest = fullPath.Replace(entry.Key, Path.Combine(sample.Destination, entry.Value)); FilesToCopy[fullPath] = dest; return GetRelativePath(dest, DestinationDirectory); } } return originalValue; } #endregion #region Relocate NuGet References void RelocateNuGetReferences() { // When projects have existing nuget references these need to be updated to be relative to // the packages directory that'll be in the sample's directory. // // We can identify these by things that reference "\packages\". NuGet adds Import, Error // and HintPath elements that might reference these. RelocateNuGetReferences(doc.Descendants(NS + "Import")); RelocateNuGetReferences(doc.Descendants(NS + "Error")); RelocateNuGetReferences(doc.Descendants(NS + "HintPath")); } static Regex packagesRegex = new Regex(@"[.\\]*\\packages\\"); void RelocateNuGetReferences(IEnumerable<XElement> elements) { foreach (var element in elements) { if (element.Value.Length > 0) element.Value = RelocateNuGetReference(relativePackagesDirectory, element.Value); foreach (var attribute in element.Attributes()) { attribute.Value = RelocateNuGetReference(relativePackagesDirectory, attribute.Value); } } } private static string RelocateNuGetReference(string relativePackagesDirectory, string reference) { var match = packagesRegex.Match(reference); if (match.Success) { return packagesRegex.Replace(reference, relativePackagesDirectory); } else { return reference; } } #endregion #region Convert Win2D project references to NuGet package references void ConvertWin2DProjectReferences() { ReferencesWin2DNuGetPackage = FindAndRemoveWin2DProjectReferences(); if (ReferencesWin2DNuGetPackage) AddWin2DNuGetPackage(); } bool FindAndRemoveWin2DProjectReferences() { bool foundAReference = false; var toRemove = new List<XElement>(); foreach (var reference in doc.Descendants(NS + "ProjectReference")) { if (config.IsWin2DProject(reference.Attribute("Include").Value)) { toRemove.Add(reference); foundAReference = true; } } toRemove.ForEach(RemoveElementAndParentIfEmpty); if (RemoveExistingReferencesToWin2DNuGet()) foundAReference = true; return foundAReference; } bool RemoveExistingReferencesToWin2DNuGet() { var elementsToRemove = new List<XElement>(); elementsToRemove.AddRange(from element in doc.Descendants(NS + "Import") where element.Attribute("Project").Value.Contains("packages\\Win2D") select element); elementsToRemove.AddRange(from element in doc.Descendants(NS + "Reference") where element.Attribute("Include").Value.Contains("Microsoft.Graphics.Canvas") select element); elementsToRemove.AddRange(from element in doc.Descendants(NS + "Error") where element.Attribute("Condition").Value.Contains("packages\\Win2D") select element); if (elementsToRemove.Count == 0) return false; elementsToRemove.ForEach(RemoveElementAndParentIfEmpty); return true; } void AddWin2DNuGetPackage() { var framework = GetFramework(); string importsDir = Path.Combine(Win2DPackagePath, "build", framework); var propsImport = Path.Combine(importsDir, "Win2D.props"); var targetsImport = Path.Combine(importsDir, "Win2D.targets"); doc.Root.AddFirst(MakeImportElement(propsImport)); // Targets is added after last element (rather than the last node) so that it appears before // any comments at the end of the project. doc.Root.Elements().Last().AddAfterSelf(MakeImportElement(targetsImport)); var importsTarget = GetEnsureNuGetPackageBuildImportsTarget(); importsTarget.Add(MakeCheckImport(propsImport)); importsTarget.Add(MakeCheckImport(targetsImport)); } public string GetFramework() { // C++ projects are always native if (fileName.EndsWith("vcxproj")) return "native"; // Otherwise we need to look at TargetPlatformIdentifier var targetPlatformIdentifier = doc.Descendants(NS + "TargetPlatformIdentifier").FirstOrDefault(); // No platform == windows if (targetPlatformIdentifier == null) return "win"; switch (targetPlatformIdentifier.Value) { case "Windows": return "win"; case "WindowsPhoneApp": return "wpa"; case "UAP": // Since NuGet currently doesn't know about UAP as a framwork moniker, // the nuget package uses 'win'. // // When NuGet learns about UAP, and the Win2D package has been updated accordingly, // this will need to be changed. return "win"; } throw new Exception("Unabled to determine NuGet framework for " + fileName); } XElement MakeImportElement(string filename) { var importElement = new XElement(NS + "Import"); importElement.SetAttributeValue("Project", filename); importElement.SetAttributeValue("Condition", "Exists('" + filename + "')"); return importElement; } string Win2DPackagePath { get { return Path.Combine(relativePackagesDirectory, "Win2D." + config.Options.Win2DVersion); } } Regex nugetTargetsFile = new Regex(@"packages\\.*\.targets$"); XElement GetEnsureNuGetPackageBuildImportsTarget() { // Look for an existing one... var targets = from element in doc.Descendants(NS + "Target") where element.Attribute("Name").Value == "EnsureNuGetPackageBuildImports" select element; var target = targets.FirstOrDefault(); if (target != null) return target; // There isn't an existing one, so we create one... var ensureImports = new XElement(NS + "Target"); ensureImports.SetAttributeValue("Name", "EnsureNuGetPackageBuildImports"); ensureImports.SetAttributeValue("BeforeTargets", "PrepareForBuild"); var propertyGroup = new XElement(NS + "PropertyGroup"); var errorText = new XElement(NS + "ErrorText"); errorText.Value = "This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}."; propertyGroup.Add(errorText); ensureImports.Add(propertyGroup); var targetsImports = from element in doc.Descendants(NS + "Import") where nugetTargetsFile.IsMatch(element.Attribute("Project").Value) select element; var firstImportTarget = targetsImports.First(); // if there isn't an import target then something strange is going on! firstImportTarget.AddBeforeSelf(ensureImports); return ensureImports; } XElement MakeCheckImport(string filename) { var element = new XElement(NS + "Error"); element.SetAttributeValue("Condition", string.Format("!Exists('{0}')", filename)); element.SetAttributeValue("Text", string.Format("$([System.String]::Format('$(ErrorText)', '{0}'))", filename)); return element; } #endregion #region Utils string ExpandPath(string root, string path) { string expandedPath = Expand(path); if (!IsValidPathName(expandedPath)) throw new Exception(string.Format("Couldn't expand path {0}", path)); return Path.GetFullPath(Path.Combine(root, expandedPath)); } // From http://stackoverflow.com/a/703292/157728 static string GetRelativePath(string filespec, string folder) { Uri pathUri = new Uri(filespec); // Folders must end in a slash if (!folder.EndsWith(Path.DirectorySeparatorChar.ToString())) { folder += Path.DirectorySeparatorChar; } Uri folderUri = new Uri(folder); return Uri.UnescapeDataString(folderUri.MakeRelativeUri(pathUri).ToString().Replace('/', Path.DirectorySeparatorChar)); } static void RemoveElementAndParentIfEmpty(XElement element) { var parent = element.Parent; element.Remove(); if (parent.IsEmpty) parent.Remove(); } #endregion } }
// 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.Collections.ObjectModel; using System.Globalization; using System.Linq; using System.Runtime.CompilerServices; using System.Threading; using System.Windows.Threading; using System.Xml.Linq; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.Extensions; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.VisualBasic; using Microsoft.VisualStudio.Composition; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Utilities; using Roslyn.Test.EditorUtilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces { public partial class TestWorkspaceFactory { /// <summary> /// This place-holder value is used to set a project's file path to be null. It was explicitly chosen to be /// convoluted to avoid any accidental usage (e.g., what if I really wanted FilePath to be the string "null"?), /// obvious to anybody debugging that it is a special value, and invalid as an actual file path. /// </summary> public const string NullFilePath = "NullFilePath::{AFA13775-BB7D-4020-9E58-C68CF43D8A68}"; private class TestDocumentationProvider : DocumentationProvider { protected override string GetDocumentationForSymbol(string documentationMemberID, CultureInfo preferredCulture, CancellationToken cancellationToken = default(CancellationToken)) { return string.Format("<member name='{0}'><summary>{0}</summary></member>", documentationMemberID); } public override bool Equals(object obj) { return ReferenceEquals(this, obj); } public override int GetHashCode() { return RuntimeHelpers.GetHashCode(this); } } public static TestWorkspace CreateWorkspace(string xmlDefinition, bool completed = true, bool openDocuments = true, ExportProvider exportProvider = null) { return CreateWorkspace(XElement.Parse(xmlDefinition), completed, openDocuments, exportProvider); } public static TestWorkspace CreateWorkspace( XElement workspaceElement, bool completed = true, bool openDocuments = true, ExportProvider exportProvider = null, string workspaceKind = null) { SynchronizationContext.SetSynchronizationContext(new DispatcherSynchronizationContext()); if (workspaceElement.Name != WorkspaceElementName) { throw new ArgumentException(); } exportProvider = exportProvider ?? TestExportProvider.ExportProviderWithCSharpAndVisualBasic; var workspace = new TestWorkspace(exportProvider, workspaceKind); var projectMap = new Dictionary<string, TestHostProject>(); var documentElementToFilePath = new Dictionary<XElement, string>(); var projectElementToAssemblyName = new Dictionary<XElement, string>(); var filePathToTextBufferMap = new Dictionary<string, ITextBuffer>(); int projectIdentifier = 0; int documentIdentifier = 0; foreach (var projectElement in workspaceElement.Elements(ProjectElementName)) { var project = CreateProject( workspaceElement, projectElement, exportProvider, workspace, projectElementToAssemblyName, documentElementToFilePath, filePathToTextBufferMap, ref projectIdentifier, ref documentIdentifier); Assert.False(projectMap.ContainsKey(project.AssemblyName)); projectMap.Add(project.AssemblyName, project); workspace.Projects.Add(project); } var documentFilePaths = new HashSet<string>(); foreach (var project in projectMap.Values) { foreach (var document in project.Documents) { Assert.True(document.IsLinkFile || documentFilePaths.Add(document.FilePath)); } } var submissions = CreateSubmissions(workspace, workspaceElement.Elements(SubmissionElementName), exportProvider); foreach (var submission in submissions) { projectMap.Add(submission.AssemblyName, submission); } var solution = new TestHostSolution(projectMap.Values.ToArray()); workspace.AddTestSolution(solution); foreach (var projectElement in workspaceElement.Elements(ProjectElementName)) { foreach (var projectReference in projectElement.Elements(ProjectReferenceElementName)) { var fromName = projectElementToAssemblyName[projectElement]; var toName = projectReference.Value; var fromProject = projectMap[fromName]; var toProject = projectMap[toName]; var aliases = projectReference.Attributes(AliasAttributeName).Select(a => a.Value).ToImmutableArray(); workspace.OnProjectReferenceAdded(fromProject.Id, new ProjectReference(toProject.Id, aliases.Any() ? aliases : default(ImmutableArray<string>))); } } for (int i = 1; i < submissions.Count; i++) { for (int j = i - 1; j >= 0; j--) { if (submissions[j].CompilationOptions != null) { workspace.OnProjectReferenceAdded(submissions[i].Id, new ProjectReference(submissions[j].Id)); break; } } } foreach (var project in projectMap.Values) { foreach (var document in project.Documents) { if (openDocuments) { workspace.OnDocumentOpened(document.Id, document.GetOpenTextContainer(), isCurrentContext: !document.IsLinkFile); } workspace.Documents.Add(document); } } return workspace; } private static IList<TestHostProject> CreateSubmissions( TestWorkspace workspace, IEnumerable<XElement> submissionElements, ExportProvider exportProvider) { var submissions = new List<TestHostProject>(); var submissionIndex = 0; foreach (var submissionElement in submissionElements) { var submissionName = "Submission" + (submissionIndex++); var languageName = GetLanguage(workspace, submissionElement); // The document var markupCode = submissionElement.NormalizedValue(); string code; int? cursorPosition; IDictionary<string, IList<TextSpan>> spans; MarkupTestFile.GetPositionAndSpans(markupCode, out code, out cursorPosition, out spans); var languageServices = workspace.Services.GetLanguageServices(languageName); var contentTypeLanguageService = languageServices.GetService<IContentTypeLanguageService>(); var contentType = contentTypeLanguageService.GetDefaultContentType(); var textBuffer = EditorFactory.CreateBuffer(contentType.TypeName, exportProvider, code); // The project var document = new TestHostDocument(exportProvider, languageServices, textBuffer, submissionName, cursorPosition, spans, SourceCodeKind.Interactive); var documents = new List<TestHostDocument> { document }; if (languageName == NoCompilationConstants.LanguageName) { submissions.Add( new TestHostProject( languageServices, compilationOptions: null, parseOptions: null, assemblyName: submissionName, references: null, documents: documents, isSubmission: true)); continue; } var syntaxFactory = languageServices.GetService<ISyntaxTreeFactoryService>(); var compilationFactory = languageServices.GetService<ICompilationFactoryService>(); var compilationOptions = compilationFactory.GetDefaultCompilationOptions().WithOutputKind(OutputKind.DynamicallyLinkedLibrary); var parseOptions = syntaxFactory.GetDefaultParseOptions().WithKind(SourceCodeKind.Interactive); var references = CreateCommonReferences(workspace, submissionElement); var project = new TestHostProject( languageServices, compilationOptions, parseOptions, submissionName, references, documents, isSubmission: true); submissions.Add(project); } return submissions; } private static TestHostProject CreateProject( XElement workspaceElement, XElement projectElement, ExportProvider exportProvider, TestWorkspace workspace, Dictionary<XElement, string> projectElementToAssemblyName, Dictionary<XElement, string> documentElementToFilePath, Dictionary<string, ITextBuffer> filePathToTextBufferMap, ref int projectId, ref int documentId) { var language = GetLanguage(workspace, projectElement); var assemblyName = GetAssemblyName(workspace, projectElement, ref projectId); projectElementToAssemblyName.Add(projectElement, assemblyName); string filePath; if (projectElement.Attribute(FilePathAttributeName) != null) { filePath = projectElement.Attribute(FilePathAttributeName).Value; if (string.Compare(filePath, NullFilePath, StringComparison.Ordinal) == 0) { // allow explicit null file path filePath = null; } } else { filePath = assemblyName + (language == LanguageNames.CSharp ? ".csproj" : language == LanguageNames.VisualBasic ? ".vbproj" : ("." + language)); } var contentTypeRegistryService = exportProvider.GetExportedValue<IContentTypeRegistryService>(); var languageServices = workspace.Services.GetLanguageServices(language); var compilationOptions = CreateCompilationOptions(workspace, projectElement, language); var parseOptions = GetParseOptions(projectElement, language, languageServices); var references = CreateReferenceList(workspace, projectElement); var analyzers = CreateAnalyzerList(workspace, projectElement); var documents = new List<TestHostDocument>(); var documentElements = projectElement.Elements(DocumentElementName).ToList(); foreach (var documentElement in documentElements) { var document = CreateDocument( workspace, workspaceElement, documentElement, language, exportProvider, languageServices, filePathToTextBufferMap, ref documentId); documents.Add(document); documentElementToFilePath.Add(documentElement, document.FilePath); } return new TestHostProject(languageServices, compilationOptions, parseOptions, assemblyName, references, documents, filePath: filePath, analyzerReferences: analyzers); } private static ParseOptions GetParseOptions(XElement projectElement, string language, HostLanguageServices languageServices) { return language == LanguageNames.CSharp || language == LanguageNames.VisualBasic ? GetParseOptionsWorker(projectElement, language, languageServices) : null; } private static ParseOptions GetParseOptionsWorker(XElement projectElement, string language, HostLanguageServices languageServices) { ParseOptions parseOptions; var preprocessorSymbolsAttribute = projectElement.Attribute(PreprocessorSymbolsAttributeName); if (preprocessorSymbolsAttribute != null) { parseOptions = GetPreProcessorParseOptions(language, preprocessorSymbolsAttribute); } else { parseOptions = languageServices.GetService<ISyntaxTreeFactoryService>().GetDefaultParseOptions(); } var languageVersionAttribute = projectElement.Attribute(LanguageVersionAttributeName); if (languageVersionAttribute != null) { parseOptions = GetParseOptionsWithLanguageVersion(language, parseOptions, languageVersionAttribute); } var documentationMode = GetDocumentationMode(projectElement); if (documentationMode != null) { parseOptions = parseOptions.WithDocumentationMode(documentationMode.Value); } return parseOptions; } private static ParseOptions GetPreProcessorParseOptions(string language, XAttribute preprocessorSymbolsAttribute) { if (language == LanguageNames.CSharp) { return new CSharpParseOptions(preprocessorSymbols: preprocessorSymbolsAttribute.Value.Split(',')); } else if (language == LanguageNames.VisualBasic) { return new VisualBasicParseOptions(preprocessorSymbols: preprocessorSymbolsAttribute.Value .Split(',').Select(v => KeyValuePair.Create(v.Split('=').ElementAt(0), (object)v.Split('=').ElementAt(1))).ToImmutableArray()); } else { throw new ArgumentException("Unexpected language '{0}' for generating custom parse options.", language); } } private static ParseOptions GetParseOptionsWithLanguageVersion(string language, ParseOptions parseOptions, XAttribute languageVersionAttribute) { if (language == LanguageNames.CSharp) { var languageVersion = (CodeAnalysis.CSharp.LanguageVersion)Enum.Parse(typeof(CodeAnalysis.CSharp.LanguageVersion), languageVersionAttribute.Value); parseOptions = ((CSharpParseOptions)parseOptions).WithLanguageVersion(languageVersion); } else if (language == LanguageNames.VisualBasic) { var languageVersion = (CodeAnalysis.VisualBasic.LanguageVersion)Enum.Parse(typeof(CodeAnalysis.VisualBasic.LanguageVersion), languageVersionAttribute.Value); parseOptions = ((VisualBasicParseOptions)parseOptions).WithLanguageVersion(languageVersion); } return parseOptions; } private static DocumentationMode? GetDocumentationMode(XElement projectElement) { var documentationModeAttribute = projectElement.Attribute(DocumentationModeAttributeName); if (documentationModeAttribute != null) { return (DocumentationMode)Enum.Parse(typeof(DocumentationMode), documentationModeAttribute.Value); } else { return null; } } private static string GetAssemblyName(TestWorkspace workspace, XElement projectElement, ref int projectId) { var assemblyNameAttribute = projectElement.Attribute(AssemblyNameAttributeName); if (assemblyNameAttribute != null) { return assemblyNameAttribute.Value; } var language = GetLanguage(workspace, projectElement); projectId++; return language == LanguageNames.CSharp ? "CSharpAssembly" + projectId : language == LanguageNames.VisualBasic ? "VisualBasicAssembly" + projectId : language + "Assembly" + projectId; } private static string GetLanguage(TestWorkspace workspace, XElement projectElement) { string languageName = projectElement.Attribute(LanguageAttributeName).Value; if (!workspace.Services.SupportedLanguages.Contains(languageName)) { throw new ArgumentException(string.Format("Language should be one of '{0}' and it is {1}", string.Join(", ", workspace.Services.SupportedLanguages), languageName)); } return languageName; } private static CompilationOptions CreateCompilationOptions( TestWorkspace workspace, XElement projectElement, string language) { var compilationOptionsElement = projectElement.Element(CompilationOptionsElementName); return language == LanguageNames.CSharp || language == LanguageNames.VisualBasic ? CreateCompilationOptions(workspace, language, compilationOptionsElement) : null; } private static CompilationOptions CreateCompilationOptions(TestWorkspace workspace, string language, XElement compilationOptionsElement) { var rootNamespace = new VisualBasicCompilationOptions(OutputKind.ConsoleApplication).RootNamespace; var globalImports = new List<GlobalImport>(); var reportDiagnostic = ReportDiagnostic.Default; if (compilationOptionsElement != null) { globalImports = compilationOptionsElement.Elements(GlobalImportElementName) .Select(x => GlobalImport.Parse(x.Value)).ToList(); var rootNamespaceAttribute = compilationOptionsElement.Attribute(RootNamespaceAttributeName); if (rootNamespaceAttribute != null) { rootNamespace = rootNamespaceAttribute.Value; } var reportDiagnosticAttribute = compilationOptionsElement.Attribute(ReportDiagnosticAttributeName); if (reportDiagnosticAttribute != null) { reportDiagnostic = (ReportDiagnostic)Enum.Parse(typeof(ReportDiagnostic), (string)reportDiagnosticAttribute); } var outputTypeAttribute = compilationOptionsElement.Attribute(OutputTypeAttributeName); if (outputTypeAttribute != null && outputTypeAttribute.Value == "WindowsRuntimeMetadata") { if (rootNamespaceAttribute == null) { rootNamespace = new VisualBasicCompilationOptions(OutputKind.WindowsRuntimeMetadata).RootNamespace; } return language == LanguageNames.CSharp ? (CompilationOptions)new CodeAnalysis.CSharp.CSharpCompilationOptions(OutputKind.WindowsRuntimeMetadata) : new VisualBasicCompilationOptions(OutputKind.WindowsRuntimeMetadata).WithGlobalImports(globalImports) .WithRootNamespace(rootNamespace); } } else { // Add some common global imports by default for VB globalImports.Add(GlobalImport.Parse("System")); globalImports.Add(GlobalImport.Parse("System.Collections.Generic")); globalImports.Add(GlobalImport.Parse("System.Linq")); } // TODO: Allow these to be specified. var languageServices = workspace.Services.GetLanguageServices(language); var compilationOptions = languageServices.GetService<ICompilationFactoryService>().GetDefaultCompilationOptions(); compilationOptions = compilationOptions.WithOutputKind(OutputKind.DynamicallyLinkedLibrary) .WithGeneralDiagnosticOption(reportDiagnostic) .WithSourceReferenceResolver(SourceFileResolver.Default) .WithXmlReferenceResolver(XmlFileResolver.Default) .WithMetadataReferenceResolver(new AssemblyReferenceResolver(MetadataFileReferenceResolver.Default, MetadataFileReferenceProvider.Default)) .WithAssemblyIdentityComparer(DesktopAssemblyIdentityComparer.Default); if (language == LanguageNames.VisualBasic) { compilationOptions = ((VisualBasicCompilationOptions)compilationOptions).WithRootNamespace(rootNamespace) .WithGlobalImports(globalImports); } return compilationOptions; } private static TestHostDocument CreateDocument( TestWorkspace workspace, XElement workspaceElement, XElement documentElement, string language, ExportProvider exportProvider, HostLanguageServices languageServiceProvider, Dictionary<string, ITextBuffer> filePathToTextBufferMap, ref int documentId) { string markupCode; string filePath; var isLinkFileAttribute = documentElement.Attribute(IsLinkFileAttributeName); bool isLinkFile = isLinkFileAttribute != null && ((bool?)isLinkFileAttribute).HasValue && ((bool?)isLinkFileAttribute).Value; if (isLinkFile) { // This is a linked file. Use the filePath and markup from the referenced document. var originalProjectName = documentElement.Attribute(LinkAssemblyNameAttributeName); var originalDocumentPath = documentElement.Attribute(LinkFilePathAttributeName); if (originalProjectName == null || originalDocumentPath == null) { throw new ArgumentException("Linked file specified without LinkAssemblyName or LinkFilePath."); } var originalProjectNameStr = originalProjectName.Value; var originalDocumentPathStr = originalDocumentPath.Value; var originalProject = workspaceElement.Elements(ProjectElementName).First(p => { var assemblyName = p.Attribute(AssemblyNameAttributeName); return assemblyName != null && assemblyName.Value == originalProjectNameStr; }); if (originalProject == null) { throw new ArgumentException("Linked file's LinkAssemblyName '{0}' project not found.", originalProjectNameStr); } var originalDocument = originalProject.Elements(DocumentElementName).First(d => { var documentPath = d.Attribute(FilePathAttributeName); return documentPath != null && documentPath.Value == originalDocumentPathStr; }); if (originalDocument == null) { throw new ArgumentException("Linked file's LinkFilePath '{0}' file not found.", originalDocumentPathStr); } markupCode = originalDocument.NormalizedValue(); filePath = GetFilePath(workspace, originalDocument, ref documentId); } else { markupCode = documentElement.NormalizedValue(); filePath = GetFilePath(workspace, documentElement, ref documentId); } var folders = GetFolders(documentElement); var optionsElement = documentElement.Element(ParseOptionsElementName); // TODO: Allow these to be specified. var codeKind = SourceCodeKind.Regular; if (optionsElement != null) { var attr = optionsElement.Attribute(KindAttributeName); codeKind = attr == null ? SourceCodeKind.Regular : (SourceCodeKind)Enum.Parse(typeof(SourceCodeKind), attr.Value); } var contentTypeLanguageService = languageServiceProvider.GetService<IContentTypeLanguageService>(); var contentType = contentTypeLanguageService.GetDefaultContentType(); string code; int? cursorPosition; IDictionary<string, IList<TextSpan>> spans; MarkupTestFile.GetPositionAndSpans(markupCode, out code, out cursorPosition, out spans); // For linked files, use the same ITextBuffer for all linked documents ITextBuffer textBuffer; if (!filePathToTextBufferMap.TryGetValue(filePath, out textBuffer)) { textBuffer = EditorFactory.CreateBuffer(contentType.TypeName, exportProvider, code); filePathToTextBufferMap.Add(filePath, textBuffer); } return new TestHostDocument(exportProvider, languageServiceProvider, textBuffer, filePath, cursorPosition, spans, codeKind, folders, isLinkFile); } private static string GetFilePath( TestWorkspace workspace, XElement documentElement, ref int documentId) { var filePathAttribute = documentElement.Attribute(FilePathAttributeName); if (filePathAttribute != null) { return filePathAttribute.Value; } var language = GetLanguage(workspace, documentElement.Ancestors(ProjectElementName).Single()); documentId++; var name = "Test" + documentId; return language == LanguageNames.CSharp ? name + ".cs" : name + ".vb"; } private static IReadOnlyList<string> GetFolders(XElement documentElement) { var folderAttribute = documentElement.Attribute(FoldersAttributeName); if (folderAttribute == null) { return null; } var folderContainers = folderAttribute.Value.Split(new[] { '\\' }, StringSplitOptions.RemoveEmptyEntries); return new ReadOnlyCollection<string>(folderContainers.ToList()); } /// <summary> /// Takes completely valid code, compiles it, and emits it to a MetadataReference without using /// the file system /// </summary> private static MetadataReference CreateMetadataReferenceFromSource(TestWorkspace workspace, XElement referencedSource) { var compilation = CreateCompilation(workspace, referencedSource); var aliasElement = referencedSource.Attribute("Aliases") != null ? referencedSource.Attribute("Aliases").Value : null; var aliases = aliasElement != null ? aliasElement.Split(',').Select(s => s.Trim()).ToImmutableArray() : default(ImmutableArray<string>); bool includeXmlDocComments = false; var includeXmlDocCommentsAttribute = referencedSource.Attribute(IncludeXmlDocCommentsAttributeName); if (includeXmlDocCommentsAttribute != null && ((bool?)includeXmlDocCommentsAttribute).HasValue && ((bool?)includeXmlDocCommentsAttribute).Value) { includeXmlDocComments = true; } return MetadataReference.CreateFromImage(compilation.EmitToArray(), new MetadataReferenceProperties(aliases: aliases), includeXmlDocComments ? new DeferredDocumentationProvider(compilation) : null); } private static Compilation CreateCompilation(TestWorkspace workspace, XElement referencedSource) { string languageName = GetLanguage(workspace, referencedSource); string assemblyName = "ReferencedAssembly"; var assemblyNameAttribute = referencedSource.Attribute(AssemblyNameAttributeName); if (assemblyNameAttribute != null) { assemblyName = assemblyNameAttribute.Value; } var languageServices = workspace.Services.GetLanguageServices(languageName); var compilationFactory = languageServices.GetService<ICompilationFactoryService>(); var options = compilationFactory.GetDefaultCompilationOptions().WithOutputKind(OutputKind.DynamicallyLinkedLibrary); var compilation = compilationFactory.CreateCompilation(assemblyName, options); var documentElements = referencedSource.Elements(DocumentElementName).ToList(); foreach (var documentElement in documentElements) { compilation = compilation.AddSyntaxTrees(CreateSyntaxTree(languageName, documentElement.Value)); } foreach (var reference in CreateReferenceList(workspace, referencedSource)) { compilation = compilation.AddReferences(reference); } return compilation; } private static SyntaxTree CreateSyntaxTree(string languageName, string referencedCode) { if (LanguageNames.CSharp == languageName) { return Microsoft.CodeAnalysis.CSharp.SyntaxFactory.ParseSyntaxTree(referencedCode); } else { return Microsoft.CodeAnalysis.VisualBasic.SyntaxFactory.ParseSyntaxTree(referencedCode); } } private static IList<MetadataReference> CreateReferenceList(TestWorkspace workspace, XElement element) { var references = CreateCommonReferences(workspace, element); foreach (var reference in element.Elements(MetadataReferenceElementName)) { references.Add(MetadataReference.CreateFromFile(reference.Value)); } foreach (var metadataReferenceFromSource in element.Elements(MetadataReferenceFromSourceElementName)) { references.Add(CreateMetadataReferenceFromSource(workspace, metadataReferenceFromSource)); } return references; } private static IList<AnalyzerReference> CreateAnalyzerList(TestWorkspace workspace, XElement projectElement) { var analyzers = new List<AnalyzerReference>(); foreach (var analyzer in projectElement.Elements(AnalyzerElementName)) { analyzers.Add( new AnalyzerImageReference( ImmutableArray<DiagnosticAnalyzer>.Empty, display: (string)analyzer.Attribute(AnalyzerDisplayAttributeName), fullPath: (string)analyzer.Attribute(AnalyzerFullPathAttributeName))); } return analyzers; } private static IList<MetadataReference> CreateCommonReferences(TestWorkspace workspace, XElement element) { var references = new List<MetadataReference>(); var net45 = element.Attribute(CommonReferencesNet45AttributeName); if (net45 != null && ((bool?)net45).HasValue && ((bool?)net45).Value) { references = new List<MetadataReference> { TestBase.MscorlibRef_v4_0_30316_17626, TestBase.SystemRef_v4_0_30319_17929, TestBase.SystemCoreRef_v4_0_30319_17929 }; if (GetLanguage(workspace, element) == LanguageNames.VisualBasic) { references.Add(TestBase.MsvbRef); references.Add(TestBase.SystemXmlRef); references.Add(TestBase.SystemXmlLinqRef); } } var commonReferencesAttribute = element.Attribute(CommonReferencesAttributeName); if (commonReferencesAttribute != null && ((bool?)commonReferencesAttribute).HasValue && ((bool?)commonReferencesAttribute).Value) { references = new List<MetadataReference> { TestBase.MscorlibRef_v4_0_30316_17626, TestBase.SystemRef_v4_0_30319_17929, TestBase.SystemCoreRef_v4_0_30319_17929 }; if (GetLanguage(workspace, element) == LanguageNames.VisualBasic) { references.Add(TestBase.MsvbRef_v4_0_30319_17929); references.Add(TestBase.SystemXmlRef); references.Add(TestBase.SystemXmlLinqRef); } } var winRT = element.Attribute(CommonReferencesWinRTAttributeName); if (winRT != null && ((bool?)winRT).HasValue && ((bool?)winRT).Value) { references = new List<MetadataReference>(TestBase.WinRtRefs.Length); references.AddRange(TestBase.WinRtRefs); if (GetLanguage(workspace, element) == LanguageNames.VisualBasic) { references.Add(TestBase.MsvbRef_v4_0_30319_17929); references.Add(TestBase.SystemXmlRef); references.Add(TestBase.SystemXmlLinqRef); } } var portable = element.Attribute(CommonReferencesPortableAttributeName); if (portable != null && ((bool?)portable).HasValue && ((bool?)portable).Value) { references = new List<MetadataReference>(TestBase.PortableRefsMinimal.Length); references.AddRange(TestBase.PortableRefsMinimal); } var systemRuntimeFacade = element.Attribute(CommonReferenceFacadeSystemRuntimeAttributeName); if (systemRuntimeFacade != null && ((bool?)systemRuntimeFacade).HasValue && ((bool?)systemRuntimeFacade).Value) { references.Add(TestBase.SystemRuntimeFacadeRef); } return references; } } }
//------------------------------------------------------------------------------ // <copyright file="ListControl.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.Globalization; using System.Web; using System.Web.UI; using System.Web.UI.Adapters; using System.Web.Util; using System.Drawing; using System.Drawing.Design; /// <devdoc> /// <para>An abstract base class. Defines the common /// properties, methods, and events for all list-type controls.</para> /// </devdoc> [ ControlValueProperty("SelectedValue"), DataBindingHandler("System.Web.UI.Design.WebControls.ListControlDataBindingHandler, " + AssemblyRef.SystemDesign), DefaultEvent("SelectedIndexChanged"), ParseChildren(true, "Items"), Designer("System.Web.UI.Design.WebControls.ListControlDesigner, " + AssemblyRef.SystemDesign) ] public abstract class ListControl : DataBoundControl, IEditableTextControl { private static readonly object EventSelectedIndexChanged = new object(); private static readonly object EventTextChanged = new object(); private ListItemCollection items; private int cachedSelectedIndex; private string cachedSelectedValue; private ArrayList cachedSelectedIndices; private bool _stateLoaded; private bool _asyncSelectPending; /// <devdoc> /// <para>Initializes a new instance of the <see cref='System.Web.UI.WebControls.ListControl'/> class.</para> /// </devdoc> public ListControl() { cachedSelectedIndex = -1; } /// <devdoc> /// <para> Gets or sets a value /// indicating whether databound items will be added to the list of staticly-declared /// items in the list.</para> /// </devdoc> [ DefaultValue(false), Themeable(false), WebCategory("Behavior"), WebSysDescription(SR.ListControl_AppendDataBoundItems), ] public virtual bool AppendDataBoundItems { get { object o = ViewState["AppendDataBoundItems"]; if (o != null) { return (bool)o; } return false; } set { ViewState["AppendDataBoundItems"] = value; if (Initialized) { RequiresDataBinding = true; } } } /// <devdoc> /// <para> Gets or sets a value /// indicating whether an automatic postback to the server will occur whenever the /// user changes the selection of the list.</para> /// </devdoc> [ DefaultValue(false), WebCategory("Behavior"), WebSysDescription(SR.ListControl_AutoPostBack), Themeable(false), ] public virtual bool AutoPostBack { get { object b = ViewState["AutoPostBack"]; return((b == null) ? false : (bool)b); } set { ViewState["AutoPostBack"] = value; } } [ DefaultValue(false), Themeable(false), WebCategory("Behavior"), WebSysDescription(SR.AutoPostBackControl_CausesValidation) ] public virtual bool CausesValidation { get { object b = ViewState["CausesValidation"]; return((b == null) ? false : (bool)b); } set { ViewState["CausesValidation"] = value; } } /// <devdoc> /// <para> Indicates the field of the /// data source that provides the text content of the list items.</para> /// </devdoc> [ DefaultValue(""), Themeable(false), WebCategory("Data"), WebSysDescription(SR.ListControl_DataTextField) ] public virtual string DataTextField { get { object s = ViewState["DataTextField"]; return((s == null) ? String.Empty : (string)s); } set { ViewState["DataTextField"] = value; if (Initialized) { RequiresDataBinding = true; } } } /// <devdoc> /// </devdoc> [ DefaultValue(""), Themeable(false), WebCategory("Data"), WebSysDescription(SR.ListControl_DataTextFormatString) ] public virtual string DataTextFormatString { get { object s = ViewState["DataTextFormatString"]; return ((s == null) ? String.Empty : (string)s); } set { ViewState["DataTextFormatString"] = value; if (Initialized) { RequiresDataBinding = true; } } } /// <devdoc> /// <para>Indicates the field of the data source that provides the value content of the /// list items.</para> /// </devdoc> [ DefaultValue(""), Themeable(false), WebCategory("Data"), WebSysDescription(SR.ListControl_DataValueField) ] public virtual string DataValueField { get { object s = ViewState["DataValueField"]; return((s == null) ? String.Empty : (string)s); } set { ViewState["DataValueField"] = value; if (Initialized) { RequiresDataBinding = true; } } } /// <devdoc> /// <para>A protected property. Indicates if the ListControl supports multiple selections</para> /// </devdoc> internal virtual bool IsMultiSelectInternal { get { return false; } } /// <devdoc> /// <para> /// Indicates the collection of items within the list. /// This property /// is read-only.</para> /// </devdoc> [ WebCategory("Default"), DefaultValue(null), Editor("System.Web.UI.Design.WebControls.ListItemsCollectionEditor," + AssemblyRef.SystemDesign, typeof(UITypeEditor)), MergableProperty(false), WebSysDescription(SR.ListControl_Items), PersistenceMode(PersistenceMode.InnerDefaultProperty) ] public virtual ListItemCollection Items { get { if (items == null) { items = new ListItemCollection(); if (IsTrackingViewState) items.TrackViewState(); } return items; } } /// <devdoc> /// Determines whether the SelectedIndices must be stored in view state, to /// optimize the size of the saved state. /// </devdoc> internal bool SaveSelectedIndicesViewState { get { // Must be saved when // 1. There is a registered event handler for SelectedIndexChanged or TextChanged. // For our controls, we know for sure that there is no event handler registered for // SelectedIndexChanged or TextChanged so we can short-circuit that check. // 2. Control is not enabled or visible, because the browser's post data will not include this control // 3. The instance is a derived instance, which might be overriding the OnSelectedIndexChanged method // This is a bit hacky, since we have to cover all the four derived classes we have... // 4. AutoPostBack is true and Adapter doesn't support JavaScript // For ListControls to behave the same on mobile devices // that simulate AutoPostBack by rendering a command button, we need to save // state. // 5. The control is paginated. // 6. The control contains items that are disabled. The browser's post data will not // include this data for disabled items, so we need to save those selected indices. // if ((Events[EventSelectedIndexChanged] != null) || (Events[EventTextChanged] != null) || (IsEnabled == false) || (Visible == false) || (AutoPostBack == true && ((Page != null) && !Page.ClientSupportsJavaScript)) ) { return true; } foreach (ListItem item in Items) { if (item.Enabled == false) { return true; } } // Note that we added BulletedList that inherits ListControl in // Whidbey, but since it doesn't support selected index, we don't // need to check it here. Type t = this.GetType(); if ((t == typeof(DropDownList)) || (t == typeof(ListBox)) || (t == typeof(CheckBoxList)) || (t == typeof(RadioButtonList))) { return false; } return true; } } /// <devdoc> /// <para>Indicates the ordinal index of the first selected item within the /// list.</para> /// </devdoc> [ Bindable(true), Browsable(false), DefaultValue(0), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), Themeable(false), WebCategory("Behavior"), WebSysDescription(SR.WebControl_SelectedIndex), ] public virtual int SelectedIndex { get { for (int i=0; i < Items.Count; i++) { if (Items[i].Selected) return i; } return -1; } set { if (value < -1) { if (Items.Count == 0) { // VSW 540083: If there are no items, setting SelectedIndex < -1 is the same as setting it to -1. Don't throw. value = -1; } else { throw new ArgumentOutOfRangeException("value", SR.GetString(SR.ListControl_SelectionOutOfRange, ID, "SelectedIndex")); } } if ((Items.Count != 0 && value < Items.Count) || value == -1) { ClearSelection(); if (value >= 0) { Items[value].Selected = true; } } else { // if we're in a postback and our state is loaded but the selection doesn't exist in the list of items, // throw saying we couldn't find the selected item. if (_stateLoaded) { throw new ArgumentOutOfRangeException("value", SR.GetString(SR.ListControl_SelectionOutOfRange, ID, "SelectedIndex")); } } // always save the selectedindex // When we've databound, we'll have items from viewstate on the next postback. // If we don't cache the selected index and reset it after we databind again, // the selection goes away. So we always have to save the selectedIndex for restore // after databind. cachedSelectedIndex = value; } } /// <devdoc> /// <para>A protected property. Gets an array of selected /// indexes within the list. This property is read-only.</para> /// </devdoc> internal virtual ArrayList SelectedIndicesInternal { get { cachedSelectedIndices = new ArrayList(3); for (int i=0; i < Items.Count; i++) { if (Items[i].Selected) { cachedSelectedIndices.Add(i); } } return cachedSelectedIndices; } } /// <devdoc> /// <para>Indicates the first selected item within the list. /// This property is read-only.</para> /// </devdoc> [ WebCategory("Behavior"), Browsable(false), DefaultValue(null), WebSysDescription(SR.ListControl_SelectedItem), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] public virtual ListItem SelectedItem{ get { int i = SelectedIndex; return(i < 0) ? null : Items[i]; } } /// <devdoc> /// <para>Indicates the value of the first selected item within the /// list.</para> /// </devdoc> [ Bindable(true, BindingDirection.TwoWay), Browsable(false), DefaultValue(""), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), Themeable(false), WebSysDescription(SR.ListControl_SelectedValue), WebCategory("Behavior"), ] public virtual string SelectedValue { get { int i = SelectedIndex; return (i < 0) ? String.Empty : Items[i].Value; } set { if (Items.Count != 0) { // at design time, a binding on SelectedValue will be reset to the default value on OnComponentChanged if (value == null || (DesignMode && value.Length == 0)) { ClearSelection(); return; } ListItem selectItem = Items.FindByValue(value); // if we're in a postback and our state is loaded or the page isn't a postback but all persistance is loaded // but the selection doesn't exist in the list of items, // throw saying we couldn't find the selected value. bool loaded = Page != null && Page.IsPostBack && _stateLoaded; if (loaded && selectItem == null) { throw new ArgumentOutOfRangeException("value", SR.GetString(SR.ListControl_SelectionOutOfRange, ID, "SelectedValue")); } if (selectItem != null) { ClearSelection(); selectItem.Selected = true; } } // always save the selectedvalue // for later databinding in case we have viewstate items or static items cachedSelectedValue = value; } } [ Browsable(false), Themeable(false), DefaultValue(""), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), WebSysDescription(SR.ListControl_Text), WebCategory("Behavior"), ] public virtual string Text { get { return SelectedValue; } set { SelectedValue = value; } } protected override HtmlTextWriterTag TagKey { get { return HtmlTextWriterTag.Select; } } [ WebCategory("Behavior"), Themeable(false), DefaultValue(""), WebSysDescription(SR.PostBackControl_ValidationGroup) ] public virtual string ValidationGroup { get { string s = (string)ViewState["ValidationGroup"]; return((s == null) ? string.Empty : s); } set { ViewState["ValidationGroup"] = value; } } /// <devdoc> /// Occurs when the list selection is changed upon server /// postback. /// </devdoc> [ WebCategory("Action"), WebSysDescription(SR.ListControl_OnSelectedIndexChanged) ] public event EventHandler SelectedIndexChanged { add { Events.AddHandler(EventSelectedIndexChanged, value); } remove { Events.RemoveHandler(EventSelectedIndexChanged, value); } } /// <devdoc> /// <para>Occurs when the content of the text box is /// changed upon server postback.</para> /// </devdoc> [ WebCategory("Action"), WebSysDescription(SR.ListControl_TextChanged) ] public event EventHandler TextChanged { add { Events.AddHandler(EventTextChanged, value); } remove { Events.RemoveHandler(EventTextChanged, value); } } protected override void AddAttributesToRender(HtmlTextWriter writer) { // Make sure we are in a form tag with runat=server. if (Page != null) { Page.VerifyRenderingInServerForm(this); } if (IsMultiSelectInternal) { writer.AddAttribute(HtmlTextWriterAttribute.Multiple, "multiple"); } if (AutoPostBack && (Page != null) && Page.ClientSupportsJavaScript) { string onChange = null; if (HasAttributes) { onChange = Attributes["onchange"]; if (onChange != null) { onChange = Util.EnsureEndWithSemiColon(onChange); Attributes.Remove("onchange"); } } PostBackOptions options = new PostBackOptions(this, String.Empty); // ASURT 98368 // Need to merge the autopostback script with the user script if (CausesValidation) { options.PerformValidation = true; options.ValidationGroup = ValidationGroup; } if (Page.Form != null) { options.AutoPostBack = true; } onChange = Util.MergeScript(onChange, Page.ClientScript.GetPostBackEventReference(options, true)); writer.AddAttribute(HtmlTextWriterAttribute.Onchange, onChange); if (EnableLegacyRendering) { writer.AddAttribute("language", "javascript", false); } } if (Enabled && !IsEnabled & SupportsDisabledAttribute) { // We need to do the cascade effect on the server, because the browser // only renders as disabled, but doesn't disable the functionality. writer.AddAttribute(HtmlTextWriterAttribute.Disabled, "disabled"); } base.AddAttributesToRender(writer); } /// <devdoc> /// <para> Clears out the list selection and sets the /// <see cref='System.Web.UI.WebControls.ListItem.Selected'/> property /// of all items to false.</para> /// </devdoc> public virtual void ClearSelection() { for (int i=0; i < Items.Count; i++) Items[i].Selected = false; // Don't clear cachedSelectedIndices here because some databound controls (such as SiteMapPath) // call databind on all child controls when restoring from viewstate. We need to preserve the // cachedSelectedIndices and restore them again for the second databinding. } /// <internalonly/> /// <devdoc> /// Load previously saved state. /// Overridden to restore selection. /// </devdoc> protected override void LoadViewState(object savedState) { if (savedState != null) { Triplet stateTriplet = (Triplet)savedState; base.LoadViewState(stateTriplet.First); // restore state of items Items.LoadViewState(stateTriplet.Second); // restore selected indices ArrayList selectedIndices = stateTriplet.Third as ArrayList; if (selectedIndices != null) { SelectInternal(selectedIndices); } } else { base.LoadViewState(null); } _stateLoaded = true; } private void OnDataSourceViewSelectCallback(IEnumerable data) { _asyncSelectPending = false; PerformDataBinding(data); PostPerformDataBindingAction(); } protected override void OnDataBinding(EventArgs e) { base.OnDataBinding(e); DataSourceView view = GetData(); // view could be null when a user implements his own GetData(). if (null == view) { throw new InvalidOperationException(SR.GetString(SR.DataControl_ViewNotFound, ID)); } // DevDiv 1036362: enable async model binding for ListControl bool useAsyncSelect = false; if (AppSettings.EnableAsyncModelBinding) { var modelDataView = view as ModelDataSourceView; useAsyncSelect = modelDataView != null && modelDataView.IsSelectMethodAsync; } if (useAsyncSelect) { _asyncSelectPending = true; // disable post data binding action until the callback is invoked view.Select(SelectArguments, OnDataSourceViewSelectCallback); } else { IEnumerable data = view.ExecuteSelect(DataSourceSelectArguments.Empty); PerformDataBinding(data); } } internal void EnsureDataBoundInLoadPostData() { if (!SkipEnsureDataBoundInLoadPostData) { EnsureDataBound(); } } internal bool SkipEnsureDataBoundInLoadPostData { get; set; } /// <internalonly/> protected internal override void OnPreRender(EventArgs e) { base.OnPreRender(e); if (Page != null && IsEnabled) { if (AutoPostBack) { Page.RegisterPostBackScript(); Page.RegisterFocusScript(); // VSWhidbey 489577 if (CausesValidation && Page.GetValidators(ValidationGroup).Count > 0) { Page.RegisterWebFormsScript(); } } if (SaveSelectedIndicesViewState == false) { // Store a client-side array of enabled control, so we can re-enable them on // postback (in case they are disabled client-side) // Postback is needed when the SelectedIndices are not stored in view state. Page.RegisterEnabledControl(this); } } } /// <devdoc> /// <para> A protected method. Raises the /// <see langword='SelectedIndexChanged'/> event.</para> /// </devdoc> protected virtual void OnSelectedIndexChanged(EventArgs e) { EventHandler onChangeHandler = (EventHandler)Events[EventSelectedIndexChanged]; if (onChangeHandler != null) onChangeHandler(this, e); OnTextChanged(e); } protected virtual void OnTextChanged(EventArgs e) { EventHandler onChangeHandler = (EventHandler)Events[EventTextChanged]; if (onChangeHandler != null) onChangeHandler(this,e); } /// <internalonly/> /// <devdoc> /// </devdoc> protected internal override void PerformDataBinding(IEnumerable dataSource) { base.PerformDataBinding(dataSource); if (dataSource != null) { bool fieldsSpecified = false; bool formatSpecified = false; string textField = DataTextField; string valueField = DataValueField; string textFormat = DataTextFormatString; if (!AppendDataBoundItems) { Items.Clear(); } ICollection collection = dataSource as ICollection; if (collection != null) { Items.Capacity = collection.Count + Items.Count; } if ((textField.Length != 0) || (valueField.Length != 0)) { fieldsSpecified = true; } if (textFormat.Length != 0) { formatSpecified = true; } foreach (object dataItem in dataSource) { ListItem item = new ListItem(); if (fieldsSpecified) { if (textField.Length > 0) { item.Text = DataBinder.GetPropertyValue(dataItem, textField, textFormat); } if (valueField.Length > 0) { item.Value = DataBinder.GetPropertyValue(dataItem, valueField, null); } } else { if (formatSpecified) { item.Text = String.Format(CultureInfo.CurrentCulture, textFormat, dataItem); } else { item.Text = dataItem.ToString(); } item.Value = dataItem.ToString(); } Items.Add(item); } } // try to apply the cached SelectedIndex and SelectedValue now if (cachedSelectedValue != null) { int cachedSelectedValueIndex = -1; cachedSelectedValueIndex = Items.FindByValueInternal(cachedSelectedValue, true); if (-1 == cachedSelectedValueIndex) { throw new ArgumentOutOfRangeException("value", SR.GetString(SR.ListControl_SelectionOutOfRange, ID, "SelectedValue")); } if ((cachedSelectedIndex != -1) && (cachedSelectedIndex != cachedSelectedValueIndex)) { throw new ArgumentException(SR.GetString(SR.Attributes_mutually_exclusive, "SelectedIndex", "SelectedValue")); } SelectedIndex = cachedSelectedValueIndex; cachedSelectedValue = null; cachedSelectedIndex = -1; } else { if (cachedSelectedIndex != -1) { SelectedIndex = cachedSelectedIndex; cachedSelectedIndex = -1; } } } protected override void PerformSelect() { // Override PerformSelect and call OnDataBinding because in V1 OnDataBinding was the function that // performed the databind, and we need to maintain backward compat. OnDataBinding will retrieve the // data from the view synchronously and call PerformDataBinding with the data, preserving the OM. OnDataBinding(EventArgs.Empty); PostPerformDataBindingAction(); } private void PostPerformDataBindingAction() { if (_asyncSelectPending) return; RequiresDataBinding = false; MarkAsDataBound(); OnDataBound(EventArgs.Empty); } /// <devdoc> /// <para>This method is used by controls and adapters /// to render the options inside a select statement.</para> /// </devdoc> protected internal override void RenderContents(HtmlTextWriter writer) { ListItemCollection liCollection = Items; int n = liCollection.Count; if (n > 0) { bool selected = false; for (int i=0; i < n; i++) { ListItem li = liCollection[i]; if (li.Enabled == false) { // the only way to disable an item in a select // is to hide it continue; } writer.WriteBeginTag("option"); if (li.Selected) { if (selected) { VerifyMultiSelect(); } selected = true; writer.WriteAttribute("selected", "selected"); } writer.WriteAttribute("value", li.Value, true /*fEncode*/); // VSWhidbey 163920 Render expando attributes. if (li.HasAttributes) { li.Attributes.Render(writer); } if (Page != null) { Page.ClientScript.RegisterForEventValidation(UniqueID, li.Value); } writer.Write(HtmlTextWriter.TagRightChar); HttpUtility.HtmlEncode(li.Text, writer); writer.WriteEndTag("option"); writer.WriteLine(); } } } /// <internalonly/> /// <devdoc> /// </devdoc> protected override object SaveViewState() { object baseState = base.SaveViewState(); object items = Items.SaveViewState(); object selectedIndicesState = null; if (SaveSelectedIndicesViewState) { selectedIndicesState = SelectedIndicesInternal; } if (selectedIndicesState != null || items != null || baseState != null) { return new Triplet(baseState, items, selectedIndicesState); } return null; } /// <devdoc> /// Sets items within the /// list to be selected according to the specified array of indexes. /// </devdoc> internal void SelectInternal(ArrayList selectedIndices) { ClearSelection(); for (int i=0; i < selectedIndices.Count; i++) { int n = (int) selectedIndices[i]; if (n >= 0 && n < Items.Count) Items[n].Selected = true; } cachedSelectedIndices = selectedIndices; } internal static void SetControlToRepeatID(Control owner, Control controlToRepeat, int index) { string idSuffix = index.ToString(NumberFormatInfo.InvariantInfo); if (owner.EffectiveClientIDMode == ClientIDMode.Static) { if (String.IsNullOrEmpty(owner.ID)) { // When IDMode=Static but has no ID, what should the item IDs be? Reverting to AutoID behavior. controlToRepeat.ID = idSuffix; controlToRepeat.ClientIDMode = ClientIDMode.AutoID; } else { controlToRepeat.ID = owner.ID + "_" + idSuffix; controlToRepeat.ClientIDMode = ClientIDMode.Inherit; } } else { controlToRepeat.ID = idSuffix; controlToRepeat.ClientIDMode = ClientIDMode.Inherit; } } /// <devdoc> /// Sets items within the list to be selected from post data. /// The difference is that these items won't be cached and reset after a databind. /// </devdoc> protected void SetPostDataSelection(int selectedIndex) { if (Items.Count != 0) { if (selectedIndex < Items.Count) { ClearSelection(); if (selectedIndex >= 0) { Items[selectedIndex].Selected = true; } } } } /// <internalonly/> /// <devdoc> /// </devdoc> protected override void TrackViewState() { base.TrackViewState(); Items.TrackViewState(); } protected internal virtual void VerifyMultiSelect() { if (!IsMultiSelectInternal) { throw new HttpException(SR.GetString(SR.Cant_Multiselect_In_Single_Mode)); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.Xml.Serialization { using System.Configuration; using System.Reflection; using System.Reflection.Emit; using System.Collections; using System.IO; using System; using System.Text; using System.Xml; using System.Threading; using System.Security; using System.Xml.Serialization.Configuration; using System.Diagnostics; using System.Globalization; using System.Runtime.Versioning; using System.Diagnostics.CodeAnalysis; using System.Collections.Generic; using System.Xml.Extensions; using System.Linq; using System.Xml.Serialization; internal class TempAssembly { internal const string GeneratedAssemblyNamespace = "Microsoft.Xml.Serialization.GeneratedAssembly"; private Assembly _assembly = null; private XmlSerializerImplementation _contract = null; private IDictionary _writerMethods; private IDictionary _readerMethods; private TempMethodDictionary _methods; private Hashtable _assemblies = new Hashtable(); internal class TempMethod { internal MethodInfo writeMethod; internal MethodInfo readMethod; internal string name; internal string ns; internal bool isSoap; internal string methodKey; } private TempAssembly() { } internal TempAssembly(XmlMapping[] xmlMappings, Assembly assembly, XmlSerializerImplementation contract) { _assembly = assembly; InitAssemblyMethods(xmlMappings); _contract = contract; } internal TempAssembly(XmlMapping[] xmlMappings, Type[] types, string defaultNamespace, string location) { #if !FEATURE_SERIALIZATION_UAPAOT bool containsSoapMapping = false; for (int i = 0; i < xmlMappings.Length; i++) { xmlMappings[i].CheckShallow(); if (xmlMappings[i].IsSoap) { containsSoapMapping = true; } } // We will make best effort to use RefEmit for assembly generation bool fallbackToCSharpAssemblyGeneration = false; if (!containsSoapMapping && !TempAssembly.UseLegacySerializerGeneration) { try { _assembly = GenerateRefEmitAssembly(xmlMappings, types, defaultNamespace); } // Only catch and handle known failures with RefEmit catch (CodeGeneratorConversionException) { fallbackToCSharpAssemblyGeneration = true; } // Add other known exceptions here... // } else { fallbackToCSharpAssemblyGeneration = true; } if (fallbackToCSharpAssemblyGeneration) { throw new PlatformNotSupportedException("Compiling JScript/CSharp scripts is not supported"); } #endif #if DEBUG // use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe if (_assembly == null) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorDetails, "Failed to generate XmlSerializer assembly, but did not throw")); #endif InitAssemblyMethods(xmlMappings); } internal static bool UseLegacySerializerGeneration { get { return false; } } internal XmlSerializerImplementation Contract { get { if (_contract == null) { _contract = (XmlSerializerImplementation)Activator.CreateInstance(GetTypeFromAssembly(_assembly, "XmlSerializerContract")); } return _contract; } } internal void InitAssemblyMethods(XmlMapping[] xmlMappings) { _methods = new TempMethodDictionary(); for (int i = 0; i < xmlMappings.Length; i++) { TempMethod method = new TempMethod(); method.isSoap = xmlMappings[i].IsSoap; method.methodKey = xmlMappings[i].Key; XmlTypeMapping xmlTypeMapping = xmlMappings[i] as XmlTypeMapping; if (xmlTypeMapping != null) { method.name = xmlTypeMapping.ElementName; method.ns = xmlTypeMapping.Namespace; } _methods.Add(xmlMappings[i].Key, method); } } /// <devdoc> /// <para> /// Attempts to load pre-generated serialization assembly. /// First check for the [XmlSerializerAssembly] attribute /// </para> /// </devdoc> // SxS: This method does not take any resource name and does not expose any resources to the caller. // It's OK to suppress the SxS warning. internal static Assembly LoadGeneratedAssembly(Type type, string defaultNamespace, out XmlSerializerImplementation contract) { Assembly serializer = null; contract = null; string serializerName = null; // check to see if we loading explicit pre-generated assembly object[] attrs = type.GetCustomAttributes(typeof(System.Xml.Serialization.XmlSerializerAssemblyAttribute), false); if (attrs.Length == 0) { // Guess serializer name: if parent assembly signed use strong name AssemblyName name = type.Assembly.GetName(); serializerName = Compiler.GetTempAssemblyName(name, defaultNamespace); // use strong name name.Name = serializerName; name.CodeBase = null; name.CultureInfo = CultureInfo.InvariantCulture; string serializerPath = Path.Combine(Path.GetDirectoryName(type.Assembly.Location), serializerName + ".dll"); if (!File.Exists(serializerPath)) { serializerPath = Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), serializerName + ".dll"); } try { serializer = Assembly.LoadFile(serializerPath); } catch (Exception e) { if (e is OutOfMemoryException) { throw; } byte[] token = name.GetPublicKeyToken(); if (token != null && token.Length > 0) { // the parent assembly was signed, so do not try to LoadWithPartialName return null; } } if (serializer == null) { if (XmlSerializer.Mode == SerializationMode.PreGenOnly) { throw new Exception(SR.Format(SR.FailLoadAssemblyUnderPregenMode, serializerName)); } return null; } } else { System.Xml.Serialization.XmlSerializerAssemblyAttribute assemblyAttribute = (System.Xml.Serialization.XmlSerializerAssemblyAttribute)attrs[0]; if (assemblyAttribute.AssemblyName != null && assemblyAttribute.CodeBase != null) throw new InvalidOperationException(SR.Format(SR.XmlPregenInvalidXmlSerializerAssemblyAttribute, "AssemblyName", "CodeBase")); // found XmlSerializerAssemblyAttribute attribute, it should have all needed information to load the pre-generated serializer if (assemblyAttribute.AssemblyName != null) { serializerName = assemblyAttribute.AssemblyName; #pragma warning disable 618 serializer = Assembly.LoadWithPartialName(serializerName); #pragma warning restore 618 } else if (assemblyAttribute.CodeBase != null && assemblyAttribute.CodeBase.Length > 0) { serializerName = assemblyAttribute.CodeBase; serializer = Assembly.LoadFrom(serializerName); } else { serializerName = type.Assembly.FullName; serializer = type.Assembly; } if (serializer == null) { throw new FileNotFoundException(null, serializerName); } } Type contractType = GetTypeFromAssembly(serializer, "XmlSerializerContract"); contract = (XmlSerializerImplementation)Activator.CreateInstance(contractType); if (contract.CanSerialize(type)) return serializer; return null; } #if !FEATURE_SERIALIZATION_UAPAOT private static string GenerateAssemblyId(Type type) { Module[] modules = type.Assembly.GetModules(); var list = new ArrayList(); for (int i = 0; i < modules.Length; i++) { list.Add(modules[i].ModuleVersionId.ToString()); } list.Sort(); var sb = new StringBuilder(); for (int i = 0; i < list.Count; i++) { sb.Append(list[i].ToString()); sb.Append(","); } return sb.ToString(); } internal static bool GenerateSerializerToStream(XmlMapping[] xmlMappings, Type[] types, string defaultNamespace, Assembly assembly, Hashtable assemblies, Stream stream) { var compiler = new Compiler(); try { var scopeTable = new Hashtable(); foreach (XmlMapping mapping in xmlMappings) scopeTable[mapping.Scope] = mapping; var scopes = new TypeScope[scopeTable.Keys.Count]; scopeTable.Keys.CopyTo(scopes, 0); assemblies.Clear(); var importedTypes = new Hashtable(); foreach (TypeScope scope in scopes) { foreach (Type t in scope.Types) { compiler.AddImport(t, importedTypes); Assembly a = t.Assembly; string name = a.FullName; if (assemblies[name] != null) { continue; } if (!a.GlobalAssemblyCache) { assemblies[name] = a; } } } for (int i = 0; i < types.Length; i++) { compiler.AddImport(types[i], importedTypes); } compiler.AddImport(typeof(object).Assembly); compiler.AddImport(typeof(System.Xml.Serialization.XmlSerializer).Assembly); var writer = new IndentedWriter(compiler.Source, false); writer.WriteLine("[assembly:System.Security.AllowPartiallyTrustedCallers()]"); writer.WriteLine("[assembly:System.Security.SecurityTransparent()]"); writer.WriteLine("[assembly:System.Security.SecurityRules(System.Security.SecurityRuleSet.Level1)]"); if (assembly != null && types.Length > 0) { for (int i = 0; i < types.Length; i++) { Type type = types[i]; if (type == null) { continue; } if (DynamicAssemblies.IsTypeDynamic(type)) { throw new InvalidOperationException(SR.Format(SR.XmlPregenTypeDynamic, types[i].FullName)); } } writer.Write("[assembly:"); writer.Write(typeof(XmlSerializerVersionAttribute).FullName); writer.Write("("); writer.Write("ParentAssemblyId="); ReflectionAwareCodeGen.WriteQuotedCSharpString(writer, GenerateAssemblyId(types[0])); writer.Write(", Version="); ReflectionAwareCodeGen.WriteQuotedCSharpString(writer, ThisAssembly.Version); if (defaultNamespace != null) { writer.Write(", Namespace="); ReflectionAwareCodeGen.WriteQuotedCSharpString(writer, defaultNamespace); } writer.WriteLine(")]"); } var classes = new CodeIdentifiers(); classes.AddUnique("XmlSerializationWriter", "XmlSerializationWriter"); classes.AddUnique("XmlSerializationReader", "XmlSerializationReader"); string suffix = null; if (types != null && types.Length == 1 && types[0] != null) { suffix = CodeIdentifier.MakeValid(types[0].Name); if (types[0].IsArray) { suffix += "Array"; } } writer.WriteLine("namespace " + GeneratedAssemblyNamespace + " {"); writer.Indent++; writer.WriteLine(); string writerClass = "XmlSerializationWriter" + suffix; writerClass = classes.AddUnique(writerClass, writerClass); var writerCodeGen = new XmlSerializationWriterCodeGen(writer, scopes, "public", writerClass); writerCodeGen.GenerateBegin(); string[] writeMethodNames = new string[xmlMappings.Length]; for (int i = 0; i < xmlMappings.Length; i++) { writeMethodNames[i] = writerCodeGen.GenerateElement(xmlMappings[i]); } writerCodeGen.GenerateEnd(); writer.WriteLine(); string readerClass = "XmlSerializationReader" + suffix; readerClass = classes.AddUnique(readerClass, readerClass); var readerCodeGen = new XmlSerializationReaderCodeGen(writer, scopes, "public", readerClass); readerCodeGen.GenerateBegin(); string[] readMethodNames = new string[xmlMappings.Length]; for (int i = 0; i < xmlMappings.Length; i++) { readMethodNames[i] = readerCodeGen.GenerateElement(xmlMappings[i]); } readerCodeGen.GenerateEnd(readMethodNames, xmlMappings, types); string baseSerializer = readerCodeGen.GenerateBaseSerializer("XmlSerializer1", readerClass, writerClass, classes); var serializers = new Hashtable(); for (int i = 0; i < xmlMappings.Length; i++) { if (serializers[xmlMappings[i].Key] == null) { serializers[xmlMappings[i].Key] = readerCodeGen.GenerateTypedSerializer(readMethodNames[i], writeMethodNames[i], xmlMappings[i], classes, baseSerializer, readerClass, writerClass); } } readerCodeGen.GenerateSerializerContract("XmlSerializerContract", xmlMappings, types, readerClass, readMethodNames, writerClass, writeMethodNames, serializers); writer.Indent--; writer.WriteLine("}"); string codecontent = compiler.Source.ToString(); Byte[] info = new UTF8Encoding(true).GetBytes(codecontent); stream.Write(info, 0, info.Length); stream.Flush(); return true; } finally { compiler.Close(); } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2106:SecureAsserts", Justification = "It is safe because the serialization assembly is generated by the framework code, not by the user.")] internal static Assembly GenerateRefEmitAssembly(XmlMapping[] xmlMappings, Type[] types, string defaultNamespace) { var scopeTable = new Dictionary<TypeScope, XmlMapping>(); foreach (XmlMapping mapping in xmlMappings) scopeTable[mapping.Scope] = mapping; TypeScope[] scopes = new TypeScope[scopeTable.Keys.Count]; scopeTable.Keys.CopyTo(scopes, 0); string assemblyName = "Microsoft.GeneratedCode"; AssemblyBuilder assemblyBuilder = CodeGenerator.CreateAssemblyBuilder(assemblyName); // Add AssemblyVersion attribute to match parent assembly version if (types != null && types.Length > 0 && types[0] != null) { ConstructorInfo AssemblyVersionAttribute_ctor = typeof(AssemblyVersionAttribute).GetConstructor( new Type[] { typeof(String) } ); string assemblyVersion = types[0].Assembly.GetName().Version.ToString(); assemblyBuilder.SetCustomAttribute(new CustomAttributeBuilder(AssemblyVersionAttribute_ctor, new Object[] { assemblyVersion })); } CodeIdentifiers classes = new CodeIdentifiers(); classes.AddUnique("XmlSerializationWriter", "XmlSerializationWriter"); classes.AddUnique("XmlSerializationReader", "XmlSerializationReader"); string suffix = null; if (types != null && types.Length == 1 && types[0] != null) { suffix = CodeIdentifier.MakeValid(types[0].Name); if (types[0].IsArray) { suffix += "Array"; } } ModuleBuilder moduleBuilder = CodeGenerator.CreateModuleBuilder(assemblyBuilder, assemblyName); string writerClass = "XmlSerializationWriter" + suffix; writerClass = classes.AddUnique(writerClass, writerClass); XmlSerializationWriterILGen writerCodeGen = new XmlSerializationWriterILGen(scopes, "public", writerClass); writerCodeGen.ModuleBuilder = moduleBuilder; writerCodeGen.GenerateBegin(); string[] writeMethodNames = new string[xmlMappings.Length]; for (int i = 0; i < xmlMappings.Length; i++) { writeMethodNames[i] = writerCodeGen.GenerateElement(xmlMappings[i]); } Type writerType = writerCodeGen.GenerateEnd(); string readerClass = "XmlSerializationReader" + suffix; readerClass = classes.AddUnique(readerClass, readerClass); XmlSerializationReaderILGen readerCodeGen = new XmlSerializationReaderILGen(scopes, "public", readerClass); readerCodeGen.ModuleBuilder = moduleBuilder; readerCodeGen.CreatedTypes.Add(writerType.Name, writerType); readerCodeGen.GenerateBegin(); string[] readMethodNames = new string[xmlMappings.Length]; for (int i = 0; i < xmlMappings.Length; i++) { readMethodNames[i] = readerCodeGen.GenerateElement(xmlMappings[i]); } readerCodeGen.GenerateEnd(readMethodNames, xmlMappings, types); string baseSerializer = readerCodeGen.GenerateBaseSerializer("XmlSerializer1", readerClass, writerClass, classes); var serializers = new Dictionary<string, string>(); for (int i = 0; i < xmlMappings.Length; i++) { if (!serializers.ContainsKey(xmlMappings[i].Key)) { serializers[xmlMappings[i].Key] = readerCodeGen.GenerateTypedSerializer(readMethodNames[i], writeMethodNames[i], xmlMappings[i], classes, baseSerializer, readerClass, writerClass); } } readerCodeGen.GenerateSerializerContract("XmlSerializerContract", xmlMappings, types, readerClass, readMethodNames, writerClass, writeMethodNames, serializers); return writerType.Assembly; } #endif private static MethodInfo GetMethodFromType(Type type, string methodName) { MethodInfo method = type.GetMethod(methodName); if (method != null) return method; // Not support pregen. Workaround SecurityCritical required for assembly.CodeBase api. MissingMethodException missingMethod = new MissingMethodException(type.FullName + "::" + methodName); throw missingMethod; } internal static Type GetTypeFromAssembly(Assembly assembly, string typeName) { typeName = GeneratedAssemblyNamespace + "." + typeName; Type type = assembly.GetType(typeName); if (type == null) throw new InvalidOperationException(SR.Format(SR.XmlMissingType, typeName, assembly.FullName)); return type; } internal bool CanRead(XmlMapping mapping, XmlReader xmlReader) { if (mapping == null) return false; if (mapping.Accessor.Any) { return true; } TempMethod method = _methods[mapping.Key]; return xmlReader.IsStartElement(method.name, method.ns); } private string ValidateEncodingStyle(string encodingStyle, string methodKey) { if (encodingStyle != null && encodingStyle.Length > 0) { if (_methods[methodKey].isSoap) { if (encodingStyle != Soap.Encoding && encodingStyle != Soap12.Encoding) { throw new InvalidOperationException(SR.Format(SR.XmlInvalidEncoding3, encodingStyle, Soap.Encoding, Soap12.Encoding)); } } else { throw new InvalidOperationException(SR.Format(SR.XmlInvalidEncodingNotEncoded1, encodingStyle)); } } else { if (_methods[methodKey].isSoap) { encodingStyle = Soap.Encoding; } } return encodingStyle; } internal object InvokeReader(XmlMapping mapping, XmlReader xmlReader, XmlDeserializationEvents events, string encodingStyle) { XmlSerializationReader reader = null; try { encodingStyle = ValidateEncodingStyle(encodingStyle, mapping.Key); reader = Contract.Reader; reader.Init(xmlReader, events, encodingStyle, this); if (_methods[mapping.Key].readMethod == null) { if (_readerMethods == null) { _readerMethods = Contract.ReadMethods; } string methodName = (string)_readerMethods[mapping.Key]; if (methodName == null) { throw new InvalidOperationException(SR.Format(SR.XmlNotSerializable, mapping.Accessor.Name)); } _methods[mapping.Key].readMethod = GetMethodFromType(reader.GetType(), methodName); } return _methods[mapping.Key].readMethod.Invoke(reader, Array.Empty<object>()); } catch (SecurityException e) { throw new InvalidOperationException(SR.XmlNoPartialTrust, e); } finally { if (reader != null) reader.Dispose(); } } internal void InvokeWriter(XmlMapping mapping, XmlWriter xmlWriter, object o, XmlSerializerNamespaces namespaces, string encodingStyle, string id) { XmlSerializationWriter writer = null; try { encodingStyle = ValidateEncodingStyle(encodingStyle, mapping.Key); writer = Contract.Writer; writer.Init(xmlWriter, namespaces, encodingStyle, id, this); if (_methods[mapping.Key].writeMethod == null) { if (_writerMethods == null) { _writerMethods = Contract.WriteMethods; } string methodName = (string)_writerMethods[mapping.Key]; if (methodName == null) { throw new InvalidOperationException(SR.Format(SR.XmlNotSerializable, mapping.Accessor.Name)); } _methods[mapping.Key].writeMethod = GetMethodFromType(writer.GetType(), methodName); } _methods[mapping.Key].writeMethod.Invoke(writer, new object[] { o }); } catch (SecurityException e) { throw new InvalidOperationException(SR.XmlNoPartialTrust, e); } finally { if (writer != null) writer.Dispose(); } } internal sealed class TempMethodDictionary : Dictionary<string, TempMethod> { } } internal class TempAssemblyCacheKey { private string _ns; private object _type; internal TempAssemblyCacheKey(string ns, object type) { _type = type; _ns = ns; } public override bool Equals(object o) { TempAssemblyCacheKey key = o as TempAssemblyCacheKey; if (key == null) return false; return (key._type == _type && key._ns == _ns); } public override int GetHashCode() { return ((_ns != null ? _ns.GetHashCode() : 0) ^ (_type != null ? _type.GetHashCode() : 0)); } } internal class TempAssemblyCache { private Dictionary<TempAssemblyCacheKey, TempAssembly> _cache = new Dictionary<TempAssemblyCacheKey, TempAssembly>(); internal TempAssembly this[string ns, object o] { get { TempAssembly tempAssembly; _cache.TryGetValue(new TempAssemblyCacheKey(ns, o), out tempAssembly); return tempAssembly; } } internal void Add(string ns, object o, TempAssembly assembly) { TempAssemblyCacheKey key = new TempAssemblyCacheKey(ns, o); lock (this) { TempAssembly tempAssembly; if (_cache.TryGetValue(key, out tempAssembly) && tempAssembly == assembly) return; _cache = new Dictionary<TempAssemblyCacheKey, TempAssembly>(_cache); // clone _cache[key] = assembly; } } } internal static class ThisAssembly { internal const string Version = "1.0.0.0"; internal const string InformationalVersion = "1.0.0.0"; } }
// 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.Reflection; using System.Reflection.Emit; using System.Linq; using Xunit; namespace System.Reflection.Emit.ILGeneration.Tests { public class CustomAttributeBuilderCtor3 { private const int MinStringLength = 1; private const int MaxStringLength = 1024; private const string PropertyTestInt32Name = "TestInt32"; private const string PropertyTestStringName = "TestString"; private const string PropertyGetOnlyStringName = "GetOnlyString"; private const string PropertyGetOnlyIntName = "GetOnlyInt32"; private const string DefaultNotExistPropertyName = "DOESNOTEXIST"; private readonly RandomDataGenerator _generator = new RandomDataGenerator(); [Fact] public void PosTest1() { string testString1 = null; string testString2 = null; int testInt1 = 0; int testInt2 = 0; testString1 = "PosTest1_TestString1"; testString2 = "PosTest1_TestString2"; testInt1 = _generator.GetInt32(); testInt2 = _generator.GetInt32(); Type CustomAttributeBuilderTestType = typeof(CustomAttributeBuilderTest); Type[] ctorParams = new Type[] { typeof(string), typeof(int) }; object[] constructorArgs = new object[] { testString1, testInt1 }; PropertyInfo[] namedProperty = new PropertyInfo[] { CustomAttributeBuilderTestType.GetProperty(PropertyTestInt32Name), CustomAttributeBuilderTestType.GetProperty(PropertyTestStringName), }; object[] propertyValues = new object[] { testInt2, testString2 }; CustomAttributeBuilder cab = new CustomAttributeBuilder( CustomAttributeBuilderTestType.GetConstructor(ctorParams), constructorArgs, namedProperty, propertyValues); Assert.NotNull(cab); PropertyInfo[] verifyFields = new PropertyInfo[] { CustomAttributeBuilderTestType.GetProperty(PropertyTestInt32Name), CustomAttributeBuilderTestType.GetProperty(PropertyTestStringName), CustomAttributeBuilderTestType.GetProperty(PropertyGetOnlyStringName), CustomAttributeBuilderTestType.GetProperty(PropertyGetOnlyIntName) }; object[] verifyFieldValues = new object[] { testInt2, testString2, testString1, testInt1 }; Assert.True(VerifyCustomAttribute(cab, CustomAttributeBuilderTestType, verifyFields, verifyFieldValues)); } [Fact] public void PosTest2() { string testString1 = null; int testInt1 = 0; int testInt2 = 0; testString1 = "PosTest2_TestString1"; testInt1 = _generator.GetInt32(); testInt2 = _generator.GetInt32(); Type CustomAttributeBuilderTestType = typeof(CustomAttributeBuilderTest); Type[] ctorParams = new Type[] { typeof(string), typeof(int) }; object[] constructorArgs = new object[] { testString1, testInt1 }; PropertyInfo[] namedProperty = new PropertyInfo[] { CustomAttributeBuilderTestType.GetProperty(PropertyTestInt32Name) }; object[] propertyValues = new object[] { testInt2 }; CustomAttributeBuilder cab = new CustomAttributeBuilder( CustomAttributeBuilderTestType.GetConstructor(ctorParams), constructorArgs, namedProperty, propertyValues); Assert.NotNull(cab); PropertyInfo[] verifyFields = new PropertyInfo[] { CustomAttributeBuilderTestType.GetProperty(PropertyTestInt32Name), CustomAttributeBuilderTestType.GetProperty(PropertyTestStringName), CustomAttributeBuilderTestType.GetProperty(PropertyGetOnlyStringName), CustomAttributeBuilderTestType.GetProperty(PropertyGetOnlyIntName) }; object[] verifyFieldValues = new object[] { testInt2, null, testString1, testInt1 }; Assert.True(VerifyCustomAttribute(cab, CustomAttributeBuilderTestType, verifyFields, verifyFieldValues)); } [Fact] public void PosTest3() { string testString1 = null; int testInt1 = 0; testString1 = "PosTest3_TestString1"; testInt1 = _generator.GetInt32(); Type CustomAttributeBuilderTestType = typeof(CustomAttributeBuilderTest); Type[] ctorParams = new Type[] { typeof(string), typeof(int) }; object[] constructorArgs = new object[] { testString1, testInt1 }; PropertyInfo[] namedProperty = new PropertyInfo[] { }; object[] propertyValues = new object[] { }; CustomAttributeBuilder cab = new CustomAttributeBuilder( CustomAttributeBuilderTestType.GetConstructor(ctorParams), constructorArgs, namedProperty, propertyValues); Assert.NotNull(cab); PropertyInfo[] verifyFields = new PropertyInfo[] { CustomAttributeBuilderTestType.GetProperty(PropertyTestInt32Name), CustomAttributeBuilderTestType.GetProperty(PropertyTestStringName), CustomAttributeBuilderTestType.GetProperty(PropertyGetOnlyStringName), CustomAttributeBuilderTestType.GetProperty(PropertyGetOnlyIntName) }; object[] verifyFieldValues = new object[] { 0, null, testString1, testInt1 }; Assert.True(VerifyCustomAttribute(cab, CustomAttributeBuilderTestType, verifyFields, verifyFieldValues)); } [Fact] public void PosTest4() { Type CustomAttributeBuilderTestType = typeof(CustomAttributeBuilderTest); Type[] ctorParams = new Type[] { }; object[] constructorArgs = new object[] { }; PropertyInfo[] namedProperty = new PropertyInfo[] { }; object[] propertyValues = new object[] { }; CustomAttributeBuilder cab = new CustomAttributeBuilder( CustomAttributeBuilderTestType.GetConstructor(ctorParams), constructorArgs, namedProperty, propertyValues); Assert.NotNull(cab); PropertyInfo[] verifyFields = new PropertyInfo[] { CustomAttributeBuilderTestType.GetProperty(PropertyTestInt32Name), CustomAttributeBuilderTestType.GetProperty(PropertyTestStringName), CustomAttributeBuilderTestType.GetProperty(PropertyGetOnlyStringName), CustomAttributeBuilderTestType.GetProperty(PropertyGetOnlyIntName) }; object[] verifyFieldValues = new object[] { 0, null, null, 0 }; Assert.True(VerifyCustomAttribute(cab, CustomAttributeBuilderTestType, verifyFields, verifyFieldValues)); } [Fact] public void PosTest5() { int testInt1 = 0; testInt1 = _generator.GetInt32(); Type CustomAttributeBuilderTestType = typeof(CustomAttributeBuilderTest); Type[] ctorParams = new Type[] { }; object[] constructorArgs = new object[] { }; PropertyInfo[] namedProperty = new PropertyInfo[] { CustomAttributeBuilderTestType.GetProperty(PropertyTestInt32Name) }; object[] propertyValues = new object[] { testInt1 }; CustomAttributeBuilder cab = new CustomAttributeBuilder( CustomAttributeBuilderTestType.GetConstructor(ctorParams), constructorArgs, namedProperty, propertyValues); Assert.NotNull(cab); PropertyInfo[] verifyFields = new PropertyInfo[] { CustomAttributeBuilderTestType.GetProperty(PropertyTestInt32Name), CustomAttributeBuilderTestType.GetProperty(PropertyTestStringName), CustomAttributeBuilderTestType.GetProperty(PropertyGetOnlyStringName), CustomAttributeBuilderTestType.GetProperty(PropertyGetOnlyIntName) }; object[] verifyFieldValues = new object[] { testInt1, null, null, 0 }; Assert.True(VerifyCustomAttribute(cab, CustomAttributeBuilderTestType, verifyFields, verifyFieldValues)); } [Fact] public void PosTest6() { string testString1 = null; int testInt1 = 0; testString1 = "PosTest6_TestString1"; testInt1 = _generator.GetInt32(); Type CustomAttributeBuilderTestType = typeof(CustomAttributeBuilderTest); Type[] ctorParams = new Type[] { }; object[] constructorArgs = new object[] { }; PropertyInfo[] namedProperty = new PropertyInfo[] { CustomAttributeBuilderTestType.GetProperty(PropertyTestInt32Name), CustomAttributeBuilderTestType.GetProperty(PropertyTestStringName), }; object[] propertyValues = new object[] { testInt1, testString1 }; CustomAttributeBuilder cab = new CustomAttributeBuilder( CustomAttributeBuilderTestType.GetConstructor(ctorParams), constructorArgs, namedProperty, propertyValues); Assert.NotNull(cab); PropertyInfo[] verifyFields = new PropertyInfo[] { CustomAttributeBuilderTestType.GetProperty(PropertyTestInt32Name), CustomAttributeBuilderTestType.GetProperty(PropertyTestStringName), CustomAttributeBuilderTestType.GetProperty(PropertyGetOnlyStringName), CustomAttributeBuilderTestType.GetProperty(PropertyGetOnlyIntName) }; object[] verifyFieldValues = new object[] { testInt1, testString1, null, 0 }; Assert.True(VerifyCustomAttribute(cab, CustomAttributeBuilderTestType, verifyFields, verifyFieldValues)); } [Fact] public void PosTest7() { string testString1 = null; string testString2 = null; int testInt1 = 0; int testInt2 = 0; testString1 = "PosTest7_TestString1"; testString2 = "PosTest7_TestString2"; testInt1 = _generator.GetInt32(); testInt2 = _generator.GetInt32(); Type CustomAttributeBuilderTestType = typeof(CustomAttributeBuilderTest); Type[] ctorParams = new Type[] { typeof(string), typeof(int), typeof(string), typeof(int) }; object[] constructorArgs = new object[] { testString1, testInt1, testString1, testInt1 }; PropertyInfo[] namedProperty = new PropertyInfo[] { CustomAttributeBuilderTestType.GetProperty(PropertyTestInt32Name), CustomAttributeBuilderTestType.GetProperty(PropertyTestStringName), }; object[] propertyValues = new object[] { testInt2, testString2 }; CustomAttributeBuilder cab = new CustomAttributeBuilder( CustomAttributeBuilderTestType.GetConstructor(ctorParams), constructorArgs, namedProperty, propertyValues); Assert.NotNull(cab); PropertyInfo[] verifyFields = new PropertyInfo[] { CustomAttributeBuilderTestType.GetProperty(PropertyTestInt32Name), CustomAttributeBuilderTestType.GetProperty(PropertyTestStringName), CustomAttributeBuilderTestType.GetProperty(PropertyGetOnlyStringName), CustomAttributeBuilderTestType.GetProperty(PropertyGetOnlyIntName) }; object[] verifyFieldValues = new object[] { testInt2, testString2, testString1, testInt1 }; Assert.True(VerifyCustomAttribute(cab, CustomAttributeBuilderTestType, verifyFields, verifyFieldValues)); } [Fact] public void NegTest1() { Type CustomAttributeBuilderTestType = typeof(CustomAttributeBuilderTest); Type[] ctorParams = new Type[] { }; object[] constructorArgs = new object[] { }; PropertyInfo[] namedProperty = new PropertyInfo[] { CustomAttributeBuilderTestType.GetProperty(PropertyTestInt32Name), }; object[] propertyValues = new object[] { }; Assert.Throws<ArgumentException>(() => { CustomAttributeBuilder cab = new CustomAttributeBuilder( CustomAttributeBuilderTestType.GetConstructor(ctorParams), constructorArgs, namedProperty, propertyValues); }); } [Fact] public void NegTest2() { int testInt1 = 0; testInt1 = _generator.GetInt32(); Type CustomAttributeBuilderTestType = typeof(CustomAttributeBuilderTest); Type[] ctorParams = new Type[] { }; object[] constructorArgs = new object[] { }; PropertyInfo[] namedProperty = new PropertyInfo[] { }; object[] propertyValues = new object[] { testInt1 }; Assert.Throws<ArgumentException>(() => { CustomAttributeBuilder cab = new CustomAttributeBuilder( CustomAttributeBuilderTestType.GetConstructor(ctorParams), constructorArgs, namedProperty, propertyValues); }); } [Fact] public void NegTest3() { Type[] ctorParams = new Type[] { }; object[] constructorArgs = new object[] { }; PropertyInfo[] namedProperty = new PropertyInfo[] { }; object[] propertyValues = new object[] { }; Assert.Throws<ArgumentException>(() => { CustomAttributeBuilder cab = new CustomAttributeBuilder( typeof(TestConstructor).GetConstructors(BindingFlags.Static | BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic) .Where(c => c.IsStatic).First(), constructorArgs, namedProperty, propertyValues); }); } [Fact] public void NegTest4() { Type[] ctorParams = new Type[] { }; object[] constructorArgs = new object[] { false }; PropertyInfo[] namedProperty = new PropertyInfo[] { }; object[] propertyValues = new object[] { }; Assert.Throws<ArgumentException>(() => { CustomAttributeBuilder cab = new CustomAttributeBuilder( typeof(TestConstructor).GetConstructors(BindingFlags.Static | BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic) .Where(c => c.IsPrivate).First(), constructorArgs, namedProperty, propertyValues); }); } [Fact] public void NegTest5() { string testString1 = null; int testInt1 = 0; testString1 = _generator.GetString(false, MinStringLength, MaxStringLength); testInt1 = _generator.GetInt32(); Type CustomAttributeBuilderTestType = typeof(CustomAttributeBuilderTest); Type[] ctorParams = new Type[] { typeof(string), typeof(int), typeof(string), typeof(int) }; object[] constructorArgs = new object[] { testString1, testInt1 }; PropertyInfo[] namedProperty = new PropertyInfo[] { }; object[] propertyValues = new object[] { }; Assert.Throws<ArgumentException>(() => { CustomAttributeBuilder cab = new CustomAttributeBuilder( CustomAttributeBuilderTestType.GetConstructor(ctorParams), constructorArgs, namedProperty, propertyValues); }); } [Fact] public void NegTest6() { string testString1 = null; int testInt1 = 0; testString1 = _generator.GetString(false, MinStringLength, MaxStringLength); testInt1 = _generator.GetInt32(); Type CustomAttributeBuilderTestType = typeof(CustomAttributeBuilderTest); Type[] ctorParams = new Type[] { typeof(string), typeof(int) }; object[] constructorArgs = new object[] { testInt1, testString1 }; PropertyInfo[] namedProperty = new PropertyInfo[] { }; object[] propertyValues = new object[] { }; Assert.Throws<ArgumentException>(() => { CustomAttributeBuilder cab = new CustomAttributeBuilder( CustomAttributeBuilderTestType.GetConstructor(ctorParams), constructorArgs, namedProperty, propertyValues); }); } [Fact] public void NegTest7() { string testString1 = null; int testInt1 = 0; testString1 = _generator.GetString(false, MinStringLength, MaxStringLength); testInt1 = _generator.GetInt32(); Type CustomAttributeBuilderTestType = typeof(CustomAttributeBuilderTest); Type[] ctorParams = new Type[] { }; object[] constructorArgs = new object[] { }; PropertyInfo[] namedProperty = new PropertyInfo[] { CustomAttributeBuilderTestType.GetProperty(PropertyTestInt32Name), CustomAttributeBuilderTestType.GetProperty(PropertyTestStringName), }; object[] propertyValues = new object[] { testString1, testInt1 }; Assert.Throws<ArgumentException>(() => { CustomAttributeBuilder cab = new CustomAttributeBuilder( CustomAttributeBuilderTestType.GetConstructor(ctorParams), constructorArgs, namedProperty, propertyValues); }); } [Fact] public void NegTest8() { string testString1 = null; testString1 = _generator.GetString(false, MinStringLength, MaxStringLength); Type CustomAttributeBuilderTestType = typeof(CustomAttributeBuilderTest); Type[] ctorParams = new Type[] { }; object[] constructorArgs = new object[] { }; PropertyInfo[] namedProperty = new PropertyInfo[] { CustomAttributeBuilderTestType.GetProperty(PropertyGetOnlyIntName) }; object[] propertyValues = new object[] { testString1 }; Assert.Throws<ArgumentException>(() => { CustomAttributeBuilder cab = new CustomAttributeBuilder( CustomAttributeBuilderTestType.GetConstructor(ctorParams), constructorArgs, namedProperty, propertyValues); }); } [Fact] public void NegTest9() { string testString1 = null; testString1 = _generator.GetString(false, MinStringLength, MaxStringLength); Type CustomAttributeBuilderTestType = typeof(CustomAttributeBuilderTest); Type[] ctorParams = new Type[] { }; object[] constructorArgs = new object[] { }; PropertyInfo[] namedProperty = new PropertyInfo[] { CustomAttributeBuilderTestType.GetProperty(PropertyGetOnlyStringName) }; object[] propertyValues = new object[] { testString1 }; Assert.Throws<ArgumentException>(() => { CustomAttributeBuilder cab = new CustomAttributeBuilder( CustomAttributeBuilderTestType.GetConstructor(ctorParams), constructorArgs, namedProperty, propertyValues); }); } [Fact] public void NegTest10() { string testString1 = null; testString1 = _generator.GetString(false, MinStringLength, MaxStringLength); Type CustomAttributeBuilderTestType = typeof(CustomAttributeBuilderTest); object[] constructorArgs = new object[] { }; PropertyInfo[] namedProperty = new PropertyInfo[] { CustomAttributeBuilderTestType.GetProperty(PropertyTestInt32Name) }; object[] propertyValues = new object[] { testString1 }; Assert.Throws<ArgumentNullException>(() => { CustomAttributeBuilder cab = new CustomAttributeBuilder( null, constructorArgs, namedProperty, propertyValues); }); } [Fact] public void NegTest11() { string testString1 = null; testString1 = _generator.GetString(false, MinStringLength, MaxStringLength); Type CustomAttributeBuilderTestType = typeof(CustomAttributeBuilderTest); Type[] ctorParams = new Type[] { }; PropertyInfo[] namedProperty = new PropertyInfo[] { CustomAttributeBuilderTestType.GetProperty(PropertyTestInt32Name) }; object[] propertyValues = new object[] { testString1 }; Assert.Throws<ArgumentNullException>(() => { CustomAttributeBuilder cab = new CustomAttributeBuilder( CustomAttributeBuilderTestType.GetConstructor(ctorParams), null, namedProperty, propertyValues); }); } [Fact] public void NegTest12() { string testString1 = null; testString1 = _generator.GetString(false, MinStringLength, MaxStringLength); Type CustomAttributeBuilderTestType = typeof(CustomAttributeBuilderTest); Type[] ctorParams = new Type[] { }; object[] constructorArgs = new object[] { }; PropertyInfo[] namedProperty = new PropertyInfo[] { CustomAttributeBuilderTestType.GetProperty(PropertyTestInt32Name) }; Assert.Throws<ArgumentNullException>(() => { CustomAttributeBuilder cab = new CustomAttributeBuilder( CustomAttributeBuilderTestType.GetConstructor(ctorParams), constructorArgs, namedProperty, null); }); } [Fact] public void NegTest13() { string testString = null; int testInt = 0; testString = _generator.GetString(false, MinStringLength, MaxStringLength); testInt = _generator.GetInt32(); Type CustomAttributeBuilderTestType = typeof(CustomAttributeBuilderTest); Type[] ctorParams = new Type[] { null, typeof(int) }; object[] constructorArgs = new object[] { testString, testInt }; PropertyInfo[] namedProperty = new PropertyInfo[] { CustomAttributeBuilderTestType.GetProperty(PropertyTestInt32Name), CustomAttributeBuilderTestType.GetProperty(PropertyTestStringName), }; object[] propertyValues = new object[] { testString, testInt }; Assert.Throws<ArgumentNullException>(() => { CustomAttributeBuilder cab = new CustomAttributeBuilder( CustomAttributeBuilderTestType.GetConstructor(ctorParams), constructorArgs, namedProperty, propertyValues); }); } [Fact] public void NegTest14() { string testString = null; int testInt = 0; testString = _generator.GetString(false, MinStringLength, MaxStringLength); testInt = _generator.GetInt32(); Type CustomAttributeBuilderTestType = typeof(CustomAttributeBuilderTest); Type[] ctorParams = new Type[] { typeof(string), typeof(int) }; object[] constructorArgs = new object[] { null, testInt }; PropertyInfo[] namedProperty = new PropertyInfo[] { CustomAttributeBuilderTestType.GetProperty(PropertyTestInt32Name), CustomAttributeBuilderTestType.GetProperty(PropertyTestStringName), }; object[] propertyValues = new object[] { testString, testInt }; Assert.Throws<ArgumentException>(() => { CustomAttributeBuilder cab = new CustomAttributeBuilder( CustomAttributeBuilderTestType.GetConstructor(ctorParams), constructorArgs, namedProperty, propertyValues); }); } [Fact] public void NegTest15() { string testString = null; int testInt = 0; testString = _generator.GetString(false, MinStringLength, MaxStringLength); testInt = _generator.GetInt32(); Type CustomAttributeBuilderTestType = typeof(CustomAttributeBuilderTest); Type[] ctorParams = new Type[] { typeof(string), typeof(int) }; object[] constructorArgs = new object[] { testString, testInt }; PropertyInfo[] namedProperty = new PropertyInfo[] { null, CustomAttributeBuilderTestType.GetProperty(PropertyTestStringName), }; object[] propertyValues = new object[] { testString, testInt }; Assert.Throws<ArgumentNullException>(() => { CustomAttributeBuilder cab = new CustomAttributeBuilder( CustomAttributeBuilderTestType.GetConstructor(ctorParams), constructorArgs, namedProperty, propertyValues); }); } [Fact] public void NegTest16() { int testInt = 0; string testString = null; testString = _generator.GetString(false, MinStringLength, MaxStringLength); testInt = _generator.GetInt32(); Type CustomAttributeBuilderTestType = typeof(CustomAttributeBuilderTest); Type[] ctorParams = new Type[] { typeof(string), typeof(int) }; object[] constructorArgs = new object[] { testString, testInt }; PropertyInfo[] namedProperty = new PropertyInfo[] { CustomAttributeBuilderTestType.GetProperty(PropertyTestInt32Name), CustomAttributeBuilderTestType.GetProperty(PropertyTestStringName), }; object[] propertyValues = new object[] { null, testInt }; Assert.Throws<ArgumentNullException>(() => { CustomAttributeBuilder cab = new CustomAttributeBuilder( CustomAttributeBuilderTestType.GetConstructor(ctorParams), constructorArgs, namedProperty, propertyValues); }); } [Fact] public void NegTest17() { string testString1 = null; testString1 = _generator.GetString(false, MinStringLength, MaxStringLength); Type CustomAttributeBuilderTestType = typeof(CustomAttributeBuilderTest); Type[] ctorParams = new Type[] { }; object[] constructorArgs = new object[] { }; object[] propertyValues = new object[] { testString1 }; Assert.Throws<ArgumentNullException>(() => { CustomAttributeBuilder cab = new CustomAttributeBuilder( CustomAttributeBuilderTestType.GetConstructor(ctorParams), constructorArgs, null as PropertyInfo[], propertyValues); }); } private bool VerifyCustomAttribute(CustomAttributeBuilder builder, Type attributeType, PropertyInfo[] namedProperties, object[] propertyValues) { AssemblyName asmName = new AssemblyName("VerificationAssembly"); bool retVal = true; AssemblyBuilder asmBuilder = AssemblyBuilder.DefineDynamicAssembly( asmName, AssemblyBuilderAccess.Run); asmBuilder.SetCustomAttribute(builder); // Verify object[] customAttributes = asmBuilder.GetCustomAttributes(attributeType).Select(a => (object)a).ToArray(); // We just support one custom attribute case if (customAttributes.Length != 1) return false; object customAttribute = customAttributes[0]; for (int i = 0; i < namedProperties.Length; ++i) { PropertyInfo property = attributeType.GetProperty(namedProperties[i].Name); object expected = property.GetValue(customAttribute, null); object actual = propertyValues[i]; if (expected == null) { if (actual != null) { retVal = false; break; } } else { if (!expected.Equals(actual)) { retVal = false; break; } } } return retVal; } } }
using System; using System.Globalization; using System.Collections.Generic; using Sasoma.Utils; using Sasoma.Microdata.Interfaces; using Sasoma.Languages.Core; using Sasoma.Microdata.Properties; namespace Sasoma.Microdata.Types { /// <summary> /// Web page type: Checkout page. /// </summary> public class CheckoutPage_Core : TypeCore, IWebPage { public CheckoutPage_Core() { this._TypeId = 56; this._Id = "CheckoutPage"; this._Schema_Org_Url = "http://schema.org/CheckoutPage"; string label = ""; GetLabel(out label, "CheckoutPage", typeof(CheckoutPage_Core)); this._Label = label; this._Ancestors = new int[]{266,78,293}; this._SubTypes = new int[0]; this._SuperTypes = new int[]{293}; this._Properties = new int[]{67,108,143,229,0,2,10,12,18,20,24,26,21,50,51,54,57,58,59,61,62,64,70,72,81,97,100,110,115,116,126,138,151,178,179,180,199,211,219,230,231,38,117,133,169,208}; } /// <summary> /// The subject matter of the content. /// </summary> private About_Core about; public About_Core About { get { return about; } set { about = value; SetPropertyInstance(about); } } /// <summary> /// Specifies the Person that is legally accountable for the CreativeWork. /// </summary> private AccountablePerson_Core accountablePerson; public AccountablePerson_Core AccountablePerson { get { return accountablePerson; } set { accountablePerson = value; SetPropertyInstance(accountablePerson); } } /// <summary> /// The overall rating, based on a collection of reviews or ratings, of the item. /// </summary> private Properties.AggregateRating_Core aggregateRating; public Properties.AggregateRating_Core AggregateRating { get { return aggregateRating; } set { aggregateRating = value; SetPropertyInstance(aggregateRating); } } /// <summary> /// A secondary title of the CreativeWork. /// </summary> private AlternativeHeadline_Core alternativeHeadline; public AlternativeHeadline_Core AlternativeHeadline { get { return alternativeHeadline; } set { alternativeHeadline = value; SetPropertyInstance(alternativeHeadline); } } /// <summary> /// The media objects that encode this creative work. This property is a synonym for encodings. /// </summary> private AssociatedMedia_Core associatedMedia; public AssociatedMedia_Core AssociatedMedia { get { return associatedMedia; } set { associatedMedia = value; SetPropertyInstance(associatedMedia); } } /// <summary> /// An embedded audio object. /// </summary> private Audio_Core audio; public Audio_Core Audio { get { return audio; } set { audio = value; SetPropertyInstance(audio); } } /// <summary> /// The author of this content. Please note that author is special in that HTML 5 provides a special mechanism for indicating authorship via the rel tag. That is equivalent to this and may be used interchangabely. /// </summary> private Author_Core author; public Author_Core Author { get { return author; } set { author = value; SetPropertyInstance(author); } } /// <summary> /// Awards won by this person or for this creative work. /// </summary> private Awards_Core awards; public Awards_Core Awards { get { return awards; } set { awards = value; SetPropertyInstance(awards); } } /// <summary> /// A set of links that can help a user understand and navigate a website hierarchy. /// </summary> private Breadcrumb_Core breadcrumb; public Breadcrumb_Core Breadcrumb { get { return breadcrumb; } set { breadcrumb = value; SetPropertyInstance(breadcrumb); } } /// <summary> /// Comments, typically from users, on this CreativeWork. /// </summary> private Comment_Core comment; public Comment_Core Comment { get { return comment; } set { comment = value; SetPropertyInstance(comment); } } /// <summary> /// The location of the content. /// </summary> private ContentLocation_Core contentLocation; public ContentLocation_Core ContentLocation { get { return contentLocation; } set { contentLocation = value; SetPropertyInstance(contentLocation); } } /// <summary> /// Official rating of a piece of content\u2014for example,'MPAA PG-13'. /// </summary> private ContentRating_Core contentRating; public ContentRating_Core ContentRating { get { return contentRating; } set { contentRating = value; SetPropertyInstance(contentRating); } } /// <summary> /// A secondary contributor to the CreativeWork. /// </summary> private Contributor_Core contributor; public Contributor_Core Contributor { get { return contributor; } set { contributor = value; SetPropertyInstance(contributor); } } /// <summary> /// The party holding the legal copyright to the CreativeWork. /// </summary> private CopyrightHolder_Core copyrightHolder; public CopyrightHolder_Core CopyrightHolder { get { return copyrightHolder; } set { copyrightHolder = value; SetPropertyInstance(copyrightHolder); } } /// <summary> /// The year during which the claimed copyright for the CreativeWork was first asserted. /// </summary> private CopyrightYear_Core copyrightYear; public CopyrightYear_Core CopyrightYear { get { return copyrightYear; } set { copyrightYear = value; SetPropertyInstance(copyrightYear); } } /// <summary> /// The creator/author of this CreativeWork or UserComments. This is the same as the Author property for CreativeWork. /// </summary> private Creator_Core creator; public Creator_Core Creator { get { return creator; } set { creator = value; SetPropertyInstance(creator); } } /// <summary> /// The date on which the CreativeWork was created. /// </summary> private DateCreated_Core dateCreated; public DateCreated_Core DateCreated { get { return dateCreated; } set { dateCreated = value; SetPropertyInstance(dateCreated); } } /// <summary> /// The date on which the CreativeWork was most recently modified. /// </summary> private DateModified_Core dateModified; public DateModified_Core DateModified { get { return dateModified; } set { dateModified = value; SetPropertyInstance(dateModified); } } /// <summary> /// Date of first broadcast/publication. /// </summary> private DatePublished_Core datePublished; public DatePublished_Core DatePublished { get { return datePublished; } set { datePublished = value; SetPropertyInstance(datePublished); } } /// <summary> /// A short description of the item. /// </summary> private Description_Core description; public Description_Core Description { get { return description; } set { description = value; SetPropertyInstance(description); } } /// <summary> /// A link to the page containing the comments of the CreativeWork. /// </summary> private DiscussionURL_Core discussionURL; public DiscussionURL_Core DiscussionURL { get { return discussionURL; } set { discussionURL = value; SetPropertyInstance(discussionURL); } } /// <summary> /// Specifies the Person who edited the CreativeWork. /// </summary> private Editor_Core editor; public Editor_Core Editor { get { return editor; } set { editor = value; SetPropertyInstance(editor); } } /// <summary> /// The media objects that encode this creative work /// </summary> private Encodings_Core encodings; public Encodings_Core Encodings { get { return encodings; } set { encodings = value; SetPropertyInstance(encodings); } } /// <summary> /// Genre of the creative work /// </summary> private Genre_Core genre; public Genre_Core Genre { get { return genre; } set { genre = value; SetPropertyInstance(genre); } } /// <summary> /// Headline of the article /// </summary> private Headline_Core headline; public Headline_Core Headline { get { return headline; } set { headline = value; SetPropertyInstance(headline); } } /// <summary> /// URL of an image of the item. /// </summary> private Image_Core image; public Image_Core Image { get { return image; } set { image = value; SetPropertyInstance(image); } } /// <summary> /// The language of the content. please use one of the language codes from the <a href=\http://tools.ietf.org/html/bcp47\>IETF BCP 47 standard.</a> /// </summary> private InLanguage_Core inLanguage; public InLanguage_Core InLanguage { get { return inLanguage; } set { inLanguage = value; SetPropertyInstance(inLanguage); } } /// <summary> /// A count of a specific user interactions with this item\u2014for example, <code>20 UserLikes</code>, <code>5 UserComments</code>, or <code>300 UserDownloads</code>. The user interaction type should be one of the sub types of <a href=\http://schema.org/UserInteraction\>UserInteraction</a>. /// </summary> private InteractionCount_Core interactionCount; public InteractionCount_Core InteractionCount { get { return interactionCount; } set { interactionCount = value; SetPropertyInstance(interactionCount); } } /// <summary> /// Indicates whether this content is family friendly. /// </summary> private IsFamilyFriendly_Core isFamilyFriendly; public IsFamilyFriendly_Core IsFamilyFriendly { get { return isFamilyFriendly; } set { isFamilyFriendly = value; SetPropertyInstance(isFamilyFriendly); } } /// <summary> /// Indicates the collection or gallery to which the item belongs. /// </summary> private IsPartOf_Core isPartOf; public IsPartOf_Core IsPartOf { get { return isPartOf; } set { isPartOf = value; SetPropertyInstance(isPartOf); } } /// <summary> /// The keywords/tags used to describe this content. /// </summary> private Keywords_Core keywords; public Keywords_Core Keywords { get { return keywords; } set { keywords = value; SetPropertyInstance(keywords); } } /// <summary> /// Indicates if this web page element is the main subject of the page. /// </summary> private MainContentOfPage_Core mainContentOfPage; public MainContentOfPage_Core MainContentOfPage { get { return mainContentOfPage; } set { mainContentOfPage = value; SetPropertyInstance(mainContentOfPage); } } /// <summary> /// Indicates that the CreativeWork contains a reference to, but is not necessarily about a concept. /// </summary> private Mentions_Core mentions; public Mentions_Core Mentions { get { return mentions; } set { mentions = value; SetPropertyInstance(mentions); } } /// <summary> /// The name of the item. /// </summary> private Name_Core name; public Name_Core Name { get { return name; } set { name = value; SetPropertyInstance(name); } } /// <summary> /// An offer to sell this item\u2014for example, an offer to sell a product, the DVD of a movie, or tickets to an event. /// </summary> private Offers_Core offers; public Offers_Core Offers { get { return offers; } set { offers = value; SetPropertyInstance(offers); } } /// <summary> /// Indicates the main image on the page /// </summary> private PrimaryImageOfPage_Core primaryImageOfPage; public PrimaryImageOfPage_Core PrimaryImageOfPage { get { return primaryImageOfPage; } set { primaryImageOfPage = value; SetPropertyInstance(primaryImageOfPage); } } /// <summary> /// Specifies the Person or Organization that distributed the CreativeWork. /// </summary> private Provider_Core provider; public Provider_Core Provider { get { return provider; } set { provider = value; SetPropertyInstance(provider); } } /// <summary> /// The publisher of the creative work. /// </summary> private Publisher_Core publisher; public Publisher_Core Publisher { get { return publisher; } set { publisher = value; SetPropertyInstance(publisher); } } /// <summary> /// Link to page describing the editorial principles of the organization primarily responsible for the creation of the CreativeWork. /// </summary> private PublishingPrinciples_Core publishingPrinciples; public PublishingPrinciples_Core PublishingPrinciples { get { return publishingPrinciples; } set { publishingPrinciples = value; SetPropertyInstance(publishingPrinciples); } } /// <summary> /// Review of the item. /// </summary> private Reviews_Core reviews; public Reviews_Core Reviews { get { return reviews; } set { reviews = value; SetPropertyInstance(reviews); } } /// <summary> /// The most significant URLs on the page. Typically, these are the non-navigation links that are clicked on the most /// </summary> private SignificantLinks_Core significantLinks; public SignificantLinks_Core SignificantLinks { get { return significantLinks; } set { significantLinks = value; SetPropertyInstance(significantLinks); } } /// <summary> /// The Organization on whose behalf the creator was working. /// </summary> private SourceOrganization_Core sourceOrganization; public SourceOrganization_Core SourceOrganization { get { return sourceOrganization; } set { sourceOrganization = value; SetPropertyInstance(sourceOrganization); } } /// <summary> /// A thumbnail image relevant to the Thing. /// </summary> private ThumbnailURL_Core thumbnailURL; public ThumbnailURL_Core ThumbnailURL { get { return thumbnailURL; } set { thumbnailURL = value; SetPropertyInstance(thumbnailURL); } } /// <summary> /// URL of the item. /// </summary> private Properties.URL_Core uRL; public Properties.URL_Core URL { get { return uRL; } set { uRL = value; SetPropertyInstance(uRL); } } /// <summary> /// The version of the CreativeWork embodied by a specified resource. /// </summary> private Version_Core version; public Version_Core Version { get { return version; } set { version = value; SetPropertyInstance(version); } } /// <summary> /// An embedded video object. /// </summary> private Video_Core video; public Video_Core Video { get { return video; } set { video = value; SetPropertyInstance(video); } } } }
// 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.Immutable; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; using System.Reflection; using System.Collections.Generic; namespace Microsoft.CodeAnalysis.Scripting { /// <summary> /// The result of running a script. /// </summary> public abstract class ScriptState { /// <summary> /// The script that ran to produce this result. /// </summary> public Script Script { get; } internal ScriptExecutionState ExecutionState { get; } private ImmutableArray<ScriptVariable> _lazyVariables; private IReadOnlyDictionary<string, int> _lazyVariableMap; internal ScriptState(ScriptExecutionState executionState, Script script) { Debug.Assert(executionState != null); Debug.Assert(script != null); ExecutionState = executionState; Script = script; } /// <summary> /// The final value produced by running the script. /// </summary> public object ReturnValue => GetReturnValue(); internal abstract object GetReturnValue(); /// <summary> /// Returns variables defined by the scripts in the declaration order. /// </summary> public ImmutableArray<ScriptVariable> Variables { get { if (_lazyVariables == null) { ImmutableInterlocked.InterlockedInitialize(ref _lazyVariables, CreateVariables()); } return _lazyVariables; } } /// <summary> /// Returns a script variable of the specified name. /// </summary> /// <remarks> /// If multiple script variables are defined in the script (in distinct submissions) returns the last one. /// Namve lookup is case sensitive in C# scripts and case insensitive in VB scripts. /// </remarks> /// <returns><see cref="ScriptVariable"/> or null, if no variable of the specified <paramref name="name"/> is defined in the script.</returns> /// <exception cref="ArgumentNullException"><paramref name="name"/> is null.</exception> public ScriptVariable GetVariable(string name) { if (name == null) { throw new ArgumentNullException(nameof(name)); } int index; return GetVariableMap().TryGetValue(name, out index) ? Variables[index] : null; } private ImmutableArray<ScriptVariable> CreateVariables() { var result = ImmutableArray.CreateBuilder<ScriptVariable>(); var executionState = ExecutionState; // Don't include the globals object (slot #0) for (int i = 1; i < executionState.SubmissionStateCount; i++) { var state = executionState.GetSubmissionState(i); Debug.Assert(state != null); foreach (var field in state.GetType().GetTypeInfo().DeclaredFields) { // TODO: synthesized fields of submissions shouldn't be public if (field.IsPublic && field.Name.Length > 0 && (char.IsLetterOrDigit(field.Name[0]) || field.Name[0] == '_')) { result.Add(new ScriptVariable(state, field)); } } } return result.ToImmutable(); } private IReadOnlyDictionary<string, int> GetVariableMap() { if (_lazyVariableMap == null) { var map = new Dictionary<string, int>(Script.Compiler.IdentifierComparer); for (int i = 0; i < Variables.Length; i++) { map[Variables[i].Name] = i; } _lazyVariableMap = map; } return _lazyVariableMap; } public Task<ScriptState<object>> ContinueWithAsync(string code, ScriptOptions options = null, CancellationToken cancellationToken = default(CancellationToken)) { return ContinueWithAsync<object>(code, options, cancellationToken); } public Task<ScriptState<TResult>> ContinueWithAsync<TResult>(string code, ScriptOptions options = null, CancellationToken cancellationToken = default(CancellationToken)) { return Script.ContinueWith<TResult>(code, options).ContinueAsync(this, cancellationToken); } // How do we resolve overloads? We should use the language semantics. // https://github.com/dotnet/roslyn/issues/3720 #if TODO /// <summary> /// Invoke a method declared by the script. /// </summary> public object Invoke(string name, params object[] args) { var func = this.FindMethod(name, args != null ? args.Length : 0); if (func != null) { return func(args); } return null; } private Func<object[], object> FindMethod(string name, int argCount) { for (int i = _executionState.Count - 1; i >= 0; i--) { var sub = _executionState[i]; if (sub != null) { var type = sub.GetType(); var method = FindMethod(type, name, argCount); if (method != null) { return (args) => method.Invoke(sub, args); } } } return null; } private MethodInfo FindMethod(Type type, string name, int argCount) { return type.GetMethod(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); } /// <summary> /// Create a delegate to a method declared by the script. /// </summary> public TDelegate CreateDelegate<TDelegate>(string name) { var delegateInvokeMethod = typeof(TDelegate).GetMethod("Invoke", BindingFlags.Instance | BindingFlags.Public); for (int i = _executionState.Count - 1; i >= 0; i--) { var sub = _executionState[i]; if (sub != null) { var type = sub.GetType(); var method = FindMatchingMethod(type, name, delegateInvokeMethod); if (method != null) { return (TDelegate)(object)method.CreateDelegate(typeof(TDelegate), sub); } } } return default(TDelegate); } private MethodInfo FindMatchingMethod(Type instanceType, string name, MethodInfo delegateInvokeMethod) { var dprms = delegateInvokeMethod.GetParameters(); foreach (var mi in instanceType.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)) { if (mi.Name == name) { var prms = mi.GetParameters(); if (prms.Length == dprms.Length) { // TODO: better matching.. return mi; } } } return null; } #endif } public sealed class ScriptState<T> : ScriptState { public new T ReturnValue { get; } internal override object GetReturnValue() => ReturnValue; internal ScriptState(ScriptExecutionState executionState, T value, Script script) : base(executionState, script) { ReturnValue = value; } } }
/* * Copyright 2012 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using ZXing.Common; using ZXing.PDF417.Internal; namespace ZXing.PDF417 { /// <summary> /// <author>Jacob Haynes</author> /// <author>qwandor@google.com (Andrew Walbran)</author> /// </summary> public sealed class PDF417Writer : Writer { /// <summary> /// default white space (margin) around the code /// </summary> private const int WHITE_SPACE = 30; /// <summary> /// default error correction level /// </summary> private const int DEFAULT_ERROR_CORRECTION_LEVEL = 2; /// <summary> /// </summary> /// <param name="contents">The contents to encode in the barcode</param> /// <param name="format">The barcode format to generate</param> /// <param name="width">The preferred width in pixels</param> /// <param name="height">The preferred height in pixels</param> /// <param name="hints">Additional parameters to supply to the encoder</param> /// <returns> /// The generated barcode as a Matrix of unsigned bytes (0 == black, 255 == white) /// </returns> public BitMatrix encode(String contents, BarcodeFormat format, int width, int height, IDictionary<EncodeHintType, object> hints) { if (format != BarcodeFormat.PDF_417) { throw new ArgumentException("Can only encode PDF_417, but got " + format); } var encoder = new Internal.PDF417(); var margin = WHITE_SPACE; var errorCorrectionLevel = DEFAULT_ERROR_CORRECTION_LEVEL; if (hints != null) { if (hints.ContainsKey(EncodeHintType.PDF417_COMPACT) && hints[EncodeHintType.PDF417_COMPACT] != null) { encoder.setCompact(Convert.ToBoolean(hints[EncodeHintType.PDF417_COMPACT].ToString())); } if (hints.ContainsKey(EncodeHintType.PDF417_COMPACTION) && hints[EncodeHintType.PDF417_COMPACTION] != null) { if (Enum.IsDefined(typeof(Compaction), hints[EncodeHintType.PDF417_COMPACTION].ToString())) { var compactionEnum = (Compaction)Enum.Parse(typeof(Compaction), hints[EncodeHintType.PDF417_COMPACTION].ToString(), true); encoder.setCompaction(compactionEnum); } } if (hints.ContainsKey(EncodeHintType.PDF417_DIMENSIONS)) { var dimensions = (Dimensions) hints[EncodeHintType.PDF417_DIMENSIONS]; encoder.setDimensions(dimensions.MaxCols, dimensions.MinCols, dimensions.MaxRows, dimensions.MinRows); } if (hints.ContainsKey(EncodeHintType.MARGIN) && hints[EncodeHintType.MARGIN] != null) { margin = Convert.ToInt32(hints[EncodeHintType.MARGIN].ToString()); } if (hints.ContainsKey(EncodeHintType.ERROR_CORRECTION) && hints[EncodeHintType.ERROR_CORRECTION] != null) { var value = hints[EncodeHintType.ERROR_CORRECTION]; if (value is PDF417ErrorCorrectionLevel || value is int) { errorCorrectionLevel = (int)value; } else { if (Enum.IsDefined(typeof(PDF417ErrorCorrectionLevel), value.ToString())) { var errorCorrectionLevelEnum = (PDF417ErrorCorrectionLevel)Enum.Parse(typeof(PDF417ErrorCorrectionLevel), value.ToString(), true); errorCorrectionLevel = (int)errorCorrectionLevelEnum; } } } if (hints.ContainsKey(EncodeHintType.CHARACTER_SET)) { #if !SILVERLIGHT || WINDOWS_PHONE var encoding = (String)hints[EncodeHintType.CHARACTER_SET]; if (encoding != null) { encoder.setEncoding(encoding); } #else // Silverlight supports only UTF-8 and UTF-16 out-of-the-box encoder.setEncoding("UTF-8"); #endif } if (hints.ContainsKey(EncodeHintType.DISABLE_ECI) && hints[EncodeHintType.DISABLE_ECI] != null) { encoder.setDisableEci(Convert.ToBoolean(hints[EncodeHintType.DISABLE_ECI].ToString())); } } return bitMatrixFromEncoder(encoder, contents, errorCorrectionLevel, width, height, margin); } /// <summary> /// Encode a barcode using the default settings. /// </summary> /// <param name="contents">The contents to encode in the barcode</param> /// <param name="format">The barcode format to generate</param> /// <param name="width">The preferred width in pixels</param> /// <param name="height">The preferred height in pixels</param> /// <returns> /// The generated barcode as a Matrix of unsigned bytes (0 == black, 255 == white) /// </returns> public BitMatrix encode(String contents, BarcodeFormat format, int width, int height) { return encode(contents, format, width, height, null); } /// <summary> /// Takes encoder, accounts for width/height, and retrieves bit matrix /// </summary> private static BitMatrix bitMatrixFromEncoder(Internal.PDF417 encoder, String contents, int errorCorrectionLevel, int width, int height, int margin) { encoder.generateBarcodeLogic(contents, errorCorrectionLevel); const int aspectRatio = 4; sbyte[][] originalScale = encoder.BarcodeMatrix.getScaledMatrix(1, aspectRatio); bool rotated = false; if ((height > width) != (originalScale[0].Length < originalScale.Length)) { originalScale = rotateArray(originalScale); rotated = true; } int scaleX = width/originalScale[0].Length; int scaleY = height/originalScale.Length; int scale; if (scaleX < scaleY) { scale = scaleX; } else { scale = scaleY; } if (scale > 1) { sbyte[][] scaledMatrix = encoder.BarcodeMatrix.getScaledMatrix(scale, scale*aspectRatio); if (rotated) { scaledMatrix = rotateArray(scaledMatrix); } return bitMatrixFromBitArray(scaledMatrix, margin); } return bitMatrixFromBitArray(originalScale, margin); } /// <summary> /// This takes an array holding the values of the PDF 417 /// </summary> /// <param name="input">a byte array of information with 0 is black, and 1 is white</param> /// <param name="margin">border around the barcode</param> /// <returns>BitMatrix of the input</returns> private static BitMatrix bitMatrixFromBitArray(sbyte[][] input, int margin) { // Creates the bit matrix with extra space for whitespace var output = new BitMatrix(input[0].Length + 2 * margin, input.Length + 2 * margin); var yOutput = output.Height - margin - 1; for (int y = 0; y < input.Length; y++, yOutput--) { var currentInput = input[y]; var currentInputLength = currentInput.Length; for (int x = 0; x < currentInputLength; x++) { // Zero is white in the bytematrix if (currentInput[x] == 1) { output[x + margin, yOutput] = true; } } } return output; } /// <summary> /// Takes and rotates the it 90 degrees /// </summary> private static sbyte[][] rotateArray(sbyte[][] bitarray) { sbyte[][] temp = new sbyte[bitarray[0].Length][]; for (int idx = 0; idx < bitarray[0].Length; idx++) temp[idx] = new sbyte[bitarray.Length]; for (int ii = 0; ii < bitarray.Length; ii++) { // This makes the direction consistent on screen when rotating the // screen; int inverseii = bitarray.Length - ii - 1; for (int jj = 0; jj < bitarray[0].Length; jj++) { temp[jj][inverseii] = bitarray[ii][jj]; } } return temp; } } }
// <copyright file="TFQMR.cs" company="Math.NET"> // Math.NET Numerics, part of the Math.NET Project // http://numerics.mathdotnet.com // http://github.com/mathnet/mathnet-numerics // http://mathnetnumerics.codeplex.com // // Copyright (c) 2009-2013 Math.NET // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. // </copyright> using System; using MathNet.Numerics.LinearAlgebra.Solvers; using MathNet.Numerics.Properties; namespace MathNet.Numerics.LinearAlgebra.Single.Solvers { /// <summary> /// A Transpose Free Quasi-Minimal Residual (TFQMR) iterative matrix solver. /// </summary> /// <remarks> /// <para> /// The TFQMR algorithm was taken from: <br/> /// Iterative methods for sparse linear systems. /// <br/> /// Yousef Saad /// <br/> /// Algorithm is described in Chapter 7, section 7.4.3, page 219 /// </para> /// <para> /// The example code below provides an indication of the possible use of the /// solver. /// </para> /// </remarks> public sealed class TFQMR : IIterativeSolver<float> { /// <summary> /// Calculates the <c>true</c> residual of the matrix equation Ax = b according to: residual = b - Ax /// </summary> /// <param name="matrix">Instance of the <see cref="Matrix"/> A.</param> /// <param name="residual">Residual values in <see cref="Vector"/>.</param> /// <param name="x">Instance of the <see cref="Vector"/> x.</param> /// <param name="b">Instance of the <see cref="Vector"/> b.</param> static void CalculateTrueResidual(Matrix<float> matrix, Vector<float> residual, Vector<float> x, Vector<float> b) { // -Ax = residual matrix.Multiply(x, residual); residual.Multiply(-1, residual); // residual + b residual.Add(b, residual); } /// <summary> /// Is <paramref name="number"/> even? /// </summary> /// <param name="number">Number to check</param> /// <returns><c>true</c> if <paramref name="number"/> even, otherwise <c>false</c></returns> static bool IsEven(int number) { return number % 2 == 0; } /// <summary> /// Solves the matrix equation Ax = b, where A is the coefficient matrix, b is the /// solution vector and x is the unknown vector. /// </summary> /// <param name="matrix">The coefficient matrix, <c>A</c>.</param> /// <param name="input">The solution vector, <c>b</c></param> /// <param name="result">The result vector, <c>x</c></param> /// <param name="iterator">The iterator to use to control when to stop iterating.</param> /// <param name="preconditioner">The preconditioner to use for approximations.</param> public void Solve(Matrix<float> matrix, Vector<float> input, Vector<float> result, Iterator<float> iterator, IPreconditioner<float> preconditioner) { if (matrix.RowCount != matrix.ColumnCount) { throw new ArgumentException(Resource.ArgumentMatrixSquare, "matrix"); } if (result.Count != input.Count) { throw new ArgumentException(Resource.ArgumentVectorsSameLength); } if (input.Count != matrix.RowCount) { throw Matrix.DimensionsDontMatch<ArgumentException>(input, matrix); } if (iterator == null) { iterator = new Iterator<float>(); } if (preconditioner == null) { preconditioner = new UnitPreconditioner<float>(); } preconditioner.Initialize(matrix); var d = new DenseVector(input.Count); var r = DenseVector.OfVector(input); var uodd = new DenseVector(input.Count); var ueven = new DenseVector(input.Count); var v = new DenseVector(input.Count); var pseudoResiduals = DenseVector.OfVector(input); var x = new DenseVector(input.Count); var yodd = new DenseVector(input.Count); var yeven = DenseVector.OfVector(input); // Temp vectors var temp = new DenseVector(input.Count); var temp1 = new DenseVector(input.Count); var temp2 = new DenseVector(input.Count); // Define the scalars float alpha = 0; float eta = 0; float theta = 0; // Initialize var tau = (float) input.L2Norm(); var rho = tau*tau; // Calculate the initial values for v // M temp = yEven preconditioner.Approximate(yeven, temp); // v = A temp matrix.Multiply(temp, v); // Set uOdd v.CopyTo(ueven); // Start the iteration var iterationNumber = 0; while (iterator.DetermineStatus(iterationNumber, result, input, pseudoResiduals) == IterationStatus.Continue) { // First part of the step, the even bit if (IsEven(iterationNumber)) { // sigma = (v, r) var sigma = v.DotProduct(r); if (sigma.AlmostEqualNumbersBetween(0, 1)) { // FAIL HERE iterator.Cancel(); break; } // alpha = rho / sigma alpha = rho/sigma; // yOdd = yEven - alpha * v v.Multiply(-alpha, temp1); yeven.Add(temp1, yodd); // Solve M temp = yOdd preconditioner.Approximate(yodd, temp); // uOdd = A temp matrix.Multiply(temp, uodd); } // The intermediate step which is equal for both even and // odd iteration steps. // Select the correct vector var uinternal = IsEven(iterationNumber) ? ueven : uodd; var yinternal = IsEven(iterationNumber) ? yeven : yodd; // pseudoResiduals = pseudoResiduals - alpha * uOdd uinternal.Multiply(-alpha, temp1); pseudoResiduals.Add(temp1, temp2); temp2.CopyTo(pseudoResiduals); // d = yOdd + theta * theta * eta / alpha * d d.Multiply(theta*theta*eta/alpha, temp); yinternal.Add(temp, d); // theta = ||pseudoResiduals||_2 / tau theta = (float) pseudoResiduals.L2Norm()/tau; var c = 1/(float) Math.Sqrt(1 + (theta*theta)); // tau = tau * theta * c tau *= theta*c; // eta = c^2 * alpha eta = c*c*alpha; // x = x + eta * d d.Multiply(eta, temp1); x.Add(temp1, temp2); temp2.CopyTo(x); // Check convergence and see if we can bail if (iterator.DetermineStatus(iterationNumber, result, input, pseudoResiduals) != IterationStatus.Continue) { // Calculate the real values preconditioner.Approximate(x, result); // Calculate the true residual. Use the temp vector for that // so that we don't pollute the pseudoResidual vector for no // good reason. CalculateTrueResidual(matrix, temp, result, input); // Now recheck the convergence if (iterator.DetermineStatus(iterationNumber, result, input, temp) != IterationStatus.Continue) { // We're all good now. return; } } // The odd step if (!IsEven(iterationNumber)) { if (rho.AlmostEqualNumbersBetween(0, 1)) { // FAIL HERE iterator.Cancel(); break; } var rhoNew = pseudoResiduals.DotProduct(r); var beta = rhoNew/rho; // Update rho for the next loop rho = rhoNew; // yOdd = pseudoResiduals + beta * yOdd yodd.Multiply(beta, temp1); pseudoResiduals.Add(temp1, yeven); // Solve M temp = yOdd preconditioner.Approximate(yeven, temp); // uOdd = A temp matrix.Multiply(temp, ueven); // v = uEven + beta * (uOdd + beta * v) v.Multiply(beta, temp1); uodd.Add(temp1, temp); temp.Multiply(beta, temp1); ueven.Add(temp1, v); } // Calculate the real values preconditioner.Approximate(x, result); iterationNumber++; } } } }
using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.IO; using System.Linq; using System.Net; using System.Security.Cryptography; using System.Threading; using UnityEngine; using UnityEngine.SceneManagement; using UnityEngine.UI; public class UpdateOperator : MonoBehaviour { public bool checkForUpdates = true; //If set to false, will immediately close client and launch Launcher to update if an update is necessary. Otherwise will check if a launcher update is necessary. public bool checkForLauncherUpdates; //Full URL for your Server File List (Should be in root directory of your CDN Bucket example s3.patchbucket.com/fileList.txt) public string serverFileListURL = ""; //Full Application Name for your Game including the .exe. For Mac builds this is the file that is in the game.app/Contents/MacOS/ folder, it will not have any extension. public string gameFullExe = ""; //Full Application Name for your Patcher including the .exe. For Mac builds this is the file that is in the patcher.app/Contents/MacOS/ folder, it will not have any extension. public string patcherFullExe = ""; public RectTransform ActivitySpinner; float spinnerRotationSpeed = 30f; string patcherNoExe = ""; string serverVersionFile = "fileList.txt"; string serverDirectory = ""; bool needsToUpdate = false; bool updatingLauncher = false; bool updatingLauncherFiles = false; bool doneCheckingFiles = false; int downloadFailures = 0; string launcher = ""; string launcherMD5 = ""; Dictionary<string, string> missingLauncherFiles = new Dictionary<string, string>(); int TotalFilesCount = 0; int FileCount = 0; string CurrentFileName = ""; bool hasInternetConnection = true; public enum OperatingSystem { Windows, Mac, Linux } public OperatingSystem buildOperatingSystem; public Text debugText; // Use this for initialization void Start() { //Disable this if your game is online only. if (Process.GetCurrentProcess().ToString() != "System.Diagnostics.Process (Unity)") CheckInternetUnity(); serverVersionFile = Path.Combine(Directory.GetCurrentDirectory(), serverVersionFile).Replace(@"\", "/"); //Ensures that it does not check for updates if you are running the game from the Editor. if (checkForUpdates && hasInternetConnection && serverFileListURL != "" && gameFullExe != "" && patcherFullExe != "" && Process.GetCurrentProcess().ToString() != "System.Diagnostics.Process (Unity)") { if (patcherFullExe.Contains(".exe")) { buildOperatingSystem = OperatingSystem.Windows; patcherNoExe = patcherFullExe.Replace(".exe", ""); } else if (patcherFullExe.Contains(".app")) { buildOperatingSystem = OperatingSystem.Mac; patcherNoExe = patcherFullExe.Replace(".app", ""); } else if (patcherFullExe.Contains(".x86")) { buildOperatingSystem = OperatingSystem.Linux; patcherNoExe = patcherFullExe.Replace(".x86", ""); } else patcherNoExe = patcherFullExe; //Starts Update Check in Background Thread. ThreadStart threadStart = delegate { CheckForUpdates(); }; new Thread(threadStart).Start(); } else { SceneManager.LoadScene(1); } } public bool CheckInternetConnection() { try { System.Net.NetworkInformation.Ping myPing = new System.Net.NetworkInformation.Ping(); string host = "google.com"; byte[] buffer = new byte[32]; int timeout = 1000; System.Net.NetworkInformation.PingOptions pingOptions = new System.Net.NetworkInformation.PingOptions(); System.Net.NetworkInformation.PingReply reply = myPing.Send(host, timeout, buffer, pingOptions); return (reply.Status == System.Net.NetworkInformation.IPStatus.Success); } catch { return false; } } public IEnumerator CheckInternetUnity() { WWW www = new WWW("http://www.google.com"); yield return www; if (string.IsNullOrEmpty(www.error)) hasInternetConnection = true; else hasInternetConnection = false; } void Update() { if (ActivitySpinner) { if (ActivitySpinner.gameObject.activeSelf) { Vector3 newRotation = new Vector3(0, 0, spinnerRotationSpeed) * Time.deltaTime; ActivitySpinner.transform.rotation *= Quaternion.Euler(newRotation); } } } void AddMessage(string message) { debugText.text += message + "\r\n"; UnityEngine.Debug.Log(message); } void CheckForUpdates() { serverDirectory = serverFileListURL.Replace("fileList.txt", ""); bool upToDate = false; upToDate = CheckFiles(); if (upToDate) { //Loads the next Scene in the project, you can load a scene by name here if you choose. SceneManager.LoadScene(1); } else { AddMessage("Failed to check for updates and patch successfully."); } } public bool CheckFiles() { bool _status = false; //Accepts all SSL Certificates ServicePointManager.ServerCertificateValidationCallback = delegate { return true; }; using (WebClient wc = new WebClient()) { AddMessage("Downloading server file md5 list " + serverFileListURL + " to " + serverVersionFile); try { wc.DownloadFile(serverFileListURL, serverVersionFile); } catch (Exception e) { AddMessage("failed to download server file list due to " + e); } } string[] _files = WriteSafeReadAllLines(serverVersionFile); TotalFilesCount = (_files.Length - 1); string _serverVersion = _files[0]; string _currentVersion = ""; string fullGameExeName = gameFullExe; if (buildOperatingSystem == OperatingSystem.Mac) { fullGameExeName = fullGameExeName + @".app/Contents/MacOS/" + fullGameExeName; patcherFullExe = patcherFullExe + @".app/Contents/MacOS/" + patcherFullExe; } string fullGamePath = Path.Combine(Directory.GetCurrentDirectory(), fullGameExeName).Replace(@"\", "/"); AddMessage("Full game path is " + fullGamePath + " patcherNoExe is " + patcherNoExe); using (var md5 = MD5.Create()) { using (var stream = File.OpenRead(fullGamePath)) { _currentVersion = BitConverter.ToString(md5.ComputeHash(stream)).Replace("-", "").ToLower(); AddMessage("Game current version is " + _currentVersion); } } if (_currentVersion != _serverVersion) { AddMessage("[UPDATE] Updating Client"); needsToUpdate = true; if (!checkForLauncherUpdates) GetFile(); } //AddMessage("Looking through " + _files.Length + " files for updates."); for (int i = 1; i < _files.Length; i++) { string[] _md5split = _files[i].Split('\t'); _md5split[0] = _md5split[0].Replace(@"\", "/"); FileCount = i; if (_md5split[0].Length > 4 && !_md5split[0].Contains(fullGameExeName)) { //AddMessage("Looking at file " + i + " " + _md5split[0] + " as it is a launcher file"); if (!File.Exists(_md5split[0]) && _md5split[0].Contains(patcherFullExe)) { AddMessage("Downloading Launcher"); updatingLauncher = true; launcher = _md5split[0]; launcherMD5 = _md5split[1]; } if (!File.Exists(_md5split[0]) && !_md5split[0].Contains(patcherNoExe)) { AddMessage("Updating due to not finding " + _md5split[0]); needsToUpdate = true; if (!checkForLauncherUpdates) GetFile(); } if (File.Exists(_md5split[0])) { using (var md5 = MD5.Create()) { using (var stream = new FileStream(_md5split[0], FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { string _mymd5 = (BitConverter.ToString(md5.ComputeHash(stream)).Replace("-", "").ToLower()); if (_mymd5 != _md5split[1]) { if (_md5split[0].Contains(patcherFullExe)) { AddMessage("Updating Launcher Executable"); updatingLauncher = true; launcher = _md5split[0]; launcherMD5 = _md5split[1]; AddMessage("Updating Launcher is " + updatingLauncher); } else if (_md5split[0].Contains(patcherNoExe)) { AddMessage("Updating Launcher Files due to mismatch md5"); updatingLauncherFiles = true; AddMessage("Updating " + _md5split[0] + " " + _md5split[1]); missingLauncherFiles.Add(_md5split[0], _md5split[1]); AddMessage("Missing Launcher File count is " + missingLauncherFiles.Count + " updatingLauncherFiles is " + updatingLauncherFiles); } else { AddMessage("Updating due to updated " + _md5split[0]); needsToUpdate = true; if (!checkForLauncherUpdates && !updatingLauncherFiles) GetFile(); } } } } } else if (!File.Exists(_md5split[0]) && _md5split[0].Contains(patcherNoExe)) { AddMessage("Updating Launcher Files due to them being missing."); updatingLauncherFiles = true; AddMessage("Updating " + _md5split[0] + " " + _md5split[1]); missingLauncherFiles.Add(_md5split[0], _md5split[1]); AddMessage("Missing Launcher File count is " + missingLauncherFiles.Count + " updatingLauncherFiles is " + updatingLauncherFiles); } } } if (updatingLauncher) { AddMessage("Downloading Launcher executable"); DownloadFile(launcher, launcherMD5); } if (updatingLauncherFiles) { AddMessage("Attempting to update launcher files now."); foreach (KeyValuePair<string, string> kvp in missingLauncherFiles) { AddMessage("Attempting to update " + kvp.Key + " " + kvp.Value); DownloadFile(kvp.Key, kvp.Value); } updatingLauncherFiles = false; updatingLauncher = false; } doneCheckingFiles = true; if (needsToUpdate && !updatingLauncher && !updatingLauncherFiles) GetFile(); _status = true; return _status; } //If you change the name of the Launcher, you must adjust the new exe name here as well. public void GetFile() { AddMessage("Updating Game."); string fullPatcherPath = Path.Combine(Directory.GetCurrentDirectory(), patcherFullExe).Replace(@"\", "/"); AddMessage("Full Patcher path is " + fullPatcherPath); if (buildOperatingSystem == OperatingSystem.Mac) { Process.Start(new ProcessStartInfo(fullPatcherPath, "--no-first-run") { UseShellExecute = false }); } else Process.Start(fullPatcherPath, serverFileListURL + " " + gameFullExe); Environment.Exit(0); } public void DownloadFile(string _fileName, string _serverMD5) { AddMessage("Starting Download for " + _fileName); try { if (Process.GetProcesses().Any(p => p.ProcessName == patcherNoExe)) { try { Process.GetProcessesByName(patcherNoExe).FirstOrDefault().Kill(); } catch { } } Process.GetProcessesByName(patcherNoExe).FirstOrDefault().Kill(); } catch { } using (WebClient wc = new WebClient()) { string _file = (serverDirectory + _fileName).Replace(@"\", "/"); CurrentFileName = "Downloading file: " + _fileName; string fullFilePath = Path.Combine(Directory.GetCurrentDirectory(), _fileName); fullFilePath = fullFilePath.Replace(@"\", "/"); try { if (!Directory.Exists(Path.GetDirectoryName(fullFilePath).Replace(@"\", "/"))) Directory.CreateDirectory(Path.GetDirectoryName(fullFilePath).Replace(@"\", "/")); } catch (Exception ex) { UnityEngine.Debug.Log("filename is " + _fileName + " " + ex); } try { AddMessage("Downloading from " + _file + " to " + fullFilePath); DownloadFileWC(new Uri(_file, UriKind.RelativeOrAbsolute), fullFilePath); } catch (Exception e) { UnityEngine.Debug.Log("failed to download file due to " + e); AddMessage("Failed to download file due to " + e); } } using (var md5 = MD5.Create()) { using (var stream = new FileStream(_fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { string _mymd5 = (BitConverter.ToString(md5.ComputeHash(stream)).Replace("-", "").ToLower()); AddMessage("[UPDATE] Newly downloaded mymd5: " + _mymd5 + " serverMD5: " + _serverMD5); if (downloadFailures < 10) { if (_mymd5 != _serverMD5) { downloadFailures++; DownloadFile(_fileName, _serverMD5); } else if (needsToUpdate && !updatingLauncherFiles) GetFile(); } else if (needsToUpdate && !updatingLauncherFiles) GetFile(); } } } public void DownloadFileWC(Uri uri, string destination) { using (var wc = new WebClient()) { wc.DownloadProgressChanged += HandleDownloadProgress; wc.DownloadFileCompleted += HandleDownloadComplete; try { var syncObj = new System.Object(); lock (syncObj) { AddMessage("Downloading from " + uri.ToString() + " to " + destination); wc.DownloadFileAsync(uri, destination, syncObj); //This would block the thread until download completes Monitor.Wait(syncObj); } } catch (Exception ex) { AddMessage("Failed to download file due to " + ex); } } } public void HandleDownloadComplete(object sender, AsyncCompletedEventArgs e) { lock (e.UserState) { AddMessage("Download complete, moving to next file"); //releases blocked thread Monitor.Pulse(e.UserState); } } public void HandleDownloadProgress(object sender, DownloadProgressChangedEventArgs e) { } public string[] WriteSafeReadAllLines(String path) { using (var csv = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) using (var sr = new StreamReader(csv)) { List<string> file = new List<string>(); while (!sr.EndOfStream) { file.Add(sr.ReadLine()); } return file.ToArray(); } } }
// $Id$ // // 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 Org.Apache.Etch.Bindings.Csharp.Msg; namespace Org.Apache.Etch.Bindings.Csharp.Transport.Fmt.Binary { /// <summary> /// Common elements for binary tagged data input and output. /// </summary> public class BinaryTaggedData : TaggedData { /// <summary> /// Sentinel which marks the end of a struct or array item list /// in a binary input or output stream. /// </summary> public class SentinelObject { public override string ToString() { return "NONE"; } } public static readonly SentinelObject NONE = new SentinelObject(); /// <summary> /// This is the current version of the protocol. /// </summary> public const sbyte VERSION = 3; public BinaryTaggedData() { // do nothing } /// <summary> /// Constructs the BinaryTaggedData. /// </summary> /// <param name="vf"></param> public BinaryTaggedData(ValueFactory vf) : base(vf) { } public override sbyte CheckValue(object value) { if (value == null) return TypeCode.NULL; else if (value == NONE) return TypeCode.NONE; Type type = value.GetType(); if (value is long) return CheckLong((long)value); else if (value is Int32) return CheckInteger((Int32)value); else if (value is short) return CheckShort((short)value); else if (value is SByte) return CheckByte((sbyte)value); else if (value is Double) return (sbyte)TypeCode.DOUBLE; else if (value is float) return (sbyte)TypeCode.FLOAT; else if (value is String) { String s = (String)value; if (s.Length == 0) return TypeCode.EMPTY_STRING; return TypeCode.STRING; } else if (value is Boolean) { if ((Boolean)value) return TypeCode.BOOLEAN_TRUE; return TypeCode.BOOLEAN_FALSE; } else if (value is StructValue) return TypeCode.CUSTOM; else if (value is Array) { Array a = (Array)value; //if (a.GetType() == typeof(Int32[])) // return TypeCode.INTS; //if (a.GetType() == typeof(Int16[])) // return TypeCode.SHORTS; //if (a.GetType() == typeof(Boolean[])) // return TypeCode.BOOLS; if (a.GetType() == typeof(SByte[])) return TypeCode.BYTES; //if (a.GetType() == typeof(Int64[])) // return TypeCode.LONGS; //if (a.GetType() == typeof(Single[])) // return TypeCode.FLOATS; //if (a.GetType() == typeof(Double[])) // return TypeCode.DOUBLES; return TypeCode.ARRAY; } return TypeCode.CUSTOM; } public override sbyte GetNativeTypeCode(Type c) { if (c == typeof(Boolean)) return TypeCode.BOOLEAN_TRUE; if (c == typeof(SByte)) return TypeCode.BYTE; if (c == typeof(short)) return TypeCode.SHORT; if (c == typeof(int)) return TypeCode.INT; if (c == typeof(long)) return TypeCode.LONG; if (c == typeof(float)) return TypeCode.FLOAT; if (c == typeof(double)) return TypeCode.DOUBLE; if (c == typeof(string)) return TypeCode.STRING; if (c == typeof(Object)) return TypeCode.ANY; return TypeCode.CUSTOM; } public override XType GetCustomStructType(Type c) { return vf.GetCustomStructType(c); } public override Type GetNativeType(sbyte type) { switch (type) { case TypeCode.BOOLEAN_TRUE: case TypeCode.BOOLEAN_FALSE: return typeof(Boolean); case TypeCode.BYTE: return typeof(sbyte); case TypeCode.SHORT: return typeof(short); case TypeCode.INT: return typeof(int); case TypeCode.LONG: return typeof(long); case TypeCode.FLOAT: return typeof(float); case TypeCode.DOUBLE: return typeof(double); case TypeCode.EMPTY_STRING: case TypeCode.STRING: return typeof(string); case TypeCode.ANY: return typeof(Object); default: throw new Exception("unsupported native type " + type); } } private static sbyte CheckByte(sbyte v) { if (v >= TypeCode.MIN_TINY_INT && v <= TypeCode.MAX_TINY_INT) return v; return TypeCode.BYTE; } private static sbyte CheckShort(short v) { if (v >= SByte.MinValue && v <= SByte.MaxValue) return CheckByte((sbyte)v); return TypeCode.SHORT; } private static sbyte CheckInteger(int v) { if (v >= short.MinValue && v <= short.MaxValue) return CheckShort((short)v); return TypeCode.INT; } private static sbyte CheckLong(long v) { if (v >= int.MinValue && v <= int.MaxValue) return CheckInteger((int)v); return TypeCode.LONG; } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace Dhgms.JobHelper.ApiWebSite.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Drawing; using System.Linq; using System.Windows.Forms; using NetGore.Editor; namespace NetGore.Features.NPCChat { /// <summary> /// A TreeNode for the <see cref="NPCChatDialogView"/>. /// </summary> [SuppressMessage("Microsoft.Usage", "CA2237:MarkISerializableTypesWithSerializable")] public class NPCChatDialogViewNode : TreeNode { NPCChatDialogViewNodeItemType _chatItemType; /// <summary> /// Initializes a new instance of the <see cref="NPCChatDialogViewNode"/> class. /// </summary> /// <param name="treeView">The tree view.</param> /// <param name="handledItem">The handled item.</param> internal NPCChatDialogViewNode(TreeView treeView, object handledItem) { Tag = handledItem; UpdateChatItemType(); treeView.Nodes.Add(this); TreeViewCasted.NotifyNodeCreated(this); Update(true); } /// <summary> /// Initializes a new instance of the <see cref="NPCChatDialogViewNode"/> class. /// </summary> /// <param name="parent">The parent.</param> /// <param name="handledItem">The handled item.</param> internal NPCChatDialogViewNode(TreeNode parent, object handledItem) { Tag = handledItem; UpdateChatItemType(); parent.Nodes.Add(this); TreeViewCasted.NotifyNodeCreated(this); UpdateText(); } /// <summary> /// Gets the NPC chat item that this <see cref="NPCChatDialogViewNode"/> handles. /// </summary> public object ChatItem { get { return Tag; } internal set { if (Tag == value) return; Tag = value; UpdateChatItemType(); UpdateText(); } } /// <summary> /// Gets the ChatItem as a <see cref="EditorNPCChatDialogItem"/>. If this is a ChatItemType is /// <see cref="NPCChatDialogViewNodeItemType.Redirect"/>, this will /// return the <see cref="EditorNPCChatDialogItem"/> that the node redirects to. /// </summary> /// <exception cref="MethodAccessException">Unsupported ChatItemType for this operation.</exception> [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "ChatItemType")] public EditorNPCChatDialogItem ChatItemAsDialogItem { get { if (ChatItemType == NPCChatDialogViewNodeItemType.DialogItem) return (EditorNPCChatDialogItem)ChatItem; else if (ChatItemType == NPCChatDialogViewNodeItemType.Redirect) return ChatItemAsRedirect.ChatItemAsDialogItem; else throw new MethodAccessException("Invalid ChatItemType for this method."); } } /// <summary> /// Gets the ChatItem as the NPCChatDialogViewNode containing the EditorNPCChatDialogItem that this /// NPCChatDialogViewNode redirects to. /// </summary> /// <exception cref="MethodAccessException">Unsupported ChatItemType for this operation.</exception> [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "ChatItemType")] public NPCChatDialogViewNode ChatItemAsRedirect { get { if (ChatItemType == NPCChatDialogViewNodeItemType.Redirect) return (NPCChatDialogViewNode)ChatItem; else throw new MethodAccessException("Invalid ChatItemType for this method."); } } /// <summary> /// Gets the ChatItem as a EditorNPCChatResponse. /// </summary> /// <exception cref="MethodAccessException">Unsupported ChatItemType for this operation.</exception> [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "ChatItemType")] public EditorNPCChatResponse ChatItemAsResponse { get { if (ChatItemType == NPCChatDialogViewNodeItemType.Response) return (EditorNPCChatResponse)ChatItem; else throw new MethodAccessException("Invalid ChatItemType for this method."); } } /// <summary> /// Gets the type of item stored in the ChatItem. /// </summary> public NPCChatDialogViewNodeItemType ChatItemType { get { return _chatItemType; } } /// <summary> /// Gets if the <see cref="NPCChatDialogViewNode"/> is dead (has been removed from the /// <see cref="TreeView"/> and is not coming back). /// </summary> public bool IsDead { get { return TreeView == null; } } /// <summary> /// Gets the Parent TreeNode casted to a NPCChatDialogViewNode. /// </summary> internal NPCChatDialogViewNode ParentCasted { get { return Parent as NPCChatDialogViewNode; } } /// <summary> /// Gets the TreeView casted to a NPCChatDialogView. /// </summary> NPCChatDialogView TreeViewCasted { get { return (NPCChatDialogView)TreeView; } } /// <summary> /// Creates a NPCChatDialogViewNode as a child of this NPCChatDialogViewNode. /// </summary> /// <param name="dialogItem">The NPCChatDialogItemBase the child node will handle.</param> /// <returns>A NPCChatDialogViewNode as a child of this NPCChatDialogViewNode.</returns> NPCChatDialogViewNode CreateNode(NPCChatDialogItemBase dialogItem) { // Check if the node already exists var children = Nodes.OfType<NPCChatDialogViewNode>(); var retNode = children.FirstOrDefault( x => (x.ChatItemType == NPCChatDialogViewNodeItemType.DialogItem || x.ChatItemType == NPCChatDialogViewNodeItemType.Redirect) && x.ChatItemAsDialogItem == dialogItem); // Create the new node if needed if (retNode == null) { // Check if it has to be a redirect node var existingDialogNode = TreeViewCasted.GetNodeForDialogItem(dialogItem); if (existingDialogNode != null) retNode = new NPCChatDialogViewNode(this, existingDialogNode); else retNode = new NPCChatDialogViewNode(this, dialogItem); } return retNode; } /// <summary> /// Creates a NPCChatDialogViewNode as a child of this NPCChatDialogViewNode. /// </summary> /// <param name="response">The NPCChatResponseBase the child node will handle.</param> /// <returns>A NPCChatDialogViewNode as a child of this NPCChatDialogViewNode.</returns> NPCChatDialogViewNode CreateNode(NPCChatResponseBase response) { // Check if the node already exists var children = Nodes.OfType<NPCChatDialogViewNode>(); var retNode = children.FirstOrDefault( x => x.ChatItemType == NPCChatDialogViewNodeItemType.Response && x.ChatItemAsResponse == response); if (retNode == null) retNode = new NPCChatDialogViewNode(this, response); return retNode; } /// <summary> /// Gets the text for a NPCChatDialogItemBase. /// </summary> /// <param name="item">The NPCChatDialogItemBase.</param> /// <returns>The text for a NPCChatDialogItemBase.</returns> static string GetText(NPCChatDialogItemBase item) { var text = item.Title; if (string.IsNullOrEmpty(text)) { text = item.Text; if (text.Length > 100) text = text.Substring(0, 100); } return text; } /// <summary> /// Gets if this NPCChatDialogViewNode is for the NPCChatDialogItemBase with the specified index. /// </summary> /// <param name="dialogItemIndex">The index of the NPCChatDialogItemBase.</param> /// <param name="includeRedirects">If true, this method will return true if the NPCChatDialogViewNode is /// for a redirection to the NPCChatDialogItemBase with the specified <paramref name="dialogItemIndex"/>; /// otherwise, only the NPCChatDialogViewNode that handles the NPCChatDialogItemBase with the /// specified <paramref name="dialogItemIndex"/> directly will return true.</param> /// <returns>True if this NPCChatDialogViewNode handles the NPCChatDialogItemBase with the specified /// <paramref name="dialogItemIndex"/>; otherwise false.</returns> public bool IsForDialogItem(ushort dialogItemIndex, bool includeRedirects) { switch (ChatItemType) { case NPCChatDialogViewNodeItemType.DialogItem: if (ChatItemAsDialogItem.ID == dialogItemIndex) return true; break; case NPCChatDialogViewNodeItemType.Redirect: if (includeRedirects && ChatItemAsDialogItem.ID == dialogItemIndex) return true; break; } return false; } /// <summary> /// Removes the current tree node from the tree view control. /// </summary> public new void Remove() { TreeViewCasted.NotifyNodeDestroyed(this); base.Remove(); } /// <summary> /// Updates this <see cref="NPCChatDialogViewNode"/>. /// </summary> /// <param name="recursive">If true, all nodes under this <see cref="NPCChatDialogViewNode"/> are updated, too.</param> /// <exception cref="ArgumentException">The <see cref="ChatItemType"/> is not a valid /// <see cref="NPCChatDialogViewNodeItemType"/>.</exception> public void Update(bool recursive) { var checkToSwapRedirectNodes = false; var childNodes = Nodes.OfType<NPCChatDialogViewNode>(); IEnumerable<NPCChatDialogViewNode> nodesToRemove = null; switch (ChatItemType) { case NPCChatDialogViewNodeItemType.DialogItem: // For a dialog item, add the responses var asDialogItem = ChatItemAsDialogItem; var validNodes = new List<NPCChatDialogViewNode>(asDialogItem.Responses.Count()); foreach (var response in asDialogItem.Responses) { validNodes.Add(CreateNode(response)); } // Mark dead nodes if (validNodes.Count != Nodes.Count) nodesToRemove = childNodes.Except(validNodes); break; case NPCChatDialogViewNodeItemType.Redirect: // For a redirect, there are no child nodes // Mark dead nodes if (Nodes.Count > 0) nodesToRemove = childNodes; break; case NPCChatDialogViewNodeItemType.Response: // For a response, add the dialog item, using a redirect if needed var dialogItem = TreeViewCasted.NPCChatDialog.GetDialogItem(ChatItemAsResponse.Page); NPCChatDialogViewNode validNode = null; if (dialogItem != null) { validNode = CreateNode(dialogItem); if (validNode.ChatItemType == NPCChatDialogViewNodeItemType.Redirect) checkToSwapRedirectNodes = true; } // Mark dead nodes if (Nodes.Count > (dialogItem != null ? 1 : 0)) nodesToRemove = childNodes.Where(x => x != validNode); break; default: const string errmsg = "Invalid ChatItemType `{0}`."; throw new ArgumentException(string.Format(errmsg, ChatItemType)); } // Remove the marked nodes to be removed if (nodesToRemove != null) { foreach (var node in nodesToRemove) { node.Remove(); } } // Update the text of this node UpdateText(); // Check to recursively update all the children nodes if (recursive) { foreach (var child in childNodes) { child.Update(true); } } // Check if to swap nodes so the redirect is as deep in the tree as possible // This must be done here at the end, otherwise we will disrupt the recursive update process // and some nodes will end up not appearing in the tree if (checkToSwapRedirectNodes) { foreach (var child in childNodes.Where(x => x.ChatItemType == NPCChatDialogViewNodeItemType.Redirect)) { var existing = TreeViewCasted.GetNodeForDialogItem(child.ChatItemAsDialogItem); var existingDepth = existing.GetDepth(); var childDepth = child.GetDepth(); if (existingDepth > childDepth) existing.SwapNode(child, existing.Nodes.Count <= 0); } } } /// <summary> /// Updates the <see cref="ChatItemAsDialogItem"/> property. /// </summary> /// <exception cref="ArgumentException">The <see cref="TreeNode.Tag"/> is not of an expected type.</exception> void UpdateChatItemType() { if (Tag is NPCChatDialogItemBase) _chatItemType = NPCChatDialogViewNodeItemType.DialogItem; else if (Tag is NPCChatResponseBase) _chatItemType = NPCChatDialogViewNodeItemType.Response; else if (Tag is TreeNode) _chatItemType = NPCChatDialogViewNodeItemType.Redirect; else { const string errmsg = "Invalid ChatItem type `{0}` (object: {1})."; throw new ArgumentException(string.Format(errmsg, Tag.GetType(), Tag)); } } /// <summary> /// Updates the text for this NPCChatDialogViewNode. /// </summary> /// <exception cref="InvalidOperationException">The <see cref="ChatItemType"/> is not of a defined /// <see cref="NPCChatDialogViewNodeItemType"/> value.</exception> [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "ChatItemType")] internal void UpdateText() { EditorNPCChatDialogItem asDialogItem; string text; Color foreColor; switch (ChatItemType) { case NPCChatDialogViewNodeItemType.Redirect: asDialogItem = ChatItemAsDialogItem; text = "[GOTO " + asDialogItem.ID + ": " + GetText(asDialogItem) + "]"; foreColor = TreeViewCasted.NodeForeColorGoTo; break; case NPCChatDialogViewNodeItemType.DialogItem: asDialogItem = ChatItemAsDialogItem; text = asDialogItem.ID + ": " + GetText(asDialogItem); foreColor = asDialogItem.IsBranch ? TreeViewCasted.NodeForeColorBranch : TreeViewCasted.NodeForeColorNormal; break; case NPCChatDialogViewNodeItemType.Response: EditorNPCChatResponse asResponse = ChatItemAsResponse; text = "[" + asResponse.Value + ": " + asResponse.Text + "]"; foreColor = TreeViewCasted.NodeForeColorResponse; break; default: const string errmsg = "Invalid ChatItemType `{0}`."; throw new InvalidOperationException(string.Format(errmsg, ChatItemType)); } Text = text; ForeColor = foreColor; } } }
/* **************************************************************************** * * Copyright (c) Microsoft Corporation. * * This source code is subject to terms and conditions of the Apache License, Version 2.0. A * copy of the license can be found in the License.html file at the root of this distribution. If * you cannot locate the Apache License, Version 2.0, please send an email to * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound * by the terms of the Apache License, Version 2.0. * * You must not remove this notice, or any other, from this software. * * * ***************************************************************************/ using System; using System.Reflection; using System.Runtime.CompilerServices; using IronPython.Runtime.Exceptions; using IronPython.Runtime.Operations; using Microsoft.Scripting.Actions; using Microsoft.Scripting.Generation; using Microsoft.Scripting.Utils; namespace IronPython.Runtime.Types { /// <summary> /// The unbound representation of an event property /// </summary> [PythonType("event#")] public sealed class ReflectedEvent : PythonTypeDataSlot, ICodeFormattable { private readonly bool _clsOnly; private readonly EventTracker/*!*/ _tracker; internal ReflectedEvent(EventTracker/*!*/ tracker, bool clsOnly) { Assert.NotNull(tracker); _clsOnly = clsOnly; _tracker = tracker; } #region Internal APIs internal override bool TryGetValue(CodeContext/*!*/ context, object instance, PythonType owner, out object value) { Assert.NotNull(context, owner); value = new BoundEvent(this, instance, owner); return true; } internal override bool GetAlwaysSucceeds { get { return true; } } internal override bool TrySetValue(CodeContext/*!*/ context, object instance, PythonType owner, object value) { Assert.NotNull(context); BoundEvent et = value as BoundEvent; if (et == null || EventInfosDiffer(et)) { BadEventChange bea = value as BadEventChange; if (bea != null) { PythonType dt = bea.Owner as PythonType; if (dt != null) { if (bea.Instance == null) { throw new MissingMemberException(String.Format("attribute '{1}' of '{0}' object is read-only", dt.Name, _tracker.Name)); } else { throw new MissingMemberException(String.Format("'{0}' object has no attribute '{1}'", dt.Name, _tracker.Name)); } } } throw ReadOnlyException(DynamicHelpers.GetPythonTypeFromType(Info.DeclaringType)); } return true; } private bool EventInfosDiffer(BoundEvent et) { // if they're the same object they're the same... if (et.Event.Info == this.Info) { return false; } // otherwise compare based upon type & metadata token (they // differ by ReflectedType) if (et.Event.Info.DeclaringType != Info.DeclaringType || et.Event.Info.MetadataToken != Info.MetadataToken) { return true; } return false; } internal override bool TryDeleteValue(CodeContext/*!*/ context, object instance, PythonType owner) { Assert.NotNull(context, owner); throw ReadOnlyException(DynamicHelpers.GetPythonTypeFromType(Info.DeclaringType)); } internal override bool IsAlwaysVisible { get { return !_clsOnly; } } #endregion #region Public Python APIs public string __doc__ { get { return DocBuilder.CreateAutoDoc(_tracker.Event); } } public EventInfo/*!*/ Info { [PythonHidden] get { return _tracker.Event; } } public EventTracker/*!*/ Tracker { [PythonHidden] get { return _tracker; } } /// <summary> /// BoundEvent is the object that gets returned when the user gets an event object. An /// BoundEvent tracks where the event was received from and is used to verify we get /// a proper add when dealing w/ statics events. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")] // TODO: fix public class BoundEvent { private readonly ReflectedEvent/*!*/ _event; private readonly PythonType/*!*/ _ownerType; private readonly object _instance; public ReflectedEvent/*!*/ Event { get { return _event; } } public BoundEvent(ReflectedEvent/*!*/ reflectedEvent, object instance, PythonType/*!*/ ownerType) { Assert.NotNull(reflectedEvent, ownerType); _event = reflectedEvent; _instance = instance; _ownerType = ownerType; } // this one's correct, InPlaceAdd is wrong but we still have some dependencies on the wrong name. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2225:OperatorOverloadsHaveNamedAlternates")] // TODO: fix [SpecialName] public object op_AdditionAssignment(CodeContext/*!*/ context, object func) { return InPlaceAdd(context, func); } [SpecialName] public object InPlaceAdd(CodeContext/*!*/ context, object func) { if (func == null || !PythonOps.IsCallable(context, func)) { throw PythonOps.TypeError("event addition expected callable object, got {0}", PythonTypeOps.GetName(func)); } if (_event.Tracker.IsStatic) { if (_ownerType != DynamicHelpers.GetPythonTypeFromType(_event.Tracker.DeclaringType)) { // mutating static event, only allow this from the type we're mutating, not sub-types return new BadEventChange(_ownerType, _instance); } } MethodInfo add = _event.Tracker.GetAddMethod(); // TODO (tomat): this used to use event.ReflectedType, is it still correct? if (_instance != null) { add = CompilerHelpers.TryGetCallableMethod(_instance.GetType(), add); } if (CompilerHelpers.IsVisible(add) || context.LanguageContext.DomainManager.Configuration.PrivateBinding) { _event.Tracker.AddHandler(_instance, func, context.LanguageContext.DelegateCreator); } else { throw new TypeErrorException("Cannot add handler to a private event."); } return this; } [SpecialName] public object InPlaceSubtract(CodeContext/*!*/ context, object func) { Assert.NotNull(context); if (func == null) { throw PythonOps.TypeError("event subtraction expected callable object, got None"); } if (_event.Tracker.IsStatic) { if (_ownerType != DynamicHelpers.GetPythonTypeFromType(_event.Tracker.DeclaringType)) { // mutating static event, only allow this from the type we're mutating, not sub-types return new BadEventChange(_ownerType, _instance); } } MethodInfo remove = _event.Tracker.GetRemoveMethod(); if (CompilerHelpers.IsVisible(remove) || context.LanguageContext.DomainManager.Configuration.PrivateBinding) { _event.Tracker.RemoveHandler(_instance, func, PythonContext.GetContext(context).EqualityComparer); } else { throw new TypeErrorException("Cannot add handler to a private event."); } return this; } } #endregion #region Private Helpers private class BadEventChange { private readonly PythonType/*!*/ _ownerType; private readonly object _instance; public BadEventChange(PythonType/*!*/ ownerType, object instance) { _ownerType = ownerType; _instance = instance; } public PythonType Owner { get { return _ownerType; } } public object Instance { get { return _instance; } } } private MissingMemberException/*!*/ ReadOnlyException(PythonType/*!*/ dt) { Assert.NotNull(dt); return new MissingMemberException(String.Format("attribute '{1}' of '{0}' object is read-only", dt.Name, _tracker.Name)); } #endregion #region ICodeFormattable Members public string/*!*/ __repr__(CodeContext/*!*/ context) { return string.Format("<event# {0} on {1}>", Info.Name, Info.DeclaringType.Name); } #endregion } }
// Copyright (c) 2015, Outercurve Foundation. // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // - Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // - Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // - Neither the name of the Outercurve Foundation nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using System; using System.IO; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Text; using System.Reflection; using System.Globalization; using Microsoft.Win32; using WebsitePanel.Providers; using WebsitePanel.Providers.HostedSolution; using WebsitePanel.Providers.Utils; using WebsitePanel.Server.Utils; using System.Management; using System.Management.Automation; using System.Management.Automation.Runspaces; using WebsitePanel.Providers.Common; using System.Runtime.InteropServices; using System.Linq; using WebsitePanel.Providers.DomainLookup; using WebsitePanel.Providers.DNS; namespace WebsitePanel.Providers.OS { public class Windows2012 : Windows2003 { #region Properties internal string PrimaryDomainController { get { return ProviderSettings["PrimaryDomainController"]; } } #endregion Properties public override bool IsInstalled() { Server.Utils.OS.WindowsVersion version = WebsitePanel.Server.Utils.OS.GetVersion(); return version == WebsitePanel.Server.Utils.OS.WindowsVersion.WindowsServer2012 || version == WebsitePanel.Server.Utils.OS.WindowsVersion.Windows8 || version == WebsitePanel.Server.Utils.OS.WindowsVersion.WindowsServer2012R2 || version == WebsitePanel.Server.Utils.OS.WindowsVersion.Windows81; } public override void SetQuotaLimitOnFolder(string folderPath, string shareNameDrive, QuotaType quotaType, string quotaLimit, int mode, string wmiUserName, string wmiPassword) { Log.WriteStart("SetQuotaLimitOnFolder"); Log.WriteInfo("FolderPath : {0}", folderPath); Log.WriteInfo("QuotaLimit : {0}", quotaLimit); string path = folderPath; if (shareNameDrive != null) path = Path.Combine(shareNameDrive + @":\", folderPath); Runspace runSpace = null; try { runSpace = OpenRunspace(); if (path.IndexOfAny(Path.GetInvalidPathChars()) == -1) { if (!FileUtils.DirectoryExists(path)) FileUtils.CreateDirectory(path); if (quotaLimit.Contains("-")) { RemoveOldQuotaOnFolder(runSpace, path); } else { var quota = CalculateQuota(quotaLimit); switch (mode) { //deleting old quota and creating new one case 0: { RemoveOldQuotaOnFolder(runSpace, path); ChangeQuotaOnFolder(runSpace, "New-FsrmQuota", path, quotaType, quota); break; } //modifying folder quota case 1: { ChangeQuotaOnFolder(runSpace, "Set-FsrmQuota", path, quotaType, quota); break; } } } } } catch (Exception ex) { Log.WriteError("SetQuotaLimitOnFolder", ex); throw; } finally { CloseRunspace(runSpace); } Log.WriteEnd("SetQuotaLimitOnFolder"); } public override Quota GetQuotaOnFolder(string folderPath, string wmiUserName, string wmiPassword) { Log.WriteStart("GetQuotaLimitOnFolder"); Log.WriteInfo("FolderPath : {0}", folderPath); Runspace runSpace = null; Quota quota = new Quota(); try { runSpace = OpenRunspace(); if (folderPath.IndexOfAny(Path.GetInvalidPathChars()) == -1) { Command cmd = new Command("Get-FsrmQuota"); cmd.Parameters.Add("Path", folderPath); var result = ExecuteShellCommand(runSpace, cmd, false); if (result.Count > 0) { quota.Size = ConvertBytesToMB(Convert.ToInt64(GetPSObjectProperty(result[0], "Size"))); quota.QuotaType = Convert.ToBoolean(GetPSObjectProperty(result[0], "SoftLimit")) ? QuotaType.Soft : QuotaType.Hard; quota.Usage = ConvertBytesToMB(Convert.ToInt64(GetPSObjectProperty(result[0], "usage"))); } } } catch (Exception ex) { Log.WriteError("GetQuotaLimitOnFolder", ex); throw; } finally { CloseRunspace(runSpace); } Log.WriteEnd("GetQuotaLimitOnFolder"); return quota; } public override Dictionary<string, Quota> GetQuotasForOrganization(string folderPath, string wmiUserName, string wmiPassword) { Log.WriteStart("GetQuotasLimitsForOrganization"); Runspace runSpace = null; Quota quota = null; var quotas = new Dictionary<string, Quota>(); try { runSpace = OpenRunspace(); Command cmd = new Command("Get-FsrmQuota"); cmd.Parameters.Add("Path", folderPath + "\\*"); var result = ExecuteShellCommand(runSpace, cmd, false); if (result.Count > 0) { foreach (var element in result) { quota = new Quota(); quota.Size = ConvertBytesToMB(Convert.ToInt64(GetPSObjectProperty(element, "Size"))); quota.QuotaType = Convert.ToBoolean(GetPSObjectProperty(element, "SoftLimit")) ? QuotaType.Soft : QuotaType.Hard; quota.Usage = ConvertBytesToMB(Convert.ToInt64(GetPSObjectProperty(element, "usage"))); quotas.Add(Convert.ToString(GetPSObjectProperty(element, "Path")), quota); } } } catch (Exception ex) { Log.WriteError("GetQuotasLimitsForOrganization", ex); throw; } finally { CloseRunspace(runSpace); } Log.WriteEnd("GetQuotasLimitsForOrganization"); return quotas; } public UInt64 CalculateQuota(string quota) { UInt64 OneKb = 1024; UInt64 OneMb = OneKb * 1024; UInt64 OneGb = OneMb * 1024; UInt64 result = 0; // Quota Unit if (quota.ToLower().Contains("gb")) { result = UInt64.Parse(quota.ToLower().Replace("gb", "")) * OneGb; } else if (quota.ToLower().Contains("mb")) { result = UInt64.Parse(quota.ToLower().Replace("mb", "")) * OneMb; } else { result = UInt64.Parse(quota.ToLower().Replace("kb", "")) * OneKb; } return result; } public int ConvertMegaBytesToGB(int megabytes) { int OneGb = 1024; if (megabytes == -1) return megabytes; return (int)(megabytes/ OneGb); } public int ConvertBytesToMB(long bytes) { int OneKb = 1024; int OneMb = OneKb * 1024; if (bytes == 0) return 0; return (int)(bytes / OneMb); } public void RemoveOldQuotaOnFolder(Runspace runSpace, string path) { try { runSpace = OpenRunspace(); if (!string.IsNullOrEmpty(path)) { Command cmd = new Command("Remove-FsrmQuota"); cmd.Parameters.Add("Path", path); ExecuteShellCommand(runSpace, cmd, false); } } catch { /* do nothing */ } } public void ChangeQuotaOnFolder(Runspace runSpace, string command, string path, QuotaType quotaType, UInt64 quota) { Command cmd = new Command(command); cmd.Parameters.Add("Path", path); cmd.Parameters.Add("Size", quota); if (quotaType == QuotaType.Soft) { cmd.Parameters.Add("SoftLimit", true); } ExecuteShellCommand(runSpace, cmd, false); } public override bool InstallFsrmService() { Log.WriteStart("InstallFsrmService"); Runspace runSpace = null; try { runSpace = OpenRunspace(); Command cmd = new Command("Install-WindowsFeature"); cmd.Parameters.Add("Name", "FS-Resource-Manager"); cmd.Parameters.Add("IncludeManagementTools", true); ExecuteShellCommand(runSpace, cmd, false); } catch (Exception ex) { Log.WriteError("InstallFsrmService", ex); return false; } finally { Log.WriteEnd("InstallFsrmService"); CloseRunspace(runSpace); } return true; } #region PowerShell integration private static InitialSessionState session = null; protected virtual Runspace OpenRunspace() { Log.WriteStart("OpenRunspace"); if (session == null) { session = InitialSessionState.CreateDefault(); session.ImportPSModule(new string[] { "FileServerResourceManager" }); } Runspace runSpace = RunspaceFactory.CreateRunspace(session); // runSpace.Open(); // runSpace.SessionStateProxy.SetVariable("ConfirmPreference", "none"); Log.WriteEnd("OpenRunspace"); return runSpace; } protected void CloseRunspace(Runspace runspace) { try { if (runspace != null && runspace.RunspaceStateInfo.State == RunspaceState.Opened) { runspace.Close(); } } catch (Exception ex) { Log.WriteError("Runspace error", ex); } } protected Collection<PSObject> ExecuteShellCommand(Runspace runSpace, Command cmd) { return ExecuteShellCommand(runSpace, cmd, true); } protected Collection<PSObject> ExecuteLocalScript(Runspace runSpace, List<string> scripts, out object[] errors, params string[] moduleImports) { return ExecuteRemoteScript(runSpace, null ,scripts, out errors, moduleImports); } protected Collection<PSObject> ExecuteRemoteScript(Runspace runSpace, string hostName, List<string> scripts, out object[] errors, params string[] moduleImports) { Command invokeCommand = new Command("Invoke-Command"); if (!string.IsNullOrEmpty(hostName)) { invokeCommand.Parameters.Add("ComputerName", hostName); } RunspaceInvoke invoke = new RunspaceInvoke(); string commandString = moduleImports.Any() ? string.Format("import-module {0};", string.Join(",", moduleImports)) : string.Empty; commandString = string.Format("{0};{1}", commandString, string.Join(";", scripts.ToArray())); ScriptBlock sb = invoke.Invoke(string.Format("{{{0}}}", commandString))[0].BaseObject as ScriptBlock; invokeCommand.Parameters.Add("ScriptBlock", sb); return ExecuteShellCommand(runSpace, invokeCommand, false, out errors); } protected Collection<PSObject> ExecuteShellCommand(Runspace runSpace, Command cmd, bool useDomainController) { object[] errors; return ExecuteShellCommand(runSpace, cmd, useDomainController, out errors); } internal Collection<PSObject> ExecuteShellCommand(Runspace runSpace, Command cmd, out object[] errors) { return ExecuteShellCommand(runSpace, cmd, true, out errors); } internal Collection<PSObject> ExecuteShellCommand(Runspace runSpace, Command cmd, bool useDomainController, out object[] errors) { Log.WriteStart("ExecuteShellCommand"); List<object> errorList = new List<object>(); if (useDomainController) { CommandParameter dc = new CommandParameter("DomainController", PrimaryDomainController); if (!cmd.Parameters.Contains(dc)) { cmd.Parameters.Add(dc); } } Collection<PSObject> results = null; // Create a pipeline Pipeline pipeLine = runSpace.CreatePipeline(); using (pipeLine) { // Add the command pipeLine.Commands.Add(cmd); // Execute the pipeline and save the objects returned. results = pipeLine.Invoke(); // Log out any errors in the pipeline execution // NOTE: These errors are NOT thrown as exceptions! // Be sure to check this to ensure that no errors // happened while executing the command. if (pipeLine.Error != null && pipeLine.Error.Count > 0) { foreach (object item in pipeLine.Error.ReadToEnd()) { errorList.Add(item); string errorMessage = string.Format("Invoke error: {0}", item); Log.WriteWarning(errorMessage); } } } pipeLine = null; errors = errorList.ToArray(); Log.WriteEnd("ExecuteShellCommand"); return results; } protected object GetPSObjectProperty(PSObject obj, string name) { return obj.Members[name].Value; } /// <summary> /// Returns the identity of the object from the shell execution result /// </summary> /// <param name="result"></param> /// <returns></returns> internal string GetResultObjectIdentity(Collection<PSObject> result) { Log.WriteStart("GetResultObjectIdentity"); if (result == null) throw new ArgumentNullException("result", "Execution result is not specified"); if (result.Count < 1) throw new ArgumentException("Execution result is empty", "result"); if (result.Count > 1) throw new ArgumentException("Execution result contains more than one object", "result"); PSMemberInfo info = result[0].Members["Identity"]; if (info == null) throw new ArgumentException("Execution result does not contain Identity property", "result"); string ret = info.Value.ToString(); Log.WriteEnd("GetResultObjectIdentity"); return ret; } internal string GetResultObjectDN(Collection<PSObject> result) { Log.WriteStart("GetResultObjectDN"); if (result == null) throw new ArgumentNullException("result", "Execution result is not specified"); if (result.Count < 1) throw new ArgumentException("Execution result does not contain any object"); if (result.Count > 1) throw new ArgumentException("Execution result contains more than one object"); PSMemberInfo info = result[0].Members["DistinguishedName"]; if (info == null) throw new ArgumentException("Execution result does not contain DistinguishedName property", "result"); string ret = info.Value.ToString(); Log.WriteEnd("GetResultObjectDN"); return ret; } #endregion } }
// // Copyright (c) 2004-2011 Jaroslaw Kowalski <jaak@jkowalski.net> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Layouts { using System; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using System.Text; using NLog.Common; using NLog.Conditions; using NLog.Config; using NLog.Internal; using NLog.LayoutRenderers; using NLog.LayoutRenderers.Wrappers; /// <summary> /// Parses layout strings. /// </summary> internal sealed class LayoutParser { internal static LayoutRenderer[] CompileLayout(ConfigurationItemFactory configurationItemFactory, SimpleStringReader sr, bool isNested, out string text) { var result = new List<LayoutRenderer>(); var literalBuf = new StringBuilder(); int ch; int p0 = sr.Position; while ((ch = sr.Peek()) != -1) { if (isNested && (ch == '}' || ch == ':')) { break; } sr.Read(); if (ch == '$' && sr.Peek() == '{') { if (literalBuf.Length > 0) { result.Add(new LiteralLayoutRenderer(literalBuf.ToString())); literalBuf.Length = 0; } LayoutRenderer newLayoutRenderer = ParseLayoutRenderer(configurationItemFactory, sr); if (CanBeConvertedToLiteral(newLayoutRenderer)) { newLayoutRenderer = ConvertToLiteral(newLayoutRenderer); } // layout renderer result.Add(newLayoutRenderer); } else { literalBuf.Append((char)ch); } } if (literalBuf.Length > 0) { result.Add(new LiteralLayoutRenderer(literalBuf.ToString())); literalBuf.Length = 0; } int p1 = sr.Position; MergeLiterals(result); text = sr.Substring(p0, p1); return result.ToArray(); } private static string ParseLayoutRendererName(SimpleStringReader sr) { int ch; var nameBuf = new StringBuilder(); while ((ch = sr.Peek()) != -1) { if (ch == ':' || ch == '}') { break; } nameBuf.Append((char)ch); sr.Read(); } return nameBuf.ToString(); } private static string ParseParameterName(SimpleStringReader sr) { int ch; int nestLevel = 0; var nameBuf = new StringBuilder(); while ((ch = sr.Peek()) != -1) { if ((ch == '=' || ch == '}' || ch == ':') && nestLevel == 0) { break; } if (ch == '$') { sr.Read(); nameBuf.Append('$'); if (sr.Peek() == '{') { nameBuf.Append('{'); nestLevel++; sr.Read(); } continue; } if (ch == '}') { nestLevel--; } if (ch == '\\') { // skip the backslash sr.Read(); // append next character nameBuf.Append((char)sr.Read()); continue; } nameBuf.Append((char)ch); sr.Read(); } return nameBuf.ToString(); } private static string ParseParameterValue(SimpleStringReader sr) { int ch; var nameBuf = new StringBuilder(); while ((ch = sr.Peek()) != -1) { if (ch == ':' || ch == '}') { break; } // Code in this condition was replaced // to support escape codes e.g. '\r' '\n' '\u003a', // which can not be used directly as they are used as tokens by the parser // All escape codes listed in the following link were included // in addition to "\{", "\}", "\:" which are NLog specific: // http://blogs.msdn.com/b/csharpfaq/archive/2004/03/12/what-character-escape-sequences-are-available.aspx if (ch == '\\') { // skip the backslash sr.Read(); var nextChar = (char)sr.Peek(); switch (nextChar) { case ':': sr.Read(); nameBuf.Append(':'); break; case '{': sr.Read(); nameBuf.Append('{'); break; case '}': sr.Read(); nameBuf.Append('}'); break; case '\'': sr.Read(); nameBuf.Append('\''); break; case '"': sr.Read(); nameBuf.Append('"'); break; case '\\': sr.Read(); nameBuf.Append('\\'); break; case '0': sr.Read(); nameBuf.Append('\0'); break; case 'a': sr.Read(); nameBuf.Append('\a'); break; case 'b': sr.Read(); nameBuf.Append('\b'); break; case 'f': sr.Read(); nameBuf.Append('\f'); break; case 'n': sr.Read(); nameBuf.Append('\n'); break; case 'r': sr.Read(); nameBuf.Append('\r'); break; case 't': sr.Read(); nameBuf.Append('\t'); break; case 'u': sr.Read(); var uChar = GetUnicode(sr, 4); // 4 digits nameBuf.Append(uChar); break; case 'U': sr.Read(); var UChar = GetUnicode(sr, 8); // 8 digits nameBuf.Append(UChar); break; case 'x': sr.Read(); var xChar = GetUnicode(sr, 4); // 1-4 digits nameBuf.Append(xChar); break; case 'v': sr.Read(); nameBuf.Append('\v'); break; } continue; } nameBuf.Append((char)ch); sr.Read(); } return nameBuf.ToString(); } private static char GetUnicode(SimpleStringReader sr, int maxDigits) { int code = 0; for (int cnt = 0; cnt < maxDigits; cnt++) { var digitCode = sr.Peek(); if (digitCode >= (int)'0' && digitCode <= (int)'9') digitCode = digitCode - (int)'0'; else if (digitCode >= (int)'a' && digitCode <= (int)'f') digitCode = digitCode - (int)'a' + 10; else if (digitCode >= (int)'A' && digitCode <= (int)'F') digitCode = digitCode - (int)'A' + 10; else break; sr.Read(); code = code * 16 + digitCode; } return (char)code; } private static LayoutRenderer ParseLayoutRenderer(ConfigurationItemFactory configurationItemFactory, SimpleStringReader sr) { int ch = sr.Read(); Debug.Assert(ch == '{', "'{' expected in layout specification"); string name = ParseLayoutRendererName(sr); LayoutRenderer lr = configurationItemFactory.LayoutRenderers.CreateInstance(name); var wrappers = new Dictionary<Type, LayoutRenderer>(); var orderedWrappers = new List<LayoutRenderer>(); ch = sr.Read(); while (ch != -1 && ch != '}') { string parameterName = ParseParameterName(sr).Trim(); if (sr.Peek() == '=') { sr.Read(); // skip the '=' PropertyInfo pi; LayoutRenderer parameterTarget = lr; if (!PropertyHelper.TryGetPropertyInfo(lr, parameterName, out pi)) { Type wrapperType; if (configurationItemFactory.AmbientProperties.TryGetDefinition(parameterName, out wrapperType)) { LayoutRenderer wrapperRenderer; if (!wrappers.TryGetValue(wrapperType, out wrapperRenderer)) { wrapperRenderer = configurationItemFactory.AmbientProperties.CreateInstance(parameterName); wrappers[wrapperType] = wrapperRenderer; orderedWrappers.Add(wrapperRenderer); } if (!PropertyHelper.TryGetPropertyInfo(wrapperRenderer, parameterName, out pi)) { pi = null; } else { parameterTarget = wrapperRenderer; } } } if (pi == null) { ParseParameterValue(sr); } else { if (typeof(Layout).IsAssignableFrom(pi.PropertyType)) { var nestedLayout = new SimpleLayout(); string txt; LayoutRenderer[] renderers = CompileLayout(configurationItemFactory, sr, true, out txt); nestedLayout.SetRenderers(renderers, txt); pi.SetValue(parameterTarget, nestedLayout, null); } else if (typeof(ConditionExpression).IsAssignableFrom(pi.PropertyType)) { var conditionExpression = ConditionParser.ParseExpression(sr, configurationItemFactory); pi.SetValue(parameterTarget, conditionExpression, null); } else { string value = ParseParameterValue(sr); PropertyHelper.SetPropertyFromString(parameterTarget, parameterName, value, configurationItemFactory); } } } else { // what we've just read is not a parameterName, but a value // assign it to a default property (denoted by empty string) PropertyInfo pi; if (PropertyHelper.TryGetPropertyInfo(lr, string.Empty, out pi)) { if (typeof(SimpleLayout) == pi.PropertyType) { pi.SetValue(lr, new SimpleLayout(parameterName), null); } else { string value = parameterName; PropertyHelper.SetPropertyFromString(lr, pi.Name, value, configurationItemFactory); } } else { InternalLogger.Warn("{0} has no default property", lr.GetType().FullName); } } ch = sr.Read(); } lr = ApplyWrappers(configurationItemFactory, lr, orderedWrappers); return lr; } private static LayoutRenderer ApplyWrappers(ConfigurationItemFactory configurationItemFactory, LayoutRenderer lr, List<LayoutRenderer> orderedWrappers) { for (int i = orderedWrappers.Count - 1; i >= 0; --i) { var newRenderer = (WrapperLayoutRendererBase)orderedWrappers[i]; InternalLogger.Trace("Wrapping {0} with {1}", lr.GetType().Name, newRenderer.GetType().Name); if (CanBeConvertedToLiteral(lr)) { lr = ConvertToLiteral(lr); } newRenderer.Inner = new SimpleLayout(new[] { lr }, string.Empty, configurationItemFactory); lr = newRenderer; } return lr; } private static bool CanBeConvertedToLiteral(LayoutRenderer lr) { foreach (IRenderable renderable in ObjectGraphScanner.FindReachableObjects<IRenderable>(lr)) { if (renderable.GetType() == typeof(SimpleLayout)) { continue; } if (!renderable.GetType().IsDefined(typeof(AppDomainFixedOutputAttribute), false)) { return false; } } return true; } private static void MergeLiterals(List<LayoutRenderer> list) { for (int i = 0; i + 1 < list.Count;) { var lr1 = list[i] as LiteralLayoutRenderer; var lr2 = list[i + 1] as LiteralLayoutRenderer; if (lr1 != null && lr2 != null) { lr1.Text += lr2.Text; list.RemoveAt(i + 1); } else { i++; } } } private static LayoutRenderer ConvertToLiteral(LayoutRenderer renderer) { return new LiteralLayoutRenderer(renderer.Render(LogEventInfo.CreateNullEvent())); } } }
using Lewis.SST.Controls; using Lewis.SST.DTSPackageClass; using Lewis.SST.SQLObjects; using System; using System.Collections; using System.ComponentModel; using System.Drawing; using System.Data; using System.Data.SqlClient; using System.IO; using System.Windows.Forms; using WeifenLuo.WinFormsUI.Docking; namespace Lewis.SST.Gui { /// <summary> /// Dialog class to display SQL server DTS packages and allow loading and saving of those DTS packages from or to XML files. /// </summary> public class DTSDoc : Document { private string _UID; private string _PWD; private DTSPackages m_dPack = new DTSPackages(); private System.Windows.Forms.Panel panelButtons; private System.Windows.Forms.Panel panelGrid; private System.Windows.Forms.DataGrid dataGrid1; private System.Windows.Forms.Button btn_GenXML; private System.Windows.Forms.ContextMenuStrip contextMenuTabPage; private System.Windows.Forms.ToolStripMenuItem menuItem3; private System.Windows.Forms.ToolStripMenuItem menuItem4; private System.Windows.Forms.ToolStripMenuItem menuItem5; private IContainer components; private string _Name; /// <summary> /// Initializes a new instance of the <see cref="DTS_Serializer"/> class. /// </summary> public DTSDoc(String name) { _Name = name; InitializeComponent(); this.TabText = _Name; this.Text = _Name; this.ToolTipText = _Name; btn_GenXML.FlatAppearance.BorderSize = 0; WireEvents(); SetupMenuIemSelectCompare(); } private void SetupMenuIemSelectCompare() { menuItem3.Name = "generateDTSXml"; menuItem3.Text = "Generate DTS XML Package File From Selected..."; menuItem3.Click += new EventHandler(generateDTS_Click); menuItem4.Name = "SyncXMLTree"; menuItem4.Text = "Synchronize in XML Node Explorer"; menuItem4.Visible = false; menuItem5.Name = "Close"; menuItem5.Text = "Close This"; menuItem5.Click += new EventHandler(closeThis_Click); } private void closeThis_Click(object sender, EventArgs e) { this.Close(); } private void generateDTS_Click(object sender, EventArgs e) { GenerateXMLPackage(); } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(DTSDoc)); this.panelButtons = new System.Windows.Forms.Panel(); this.btn_GenXML = new System.Windows.Forms.Button(); this.panelGrid = new System.Windows.Forms.Panel(); this.dataGrid1 = new System.Windows.Forms.DataGrid(); this.contextMenuTabPage = new System.Windows.Forms.ContextMenuStrip(this.components); this.menuItem3 = new System.Windows.Forms.ToolStripMenuItem(); this.menuItem4 = new System.Windows.Forms.ToolStripMenuItem(); this.menuItem5 = new System.Windows.Forms.ToolStripMenuItem(); this.panelButtons.SuspendLayout(); this.panelGrid.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.dataGrid1)).BeginInit(); this.contextMenuTabPage.SuspendLayout(); this.SuspendLayout(); // // panelButtons // this.panelButtons.Controls.Add(this.btn_GenXML); this.panelButtons.Dock = System.Windows.Forms.DockStyle.Bottom; this.panelButtons.Location = new System.Drawing.Point(0, 325); this.panelButtons.Name = "panelButtons"; this.panelButtons.Padding = new System.Windows.Forms.Padding(2); this.panelButtons.Size = new System.Drawing.Size(640, 32); this.panelButtons.TabIndex = 3; // // btn_GenXML // this.btn_GenXML.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.btn_GenXML.BackColor = System.Drawing.Color.Transparent; this.btn_GenXML.FlatAppearance.BorderColor = System.Drawing.Color.RoyalBlue; this.btn_GenXML.FlatAppearance.BorderSize = 0; this.btn_GenXML.FlatAppearance.MouseOverBackColor = System.Drawing.Color.LightSteelBlue; this.btn_GenXML.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.btn_GenXML.Image = ((System.Drawing.Image)(resources.GetObject("btn_GenXML.Image"))); this.btn_GenXML.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; this.btn_GenXML.Location = new System.Drawing.Point(519, 5); this.btn_GenXML.Name = "btn_GenXML"; this.btn_GenXML.Size = new System.Drawing.Size(116, 23); this.btn_GenXML.TabIndex = 0; this.btn_GenXML.Text = "Generate XML"; this.btn_GenXML.UseVisualStyleBackColor = false; this.btn_GenXML.MouseLeave += new System.EventHandler(this.btn_GenXML_MouseLeave); this.btn_GenXML.Click += new System.EventHandler(this.btn_GenXML_Click); this.btn_GenXML.MouseMove += new System.Windows.Forms.MouseEventHandler(this.btn_GenXML_MouseMove); // // panelGrid // this.panelGrid.Controls.Add(this.dataGrid1); this.panelGrid.Dock = System.Windows.Forms.DockStyle.Fill; this.panelGrid.Location = new System.Drawing.Point(0, 4); this.panelGrid.Name = "panelGrid"; this.panelGrid.Padding = new System.Windows.Forms.Padding(2); this.panelGrid.Size = new System.Drawing.Size(640, 321); this.panelGrid.TabIndex = 4; // // dataGrid1 // this.dataGrid1.BorderStyle = System.Windows.Forms.BorderStyle.None; this.dataGrid1.CaptionText = "DTS Packages"; this.dataGrid1.DataMember = ""; this.dataGrid1.Dock = System.Windows.Forms.DockStyle.Fill; this.dataGrid1.FlatMode = true; this.dataGrid1.HeaderForeColor = System.Drawing.SystemColors.ControlText; this.dataGrid1.Location = new System.Drawing.Point(2, 2); this.dataGrid1.Name = "dataGrid1"; this.dataGrid1.ReadOnly = true; this.dataGrid1.RowHeaderWidth = 5; this.dataGrid1.Size = new System.Drawing.Size(636, 317); this.dataGrid1.TabIndex = 1; // // contextMenuTabPage // this.contextMenuTabPage.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.menuItem3, this.menuItem4, this.menuItem5}); this.contextMenuTabPage.Name = "contextMenuTabPage"; this.contextMenuTabPage.Size = new System.Drawing.Size(127, 70); // // menuItem3 // this.menuItem3.Name = "menuItem3"; this.menuItem3.Size = new System.Drawing.Size(126, 22); this.menuItem3.Text = "Option &1"; // // menuItem4 // this.menuItem4.Name = "menuItem4"; this.menuItem4.Size = new System.Drawing.Size(126, 22); this.menuItem4.Text = "Option &2"; // // menuItem5 // this.menuItem5.Name = "menuItem5"; this.menuItem5.Size = new System.Drawing.Size(126, 22); this.menuItem5.Text = "Option &3"; // // DTS_Serializer // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(640, 357); this.Controls.Add(this.panelGrid); this.Controls.Add(this.panelButtons); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.Name = "DTS_Serializer"; this.Padding = new System.Windows.Forms.Padding(0, 4, 0, 0); this.TabPageContextMenuStrip = this.contextMenuTabPage; this.TabText = "(Local)"; this.Text = "(Local)"; this.panelButtons.ResumeLayout(false); this.panelGrid.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.dataGrid1)).EndInit(); this.contextMenuTabPage.ResumeLayout(false); this.ResumeLayout(false); } #endregion /// <summary> /// Refreshes the grid. /// </summary> public void RefreshGrid(SqlConnection sqlConnection) { m_dPack.GetObject<DTSPackages>(sqlConnection, false); if (m_dPack.Tables.Count > 0) { this.dataGrid1.DataSource = m_dPack.Tables[0]; } else { this.dataGrid1.DataSource = null; } dataGrid1.Focus(); } /// <summary> /// Refreshes the grid. /// </summary> /// <param name="MostRecentOnly">if set to <c>true</c> [most recent only].</param> public void RefreshGrid(SqlConnection sqlConnection, bool MostRecentOnly) { m_dPack.GetObject<DTSPackages>(sqlConnection, MostRecentOnly); if (m_dPack.Tables.Count > 0) { this.dataGrid1.DataSource = m_dPack.Tables[0]; } else { this.dataGrid1.DataSource = null; } dataGrid1.Focus(); } /// <summary> /// Refreshes the grid. /// </summary> /// <param name="UserID">The user ID.</param> /// <param name="Password">The password.</param> public void RefreshGrid(string UserID, string Password) { _UID = UserID; _PWD = Password; m_dPack.GetObject<DTSPackages>(null, this.Text, false, UserID, Password, false); if (m_dPack.Tables.Count > 0) { this.dataGrid1.DataSource = m_dPack.Tables[0]; } else { this.dataGrid1.DataSource = null; } dataGrid1.Focus(); } /// <summary> /// Refreshes the grid. /// </summary> /// <param name="UserID">The user ID.</param> /// <param name="Password">The password.</param> /// <param name="MostRecentOnly">if set to <c>true</c> [most recent only].</param> public void RefreshGrid(string UserID, string Password, bool MostRecentOnly) { _UID = UserID; _PWD = Password; m_dPack.GetObject<DTSPackages>(null, this.Text, false, UserID, Password, MostRecentOnly); if (m_dPack.Tables.Count > 0) { this.dataGrid1.DataSource = m_dPack.Tables[0]; } else { this.dataGrid1.DataSource = null; } dataGrid1.Focus(); } private void SerializePackageAsXML(string PackageName, string LogFileName, string Description, string packGUID, string verGUID) { Cursor.Current = Cursors.WaitCursor; try { DTSPackage2 oPackage = new DTSPackage2(PackageName, LogFileName, Description); // set the DTS package authentication type if (_UID != null && _PWD != null) { oPackage.Authentication = DTSPackage2.authTypeFlags.Default; } else { oPackage.Authentication = DTSPackage2.authTypeFlags.Trusted; } string SQLserver = this.TabText; // load the package from SQL server into the persisted object oPackage.Load(SQLserver, _UID, _PWD, null, packGUID, verGUID); m_DialogTitle = "Save DTS XML Package File as..."; m_DialogTypeFilter = "XML files (*.xml)|*.xml|All files (*.*)|*.*"; ArrayList arl = ShowSaveFileDialog(PackageName, m_DialogTitle, m_DialogTypeFilter); DialogResult dr = (DialogResult)arl[0]; if (dr == DialogResult.OK) { // save package from persisted object onto the HD as a file FileName = (string)arl[1]; // TODO: may want to do this async for bigger DTS packages oPackage.Save(FileName); // show xml XMLDoc xmlDoc = new XMLDoc(); xmlDoc.RightToLeftLayout = RightToLeftLayout; FileInfo fi = new FileInfo(FileName); xmlDoc.TabText = fi.Name; xmlDoc.Text = fi.Name; xmlDoc.ToolTipText = fi.Name; xmlDoc.FileName = FileName; xmlDoc.Show(this.DockPanel); } } catch(Exception ex) { Cursor.Current = Cursors.Default; MessageBox.Show("XML Serializer Error is: " + ex.Message, "SERIALIZER ERROR!", MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { Cursor.Current = Cursors.Default; } } public void GenerateXMLPackage() { DataTable dt = (DataTable)this.dataGrid1.DataSource; BindingManagerBase bmGrid; if (dt != null) { bmGrid = BindingContext[dt]; //int row = bmGrid.Position; if (bmGrid != null && bmGrid.Count > 0 && bmGrid.Current != null) { DataRowView drv = (DataRowView)bmGrid.Current; DataRow dr = drv.Row; string PackGUID = "{" + dr["id"].ToString().ToUpper() + "}"; string VerGUID = "{" + dr["versionid"].ToString().ToUpper() + "}"; string msgstr = string.Format("Serialize the following DTS package as XML?\n\nSQL Server: {0}\nPackage Name: {1}\nPackage ID: {2}\nVersion ID: {3}", this.TabText, dr["name"], PackGUID, VerGUID); DialogResult res = MessageBox.Show(this, msgstr, "Serialize DTS?", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (res == DialogResult.Yes) { SerializePackageAsXML(dr["name"].ToString(), "", dr["description"].ToString(), PackGUID, VerGUID); } } } } public DataTable gridDataSource { get { return (DataTable)this.dataGrid1.DataSource; } } private void btn_GenXML_Click(object sender, EventArgs e) { GenerateXMLPackage(); } private void btn_GenXML_MouseMove(object sender, MouseEventArgs e) { btn_GenXML.FlatAppearance.BorderSize = 1; // about 2 pixels wide it seems, TODO: make a button who's style is like the tool bar menu buttons in VS2005 } private void btn_GenXML_MouseLeave(object sender, EventArgs e) { btn_GenXML.FlatAppearance.BorderSize = 0; } } }
namespace ChoETL { #region NameSpaces using System; using System.Text; using System.Collections; using System.Collections.Generic; using System.Linq; #endregion /// <summary>Collection implemented with the properties of a binary heap.</summary> public class ChoBinaryHeap : ICollection, ICloneable { #region Member Variables /// <summary>The underlying array for the heap (ArrayList gives us resizing capability).</summary> private ArrayList _list; #endregion #region Construction /// <summary>Initialize the heap with another heap.</summary> /// <param name="heap">The heap on which to perform a shallow-copy.</param> public ChoBinaryHeap(ChoBinaryHeap heap) { // Clone the list (the only state we have) _list = (ArrayList)heap._list.Clone(); } /// <summary>Initialize the heap.</summary> /// <param name="capacity">The initial size of the heap.</param> public ChoBinaryHeap(int capacity) { _list = new ArrayList(capacity); } /// <summary>Initialize the heap.</summary> public ChoBinaryHeap() { _list = new ArrayList(); } #endregion #region Methods /// <summary>Empties the heap.</summary> public virtual void Clear() { _list.Clear(); } /// <summary>Performs a shallow-copy of the heap.</summary> /// <returns>A shallow-copy of the heap.</returns> public virtual ChoBinaryHeap Clone() { return new ChoBinaryHeap(this); } /// <summary>Determines whether an object is in the heap.</summary> /// <param name="value">The object for which we want to search.</param> /// <returns>Whether the object is in the heap.</returns> public virtual bool Contains(object value) { foreach (ChoBinaryHeapEntry entry in _list) { if (entry.Value == value) return true; } return false; } /// <summary>Adds an item to the heap.</summary> /// <param name="key">The key for this entry.</param> /// <param name="value">The value for this entry.</param> public virtual void Insert(IComparable key, object value) { // Create the entry based on the provided key and value ChoBinaryHeapEntry entry = new ChoBinaryHeapEntry(key, value); // Add the item to the list, making sure to keep track of where it was added. int pos = _list.Add(entry); // don't actually need it inserted yet, but want to make sure there's enough space for it // If it was added at the beginning, i.e. this is the only item, we're done. if (pos == 0) return; // Otherwise, perform log(n) operations, walking up the tree, swapping // where necessary based on key values while (pos > 0) { // Get the next position to check int nextPos = pos / 2; // Extract the entry at the next position ChoBinaryHeapEntry toCheck = (ChoBinaryHeapEntry)_list[nextPos]; // Compare that entry to our new one. If our entry has a larger key, move it up. // Otherwise, we're done. if (entry.CompareTo(toCheck) > 0) { _list[pos] = toCheck; pos = nextPos; } else break; } // Make sure we put this entry back in, just in case _list[pos] = entry; } /// <summary>Removes the entry at the top of the heap.</summary> /// <returns>The removed entry.</returns> public virtual object Remove() { // Get the first item and save it for later (this is what will be returned). if (_list.Count == 0) throw new InvalidOperationException("Cannot remove an item from the heap as it is empty."); object toReturn = ((ChoBinaryHeapEntry)_list[0]).Value; // Remove the first item _list.RemoveAt(0); // See if we can stop now (if there's only one item or we're empty, we're done) if (_list.Count > 1) { // Move the last element to the beginning _list.Insert(0, _list[_list.Count - 1]); _list.RemoveAt(_list.Count - 1); // Start reheapify int current = 0, possibleSwap = 0; // Keep going until the tree is a heap while (true) { // Get the positions of the node's children int leftChildPos = 2 * current + 1; int rightChildPos = leftChildPos + 1; // Should we swap with the left child? if (leftChildPos < _list.Count) { // Get the two entries to compare (node and its left child) ChoBinaryHeapEntry entry1 = (ChoBinaryHeapEntry)_list[current]; ChoBinaryHeapEntry entry2 = (ChoBinaryHeapEntry)_list[leftChildPos]; // If the child has a higher key than the parent, set that as a possible swap if (entry2.CompareTo(entry1) > 0) possibleSwap = leftChildPos; } else break; // if can't swap this, we're done // Should we swap with the right child? Note that now we check with the possible swap // position (which might be current and might be left child). if (rightChildPos < _list.Count) { // Get the two entries to compare (node and its left child) ChoBinaryHeapEntry entry1 = (ChoBinaryHeapEntry)_list[possibleSwap]; ChoBinaryHeapEntry entry2 = (ChoBinaryHeapEntry)_list[rightChildPos]; // If the child has a higher key than the parent, set that as a possible swap if (entry2.CompareTo(entry1) > 0) possibleSwap = rightChildPos; } // Now swap current and possible swap if necessary if (current != possibleSwap) { object temp = _list[current]; _list[current] = _list[possibleSwap]; _list[possibleSwap] = temp; } else break; // if nothing to swap, we're done // Update current to the location of the swap current = possibleSwap; } } // Return the item from the heap return toReturn; } public object[] ToArray() { List<object> array = new List<object>(); foreach (ChoBinaryHeapEntry entry in _list) array.Add(entry.Value); return array.ToArray(); } public object[] ToArray(Type type) { List<object> array = new List<object>(); foreach (ChoBinaryHeapEntry entry in _list) array.Add(entry.Value); return array.ToArray(); } #endregion #region Implementation of ICloneable /// <summary>Performs a shallow-copy of the heap.</summary> /// <returns>A shallow-copy of the heap.</returns> object ICloneable.Clone() { return Clone(); } #endregion #region Implementation of ICollection /// <summary>Copies the entire heap to a compatible one-dimensional array, starting at the given index.</summary> /// <param name="array">The array to which the heap should be copied.</param> /// <param name="index">The starting index.</param> public virtual void CopyTo(System.Array array, int index) { _list.CopyTo(array, index); } /// <summary>Gets a value indicating whether this heap is synchronized.</summary> public virtual bool IsSynchronized { get { return false; } } /// <summary>Gets the number of objects stored in the heap.</summary> public virtual int Count { get { return _list.Count; } } /// <summary>Gets an object which can be locked in order to synchronize this class.</summary> public object SyncRoot { get { return this; } } #endregion #region Implementation of IEnumerable /// <summary>Gets an enumerator for the heap.</summary> /// <returns>An enumerator for all elements of the heap.</returns> public virtual IEnumerator GetEnumerator() { return new ChoBinaryHeapEnumerator(_list.GetEnumerator()); } /// <summary>Enumerator for entries in the heap.</summary> public class ChoBinaryHeapEnumerator : IEnumerator { #region Member Variables /// <summary>The enumerator of the array list containing ChoBinaryHeapEntry objects.</summary> private IEnumerator _enumerator; #endregion #region Construction /// <summary>Initialize the enumerator</summary> /// <param name="enumerator">The array list enumerator.</param> internal ChoBinaryHeapEnumerator(IEnumerator enumerator) { _enumerator = enumerator; } #endregion #region Implementation of IEnumerator /// <summary>Resets the enumerator.</summary> public void Reset() { _enumerator.Reset(); } /// <summary>Moves to the next item in the list.</summary> /// <returns>Whether there are more items in the list.</returns> public bool MoveNext() { return _enumerator.MoveNext(); } /// <summary>Gets the current object in the list.</summary> public object Current { get { // Returns the value from the entry if it exists; otherwise, null. ChoBinaryHeapEntry entry = _enumerator.Current as ChoBinaryHeapEntry; return entry != null ? entry.Value : null; } } #endregion } #endregion #region Synchronization /// <summary>Ensures that heap is wrapped in a synchronous wrapper.</summary> /// <param name="heap">The heap to be wrapped.</param> /// <returns>A synchronized wrapper for the heap.</returns> public static ChoBinaryHeap Synchronize(ChoBinaryHeap heap) { // Create a synchronization wrapper around the heap and return it. if (heap is ChoSyncBinaryHeap) return heap; return new ChoSyncBinaryHeap(heap); } #endregion /// <summary>Represents an entry in a binary heap.</summary> private class ChoBinaryHeapEntry : IComparable, ICloneable { #region Member Variables /// <summary>The key for this entry.</summary> private IComparable _key; /// <summary>The value for this entry.</summary> private object _value; #endregion #region Construction /// <summary>Initializes an entry to be used in a binary heap.</summary> /// <param name="key">The key for this entry.</param> /// <param name="value">The value for this entry.</param> public ChoBinaryHeapEntry(IComparable key, object value) { _key = key; _value = value; } #endregion #region Properties /// <summary>Gets the key for this entry.</summary> public IComparable Key { get { return _key; } set { _key = value; } } /// <summary>Gets the value for this entry.</summary> public object Value { get { return _value; } set { _value = value; } } #endregion #region Implementation of IComparable /// <summary>Compares the current instance with another object of the same type.</summary> /// <param name="entry">An object to compare with this instance.</param> /// <returns> /// Less than 0 if this instance is less than the argument, /// 0 if the instances are equal, /// Greater than 0 if this instance is greater than the argument. /// </returns> public int CompareTo(ChoBinaryHeapEntry entry) { // Make sure we have valid arguments. if (entry == null) throw new ArgumentNullException("entry", "Cannot compare to a null value."); // Compare the keys return _key.CompareTo(entry.Key); } /// <summary>Compares the current instance with another object of the same type.</summary> /// <param name="obj">An object to compare with this instance.</param> /// <returns> /// Less than 0 if this instance is less than the argument, /// 0 if the instances are equal, /// Greater than 0 if this instance is greater than the argument. /// </returns> int IComparable.CompareTo(object obj) { // Make sure we have valid arguments, then compare. if (!(obj is ChoBinaryHeapEntry)) throw new ArgumentException("Object is not a ChoBinaryHeapEntry", "obj"); return CompareTo((ChoBinaryHeapEntry)obj); } #endregion #region Implementation of ICloneable /// <summary>Shallow-copy of the object.</summary> /// <returns>A shallow-copy of the object.</returns> public ChoBinaryHeapEntry Clone() { return new ChoBinaryHeapEntry(_key, _value); } /// <summary>Shallow-copy of the object.</summary> /// <returns>A shallow-copy of the object.</returns> object ICloneable.Clone() { return Clone(); } #endregion } /// <summary>A synchronized ChoBinaryHeap.</summary> public class ChoSyncBinaryHeap : ChoBinaryHeap { #region Member Variables /// <summary>The heap to synchronize.</summary> private ChoBinaryHeap _heap; #endregion #region Construction /// <summary>Initialize the synchronized heap.</summary> /// <param name="heap">The heap to synchronize.</param> internal ChoSyncBinaryHeap(ChoBinaryHeap heap) { _heap = heap; } #endregion #region Methods /// <summary>Performs a shallow-copy of the heap.</summary> /// <returns>A shallow-copy of the heap.</returns> public override ChoBinaryHeap Clone() { lock (_heap.SyncRoot) return _heap.Clone(); } /// <summary>Empties the heap.</summary> public override void Clear() { lock (_heap.SyncRoot) _heap.Clear(); } /// <summary>Determines whether an object is in the heap.</summary> /// <param name="value">The object for which we want to search.</param> /// <returns>Whether the object is in the heap.</returns> public override bool Contains(object value) { lock (_heap.SyncRoot) return _heap.Contains(value); } /// <summary>Adds an item to the heap.</summary> /// <param name="key">The key for this entry.</param> /// <param name="value">The value for this entry.</param> public override void Insert(IComparable key, object value) { lock (_heap.SyncRoot) _heap.Insert(key, value); } /// <summary>Removes the entry at the top of the heap.</summary> /// <returns>The removed entry.</returns> public override object Remove() { lock (_heap.SyncRoot) return _heap.Remove(); } /// <summary>Copies the entire heap to a compatible one-dimensional array, starting at the given index.</summary> /// <param name="array">The array to which the heap should be copied.</param> /// <param name="index">The starting index.</param> public override void CopyTo(System.Array array, int index) { lock (_heap.SyncRoot) _heap.CopyTo(array, index); } /// <summary>Gets a value indicating whether this heap is synchronized.</summary> public override bool IsSynchronized { get { return true; } } /// <summary>Gets the number of objects stored in the heap.</summary> public override int Count { get { lock (_heap.SyncRoot) return _heap.Count; } } /// <summary>Gets an enumerator for the heap.</summary> /// <returns>An enumerator for all elements of the heap.</returns> public override IEnumerator GetEnumerator() { lock (_heap.SyncRoot) return _heap.GetEnumerator(); } #endregion } } }
// // AudioCdSource.cs // // Author: // Aaron Bockover <abockover@novell.com> // // 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 System.Threading; using Mono.Unix; using Hyena; using Banshee.Base; using Banshee.ServiceStack; using Banshee.Sources; using Banshee.Library; using Banshee.Collection; using Banshee.Collection.Database; using Gtk; using Banshee.Gui; using Selection = Hyena.Collections.Selection; namespace Banshee.AudioCd { public class AudioCdSource : Source, ITrackModelSource, IUnmapableSource, IImportSource, IDurationAggregator, IFileSizeAggregator, IDisposable { private AudioCdService service; private AudioCdDiscModel disc_model; private SourceMessage query_message; public AudioCdSource (AudioCdService service, AudioCdDiscModel discModel) : base (Catalog.GetString ("Audio CD"), discModel.Title, 400) { this.service = service; this.disc_model = discModel; TypeUniqueId = ""; Properties.SetString ("TrackView.ColumnControllerXml", String.Format (@" <column-controller> <column> <renderer type=""Hyena.Data.Gui.ColumnCellCheckBox"" property=""RipEnabled""/> </column> <add-all-defaults /> </column-controller> ")); disc_model.MetadataQueryStarted += OnMetadataQueryStarted; disc_model.MetadataQueryFinished += OnMetadataQueryFinished; disc_model.EnabledCountChanged += OnEnabledCountChanged; disc_model.LoadModelFromDisc (); SetupGui (); } public TimeSpan Duration { get { return disc_model.Duration; } } public long FileSize { get { return disc_model.FileSize; } } public bool DiscIsPlaying { get { AudioCdTrackInfo playing_track = ServiceManager.PlayerEngine.CurrentTrack as AudioCdTrackInfo; return playing_track != null && playing_track.Model == disc_model; } } public void StopPlayingDisc () { if (DiscIsPlaying) { ServiceManager.PlayerEngine.Close (true); } } public void Dispose () { ClearMessages (); disc_model.MetadataQueryStarted -= OnMetadataQueryStarted; disc_model.MetadataQueryFinished -= OnMetadataQueryFinished; disc_model.EnabledCountChanged -= OnEnabledCountChanged; service = null; disc_model = null; } public AudioCdDiscModel DiscModel { get { return disc_model; } } private void OnEnabledCountChanged (object o, EventArgs args) { UpdateActions (); } private void OnMetadataQueryStarted (object o, EventArgs args) { if (query_message != null) { DestroyQueryMessage (); } query_message = new SourceMessage (this); query_message.FreezeNotify (); query_message.CanClose = false; query_message.IsSpinning = true; query_message.Text = Catalog.GetString ("Searching for track information..."); query_message.ThawNotify (); PushMessage (query_message); } private void OnMetadataQueryFinished (object o, EventArgs args) { if (disc_model.Title != Name) { Name = disc_model.Title; OnUpdated (); } if (disc_model.MetadataQuerySuccess) { DestroyQueryMessage (); if (DiscIsPlaying) { ServiceManager.PlayerEngine.TrackInfoUpdated (); } if (AudioCdService.AutoRip.Get ()) { BeginAutoRip (); } return; } if (query_message == null) { return; } query_message.FreezeNotify (); query_message.IsSpinning = false; query_message.SetIconName ("dialog-error"); query_message.Text = Catalog.GetString ("Could not fetch track information"); query_message.CanClose = true; query_message.ThawNotify (); } private void DestroyQueryMessage () { if (query_message != null) { RemoveMessage (query_message); query_message = null; } } private void BeginAutoRip () { // Make sure the album isn't already in the Library TrackInfo track = disc_model[0]; int count = ServiceManager.DbConnection.Query<int> ( @"SELECT Count(*) FROM CoreTracks, CoreArtists, CoreAlbums WHERE CoreTracks.PrimarySourceID = ? AND CoreTracks.ArtistID = CoreArtists.ArtistID AND CoreTracks.AlbumID = CoreAlbums.AlbumID AND CoreArtists.Name = ? AND CoreAlbums.Title = ? AND (CoreTracks.Disc = ? OR CoreTracks.Disc = 0)", ServiceManager.SourceManager.MusicLibrary.DbId, track.ArtistName, track.AlbumTitle, track.DiscNumber ); if (count > 0) { SetStatus (Catalog.GetString ("Automatic import off since this album is already in the Music Library."), true, false, null); return; } Log.DebugFormat ("Beginning auto rip of {0}", Name); ImportDisc (); } internal void ImportDisc () { AudioCdRipper ripper = null; try { if (AudioCdRipper.Supported) { ripper = new AudioCdRipper (this); ripper.Finished += OnRipperFinished; ripper.Start (); } } catch (Exception e) { if (ripper != null) { ripper.Dispose (); } Log.Error (Catalog.GetString ("Could not import CD"), e.Message, true); Log.Exception (e); } } private void OnRipperFinished (object o, EventArgs args) { if (AudioCdService.EjectAfterRipped.Get ()) { Unmap (); } } internal void DuplicateDisc () { try { AudioCdDuplicator.Duplicate (disc_model); } catch (Exception e) { Hyena.Log.Error (Catalog.GetString ("Could not duplicate audio CD"), e.Message, true); Hyena.Log.Exception (e); } } internal void LockAllTracks () { StopPlayingDisc (); foreach (AudioCdTrackInfo track in disc_model) { track.CanPlay = false; } disc_model.NotifyUpdated (); } internal void UnlockAllTracks () { foreach (AudioCdTrackInfo track in disc_model) { track.CanPlay = true; } disc_model.NotifyUpdated (); } internal void UnlockTrack (AudioCdTrackInfo track) { track.CanPlay = true; disc_model.NotifyUpdated (); } #region Source Overrides public override int Count { get { return disc_model.Count; } } public override string PreferencesPageId { get { return "audio-cd"; } } public override bool HasEditableTrackProperties { get { return true; } } public override bool HasViewableTrackProperties { get { return true; } } #endregion #region ITrackModelSource Implementation public TrackListModel TrackModel { get { return disc_model; } } public AlbumListModel AlbumModel { get { return null; } } public ArtistListModel ArtistModel { get { return null; } } public void Reload () { disc_model.Reload (); } public void RemoveTracks (Selection selection) { } public void DeleteTracks (Selection selection) { } public bool CanAddTracks { get { return false; } } public bool CanRemoveTracks { get { return false; } } public bool CanDeleteTracks { get { return false; } } public bool ConfirmRemoveTracks { get { return false; } } public virtual bool CanRepeat { get { return true; } } public virtual bool CanShuffle { get { return true; } } public bool ShowBrowser { get { return false; } } public bool HasDependencies { get { return false; } } public bool Indexable { get { return false; } } #endregion #region IUnmapableSource Implementation public bool Unmap () { StopPlayingDisc (); foreach (TrackInfo track in disc_model) { track.CanPlay = false; } OnUpdated (); SourceMessage eject_message = new SourceMessage (this); eject_message.FreezeNotify (); eject_message.IsSpinning = true; eject_message.CanClose = false; eject_message.Text = Catalog.GetString ("Ejecting audio CD..."); eject_message.ThawNotify (); PushMessage (eject_message); ThreadPool.QueueUserWorkItem (delegate { try { disc_model.Volume.Unmount (); disc_model.Volume.Eject (); ThreadAssist.ProxyToMain (delegate { service.UnmapDiscVolume (disc_model.Volume.Uuid); Dispose (); }); } catch (Exception e) { ThreadAssist.ProxyToMain (delegate { ClearMessages (); eject_message.IsSpinning = false; eject_message.SetIconName ("dialog-error"); eject_message.Text = String.Format (Catalog.GetString ("Could not eject audio CD: {0}"), e.Message); PushMessage (eject_message); foreach (TrackInfo track in disc_model) { track.CanPlay = true; } OnUpdated (); }); Log.Exception (e); } }); return true; } public bool CanUnmap { get { return DiscModel != null ? !DiscModel.IsDoorLocked : true; } } public bool ConfirmBeforeUnmap { get { return false; } } #endregion #region GUI/ThickClient private bool actions_loaded = false; private void SetupGui () { Properties.SetStringList ("Icon.Name", "media-cdrom", "gnome-dev-cdrom-audio", "source-cd-audio"); Properties.SetString ("SourcePreferencesActionLabel", Catalog.GetString ("Audio CD Preferences")); Properties.SetString ("UnmapSourceActionLabel", Catalog.GetString ("Eject Disc")); Properties.SetString ("UnmapSourceActionIconName", "media-eject"); Properties.SetString ("ActiveSourceUIResource", "ActiveSourceUI.xml"); Properties.SetString ("GtkActionPath", "/AudioCdContextMenu"); actions_loaded = true; UpdateActions (); } private void UpdateActions () { InterfaceActionService uia_service = ServiceManager.Get<InterfaceActionService> (); if (uia_service == null) { return; } Gtk.Action rip_action = uia_service.GlobalActions["RipDiscAction"]; if (rip_action != null) { string title = disc_model.Title; int max_title_length = 20; title = title.Length > max_title_length ? String.Format ("{0}\u2026", title.Substring (0, max_title_length).Trim ()) : title; rip_action.Label = String.Format (Catalog.GetString ("Import \u201f{0}\u201d"), title); rip_action.ShortLabel = Catalog.GetString ("Import CD"); rip_action.IconName = "media-import-audio-cd"; rip_action.Sensitive = AudioCdRipper.Supported && disc_model.EnabledCount > 0; } Gtk.Action duplicate_action = uia_service.GlobalActions["DuplicateDiscAction"]; if (duplicate_action != null) { duplicate_action.IconName = "media-cdrom"; duplicate_action.Visible = AudioCdDuplicator.Supported; } } protected override void OnUpdated () { if (actions_loaded) { UpdateActions (); } base.OnUpdated (); } #endregion #region IImportSource void IImportSource.Import () { ImportDisc (); } string [] IImportSource.IconNames { get { return Properties.GetStringList ("Icon.Name"); } } bool IImportSource.CanImport { get { return true; } } int IImportSource.SortOrder { get { return -10; } } string IImportSource.ImportLabel { get { return null; } } #endregion } }
#if (UNITY_IPHONE || UNITY_ANDROID || UNITY_WP8) #define TOUCH_SCREEN_KEYBOARD #endif using UnityEngine; using System.Collections; /// <summary> /// TextInput control /// </summary> [ExecuteInEditMode] [AddComponentMenu("2D Toolkit/UI/tk2dUITextInput")] public class tk2dUITextInput : MonoBehaviour { /// <summary> /// UItem that will make cause TextInput to become selected on click /// </summary> public tk2dUIItem selectionBtn; /// <summary> /// TextMesh while text input will be displayed /// </summary> public tk2dTextMesh inputLabel; /// <summary> /// TextMesh that will be displayed if nothing in inputLabel and is not selected /// </summary> public tk2dTextMesh emptyDisplayLabel; /// <summary> /// State to be active if text input is not selected /// </summary> public GameObject unSelectedStateGO; /// <summary> /// Stated to be active if text input is selected /// </summary> public GameObject selectedStateGO; /// <summary> /// Text cursor to be displayed at next of text input on selection /// </summary> public GameObject cursor; /// <summary> /// How long the field is (visible) /// </summary> public float fieldLength = 1; /// <summary> /// Maximum number of characters allowed for input /// </summary> public int maxCharacterLength = 30; /// <summary> /// Text to be displayed when no text is entered and text input is not selected /// </summary> public string emptyDisplayText; /// <summary> /// If set to true (is a password field), then all characters will be replaced with password char /// </summary> public bool isPasswordField = false; /// <summary> /// Each character in the password field is replaced with the first character of this string /// Default: * if string is empty. /// </summary> public string passwordChar = "*"; [SerializeField] [HideInInspector] private tk2dUILayout layoutItem = null; public tk2dUILayout LayoutItem { get { return layoutItem; } set { if (layoutItem != value) { if (layoutItem != null) { layoutItem.OnReshape -= LayoutReshaped; } layoutItem = value; if (layoutItem != null) { layoutItem.OnReshape += LayoutReshaped; } } } } private bool isSelected = false; private bool wasStartedCalled = false; private bool wasOnAnyPressEventAttached = false; #if TOUCH_SCREEN_KEYBOARD private TouchScreenKeyboard keyboard = null; #endif private bool listenForKeyboardText = false; private bool isDisplayTextShown =false; public System.Action<tk2dUITextInput> OnTextChange; public string SendMessageOnTextChangeMethodName = ""; public GameObject SendMessageTarget { get { if (selectionBtn != null) { return selectionBtn.sendMessageTarget; } else return null; } set { if (selectionBtn != null && selectionBtn.sendMessageTarget != value) { selectionBtn.sendMessageTarget = value; #if UNITY_EDITOR UnityEditor.EditorUtility.SetDirty(selectionBtn); #endif } } } public bool IsFocus { get { return isSelected; } } private string text = ""; /// <summary> /// Update the input text /// </summary> public string Text { get { return text; } set { if (text != value) { text = value; if (text.Length > maxCharacterLength) { text = text.Substring(0, maxCharacterLength); } FormatTextForDisplay(text); if (isSelected) { SetCursorPosition(); } } } } void Awake() { SetState(); ShowDisplayText(); } void Start() { wasStartedCalled = true; if (tk2dUIManager.Instance__NoCreate != null) { tk2dUIManager.Instance.OnAnyPress += AnyPress; } wasOnAnyPressEventAttached = true; } void OnEnable() { if (wasStartedCalled && !wasOnAnyPressEventAttached) { if (tk2dUIManager.Instance__NoCreate != null) { tk2dUIManager.Instance.OnAnyPress += AnyPress; } } if (layoutItem != null) { layoutItem.OnReshape += LayoutReshaped; } selectionBtn.OnClick += InputSelected; } void OnDisable() { if (tk2dUIManager.Instance__NoCreate != null) { tk2dUIManager.Instance.OnAnyPress -= AnyPress; if (listenForKeyboardText) { tk2dUIManager.Instance.OnInputUpdate -= ListenForKeyboardTextUpdate; } } wasOnAnyPressEventAttached = false; selectionBtn.OnClick -= InputSelected; listenForKeyboardText = false; if (layoutItem != null) { layoutItem.OnReshape -= LayoutReshaped; } } public void SetFocus() { SetFocus(true); } /// <summary> /// Sets or removes focus from the text input /// Currently you will need to manually need to remove focus and set focus on the new /// textinput if you wish to do this from a textInput callback, eg. auto advance when /// enter is pressed. /// </summary> public void SetFocus(bool focus) { if (!IsFocus && focus) { InputSelected(); } else if (IsFocus && !focus) { InputDeselected(); } } private void FormatTextForDisplay(string modifiedText) { if (isPasswordField) { int charLength = modifiedText.Length; char passwordReplaceChar = ( passwordChar.Length > 0 ) ? passwordChar[0] : '*'; modifiedText = ""; modifiedText=modifiedText.PadRight(charLength, passwordReplaceChar); } inputLabel.text = modifiedText; inputLabel.Commit(); while (inputLabel.renderer.bounds.extents.x * 2 > fieldLength) { modifiedText=modifiedText.Substring(1, modifiedText.Length - 1); inputLabel.text = modifiedText; inputLabel.Commit(); } if (modifiedText.Length==0 && !listenForKeyboardText) { ShowDisplayText(); } else { HideDisplayText(); } } private void ListenForKeyboardTextUpdate() { bool change = false; string newText = text; //http://docs.unity3d.com/Documentation/ScriptReference/Input-inputString.html string inputStr = Input.inputString; char c; for (int i=0; i<inputStr.Length; i++) { c = inputStr[i]; if (c == "\b"[0]) { if (text.Length != 0) { newText = text.Substring(0, text.Length - 1); change = true; } } else if (c == "\n"[0] || c == "\r"[0]) { } else if ((int)c!=9 && (int)c!=27) //deal with a Mac only Unity bug where it returns a char for escape and tab { newText += c; change = true; } } if (change) { Text = newText; if (OnTextChange != null) { OnTextChange(this); } if (SendMessageTarget != null && SendMessageOnTextChangeMethodName.Length > 0) { SendMessageTarget.SendMessage( SendMessageOnTextChangeMethodName, this, SendMessageOptions.RequireReceiver ); } } } private void InputSelected() { if (text.Length == 0) { HideDisplayText(); } isSelected = true; if (!listenForKeyboardText) { tk2dUIManager.Instance.OnInputUpdate += ListenForKeyboardTextUpdate; } listenForKeyboardText = true; SetState(); SetCursorPosition(); #if TOUCH_SCREEN_KEYBOARD if (Application.platform != RuntimePlatform.WindowsEditor && Application.platform != RuntimePlatform.OSXEditor) { #if UNITY_ANDROID //due to a delete key bug in Unity Android TouchScreenKeyboard.hideInput = false; #else TouchScreenKeyboard.hideInput = true; #endif keyboard = TouchScreenKeyboard.Open(text, TouchScreenKeyboardType.Default, false, false, false, false); StartCoroutine(TouchScreenKeyboardLoop()); } #endif } #if TOUCH_SCREEN_KEYBOARD private IEnumerator TouchScreenKeyboardLoop() { while (keyboard != null && !keyboard.done && keyboard.active) { Text = keyboard.text; yield return null; } if (keyboard != null) { Text = keyboard.text; } if (isSelected) { InputDeselected(); } } #endif private void InputDeselected() { if (text.Length == 0) { ShowDisplayText(); } isSelected = false; if (listenForKeyboardText) { tk2dUIManager.Instance.OnInputUpdate -= ListenForKeyboardTextUpdate; } listenForKeyboardText = false; SetState(); #if TOUCH_SCREEN_KEYBOARD if (keyboard!=null && !keyboard.done) { keyboard.active = false; } keyboard = null; #endif } private void AnyPress() { if (isSelected && tk2dUIManager.Instance.PressedUIItem != selectionBtn) { InputDeselected(); } } private void SetState() { tk2dUIBaseItemControl.ChangeGameObjectActiveStateWithNullCheck(unSelectedStateGO, !isSelected); tk2dUIBaseItemControl.ChangeGameObjectActiveStateWithNullCheck(selectedStateGO, isSelected); tk2dUIBaseItemControl.ChangeGameObjectActiveState(cursor, isSelected); } private void SetCursorPosition() { float multiplier = 1; float cursorOffset = 0.002f; if (inputLabel.anchor == TextAnchor.MiddleLeft || inputLabel.anchor == TextAnchor.LowerLeft || inputLabel.anchor == TextAnchor.UpperLeft) { multiplier = 2; } else if (inputLabel.anchor == TextAnchor.MiddleRight || inputLabel.anchor == TextAnchor.LowerRight || inputLabel.anchor == TextAnchor.UpperRight) { multiplier = -2; cursorOffset = 0.012f; } if (text.EndsWith(" ")) { tk2dFontChar chr; if (inputLabel.font.useDictionary) { chr = inputLabel.font.charDict[' ']; } else { chr = inputLabel.font.chars[' ']; } cursorOffset += chr.advance * inputLabel.scale.x/2; } cursor.transform.localPosition = new Vector3(inputLabel.transform.localPosition.x + (inputLabel.renderer.bounds.extents.x + cursorOffset) * multiplier, cursor.transform.localPosition.y, cursor.transform.localPosition.z); } private void ShowDisplayText() { if (!isDisplayTextShown) { isDisplayTextShown = true; if (emptyDisplayLabel != null) { emptyDisplayLabel.text = emptyDisplayText; emptyDisplayLabel.Commit(); tk2dUIBaseItemControl.ChangeGameObjectActiveState(emptyDisplayLabel.gameObject, true); } tk2dUIBaseItemControl.ChangeGameObjectActiveState(inputLabel.gameObject, false); } } private void HideDisplayText() { if (isDisplayTextShown) { isDisplayTextShown = false; tk2dUIBaseItemControl.ChangeGameObjectActiveStateWithNullCheck(emptyDisplayLabel.gameObject, false); tk2dUIBaseItemControl.ChangeGameObjectActiveState(inputLabel.gameObject, true); } } private void LayoutReshaped(Vector3 dMin, Vector3 dMax) { fieldLength += (dMax.x - dMin.x); // No way to trigger re-format yet string tmpText = this.text; text = ""; Text = tmpText; } }
using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using Juice.Framework; using Juice.Framework.TypeConverters; namespace Juice { /// <summary> /// Extend a Control with the jQuery UI Sortable behavior http://api.jqueryui.com/sortable/ /// </summary> [TargetControlType(typeof(WebControl))] [TargetControlType(typeof(System.Web.UI.HtmlControls.HtmlControl))] [WidgetEvent("create")] [WidgetEvent("start")] [WidgetEvent("sort")] [WidgetEvent("change")] [WidgetEvent("beforeStop")] [WidgetEvent("update")] [WidgetEvent("over")] [WidgetEvent("out")] [WidgetEvent("activate")] [WidgetEvent("deactivate")] public class Sortable : JuiceExtender { public Sortable() : base("sortable") { } #region Widget Options /// <summary> /// Defines where the helper that moves with the mouse is being appended to during the drag (for example, to resolve overlap/zIndex issues). /// Reference: http://api.jqueryui.com/sortable/#option-appendTo /// </summary> [WidgetOption("appendTo", "parent")] [Category("Behavior")] [DefaultValue("parent")] [Description("Defines where the helper that moves with the mouse is being appended to during the drag (for example, to resolve overlap/zIndex issues).")] public string AppendTo { get; set; } /// <summary> /// If defined, the items can be dragged only horizontally or vertically. Possible values:'x', 'y'. /// Reference: http://api.jqueryui.com/sortable/#option-axis /// </summary> [WidgetOption("axis", false)] [Category("Behavior")] [DefaultValue(false)] [Description("If defined, the items can be dragged only horizontally or vertically. Possible values:'x', 'y'.")] [TypeConverter(typeof(StringToObjectConverter))] public dynamic Axis { get; set; } /// <summary> /// Prevents sorting if you start on elements matching the selector. /// Reference: http://api.jqueryui.com/sortable/#option-cancel /// </summary> [WidgetOption("cancel", ":input,button")] [Category("Behavior")] [DefaultValue(":input,button")] [Description("Prevents sorting if you start on elements matching the selector.")] public string Cancel { get; set; } /// <summary> /// Takes a jQuery selector with items that also have sortables applied. If used, the sortable is now connected to the other one-way, so you can drag from this sortable to the other. /// Reference: http://api.jqueryui.com/sortable/#option-connectWith /// </summary> [WidgetOption("connectWith", false)] [Category("Behavior")] [DefaultValue(false)] [Description("Takes a jQuery selector with items that also have sortables applied. If used, the sortable is now connected to the other one-way, so you can drag from this sortable to the other.")] [TypeConverter(typeof(StringToObjectConverter))] public dynamic ConnectWith { get; set; } /// <summary> /// Constrains dragging to within the bounds of the specified element - can be a DOM element, 'parent', 'document', 'window', or a jQuery selector. /// Note: the element specified for containment must have a calculated width and height (though it need not be explicit), so for example, if you have float:left sortable children and specify containment:'parent' be sure to have float:left on the sortable/parent container as well or it will have height: 0, causing undefined behavior. /// Reference: http://api.jqueryui.com/sortable/#option-containment /// </summary> [WidgetOption("containment", false)] [Category("Behavior")] [DefaultValue(false)] [Description("Constrains dragging to within the bounds of the specified element - can be a DOM element, 'parent', 'document', 'window', or a jQuery selector. \nNote: the element specified for containment must have a calculated width and height (though it need not be explicit), so for example, if you have float:left sortable children and specify containment:'parent' be sure to have float:left on the sortable/parent container as well or it will have height: 0, causing undefined behavior.")] [TypeConverter(typeof(StringToObjectConverter))] public dynamic Containment { get; set; } /// <summary> /// Defines the cursor that is being shown while sorting. /// Reference: http://api.jqueryui.com/sortable/#option-cursor /// </summary> [WidgetOption("cursor", "auto")] [Category("Appearance")] [DefaultValue("auto")] [Description("Defines the cursor that is being shown while sorting.")] public string Cursor { get; set; } /// <summary> /// Moves the sorting element or helper so the cursor always appears to drag from the same position. Coordinates can be given as a hash using a combination of one or two keys: { top, left, right, bottom }. /// Reference: http://api.jqueryui.com/sortable/#option-cursorAt /// </summary> [WidgetOption("cursorAt", "{}", Eval=true)] [Category("Behavior")] [DefaultValue("{}")] [Description("Moves the sorting element or helper so the cursor always appears to drag from the same position. Coordinates can be given as a hash using a combination of one or two keys: { top, left, right, bottom }.")] public string CursorAt { get; set; } /// <summary> /// Time in milliseconds to define when the sorting should start. It helps preventing unwanted drags when clicking on an element. /// Reference: http://api.jqueryui.com/sortable/#option-delay /// </summary> [WidgetOption("delay", 0)] [Category("Behavior")] [DefaultValue(0)] [Description("Time in milliseconds to define when the sorting should start. It helps preventing unwanted drags when clicking on an element.")] public int Delay { get; set; } /// <summary> /// Tolerance, in pixels, for when sorting should start. If specified, sorting will not start until after mouse is dragged beyond distance. Can be used to allow for clicks on elements within a handle. /// Reference: http://api.jqueryui.com/sortable/#option-distance /// </summary> [WidgetOption("distance", 1)] [Category("Behavior")] [DefaultValue(1)] [Description("Tolerance, in pixels, for when sorting should start. If specified, sorting will not start until after mouse is dragged beyond distance. Can be used to allow for clicks on elements within a handle.")] public int Distance { get; set; } /// <summary> /// If false items from this sortable can't be dropped to an empty linked sortable. /// Reference: http://api.jqueryui.com/sortable/#option-dropOnEmpty /// </summary> [WidgetOption("dropOnEmpty", true)] [Category("Behavior")] [DefaultValue(true)] [Description("If false items from this sortable can't be dropped to an empty linked sortable.")] public bool DropOnEmpty { get; set; } /// <summary> /// If true, forces the helper to have a size. /// Reference: http://api.jqueryui.com/sortable/#option-forceHelperSize /// </summary> [WidgetOption("forceHelperSize", false)] [Category("Behavior")] [DefaultValue(false)] [Description("If true, forces the helper to have a size.")] public bool ForceHelperSize { get; set; } /// <summary> /// If true, forces the placeholder to have a size. /// Reference: http://api.jqueryui.com/sortable/#option-forcePlaceholderSize /// </summary> [WidgetOption("forcePlaceholderSize", false)] [Category("Behavior")] [DefaultValue(false)] [Description("If true, forces the placeholder to have a size.")] public bool ForcePlaceholderSize { get; set; } /// <summary> /// Snaps the sorting element or helper to a grid, every x and y pixels. Array values: [x, y] /// Reference: http://api.jqueryui.com/sortable/#option-grid /// </summary> [WidgetOption("grid", null)] [TypeConverter(typeof(Int32ArrayConverter))] [Category("Behavior")] [DefaultValue(null)] [Description("Snaps the sorting element or helper to a grid, every x and y pixels. Array values: [x, y]")] public int[] Grid { get; set; } /// <summary> /// Restricts sort start click to the specified element. /// Reference: http://api.jqueryui.com/sortable/#option-handle /// </summary> [WidgetOption("handle", false)] [Category("Behavior")] [DefaultValue(false)] [Description("Restricts sort start click to the specified element.")] [TypeConverter(typeof(StringToObjectConverter))] public dynamic Handle { get; set; } /// <summary> /// Allows for a helper element to be used for dragging display. Possible values: 'original', 'clone' /// Reference: http://api.jqueryui.com/sortable/#option-helper /// </summary> [WidgetOption("helper", "original")] [Category("Behavior")] [DefaultValue("original")] [Description("Allows for a helper element to be used for dragging display. Possible values: 'original', 'clone'")] public string Helper { get; set; } /// <summary> /// Specifies which items inside the element should be sortable. /// Reference: http://api.jqueryui.com/sortable/#option-items /// </summary> [WidgetOption("items", "> *")] [Category("Behavior")] [DefaultValue("> *")] [Description("Specifies which items inside the element should be sortable.")] public string Items { get; set; } /// <summary> /// Defines the opacity of the helper while sorting. From 0.01 to 1 /// Reference: http://api.jqueryui.com/sortable/#option-opacity /// </summary> [WidgetOption("opacity", 1)] [Category("Appearance")] [DefaultValue(1)] [Description("Defines the opacity of the helper while sorting. From 0.01 to 1")] public float Opacity { get; set; } /// <summary> /// Class that gets applied to the otherwise white space. /// Reference: http://api.jqueryui.com/sortable/#option-placeholder /// </summary> [WidgetOption("placeholder", false)] [Category("Appearance")] [DefaultValue(false)] [Description("Class that gets applied to the otherwise white space.")] [TypeConverter(typeof(StringToObjectConverter))] public dynamic Placeholder { get; set; } /// <summary> /// If set to true, the item will be reverted to its new DOM position with a smooth animation. Optionally, it can also be set to a number that controls the duration of the animation in ms. /// Reference: http://api.jqueryui.com/sortable/#option-revert /// </summary> [WidgetOption("revert", false)] [Category("Behavior")] [DefaultValue(false)] [Description("If set to true, the item will be reverted to its new DOM position with a smooth animation. Optionally, it can also be set to a number that controls the duration of the animation in ms.")] [TypeConverter(typeof(StringToObjectConverter))] public dynamic Revert { get; set; } /// <summary> /// If set to true, the page scrolls when coming to an edge. /// Reference: http://api.jqueryui.com/sortable/#option-scroll /// </summary> [WidgetOption("scroll", true)] [Category("Behavior")] [DefaultValue(true)] [Description("If set to true, the page scrolls when coming to an edge.")] public bool Scroll { get; set; } /// <summary> /// Defines how near the mouse must be to an edge to start scrolling. /// Reference: http://api.jqueryui.com/sortable/#option-scrollSensitivity /// </summary> [WidgetOption("scrollSensitivity", 20)] [Category("Behavior")] [DefaultValue(20)] [Description("Defines how near the mouse must be to an edge to start scrolling.")] public int ScrollSensitivity { get; set; } /// <summary> /// The speed at which the window should scroll once the mouse pointer gets within the scrollSensitivity distance. /// Reference: http://api.jqueryui.com/sortable/#option-scrollSpeed /// </summary> [WidgetOption("scrollSpeed", 20)] [Category("Behavior")] [DefaultValue(20)] [Description("The speed at which the window should scroll once the mouse pointer gets within the scrollSensitivity distance.")] public int ScrollSpeed { get; set; } /// <summary> /// This is the way the reordering behaves during drag. Possible values: 'intersect', 'pointer'. In some setups, 'pointer' is more natural. /// Reference: http://api.jqueryui.com/sortable/#option-tolerance /// </summary> [WidgetOption("tolerance", "intersect")] [Category("Behavior")] [DefaultValue("intersect")] [Description("This is the way the reordering behaves during drag. Possible values: 'intersect', 'pointer'. In some setups, 'pointer' is more natural.")] public string Tolerance { get; set; } /// <summary> /// Z-index for element/helper while being sorted. /// Reference: http://api.jqueryui.com/sortable/#option-zIndex /// </summary> [WidgetOption("zIndex", 1000)] [Category("Layout")] [DefaultValue(1000)] [Description("Z-index for element/helper while being sorted.")] public int ZIndex { get; set; } #endregion #region Widget Events /// <summary> /// This event is triggered when sorting has stopped. /// Reference: http://api.jqueryui.com/sortable/#event-stop /// </summary> [WidgetEvent("stop")] [Category("Action")] [Description("This event is triggered when sorting has stopped.")] public event EventHandler Stop; /// <summary> /// This event is triggered when a connected sortable list has received an item from another list. /// Reference: http://api.jqueryui.com/sortable/#event-receive /// </summary> [WidgetEvent("receive")] [Category("Action")] [Description("This event is triggered when a connected sortable list has received an item from another list.")] public event EventHandler Receive; /// <summary> /// This event is triggered when a sortable item has been dragged out from the list and into another. /// Reference: http://api.jqueryui.com/sortable/#event-remove /// </summary> [WidgetEvent("remove")] [Category("Action")] [Description("This event is triggered when a sortable item has been dragged out from the list and into another.")] public event EventHandler Remove; #endregion } }
namespace Gu.Wpf.UiAutomation.UiTests.Elements { using System; using NUnit.Framework; public class DataGridCellTests { private const string ExeFileName = "WpfApplication.exe"; [OneTimeTearDown] public void OneTimeTearDown() { Application.KillLaunched(ExeFileName); } [TestCase("DataGrid", false)] [TestCase("DataGrid10", false)] [TestCase("DataGridNoHeaders", false)] [TestCase("ReadOnlyDataGrid", true)] [TestCase("ReadonlyColumnsDataGrid", true)] [TestCase("TemplateColumnDataGrid", false)] public void IsReadOnly(string name, bool expected) { using var app = Application.AttachOrLaunch(ExeFileName, "DataGridWindow"); var window = app.MainWindow; var dataGrid = window.FindDataGrid(name); Assert.AreEqual(expected, dataGrid[0, 0].IsReadOnly); Assert.AreEqual(expected, dataGrid[0, 1].IsReadOnly); Assert.AreEqual(expected, dataGrid[1, 0].IsReadOnly); Assert.AreEqual(expected, dataGrid[1, 1].IsReadOnly); Assert.AreEqual(expected, dataGrid[2, 0].IsReadOnly); Assert.AreEqual(expected, dataGrid[2, 1].IsReadOnly); if (name != "ReadOnlyDataGrid") { Assert.AreEqual(expected, dataGrid[3, 0].IsReadOnly); Assert.AreEqual(expected, dataGrid[3, 1].IsReadOnly); } } [TestCase("DataGrid")] [TestCase("DataGrid10")] [TestCase("DataGridNoHeaders")] [TestCase("ReadOnlyDataGrid")] [TestCase("ReadonlyColumnsDataGrid")] [TestCase("TemplateColumnDataGrid")] public void ContainingGrid(string name) { using var app = Application.AttachOrLaunch(ExeFileName, "DataGridWindow"); var window = app.MainWindow; var dataGrid = window.FindDataGrid(name); Assert.AreEqual(dataGrid, dataGrid[0, 0].ContainingDataGrid); Assert.AreEqual(dataGrid, dataGrid[0, 1].ContainingDataGrid); Assert.AreEqual(dataGrid, dataGrid[1, 0].ContainingDataGrid); Assert.AreEqual(dataGrid, dataGrid[1, 1].ContainingDataGrid); Assert.AreEqual(dataGrid, dataGrid[2, 0].ContainingDataGrid); Assert.AreEqual(dataGrid, dataGrid[2, 1].ContainingDataGrid); } [TestCase("DataGrid")] [TestCase("DataGrid10")] [TestCase("DataGridNoHeaders")] [TestCase("TemplateColumnDataGrid")] public void NewItemPlaceholder(string name) { using var app = Application.AttachOrLaunch(ExeFileName, "DataGridWindow"); var window = app.MainWindow; var dataGrid = window.FindDataGrid(name); Assert.AreEqual(false, dataGrid[0, 0].IsNewItemPlaceholder); Assert.AreEqual(true, dataGrid[dataGrid.RowCount - 1, 0].IsNewItemPlaceholder); Assert.AreEqual(string.Empty, dataGrid[dataGrid.RowCount - 1, 0].Value); Assert.AreEqual(true, dataGrid[dataGrid.RowCount - 1, 1].IsNewItemPlaceholder); Assert.AreEqual(string.Empty, dataGrid[dataGrid.RowCount - 1, 1].Value); } [TestCase("DataGrid")] [TestCase("DataGrid10")] [TestCase("DataGridNoHeaders")] public void Enter(string name) { using var app = Application.Launch(ExeFileName, "DataGridWindow"); var window = app.MainWindow; var dataGrid = window.FindDataGrid(name); Assert.AreEqual("1", dataGrid[0, 0].Value); Assert.AreEqual("Item 1", dataGrid[0, 1].Value); Assert.AreEqual("2", dataGrid[1, 0].Value); Assert.AreEqual("Item 2", dataGrid[1, 1].Value); Assert.AreEqual("3", dataGrid[2, 0].Value); Assert.AreEqual("Item 3", dataGrid[2, 1].Value); dataGrid[0, 0].Enter("11"); Assert.AreEqual("1", dataGrid[0, 0].Value); Assert.AreEqual("11", dataGrid[0, 0].FindTextBox().Text); Assert.AreEqual("Item 1", dataGrid[0, 1].Value); Assert.AreEqual("2", dataGrid[1, 0].Value); Assert.AreEqual("Item 2", dataGrid[1, 1].Value); Assert.AreEqual("3", dataGrid[2, 0].Value); Assert.AreEqual("Item 3", dataGrid[2, 1].Value); dataGrid[1, 1].Click(); Assert.AreEqual("11", dataGrid[0, 0].Value); Assert.AreEqual("11", dataGrid[0, 0].FindTextBlock().Text); Assert.AreEqual("Item 1", dataGrid[0, 1].Value); Assert.AreEqual("2", dataGrid[1, 0].Value); Assert.AreEqual("Item 2", dataGrid[1, 1].Value); Assert.AreEqual("3", dataGrid[2, 0].Value); Assert.AreEqual("Item 3", dataGrid[2, 1].Value); dataGrid[0, 0].Enter("111"); Assert.AreEqual("11", dataGrid[0, 0].Value); Assert.AreEqual("Item 1", dataGrid[0, 1].Value); Assert.AreEqual("2", dataGrid[1, 0].Value); Assert.AreEqual("Item 2", dataGrid[1, 1].Value); Assert.AreEqual("3", dataGrid[2, 0].Value); Assert.AreEqual("Item 3", dataGrid[2, 1].Value); } [Test] public void EnterTemplateColumn() { using var app = Application.Launch(ExeFileName, "DataGridWindow"); var window = app.MainWindow; var dataGrid = window.FindDataGrid("TemplateColumnDataGrid"); Assert.AreEqual("1", dataGrid[0, 0].Value); Assert.AreEqual("Item 1", dataGrid[0, 1].Value); Assert.AreEqual("2", dataGrid[1, 0].Value); Assert.AreEqual("Item 2", dataGrid[1, 1].Value); Assert.AreEqual("3", dataGrid[2, 0].Value); Assert.AreEqual("Item 3", dataGrid[2, 1].Value); dataGrid[0, 0].Enter("11"); Assert.AreEqual("11", dataGrid[0, 0].Value); Assert.AreEqual("11", dataGrid[0, 0].FindTextBox().Text); Assert.AreEqual("Item 1", dataGrid[0, 1].Value); Assert.AreEqual("2", dataGrid[1, 0].Value); Assert.AreEqual("Item 2", dataGrid[1, 1].Value); Assert.AreEqual("3", dataGrid[2, 0].Value); Assert.AreEqual("Item 3", dataGrid[2, 1].Value); dataGrid[0, 0].Enter("111"); Assert.AreEqual("111", dataGrid[0, 0].Value); Assert.AreEqual("Item 1", dataGrid[0, 1].Value); Assert.AreEqual("2", dataGrid[1, 0].Value); Assert.AreEqual("Item 2", dataGrid[1, 1].Value); Assert.AreEqual("3", dataGrid[2, 0].Value); Assert.AreEqual("Item 3", dataGrid[2, 1].Value); } [TestCase("DataGrid")] [TestCase("SelectCellDataGrid")] public void EnterInvalidValue(string name) { using var app = Application.Launch(ExeFileName, "DataGridWindow"); var window = app.MainWindow; var dataGrid = window.FindDataGrid(name); var cell = dataGrid[0, 0]; Assert.AreEqual("1", cell.Value); cell.Enter("a"); Keyboard.Type(Key.TAB); Keyboard.Type(Key.TAB); Keyboard.Type(Key.TAB); Assert.AreEqual("1", cell.Value); Assert.AreEqual("a", cell.FindTextBox().Text); cell.Enter("11"); Keyboard.Type(Key.TAB); Keyboard.Type(Key.TAB); Keyboard.Type(Key.TAB); Assert.AreEqual("11", cell.Value); Assert.AreEqual("11", cell.FindTextBlock().Text); } [Test] public void EnterInvalidValueTemplateColumn() { using var app = Application.Launch(ExeFileName, "DataGridWindow"); var window = app.MainWindow; var dataGrid = window.FindDataGrid("TemplateColumnDataGrid"); var cell = dataGrid[0, 0]; Assert.AreEqual("1", cell.Value); cell.Enter("a"); Keyboard.Type(Key.TAB); Keyboard.Type(Key.TAB); Keyboard.Type(Key.TAB); Assert.AreEqual("a", cell.Value); Assert.AreEqual("a", cell.FindTextBox().Text); cell.Enter("11"); Keyboard.Type(Key.TAB); Keyboard.Type(Key.TAB); Keyboard.Type(Key.TAB); Assert.AreEqual("11", cell.Value); Assert.AreEqual("11", cell.FindTextBlock().Text); } [TestCase("DataGrid")] [TestCase("DataGrid10")] [TestCase("DataGridNoHeaders")] [TestCase("TemplateColumnDataGrid")] public void SetValue(string name) { using var app = Application.Launch(ExeFileName, "DataGridWindow"); var window = app.MainWindow; var dataGrid = window.FindDataGrid(name); Assert.AreEqual("1", dataGrid[0, 0].Value); Assert.AreEqual("Item 1", dataGrid[0, 1].Value); Assert.AreEqual("2", dataGrid[1, 0].Value); Assert.AreEqual("Item 2", dataGrid[1, 1].Value); Assert.AreEqual("3", dataGrid[2, 0].Value); Assert.AreEqual("Item 3", dataGrid[2, 1].Value); dataGrid[0, 0].Value = "11"; Assert.AreEqual("11", dataGrid[0, 0].Value); Assert.AreEqual("Item 1", dataGrid[0, 1].Value); Assert.AreEqual("2", dataGrid[1, 0].Value); Assert.AreEqual("Item 2", dataGrid[1, 1].Value); Assert.AreEqual("3", dataGrid[2, 0].Value); Assert.AreEqual("Item 3", dataGrid[2, 1].Value); dataGrid[2, 1].Value = "Item 5"; Assert.AreEqual("11", dataGrid[0, 0].Value); Assert.AreEqual("11", dataGrid[0, 0].FindTextBlock().Text); Assert.AreEqual("Item 1", dataGrid[0, 1].Value); Assert.AreEqual("2", dataGrid[1, 0].Value); Assert.AreEqual("Item 2", dataGrid[1, 1].Value); Assert.AreEqual("3", dataGrid[2, 0].Value); Assert.AreEqual("Item 5", dataGrid[2, 1].Value); dataGrid[0, 0].Value = "111"; Assert.AreEqual("111", dataGrid[0, 0].Value); Assert.AreEqual("Item 1", dataGrid[0, 1].Value); Assert.AreEqual("2", dataGrid[1, 0].Value); Assert.AreEqual("Item 2", dataGrid[1, 1].Value); Assert.AreEqual("3", dataGrid[2, 0].Value); Assert.AreEqual("Item 5", dataGrid[2, 1].Value); Assert.AreEqual("Item 5", dataGrid[2, 1].FindTextBlock().Text); } [TestCase("DataGrid")] [TestCase("DataGrid10")] [TestCase("DataGridNoHeaders")] [TestCase("TemplateColumnDataGrid")] public void SetValueWhenClickedOnce(string name) { using var app = Application.Launch(ExeFileName, "DataGridWindow"); var window = app.MainWindow; var dataGrid = window.FindDataGrid(name); var cell = dataGrid[0, 0]; Assert.AreEqual("1", cell.Value); cell.Click(); cell.Value = "11"; Assert.AreEqual("11", cell.Value); } [TestCase("DataGrid")] [TestCase("DataGrid10")] [TestCase("DataGridNoHeaders")] [TestCase("TemplateColumnDataGrid")] public void SetValueWhenClickedTwice(string name) { using var app = Application.Launch(ExeFileName, "DataGridWindow"); var window = app.MainWindow; var dataGrid = window.FindDataGrid(name); var cell = dataGrid[0, 0]; Assert.AreEqual("1", cell.Value); cell.Click(); cell.Click(); cell.Value = "11"; Assert.AreEqual("11", cell.Value); } [Explicit("Dunno if this is possible.")] [TestCase("DataGrid")] [TestCase("SelectCellDataGrid")] public void SetInvalidValueThrows(string name) { Assert.Inconclusive("VS test runner does not understand [Explicit]."); using var app = Application.Launch(ExeFileName, "DataGridWindow"); var window = app.MainWindow; var dataGrid = window.FindDataGrid(name); var cell = dataGrid[0, 0]; var exception = Assert.Throws<InvalidOperationException>(() => cell.Value = "a"); Assert.AreEqual("Failed setting value.", exception.Message); } [Test] public void SetValueUpdatesBinding() { using var app = Application.Launch(ExeFileName, "DataGridWindow"); var window = app.MainWindow; var dataGrid = window.FindDataGrid("DataGrid"); var readOnly = window.FindDataGrid("ReadOnlyDataGrid"); Assert.AreEqual("1", dataGrid[0, 0].Value); Assert.AreEqual("1", readOnly[0, 0].Value); dataGrid[0, 0].Value = "11"; Assert.AreEqual("11", dataGrid[0, 0].Value); Assert.Inconclusive("Figure out the least ugly way here."); //// ReSharper disable once HeuristicUnreachableCode Assert.AreEqual("11", readOnly[0, 0].Value); } [TestCase("DataGrid10", 9)] [TestCase("DataGrid10", 10)] public void SetValueWhenOffScreen(string name, int row) { using var app = Application.Launch(ExeFileName, "DataGridWindow"); var window = app.MainWindow; var dataGrid = window.FindDataGrid(name); dataGrid[row, 0].Value = "-1"; dataGrid[row, 1].Value = "Item -1"; Assert.AreEqual("-1", dataGrid[row, 0].Value); Assert.AreEqual("Item -1", dataGrid[row, 1].Value); } [TestCase("DataGrid10")] public void GetValueWhenOffScreen(string name) { using var app = Application.AttachOrLaunch(ExeFileName, "DataGridWindow"); var window = app.MainWindow; var dataGrid = window.FindDataGrid(name); Assert.AreEqual("10", dataGrid[9, 0].Value); Assert.AreEqual("Item 10", dataGrid[9, 1].Value); } } }
/////////////////////////////////////////////////////////////////////////////////// // Open 3D Model Viewer (open3mod) (v2.0) // [Tab.cs] // (c) 2012-2015, Open3Mod Contributors // // Licensed under the terms and conditions of the 3-clause BSD license. See // the LICENSE file in the root folder of the repository for the details. // // HIS 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; using System.Collections.Generic; using System.Diagnostics; using System.Drawing; using System.Linq; using System.Text; using OpenTK; namespace open3mod { /// <summary> /// Represents a single tab in the UI. A tab always contains exactly one scene /// being rendered, a scene being loaded or no scene at all (the latter is the /// dummy tab that is initially open). /// /// A scene is thus coupled to a tab and therefore owned by TabState. The /// list of all tabs is maintained by UIState, which also knows which tab /// is active. /// </summary> public sealed class Tab { /// <summary> /// Enum of all supported tab states. /// </summary> public enum TabState { Empty = 0, Loading, Rendering, Failed } /// <summary> /// Index all 3D views - there can be up to four 3D views at this time, /// but the rest of the codebase always works with _Max so it can be /// nicely adjusted simply by adding more indexes. /// </summary> public enum ViewIndex { Index0 = 0, Index1, Index2, Index3, _Max } /// <summary> /// Enumerates all the separator bars that can be dragged in order to /// resize viewports. /// </summary> public enum ViewSeparator { Horizontal = 0, Vertical, _Max, Both } /// <summary> /// Supported arrangements of 3D views. Right now only the number of /// 3d windows. /// </summary> public enum ViewMode { // values pertain to CoreSettings:DefaultViewMode! Single = 0, Two = 1, Four = 2, TwoHorizontal = 3, } /// <summary> /// Current state of the tab. The state flag is maintained internally /// and switched to "Rendering" as soon as a scene is set. The initial /// state can be set using the constructor. /// </summary> public TabState State { get; private set; } /// <summary> /// Index of the currently active viewport /// </summary> public ViewIndex ActiveViewIndex = 0; /// <summary> /// Array of viewport objects. Entries are null until a viewport index is /// at least used once with the tab. After a viewport has been enabled once, /// the corresponding Viewport instance is retained so a viewport /// keeps its state when the user hides it and shows it again. /// /// Which viewport setup is currently active in the GUI is specified by the /// ActiveViewMode property. /// </summary> public Viewport[] ActiveViews { get { if (_dirtySplit) { ValidateViewportBounds(); } return _activeViews; } set{ _activeViews = value; } } private Viewport[] _activeViews = new Viewport[(int)ViewIndex._Max]; /// <summary> /// Current view mode /// </summary> public ViewMode ActiveViewMode { get { return _activeViewMode; } set { // hardcoded table of viewport sizes. This is the only location // so changing these constants is sufficient to adjust viewport defaults _activeViewMode = value; CoreSettings.CoreSettings.Default.DefaultViewMode = (int) value; switch(_activeViewMode) { case ViewMode.Single: ActiveViews = new [] { new Viewport(new Vector4(0.0f, 0.0f, 1.0f, 1.0f), CameraMode.Orbit), null, null, null }; break; case ViewMode.Two: ActiveViews = new [] { new Viewport(new Vector4(0.0f, 0.0f, 1.0f, 0.5f), CameraMode.Orbit), null, new Viewport(new Vector4(0.0f, 0.5f, 1.0f, 1.0f), CameraMode.X), null }; break; case ViewMode.TwoHorizontal: ActiveViews = new[] { new Viewport(new Vector4(0.0f, 0.0f, 0.5f, 1.0f), CameraMode.Orbit), new Viewport(new Vector4(0.5f, 0.0f, 1.0f, 1.0f), CameraMode.X), null, null }; break; case ViewMode.Four: ActiveViews = new [] { new Viewport(new Vector4(0.0f, 0.0f, 0.5f, 0.5f), CameraMode.Orbit), new Viewport(new Vector4(0.5f, 0.0f, 1.0f, 0.5f), CameraMode.Z), new Viewport(new Vector4(0.0f, 0.5f, 0.5f, 1.0f), CameraMode.X), new Viewport(new Vector4(0.5f, 0.5f, 1.0f, 1.0f), CameraMode.Y) }; break; default: throw new ArgumentOutOfRangeException(); } Debug.Assert(ActiveViews[0] != null); if (ActiveViews[(int)ActiveViewIndex] == null) { ActiveViewIndex = ViewIndex.Index0; } } } /// <summary> /// Obtain an instance of the current active camera controller (i.e. /// the controller for the current active view and current active camera /// mode. This may be a null. /// </summary> public ICameraController ActiveCameraController { get { return ActiveCameraControllerForView(ActiveViewIndex); } } /// <summary> /// Current active scene /// </summary> public Scene ActiveScene { get { return _activeScene; } set { Debug.Assert(State != TabState.Failed, "cannot recover from TabState.Failed"); // make sure the previous scene instance is properly disposed if (_activeScene != null) { _activeScene.Dispose(); } _activeScene = value; // switch state to "Rendering" if the new scene is non-null if (_activeScene == null) { State = TabState.Empty; } else { State = TabState.Rendering; } } } /// <summary> /// File name of the scene in the tab. This member is already set while /// the scene is loading and "ActiveScene" is null. This field is null /// if the tab is in state TabState.Empty. /// </summary> public string File { get; private set; } /// <summary> /// If the tab is in a failed state this contains the error message /// that describes the failure. Otherwise, this is an empty string. /// </summary> public string ErrorMessage { get { return _errorMessage; } } /// <summary> /// Unique ID of the tab. This is used to connect with the UI. The value /// is set via the constructor and never changes. /// </summary> public readonly object Id; private Scene _activeScene; private string _errorMessage; private ViewMode _activeViewMode = ViewMode.Four; /// <summary> /// Position of the horizontal and vertical splits /// in [MinimumViewportSplit,1-MinimumViewportSplit] /// </summary> private float _verticalSplitPos = 0.5f; private float _horizontalSplitPos = 0.5f; /// <summary> /// dirty flag for the recalculation of viewport bounds /// </summary> private bool _dirtySplit = true; /// <summary> /// Create an empty tab. /// <param name="id">Static id to associate with the tab, see "ID"</param> /// <param name="fileBeingLoaded">Specifies the file that is being loaded /// for this tab. If this is non-null, the state of the tab is set /// to TabState.Loading and the file name is stored in the File field.</param> /// </summary> public Tab(object id, string fileBeingLoaded) { var vm = CoreSettings.CoreSettings.Default.DefaultViewMode; if(vm <= 2 && vm >= 0) { ActiveViewMode = (ViewMode) vm; } else { ActiveViewMode = ViewMode.Four; CoreSettings.CoreSettings.Default.DefaultViewMode = (int) ViewMode.Four; } State = fileBeingLoaded == null ? TabState.Empty : TabState.Loading; File = fileBeingLoaded; Id = id; } /// <summary> /// Gets the ICameraController responsible for a particular view /// for the current active camera mode. /// </summary> /// <param name="targetView">View index</param> /// <returns>ICameraController or null if there is no implementation</returns> public ICameraController ActiveCameraControllerForView(ViewIndex targetView) { return ActiveViews[(int)targetView] == null ? null : ActiveViews[(int) targetView].ActiveCameraControllerForView(); } public void Dispose() { if (ActiveScene != null) { ActiveScene.Dispose(); ActiveScene = null; } GC.SuppressFinalize(this); } #if DEBUG ~Tab() { // OpenTk is unsafe from here, explicit Dispose() is required. Debug.Assert(false); } #endif /// <summary> /// Sets the tab to a permanent "failed to load" state. In this /// state, the tab keeps displaying an error message but nothing /// else. /// </summary> /// <param name="message"></param> public void SetFailed(string message) { State = TabState.Failed; _activeScene = null; _errorMessage = message; } /// <summary> /// Changes the camera mode in the currently active view. /// </summary> /// <param name="cameraMode">New camera mode</param> public void ChangeActiveCameraMode(CameraMode cameraMode) { ChangeCameraModeForView(ActiveViewIndex, cameraMode); } /// <summary> /// Changes the camera mode for a view. /// </summary> /// <param name="viewIndex">index of the view.</param> /// <param name="cameraMode">New camera mode.</param> public void ChangeCameraModeForView(ViewIndex viewIndex, CameraMode cameraMode) { Debug.Assert(ActiveViews[(int)viewIndex] != null); var view = ActiveViews[(int) viewIndex]; view.ChangeCameraModeForView(cameraMode); } /// <summary> /// Resets the camera in the currently active view /// </summary> /// <param name="cameraMode">New camera mode</param> public void ResetActiveCameraController() { Debug.Assert(ActiveViews[(int)ActiveViewIndex] != null); var view = ActiveViews[(int)ActiveViewIndex]; view.ResetCameraController(); } /// <summary> /// Converts a (mouse) hit position to a viewport index - in other words, /// it calculates the index of the viewport that is hit by a click /// on a given mouse position. /// </summary> /// <param name="x">Hit position x, in normalized [0,1] range</param> /// <param name="y">Hit position y, in normalized [0,1] range</param> /// <returns>Tab.ViewIndex._Max if the hit coordinate doesn't hit a /// viewport. If not, the ViewIndex of the tab that was hit.</returns> public ViewIndex GetViewportIndexHit(float x, float y) { var index = ViewIndex.Index0; foreach (var viewport in ActiveViews) { if (viewport == null) { ++index; continue; } var view = viewport.Bounds; if (x >= view.X && x <= view.Z && y >= view.Y && y <= view.W) { break; } ++index; } return index; } /// <summary> /// Converts a mouse position to a viewport separator. It therefore /// checks whether the mouse is in a region where dragging viewport /// borders is possible. /// </summary> /// <param name="x">Mouse x, in relative coordinates</param> /// <param name="y">Mouse y, in relative coordinates</param> /// <returns>Tab.ViewSeparator._Max if the mouse coordinate doesn't hit a /// viewport separator. If not, the separator that was hit.</returns> public ViewSeparator GetViewportSeparatorHit(float x, float y) { if (_activeViewMode == ViewMode.Single) { return ViewSeparator._Max; } var vp = ActiveViews[0]; Debug.Assert(vp != null); const float threshold = 0.01f; if (Math.Abs(x - vp.Bounds.Z) < threshold && _activeViewMode != ViewMode.Two) { if (Math.Abs(y - vp.Bounds.W) < threshold) { return ViewSeparator.Both; } return ViewSeparator.Vertical; } if (Math.Abs(y - vp.Bounds.W) < threshold && _activeViewMode != ViewMode.TwoHorizontal) { return ViewSeparator.Horizontal; } return ViewSeparator._Max; } private const float MinimumViewportSplit = 0.1f; /// <summary> /// Sets a new position for the horizontal split between viewports. /// /// This is only possible (and otherwise ignored) if all the four viewports are enabled. /// </summary> /// <param name="f">New splitter bar position, in [0,1]. Positions outside /// [MinimumViewportSplit,1-MinimumViewportSplit] are clamped.</param> public void SetViewportSplitH(float f) { if (ActiveViewMode != ViewMode.TwoHorizontal && ActiveViewMode != ViewMode.Four) { return; } if (f < MinimumViewportSplit) { f = MinimumViewportSplit; } else if (f > 1.0f-MinimumViewportSplit) { f = 1.0f-MinimumViewportSplit; } _horizontalSplitPos = f; _dirtySplit = true; } /// <summary> /// Sets a new position for the vertical split between viewports. /// /// This is only possible (and otherwise ignored) if at least two viewports are enabled. /// </summary> /// <param name="f">New splitter bar position, in [0,1]. Positions outside /// [MinimumViewportSplit,1-MinimumViewportSplit] are clamped.</param> public void SetViewportSplitV(float f) { if (ActiveViewMode != ViewMode.Two && ActiveViewMode != ViewMode.Four) { return; } if (f < MinimumViewportSplit) { f = MinimumViewportSplit; } else if (f > 1.0f - MinimumViewportSplit) { f = 1.0f - MinimumViewportSplit; } _verticalSplitPos = f; _dirtySplit = true; } /// <summary> /// Ensure every viewport bounds do not overlap the splitter in both directions /// </summary> private void ValidateViewportBounds() { Debug.Assert(_dirtySplit); foreach (var viewport in _activeViews.Where(viewport => viewport != null)) { var b = viewport.Bounds; //set vertical split if (Math.Abs(b.Y - _verticalSplitPos) > 0.0f && b.Y >= MinimumViewportSplit * 0.99999f) { b.Y = _verticalSplitPos; } else if (b.W <= 1.0f - MinimumViewportSplit * 0.99999f) { b.W = _verticalSplitPos; } //set horizontal split if (Math.Abs(b.X - _horizontalSplitPos) > 0.0f && b.X >= MinimumViewportSplit * 0.99999f) { b.X = _horizontalSplitPos; } else if (b.Z <= 1.0f - MinimumViewportSplit * 0.99999f) { b.Z = _horizontalSplitPos; } viewport.Bounds = b; } _dirtySplit = false; } } } /* vi: set shiftwidth=4 tabstop=4: */
// Copyright 2007-2012 Chris Patterson, Dru Sellers, Travis Smith, et. al. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. namespace Topshelf.Hosts { using System; using System.Collections.Generic; using System.Linq; using System.ServiceProcess; using Logging; using Runtime; public class InstallHost : Host { static readonly LogWriter _log = HostLogger.Get<InstallHost>(); readonly HostEnvironment _environment; readonly InstallHostSettings _installSettings; readonly IEnumerable<Action<InstallHostSettings>> _postActions; readonly IEnumerable<Action<InstallHostSettings>> _preActions; readonly IEnumerable<Action<InstallHostSettings>> _postRollbackActions; readonly IEnumerable<Action<InstallHostSettings>> _preRollbackActions; readonly HostSettings _settings; readonly bool _sudo; public InstallHost(HostEnvironment environment, HostSettings settings, HostStartMode startMode, IEnumerable<string> dependencies, Credentials credentials, IEnumerable<Action<InstallHostSettings>> preActions, IEnumerable<Action<InstallHostSettings>> postActions, IEnumerable<Action<InstallHostSettings>> preRollbackActions, IEnumerable<Action<InstallHostSettings>> postRollbackActions, bool sudo) { _environment = environment; _settings = settings; _installSettings = new InstallServiceSettingsImpl(settings, credentials, startMode, dependencies.ToArray()); _preActions = preActions; _postActions = postActions; _preRollbackActions = preRollbackActions; _postRollbackActions = postRollbackActions; _sudo = sudo; } public InstallHostSettings InstallSettings { get { return _installSettings; } } public HostSettings Settings { get { return _settings; } } public TopshelfExitCode Run() { if (_environment.IsServiceInstalled(_settings.ServiceName)) { _log.ErrorFormat("The {0} service is already installed.", _settings.ServiceName); return TopshelfExitCode.ServiceAlreadyInstalled; } if (!_environment.IsAdministrator) { if (_sudo) { if (_environment.RunAsAdministrator()) return TopshelfExitCode.Ok; } _log.ErrorFormat("The {0} service can only be installed as an administrator", _settings.ServiceName); return TopshelfExitCode.SudoRequired; } _log.DebugFormat("Attempting to install '{0}'", _settings.ServiceName); _environment.InstallService(_installSettings, ExecutePreActions, ExecutePostActions, ExecutePreRollbackActions, ExecutePostRollbackActions); return TopshelfExitCode.Ok; } void ExecutePreActions(InstallHostSettings settings) { foreach (Action<InstallHostSettings> action in _preActions) { action(_installSettings); } } void ExecutePostActions() { foreach (Action<InstallHostSettings> action in _postActions) { action(_installSettings); } } void ExecutePreRollbackActions() { foreach (Action<InstallHostSettings> action in _preRollbackActions) { action(_installSettings); } } void ExecutePostRollbackActions() { foreach (Action<InstallHostSettings> action in _postRollbackActions) { action(_installSettings); } } class InstallServiceSettingsImpl : InstallHostSettings { private Credentials _credentials; readonly string[] _dependencies; readonly HostSettings _settings; readonly HostStartMode _startMode; public InstallServiceSettingsImpl(HostSettings settings, Credentials credentials, HostStartMode startMode, string[] dependencies) { _credentials = credentials; _settings = settings; _startMode = startMode; _dependencies = dependencies; } public string Name { get { return _settings.Name; } } public string DisplayName { get { return _settings.DisplayName; } } public string Description { get { return _settings.Description; } } public string InstanceName { get { return _settings.InstanceName; } } public string ServiceName { get { return _settings.ServiceName; } } public bool CanPauseAndContinue { get { return _settings.CanPauseAndContinue; } } public bool CanShutdown { get { return _settings.CanShutdown; } } public bool CanSessionChanged { get { return _settings.CanSessionChanged; } } public Credentials Credentials { get { return _credentials; } set { _credentials = value; } } public string[] Dependencies { get { return _dependencies; } } public HostStartMode StartMode { get { return _startMode; } } public TimeSpan StartTimeOut { get { return _settings.StartTimeOut; } } public TimeSpan StopTimeOut { get { return _settings.StopTimeOut; } } } } }
// System.Xml.XmlDocumentTests // // Authors: // Jason Diamond <jason@injektilo.org> // Kral Ferch <kral_ferch@hotmail.com> // Martin Willemoes Hansen <mwh@sysrq.dk> // // (C) 2002 Jason Diamond, Kral Ferch // (C) 2003 Martin Willemoes Hansen // using System; using System.Collections; using System.Xml; using System.IO; using System.Text; using NUnit.Framework; #if NET_2_0 using InvalidNodeTypeArgException = System.ArgumentException; #else // it makes less sense using InvalidNodeTypeArgException = System.ArgumentOutOfRangeException; #endif namespace MonoTests.System.Xml { [TestFixture] public class XmlDocumentTests { private XmlDocument document; private ArrayList eventStrings = new ArrayList(); // These Event* methods support the TestEventNode* Tests in this file. // Most of them are event handlers for the XmlNodeChangedEventHandler // delegate. private void EventStringAdd(string eventName, XmlNodeChangedEventArgs e) { string oldParent = (e.OldParent != null) ? e.OldParent.Name : "<none>"; string newParent = (e.NewParent != null) ? e.NewParent.Name : "<none>"; eventStrings.Add (String.Format ("{0}, {1}, {2}, {3}, {4}", eventName, e.Action.ToString (), e.Node.OuterXml, oldParent, newParent)); } private void EventNodeChanged(Object sender, XmlNodeChangedEventArgs e) { EventStringAdd ("NodeChanged", e); } private void EventNodeChanging (Object sender, XmlNodeChangedEventArgs e) { EventStringAdd ("NodeChanging", e); } private void EventNodeChangingException (Object sender, XmlNodeChangedEventArgs e) { throw new Exception ("don't change the value."); } private void EventNodeInserted(Object sender, XmlNodeChangedEventArgs e) { EventStringAdd ("NodeInserted", e); } private void EventNodeInserting(Object sender, XmlNodeChangedEventArgs e) { EventStringAdd ("NodeInserting", e); } private void EventNodeInsertingException(Object sender, XmlNodeChangedEventArgs e) { throw new Exception ("don't insert the element."); } private void EventNodeRemoved(Object sender, XmlNodeChangedEventArgs e) { EventStringAdd ("NodeRemoved", e); } private void EventNodeRemoving(Object sender, XmlNodeChangedEventArgs e) { EventStringAdd ("NodeRemoving", e); } private void EventNodeRemovingException(Object sender, XmlNodeChangedEventArgs e) { throw new Exception ("don't remove the element."); } [SetUp] public void GetReady () { document = new XmlDocument (); document.PreserveWhitespace = true; } [Test] public void CreateNodeNodeTypeNameEmptyParams () { try { document.CreateNode (null, null, null); Assert.Fail ("Expected an ArgumentException to be thrown."); } catch (ArgumentException) {} try { document.CreateNode ("attribute", null, null); Assert.Fail ("Expected a NullReferenceException to be thrown."); } catch (NullReferenceException) {} try { document.CreateNode ("attribute", "", null); Assert.Fail ("Expected an ArgumentException to be thrown."); } catch (ArgumentException) {} try { document.CreateNode ("element", null, null); Assert.Fail ("Expected a NullReferenceException to be thrown."); } catch (NullReferenceException) {} try { document.CreateNode ("element", "", null); Assert.Fail ("Expected an ArgumentException to be thrown."); } catch (ArgumentException) {} try { document.CreateNode ("entityreference", null, null); Assert.Fail ("Expected a NullReferenceException to be thrown."); } catch (NullReferenceException) {} } [Test] public void CreateNodeInvalidXmlNodeType () { XmlNode node; try { node = document.CreateNode (XmlNodeType.EndElement, null, null); Assert.Fail ("Expected an ArgumentOutOfRangeException to be thrown."); } catch (InvalidNodeTypeArgException) {} try { node = document.CreateNode (XmlNodeType.EndEntity, null, null); Assert.Fail ("Expected an ArgumentOutOfRangeException to be thrown."); } catch (InvalidNodeTypeArgException) {} try { node = document.CreateNode (XmlNodeType.Entity, null, null); Assert.Fail ("Expected an ArgumentOutOfRangeException to be thrown."); } catch (InvalidNodeTypeArgException) {} try { node = document.CreateNode (XmlNodeType.None, null, null); Assert.Fail ("Expected an ArgumentOutOfRangeException to be thrown."); } catch (InvalidNodeTypeArgException) {} try { node = document.CreateNode (XmlNodeType.Notation, null, null); Assert.Fail ("Expected an ArgumentOutOfRangeException to be thrown."); } catch (InvalidNodeTypeArgException) {} // TODO: undocumented allowable type. node = document.CreateNode (XmlNodeType.XmlDeclaration, null, null); Assert.AreEqual (XmlNodeType.XmlDeclaration, node.NodeType); } [Test] public void CreateNodeWhichParamIsUsed () { XmlNode node; // No constructor params for Document, DocumentFragment. node = document.CreateNode (XmlNodeType.CDATA, "a", "b", "c"); Assert.AreEqual (String.Empty, ((XmlCDataSection)node).Value); node = document.CreateNode (XmlNodeType.Comment, "a", "b", "c"); Assert.AreEqual (String.Empty, ((XmlComment)node).Value); node = document.CreateNode (XmlNodeType.DocumentType, "a", "b", "c"); Assert.IsNull (((XmlDocumentType)node).Value); // TODO: add this back in to test when it's implemented. // node = document.CreateNode (XmlNodeType.EntityReference, "a", "b", "c"); // Assert.IsNull (((XmlEntityReference)node).Value); // TODO: add this back in to test when it's implemented. // node = document.CreateNode (XmlNodeType.ProcessingInstruction, "a", "b", "c"); // Assert.AreEqual (String.Empty, ((XmlProcessingInstruction)node).Value); node = document.CreateNode (XmlNodeType.SignificantWhitespace, "a", "b", "c"); Assert.AreEqual (String.Empty, ((XmlSignificantWhitespace)node).Value); node = document.CreateNode (XmlNodeType.Text, "a", "b", "c"); Assert.AreEqual (String.Empty, ((XmlText)node).Value); node = document.CreateNode (XmlNodeType.Whitespace, "a", "b", "c"); Assert.AreEqual (String.Empty, ((XmlWhitespace)node).Value); node = document.CreateNode (XmlNodeType.XmlDeclaration, "a", "b", "c"); Assert.AreEqual ("version=\"1.0\"", ((XmlDeclaration)node).Value); } [Test] #if NET_2_0 [Category ("NotDotNet")] // enbug in 2.0 #endif public void CreateNodeNodeTypeName () { XmlNode node; try { node = document.CreateNode ("foo", null, null); Assert.Fail ("Expected an ArgumentException to be thrown."); } catch (ArgumentException) {} // .NET 2.0 fails here. node = document.CreateNode("attribute", "foo", null); Assert.AreEqual (XmlNodeType.Attribute, node.NodeType); node = document.CreateNode("cdatasection", null, null); Assert.AreEqual (XmlNodeType.CDATA, node.NodeType); node = document.CreateNode("comment", null, null); Assert.AreEqual (XmlNodeType.Comment, node.NodeType); node = document.CreateNode("document", null, null); Assert.AreEqual (XmlNodeType.Document, node.NodeType); // TODO: test which constructor this ended up calling, // i.e. reuse underlying NameTable or not? node = document.CreateNode("documentfragment", null, null); Assert.AreEqual (XmlNodeType.DocumentFragment, node.NodeType); node = document.CreateNode("documenttype", null, null); Assert.AreEqual (XmlNodeType.DocumentType, node.NodeType); node = document.CreateNode("element", "foo", null); Assert.AreEqual (XmlNodeType.Element, node.NodeType); // TODO: add this back in to test when it's implemented. // ---> It is implemented, but it is LAMESPEC that allows null entity reference name. // node = document.CreateNode("entityreference", "foo", null); // Assert.AreEqual (XmlNodeType.EntityReference, node.NodeType); // LAMESPEC: null PI name is silly. // node = document.CreateNode("processinginstruction", null, null); // Assert.AreEqual (XmlNodeType.ProcessingInstruction, node.NodeType); node = document.CreateNode("significantwhitespace", null, null); Assert.AreEqual (XmlNodeType.SignificantWhitespace, node.NodeType); node = document.CreateNode("text", null, null); Assert.AreEqual (XmlNodeType.Text, node.NodeType); node = document.CreateNode("whitespace", null, null); Assert.AreEqual (XmlNodeType.Whitespace, node.NodeType); } [Test] public void DocumentElement () { Assert.IsNull (document.DocumentElement); XmlElement element = document.CreateElement ("foo", "bar", "http://foo/"); Assert.IsNotNull (element); Assert.AreEqual ("foo", element.Prefix); Assert.AreEqual ("bar", element.LocalName); Assert.AreEqual ("http://foo/", element.NamespaceURI); Assert.AreEqual ("foo:bar", element.Name); Assert.AreSame (element, document.AppendChild (element)); Assert.AreSame (element, document.DocumentElement); } [Test] public void DocumentEmpty() { Assert.AreEqual ("", document.OuterXml, "Incorrect output for empty document."); } [Test] public void EventNodeChanged() { XmlElement element; XmlComment comment; document.NodeChanged += new XmlNodeChangedEventHandler (this.EventNodeChanged); // Node that is part of the document. document.AppendChild (document.CreateElement ("foo")); comment = document.CreateComment ("bar"); document.DocumentElement.AppendChild (comment); Assert.AreEqual ("<!--bar-->", document.DocumentElement.InnerXml); comment.Value = "baz"; Assert.IsTrue (eventStrings.Contains ("NodeChanged, Change, <!--baz-->, foo, foo")); Assert.AreEqual ("<!--baz-->", document.DocumentElement.InnerXml); // Node that isn't part of the document but created by the document. element = document.CreateElement ("foo"); comment = document.CreateComment ("bar"); element.AppendChild (comment); Assert.AreEqual ("<!--bar-->", element.InnerXml); comment.Value = "baz"; Assert.IsTrue (eventStrings.Contains ("NodeChanged, Change, <!--baz-->, foo, foo")); Assert.AreEqual ("<!--baz-->", element.InnerXml); /* TODO: Insert this when XmlNode.InnerText() and XmlNode.InnerXml() have been implemented. // Node that is part of the document. element = document.CreateElement ("foo"); element.InnerText = "bar"; document.AppendChild(element); element.InnerText = "baz"; Assert.IsTrue (eventStrings.Contains("NodeChanged, Change, baz, foo, foo")); // Node that isn't part of the document but created by the document. element = document.CreateElement("qux"); element.InnerText = "quux"; element.InnerText = "quuux"; Assert.IsTrue (eventStrings.Contains("NodeChanged, Change, quuux, qux, qux")); */ } [Test] public void EventNodeChanging() { XmlElement element; XmlComment comment; document.NodeChanging += new XmlNodeChangedEventHandler (this.EventNodeChanging); // Node that is part of the document. document.AppendChild (document.CreateElement ("foo")); comment = document.CreateComment ("bar"); document.DocumentElement.AppendChild (comment); Assert.AreEqual ("<!--bar-->", document.DocumentElement.InnerXml); comment.Value = "baz"; Assert.IsTrue (eventStrings.Contains ("NodeChanging, Change, <!--bar-->, foo, foo")); Assert.AreEqual ("<!--baz-->", document.DocumentElement.InnerXml); // Node that isn't part of the document but created by the document. element = document.CreateElement ("foo"); comment = document.CreateComment ("bar"); element.AppendChild (comment); Assert.AreEqual ("<!--bar-->", element.InnerXml); comment.Value = "baz"; Assert.IsTrue (eventStrings.Contains ("NodeChanging, Change, <!--bar-->, foo, foo")); Assert.AreEqual ("<!--baz-->", element.InnerXml); // If an exception is thrown the Document returns to original state. document.NodeChanging += new XmlNodeChangedEventHandler (this.EventNodeChangingException); element = document.CreateElement("foo"); comment = document.CreateComment ("bar"); element.AppendChild (comment); Assert.AreEqual ("<!--bar-->", element.InnerXml); try { comment.Value = "baz"; Assert.Fail ("Expected an exception to be thrown by the NodeChanging event handler method EventNodeChangingException()."); } catch (Exception) {} Assert.AreEqual ("<!--bar-->", element.InnerXml); // Yes it's a bit anal but this tests whether the node changing event exception fires before the // ArgumentOutOfRangeException. Turns out it does so that means our implementation needs to raise // the node changing event before doing any work. try { comment.ReplaceData(-1, 0, "qux"); Assert.Fail ("Expected an ArgumentOutOfRangeException to be thrown."); } catch (Exception) {} /* TODO: Insert this when XmlNode.InnerText() and XmlNode.InnerXml() have been implemented. // Node that is part of the document. element = document.CreateElement ("foo"); element.InnerText = "bar"; document.AppendChild(element); element.InnerText = "baz"; Assert.IsTrue (eventStrings.Contains("NodeChanging, Change, bar, foo, foo")); // Node that isn't part of the document but created by the document. element = document.CreateElement("foo"); element.InnerText = "bar"; element.InnerText = "baz"; Assert.IsTrue (eventStrings.Contains("NodeChanging, Change, bar, foo, foo")); // If an exception is thrown the Document returns to original state. document.NodeChanging += new XmlNodeChangedEventHandler (this.EventNodeChangingException); element = document.CreateElement("foo"); element.InnerText = "bar"; try { element.InnerText = "baz"; Assert.Fail ("Expected an exception to be thrown by the NodeChanging event handler method EventNodeChangingException()."); } catch (Exception) {} Assert.AreEqual ("bar", element.InnerText); */ } [Test] public void EventNodeInserted() { XmlElement element; document.NodeInserted += new XmlNodeChangedEventHandler (this.EventNodeInserted); // Inserted 'foo' element to the document. element = document.CreateElement ("foo"); document.AppendChild (element); Assert.IsTrue (eventStrings.Contains ("NodeInserted, Insert, <foo />, <none>, #document")); // Append child on node in document element = document.CreateElement ("foo"); document.DocumentElement.AppendChild (element); Assert.IsTrue (eventStrings.Contains ("NodeInserted, Insert, <foo />, <none>, foo")); // Append child on node not in document but created by document element = document.CreateElement ("bar"); element.AppendChild(document.CreateElement ("bar")); Assert.IsTrue (eventStrings.Contains("NodeInserted, Insert, <bar />, <none>, bar")); } [Test] public void EventNodeInserting() { XmlElement element; document.NodeInserting += new XmlNodeChangedEventHandler (this.EventNodeInserting); // Inserting 'foo' element to the document. element = document.CreateElement ("foo"); document.AppendChild (element); Assert.IsTrue (eventStrings.Contains ("NodeInserting, Insert, <foo />, <none>, #document")); // Append child on node in document element = document.CreateElement ("foo"); document.DocumentElement.AppendChild (element); Assert.IsTrue (eventStrings.Contains ("NodeInserting, Insert, <foo />, <none>, foo")); // Append child on node not in document but created by document element = document.CreateElement ("bar"); Assert.AreEqual (0, element.ChildNodes.Count); element.AppendChild (document.CreateElement ("bar")); Assert.IsTrue (eventStrings.Contains ("NodeInserting, Insert, <bar />, <none>, bar")); Assert.AreEqual (1, element.ChildNodes.Count); // If an exception is thrown the Document returns to original state. document.NodeInserting += new XmlNodeChangedEventHandler (this.EventNodeInsertingException); Assert.AreEqual (1, element.ChildNodes.Count); try { element.AppendChild (document.CreateElement("baz")); Assert.Fail ("Expected an exception to be thrown by the NodeInserting event handler method EventNodeInsertingException()."); } catch (Exception) {} Assert.AreEqual (1, element.ChildNodes.Count); } [Test] public void EventNodeRemoved() { XmlElement element; XmlElement element2; document.NodeRemoved += new XmlNodeChangedEventHandler (this.EventNodeRemoved); // Removed 'bar' element from 'foo' outside document. element = document.CreateElement ("foo"); element2 = document.CreateElement ("bar"); element.AppendChild (element2); Assert.AreEqual (1, element.ChildNodes.Count); element.RemoveChild (element2); Assert.IsTrue (eventStrings.Contains ("NodeRemoved, Remove, <bar />, foo, <none>")); Assert.AreEqual (0, element.ChildNodes.Count); /* * TODO: put this test back in when AttributeCollection.RemoveAll() is implemented. // RemoveAll. element = document.CreateElement ("foo"); element2 = document.CreateElement ("bar"); element.AppendChild(element2); Assert.AreEqual (1, element.ChildNodes.Count); element.RemoveAll(); Assert.IsTrue (eventStrings.Contains ("NodeRemoved, Remove, <bar />, foo, <none>")); Assert.AreEqual (0, element.ChildNodes.Count); */ // Removed 'bar' element from 'foo' inside document. element = document.CreateElement ("foo"); document.AppendChild (element); element = document.CreateElement ("bar"); document.DocumentElement.AppendChild (element); Assert.AreEqual (1, document.DocumentElement.ChildNodes.Count); document.DocumentElement.RemoveChild (element); Assert.IsTrue (eventStrings.Contains ("NodeRemoved, Remove, <bar />, foo, <none>")); Assert.AreEqual (0, document.DocumentElement.ChildNodes.Count); } [Test] public void EventNodeRemoving() { XmlElement element; XmlElement element2; document.NodeRemoving += new XmlNodeChangedEventHandler (this.EventNodeRemoving); // Removing 'bar' element from 'foo' outside document. element = document.CreateElement ("foo"); element2 = document.CreateElement ("bar"); element.AppendChild (element2); Assert.AreEqual (1, element.ChildNodes.Count); element.RemoveChild (element2); Assert.IsTrue (eventStrings.Contains ("NodeRemoving, Remove, <bar />, foo, <none>")); Assert.AreEqual (0, element.ChildNodes.Count); /* * TODO: put this test back in when AttributeCollection.RemoveAll() is implemented. // RemoveAll. element = document.CreateElement ("foo"); element2 = document.CreateElement ("bar"); element.AppendChild(element2); Assert.AreEqual (1, element.ChildNodes.Count); element.RemoveAll(); Assert.IsTrue (eventStrings.Contains ("NodeRemoving, Remove, <bar />, foo, <none>")); Assert.AreEqual (0, element.ChildNodes.Count); */ // Removing 'bar' element from 'foo' inside document. element = document.CreateElement ("foo"); document.AppendChild (element); element = document.CreateElement ("bar"); document.DocumentElement.AppendChild (element); Assert.AreEqual (1, document.DocumentElement.ChildNodes.Count); document.DocumentElement.RemoveChild (element); Assert.IsTrue (eventStrings.Contains ("NodeRemoving, Remove, <bar />, foo, <none>")); Assert.AreEqual (0, document.DocumentElement.ChildNodes.Count); // If an exception is thrown the Document returns to original state. document.NodeRemoving += new XmlNodeChangedEventHandler (this.EventNodeRemovingException); element.AppendChild (element2); Assert.AreEqual (1, element.ChildNodes.Count); try { element.RemoveChild(element2); Assert.Fail ("Expected an exception to be thrown by the NodeRemoving event handler method EventNodeRemovingException()."); } catch (Exception) {} Assert.AreEqual (1, element.ChildNodes.Count); } [Test] public void GetElementsByTagNameNoNameSpace () { string xml = @"<library><book><title>XML Fun</title><author>John Doe</author> <price>34.95</price></book><book><title>Bear and the Dragon</title> <author>Tom Clancy</author><price>6.95</price></book><book> <title>Bourne Identity</title><author>Robert Ludlum</author> <price>9.95</price></book><Fluffer><Nutter><book> <title>Bourne Ultimatum</title><author>Robert Ludlum</author> <price>9.95</price></book></Nutter></Fluffer></library>"; MemoryStream memoryStream = new MemoryStream (Encoding.UTF8.GetBytes (xml)); document = new XmlDocument (); document.Load (memoryStream); XmlNodeList bookList = document.GetElementsByTagName ("book"); Assert.AreEqual (4, bookList.Count, "GetElementsByTagName (string) returned incorrect count."); } [Test] public void GetElementsByTagNameUsingNameSpace () { StringBuilder xml = new StringBuilder (); xml.Append ("<?xml version=\"1.0\" ?><library xmlns:North=\"http://www.foo.com\" "); xml.Append ("xmlns:South=\"http://www.goo.com\"><North:book type=\"non-fiction\"> "); xml.Append ("<North:title type=\"intro\">XML Fun</North:title> " ); xml.Append ("<North:author>John Doe</North:author> " ); xml.Append ("<North:price>34.95</North:price></North:book> " ); xml.Append ("<South:book type=\"fiction\"> " ); xml.Append ("<South:title>Bear and the Dragon</South:title> " ); xml.Append ("<South:author>Tom Clancy</South:author> " ); xml.Append ("<South:price>6.95</South:price></South:book> " ); xml.Append ("<South:book type=\"fiction\"><South:title>Bourne Identity</South:title> " ); xml.Append ("<South:author>Robert Ludlum</South:author> " ); xml.Append ("<South:price>9.95</South:price></South:book></library>"); MemoryStream memoryStream = new MemoryStream (Encoding.UTF8.GetBytes (xml.ToString ())); document = new XmlDocument (); document.Load (memoryStream); XmlNodeList bookList = document.GetElementsByTagName ("book", "http://www.goo.com"); Assert.AreEqual (2, bookList.Count, "GetElementsByTagName (string, uri) returned incorrect count."); } [Test] public void GetElementsByTagNameNs2 () { document.LoadXml (@"<root> <x:a xmlns:x='urn:foo' id='a'> <y:a xmlns:y='urn:foo' id='b'/> <x:a id='c' /> <z id='d' /> text node <?a processing instruction ?> <x:w id='e'/> </x:a> </root>"); // id='b' has different prefix. Should not caught by (name), // while should caught by (name, ns). XmlNodeList nl = document.GetElementsByTagName ("x:a"); Assert.AreEqual (2, nl.Count); Assert.AreEqual ("a", nl [0].Attributes ["id"].Value); Assert.AreEqual ("c", nl [1].Attributes ["id"].Value); nl = document.GetElementsByTagName ("a", "urn:foo"); Assert.AreEqual (3, nl.Count); Assert.AreEqual ("a", nl [0].Attributes ["id"].Value); Assert.AreEqual ("b", nl [1].Attributes ["id"].Value); Assert.AreEqual ("c", nl [2].Attributes ["id"].Value); // name wildcard nl = document.GetElementsByTagName ("*"); Assert.AreEqual (6, nl.Count); Assert.AreEqual ("root", nl [0].Name); Assert.AreEqual ("a", nl [1].Attributes ["id"].Value); Assert.AreEqual ("b", nl [2].Attributes ["id"].Value); Assert.AreEqual ("c", nl [3].Attributes ["id"].Value); Assert.AreEqual ("d", nl [4].Attributes ["id"].Value); Assert.AreEqual ("e", nl [5].Attributes ["id"].Value); // wildcard - local and ns nl = document.GetElementsByTagName ("*", "*"); Assert.AreEqual (6, nl.Count); Assert.AreEqual ("root", nl [0].Name); Assert.AreEqual ("a", nl [1].Attributes ["id"].Value); Assert.AreEqual ("b", nl [2].Attributes ["id"].Value); Assert.AreEqual ("c", nl [3].Attributes ["id"].Value); Assert.AreEqual ("d", nl [4].Attributes ["id"].Value); Assert.AreEqual ("e", nl [5].Attributes ["id"].Value); // namespace wildcard - namespace nl = document.GetElementsByTagName ("*", "urn:foo"); Assert.AreEqual (4, nl.Count); Assert.AreEqual ("a", nl [0].Attributes ["id"].Value); Assert.AreEqual ("b", nl [1].Attributes ["id"].Value); Assert.AreEqual ("c", nl [2].Attributes ["id"].Value); Assert.AreEqual ("e", nl [3].Attributes ["id"].Value); // namespace wildcard - local only. I dare say, such usage is not XML-ish! nl = document.GetElementsByTagName ("a", "*"); Assert.AreEqual (3, nl.Count); Assert.AreEqual ("a", nl [0].Attributes ["id"].Value); Assert.AreEqual ("b", nl [1].Attributes ["id"].Value); Assert.AreEqual ("c", nl [2].Attributes ["id"].Value); } [Test] public void Implementation () { Assert.IsNotNull (new XmlDocument ().Implementation); } [Test] public void InnerAndOuterXml () { Assert.AreEqual (String.Empty, document.InnerXml); Assert.AreEqual (document.InnerXml, document.OuterXml); XmlDeclaration declaration = document.CreateXmlDeclaration ("1.0", null, null); document.AppendChild (declaration); Assert.AreEqual ("<?xml version=\"1.0\"?>", document.InnerXml); Assert.AreEqual (document.InnerXml, document.OuterXml); XmlElement element = document.CreateElement ("foo"); document.AppendChild (element); Assert.AreEqual ("<?xml version=\"1.0\"?><foo />", document.InnerXml); Assert.AreEqual (document.InnerXml, document.OuterXml); XmlComment comment = document.CreateComment ("bar"); document.DocumentElement.AppendChild (comment); Assert.AreEqual ("<?xml version=\"1.0\"?><foo><!--bar--></foo>", document.InnerXml); Assert.AreEqual (document.InnerXml, document.OuterXml); XmlText text = document.CreateTextNode ("baz"); document.DocumentElement.AppendChild (text); Assert.AreEqual ("<?xml version=\"1.0\"?><foo><!--bar-->baz</foo>", document.InnerXml); Assert.AreEqual (document.InnerXml, document.OuterXml); element = document.CreateElement ("quux"); element.SetAttribute ("quuux", "squonk"); document.DocumentElement.AppendChild (element); Assert.AreEqual ("<?xml version=\"1.0\"?><foo><!--bar-->baz<quux quuux=\"squonk\" /></foo>", document.InnerXml); Assert.AreEqual (document.InnerXml, document.OuterXml); } [Test] public void LoadWithSystemIOStream () { string xml = @"<library><book><title>XML Fun</title><author>John Doe</author> <price>34.95</price></book><book><title>Bear and the Dragon</title> <author>Tom Clancy</author><price>6.95</price></book><book> <title>Bourne Identity</title><author>Robert Ludlum</author> <price>9.95</price></book><Fluffer><Nutter><book> <title>Bourne Ultimatum</title><author>Robert Ludlum</author> <price>9.95</price></book></Nutter></Fluffer></library>"; MemoryStream memoryStream = new MemoryStream (Encoding.UTF8.GetBytes (xml)); document = new XmlDocument (); document.Load (memoryStream); Assert.AreEqual (true, document.HasChildNodes, "Not Loaded From IOStream"); } [Test] public void LoadXmlReaderNamespacesFalse () { XmlTextReader xtr = new XmlTextReader ( "<root xmlns='urn:foo' />", XmlNodeType.Document, null); xtr.Namespaces = false; document.Load (xtr); // Don't complain about xmlns attribute with its namespaceURI == String.Empty. } [Test] public void LoadXmlCDATA () { document.LoadXml ("<foo><![CDATA[bar]]></foo>"); Assert.IsTrue (document.DocumentElement.FirstChild.NodeType == XmlNodeType.CDATA); Assert.AreEqual ("bar", document.DocumentElement.FirstChild.Value); } [Test] public void LoadXMLComment() { // XmlTextReader needs to throw this exception // try { // document.LoadXml("<!--foo-->"); // Assert.Fail ("XmlException should have been thrown."); // } // catch (XmlException e) { // Assert.AreEqual ("The root element is missing.", e.Message, "Exception message doesn't match."); // } document.LoadXml ("<foo><!--Comment--></foo>"); Assert.IsTrue (document.DocumentElement.FirstChild.NodeType == XmlNodeType.Comment); Assert.AreEqual ("Comment", document.DocumentElement.FirstChild.Value); document.LoadXml (@"<foo><!--bar--></foo>"); Assert.AreEqual ("bar", ((XmlComment)document.FirstChild.FirstChild).Data, "Incorrect target."); } [Test] public void LoadXmlElementSingle () { Assert.IsNull (document.DocumentElement); document.LoadXml ("<foo/>"); Assert.IsNotNull (document.DocumentElement); Assert.AreSame (document.FirstChild, document.DocumentElement); Assert.AreEqual (String.Empty, document.DocumentElement.Prefix); Assert.AreEqual ("foo", document.DocumentElement.LocalName); Assert.AreEqual (String.Empty, document.DocumentElement.NamespaceURI); Assert.AreEqual ("foo", document.DocumentElement.Name); } [Test] public void LoadXmlElementWithAttributes () { Assert.IsNull (document.DocumentElement); document.LoadXml ("<foo bar='baz' quux='quuux' hoge='hello &amp; world' />"); XmlElement documentElement = document.DocumentElement; Assert.AreEqual ("baz", documentElement.GetAttribute ("bar")); Assert.AreEqual ("quuux", documentElement.GetAttribute ("quux")); Assert.AreEqual ("hello & world", documentElement.GetAttribute ("hoge")); Assert.AreEqual ("hello & world", documentElement.Attributes ["hoge"].Value); Assert.AreEqual (1, documentElement.GetAttributeNode ("hoge").ChildNodes.Count); } [Test] public void LoadXmlElementWithChildElement () { document.LoadXml ("<foo><bar/></foo>"); Assert.IsTrue (document.ChildNodes.Count == 1); Assert.IsTrue (document.FirstChild.ChildNodes.Count == 1); Assert.AreEqual ("foo", document.DocumentElement.LocalName); Assert.AreEqual ("bar", document.DocumentElement.FirstChild.LocalName); } [Test] public void LoadXmlElementWithTextNode () { document.LoadXml ("<foo>bar</foo>"); Assert.IsTrue (document.DocumentElement.FirstChild.NodeType == XmlNodeType.Text); Assert.AreEqual ("bar", document.DocumentElement.FirstChild.Value); } [Test] public void LoadXmlExceptionClearsDocument () { document.LoadXml ("<foo/>"); Assert.IsTrue (document.FirstChild != null); try { document.LoadXml ("<123/>"); Assert.Fail ("An XmlException should have been thrown."); } catch (XmlException) {} Assert.IsTrue (document.FirstChild == null); } [Test] public void LoadXmlProcessingInstruction () { document.LoadXml (@"<?foo bar='baaz' quux='quuux'?><quuuux></quuuux>"); Assert.AreEqual ("foo", ((XmlProcessingInstruction)document.FirstChild).Target, "Incorrect target."); Assert.AreEqual ("bar='baaz' quux='quuux'", ((XmlProcessingInstruction)document.FirstChild).Data, "Incorrect data."); } [Test] public void OuterXml () { string xml; xml = "<root><![CDATA[foo]]></root>"; document.LoadXml (xml); Assert.AreEqual (xml, document.OuterXml, "XmlDocument with cdata OuterXml is incorrect."); xml = "<root><!--foo--></root>"; document.LoadXml (xml); Assert.AreEqual (xml, document.OuterXml, "XmlDocument with comment OuterXml is incorrect."); xml = "<root><?foo bar?></root>"; document.LoadXml (xml); Assert.AreEqual (xml, document.OuterXml, "XmlDocument with processing instruction OuterXml is incorrect."); } [Test] public void ParentNodes () { document.LoadXml ("<foo><bar><baz/></bar></foo>"); XmlNode node = document.FirstChild.FirstChild.FirstChild; Assert.AreEqual ("baz", node.LocalName, "Wrong child found."); Assert.AreEqual ("bar", node.ParentNode.LocalName, "Wrong parent."); Assert.AreEqual ("foo", node.ParentNode.ParentNode.LocalName, "Wrong parent."); Assert.AreEqual ("#document", node.ParentNode.ParentNode.ParentNode.LocalName, "Wrong parent."); Assert.IsNull (node.ParentNode.ParentNode.ParentNode.ParentNode, "Expected parent to be null."); } [Test] public void RemovedElementNextSibling () { XmlNode node; XmlNode nextSibling; document.LoadXml ("<foo><child1/><child2/></foo>"); node = document.DocumentElement.FirstChild; document.DocumentElement.RemoveChild (node); nextSibling = node.NextSibling; Assert.IsNull (nextSibling, "Expected removed node's next sibling to be null."); } // ImportNode [Test] public void ImportNode () { XmlNode n; string xlinkURI = "http://www.w3.org/1999/XLink"; string xml1 = "<?xml version='1.0' encoding='utf-8' ?><foo xmlns:xlink='" + xlinkURI + "'><bar a1='v1' xlink:href='#foo'><baz><![CDATA[cdata section.\n\titem 1\n\titem 2\n]]>From here, simple text node.</baz></bar></foo>"; document.LoadXml(xml1); XmlDocument newDoc = new XmlDocument(); newDoc.LoadXml("<hoge><fuga /></hoge>"); XmlElement bar = document.DocumentElement.FirstChild as XmlElement; // Attribute n = newDoc.ImportNode(bar.GetAttributeNode("href", xlinkURI), true); Assert.AreEqual ("href", n.LocalName, "#ImportNode.Attr.NS.LocalName"); Assert.AreEqual (xlinkURI, n.NamespaceURI, "#ImportNode.Attr.NS.NSURI"); Assert.AreEqual ("#foo", n.Value, "#ImportNode.Attr.NS.Value"); // CDATA n = newDoc.ImportNode(bar.FirstChild.FirstChild, true); Assert.AreEqual ("cdata section.\n\titem 1\n\titem 2\n", n.Value, "#ImportNode.CDATA"); // Element XmlElement e = newDoc.ImportNode(bar, true) as XmlElement; Assert.AreEqual ("bar", e.Name, "#ImportNode.Element.Name"); Assert.AreEqual ("#foo", e.GetAttribute("href", xlinkURI), "#ImportNode.Element.Attr"); Assert.AreEqual ("baz", e.FirstChild.Name, "#ImportNode.Element.deep"); // Entity Reference: // [2002/10/14] CreateEntityReference was not implemented. // document.LoadXml("<!DOCTYPE test PUBLIC 'dummy' [<!ENTITY FOOENT 'foo'>]><root>&FOOENT;</root>"); // n = newDoc.ImportNode(document.DocumentElement.FirstChild); // Assert.AreEqual ("FOOENT", n.Name, "#ImportNode.EntityReference"); // Assert.AreEqual ("foo_", n.Value, "#ImportNode.EntityReference"); // Processing Instruction document.LoadXml("<foo><?xml-stylesheet href='foo.xsl' ?></foo>"); XmlProcessingInstruction pi = (XmlProcessingInstruction)newDoc.ImportNode(document.DocumentElement.FirstChild, false); Assert.AreEqual ("xml-stylesheet", pi.Name, "#ImportNode.ProcessingInstruction.Name"); Assert.AreEqual ("href='foo.xsl'", pi.Data.Trim(), "#ImportNode.ProcessingInstruction.Data"); // Text document.LoadXml(xml1); n = newDoc.ImportNode((XmlText)bar.FirstChild.ChildNodes[1], true); Assert.AreEqual ("From here, simple text node.", n.Value, "#ImportNode.Text"); // XmlDeclaration document.LoadXml(xml1); XmlDeclaration decl = (XmlDeclaration)newDoc.ImportNode(document.FirstChild, false); Assert.AreEqual (XmlNodeType.XmlDeclaration, decl.NodeType, "#ImportNode.XmlDeclaration.Type"); Assert.AreEqual ("utf-8", decl.Encoding, "#ImportNode.XmlDeclaration.Encoding"); } [Test] public void NameTable() { XmlDocument doc = new XmlDocument(); Assert.IsNotNull (doc.NameTable); } [Test] public void SingleEmptyRootDocument() { XmlDocument doc = new XmlDocument(); doc.LoadXml("<root />"); Assert.IsNotNull (doc.DocumentElement); } [Test] public void DocumentWithDoctypeDecl () { XmlDocument doc = new XmlDocument (); // In fact it is invalid, but it doesn't fail with MS.NET 1.0. doc.LoadXml ("<!DOCTYPE test><root />"); Assert.IsNotNull (doc.DocumentType); #if NetworkEnabled try { doc.LoadXml ("<!DOCTYPE test SYSTEM 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'><root />"); } catch (XmlException) { Assert.Fail ("#DoctypeDecl.System"); } try { doc.LoadXml ("<!DOCTYPE test PUBLIC '-//test' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'><root />"); } catch (XmlException) { Assert.Fail ("#DoctypeDecl.Public"); } #endif // Should this be commented out? doc.LoadXml ("<!DOCTYPE test [<!ELEMENT foo EMPTY>]><test><foo/></test>"); } [Test] public void CloneNode () { XmlDocument doc = new XmlDocument (); doc.LoadXml ("<foo><bar /><baz hoge='fuga'>TEST Text</baz></foo>"); XmlDocument doc2 = (XmlDocument)doc.CloneNode (false); Assert.AreEqual (0, doc2.ChildNodes.Count, "ShallowCopy"); doc2 = (XmlDocument)doc.CloneNode (true); Assert.AreEqual ("foo", doc2.DocumentElement.Name, "DeepCopy"); } [Test] public void OuterXmlWithDefaultXmlns () { XmlDocument doc = new XmlDocument (); doc.LoadXml ("<iq type=\"get\" id=\"ATECLIENT_1\"><query xmlns=\"jabber:iq:auth\"><username></username></query></iq>"); Assert.AreEqual ("<iq type=\"get\" id=\"ATECLIENT_1\"><query xmlns=\"jabber:iq:auth\"><username></username></query></iq>", doc.OuterXml); } [Test] public void PreserveWhitespace () { string input = "<?xml version=\"1.0\" encoding=\"utf-8\" ?><!-- --> <foo/>"; XmlDocument dom = new XmlDocument (); XmlTextReader reader = new XmlTextReader (new StringReader (input)); dom.Load (reader); Assert.AreEqual (XmlNodeType.Element, dom.FirstChild.NextSibling.NextSibling.NodeType); } [Test] public void PreserveWhitespace2 () { XmlDocument doc = new XmlDocument (); Assert.IsTrue (!doc.PreserveWhitespace); doc.PreserveWhitespace = true; XmlDocument d2 = doc.Clone () as XmlDocument; Assert.IsTrue (!d2.PreserveWhitespace); // i.e. not cloned d2.AppendChild (d2.CreateElement ("root")); d2.DocumentElement.AppendChild (d2.CreateWhitespace (" ")); StringWriter sw = new StringWriter (); d2.WriteTo (new XmlTextWriter (sw)); Assert.AreEqual ("<root> </root>", sw.ToString ()); } [Test] public void CreateAttribute () { XmlDocument dom = new XmlDocument (); // Check that null prefix and namespace are allowed and // equivalent to "" XmlAttribute attr = dom.CreateAttribute (null, "FOO", null); Assert.AreEqual (attr.Prefix, ""); Assert.AreEqual (attr.NamespaceURI, ""); } [Test] public void DocumentTypeNodes () { string entities = "<!ENTITY foo 'foo-ent'>"; string dtd = "<!DOCTYPE root [<!ELEMENT root (#PCDATA)*> " + entities + "]>"; string xml = dtd + "<root>&foo;</root>"; XmlValidatingReader xvr = new XmlValidatingReader (xml, XmlNodeType.Document, null); document.Load (xvr); Assert.IsNotNull (document.DocumentType); Assert.AreEqual (1, document.DocumentType.Entities.Count); XmlEntity foo = document.DocumentType.Entities.GetNamedItem ("foo") as XmlEntity; Assert.IsNotNull (foo); Assert.IsNotNull (document.DocumentType.Entities.GetNamedItem ("foo", "")); Assert.AreEqual ("foo", foo.Name); Assert.IsNull (foo.Value); Assert.AreEqual ("foo-ent", foo.InnerText); } [Test] public void DTDEntityAttributeHandling () { string dtd = "<!DOCTYPE root[<!ATTLIST root hoge CDATA 'hoge-def'><!ENTITY foo 'ent-foo'>]>"; string xml = dtd + "<root>&foo;</root>"; XmlValidatingReader xvr = new XmlValidatingReader (xml, XmlNodeType.Document,null); xvr.EntityHandling = EntityHandling.ExpandCharEntities; xvr.ValidationType = ValidationType.None; document.Load (xvr); // Don't include default attributes here. Assert.AreEqual (xml, document.OuterXml); Assert.AreEqual ("hoge-def", document.DocumentElement.GetAttribute ("hoge")); } // [Test] Comment out in the meantime. // public void LoadExternalUri () // { // // set any URL of well-formed XML. // document.Load ("http://www.go-mono.com/index.rss"); // } // [Test] comment out in the meantime. // public void LoadDocumentWithIgnoreSection () // { // // set any URL of well-formed XML. // document.Load ("xmlfiles/test.xml"); // } [Test] [ExpectedException (typeof (XmlException))] public void LoadThrowsUndeclaredEntity () { string ent1 = "<!ENTITY ent 'entity string'>"; string ent2 = "<!ENTITY ent2 '<foo/><foo/>'>]>"; string dtd = "<!DOCTYPE root[<!ELEMENT root (#PCDATA|foo)*>" + ent1 + ent2; string xml = dtd + "<root>&ent3;&ent2;</root>"; XmlTextReader xtr = new XmlTextReader (xml, XmlNodeType.Document, null); document.Load (xtr); xtr.Close (); } [Test] public void CreateEntityReferencesWithoutDTD () { document.RemoveAll (); document.AppendChild (document.CreateElement ("root")); document.DocumentElement.AppendChild (document.CreateEntityReference ("foo")); } [Test] public void LoadEntityReference () { string xml = "<!DOCTYPE root [<!ELEMENT root (#PCDATA)*><!ENTITY ent 'val'>]><root attr='a &ent; string'>&ent;</root>"; XmlTextReader xtr = new XmlTextReader (xml, XmlNodeType.Document, null); XmlDocument doc = new XmlDocument (); doc.Load (xtr); Assert.AreEqual (XmlNodeType.EntityReference, doc.DocumentElement.FirstChild.NodeType, "#text node"); Assert.AreEqual (XmlNodeType.EntityReference, doc.DocumentElement.Attributes [0].ChildNodes [1].NodeType, "#attribute"); } [Test] public void ReadNodeEmptyContent () { XmlTextReader xr = new XmlTextReader ("", XmlNodeType.Element, null); xr.Read (); Console.WriteLine (xr.NodeType); XmlNode n = document.ReadNode (xr); Assert.IsNull (n); } [Test] public void ReadNodeWhitespace () { XmlTextReader xr = new XmlTextReader (" ", XmlNodeType.Element, null); xr.Read (); Console.WriteLine (xr.NodeType); document.PreserveWhitespace = false; // Note this line. XmlNode n = document.ReadNode (xr); Assert.IsNotNull (n); Assert.AreEqual (XmlNodeType.Whitespace, n.NodeType); } [Test] public void SavePreserveWhitespace () { string xml = "<root> <element>text\n</element></root>"; XmlDocument doc = new XmlDocument (); doc.PreserveWhitespace = true; doc.LoadXml (xml); StringWriter sw = new StringWriter (); doc.Save (sw); Assert.AreEqual ("<?xml version=\"1.0\" encoding=\"utf-16\"?>" + xml, sw.ToString ()); doc.PreserveWhitespace = false; sw = new StringWriter (); doc.Save (sw); string NEL = Environment.NewLine; Assert.AreEqual ("<?xml version=\"1.0\" encoding=\"utf-16\"?>" + NEL + "<root> <element>text" + "\n</element></root>", sw.ToString ()); } [Test] public void ReadNodeEntityReferenceFillsChildren () { string dtd = "<!DOCTYPE root [<!ELEMENT root (#PCDATA)*><!ENTITY ent 'val'>]>"; string xml = dtd + "<root attr='a &ent; string'>&ent;</root>"; XmlValidatingReader reader = new XmlValidatingReader ( xml, XmlNodeType.Document, null); reader.EntityHandling = EntityHandling.ExpandCharEntities; reader.ValidationType = ValidationType.None; //skip the doctype delcaration reader.Read (); reader.Read (); XmlDocument doc = new XmlDocument (); doc.Load (reader); Assert.AreEqual (1, doc.DocumentElement.FirstChild.ChildNodes.Count); } [Test] public void LoadTreatsFixedAttributesAsIfItExisted () { string xml = @"<!DOCTYPE foo [<!ELEMENT foo EMPTY><!ATTLIST foo xmlns CDATA #FIXED 'urn:foo'>]><foo />"; XmlDocument doc = new XmlDocument (); doc.Load (new StringReader (xml)); Assert.AreEqual ("urn:foo", doc.DocumentElement.NamespaceURI); } [Test] public void Bug79468 () // XmlNameEntryCache bug { string xml = "<?xml version='1.0' encoding='UTF-8'?>" + "<ns0:DebtAmountRequest xmlns:ns0='http://whatever'>" + " <Signature xmlns='http://www.w3.org/2000/09/xmldsig#' />" + "</ns0:DebtAmountRequest>"; XmlDocument doc = new XmlDocument (); doc.LoadXml (xml); XmlNodeList nodeList = doc.GetElementsByTagName ("Signature"); } class MyXmlDocument : XmlDocument { public override XmlAttribute CreateAttribute (string p, string l, string n) { return base.CreateAttribute (p, "hijacked", n); } } [Test] public void UseOverridenCreateAttribute () { XmlDocument doc = new MyXmlDocument (); doc.LoadXml ("<root a='sane' />"); Assert.IsNotNull (doc.DocumentElement.GetAttributeNode ("hijacked")); Assert.IsNull (doc.DocumentElement.GetAttributeNode ("a")); } [Test] public void LoadFromMiddleOfDocument () { // bug #598953 string xml = @"<?xml version='1.0' encoding='utf-8' ?> <Racal> <Ports> <ConsolePort value='9998' /> </Ports> </Racal>"; var r = new XmlTextReader (new StringReader (xml)); r.WhitespaceHandling = WhitespaceHandling.All; r.MoveToContent (); r.Read (); var doc = new XmlDocument (); doc.Load (r); Assert.AreEqual (XmlNodeType.EndElement, r.NodeType, "#1"); } } }
using System; using System.Collections.Generic; using System.Globalization; using System.Text; using System.Text.RegularExpressions; namespace GitHub.Unity { class LogEntryOutputProcessor : BaseOutputListProcessor<GitLogEntry> { private readonly IGitObjectFactory gitObjectFactory; private ProcessingPhase phase; private string authorName; private string mergeA; private string mergeB; private List<GitStatusEntry> changes; private string authorEmail; private string summary; private List<string> descriptionLines; private string commitId; private DateTimeOffset? time; private int newlineCount; private string committerName; private string committerEmail; private DateTimeOffset? committerTime; private bool seenBodyEnd = false; private Regex hashRegex = new Regex("[0-9a-fA-F]{40}"); private StringBuilder sb; public LogEntryOutputProcessor(IGitObjectFactory gitObjectFactory) { Guard.ArgumentNotNull(gitObjectFactory, "gitObjectFactory"); this.gitObjectFactory = gitObjectFactory; Reset(); } private void Reset() { sb = new StringBuilder(); phase = ProcessingPhase.CommitHash; authorName = null; mergeA = null; mergeB = null; changes = new List<GitStatusEntry>(); authorEmail = null; summary = null; descriptionLines = new List<string>(); commitId = null; time = null; newlineCount = 0; committerName = null; committerEmail = null; committerTime = null; seenBodyEnd = false; } public override void LineReceived(string line) { if (line == null) { ReturnGitLogEntry(); return; } sb.AppendLine(line); if (phase == ProcessingPhase.Files && seenBodyEnd) { seenBodyEnd = false; var proc = new LineParser(line); if (proc.Matches(hashRegex)) { // there's no files on this commit, it's a new one! ReturnGitLogEntry(); } } switch (phase) { case ProcessingPhase.CommitHash: commitId = line; phase++; break; case ProcessingPhase.ParentHash: var parentHashes = line.Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries); if (parentHashes.Length > 1) { mergeA = parentHashes[0]; mergeB = parentHashes[1]; } phase++; break; case ProcessingPhase.AuthorName: authorName = line; phase++; break; case ProcessingPhase.AuthorEmail: authorEmail = line; phase++; break; case ProcessingPhase.AuthorDate: DateTimeOffset t; if (DateTimeOffset.TryParse(line, out t)) { time = t; } else { Logger.Error("ERROR {0}", sb.ToString()); throw new FormatException("Invalid line"); } phase++; break; case ProcessingPhase.CommitterName: committerName = line; phase++; break; case ProcessingPhase.CommitterEmail: committerEmail = line; phase++; break; case ProcessingPhase.CommitterDate: committerTime = DateTimeOffset.Parse(line); phase++; break; case ProcessingPhase.Summary: { var idx = line.IndexOf("---GHUBODYEND---", StringComparison.InvariantCulture); var oneliner = idx >= 0; if (oneliner) { line = line.Substring(0, idx); } summary = line; descriptionLines.Add(line); phase++; // there's no description so skip it if (oneliner) { phase++; seenBodyEnd = true; } } break; case ProcessingPhase.Description: var indexOf = line.IndexOf("---GHUBODYEND---", StringComparison.InvariantCulture); if (indexOf == -1) { descriptionLines.Add(line); } else if (indexOf == 0) { phase++; seenBodyEnd = true; } else { var substring = line.Substring(0, indexOf); descriptionLines.Add(substring); phase++; seenBodyEnd = true; } break; case ProcessingPhase.Files: if (line == string.Empty) { ReturnGitLogEntry(); return; } if (line.IndexOf("---GHUBODYEND---", StringComparison.InvariantCulture) >= 0) { seenBodyEnd = true; return; } var proc = new LineParser(line); string file = null; GitFileStatus status; string originalPath = null; if (proc.Matches('M')) { status = GitFileStatus.Modified; } else if (proc.Matches('A')) { status = GitFileStatus.Added; } else if (proc.Matches('D')) { status = GitFileStatus.Deleted; } else if (proc.Matches('R')) { status = GitFileStatus.Renamed; } else if (proc.Matches('C')) { status = GitFileStatus.Copied; } else if (proc.Matches('T')) { status = GitFileStatus.TypeChange; } else if (proc.Matches('U')) { status = GitFileStatus.Unmerged; } else if (proc.Matches('X')) { status = GitFileStatus.Unknown; } else if (proc.Matches('B')) { status = GitFileStatus.Broken; } else if (String.IsNullOrEmpty(line)) { // there's no files on this commit, it's a new one! ReturnGitLogEntry(); return; } else { HandleUnexpected(line); return; } switch (status) { case GitFileStatus.Modified: case GitFileStatus.Added: case GitFileStatus.Deleted: proc.SkipWhitespace(); file = proc.Matches('"') ? proc.ReadUntil('"') : proc.ReadToEnd(); break; case GitFileStatus.Renamed: proc.SkipWhitespace(); originalPath = proc.Matches('"') ? proc.ReadUntil('"') : proc.ReadUntilWhitespace(); proc.SkipWhitespace(); file = proc.Matches('"') ? proc.ReadUntil('"') : proc.ReadToEnd(); break; default: proc.SkipWhitespace(); file = proc.Matches('"') ? proc.ReadUntil('"') : proc.ReadUntilWhitespace(); if (file == null) { file = proc.ReadToEnd(); } break; } changes.Add(gitObjectFactory.CreateGitStatusEntry(file, status, originalPath)); break; default: HandleUnexpected(line); break; } } private void PopNewlines() { while (newlineCount > 0) { descriptionLines.Add(string.Empty); newlineCount--; } } private void HandleUnexpected(string line) { Logger.Error("Unexpected Input:\"{0}\" Phase:{1}", line, phase); Reset(); } private void ReturnGitLogEntry() { PopNewlines(); var description = string.Join(Environment.NewLine, descriptionLines.ToArray()); if (time.HasValue) { RaiseOnEntry(new GitLogEntry() { AuthorName = authorName, CommitName = committerName, MergeA = mergeA, MergeB = mergeB, Changes = changes, AuthorEmail = authorEmail, CommitEmail = committerEmail, Summary = summary, Description = description, CommitID = commitId, TimeString = time.Value.ToString(DateTimeFormatInfo.CurrentInfo), CommitTimeString = committerTime.Value.ToString(DateTimeFormatInfo.CurrentInfo) }); } Reset(); } private enum ProcessingPhase { CommitHash = 0, ParentHash = 1, AuthorName = 2, AuthorEmail = 3, AuthorDate = 4, CommitterName = 5, CommitterEmail = 6, CommitterDate = 7, Summary = 8, Description = 9, Files = 10, } } }
// 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. //////////////////////////////////////////////////////////////////////////// // // // Purpose: This class defines behaviors specific to a writing system. // A writing system is the collection of scripts and // orthographic rules required to represent a language as text. // // //////////////////////////////////////////////////////////////////////////// namespace System.Globalization { using System; using System.Runtime.Serialization; using System.Security.Permissions; using System.Diagnostics.Contracts; [Serializable] [System.Runtime.InteropServices.ComVisible(true)] public class StringInfo { [OptionalField(VersionAdded = 2)] private String m_str; // We allow this class to be serialized but there is no conceivable reason // for them to do so. Thus, we do not serialize the instance variables. [NonSerialized] private int[] m_indexes; // Legacy constructor public StringInfo() : this(""){} // Primary, useful constructor public StringInfo(String value) { this.String = value; } #region Serialization [OnDeserializing] private void OnDeserializing(StreamingContext ctx) { m_str = String.Empty; } [OnDeserialized] private void OnDeserialized(StreamingContext ctx) { if (m_str.Length == 0) { m_indexes = null; } } #endregion Serialization [System.Runtime.InteropServices.ComVisible(false)] public override bool Equals(Object value) { StringInfo that = value as StringInfo; if (that != null) { return (this.m_str.Equals(that.m_str)); } return (false); } [System.Runtime.InteropServices.ComVisible(false)] public override int GetHashCode() { return this.m_str.GetHashCode(); } // Our zero-based array of index values into the string. Initialize if // our private array is not yet, in fact, initialized. private int[] Indexes { get { if((null == this.m_indexes) && (0 < this.String.Length)) { this.m_indexes = StringInfo.ParseCombiningCharacters(this.String); } return(this.m_indexes); } } public String String { get { return(this.m_str); } set { if (null == value) { throw new ArgumentNullException(nameof(String), Environment.GetResourceString("ArgumentNull_String")); } Contract.EndContractBlock(); this.m_str = value; this.m_indexes = null; } } public int LengthInTextElements { get { if(null == this.Indexes) { // Indexes not initialized, so assume length zero return(0); } return(this.Indexes.Length); } } public String SubstringByTextElements(int startingTextElement) { // If the string is empty, no sense going further. if(null == this.Indexes) { // Just decide which error to give depending on the param they gave us.... if(startingTextElement < 0) { throw new ArgumentOutOfRangeException(nameof(startingTextElement), Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum")); } else { throw new ArgumentOutOfRangeException(nameof(startingTextElement), Environment.GetResourceString("Arg_ArgumentOutOfRangeException")); } } return (this.SubstringByTextElements(startingTextElement, this.Indexes.Length - startingTextElement)); } public String SubstringByTextElements(int startingTextElement, int lengthInTextElements) { // // Parameter checking // if(startingTextElement < 0) { throw new ArgumentOutOfRangeException(nameof(startingTextElement), Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum")); } if(this.String.Length == 0 || startingTextElement >= this.Indexes.Length) { throw new ArgumentOutOfRangeException(nameof(startingTextElement), Environment.GetResourceString("Arg_ArgumentOutOfRangeException")); } if(lengthInTextElements < 0) { throw new ArgumentOutOfRangeException(nameof(lengthInTextElements), Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum")); } if(startingTextElement > this.Indexes.Length - lengthInTextElements) { throw new ArgumentOutOfRangeException(nameof(lengthInTextElements), Environment.GetResourceString("Arg_ArgumentOutOfRangeException")); } int start = this.Indexes[startingTextElement]; if(startingTextElement + lengthInTextElements == this.Indexes.Length) { // We are at the last text element in the string and because of that // must handle the call differently. return(this.String.Substring(start)); } else { return(this.String.Substring(start, (this.Indexes[lengthInTextElements + startingTextElement] - start))); } } public static String GetNextTextElement(String str) { return (GetNextTextElement(str, 0)); } //////////////////////////////////////////////////////////////////////// // // Get the code point count of the current text element. // // A combining class is defined as: // A character/surrogate that has the following Unicode category: // * NonSpacingMark (e.g. U+0300 COMBINING GRAVE ACCENT) // * SpacingCombiningMark (e.g. U+ 0903 DEVANGARI SIGN VISARGA) // * EnclosingMark (e.g. U+20DD COMBINING ENCLOSING CIRCLE) // // In the context of GetNextTextElement() and ParseCombiningCharacters(), a text element is defined as: // // 1. If a character/surrogate is in the following category, it is a text element. // It can NOT further combine with characters in the combinging class to form a text element. // * one of the Unicode category in the combinging class // * UnicodeCategory.Format // * UnicodeCateogry.Control // * UnicodeCategory.OtherNotAssigned // 2. Otherwise, the character/surrogate can be combined with characters in the combinging class to form a text element. // // Return: // The length of the current text element // // Parameters: // String str // index The starting index // len The total length of str (to define the upper boundary) // ucCurrent The Unicode category pointed by Index. It will be updated to the uc of next character if this is not the last text element. // currentCharCount The char count of an abstract char pointed by Index. It will be updated to the char count of next abstract character if this is not the last text element. // //////////////////////////////////////////////////////////////////////// internal static int GetCurrentTextElementLen(String str, int index, int len, ref UnicodeCategory ucCurrent, ref int currentCharCount) { Contract.Assert(index >= 0 && len >= 0, "StringInfo.GetCurrentTextElementLen() : index = " + index + ", len = " + len); Contract.Assert(index < len, "StringInfo.GetCurrentTextElementLen() : index = " + index + ", len = " + len); if (index + currentCharCount == len) { // This is the last character/surrogate in the string. return (currentCharCount); } // Call an internal GetUnicodeCategory, which will tell us both the unicode category, and also tell us if it is a surrogate pair or not. int nextCharCount; UnicodeCategory ucNext = CharUnicodeInfo.InternalGetUnicodeCategory(str, index + currentCharCount, out nextCharCount); if (CharUnicodeInfo.IsCombiningCategory(ucNext)) { // The next element is a combining class. // Check if the current text element to see if it is a valid base category (i.e. it should not be a combining category, // not a format character, and not a control character). if (CharUnicodeInfo.IsCombiningCategory(ucCurrent) || (ucCurrent == UnicodeCategory.Format) || (ucCurrent == UnicodeCategory.Control) || (ucCurrent == UnicodeCategory.OtherNotAssigned) || (ucCurrent == UnicodeCategory.Surrogate)) // An unpair high surrogate or low surrogate { // Will fall thru and return the currentCharCount } else { int startIndex = index; // Remember the current index. // We have a valid base characters, and we have a character (or surrogate) that is combining. // Check if there are more combining characters to follow. // Check if the next character is a nonspacing character. index += currentCharCount + nextCharCount; while (index < len) { ucNext = CharUnicodeInfo.InternalGetUnicodeCategory(str, index, out nextCharCount); if (!CharUnicodeInfo.IsCombiningCategory(ucNext)) { ucCurrent = ucNext; currentCharCount = nextCharCount; break; } index += nextCharCount; } return (index - startIndex); } } // The return value will be the currentCharCount. int ret = currentCharCount; ucCurrent = ucNext; // Update currentCharCount. currentCharCount = nextCharCount; return (ret); } // Returns the str containing the next text element in str starting at // index index. If index is not supplied, then it will start at the beginning // of str. It recognizes a base character plus one or more combining // characters or a properly formed surrogate pair as a text element. See also // the ParseCombiningCharacters() and the ParseSurrogates() methods. public static String GetNextTextElement(String str, int index) { // // Validate parameters. // if (str==null) { throw new ArgumentNullException(nameof(str)); } Contract.EndContractBlock(); int len = str.Length; if (index < 0 || index >= len) { if (index == len) { return (String.Empty); } throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index")); } int charLen; UnicodeCategory uc = CharUnicodeInfo.InternalGetUnicodeCategory(str, index, out charLen); return (str.Substring(index, GetCurrentTextElementLen(str, index, len, ref uc, ref charLen))); } public static TextElementEnumerator GetTextElementEnumerator(String str) { return (GetTextElementEnumerator(str, 0)); } public static TextElementEnumerator GetTextElementEnumerator(String str, int index) { // // Validate parameters. // if (str==null) { throw new ArgumentNullException(nameof(str)); } Contract.EndContractBlock(); int len = str.Length; if (index < 0 || (index > len)) { throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index")); } return (new TextElementEnumerator(str, index, len)); } /* * Returns the indices of each base character or properly formed surrogate pair * within the str. It recognizes a base character plus one or more combining * characters or a properly formed surrogate pair as a text element and returns * the index of the base character or high surrogate. Each index is the * beginning of a text element within a str. The length of each element is * easily computed as the difference between successive indices. The length of * the array will always be less than or equal to the length of the str. For * example, given the str \u4f00\u302a\ud800\udc00\u4f01, this method would * return the indices: 0, 2, 4. */ public static int[] ParseCombiningCharacters(String str) { if (str == null) { throw new ArgumentNullException(nameof(str)); } Contract.EndContractBlock(); int len = str.Length; int[] result = new int[len]; if (len == 0) { return (result); } int resultCount = 0; int i = 0; int currentCharLen; UnicodeCategory currentCategory = CharUnicodeInfo.InternalGetUnicodeCategory(str, 0, out currentCharLen); while (i < len) { result[resultCount++] = i; i += GetCurrentTextElementLen(str, i, len, ref currentCategory, ref currentCharLen); } if (resultCount < len) { int[] returnArray = new int[resultCount]; Array.Copy(result, returnArray, resultCount); return (returnArray); } return (result); } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/protobuf/wrappers.proto #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace Google.Protobuf.WellKnownTypes { /// <summary>Holder for reflection information generated from google/protobuf/wrappers.proto</summary> public static partial class WrappersReflection { #region Descriptor /// <summary>File descriptor for google/protobuf/wrappers.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static WrappersReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "Ch5nb29nbGUvcHJvdG9idWYvd3JhcHBlcnMucHJvdG8SD2dvb2dsZS5wcm90", "b2J1ZiIcCgtEb3VibGVWYWx1ZRINCgV2YWx1ZRgBIAEoASIbCgpGbG9hdFZh", "bHVlEg0KBXZhbHVlGAEgASgCIhsKCkludDY0VmFsdWUSDQoFdmFsdWUYASAB", "KAMiHAoLVUludDY0VmFsdWUSDQoFdmFsdWUYASABKAQiGwoKSW50MzJWYWx1", "ZRINCgV2YWx1ZRgBIAEoBSIcCgtVSW50MzJWYWx1ZRINCgV2YWx1ZRgBIAEo", "DSIaCglCb29sVmFsdWUSDQoFdmFsdWUYASABKAgiHAoLU3RyaW5nVmFsdWUS", "DQoFdmFsdWUYASABKAkiGwoKQnl0ZXNWYWx1ZRINCgV2YWx1ZRgBIAEoDEJ8", "ChNjb20uZ29vZ2xlLnByb3RvYnVmQg1XcmFwcGVyc1Byb3RvUAFaKmdpdGh1", "Yi5jb20vZ29sYW5nL3Byb3RvYnVmL3B0eXBlcy93cmFwcGVyc/gBAaICA0dQ", "QqoCHkdvb2dsZS5Qcm90b2J1Zi5XZWxsS25vd25UeXBlc2IGcHJvdG8z")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.WellKnownTypes.DoubleValue), global::Google.Protobuf.WellKnownTypes.DoubleValue.Parser, new[]{ "Value" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.WellKnownTypes.FloatValue), global::Google.Protobuf.WellKnownTypes.FloatValue.Parser, new[]{ "Value" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.WellKnownTypes.Int64Value), global::Google.Protobuf.WellKnownTypes.Int64Value.Parser, new[]{ "Value" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.WellKnownTypes.UInt64Value), global::Google.Protobuf.WellKnownTypes.UInt64Value.Parser, new[]{ "Value" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.WellKnownTypes.Int32Value), global::Google.Protobuf.WellKnownTypes.Int32Value.Parser, new[]{ "Value" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.WellKnownTypes.UInt32Value), global::Google.Protobuf.WellKnownTypes.UInt32Value.Parser, new[]{ "Value" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.WellKnownTypes.BoolValue), global::Google.Protobuf.WellKnownTypes.BoolValue.Parser, new[]{ "Value" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.WellKnownTypes.StringValue), global::Google.Protobuf.WellKnownTypes.StringValue.Parser, new[]{ "Value" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.WellKnownTypes.BytesValue), global::Google.Protobuf.WellKnownTypes.BytesValue.Parser, new[]{ "Value" }, null, null, null) })); } #endregion } #region Messages /// <summary> /// Wrapper message for `double`. /// /// The JSON representation for `DoubleValue` is JSON number. /// </summary> public sealed partial class DoubleValue : pb::IMessage<DoubleValue> { private static readonly pb::MessageParser<DoubleValue> _parser = new pb::MessageParser<DoubleValue>(() => new DoubleValue()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<DoubleValue> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Protobuf.WellKnownTypes.WrappersReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public DoubleValue() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public DoubleValue(DoubleValue other) : this() { value_ = other.value_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public DoubleValue Clone() { return new DoubleValue(this); } /// <summary>Field number for the "value" field.</summary> public const int ValueFieldNumber = 1; private double value_; /// <summary> /// The double value. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public double Value { get { return value_; } set { value_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as DoubleValue); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(DoubleValue other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Value != other.Value) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Value != 0D) hash ^= Value.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (Value != 0D) { output.WriteRawTag(9); output.WriteDouble(Value); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Value != 0D) { size += 1 + 8; } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(DoubleValue other) { if (other == null) { return; } if (other.Value != 0D) { Value = other.Value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 9: { Value = input.ReadDouble(); break; } } } } } /// <summary> /// Wrapper message for `float`. /// /// The JSON representation for `FloatValue` is JSON number. /// </summary> public sealed partial class FloatValue : pb::IMessage<FloatValue> { private static readonly pb::MessageParser<FloatValue> _parser = new pb::MessageParser<FloatValue>(() => new FloatValue()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<FloatValue> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Protobuf.WellKnownTypes.WrappersReflection.Descriptor.MessageTypes[1]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public FloatValue() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public FloatValue(FloatValue other) : this() { value_ = other.value_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public FloatValue Clone() { return new FloatValue(this); } /// <summary>Field number for the "value" field.</summary> public const int ValueFieldNumber = 1; private float value_; /// <summary> /// The float value. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public float Value { get { return value_; } set { value_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as FloatValue); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(FloatValue other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Value != other.Value) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Value != 0F) hash ^= Value.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (Value != 0F) { output.WriteRawTag(13); output.WriteFloat(Value); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Value != 0F) { size += 1 + 4; } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(FloatValue other) { if (other == null) { return; } if (other.Value != 0F) { Value = other.Value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 13: { Value = input.ReadFloat(); break; } } } } } /// <summary> /// Wrapper message for `int64`. /// /// The JSON representation for `Int64Value` is JSON string. /// </summary> public sealed partial class Int64Value : pb::IMessage<Int64Value> { private static readonly pb::MessageParser<Int64Value> _parser = new pb::MessageParser<Int64Value>(() => new Int64Value()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<Int64Value> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Protobuf.WellKnownTypes.WrappersReflection.Descriptor.MessageTypes[2]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Int64Value() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Int64Value(Int64Value other) : this() { value_ = other.value_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Int64Value Clone() { return new Int64Value(this); } /// <summary>Field number for the "value" field.</summary> public const int ValueFieldNumber = 1; private long value_; /// <summary> /// The int64 value. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public long Value { get { return value_; } set { value_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as Int64Value); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(Int64Value other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Value != other.Value) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Value != 0L) hash ^= Value.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (Value != 0L) { output.WriteRawTag(8); output.WriteInt64(Value); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Value != 0L) { size += 1 + pb::CodedOutputStream.ComputeInt64Size(Value); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(Int64Value other) { if (other == null) { return; } if (other.Value != 0L) { Value = other.Value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 8: { Value = input.ReadInt64(); break; } } } } } /// <summary> /// Wrapper message for `uint64`. /// /// The JSON representation for `UInt64Value` is JSON string. /// </summary> public sealed partial class UInt64Value : pb::IMessage<UInt64Value> { private static readonly pb::MessageParser<UInt64Value> _parser = new pb::MessageParser<UInt64Value>(() => new UInt64Value()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<UInt64Value> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Protobuf.WellKnownTypes.WrappersReflection.Descriptor.MessageTypes[3]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public UInt64Value() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public UInt64Value(UInt64Value other) : this() { value_ = other.value_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public UInt64Value Clone() { return new UInt64Value(this); } /// <summary>Field number for the "value" field.</summary> public const int ValueFieldNumber = 1; private ulong value_; /// <summary> /// The uint64 value. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ulong Value { get { return value_; } set { value_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as UInt64Value); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(UInt64Value other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Value != other.Value) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Value != 0UL) hash ^= Value.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (Value != 0UL) { output.WriteRawTag(8); output.WriteUInt64(Value); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Value != 0UL) { size += 1 + pb::CodedOutputStream.ComputeUInt64Size(Value); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(UInt64Value other) { if (other == null) { return; } if (other.Value != 0UL) { Value = other.Value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 8: { Value = input.ReadUInt64(); break; } } } } } /// <summary> /// Wrapper message for `int32`. /// /// The JSON representation for `Int32Value` is JSON number. /// </summary> public sealed partial class Int32Value : pb::IMessage<Int32Value> { private static readonly pb::MessageParser<Int32Value> _parser = new pb::MessageParser<Int32Value>(() => new Int32Value()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<Int32Value> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Protobuf.WellKnownTypes.WrappersReflection.Descriptor.MessageTypes[4]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Int32Value() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Int32Value(Int32Value other) : this() { value_ = other.value_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Int32Value Clone() { return new Int32Value(this); } /// <summary>Field number for the "value" field.</summary> public const int ValueFieldNumber = 1; private int value_; /// <summary> /// The int32 value. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int Value { get { return value_; } set { value_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as Int32Value); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(Int32Value other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Value != other.Value) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Value != 0) hash ^= Value.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (Value != 0) { output.WriteRawTag(8); output.WriteInt32(Value); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Value != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(Value); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(Int32Value other) { if (other == null) { return; } if (other.Value != 0) { Value = other.Value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 8: { Value = input.ReadInt32(); break; } } } } } /// <summary> /// Wrapper message for `uint32`. /// /// The JSON representation for `UInt32Value` is JSON number. /// </summary> public sealed partial class UInt32Value : pb::IMessage<UInt32Value> { private static readonly pb::MessageParser<UInt32Value> _parser = new pb::MessageParser<UInt32Value>(() => new UInt32Value()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<UInt32Value> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Protobuf.WellKnownTypes.WrappersReflection.Descriptor.MessageTypes[5]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public UInt32Value() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public UInt32Value(UInt32Value other) : this() { value_ = other.value_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public UInt32Value Clone() { return new UInt32Value(this); } /// <summary>Field number for the "value" field.</summary> public const int ValueFieldNumber = 1; private uint value_; /// <summary> /// The uint32 value. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public uint Value { get { return value_; } set { value_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as UInt32Value); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(UInt32Value other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Value != other.Value) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Value != 0) hash ^= Value.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (Value != 0) { output.WriteRawTag(8); output.WriteUInt32(Value); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Value != 0) { size += 1 + pb::CodedOutputStream.ComputeUInt32Size(Value); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(UInt32Value other) { if (other == null) { return; } if (other.Value != 0) { Value = other.Value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 8: { Value = input.ReadUInt32(); break; } } } } } /// <summary> /// Wrapper message for `bool`. /// /// The JSON representation for `BoolValue` is JSON `true` and `false`. /// </summary> public sealed partial class BoolValue : pb::IMessage<BoolValue> { private static readonly pb::MessageParser<BoolValue> _parser = new pb::MessageParser<BoolValue>(() => new BoolValue()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<BoolValue> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Protobuf.WellKnownTypes.WrappersReflection.Descriptor.MessageTypes[6]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public BoolValue() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public BoolValue(BoolValue other) : this() { value_ = other.value_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public BoolValue Clone() { return new BoolValue(this); } /// <summary>Field number for the "value" field.</summary> public const int ValueFieldNumber = 1; private bool value_; /// <summary> /// The bool value. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Value { get { return value_; } set { value_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as BoolValue); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(BoolValue other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Value != other.Value) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Value != false) hash ^= Value.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (Value != false) { output.WriteRawTag(8); output.WriteBool(Value); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Value != false) { size += 1 + 1; } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(BoolValue other) { if (other == null) { return; } if (other.Value != false) { Value = other.Value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 8: { Value = input.ReadBool(); break; } } } } } /// <summary> /// Wrapper message for `string`. /// /// The JSON representation for `StringValue` is JSON string. /// </summary> public sealed partial class StringValue : pb::IMessage<StringValue> { private static readonly pb::MessageParser<StringValue> _parser = new pb::MessageParser<StringValue>(() => new StringValue()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<StringValue> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Protobuf.WellKnownTypes.WrappersReflection.Descriptor.MessageTypes[7]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public StringValue() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public StringValue(StringValue other) : this() { value_ = other.value_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public StringValue Clone() { return new StringValue(this); } /// <summary>Field number for the "value" field.</summary> public const int ValueFieldNumber = 1; private string value_ = ""; /// <summary> /// The string value. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Value { get { return value_; } set { value_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as StringValue); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(StringValue other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Value != other.Value) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Value.Length != 0) hash ^= Value.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (Value.Length != 0) { output.WriteRawTag(10); output.WriteString(Value); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Value.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Value); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(StringValue other) { if (other == null) { return; } if (other.Value.Length != 0) { Value = other.Value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { Value = input.ReadString(); break; } } } } } /// <summary> /// Wrapper message for `bytes`. /// /// The JSON representation for `BytesValue` is JSON string. /// </summary> public sealed partial class BytesValue : pb::IMessage<BytesValue> { private static readonly pb::MessageParser<BytesValue> _parser = new pb::MessageParser<BytesValue>(() => new BytesValue()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<BytesValue> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Protobuf.WellKnownTypes.WrappersReflection.Descriptor.MessageTypes[8]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public BytesValue() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public BytesValue(BytesValue other) : this() { value_ = other.value_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public BytesValue Clone() { return new BytesValue(this); } /// <summary>Field number for the "value" field.</summary> public const int ValueFieldNumber = 1; private pb::ByteString value_ = pb::ByteString.Empty; /// <summary> /// The bytes value. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pb::ByteString Value { get { return value_; } set { value_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as BytesValue); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(BytesValue other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Value != other.Value) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Value.Length != 0) hash ^= Value.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (Value.Length != 0) { output.WriteRawTag(10); output.WriteBytes(Value); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Value.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeBytesSize(Value); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(BytesValue other) { if (other == null) { return; } if (other.Value.Length != 0) { Value = other.Value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { Value = input.ReadBytes(); break; } } } } } #endregion } #endregion Designer generated code
using System; using System.Collections.Generic; using System.IO.Ports; using System.Linq; using System.Net.NetworkInformation; using System.Reflection; using System.Windows.Forms; using Microsoft.VisualBasic; using VSPropertyPages; using Cosmos.Build.Common; using DebugMode = Cosmos.Build.Common.DebugMode; namespace Cosmos.VS.ProjectSystem.VS.PropertyPages { internal partial class OldCosmosPropertyPageControl : WinFormsPropertyPageUI { protected class ProfileItem { public string Prefix; public string Name; public bool IsPreset; public override string ToString() => Name; } private OldCosmosPropertyPageViewModel mViewModel; protected ProfilePresets mPresets = new ProfilePresets(); protected int mVMwareAndBochsDebugPipe; protected int mHyperVDebugPipe; protected bool mShowTabBochs; protected bool mShowTabDebug; protected bool mShowTabDeployment; protected bool mShowTabLaunch; protected bool mShowTabVMware; protected bool mShowTabHyperV; protected bool mShowTabPXE; protected bool mShowTabUSB; protected bool mShowTabISO; protected bool mShowTabSlave; protected bool FreezeEvents; public OldCosmosPropertyPageControl(OldCosmosPropertyPageViewModel aViewModel) { InitializeComponent(); mViewModel = aViewModel; #region Profile butnProfileClone.Click += new EventHandler(butnProfileClone_Click); butnProfileDelete.Click += new EventHandler(butnProfileDelete_Click); butnProfileRename.Click += new EventHandler(butnProfileRename_Click); lboxProfile.SelectedIndexChanged += delegate (Object sender, EventArgs e) { var xProfile = (ProfileItem)lboxProfile.SelectedItem; if (xProfile.Prefix != mViewModel.BuildProperties.Profile) { // Save existing profile mViewModel.BuildProperties.SaveProfile(mViewModel.BuildProperties.Profile); // Load newly selected profile mViewModel.BuildProperties.LoadProfile(xProfile.Prefix); mViewModel.BuildProperties.Profile = xProfile.Prefix; UpdateUI(); } }; #endregion # region Deploy lboxDeployment.SelectedIndexChanged += delegate (Object sender, EventArgs e) { var xValue = (DeploymentType)((EnumValue)lboxDeployment.SelectedItem).Value; if (xValue != mViewModel.BuildProperties.Deployment) { mViewModel.BuildProperties.Deployment = xValue; } }; #endregion # region Launch lboxLaunch.SelectedIndexChanged += delegate (Object sender, EventArgs e) { var xValue = (LaunchType)((EnumValue)lboxLaunch.SelectedItem).Value; if (xValue != mViewModel.BuildProperties.Launch) { mViewModel.BuildProperties.Launch = xValue; // Bochs requires an ISO. Force Deployment property. if (LaunchType.Bochs == xValue) { if (DeploymentType.ISO != mViewModel.BuildProperties.Deployment) { foreach (EnumValue scannedValue in lboxDeployment.Items) { if (DeploymentType.ISO == (DeploymentType)scannedValue.Value) { lboxDeployment.SelectedItem = scannedValue; break; } } } } } }; #endregion #region Compile comboFramework.SelectedIndexChanged += delegate (Object sender, EventArgs e) { if (FreezeEvents) return; var value = (Framework)((EnumValue)comboFramework.SelectedItem).Value; if (value != mViewModel.BuildProperties.Framework) { mViewModel.BuildProperties.Framework = value; } }; comboBinFormat.SelectedIndexChanged += delegate (Object sender, EventArgs e) { if (FreezeEvents) return; var value = (BinFormat)((EnumValue)comboBinFormat.SelectedItem).Value; if (value != mViewModel.BuildProperties.BinFormat) { mViewModel.BuildProperties.BinFormat = value; } }; #endregion #region Assembler checkUseInternalAssembler.CheckedChanged += delegate (Object sender, EventArgs e) { if (FreezeEvents) return; bool value = checkUseInternalAssembler.Checked; if (value != mViewModel.BuildProperties.UseInternalAssembler) { mViewModel.BuildProperties.UseInternalAssembler = value; } }; #endregion #region VMware cmboVMwareEdition.SelectedIndexChanged += delegate (Object sender, EventArgs e) { if (FreezeEvents) return; var x = (VMwareEdition)((EnumValue)cmboVMwareEdition.SelectedItem).Value; if (x != mViewModel.BuildProperties.VMwareEdition) { mViewModel.BuildProperties.VMwareEdition = x; } }; #endregion #region PXE comboPxeInterface.TextChanged += delegate (Object sender, EventArgs e) { if (FreezeEvents) return; var x = comboPxeInterface.Text.Trim(); if (x != mViewModel.BuildProperties.PxeInterface) { mViewModel.BuildProperties.PxeInterface = x; } }; cmboSlavePort.SelectedIndexChanged += delegate (Object sender, EventArgs e) { if (FreezeEvents) return; var x = (string)cmboSlavePort.SelectedItem; if (x != mViewModel.BuildProperties.SlavePort) { mViewModel.BuildProperties.SlavePort = x; } }; butnPxeRefresh.Click += new EventHandler(butnPxeRefresh_Click); #endregion #region Debug comboDebugMode.SelectedIndexChanged += delegate (Object sender, EventArgs e) { if (FreezeEvents) return; var x = (DebugMode)((EnumValue)comboDebugMode.SelectedItem).Value; if (x != mViewModel.BuildProperties.DebugMode) { mViewModel.BuildProperties.DebugMode = x; } }; chckEnableDebugStub.CheckedChanged += delegate (object aSender, EventArgs e) { if (FreezeEvents) return; panlDebugSettings.Enabled = chckEnableDebugStub.Checked; mViewModel.BuildProperties.DebugEnabled = chckEnableDebugStub.Checked; }; comboTraceMode.SelectedIndexChanged += delegate (Object sender, EventArgs e) { if (FreezeEvents) return; var x = (TraceAssemblies)((EnumValue)comboTraceMode.SelectedItem).Value; if (x != mViewModel.BuildProperties.TraceAssemblies) { mViewModel.BuildProperties.TraceAssemblies = x; } }; checkIgnoreDebugStubAttribute.CheckedChanged += delegate (Object sender, EventArgs e) { if (FreezeEvents) return; bool x = checkIgnoreDebugStubAttribute.Checked; if (x != mViewModel.BuildProperties.IgnoreDebugStubAttribute) { mViewModel.BuildProperties.IgnoreDebugStubAttribute = x; } }; cmboCosmosDebugPort.SelectedIndexChanged += delegate (Object sender, EventArgs e) { if (FreezeEvents) return; var x = (string)cmboCosmosDebugPort.SelectedItem; if (x != mViewModel.BuildProperties.CosmosDebugPort) { mViewModel.BuildProperties.CosmosDebugPort = x; } }; cmboVisualStudioDebugPort.SelectedIndexChanged += delegate (Object sender, EventArgs e) { if (FreezeEvents) return; var x = (string)cmboVisualStudioDebugPort.SelectedItem; if (x != mViewModel.BuildProperties.VisualStudioDebugPort) { mViewModel.BuildProperties.VisualStudioDebugPort = x; } }; checkEnableGDB.CheckedChanged += delegate (Object sender, EventArgs e) { if (FreezeEvents) return; bool x = checkEnableGDB.Checked; if (x != mViewModel.BuildProperties.EnableGDB) { mViewModel.BuildProperties.EnableGDB = x; } checkStartCosmosGDB.Enabled = x; checkStartCosmosGDB.Checked = x; }; checkStartCosmosGDB.CheckedChanged += delegate (Object sender, EventArgs e) { if (FreezeEvents) return; bool x = checkStartCosmosGDB.Checked; if (x != mViewModel.BuildProperties.StartCosmosGDB) { mViewModel.BuildProperties.StartCosmosGDB = x; } }; checkEnableBochsDebug.CheckedChanged += delegate (Object sender, EventArgs e) { if (FreezeEvents) return; bool x = checkEnableBochsDebug.Checked; if (x != mViewModel.BuildProperties.EnableBochsDebug) { mViewModel.BuildProperties.EnableBochsDebug = x; } checkStartBochsDebugGui.Enabled = x; if (x == false) { checkStartBochsDebugGui.Checked = x; } }; checkStartBochsDebugGui.CheckedChanged += delegate (object sender, EventArgs e) { if (FreezeEvents) return; bool x = checkStartBochsDebugGui.Checked; if (x != mViewModel.BuildProperties.StartBochsDebugGui) { mViewModel.BuildProperties.StartBochsDebugGui = x; } }; #endregion FillProperties(); } protected void RemoveTab(TabPage aTab) { if (TabControl1.TabPages.Contains(aTab)) { TabControl1.TabPages.Remove(aTab); } } protected void UpdateTabs() { var xTab = TabControl1.SelectedTab; RemoveTab(tabDebug); RemoveTab(tabDeployment); RemoveTab(tabLaunch); RemoveTab(tabVMware); RemoveTab(tabHyperV); RemoveTab(tabPXE); RemoveTab(tabUSB); RemoveTab(tabISO); RemoveTab(tabSlave); RemoveTab(tabBochs); if (mShowTabDebug) { TabControl1.TabPages.Add(tabDebug); } if (mShowTabDeployment) { TabControl1.TabPages.Add(tabDeployment); } if (mShowTabPXE) { TabControl1.TabPages.Add(tabPXE); } if (mShowTabUSB) { TabControl1.TabPages.Add(tabUSB); } if (mShowTabISO) { TabControl1.TabPages.Add(tabISO); } if (mShowTabLaunch) { TabControl1.TabPages.Add(tabLaunch); } if (mShowTabVMware) { TabControl1.TabPages.Add(tabVMware); } if (mShowTabHyperV) { TabControl1.TabPages.Add(tabHyperV); } if (mShowTabSlave) { TabControl1.TabPages.Add(tabSlave); } if (mShowTabBochs) { TabControl1.TabPages.Add(tabBochs); } if (TabControl1.TabPages.Contains(xTab)) { TabControl1.SelectedTab = xTab; } else { TabControl1.SelectedTab = tabProfile; } } protected void UpdatePresetsUI() { FreezeEvents = true; mShowTabDebug = true; cmboCosmosDebugPort.Enabled = true; cmboVisualStudioDebugPort.Enabled = true; if (mViewModel.BuildProperties.Profile == "ISO") { mShowTabDebug = false; chckEnableDebugStub.Checked = false; } else if (mViewModel.BuildProperties.Profile == "USB") { mShowTabDebug = false; mShowTabUSB = true; } else if (mViewModel.BuildProperties.Profile == "VMware") { mShowTabVMware = true; chckEnableDebugStub.Checked = true; chkEnableStackCorruptionDetection.Checked = true; cmboCosmosDebugPort.Enabled = false; cmboVisualStudioDebugPort.Enabled = false; cmboVisualStudioDebugPort.SelectedIndex = mVMwareAndBochsDebugPipe; } else if (mViewModel.BuildProperties.Profile == "HyperV") { mShowTabHyperV = true; chckEnableDebugStub.Checked = true; chkEnableStackCorruptionDetection.Checked = true; cmboCosmosDebugPort.Enabled = false; cmboVisualStudioDebugPort.Enabled = false; cmboVisualStudioDebugPort.SelectedIndex = mHyperVDebugPipe; } else if (mViewModel.BuildProperties.Profile == "PXE") { chckEnableDebugStub.Checked = false; } else if (mViewModel.BuildProperties.Profile == "Bochs") { mShowTabBochs = true; chckEnableDebugStub.Checked = true; chkEnableStackCorruptionDetection.Checked = true; cmboCosmosDebugPort.Enabled = false; cmboVisualStudioDebugPort.Enabled = false; cmboVisualStudioDebugPort.SelectedIndex = mVMwareAndBochsDebugPipe; } else if (mViewModel.BuildProperties.Profile == "IntelEdison") { mShowTabBochs = false; mShowTabVMware = false; cmboVisualStudioDebugPort.Enabled = false; } FreezeEvents = false; } protected void UpdateUI() { UpdatePresetsUI(); var xProfile = (ProfileItem)lboxProfile.SelectedItem; if (xProfile == null) { return; } if (mShowTabDebug == false) { chckEnableDebugStub.Checked = false; } lablCurrentProfile.Text = xProfile.Name; lablDeployText.Text = mViewModel.BuildProperties.Description; lboxDeployment.SelectedItem = mViewModel.BuildProperties.Deployment; // Launch lboxLaunch.SelectedItem = mViewModel.BuildProperties.Launch; lablBuildOnly.Visible = mViewModel.BuildProperties.Launch == LaunchType.None; lboxDeployment.SelectedItem = EnumValue.Find(lboxDeployment.Items, mViewModel.BuildProperties.Deployment); lboxLaunch.SelectedItem = EnumValue.Find(lboxLaunch.Items, mViewModel.BuildProperties.Launch); cmboVMwareEdition.SelectedItem = EnumValue.Find(cmboVMwareEdition.Items, mViewModel.BuildProperties.VMwareEdition); chckEnableDebugStub.Checked = mViewModel.BuildProperties.DebugEnabled; chkEnableStackCorruptionDetection.Checked = mViewModel.BuildProperties.StackCorruptionDetectionEnabled; comboStackCorruptionDetectionLevel.SelectedItem = EnumValue.Find(comboStackCorruptionDetectionLevel.Items, mViewModel.BuildProperties.StackCorruptionDetectionLevel); panlDebugSettings.Enabled = mViewModel.BuildProperties.DebugEnabled; cmboCosmosDebugPort.SelectedIndex = cmboCosmosDebugPort.Items.IndexOf(mViewModel.BuildProperties.CosmosDebugPort); if (!String.IsNullOrWhiteSpace(mViewModel.BuildProperties.VisualStudioDebugPort)) { cmboVisualStudioDebugPort.SelectedIndex = cmboVisualStudioDebugPort.Items.IndexOf(mViewModel.BuildProperties.VisualStudioDebugPort); } comboFramework.SelectedItem = EnumValue.Find(comboFramework.Items, mViewModel.BuildProperties.Framework); comboBinFormat.SelectedItem = EnumValue.Find(comboBinFormat.Items, mViewModel.BuildProperties.BinFormat); checkUseInternalAssembler.Checked = mViewModel.BuildProperties.UseInternalAssembler; checkEnableGDB.Checked = mViewModel.BuildProperties.EnableGDB; checkStartCosmosGDB.Checked = mViewModel.BuildProperties.StartCosmosGDB; checkEnableBochsDebug.Checked = mViewModel.BuildProperties.EnableBochsDebug; checkStartBochsDebugGui.Checked = mViewModel.BuildProperties.StartBochsDebugGui; // Locked to COM1 for now. //cmboCosmosDebugPort.SelectedIndex = 0; #region Slave cmboSlavePort.SelectedIndex = cmboSlavePort.Items.IndexOf(mViewModel.BuildProperties.SlavePort); #endregion checkIgnoreDebugStubAttribute.Checked = mViewModel.BuildProperties.IgnoreDebugStubAttribute; comboDebugMode.SelectedItem = EnumValue.Find(comboDebugMode.Items, mViewModel.BuildProperties.DebugMode); comboTraceMode.SelectedItem = EnumValue.Find(comboTraceMode.Items, mViewModel.BuildProperties.TraceAssemblies); lablPreset.Visible = xProfile.IsPreset; mShowTabDeployment = !xProfile.IsPreset; mShowTabLaunch = !xProfile.IsPreset; // mShowTabISO = mViewModel.BuildProperties.Deployment == DeploymentType.ISO; mShowTabUSB = mViewModel.BuildProperties.Deployment == DeploymentType.USB; mShowTabPXE = mViewModel.BuildProperties.Deployment == DeploymentType.PXE; // mShowTabVMware = mViewModel.BuildProperties.Launch == LaunchType.VMware; mShowTabHyperV = mViewModel.BuildProperties.Launch == LaunchType.HyperV; mShowTabSlave = mViewModel.BuildProperties.Launch == LaunchType.Slave; mShowTabBochs = (LaunchType.Bochs == mViewModel.BuildProperties.Launch); // UpdateTabs(); } protected int FillProfile(string aPrefix, string aName) { var xProfile = new ProfileItem { Prefix = aPrefix, Name = aName, IsPreset = true }; return lboxProfile.Items.Add(xProfile); } protected int FillProfile(int aID) { var xProfile = new ProfileItem { Prefix = "User" + aID.ToString("000"), IsPreset = false }; xProfile.Name = mViewModel.BuildProperties.GetProperty(xProfile.Prefix + "_Name"); return lboxProfile.Items.Add(xProfile); } protected void FillProfiles() { lboxProfile.Items.Clear(); foreach (var xPreset in mPresets) { FillProfile(xPreset.Key, xPreset.Value); } for (int i = 1; i < 100; i++) { if (!string.IsNullOrEmpty(mViewModel.BuildProperties.GetProperty("User" + i.ToString("000") + "_Name"))) { FillProfile(i); } } } void butnProfileRename_Click(object sender, EventArgs e) { var xItem = (ProfileItem)lboxProfile.SelectedItem; if (xItem == null) { // This should be impossible, but we check for it anwyays. } else if (xItem.IsPreset) { MessageBox.Show("Preset profiles cannot be renamed."); } else { string xName = Interaction.InputBox("Profile Name", "Rename Profile", mViewModel.BuildProperties.Name); if (xName != "") { mViewModel.BuildProperties.Name = xName; xItem.Name = xName; typeof(ListBox).InvokeMember( "RefreshItems", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.InvokeMethod, null, lboxProfile, new object[] { }); } } } void butnProfileDelete_Click(object sender, EventArgs e) { var xItem = (ProfileItem)lboxProfile.SelectedItem; if (xItem == null) { // This should be impossible, but we check for it anwyays. } else if (xItem.IsPreset) { MessageBox.Show("Preset profiles cannot be deleted."); } else if (MessageBox.Show("Delete profile '" + xItem.Name + "'?", "", MessageBoxButtons.YesNo) == DialogResult.Yes) { // Select a new profile first, so the selectchange logic wont barf lboxProfile.SelectedIndex = 0; lboxProfile.Items.Remove(xItem); mViewModel.BuildProperties.DeleteProfile(xItem.Prefix); } } void butnProfileClone_Click(object sender, EventArgs e) { var xItem = (ProfileItem)lboxProfile.SelectedItem; if (xItem == null) { // This should be impossible, but we check for it anwyays. return; } int xID; string xPrefix = null; for (xID = 1; xID < 100; xID++) { xPrefix = "User" + xID.ToString("000"); if (mViewModel.BuildProperties.GetProperty(xPrefix + "_Name") == "") { break; } } if (xID == 100) { MessageBox.Show("No more profile space is available."); return; } mViewModel.BuildProperties.Name = xItem.Prefix + " User " + xID.ToString("000"); mViewModel.BuildProperties.Description = ""; mViewModel.BuildProperties.SaveProfile(xPrefix); lboxProfile.SelectedIndex = FillProfile(xID); } void butnPxeRefresh_Click(object sender, EventArgs e) { FillNetworkInterfaces(); } /// <summary> /// Load properties for the given profile. /// </summary> /// <param name="aPrefix">Name of the profile for which load properties.</param> protected void LoadProfileProps(string aPrefix) { string xPrefix = aPrefix + (aPrefix == "" ? "" : "_"); foreach (var xName in BuildProperties.PropNames) { if (!mViewModel.BuildProperties.ProjectIndependentProperties.Contains(xName)) { string xValue = mViewModel.GetProjectProperty(xPrefix + xName); // This is important that we dont copy empty values, so instead the defaults will be used. if (!string.IsNullOrWhiteSpace(xValue)) { mViewModel.BuildProperties.SetProperty(xPrefix + xName, xValue); } } } } protected void LoadProps() { // Load mViewModel.BuildProperties from project config file. // The reason for loading into mViewModel.BuildProperties seems to be so we can track changes, and cancel if necessary. mViewModel.BuildProperties.Reset(); // Reset cache only on first one // Get selected profile mViewModel.LoadProfile(); mViewModel.LoadProjectProperties(); // Load selected profile props LoadProfileProps(""); foreach (var xPreset in mPresets) { LoadProfileProps(xPreset.Key); } } private void FillProperties() { LoadProps(); FillProfiles(); foreach (ProfileItem xItem in lboxProfile.Items) { if (xItem.Prefix == mViewModel.BuildProperties.Profile) { lboxProfile.SelectedItem = xItem; break; } } lboxDeployment.Items.AddRange(EnumValue.GetEnumValues(typeof(DeploymentType), true)); comboFramework.Items.AddRange(EnumValue.GetEnumValues(typeof(Framework), true)); comboBinFormat.Items.AddRange(EnumValue.GetEnumValues(typeof(BinFormat), true)); lboxLaunch.Items.AddRange(EnumValue.GetEnumValues(typeof(LaunchType), true)); #region VMware cmboVMwareEdition.Items.AddRange(EnumValue.GetEnumValues(typeof(VMwareEdition), true)); #endregion #region Debug cmboCosmosDebugPort.Items.Clear(); FillComPorts(cmboCosmosDebugPort.Items); cmboVisualStudioDebugPort.Items.Clear(); FillComPorts(cmboVisualStudioDebugPort.Items); mVMwareAndBochsDebugPipe = cmboVisualStudioDebugPort.Items.Add(@"Pipe: Cosmos\Serial"); mHyperVDebugPipe = cmboVisualStudioDebugPort.Items.Add(@"Pipe: CosmosSerial"); comboDebugMode.Items.AddRange(EnumValue.GetEnumValues(typeof(DebugMode), false)); comboTraceMode.Items.AddRange(EnumValue.GetEnumValues(typeof(TraceAssemblies), false)); comboStackCorruptionDetectionLevel.Items.AddRange(EnumValue.GetEnumValues(typeof(StackCorruptionDetectionLevel), true)); #endregion #region PXE FillNetworkInterfaces(); cmboSlavePort.Items.Clear(); cmboSlavePort.Items.Add("None"); FillComPorts(cmboSlavePort.Items); #endregion UpdateUI(); } protected void FillComPorts(System.Collections.IList aList) { //TODO http://stackoverflow.com/questions/2937585/how-to-open-a-serial-port-by-friendly-name foreach (string xPort in SerialPort.GetPortNames()) { aList.Add("Serial: " + xPort); } } protected void FillNetworkInterfaces() { comboPxeInterface.Items.Clear(); comboPxeInterface.Items.AddRange(GetNetworkInterfaces().ToArray()); if (mViewModel.BuildProperties.PxeInterface == String.Empty) { if (comboPxeInterface.Items.Count > 0) { comboPxeInterface.Text = comboPxeInterface.Items[0].ToString(); } else { comboPxeInterface.Text = "192.168.42.1"; } } else { comboPxeInterface.Text = mViewModel.BuildProperties.PxeInterface; } } protected List<string> GetNetworkInterfaces() { NetworkInterface[] nInterfaces = NetworkInterface.GetAllNetworkInterfaces(); List<string> interfaces_list = new List<string>(); foreach (NetworkInterface nInterface in nInterfaces) { if (nInterface.OperationalStatus == OperationalStatus.Up) { IPInterfaceProperties ipProperties = nInterface.GetIPProperties(); foreach (var ip in ipProperties.UnicastAddresses) { if (ip.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) { interfaces_list.Add(ip.Address.ToString()); } } } } return interfaces_list; } private void chkEnableStacckCorruptionDetection_CheckedChanged(object sender, EventArgs e) { if (!FreezeEvents) { mViewModel.BuildProperties.StackCorruptionDetectionEnabled = chkEnableStackCorruptionDetection.Checked; comboStackCorruptionDetectionLevel.Enabled = mViewModel.BuildProperties.StackCorruptionDetectionEnabled; } } private void stackCorruptionDetectionLevelComboBox_SelectedIndexChanged(object sender, EventArgs e) { if (!FreezeEvents) { var x = (StackCorruptionDetectionLevel)((EnumValue) comboStackCorruptionDetectionLevel.SelectedItem).Value; if (x != mViewModel.BuildProperties.StackCorruptionDetectionLevel) { mViewModel.BuildProperties.StackCorruptionDetectionLevel = x; } } } } }
// Copyright (c) DotSpatial Team. All rights reserved. // Licensed under the MIT license. See License.txt file in the project root for full license information. using System; using System.ComponentModel; using System.Drawing; using System.Windows.Forms; namespace DotSpatial.Data.Forms { /// <summary> /// frmInputBox. /// </summary> public class InputBox : Form { #region Fields /// <summary> /// Required designer variable. /// </summary> private readonly IContainer _components = null; private Button _cmdCancel; private Button _cmdOk; private Label _lblMessageText; private TextBox _txtInput; #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="InputBox"/> class. /// </summary> public InputBox() { InitializeComponent(); } /// <summary> /// Initializes a new instance of the <see cref="InputBox"/> class. /// </summary> /// <param name="text">Sets the text of the message to show.</param> public InputBox(string text) : this() { _lblMessageText.Text = text; Validation = ValidationType.None; } /// <summary> /// Initializes a new instance of the <see cref="InputBox"/> class. /// </summary> /// <param name="text">The string message to show.</param> /// <param name="caption">The string caption to allow.</param> public InputBox(string text, string caption) : this() { _lblMessageText.Text = text; Validation = ValidationType.None; Text = caption; } /// <summary> /// Initializes a new instance of the <see cref="InputBox"/> class. /// </summary> /// <param name="text">The string message to show.</param> /// <param name="caption">The string caption to allow.</param> /// <param name="validation">A DotSpatial.Data.ValidationType enumeration specifying acceptable validation to return OK.</param> public InputBox(string text, string caption, ValidationType validation) : this() { _lblMessageText.Text = text; Validation = validation; Text = caption; } /// <summary> /// Initializes a new instance of the <see cref="InputBox"/> class. /// </summary> /// <param name="text">The string message to show.</param> /// <param name="caption">The string caption to allow.</param> /// <param name="validation">A DotSpatial.Data.ValidationType enumeration specifying acceptable validation to return OK.</param> /// <param name="icon">Specifies an icon to appear on this messagebox.</param> public InputBox(string text, string caption, ValidationType validation, Icon icon) : this() { _lblMessageText.Text = text; Validation = validation; Text = caption; ShowIcon = true; Icon = icon; } /// <summary> /// Initializes a new instance of the <see cref="InputBox"/> class. /// </summary> /// <param name="owner">Specifies the Form to set as the owner of this dialog.</param> /// <param name="text">Sets the text of the message to show.</param> public InputBox(Form owner, string text) : this() { Owner = owner; _lblMessageText.Text = text; } /// <summary> /// Initializes a new instance of the <see cref="InputBox"/> class. /// </summary> /// <param name="owner">Specifies the Form to set as the owner of this dialog.</param> /// <param name="text">The string message to show.</param> /// <param name="caption">The string caption to allow.</param> public InputBox(Form owner, string text, string caption) : this() { Owner = owner; _lblMessageText.Text = text; Text = caption; } /// <summary> /// Initializes a new instance of the <see cref="InputBox"/> class. /// </summary> /// <param name="owner">Specifies the Form to set as the owner of this dialog.</param> /// <param name="text">The string message to show.</param> /// <param name="caption">The string caption to allow.</param> /// <param name="validation">A DotSpatial.Data.ValidationType enumeration specifying acceptable validation to return OK.</param> public InputBox(Form owner, string text, string caption, ValidationType validation) : this() { Owner = owner; _lblMessageText.Text = text; Text = caption; Validation = validation; } /// <summary> /// Initializes a new instance of the <see cref="InputBox"/> class. /// </summary> /// <param name="owner">Specifies the Form to set as the owner of this dialog.</param> /// <param name="text">The string message to show.</param> /// <param name="caption">The string caption to allow.</param> /// <param name="validation">A DotSpatial.Data.ValidationType enumeration specifying acceptable validation to return OK.</param> /// <param name="icon">Specifies an icon to appear on this messagebox.</param> public InputBox(Form owner, string text, string caption, ValidationType validation, Icon icon) : this() { Owner = owner; Validation = validation; _lblMessageText.Text = text; Text = caption; ShowIcon = true; Icon = icon; } #endregion #region Properties /// <summary> /// Gets the string result that was entered for this text box. /// </summary> public string Result => _txtInput.Text; /// <summary> /// Gets or sets the type of validation to force on the value before the OK option is permitted. /// </summary> public ValidationType Validation { get; set; } #endregion #region Methods /// <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?.Dispose(); } base.Dispose(disposing); } private void CmdCancelClick(object sender, EventArgs e) { DialogResult = DialogResult.Cancel; Close(); } private void CmdOkClick(object sender, EventArgs e) { // Parse the value entered in the text box. If the value doesn't match the criteria, don't // allow the user to exit the dialog by pressing ok. switch (Validation) { case ValidationType.Byte: if (Global.IsByte(_txtInput.Text) == false) { LogManager.DefaultLogManager.LogMessageBox(DataFormsMessageStrings.ParseFailed_S.Replace("%S", "byte")); return; } break; case ValidationType.Double: if (Global.IsDouble(_txtInput.Text) == false) { LogManager.DefaultLogManager.LogMessageBox(DataFormsMessageStrings.ParseFailed_S.Replace("%S", "double")); return; } break; case ValidationType.Float: if (Global.IsFloat(_txtInput.Text) == false) { LogManager.DefaultLogManager.LogMessageBox(DataFormsMessageStrings.ParseFailed_S.Replace("%S", "float")); return; } break; case ValidationType.Integer: if (Global.IsInteger(_txtInput.Text) == false) { LogManager.DefaultLogManager.LogMessageBox(DataFormsMessageStrings.ParseFailed_S.Replace("%S", "integer")); return; } break; case ValidationType.PositiveDouble: if (Global.IsDouble(_txtInput.Text) == false) { LogManager.DefaultLogManager.LogMessageBox(DataFormsMessageStrings.ParseFailed_S.Replace("%S", "double")); return; } if (Global.GetDouble(_txtInput.Text) < 0) { LogManager.DefaultLogManager.LogMessageBox(DataFormsMessageStrings.ParseFailed_S.Replace("%S", "positive double")); return; } break; case ValidationType.PositiveFloat: if (Global.IsFloat(_txtInput.Text) == false) { LogManager.DefaultLogManager.LogMessageBox(DataFormsMessageStrings.ParseFailed_S.Replace("%S", "float")); return; } if (Global.GetFloat(_txtInput.Text) < 0) { LogManager.DefaultLogManager.LogMessageBox(DataFormsMessageStrings.ParseFailed_S.Replace("%S", "positive float")); return; } break; case ValidationType.PositiveInteger: if (Global.IsInteger(_txtInput.Text) == false) { LogManager.DefaultLogManager.LogMessageBox(DataFormsMessageStrings.ParseFailed_S.Replace("%S", "integer")); return; } if (Global.GetInteger(_txtInput.Text) < 0) { LogManager.DefaultLogManager.LogMessageBox(DataFormsMessageStrings.ParseFailed_S.Replace("%S", "positive integer")); return; } break; case ValidationType.PositiveShort: if (Global.IsShort(_txtInput.Text) == false) { LogManager.DefaultLogManager.LogMessageBox(DataFormsMessageStrings.ParseFailed_S.Replace("%S", "short")); return; } if (Global.GetShort(_txtInput.Text) < 0) { LogManager.DefaultLogManager.LogMessageBox(DataFormsMessageStrings.ParseFailed_S.Replace("%S", "positive short")); return; } break; } DialogResult = DialogResult.OK; Close(); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { ComponentResourceManager resources = new ComponentResourceManager(typeof(InputBox)); _lblMessageText = new Label(); _txtInput = new TextBox(); _cmdOk = new Button(); _cmdCancel = new Button(); SuspendLayout(); // lblMessageText resources.ApplyResources(_lblMessageText, "_lblMessageText"); _lblMessageText.Name = "_lblMessageText"; // txtInput resources.ApplyResources(_txtInput, "_txtInput"); _txtInput.Name = "_txtInput"; // cmdOk resources.ApplyResources(_cmdOk, "_cmdOk"); _cmdOk.BackColor = Color.Transparent; _cmdOk.DialogResult = DialogResult.OK; _cmdOk.Name = "_cmdOk"; _cmdOk.UseVisualStyleBackColor = false; _cmdOk.Click += CmdOkClick; // cmdCancel resources.ApplyResources(_cmdCancel, "_cmdCancel"); _cmdCancel.BackColor = Color.Transparent; _cmdCancel.DialogResult = DialogResult.Cancel; _cmdCancel.Name = "_cmdCancel"; _cmdCancel.UseVisualStyleBackColor = false; _cmdCancel.Click += CmdCancelClick; // InputBox AcceptButton = _cmdOk; CancelButton = _cmdCancel; resources.ApplyResources(this, "$this"); Controls.Add(_cmdCancel); Controls.Add(_cmdOk); Controls.Add(_txtInput); Controls.Add(_lblMessageText); MaximizeBox = false; MinimizeBox = false; Name = "InputBox"; ShowIcon = false; ResumeLayout(false); PerformLayout(); } #endregion } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using Mono.Cecil; using Mono.Cecil.Cil; using Mono.Cecil.Mdb; using Mono.Cecil.Pdb; using NUnit.Framework; namespace Mono.Cecil.Tests { [TestFixture] public class ILProcessorTests : BaseTestFixture { [Test] public void Append () { var method = CreateTestMethod (); var il = method.GetILProcessor (); var ret = il.Create (OpCodes.Ret); il.Append (ret); AssertOpCodeSequence (new [] { OpCodes.Ret }, method); } [Test] public void InsertBefore () { var method = CreateTestMethod (OpCodes.Ldloc_0, OpCodes.Ldloc_2, OpCodes.Ldloc_3); var il = method.GetILProcessor (); var ldloc_2 = method.Instructions.Where (i => i.OpCode == OpCodes.Ldloc_2).First (); il.InsertBefore ( ldloc_2, il.Create (OpCodes.Ldloc_1)); AssertOpCodeSequence (new [] { OpCodes.Ldloc_0, OpCodes.Ldloc_1, OpCodes.Ldloc_2, OpCodes.Ldloc_3 }, method); } [Test] public void InsertBeforeIssue697 () { var parameters = new ReaderParameters { SymbolReaderProvider = new MdbReaderProvider () }; using (var module = GetResourceModule ("Issue697.dll", parameters)) { var pathGetterDef = module.GetTypes () .SelectMany (t => t.Methods) .First (m => m.Name.Equals ("get_Defer")); var body = pathGetterDef.Body; var worker = body.GetILProcessor (); var initialBody = body.Instructions.ToList (); var head = initialBody.First (); var opcode = worker.Create (OpCodes.Ldc_I4_1); worker.InsertBefore (head, opcode); worker.InsertBefore (head, worker.Create (OpCodes.Ret)); initialBody.ForEach (worker.Remove); AssertOpCodeSequence (new [] { OpCodes.Ldc_I4_1, OpCodes.Ret }, pathGetterDef.body); } } [Test] public void InsertAfter () { var method = CreateTestMethod (OpCodes.Ldloc_0, OpCodes.Ldloc_2, OpCodes.Ldloc_3); var il = method.GetILProcessor (); var ldloc_0 = method.Instructions.First (); il.InsertAfter ( ldloc_0, il.Create (OpCodes.Ldloc_1)); AssertOpCodeSequence (new [] { OpCodes.Ldloc_0, OpCodes.Ldloc_1, OpCodes.Ldloc_2, OpCodes.Ldloc_3 }, method); } [Test] public void InsertAfterUsingIndex () { var method = CreateTestMethod (OpCodes.Ldloc_0, OpCodes.Ldloc_2, OpCodes.Ldloc_3); var il = method.GetILProcessor (); il.InsertAfter ( 0, il.Create (OpCodes.Ldloc_1)); AssertOpCodeSequence (new [] { OpCodes.Ldloc_0, OpCodes.Ldloc_1, OpCodes.Ldloc_2, OpCodes.Ldloc_3 }, method); } [Test] public void ReplaceUsingIndex () { var method = CreateTestMethod (OpCodes.Ldloc_0, OpCodes.Ldloc_2, OpCodes.Ldloc_3); var il = method.GetILProcessor (); il.Replace (1, il.Create (OpCodes.Nop)); AssertOpCodeSequence (new [] { OpCodes.Ldloc_0, OpCodes.Nop, OpCodes.Ldloc_3 }, method); } [Test] public void Clear () { var method = CreateTestMethod (OpCodes.Ldloc_0, OpCodes.Ldloc_2, OpCodes.Ldloc_3); var il = method.GetILProcessor (); il.Clear (); AssertOpCodeSequence (new OpCode[] { }, method); } [TestCase (RoundtripType.None, false, false)] [TestCase (RoundtripType.Pdb, false, false)] [TestCase (RoundtripType.Pdb, true, false)] [TestCase (RoundtripType.Pdb, true, true)] [TestCase (RoundtripType.PortablePdb, false, false)] [TestCase (RoundtripType.PortablePdb, true, false)] [TestCase (RoundtripType.PortablePdb, true, true)] public void InsertAfterWithSymbolRoundtrip (RoundtripType roundtripType, bool forceUnresolved, bool reverseScopes) { var methodBody = CreateTestMethodWithLocalScopes (); methodBody = RoundtripMethodBody (methodBody, roundtripType, forceUnresolved, reverseScopes); var il = methodBody.GetILProcessor (); il.InsertAfter (1, il.Create (OpCodes.Ldstr, "Test")); methodBody = RoundtripMethodBody (methodBody, roundtripType, false, reverseScopes); var wholeBodyScope = VerifyWholeBodyScope (methodBody); AssertLocalScope (methodBody, wholeBodyScope.Scopes [0], 1, 3); AssertLocalScope (methodBody, wholeBodyScope.Scopes [1], 4, null); AssertLocalScope (methodBody, wholeBodyScope.Scopes [1].Scopes [0], 5, 6); methodBody.Method.Module.Dispose (); } [TestCase (RoundtripType.None, false, false)] [TestCase (RoundtripType.Pdb, false, false)] [TestCase (RoundtripType.Pdb, true, false)] [TestCase (RoundtripType.Pdb, true, true)] [TestCase (RoundtripType.PortablePdb, false, false)] [TestCase (RoundtripType.PortablePdb, true, false)] [TestCase (RoundtripType.PortablePdb, true, true)] public void RemoveWithSymbolRoundtrip (RoundtripType roundtripType, bool forceUnresolved, bool reverseScopes) { var methodBody = CreateTestMethodWithLocalScopes (); methodBody = RoundtripMethodBody (methodBody, roundtripType, forceUnresolved, reverseScopes); var il = methodBody.GetILProcessor (); il.RemoveAt (1); methodBody = RoundtripMethodBody (methodBody, roundtripType, false, reverseScopes); var wholeBodyScope = VerifyWholeBodyScope (methodBody); AssertLocalScope (methodBody, wholeBodyScope.Scopes [0], 1, 1); AssertLocalScope (methodBody, wholeBodyScope.Scopes [1], 2, null); AssertLocalScope (methodBody, wholeBodyScope.Scopes [1].Scopes [0], 3, 4); methodBody.Method.Module.Dispose (); } [TestCase (RoundtripType.None, false, false)] [TestCase (RoundtripType.Pdb, false, false)] [TestCase (RoundtripType.Pdb, true, false)] [TestCase (RoundtripType.Pdb, true, true)] [TestCase (RoundtripType.PortablePdb, false, false)] [TestCase (RoundtripType.PortablePdb, true, false)] [TestCase (RoundtripType.PortablePdb, true, true)] public void ReplaceWithSymbolRoundtrip (RoundtripType roundtripType, bool forceUnresolved, bool reverseScopes) { var methodBody = CreateTestMethodWithLocalScopes (); methodBody = RoundtripMethodBody (methodBody, roundtripType, forceUnresolved, reverseScopes); var il = methodBody.GetILProcessor (); il.Replace (1, il.Create (OpCodes.Ldstr, "Test")); methodBody = RoundtripMethodBody (methodBody, roundtripType, false, reverseScopes); var wholeBodyScope = VerifyWholeBodyScope (methodBody); AssertLocalScope (methodBody, wholeBodyScope.Scopes [0], 1, 2); AssertLocalScope (methodBody, wholeBodyScope.Scopes [1], 3, null); AssertLocalScope (methodBody, wholeBodyScope.Scopes [1].Scopes [0], 4, 5); methodBody.Method.Module.Dispose (); } [TestCase (RoundtripType.None, false, false)] [TestCase (RoundtripType.Pdb, false, false)] [TestCase (RoundtripType.Pdb, true, false)] [TestCase (RoundtripType.Pdb, true, true)] [TestCase (RoundtripType.PortablePdb, false, false)] [TestCase (RoundtripType.PortablePdb, true, false)] [TestCase (RoundtripType.PortablePdb, true, true)] public void EditBodyWithScopesAndSymbolRoundtrip (RoundtripType roundtripType, bool forceUnresolved, bool reverseScopes) { var methodBody = CreateTestMethodWithLocalScopes (); methodBody = RoundtripMethodBody (methodBody, roundtripType, forceUnresolved, reverseScopes); var il = methodBody.GetILProcessor (); il.Replace (4, il.Create (OpCodes.Ldstr, "Test")); il.InsertAfter (5, il.Create (OpCodes.Ldloc_3)); var tempVar3 = new VariableDefinition (methodBody.Method.Module.ImportReference (typeof (string))); methodBody.Variables.Add (tempVar3); methodBody.Method.DebugInformation.Scope.Scopes [reverseScopes ? 0 : 1].Scopes.Insert (reverseScopes ? 0 : 1, new ScopeDebugInformation (methodBody.Instructions [5], methodBody.Instructions [6]) { Variables = { new VariableDebugInformation (tempVar3, "tempVar3") } }); methodBody = RoundtripMethodBody (methodBody, roundtripType, false, reverseScopes); var wholeBodyScope = VerifyWholeBodyScope (methodBody); AssertLocalScope (methodBody, wholeBodyScope.Scopes [0], 1, 2); AssertLocalScope (methodBody, wholeBodyScope.Scopes [1], 3, null); AssertLocalScope (methodBody, wholeBodyScope.Scopes [1].Scopes [0], 4, 5); AssertLocalScope (methodBody, wholeBodyScope.Scopes [1].Scopes [1], 5, 6); methodBody.Method.Module.Dispose (); } [Test] public void EditWithDebugInfoButNoLocalScopes() { var methodBody = CreateTestMethod (OpCodes.Ret); methodBody.Method.DebugInformation = new MethodDebugInformation (methodBody.Method); var il = methodBody.GetILProcessor (); il.Replace (methodBody.Instructions [0], il.Create (OpCodes.Nop)); Assert.AreEqual (1, methodBody.Instructions.Count); Assert.AreEqual (Code.Nop, methodBody.Instructions [0].OpCode.Code); Assert.Null (methodBody.Method.DebugInformation.Scope); } static void AssertOpCodeSequence (OpCode [] expected, MethodBody body) { var opcodes = body.Instructions.Select (i => i.OpCode).ToArray (); Assert.AreEqual (expected.Length, opcodes.Length); for (int i = 0; i < opcodes.Length; i++) Assert.AreEqual (expected [i], opcodes [i]); } static MethodBody CreateTestMethod (params OpCode [] opcodes) { var method = new MethodDefinition { Name = "function", Attributes = MethodAttributes.Public | MethodAttributes.Static }; var il = method.Body.GetILProcessor (); foreach (var opcode in opcodes) il.Emit (opcode); var instructions = method.Body.Instructions; int size = 0; for (int i = 0; i < instructions.Count; i++) { var instruction = instructions [i]; instruction.Offset = size; size += instruction.GetSize (); } return method.Body; } static ScopeDebugInformation VerifyWholeBodyScope (MethodBody body) { var debug_info = body.Method.DebugInformation; Assert.IsNotNull (debug_info); AssertLocalScope (body, debug_info.Scope, 0, null); return debug_info.Scope; } static void AssertLocalScope (MethodBody methodBody, ScopeDebugInformation scope, int startIndex, int? endIndex) { Assert.IsNotNull (scope); Assert.AreEqual (methodBody.Instructions [startIndex], scope.Start.ResolvedInstruction); if (endIndex.HasValue) Assert.AreEqual (methodBody.Instructions [endIndex.Value], scope.End.ResolvedInstruction); else Assert.IsTrue (scope.End.IsEndOfMethod); } static MethodBody CreateTestMethodWithLocalScopes () { var module = ModuleDefinition.CreateModule ("TestILProcessor", ModuleKind.Dll); var type = new TypeDefinition ("NS", "TestType", TypeAttributes.Public | TypeAttributes.Abstract | TypeAttributes.Sealed, module.ImportReference (typeof (object))); module.Types.Add (type); var methodBody = CreateTestMethod (OpCodes.Nop, OpCodes.Ldloc_0, OpCodes.Nop, OpCodes.Ldloc_1, OpCodes.Nop, OpCodes.Ldloc_2, OpCodes.Nop); var method = methodBody.Method; method.ReturnType = module.ImportReference (typeof (void)); type.Methods.Add (method); methodBody.InitLocals = true; var tempVar1 = new VariableDefinition (module.ImportReference (typeof (string))); methodBody.Variables.Add (tempVar1); var tempVar2 = new VariableDefinition (module.ImportReference (typeof (string))); methodBody.Variables.Add (tempVar2); var debug_info = method.DebugInformation; // Must add a sequence point, otherwise the native PDB writer will not actually write the method's debug info // into the PDB. foreach (var instr in methodBody.Instructions) { var sequence_point = new SequencePoint (instr, new Document (@"C:\test.cs")) { StartLine = 0, StartColumn = 0, EndLine = 0, EndColumn = 4, }; debug_info.SequencePoints.Add (sequence_point); } // The method looks like this: // | Scope | Scope.Scopes[0] | Scope.Scopes[1] | Scope.Scopes[1].Scopes[0] // #0 Nop | > | | | // #1 Ldloc_0 | . | > | | // #2 Nop | . | < | | // #3 Ldloc_1 | . | | > | // #4 Nop | . | | . | > // #5 Ldloc_2 | . | | . | < // #6 Nop | . | | . | // <end of m> | < | | < | var instructions = methodBody.Instructions; debug_info.Scope = new ScopeDebugInformation (instructions[0], null) { Scopes = { new ScopeDebugInformation (instructions[1], instructions[2]) { Variables = { new VariableDebugInformation(tempVar1, "tempVar1") } }, new ScopeDebugInformation (instructions[3], null) { Scopes = { new ScopeDebugInformation (instructions[4], instructions[5]) { Variables = { new VariableDebugInformation(tempVar2, "tempVar2") } } } } } }; return methodBody; } public enum RoundtripType { None, Pdb, PortablePdb } static MethodBody RoundtripMethodBody(MethodBody methodBody, RoundtripType roundtripType, bool forceUnresolvedScopes = false, bool reverseScopeOrder = false) { var newModule = RoundtripModule (methodBody.Method.Module, roundtripType); var newMethodBody = newModule.GetType ("NS.TestType").GetMethod ("function").Body; if (forceUnresolvedScopes) UnresolveScopes (newMethodBody.Method.DebugInformation.Scope); if (reverseScopeOrder) ReverseScopeOrder (newMethodBody.Method.DebugInformation.Scope); return newMethodBody; } static void UnresolveScopes(ScopeDebugInformation scope) { scope.Start = new InstructionOffset (scope.Start.Offset); if (!scope.End.IsEndOfMethod) scope.End = new InstructionOffset (scope.End.Offset); foreach (var subScope in scope.Scopes) UnresolveScopes (subScope); } static void ReverseScopeOrder(ScopeDebugInformation scope) { List<ScopeDebugInformation> subScopes = scope.Scopes.ToList (); subScopes.Reverse (); scope.Scopes.Clear (); foreach (var subScope in subScopes) scope.Scopes.Add (subScope); foreach (var subScope in scope.Scopes) ReverseScopeOrder (subScope); } static ModuleDefinition RoundtripModule(ModuleDefinition module, RoundtripType roundtripType) { if (roundtripType == RoundtripType.None) return module; var file = Path.Combine (Path.GetTempPath (), "TestILProcessor.dll"); if (File.Exists (file)) File.Delete (file); ISymbolWriterProvider symbolWriterProvider; switch (roundtripType) { case RoundtripType.Pdb when Platform.HasNativePdbSupport: symbolWriterProvider = new PdbWriterProvider (); break; case RoundtripType.PortablePdb: default: symbolWriterProvider = new PortablePdbWriterProvider (); break; } module.Write (file, new WriterParameters { SymbolWriterProvider = symbolWriterProvider, }); module.Dispose (); ISymbolReaderProvider symbolReaderProvider; switch (roundtripType) { case RoundtripType.Pdb when Platform.HasNativePdbSupport: symbolReaderProvider = new PdbReaderProvider (); break; case RoundtripType.PortablePdb: default: symbolReaderProvider = new PortablePdbReaderProvider (); break; } return ModuleDefinition.ReadModule (file, new ReaderParameters { SymbolReaderProvider = symbolReaderProvider, InMemory = true }); } } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: ArraySegment<T> ** ** ** Purpose: Convenient wrapper for an array, an offset, and ** a count. Ideally used in streams & collections. ** Net Classes will consume an array of these. ** ** ===========================================================*/ using System.Collections; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Diagnostics.Contracts; namespace System { // Note: users should make sure they copy the fields out of an ArraySegment onto their stack // then validate that the fields describe valid bounds within the array. This must be done // because assignments to value types are not atomic, and also because one thread reading // three fields from an ArraySegment may not see the same ArraySegment from one call to another // (ie, users could assign a new value to the old location). [Serializable] public struct ArraySegment<T> : IList<T>, IReadOnlyList<T> { private T[] _array; private int _offset; private int _count; public ArraySegment(T[] array) { if (array == null) throw new ArgumentNullException("array"); Contract.EndContractBlock(); _array = array; _offset = 0; _count = array.Length; } public ArraySegment(T[] array, int offset, int count) { if (array == null) throw new ArgumentNullException("array"); if (offset < 0) throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (count < 0) throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (array.Length - offset < count) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen")); Contract.EndContractBlock(); _array = array; _offset = offset; _count = count; } public T[] Array { get { Contract.Assert( (null == _array && 0 == _offset && 0 == _count) || (null != _array && _offset >= 0 && _count >= 0 && _offset + _count <= _array.Length), "ArraySegment is invalid"); return _array; } } public int Offset { get { // Since copying value types is not atomic & callers cannot atomically // read all three fields, we cannot guarantee that Offset is within // the bounds of Array. That is our intent, but let's not specify // it as a postcondition - force callers to re-verify this themselves // after reading each field out of an ArraySegment into their stack. Contract.Ensures(Contract.Result<int>() >= 0); Contract.Assert( (null == _array && 0 == _offset && 0 == _count) || (null != _array && _offset >= 0 && _count >= 0 && _offset + _count <= _array.Length), "ArraySegment is invalid"); return _offset; } } public int Count { get { // Since copying value types is not atomic & callers cannot atomically // read all three fields, we cannot guarantee that Count is within // the bounds of Array. That's our intent, but let's not specify // it as a postcondition - force callers to re-verify this themselves // after reading each field out of an ArraySegment into their stack. Contract.Ensures(Contract.Result<int>() >= 0); Contract.Assert( (null == _array && 0 == _offset && 0 == _count) || (null != _array && _offset >= 0 && _count >= 0 && _offset + _count <= _array.Length), "ArraySegment is invalid"); return _count; } } public override int GetHashCode() { return null == _array ? 0 : _array.GetHashCode() ^ _offset ^ _count; } public override bool Equals(Object obj) { if (obj is ArraySegment<T>) return Equals((ArraySegment<T>)obj); else return false; } public bool Equals(ArraySegment<T> obj) { return obj._array == _array && obj._offset == _offset && obj._count == _count; } public static bool operator ==(ArraySegment<T> a, ArraySegment<T> b) { return a.Equals(b); } public static bool operator !=(ArraySegment<T> a, ArraySegment<T> b) { return !(a == b); } #region IList<T> T IList<T>.this[int index] { get { if (_array == null) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NullArray")); if (index < 0 || index >= _count) throw new ArgumentOutOfRangeException("index"); Contract.EndContractBlock(); return _array[_offset + index]; } set { if (_array == null) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NullArray")); if (index < 0 || index >= _count) throw new ArgumentOutOfRangeException("index"); Contract.EndContractBlock(); _array[_offset + index] = value; } } int IList<T>.IndexOf(T item) { if (_array == null) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NullArray")); Contract.EndContractBlock(); int index = System.Array.IndexOf<T>(_array, item, _offset, _count); Contract.Assert(index == -1 || (index >= _offset && index < _offset + _count)); return index >= 0 ? index - _offset : -1; } void IList<T>.Insert(int index, T item) { throw new NotSupportedException(); } void IList<T>.RemoveAt(int index) { throw new NotSupportedException(); } #endregion #region IReadOnlyList<T> T IReadOnlyList<T>.this[int index] { get { if (_array == null) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NullArray")); if (index < 0 || index >= _count) throw new ArgumentOutOfRangeException("index"); Contract.EndContractBlock(); return _array[_offset + index]; } } #endregion IReadOnlyList<T> #region ICollection<T> bool ICollection<T>.IsReadOnly { get { // the indexer setter does not throw an exception although IsReadOnly is true. // This is to match the behavior of arrays. return true; } } void ICollection<T>.Add(T item) { throw new NotSupportedException(); } void ICollection<T>.Clear() { throw new NotSupportedException(); } bool ICollection<T>.Contains(T item) { if (_array == null) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NullArray")); Contract.EndContractBlock(); int index = System.Array.IndexOf<T>(_array, item, _offset, _count); Contract.Assert(index == -1 || (index >= _offset && index < _offset + _count)); return index >= 0; } void ICollection<T>.CopyTo(T[] array, int arrayIndex) { if (_array == null) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NullArray")); Contract.EndContractBlock(); System.Array.Copy(_array, _offset, array, arrayIndex, _count); } bool ICollection<T>.Remove(T item) { throw new NotSupportedException(); } #endregion #region IEnumerable<T> IEnumerator<T> IEnumerable<T>.GetEnumerator() { if (_array == null) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NullArray")); Contract.EndContractBlock(); return new ArraySegmentEnumerator(this); } #endregion #region IEnumerable IEnumerator IEnumerable.GetEnumerator() { if (_array == null) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NullArray")); Contract.EndContractBlock(); return new ArraySegmentEnumerator(this); } #endregion [Serializable] private sealed class ArraySegmentEnumerator : IEnumerator<T> { private T[] _array; private int _start; private int _end; private int _current; internal ArraySegmentEnumerator(ArraySegment<T> arraySegment) { Contract.Requires(arraySegment.Array != null); Contract.Requires(arraySegment.Offset >= 0); Contract.Requires(arraySegment.Count >= 0); Contract.Requires(arraySegment.Offset + arraySegment.Count <= arraySegment.Array.Length); _array = arraySegment._array; _start = arraySegment._offset; _end = _start + arraySegment._count; _current = _start - 1; } public bool MoveNext() { if (_current < _end) { _current++; return (_current < _end); } return false; } public T Current { get { if (_current < _start) throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumNotStarted)); if (_current >= _end) throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumEnded)); return _array[_current]; } } object IEnumerator.Current { get { return Current; } } void IEnumerator.Reset() { _current = _start - 1; } public void Dispose() { } } } }
// $Id: mxFastOrganicLayout.cs,v 1.12 2009-11-12 19:36:59 gaudenz Exp $ // Copyright (c) 2007-2008, Gaudenz Alder using System; using System.Collections.Generic; using System.Text; namespace com.mxgraph { /// <summary> /// Fast organic layout algorithm. /// </summary> public class mxFastOrganicLayout: mxIGraphLayout { /// <summary> /// Holds the enclosing graph. /// </summary> protected mxGraph graph; /// <summary> /// The force constant by which the attractive forces are divided and the /// replusive forces are multiple by the square of. The value equates to the /// average radius there is of free space around each node. Default is 50. /// </summary> protected double forceConstant = 50; /// <summary> /// Cache of forceConstant^2 for performance. /// </summary> protected double forceConstantSquared = 0; /// <summary> /// Minimal distance limit. Default is 2. Prevents of /// dividing by zero. /// </summary> protected double minDistanceLimit = 2; /// <summary> /// Cached version of minDistanceLimit squared. /// </summary> protected double minDistanceLimitSquared = 0; /// <summary> /// Start value of temperature. Default is 200. /// </summary> protected double initialTemp = 200; /// <summary> /// Temperature to limit displacement at later stages of layout. /// </summary> protected double temperature = 0; /// <summary> /// Total number of iterations to run the layout though. /// </summary> protected int maxIterations = 0; /// <summary> /// Current iteration count. /// </summary> protected int iteration = 0; /// <summary> /// An array of all vertices to be laid out. /// </summary> protected Object[] vertexArray; /// <summary> /// An array of locally stored X co-ordinate displacements for the vertices. /// </summary> protected double[] dispX; /// <summary> /// An array of locally stored Y co-ordinate displacements for the vertices. /// </summary> protected double[] dispY; /// <summary> /// An array of locally stored co-ordinate positions for the vertices. /// </summary> protected double[][] cellLocation; /// <summary> /// The approximate radius of each cell, nodes only. /// </summary> protected double[] radius; /// <summary> /// The approximate radius squared of each cell, nodes only. /// </summary> protected double[] radiusSquared; /// <summary> /// Array of booleans representing the movable states of the vertices. /// </summary> protected bool[] isMoveable; /// <summary> /// Local copy of cell neighbours. /// </summary> protected int[][] neighbours; /// <summary> /// Boolean flag that specifies if the layout is allowed to run. If this is /// set to false, then the layout exits in the following iteration. /// </summary> protected bool allowedToRun = true; /// <summary> /// Maps from vertices to indices. /// </summary> protected Dictionary<object, int> indices = new Dictionary<object, int>(); /// <summary> /// Random number generator. /// </summary> protected Random random = new Random(); /// <summary> /// Constructs a new fast organic layout for the specified graph. /// </summary> /// <param name="graph"></param> public mxFastOrganicLayout(mxGraph graph) { this.graph = graph; } /// <summary> /// Flag to stop a running layout run. /// </summary> public bool IsAllowedToRun { get { return allowedToRun; } set { allowedToRun = value; } } /// <summary> /// Returns true if the given cell should be ignored by the layout algorithm. /// This implementation returns false if the cell is a vertex and has at least /// one connected edge. /// </summary> /// <param name="cell">Object that represents the cell.</param> /// <returns>Returns true if the given cell should be ignored.</returns> public bool IsCellIgnored(Object cell) { return !graph.Model.IsVertex(cell) || graph.Model.GetEdgeCount(cell) == 0; } /// <summary> /// Maximum number of iterations. /// </summary> public int MaxIterations { get { return maxIterations; } set { maxIterations = value; } } /// <summary> /// Force constant to be used for the springs. /// </summary> public double ForceConstant { get { return forceConstant; } set { forceConstant = value; } } /// <summary> /// Minimum distance between nodes. /// </summary> public double MinDistanceLimit { get { return minDistanceLimit; } set { minDistanceLimit = value; } } /// <summary> /// Initial temperature. /// </summary> public double InitialTemp { get { return initialTemp; } set { initialTemp = value; } } /// <summary> /// Reduces the temperature of the layout from an initial setting in a linear /// fashion to zero. /// </summary> protected void reduceTemperature() { temperature = initialTemp * (1.0 - iteration / maxIterations); } /// <summary> /// Notified when a cell is being moved in a parent /// that has automatic layout to update the cell /// state (eg. index) so that the outcome of the /// layou will position the vertex as close to the /// point (x, y) as possible. /// /// Not yet implemented. /// </summary> /// <param name="cell"></param> /// <param name="x"></param> /// <param name="y"></param> public void move(Object cell, double x, double y) { // TODO: Map the position to a child index for // the cell to be placed closest to the position } /// <summary> /// Executes the fast organic layout. /// </summary> /// <param name="parent"></param> public void execute(Object parent) { mxIGraphModel model = graph.Model; // Finds the relevant vertices for the layout int childCount = model.GetChildCount(parent); List<Object> tmp = new List<Object>(childCount); for (int i = 0; i < childCount; i++) { Object child = model.GetChildAt(parent, i); if (!IsCellIgnored(child)) { tmp.Add(child); } } vertexArray = tmp.ToArray(); int n = vertexArray.Length; dispX = new double[n]; dispY = new double[n]; cellLocation = new double[n][]; isMoveable = new bool[n]; neighbours = new int[n][]; radius = new double[n]; radiusSquared = new double[n]; minDistanceLimitSquared = minDistanceLimit * minDistanceLimit; if (forceConstant < 0.001) { forceConstant = 0.001; } forceConstantSquared = forceConstant * forceConstant; // Create a map of vertices first. This is required for the array of // arrays called neighbours which holds, for each vertex, a list of // ints which represents the neighbours cells to that vertex as // the indices into vertexArray for (int i = 0; i < vertexArray.Length; i++) { Object vertex = vertexArray[i]; cellLocation[i] = new double[2]; // Set up the mapping from array indices to cells indices[vertex] = i; mxGeometry bounds = model.GetGeometry(vertex); // Set the X,Y value of the internal version of the cell to // the center point of the vertex for better positioning double width = bounds.Width; double height = bounds.Height; // Randomize (0, 0) locations double x = bounds.X; double y = bounds.Y; cellLocation[i][0] = x + width / 2.0; cellLocation[i][1] = y + height / 2.0; radius[i] = Math.Min(width, height); radiusSquared[i] = radius[i] * radius[i]; } for (int i = 0; i < n; i++) { dispX[i] = 0; dispY[i] = 0; isMoveable[i] = graph.IsCellMovable(vertexArray[i]); // Get lists of neighbours to all vertices, translate the cells // obtained in indices into vertexArray and store as an array // against the orginial cell index Object[] edges = mxGraphModel.GetEdges(model, vertexArray[i]); Object[] cells = mxGraphModel.GetOpposites(model, edges, vertexArray[i], true, true); neighbours[i] = new int[cells.Length]; for (int j = 0; j < cells.Length; j++) { int? index = indices[cells[j]]; // Check the connected cell in part of the vertex list to be // acted on by this layout if (index != null) { neighbours[i][j] = (int) index; } // Else if index of the other cell doesn't correspond to // any cell listed to be acted upon in this layout. Set // the index to the value of this vertex (a dummy self-loop) // so the attraction force of the edge is not calculated else { neighbours[i][j] = i; } } } temperature = initialTemp; // If max number of iterations has not been set, guess it if (maxIterations == 0) { maxIterations = (int)(20 * Math.Sqrt(n)); } // Main iteration loop for (iteration = 0; iteration < maxIterations; iteration++) { if (!allowedToRun) { return; } // Calculate repulsive forces on all vertices calcRepulsion(); // Calculate attractive forces through edges calcAttraction(); calcPositions(); reduceTemperature(); } // Moved cell location back to top-left from center locations used in // algorithm model.BeginUpdate(); try { double? minx = null; double? miny = null; for (int i = 0; i < vertexArray.Length; i++) { Object vertex = vertexArray[i]; mxGeometry geo = model.GetGeometry(vertex); if (geo != null) { cellLocation[i][0] -= geo.Width / 2.0; cellLocation[i][1] -= geo.Height / 2.0; geo = geo.Clone(); geo.X = graph.Snap(cellLocation[i][0]); geo.Y = graph.Snap(cellLocation[i][1]); model.SetGeometry(vertex, geo); if (minx == null) { minx = geo.X; } else { minx = Math.Min((double) minx, geo.X); } if (miny == null) { miny = geo.Y; } else { miny = Math.Min((double) miny, geo.Y); } } } // Modifies the cloned geometries in-place. Not needed // to clone the geometries again as we're in the same // undoable change. if (minx != null || miny != null) { for (int i = 0; i < vertexArray.Length; i++) { Object vertex = vertexArray[i]; mxGeometry geo = model.GetGeometry(vertex); if (geo != null) { if (minx != null) { geo.X -= ((double) minx) - 1; } if (miny != null) { geo.Y -= ((double) miny) - 1; } } } } } finally { model.EndUpdate(); } } /// <summary> /// Takes the displacements calculated for each cell and applies them to the /// local cache of cell positions. Limits the displacement to the current /// temperature. /// </summary> protected void calcPositions() { for (int index = 0; index < vertexArray.Length; index++) { if (isMoveable[index]) { // Get the distance of displacement for this node for this // iteration double deltaLength = Math.Sqrt(dispX[index] * dispX[index] + dispY[index] * dispY[index]); if (deltaLength < 0.001) { deltaLength = 0.001; } // Scale down by the current temperature if less than the // displacement distance double newXDisp = dispX[index] / deltaLength * Math.Min(deltaLength, temperature); double newYDisp = dispY[index] / deltaLength * Math.Min(deltaLength, temperature); // reset displacements dispX[index] = 0; dispY[index] = 0; // Update the cached cell locations cellLocation[index][0] += newXDisp; cellLocation[index][1] += newYDisp; } } } /// <summary> /// Calculates the attractive forces between all laid out nodes linked by /// edges /// </summary> protected void calcAttraction() { // Check the neighbours of each vertex and calculate the attractive // force of the edge connecting them for (int i = 0; i < vertexArray.Length; i++) { for (int k = 0; k < neighbours[i].Length; k++) { // Get the index of the othe cell in the vertex array int j = neighbours[i][k]; // Do not proceed self-loops if (i != j) { double xDelta = cellLocation[i][0] - cellLocation[j][0]; double yDelta = cellLocation[i][1] - cellLocation[j][1]; // The distance between the nodes double deltaLengthSquared = xDelta * xDelta + yDelta * yDelta - radiusSquared[i] - radiusSquared[j]; if (deltaLengthSquared < minDistanceLimitSquared) { deltaLengthSquared = minDistanceLimitSquared; } double deltaLength = Math.Sqrt(deltaLengthSquared); double force = (deltaLengthSquared) / forceConstant; double displacementX = (xDelta / deltaLength) * force; double displacementY = (yDelta / deltaLength) * force; if (isMoveable[i]) { this.dispX[i] -= displacementX; this.dispY[i] -= displacementY; } if (isMoveable[j]) { dispX[j] += displacementX; dispY[j] += displacementY; } } } } } /// <summary> /// Calculates the repulsive forces between all laid out nodes /// </summary> protected void calcRepulsion() { int vertexCount = vertexArray.Length; for (int i = 0; i < vertexCount; i++) { for (int j = i; j < vertexCount; j++) { // Exits if the layout is no longer allowed to run if (!allowedToRun) { return; } if (j != i) { double xDelta = cellLocation[i][0] - cellLocation[j][0]; double yDelta = cellLocation[i][1] - cellLocation[j][1]; if (xDelta == 0) { xDelta = 0.01 + random.NextDouble(); } if (yDelta == 0) { yDelta = 0.01 + random.NextDouble(); } // Distance between nodes double deltaLength = Math.Sqrt((xDelta * xDelta) + (yDelta * yDelta)); double deltaLengthWithRadius = deltaLength - radius[i] - radius[j]; if (deltaLengthWithRadius < minDistanceLimit) { deltaLengthWithRadius = minDistanceLimit; } double force = forceConstantSquared / deltaLengthWithRadius; double displacementX = (xDelta / deltaLength) * force; double displacementY = (yDelta / deltaLength) * force; if (isMoveable[i]) { dispX[i] += displacementX; dispY[i] += displacementY; } if (isMoveable[j]) { dispX[j] -= displacementX; dispY[j] -= displacementY; } } } } } } }
/* * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.SimpleWorkflow.Model { /// <summary> /// Container for the parameters to the ListWorkflowTypes operation. /// <para> Returns information about workflow types in the specified domain. The results may be split into multiple pages that can be retrieved /// by making the call repeatedly. </para> <para> <b>Access Control</b> </para> <para>You can use IAM policies to control this action's access /// to Amazon SWF resources as follows:</para> /// <ul> /// <li>Use a <c>Resource</c> element with the domain name to limit the action to only specified domains.</li> /// <li>Use an <c>Action</c> element to allow or deny permission to call this action.</li> /// <li>You cannot use an IAM policy to constrain this action's parameters.</li> /// /// </ul> /// <para>If the caller does not have sufficient permissions to invoke the action, or the parameter values fall outside the specified /// constraints, the action fails by throwing <c>OperationNotPermitted</c> . For details and example IAM policies, see Using IAM to Manage /// Access to Amazon SWF Workflows.</para> /// </summary> /// <seealso cref="Amazon.SimpleWorkflow.AmazonSimpleWorkflow.ListWorkflowTypes"/> public class ListWorkflowTypesRequest : AmazonWebServiceRequest { private string domain; private string name; private string registrationStatus; private string nextPageToken; private int? maximumPageSize; private bool? reverseOrder; /// <summary> /// The name of the domain in which the workflow types have been registered. /// /// <para> /// <b>Constraints:</b> /// <list type="definition"> /// <item> /// <term>Length</term> /// <description>1 - 256</description> /// </item> /// </list> /// </para> /// </summary> public string Domain { get { return this.domain; } set { this.domain = value; } } /// <summary> /// Sets the Domain property /// </summary> /// <param name="domain">The value to set for the Domain property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public ListWorkflowTypesRequest WithDomain(string domain) { this.domain = domain; return this; } // Check to see if Domain property is set internal bool IsSetDomain() { return this.domain != null; } /// <summary> /// If specified, lists the workflow type with this name. /// /// <para> /// <b>Constraints:</b> /// <list type="definition"> /// <item> /// <term>Length</term> /// <description>1 - 256</description> /// </item> /// </list> /// </para> /// </summary> public string Name { get { return this.name; } set { this.name = value; } } /// <summary> /// Sets the Name property /// </summary> /// <param name="name">The value to set for the Name property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public ListWorkflowTypesRequest WithName(string name) { this.name = name; return this; } // Check to see if Name property is set internal bool IsSetName() { return this.name != null; } /// <summary> /// Specifies the registration status of the workflow types to list. /// /// <para> /// <b>Constraints:</b> /// <list type="definition"> /// <item> /// <term>Allowed Values</term> /// <description>REGISTERED, DEPRECATED</description> /// </item> /// </list> /// </para> /// </summary> public string RegistrationStatus { get { return this.registrationStatus; } set { this.registrationStatus = value; } } /// <summary> /// Sets the RegistrationStatus property /// </summary> /// <param name="registrationStatus">The value to set for the RegistrationStatus property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public ListWorkflowTypesRequest WithRegistrationStatus(string registrationStatus) { this.registrationStatus = registrationStatus; return this; } // Check to see if RegistrationStatus property is set internal bool IsSetRegistrationStatus() { return this.registrationStatus != null; } /// <summary> /// If on a previous call to this method a <c>NextPageToken</c> was returned, the results are being paginated. To get the next page of results, /// repeat the call with the returned token and all other arguments unchanged. /// /// <para> /// <b>Constraints:</b> /// <list type="definition"> /// <item> /// <term>Length</term> /// <description>0 - 2048</description> /// </item> /// </list> /// </para> /// </summary> public string NextPageToken { get { return this.nextPageToken; } set { this.nextPageToken = value; } } /// <summary> /// Sets the NextPageToken property /// </summary> /// <param name="nextPageToken">The value to set for the NextPageToken property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public ListWorkflowTypesRequest WithNextPageToken(string nextPageToken) { this.nextPageToken = nextPageToken; return this; } // Check to see if NextPageToken property is set internal bool IsSetNextPageToken() { return this.nextPageToken != null; } /// <summary> /// The maximum number of results returned in each page. The default is 100, but the caller can override this value to a page size /// <i>smaller</i> than the default. You cannot specify a page size greater than 100. Note that the number of types may be less than the /// maxiumum page size, in which case, the returned page will have fewer results than the maximumPageSize specified. /// /// <para> /// <b>Constraints:</b> /// <list type="definition"> /// <item> /// <term>Range</term> /// <description>0 - 1000</description> /// </item> /// </list> /// </para> /// </summary> public int MaximumPageSize { get { return this.maximumPageSize ?? default(int); } set { this.maximumPageSize = value; } } /// <summary> /// Sets the MaximumPageSize property /// </summary> /// <param name="maximumPageSize">The value to set for the MaximumPageSize property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public ListWorkflowTypesRequest WithMaximumPageSize(int maximumPageSize) { this.maximumPageSize = maximumPageSize; return this; } // Check to see if MaximumPageSize property is set internal bool IsSetMaximumPageSize() { return this.maximumPageSize.HasValue; } /// <summary> /// When set to <c>true</c>, returns the results in reverse order. By default the results are returned in ascending alphabetical order of the /// <c>name</c> of the workflow types. /// /// </summary> public bool ReverseOrder { get { return this.reverseOrder ?? default(bool); } set { this.reverseOrder = value; } } /// <summary> /// Sets the ReverseOrder property /// </summary> /// <param name="reverseOrder">The value to set for the ReverseOrder property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public ListWorkflowTypesRequest WithReverseOrder(bool reverseOrder) { this.reverseOrder = reverseOrder; return this; } // Check to see if ReverseOrder property is set internal bool IsSetReverseOrder() { return this.reverseOrder.HasValue; } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Threading; namespace Apache.Geode.Client.UnitTests { using NUnit.Framework; using Apache.Geode.DUnitFramework; using Apache.Geode.Client.Tests; using Apache.Geode.Client; //using Region = Apache.Geode.Client.IRegion<Object, Object>; using AssertionException = Apache.Geode.Client.AssertionException; public abstract class ThinClientSecurityAuthzTestBase : ThinClientRegionSteps { #region Protected members protected const string SubregionName = "AuthSubregion"; protected const string CacheXml1 = "cacheserver_notify_subscription.xml"; protected const string CacheXml2 = "cacheserver_notify_subscription2.xml"; #endregion #region Private methods private static string IndicesToString(int[] indices) { string str = string.Empty; if (indices != null && indices.Length > 0) { str += indices[0]; for (int index = 1; index < indices.Length; ++index) { str += ','; str += indices[index]; } } return str; } private IRegion<TKey, TValue> CreateSubregion<TKey, TValue>(IRegion<TKey, TValue> region) { Util.Log("CreateSubregion " + SubregionName); IRegion<TKey, TValue> subregion = region.GetSubRegion(SubregionName); if (subregion == null) { //subregion = region.CreateSubRegion(SubregionName, region.Attributes); subregion = CacheHelper.GetRegion<TKey, TValue>(region.FullPath).CreateSubRegion(SubregionName, region.Attributes); } return subregion; } private bool CheckFlags(OpFlags flags, OpFlags checkFlag) { return ((flags & checkFlag) == checkFlag); } protected void DoOp(OperationCode op, int[] indices, OpFlags flags, ExpectedResult expectedResult) { DoOp(op, indices, flags, expectedResult, null, false); } protected void DoOp(OperationCode op, int[] indices, OpFlags flags, ExpectedResult expectedResult, Properties<string, string> creds, bool isMultiuser) { IRegion<object, object> region; if(isMultiuser) region = CacheHelper.GetRegion<object, object>(RegionName, creds); else region = CacheHelper.GetRegion<object, object>(RegionName); if (CheckFlags(flags, OpFlags.UseSubRegion)) { IRegion<object, object> subregion = null; if (CheckFlags(flags, OpFlags.NoCreateSubRegion)) { subregion = region.GetSubRegion(SubregionName); if (CheckFlags(flags, OpFlags.CheckNoRegion)) { Assert.IsNull(subregion); return; } else { Assert.IsNotNull(subregion); } } else { subregion = CreateSubregion(region); if (isMultiuser) subregion = region.GetSubRegion(SubregionName); } Assert.IsNotNull(subregion); region = subregion; } else if (CheckFlags(flags, OpFlags.CheckNoRegion)) { Assert.IsNull(region); return; } else { Assert.IsNotNull(region); } string valPrefix; if (CheckFlags(flags, OpFlags.UseNewVal)) { valPrefix = NValuePrefix; } else { valPrefix = ValuePrefix; } int numOps = indices.Length; Util.Log("Got DoOp for op: " + op + ", numOps: " + numOps + ", indices: " + IndicesToString(indices)); bool exceptionOccured = false; bool breakLoop = false; for (int indexIndex = 0; indexIndex < indices.Length; ++indexIndex) { if (breakLoop) { break; } int index = indices[indexIndex]; string key = KeyPrefix + index; string expectedValue = (valPrefix + index); try { switch (op) { case OperationCode.Get: Object value = null; if (CheckFlags(flags, OpFlags.LocalOp)) { int sleepMillis = 100; int numTries = 30; bool success = false; while (!success && numTries-- > 0) { if (!isMultiuser && region.ContainsValueForKey(key)) { value = region[key]; success = expectedValue.Equals(value.ToString()); if (CheckFlags(flags, OpFlags.CheckFail)) { success = !success; } } else { value = null; success = CheckFlags(flags, OpFlags.CheckFail); } if (!success) { Thread.Sleep(sleepMillis); } } } else { if (!isMultiuser) { if (CheckFlags(flags, OpFlags.CheckNoKey)) { Assert.IsFalse(region.GetLocalView().ContainsKey(key)); } else { Assert.IsTrue(region.GetLocalView().ContainsKey(key)); region.GetLocalView().Invalidate(key); } } try { value = region[key]; } catch (Client.KeyNotFoundException ) { Util.Log("KeyNotFoundException while getting key. should be ok as we are just testing auth"); } } if (!isMultiuser && value != null) { if (CheckFlags(flags, OpFlags.CheckFail)) { Assert.AreNotEqual(expectedValue, value.ToString()); } else { Assert.AreEqual(expectedValue, value.ToString()); } } break; case OperationCode.Put: region[key] = expectedValue; break; case OperationCode.Destroy: if (!isMultiuser && !region.GetLocalView().ContainsKey(key)) { // Since DESTROY will fail unless the value is present // in the local cache, this is a workaround for two cases: // 1. When the operation is supposed to succeed then in // the current AuthzCredentialGenerators the clients having // DESTROY permission also has CREATE/UPDATE permission // so that calling region.Put() will work for that case. // 2. When the operation is supposed to fail with // NotAuthorizedException then in the current // AuthzCredentialGenerators the clients not // having DESTROY permission are those with reader role that have // GET permission. // // If either of these assumptions fails, then this has to be // adjusted or reworked accordingly. if (CheckFlags(flags, OpFlags.CheckNotAuthz)) { value = region[key]; Assert.AreEqual(expectedValue, value.ToString()); } else { region[key] = expectedValue; } } if ( !isMultiuser && CheckFlags(flags, OpFlags.LocalOp)) { region.GetLocalView().Remove(key); //Destroyed replaced by Remove() API } else { region.Remove(key); //Destroyed replaced by Remove API } break; //TODO: Need to fix Stack overflow exception.. case OperationCode.RegisterInterest: if (CheckFlags(flags, OpFlags.UseList)) { breakLoop = true; // Register interest list in this case List<CacheableKey> keyList = new List<CacheableKey>(numOps); for (int keyNumIndex = 0; keyNumIndex < numOps; ++keyNumIndex) { int keyNum = indices[keyNumIndex]; keyList.Add(KeyPrefix + keyNum); } region.GetSubscriptionService().RegisterKeys(keyList.ToArray()); } else if (CheckFlags(flags, OpFlags.UseRegex)) { breakLoop = true; region.GetSubscriptionService().RegisterRegex(KeyPrefix + "[0-" + (numOps - 1) + ']'); } else if (CheckFlags(flags, OpFlags.UseAllKeys)) { breakLoop = true; region.GetSubscriptionService().RegisterAllKeys(); } break; //TODO: Need to fix Stack overflow exception.. case OperationCode.UnregisterInterest: if (CheckFlags(flags, OpFlags.UseList)) { breakLoop = true; // Register interest list in this case List<CacheableKey> keyList = new List<CacheableKey>(numOps); for (int keyNumIndex = 0; keyNumIndex < numOps; ++keyNumIndex) { int keyNum = indices[keyNumIndex]; keyList.Add(KeyPrefix + keyNum); } region.GetSubscriptionService().UnregisterKeys(keyList.ToArray()); } else if (CheckFlags(flags, OpFlags.UseRegex)) { breakLoop = true; region.GetSubscriptionService().UnregisterRegex(KeyPrefix + "[0-" + (numOps - 1) + ']'); } else if (CheckFlags(flags, OpFlags.UseAllKeys)) { breakLoop = true; region.GetSubscriptionService().UnregisterAllKeys(); } break; case OperationCode.Query: breakLoop = true; ISelectResults<object> queryResults; if (!isMultiuser) { queryResults = (ResultSet<object>)region.Query<object>( "SELECT DISTINCT * FROM " + region.FullPath); } else { queryResults = CacheHelper.getMultiuserCache(creds).GetQueryService().NewQuery<object>("SELECT DISTINCT * FROM " + region.FullPath).Execute(); } Assert.IsNotNull(queryResults); if (!CheckFlags(flags, OpFlags.CheckFail)) { Assert.AreEqual(numOps, queryResults.Size); } var querySet = new List<string>((int) queryResults.Size); ResultSet<object> rs = queryResults as ResultSet<object>; foreach ( object result in rs) { querySet.Add(result.ToString()); } for (int keyNumIndex = 0; keyNumIndex < numOps; ++keyNumIndex) { int keyNum = indices[keyNumIndex]; string expectedVal = valPrefix + keyNumIndex; if (CheckFlags(flags, OpFlags.CheckFail)) { Assert.IsFalse(querySet.Contains(expectedVal)); } else { Assert.IsTrue(querySet.Contains(expectedVal)); } } break; case OperationCode.RegionDestroy: breakLoop = true; if ( !isMultiuser && CheckFlags(flags, OpFlags.LocalOp)) { region.GetLocalView().DestroyRegion(); } else { region.DestroyRegion(); } break; case OperationCode.GetServerKeys: breakLoop = true; ICollection<object> serverKeys = region.Keys; break; //TODO: Need to fix System.ArgumentOutOfRangeException: Index was out of range. Know issue with GetAll() case OperationCode.GetAll: //ICacheableKey[] keymap = new ICacheableKey[5]; List<object> keymap = new List<object>(); for (int i = 0; i < 5; i++) { keymap.Add(i); //CacheableInt32 item = CacheableInt32.Create(i); //Int32 item = i; // NOTE: GetAll should operate right after PutAll //keymap[i] = item; } Dictionary<Object, Object> entrymap = new Dictionary<Object, Object>(); //CacheableHashMap entrymap = CacheableHashMap.Create(); region.GetAll(keymap, entrymap, null, false); if (entrymap.Count < 5) { Assert.Fail("DoOp: Got fewer entries for op " + op); } break; case OperationCode.PutAll: // NOTE: PutAll should operate right before GetAll //CacheableHashMap entrymap2 = CacheableHashMap.Create(); Dictionary<Object, Object> entrymap2 = new Dictionary<object, object>(); for (int i = 0; i < 5; i++) { //CacheableInt32 item = CacheableInt32.Create(i); Int32 item = i; entrymap2.Add(item, item); } region.PutAll(entrymap2); break; case OperationCode.RemoveAll: Dictionary<Object, Object> entrymap3 = new Dictionary<object, object>(); for (int i = 0; i < 5; i++) { //CacheableInt32 item = CacheableInt32.Create(i); Int32 item = i; entrymap3.Add(item, item); } region.PutAll(entrymap3); ICollection<object> keys = new LinkedList<object>(); for (int i = 0; i < 5; i++) { Int32 item = i; keys.Add(item); } region.RemoveAll(keys); break; case OperationCode.ExecuteCQ: Pool/*<object, object>*/ pool = CacheHelper.DCache.GetPoolManager().Find("__TESTPOOL1_"); QueryService qs; if (pool != null) { qs = pool.GetQueryService(); } else { //qs = CacheHelper.DCache.GetQueryService(); qs = null; } CqAttributesFactory<object, object> cqattrsfact = new CqAttributesFactory<object, object>(); CqAttributes<object, object> cqattrs = cqattrsfact.Create(); CqQuery<object, object> cq = qs.NewCq("cq_security", "SELECT * FROM /" + region.Name, cqattrs, false); qs.ExecuteCqs(); qs.StopCqs(); qs.CloseCqs(); break; case OperationCode.ExecuteFunction: if (!isMultiuser) { Pool/*<object, object>*/ pool2 = CacheHelper.DCache.GetPoolManager().Find("__TESTPOOL1_"); if (pool2 != null) { Client.FunctionService<object>.OnServer(pool2).Execute("securityTest"); Client.FunctionService<object>.OnRegion<object, object>(region).Execute("FireNForget"); } else { expectedResult = ExpectedResult.Success; } } else { //FunctionService fs = CacheHelper.getMultiuserCache(creds).GetFunctionService(); //Execution exe = fs.OnServer(); IRegionService userCache = CacheHelper.getMultiuserCache(creds); Apache.Geode.Client.Execution<object> exe = Client.FunctionService<object>.OnServer(userCache); exe.Execute("securityTest"); exe = Client.FunctionService<object>.OnServers(userCache); Client.FunctionService<object>.OnRegion<object, object>(region); Client.FunctionService<object>.OnRegion<object, object>(userCache.GetRegion<object, object>(region.Name)).Execute("FireNForget"); } break; default: Assert.Fail("DoOp: Unhandled operation " + op); break; } if (expectedResult != ExpectedResult.Success) { Assert.Fail("Expected an exception while performing operation"); } } catch (AssertionException ex) { Util.Log("DoOp: failed assertion: {0}", ex); throw; } catch (NotAuthorizedException ex) { exceptionOccured = true; if (expectedResult == ExpectedResult.NotAuthorizedException) { Util.Log( "DoOp: Got expected NotAuthorizedException when doing operation [" + op + "] with flags [" + flags + "]: " + ex.Message); continue; } else { Assert.Fail("DoOp: Got unexpected NotAuthorizedException when " + "doing operation: " + ex.Message); } } catch (Exception ex) { exceptionOccured = true; if (expectedResult == ExpectedResult.OtherException) { Util.Log("DoOp: Got expected exception when doing operation: " + ex.GetType() + "::" + ex.Message); continue; } else { Assert.Fail("DoOp: Got unexpected exception when doing operation: " + ex); } } } if (!exceptionOccured && expectedResult != ExpectedResult.Success) { Assert.Fail("Expected an exception while performing operation"); } Util.Log(" doop done"); } protected void ExecuteOpBlock(List<OperationWithAction> opBlock, string authInit, Properties<string, string> extraAuthProps, Properties<string, string> extraAuthzProps, TestCredentialGenerator gen, Random rnd, bool isMultiuser, bool ssl,bool withPassword) { foreach (OperationWithAction currentOp in opBlock) { // Start client with valid credentials as specified in // OperationWithAction OperationCode opCode = currentOp.OpCode; OpFlags opFlags = currentOp.Flags; int clientNum = currentOp.ClientNum; if (clientNum > m_clients.Length) { Assert.Fail("ExecuteOpBlock: Unknown client number " + clientNum); } ClientBase client = m_clients[clientNum - 1]; Util.Log("ExecuteOpBlock: performing operation number [" + currentOp.OpNum + "]: " + currentOp); Properties<string, string> clientProps = null; if (!CheckFlags(opFlags, OpFlags.UseOldConn)) { Properties<string, string> opCredentials; int newRnd = rnd.Next(100) + 1; string currentRegionName = '/' + RegionName; if (CheckFlags(opFlags, OpFlags.UseSubRegion)) { currentRegionName += ('/' + SubregionName); } string credentialsTypeStr; OperationCode authOpCode = currentOp.AuthzOperationCode; int[] indices = currentOp.Indices; CredentialGenerator cGen = gen.GetCredentialGenerator(); Properties<string, string> javaProps = null; if (CheckFlags(opFlags, OpFlags.CheckNotAuthz) || CheckFlags(opFlags, OpFlags.UseNotAuthz)) { opCredentials = gen.GetDisallowedCredentials( new OperationCode[] { authOpCode }, new string[] { currentRegionName }, indices, newRnd); credentialsTypeStr = " unauthorized " + authOpCode; } else { opCredentials = gen.GetAllowedCredentials(new OperationCode[] { opCode, authOpCode }, new string[] { currentRegionName }, indices, newRnd); credentialsTypeStr = " authorized " + authOpCode; } if (cGen != null) { javaProps = cGen.JavaProperties; } clientProps = SecurityTestUtil.ConcatProperties( opCredentials, extraAuthProps, extraAuthzProps); // Start the client with valid credentials but allowed or disallowed to // perform an operation Util.Log("ExecuteOpBlock: For client" + clientNum + credentialsTypeStr + " credentials: " + opCredentials); if(!isMultiuser) client.Call(SecurityTestUtil.CreateClientSSL, RegionName, CacheHelper.Locators, authInit, clientProps, ssl, withPassword); else client.Call(SecurityTestUtil.CreateClientMU, RegionName, CacheHelper.Locators, authInit, (Properties<string, string>)null, true); } ExpectedResult expectedResult; if (CheckFlags(opFlags, OpFlags.CheckNotAuthz)) { expectedResult = ExpectedResult.NotAuthorizedException; } else if (CheckFlags(opFlags, OpFlags.CheckException)) { expectedResult = ExpectedResult.OtherException; } else { expectedResult = ExpectedResult.Success; } // Perform the operation from selected client if (!isMultiuser) client.Call(DoOp, opCode, currentOp.Indices, opFlags, expectedResult); else client.Call(DoOp, opCode, currentOp.Indices, opFlags, expectedResult, clientProps, true); } } protected List<AuthzCredentialGenerator> GetAllGeneratorCombos(bool isMultiUser) { List<AuthzCredentialGenerator> generators = new List<AuthzCredentialGenerator>(); foreach (AuthzCredentialGenerator.ClassCode authzClassCode in Enum.GetValues(typeof(AuthzCredentialGenerator.ClassCode))) { List<CredentialGenerator> cGenerators = SecurityTestUtil.getAllGenerators(isMultiUser); foreach (CredentialGenerator cGen in cGenerators) { AuthzCredentialGenerator authzGen = AuthzCredentialGenerator .Create(authzClassCode); if (authzGen != null) { if (authzGen.Init(cGen)) { generators.Add(authzGen); } } } } return generators; } protected void RunOpsWithFailoverSSL(OperationWithAction[] opCodes, string testName, bool withPassword) { RunOpsWithFailover(opCodes, testName, false, true,withPassword); } protected void RunOpsWithFailover(OperationWithAction[] opCodes, string testName) { RunOpsWithFailover(opCodes, testName, false); } protected void RunOpsWithFailover(OperationWithAction[] opCodes, string testName, bool isMultiUser) { RunOpsWithFailover(opCodes, testName, isMultiUser, false, false); } protected void RunOpsWithFailover(OperationWithAction[] opCodes, string testName, bool isMultiUser, bool ssl, bool withPassword) { CacheHelper.SetupJavaServers(true, CacheXml1, CacheXml2); CacheHelper.StartJavaLocator(1, "GFELOC", null, ssl); Util.Log("Locator started"); foreach (AuthzCredentialGenerator authzGen in GetAllGeneratorCombos(isMultiUser)) { CredentialGenerator cGen = authzGen.GetCredentialGenerator(); Properties<string, string> extraAuthProps = cGen.SystemProperties; Properties<string, string> javaProps = cGen.JavaProperties; Properties<string, string> extraAuthzProps = authzGen.SystemProperties; string authenticator = cGen.Authenticator; string authInit = cGen.AuthInit; string accessor = authzGen.AccessControl; TestAuthzCredentialGenerator tgen = new TestAuthzCredentialGenerator(authzGen); Util.Log(testName + ": Using authinit: " + authInit); Util.Log(testName + ": Using authenticator: " + authenticator); Util.Log(testName + ": Using accessor: " + accessor); // Start servers with all required properties string serverArgs = SecurityTestUtil.GetServerArgs(authenticator, accessor, null, SecurityTestUtil.ConcatProperties(extraAuthProps, extraAuthzProps), javaProps); // Perform all the ops on the clients List<OperationWithAction> opBlock = new List<OperationWithAction>(); Random rnd = new Random(); for (int opNum = 0; opNum < opCodes.Length; ++opNum) { // Start client with valid credentials as specified in // OperationWithAction OperationWithAction currentOp = opCodes[opNum]; if (currentOp == OperationWithAction.OpBlockEnd || currentOp == OperationWithAction.OpBlockNoFailover) { // End of current operation block; execute all the operations // on the servers with/without failover if (opBlock.Count > 0) { // Start the first server and execute the operation block CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1, serverArgs, ssl); Util.Log("Cacheserver 1 started."); CacheHelper.StopJavaServer(2, false); ExecuteOpBlock(opBlock, authInit, extraAuthProps, extraAuthzProps, tgen, rnd, isMultiUser, ssl, withPassword); if (currentOp == OperationWithAction.OpBlockNoFailover) { CacheHelper.StopJavaServer(1); } else { // Failover to the second server and run the block again CacheHelper.StartJavaServerWithLocators(2, "GFECS2", 1, serverArgs, ssl); Util.Log("Cacheserver 2 started."); CacheHelper.StopJavaServer(1); ExecuteOpBlock(opBlock, authInit, extraAuthProps, extraAuthzProps, tgen, rnd, isMultiUser, ssl, withPassword); } opBlock.Clear(); } } else { currentOp.OpNum = opNum; opBlock.Add(currentOp); } } // Close all clients here since we run multiple iterations for pool and non pool configs foreach (ClientBase client in m_clients) { client.Call(Close); } } CacheHelper.StopJavaLocator(1, true, ssl); CacheHelper.ClearEndpoints(); CacheHelper.ClearLocators(); } #endregion /// <summary> /// This class specifies flags that can be used to alter the behaviour of /// operations being performed by the <see cref="DoOp"/> method. /// </summary> [Flags] public enum OpFlags { /// <summary> /// Default behaviour. /// </summary> None = 0x0, /// <summary> /// Check that the operation should fail. /// </summary> CheckFail = 0x1, /// <summary> /// Check that the operation should throw <c>NotAuthorizedException</c>. /// </summary> CheckNotAuthz = 0x2, /// <summary> /// Do the connection with unauthorized credentials but do not check that the /// operation throws <c>NotAuthorizedException</c>. /// </summary> UseNotAuthz = 0x4, /// <summary> /// Check that the region should not be available. /// </summary> CheckNoRegion = 0x8, /// <summary> /// Check that the operation should throw an exception other than the /// <c>NotAuthorizedException</c>. /// </summary> CheckException = 0x10, /// <summary> /// Check for values starting with <c>NValuePrefix</c> instead of /// <c>ValuePrefix</c>. /// </summary> UseNewVal = 0x20, /// <summary> /// Register a regular expression. /// </summary> UseRegex = 0x40, /// <summary> /// Register a list of keys. /// </summary> UseList = 0x80, /// <summary> /// Register all keys. /// </summary> UseAllKeys = 0x100, /// <summary> /// Perform the local version of the operation (if applicable). /// </summary> LocalOp = 0x200, /// <summary> /// Check that the key for the operation should not be present. /// </summary> CheckNoKey = 0x400, /// <summary> /// Use the sub-region for performing the operation. /// </summary> UseSubRegion = 0x800, /// <summary> /// Do not try to create the sub-region. /// </summary> NoCreateSubRegion = 0x1000, /// <summary> /// Do not re-connect using new credentials rather use the previous /// connection. /// </summary> UseOldConn = 0x2000, } /// <summary> /// This class encapsulates an <see cref="OperationCode"/> with associated flags, the /// client to perform the operation, and the number of operations to perform. /// </summary> public class OperationWithAction { /// <summary> /// The operation to be performed. /// </summary> private OperationCode m_opCode; /// <summary> /// The operation for which authorized or unauthorized credentials have to be /// generated. This is the same as {@link #opCode} when not specified. /// </summary> private OperationCode m_authzOpCode; /// <summary> /// The client number on which the operation has to be performed. /// </summary> private int m_clientNum; /// <summary> /// Bitwise or'd <see cref="OpFlags"/> to change/specify the behaviour of /// the operations. /// </summary> private OpFlags m_flags; /// <summary> /// Indices of the keys array to be used for operations. The keys used /// will be concatenation of <c>KeyPrefix</c> and <c>index</c> integer. /// </summary> private int[] m_indices; /// <summary> /// An index for the operation used for logging. /// </summary> private int m_opNum; /// <summary> /// Indicates end of an operation block which can be used for testing with /// failover. /// </summary> public static readonly OperationWithAction OpBlockEnd = new OperationWithAction( OperationCode.Get, 4); /// <summary> /// Indicates end of an operation block which should not be used for testing /// with failover. /// </summary> public static readonly OperationWithAction OpBlockNoFailover = new OperationWithAction(OperationCode.Get, 5); private void SetIndices(int numOps) { this.m_indices = new int[numOps]; for (int index = 0; index < numOps; ++index) { this.m_indices[index] = index; } } public OperationWithAction(OperationCode opCode) { this.m_opCode = opCode; this.m_authzOpCode = opCode; this.m_clientNum = 1; this.m_flags = OpFlags.None; SetIndices(4); this.m_opNum = 0; } public OperationWithAction(OperationCode opCode, int clientNum) { this.m_opCode = opCode; this.m_authzOpCode = opCode; this.m_clientNum = clientNum; this.m_flags = OpFlags.None; SetIndices(4); this.m_opNum = 0; } public OperationWithAction(OperationCode opCode, int clientNum, OpFlags flags, int numOps) { this.m_opCode = opCode; this.m_authzOpCode = opCode; this.m_clientNum = clientNum; this.m_flags = flags; SetIndices(numOps); this.m_opNum = 0; } public OperationWithAction(OperationCode opCode, OperationCode deniedOpCode, int clientNum, OpFlags flags, int numOps) { this.m_opCode = opCode; this.m_authzOpCode = deniedOpCode; this.m_clientNum = clientNum; this.m_flags = flags; SetIndices(numOps); this.m_opNum = 0; } public OperationWithAction(OperationCode opCode, int clientNum, OpFlags flags, int[] indices) { this.m_opCode = opCode; this.m_authzOpCode = opCode; this.m_clientNum = clientNum; this.m_flags = flags; this.m_indices = indices; this.m_opNum = 0; } public OperationWithAction(OperationCode opCode, OperationCode authzOpCode, int clientNum, OpFlags flags, int[] indices) { this.m_opCode = opCode; this.m_authzOpCode = authzOpCode; this.m_clientNum = clientNum; this.m_flags = flags; this.m_indices = indices; this.m_opNum = 0; } public OperationCode OpCode { get { return this.m_opCode; } } public OperationCode AuthzOperationCode { get { return this.m_authzOpCode; } } public int ClientNum { get { return this.m_clientNum; } } public OpFlags Flags { get { return this.m_flags; } } public int[] Indices { get { return this.m_indices; } } public int OpNum { get { return this.m_opNum; } set { this.m_opNum = value; } } public override string ToString() { return "opCode:" + this.m_opCode + ",authOpCode:" + this.m_authzOpCode + ",clientNum:" + this.m_clientNum + ",flags:" + this.m_flags + ",numOps:" + this.m_indices.Length + ",indices:" + IndicesToString(this.m_indices); } } /// <summary> /// Simple interface to generate credentials with authorization based on key /// indices also. This is utilized by the post-operation authorization tests /// <c>ThinClientAuthzObjectModTests</c> where authorization depends on /// the actual keys being used for the operation. /// </summary> public interface TestCredentialGenerator { /// <summary> /// Get allowed credentials for the given set of operations in the given /// regions and indices of keys. /// </summary> Properties<string, string> GetAllowedCredentials(OperationCode[] opCodes, string[] regionNames, int[] keyIndices, int num); /// <summary> /// Get disallowed credentials for the given set of operations in the given /// regions and indices of keys. /// </summary> Properties<string, string> GetDisallowedCredentials(OperationCode[] opCodes, string[] regionNames, int[] keyIndices, int num); /// <summary> /// Get the <see cref="CredentialGenerator"/> if any. /// </summary> /// <returns></returns> CredentialGenerator GetCredentialGenerator(); } /// <summary> /// Contains a <c>AuthzCredentialGenerator</c> and implements the /// <c>TestCredentialGenerator</c> interface. /// </summary> protected class TestAuthzCredentialGenerator : TestCredentialGenerator { private AuthzCredentialGenerator authzGen; public TestAuthzCredentialGenerator(AuthzCredentialGenerator authzGen) { this.authzGen = authzGen; } public Properties<string, string> GetAllowedCredentials(OperationCode[] opCodes, string[] regionNames, int[] keyIndices, int num) { return this.authzGen.GetAllowedCredentials(opCodes, regionNames, num); } public Properties<string, string> GetDisallowedCredentials(OperationCode[] opCodes, string[] regionNames, int[] keyIndices, int num) { return this.authzGen.GetDisallowedCredentials(opCodes, regionNames, num); } public CredentialGenerator GetCredentialGenerator() { return authzGen.GetCredentialGenerator(); } } } }
// Copyright (c) Charlie Poole, Rob Prouse and Contributors. MIT License - see LICENSE.txt using System; using System.IO; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using NUnit.Framework.Interfaces; using NUnit.TestData.TestContextData; using NUnit.TestUtilities; using NUnit.Framework.Internal; namespace NUnit.Framework { [TestFixture] public class TestContextTests { private TestContext _setupContext; private readonly string _name = TestContext.CurrentContext.Test.Name; private readonly string _testDirectory = TestContext.CurrentContext.TestDirectory; private readonly string _workDirectory = TestContext.CurrentContext.WorkDirectory; private string _tempFilePath; private const string TempFileName = "TestContextTests.tmp"; [OneTimeSetUp] public void CreateTempFile() { _tempFilePath = Path.Combine(TestContext.CurrentContext.WorkDirectory, TempFileName); File.Create(_tempFilePath).Dispose(); } [OneTimeTearDown] public void RemoveTempFile() { File.Delete(_tempFilePath); } [SetUp] public void SaveSetUpContext() { _setupContext = TestContext.CurrentContext; } #region TestDirectory [Test] public void ConstructorCanAccessTestDirectory() { Assert.That(_testDirectory, Is.Not.Null); } [TestCaseSource(nameof(TestDirectorySource))] public void TestCaseSourceCanAccessTestDirectory(string testDirectory) { Assert.That(testDirectory, Is.EqualTo(_testDirectory)); } static IEnumerable<string> TestDirectorySource() { yield return TestContext.CurrentContext.TestDirectory; } #endregion #region WorkDirectory [Test] public void ConstructorAccessWorkDirectory() { Assert.That(_workDirectory, Is.Not.Null); } [Test] public void TestCanAccessWorkDirectory() { string workDirectory = TestContext.CurrentContext.WorkDirectory; Assert.NotNull(workDirectory); Assert.That(Directory.Exists(workDirectory), string.Format("Directory {0} does not exist", workDirectory)); } [TestCaseSource(nameof(WorkDirectorySource))] public void TestCaseSourceCanAccessWorkDirectory(string workDirectory) { Assert.That(workDirectory, Is.EqualTo(_workDirectory)); } static IEnumerable<string> WorkDirectorySource() { yield return TestContext.CurrentContext.WorkDirectory; } #endregion #region Test #region Name [Test] public void ConstructorCanAccessFixtureName() { Assert.That(_name, Is.EqualTo("TestContextTests")); } [Test] public void TestCanAccessItsOwnName() { Assert.That(TestContext.CurrentContext.Test.Name, Is.EqualTo("TestCanAccessItsOwnName")); } [Test] public void SetUpCanAccessTestName() { Assert.That(_setupContext.Test.Name, Is.EqualTo(TestContext.CurrentContext.Test.Name)); } [TestCase(5)] public void TestCaseCanAccessItsOwnName(int x) { Assert.That(TestContext.CurrentContext.Test.Name, Is.EqualTo("TestCaseCanAccessItsOwnName(5)")); } #endregion #region FullName [Test] public void SetUpCanAccessTestFullName() { Assert.That(_setupContext.Test.FullName, Is.EqualTo(TestContext.CurrentContext.Test.FullName)); } [Test] public void TestCanAccessItsOwnFullName() { Assert.That(TestContext.CurrentContext.Test.FullName, Is.EqualTo("NUnit.Framework.TestContextTests.TestCanAccessItsOwnFullName")); } [TestCase(42)] public void TestCaseCanAccessItsOwnFullName(int x) { Assert.That(TestContext.CurrentContext.Test.FullName, Is.EqualTo("NUnit.Framework.TestContextTests.TestCaseCanAccessItsOwnFullName(42)")); } #endregion #region MethodName [Test] public void SetUpCanAccessTestMethodName() { Assert.That(_setupContext.Test.MethodName, Is.EqualTo(TestContext.CurrentContext.Test.MethodName)); } [Test] public void TestCanAccessItsOwnMethodName() { Assert.That(TestContext.CurrentContext.Test.MethodName, Is.EqualTo("TestCanAccessItsOwnMethodName")); } [TestCase(5)] public void TestCaseCanAccessItsOwnMethodName(int x) { Assert.That(TestContext.CurrentContext.Test.MethodName, Is.EqualTo("TestCaseCanAccessItsOwnMethodName")); } #endregion #region Id [Test] public void TestCanAccessItsOwnId() { Assert.That(TestContext.CurrentContext.Test.ID, Is.Not.Null.And.Not.Empty); } [Test] public void SetUpCanAccessTestId() { Assert.That(_setupContext.Test.ID, Is.EqualTo(TestContext.CurrentContext.Test.ID)); } #endregion #region Properties [Test] [Property("Answer", "42")] public void TestCanAccessItsOwnProperties() { Assert.That(TestContext.CurrentContext.Test.Properties.Get("Answer"), Is.EqualTo("42")); } #endregion #region Arguments [TestCase(24, "abc")] public void TestCanAccessItsOwnArguments(int x, string s) { Assert.That(TestContext.CurrentContext.Test.Arguments, Is.EqualTo(new object[] { 24, "abc" })); } [Test] public void TestCanAccessEmptyArgumentsArrayWhenDoesNotHaveArguments() { Assert.That(TestContext.CurrentContext.Test.Arguments, Is.EqualTo(new object[0])); } #endregion #endregion #region Result [Test] public void TestCanAccessAssertCount() { var context = TestExecutionContext.CurrentContext; // These are counted as asserts Assert.That(context.AssertCount, Is.EqualTo(0)); Assert.AreEqual(4, 2 + 2); Warn.Unless(2 + 2, Is.EqualTo(4)); // This one is counted below Assert.That(context.AssertCount, Is.EqualTo(3)); // Assumptions are not counted are not counted Assume.That(2 + 2, Is.EqualTo(4)); Assert.That(TestContext.CurrentContext.AssertCount, Is.EqualTo(4)); } [TestCase("ThreeAsserts_TwoFailed", AssertionStatus.Failed, AssertionStatus.Failed)] [TestCase("WarningPlusFailedAssert", AssertionStatus.Warning, AssertionStatus.Failed)] public void TestCanAccessAssertionResults(string testName, params AssertionStatus[] expectedStatus) { AssertionResultFixture fixture = new AssertionResultFixture(); TestBuilder.RunTestCase(fixture, testName); var assertions = fixture.Assertions; Assert.That(assertions.Select((o) => o.Status), Is.EqualTo(expectedStatus)); Assert.That(assertions.Select((o) => o.Message), Has.All.Contains("Expected: 5")); Assert.That(assertions.Select((o) => o.StackTrace), Has.All.Contains(testName)); } [Test] public void TestCanAccessTestState_PassingTest() { TestStateRecordingFixture fixture = new TestStateRecordingFixture(); TestBuilder.RunTestFixture(fixture); Assert.That(fixture.StateList, Is.EqualTo("Inconclusive=>Inconclusive=>Passed")); } [Test] public void TestCanAccessTestState_FailureInSetUp() { TestStateRecordingFixture fixture = new TestStateRecordingFixture(); fixture.SetUpFailure = true; TestBuilder.RunTestFixture(fixture); Assert.That(fixture.StateList, Is.EqualTo("Inconclusive=>=>Failed")); } [Test] public void TestCanAccessTestState_FailingTest() { TestStateRecordingFixture fixture = new TestStateRecordingFixture(); fixture.TestFailure = true; TestBuilder.RunTestFixture(fixture); Assert.That(fixture.StateList, Is.EqualTo("Inconclusive=>Inconclusive=>Failed")); } [Test] public void TestCanAccessTestState_IgnoredInSetUp() { TestStateRecordingFixture fixture = new TestStateRecordingFixture(); fixture.SetUpIgnore = true; TestBuilder.RunTestFixture(fixture); Assert.That(fixture.StateList, Is.EqualTo("Inconclusive=>=>Skipped:Ignored")); } [Test] public void TestContextStoresFailureInfoForTearDown() { var fixture = new TestTestContextInTearDown(); TestBuilder.RunTestFixture(fixture); Assert.That(fixture.FailCount, Is.EqualTo(1)); Assert.That(fixture.Message, Is.EqualTo("Deliberate failure")); PlatformInconsistency.MonoMethodInfoInvokeLosesStackTrace.SkipOnAffectedPlatform(() => { Assert.That(fixture.StackTrace, Does.Contain("NUnit.TestData.TestContextData.TestTestContextInTearDown.FailingTest")); }); } [Test] public void TestContextStoresFailureInfoForOneTimeTearDown() { var fixture = new TestTestContextInOneTimeTearDown(); TestBuilder.RunTestFixture(fixture); Assert.That(fixture.PassCount, Is.EqualTo(2)); Assert.That(fixture.FailCount, Is.EqualTo(1)); Assert.That(fixture.WarningCount, Is.EqualTo(0)); Assert.That(fixture.SkipCount, Is.EqualTo(3)); Assert.That(fixture.InconclusiveCount, Is.EqualTo(4)); Assert.That(fixture.Message, Is.EqualTo(TestResult.CHILD_ERRORS_MESSAGE)); Assert.That(fixture.StackTrace, Is.Null); } #endregion #region Out [Test] public async Task TestContextOut_ShouldFlowWithAsyncExecution() { var expected = TestContext.Out; await YieldAsync(); Assert.AreEqual(expected, TestContext.Out); } [Test] public async Task TestContextWriteLine_ShouldNotThrow_WhenExecutedFromAsyncMethod() { Assert.DoesNotThrow(TestContext.WriteLine); await YieldAsync(); Assert.DoesNotThrow(TestContext.WriteLine); } [Test] public void TestContextOut_ShouldBeAvailableFromOtherThreads() { var isTestContextOutAvailable = false; Task.Factory.StartNew(() => { isTestContextOutAvailable = TestContext.Out != null; }).Wait(); Assert.True(isTestContextOutAvailable); } private async Task YieldAsync() { await Task.Yield(); } #endregion #region Test Attachments [Test] public void FilePathOnlyDoesNotThrow() { Assert.That(() => TestContext.AddTestAttachment(_tempFilePath), Throws.Nothing); } [Test] public void FilePathAndDescriptionDoesNotThrow() { Assert.That(() => TestContext.AddTestAttachment(_tempFilePath, "Description"), Throws.Nothing); } [TestCase(null)] [TestCase("bad|path.png", IncludePlatform = "Win")] public void InvalidFilePathsThrowsArgumentException(string filePath) { Assert.That(() => TestContext.AddTestAttachment(filePath), Throws.InstanceOf<ArgumentException>()); } [Test] public void NoneExistentFileThrowsFileNotFoundException() { Assert.That(() => TestContext.AddTestAttachment("NotAFile.txt"), Throws.InstanceOf<FileNotFoundException>()); } #endregion #region Retry [Test] public void TestCanAccessCurrentRepeatCount() { var context = TestExecutionContext.CurrentContext; Assert.That(context.CurrentRepeatCount, Is.EqualTo(0), "expected TestContext.CurrentRepeatCount to be accessible and be zero on first execution of test"); } #endregion } [TestFixture] public class TestContextTearDownTests { private const int THE_MEANING_OF_LIFE = 42; [Test] public void TestTheMeaningOfLife() { Assert.That(THE_MEANING_OF_LIFE, Is.EqualTo(42)); } [TearDown] public void TearDown() { TestContext context = TestContext.CurrentContext; Assert.That(context, Is.Not.Null); Assert.That(context.Test, Is.Not.Null); Assert.That(context.Test.Name, Is.EqualTo("TestTheMeaningOfLife")); Assert.That(context.Result, Is.Not.Null); Assert.That(context.Result.Outcome, Is.EqualTo(ResultState.Success)); Assert.That(context.Result.PassCount, Is.EqualTo(1)); Assert.That(context.Result.FailCount, Is.EqualTo(0)); Assert.That(context.TestDirectory, Is.Not.Null); Assert.That(context.WorkDirectory, Is.Not.Null); } } [TestFixture] public class TestContextOneTimeTearDownTests { [Test] public void TestTruth() { Assert.That(true, Is.True); } [Test] public void TestFalsehood() { Assert.That(false, Is.False); } [Test, Explicit] public void TestExplicit() { Assert.Pass("Always passes if you run it!"); } [OneTimeTearDown] public void OneTimeTearDown() { TestContext context = TestContext.CurrentContext; Assert.That(context, Is.Not.Null); Assert.That(context.Test, Is.Not.Null); Assert.That(context.Test.Name, Is.EqualTo("TestContextOneTimeTearDownTests")); Assert.That(context.Result, Is.Not.Null); Assert.That(context.Result.Outcome, Is.EqualTo(ResultState.Success)); Assert.That(context.Result.PassCount, Is.EqualTo(2)); Assert.That(context.Result.FailCount, Is.EqualTo(0)); Assert.That(context.Result.SkipCount, Is.EqualTo(1)); } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Core.Tests.Compute { using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using Apache.Ignite.Core.Binary; using Apache.Ignite.Core.Cluster; using Apache.Ignite.Core.Common; using Apache.Ignite.Core.Compute; using Apache.Ignite.Core.Resource; using NUnit.Framework; /// <summary> /// Tests for exception handling on various task execution stages. /// </summary> public class IgniteExceptionTaskSelfTest : AbstractTaskTest { /** Error mode. */ private static ErrorMode _mode; /** Observed job errors. */ private static readonly ICollection<Exception> JobErrs = new List<Exception>(); /// <summary> /// Constructor. /// </summary> public IgniteExceptionTaskSelfTest() : base(false) { } /// <summary> /// Constructor. /// </summary> /// <param name="fork">Fork flag.</param> protected IgniteExceptionTaskSelfTest(bool fork) : base(fork) { } /// <summary> /// Test error occurred during map step. /// </summary> [Test] public void TestMapError() { _mode = ErrorMode.MapErr; GoodException e = ExecuteWithError() as GoodException; Assert.IsNotNull(e); Assert.AreEqual(ErrorMode.MapErr, e.Mode); } /// <summary> /// Test not-marshalable error occurred during map step. /// </summary> [Test] public void TestMapNotMarshalableError() { _mode = ErrorMode.MapErrNotMarshalable; BadException e = ExecuteWithError() as BadException; Assert.IsNotNull(e); Assert.AreEqual(ErrorMode.MapErrNotMarshalable, e.Mode); } /// <summary> /// Test task behavior when job produced by mapper is not marshalable. /// </summary> [Test] public void TestMapNotMarshalableJob() { _mode = ErrorMode.MapJobNotMarshalable; Assert.IsInstanceOf<BinaryObjectException>(ExecuteWithError()); } /// <summary> /// Test local job error. /// </summary> [Test] public void TestLocalJobError() { _mode = ErrorMode.LocJobErr; int res = Execute(); Assert.AreEqual(1, res); Assert.AreEqual(4, JobErrs.Count); var goodEx = JobErrs.First().InnerException as GoodException; Assert.IsNotNull(goodEx); Assert.AreEqual(ErrorMode.LocJobErr, goodEx.Mode); } /// <summary> /// Test local not-marshalable job error. /// </summary> [Test] public void TestLocalJobErrorNotMarshalable() { _mode = ErrorMode.LocJobErrNotMarshalable; int res = Execute(); Assert.AreEqual(1, res); Assert.AreEqual(4, JobErrs.Count); Assert.IsInstanceOf<BadException>(JobErrs.First().InnerException); // Local job exception is not marshalled. } /// <summary> /// Test local not-marshalable job result. /// </summary> [Test] public void TestLocalJobResultNotMarshalable() { _mode = ErrorMode.LocJobResNotMarshalable; int res = Execute(); Assert.AreEqual(2, res); // Local job result is not marshalled. Assert.AreEqual(0, JobErrs.Count); } /// <summary> /// Test remote job error. /// </summary> [Test] public void TestRemoteJobError() { _mode = ErrorMode.RmtJobErr; int res = Execute(); Assert.AreEqual(1, res); Assert.AreEqual(4, JobErrs.Count); var goodEx = JobErrs.First().InnerException as GoodException; Assert.IsNotNull(goodEx); Assert.AreEqual(ErrorMode.RmtJobErr, goodEx.Mode); } /// <summary> /// Test remote not-marshalable job error. /// </summary> [Test] public void TestRemoteJobErrorNotMarshalable() { _mode = ErrorMode.RmtJobErrNotMarshalable; var ex = Assert.Throws<AggregateException>(() => Execute()); Assert.IsInstanceOf<SerializationException>(ex.InnerException); } /// <summary> /// Test local not-marshalable job result. /// </summary> [Test] public void TestRemoteJobResultNotMarshalable() { _mode = ErrorMode.RmtJobResNotMarshalable; int res = Execute(); Assert.AreEqual(1, res); Assert.AreEqual(4, JobErrs.Count); Assert.IsNotNull(JobErrs.ElementAt(0) as IgniteException); } /// <summary> /// Test local result error. /// </summary> [Test] public void TestLocalResultError() { _mode = ErrorMode.LocResErr; GoodException e = ExecuteWithError() as GoodException; Assert.IsNotNull(e); Assert.AreEqual(ErrorMode.LocResErr, e.Mode); } /// <summary> /// Test local result not-marshalable error. /// </summary> [Test] public void TestLocalResultErrorNotMarshalable() { _mode = ErrorMode.LocResErrNotMarshalable; BadException e = ExecuteWithError() as BadException; Assert.IsNotNull(e); Assert.AreEqual(ErrorMode.LocResErrNotMarshalable, e.Mode); } /// <summary> /// Test remote result error. /// </summary> [Test] public void TestRemoteResultError() { _mode = ErrorMode.RmtResErr; GoodException e = ExecuteWithError() as GoodException; Assert.IsNotNull(e); Assert.AreEqual(ErrorMode.RmtResErr, e.Mode); } /// <summary> /// Test remote result not-marshalable error. /// </summary> [Test] public void TestRemoteResultErrorNotMarshalable() { _mode = ErrorMode.RmtResErrNotMarshalable; var err = ExecuteWithError(); var badException = err as BadException; Assert.IsNotNull(badException, err.ToString()); Assert.AreEqual(ErrorMode.RmtResErrNotMarshalable, badException.Mode); } /// <summary> /// Test reduce with error. /// </summary> [Test] public void TestReduceError() { _mode = ErrorMode.ReduceErr; GoodException e = ExecuteWithError() as GoodException; Assert.IsNotNull(e); Assert.AreEqual(ErrorMode.ReduceErr, e.Mode); } /// <summary> /// Test reduce with not-marshalable error. /// </summary> [Test] public void TestReduceErrorNotMarshalable() { _mode = ErrorMode.ReduceErrNotMarshalable; BadException e = ExecuteWithError() as BadException; Assert.IsNotNull(e); Assert.AreEqual(ErrorMode.ReduceErrNotMarshalable, e.Mode); } /// <summary> /// Test reduce with not-marshalable result. /// </summary> [Test] public void TestReduceResultNotMarshalable() { _mode = ErrorMode.ReduceResNotMarshalable; int res = Execute(); Assert.AreEqual(2, res); } /// <summary> /// Execute task successfully. /// </summary> /// <returns>Task result.</returns> private int Execute() { JobErrs.Clear(); Func<object, int> getRes = r => r is GoodTaskResult ? ((GoodTaskResult) r).Res : ((BadTaskResult) r).Res; var res1 = getRes(Grid1.GetCompute().Execute(new Task())); var res2 = getRes(Grid1.GetCompute().Execute<object, object>(typeof(Task))); var resAsync1 = getRes(Grid1.GetCompute().ExecuteAsync(new Task()).Result); var resAsync2 = getRes(Grid1.GetCompute().ExecuteAsync<object, object>(typeof(Task)).Result); Assert.AreEqual(res1, res2); Assert.AreEqual(res2, resAsync1); Assert.AreEqual(resAsync1, resAsync2); return res1; } /// <summary> /// Execute task with error. /// </summary> /// <returns>Task</returns> private Exception ExecuteWithError() { JobErrs.Clear(); var ex = Assert.Throws<AggregateException>(() => Grid1.GetCompute().Execute(new Task())); Assert.IsNotNull(ex.InnerException); return ex.InnerException; } /// <summary> /// Error modes. /// </summary> private enum ErrorMode { /** Error during map step. */ MapErr, /** Error during map step which is not marshalable. */ MapErrNotMarshalable, /** Job created by mapper is not marshalable. */ MapJobNotMarshalable, /** Error occurred in local job. */ LocJobErr, /** Error occurred in local job and is not marshalable. */ LocJobErrNotMarshalable, /** Local job result is not marshalable. */ LocJobResNotMarshalable, /** Error occurred in remote job. */ RmtJobErr, /** Error occurred in remote job and is not marshalable. */ RmtJobErrNotMarshalable, /** Remote job result is not marshalable. */ RmtJobResNotMarshalable, /** Error occurred during local result processing. */ LocResErr, /** Error occurred during local result processing and is not marshalable. */ LocResErrNotMarshalable, /** Error occurred during remote result processing. */ RmtResErr, /** Error occurred during remote result processing and is not marshalable. */ RmtResErrNotMarshalable, /** Error during reduce step. */ ReduceErr, /** Error during reduce step and is not marshalable. */ ReduceErrNotMarshalable, /** Reduce result is not marshalable. */ ReduceResNotMarshalable } /// <summary> /// Task. /// </summary> private class Task : IComputeTask<object, object> { /** Grid. */ [InstanceResource] private readonly IIgnite _grid = null; /** Result. */ private int _res; /** <inheritDoc /> */ public IDictionary<IComputeJob<object>, IClusterNode> Map(IList<IClusterNode> subgrid, object arg) { switch (_mode) { case ErrorMode.MapErr: throw new GoodException(ErrorMode.MapErr); case ErrorMode.MapErrNotMarshalable: throw new BadException(ErrorMode.MapErrNotMarshalable); case ErrorMode.MapJobNotMarshalable: { var badJobs = new Dictionary<IComputeJob<object>, IClusterNode>(); foreach (IClusterNode node in subgrid) badJobs.Add(new BadJob(), node); return badJobs; } } // Map completes sucessfully and we spread jobs to all nodes. var jobs = new Dictionary<IComputeJob<object>, IClusterNode>(); foreach (IClusterNode node in subgrid) jobs.Add(new GoodJob(!_grid.GetCluster().GetLocalNode().Id.Equals(node.Id)), node); return jobs; } /** <inheritDoc /> */ public ComputeJobResultPolicy OnResult(IComputeJobResult<object> res, IList<IComputeJobResult<object>> rcvd) { if (res.Exception != null) { JobErrs.Add(res.Exception); } else { object res0 = res.Data; var result = res0 as GoodJobResult; bool rmt = result != null ? result.Rmt : ((BadJobResult) res0).Rmt; if (rmt) { switch (_mode) { case ErrorMode.RmtResErr: throw new GoodException(ErrorMode.RmtResErr); case ErrorMode.RmtResErrNotMarshalable: throw new BadException(ErrorMode.RmtResErrNotMarshalable); } } else { switch (_mode) { case ErrorMode.LocResErr: throw new GoodException(ErrorMode.LocResErr); case ErrorMode.LocResErrNotMarshalable: throw new BadException(ErrorMode.LocResErrNotMarshalable); } } _res += 1; } return ComputeJobResultPolicy.Wait; } /** <inheritDoc /> */ public object Reduce(IList<IComputeJobResult<object>> results) { switch (_mode) { case ErrorMode.ReduceErr: throw new GoodException(ErrorMode.ReduceErr); case ErrorMode.ReduceErrNotMarshalable: throw new BadException(ErrorMode.ReduceErrNotMarshalable); case ErrorMode.ReduceResNotMarshalable: return new BadTaskResult(_res); } return new GoodTaskResult(_res); } } /// <summary> /// /// </summary> [Serializable] private class GoodJob : IComputeJob<object>, ISerializable { /** Whether the job is remote. */ private readonly bool _rmt; /// <summary> /// /// </summary> /// <param name="rmt"></param> public GoodJob(bool rmt) { _rmt = rmt; } /// <summary> /// /// </summary> /// <param name="info"></param> /// <param name="context"></param> protected GoodJob(SerializationInfo info, StreamingContext context) { _rmt = info.GetBoolean("rmt"); } /** <inheritDoc /> */ public void GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue("rmt", _rmt); } /** <inheritDoc /> */ public object Execute() { if (_rmt) { switch (_mode) { case ErrorMode.RmtJobErr: throw new GoodException(ErrorMode.RmtJobErr); case ErrorMode.RmtJobErrNotMarshalable: throw new BadException(ErrorMode.RmtJobErr); case ErrorMode.RmtJobResNotMarshalable: return new BadJobResult(_rmt); } } else { switch (_mode) { case ErrorMode.LocJobErr: throw new GoodException(ErrorMode.LocJobErr); case ErrorMode.LocJobErrNotMarshalable: throw new BadException(ErrorMode.LocJobErr); case ErrorMode.LocJobResNotMarshalable: return new BadJobResult(_rmt); } } return new GoodJobResult(_rmt); } /** <inheritDoc /> */ public void Cancel() { // No-op. } } /// <summary> /// /// </summary> private class BadJob : IComputeJob<object>, IBinarizable { /** <inheritDoc /> */ public object Execute() { throw new NotImplementedException(); } /** <inheritDoc /> */ public void Cancel() { // No-op. } /** <inheritDoc /> */ public void WriteBinary(IBinaryWriter writer) { throw new BinaryObjectException("Expected"); } /** <inheritDoc /> */ public void ReadBinary(IBinaryReader reader) { throw new BinaryObjectException("Expected"); } } /// <summary> /// /// </summary> [Serializable] private class GoodJobResult : ISerializable { /** */ public readonly bool Rmt; /// <summary> /// /// </summary> /// <param name="rmt"></param> public GoodJobResult(bool rmt) { Rmt = rmt; } /// <summary> /// /// </summary> /// <param name="info"></param> /// <param name="context"></param> protected GoodJobResult(SerializationInfo info, StreamingContext context) { Rmt = info.GetBoolean("rmt"); } /** <inheritDoc /> */ public void GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue("rmt", Rmt); } } /// <summary> /// /// </summary> private class BadJobResult : IBinarizable { /** */ public readonly bool Rmt; /// <summary> /// /// </summary> /// <param name="rmt"></param> public BadJobResult(bool rmt) { Rmt = rmt; } /** <inheritDoc /> */ public void WriteBinary(IBinaryWriter writer) { throw new BinaryObjectException("Expected"); } /** <inheritDoc /> */ public void ReadBinary(IBinaryReader reader) { throw new BinaryObjectException("Expected"); } } /// <summary> /// /// </summary> [Serializable] private class GoodTaskResult : ISerializable { /** */ public readonly int Res; /// <summary> /// /// </summary> /// <param name="res"></param> public GoodTaskResult(int res) { Res = res; } /// <summary> /// /// </summary> /// <param name="info"></param> /// <param name="context"></param> protected GoodTaskResult(SerializationInfo info, StreamingContext context) { Res = info.GetInt32("res"); } /** <inheritDoc /> */ public void GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue("res", Res); } } /// <summary> /// /// </summary> private class BadTaskResult { /** */ public readonly int Res; /// <summary> /// /// </summary> /// <param name="res"></param> public BadTaskResult(int res) { Res = res; } } /// <summary> /// Marshalable exception. /// </summary> [Serializable] private class GoodException : Exception { /** */ public readonly ErrorMode Mode; /// <summary> /// /// </summary> /// <param name="mode"></param> public GoodException(ErrorMode mode) { Mode = mode; } /// <summary> /// /// </summary> /// <param name="info"></param> /// <param name="context"></param> protected GoodException(SerializationInfo info, StreamingContext context) { Mode = (ErrorMode)info.GetInt32("mode"); } /** <inheritDoc /> */ public override void GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue("mode", (int)Mode); base.GetObjectData(info, context); } } /// <summary> /// Not marshalable exception. /// </summary> private class BadException : Exception { /** */ public readonly ErrorMode Mode; /// <summary> /// /// </summary> /// <param name="mode"></param> public BadException(ErrorMode mode) { Mode = mode; } } } }
// 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.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.VisualStudio.Language.StandardClassification; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Classification; using Microsoft.VisualStudio.Utilities; namespace Microsoft.VisualStudio.InteractiveWindow.Commands { internal sealed class Commands : IInteractiveWindowCommands { private const string _commandSeparator = ","; private readonly Dictionary<string, IInteractiveWindowCommand> _commands; private readonly int _maxCommandNameLength; private readonly IInteractiveWindow _window; private readonly IContentType _commandContentType; private readonly IStandardClassificationService _classificationRegistry; private IContentType _languageContentType; private ITextBuffer _previousBuffer; public string CommandPrefix { get; set; } public bool InCommand { get { return _window.CurrentLanguageBuffer.ContentType == _commandContentType; } } internal Commands(IInteractiveWindow window, string prefix, IEnumerable<IInteractiveWindowCommand> commands, IContentTypeRegistryService contentTypeRegistry = null, IStandardClassificationService classificationRegistry = null) { CommandPrefix = prefix; _window = window; Dictionary<string, IInteractiveWindowCommand> commandsDict = new Dictionary<string, IInteractiveWindowCommand>(); foreach (var command in commands) { int length = 0; foreach (var name in command.Names) { if (commandsDict.ContainsKey(name)) { throw new InvalidOperationException(string.Format(InteractiveWindowResources.DuplicateCommand, string.Join(", ", command.Names))); } if (length != 0) { length += _commandSeparator.Length; } length += name.Length; commandsDict[name] = command; } if (length == 0) { throw new InvalidOperationException(string.Format(InteractiveWindowResources.MissingCommandName, command.GetType().Name)); } _maxCommandNameLength = Math.Max(_maxCommandNameLength, length); } _commands = commandsDict; _classificationRegistry = classificationRegistry; if (contentTypeRegistry != null) { _commandContentType = contentTypeRegistry.GetContentType(PredefinedInteractiveCommandsContentTypes.InteractiveCommandContentTypeName); } if (window != null) { window.SubmissionBufferAdded += Window_SubmissionBufferAdded; window.Properties[typeof(IInteractiveWindowCommands)] = this; } } private void Window_SubmissionBufferAdded(object sender, SubmissionBufferAddedEventArgs e) { if (_previousBuffer != null) { _previousBuffer.Changed -= NewBufferChanged; } _languageContentType = e.NewBuffer.ContentType; e.NewBuffer.Changed += NewBufferChanged; _previousBuffer = e.NewBuffer; } private void NewBufferChanged(object sender, TextContentChangedEventArgs e) { bool isCommand = IsCommand(e.After.GetExtent()); ITextBuffer buffer = e.After.TextBuffer; IContentType contentType = buffer.ContentType; IContentType newContentType = null; if (contentType == _languageContentType) { if (isCommand) { newContentType = _commandContentType; } } else { if (!isCommand) { newContentType = _languageContentType; } } if (newContentType != null) { buffer.ChangeContentType(newContentType, editTag: null); } } internal bool IsCommand(SnapshotSpan span) { SnapshotSpan prefixSpan, commandSpan, argumentsSpan; return TryParseCommand(span, out prefixSpan, out commandSpan, out argumentsSpan) != null; } internal IInteractiveWindowCommand TryParseCommand(SnapshotSpan span, out SnapshotSpan prefixSpan, out SnapshotSpan commandSpan, out SnapshotSpan argumentsSpan) { string prefix = CommandPrefix; SnapshotSpan trimmed = span.TrimStart(); if (!trimmed.StartsWith(prefix)) { prefixSpan = commandSpan = argumentsSpan = default(SnapshotSpan); return null; } prefixSpan = trimmed.SubSpan(0, prefix.Length); var nameAndArgs = trimmed.SubSpan(prefix.Length).TrimStart(); SnapshotPoint nameEnd = nameAndArgs.IndexOfAnyWhiteSpace() ?? span.End; commandSpan = new SnapshotSpan(span.Snapshot, Span.FromBounds(nameAndArgs.Start.Position, nameEnd.Position)); argumentsSpan = new SnapshotSpan(span.Snapshot, Span.FromBounds(nameEnd.Position, span.End.Position)).Trim(); return this[commandSpan.GetText()]; } public IInteractiveWindowCommand this[string name] { get { IInteractiveWindowCommand command; _commands.TryGetValue(name, out command); return command; } } public IEnumerable<IInteractiveWindowCommand> GetCommands() { return _commands.Values; } internal IEnumerable<string> Help() { string format = "{0,-" + _maxCommandNameLength + "} {1}"; return _commands.OrderBy(entry => entry.Key).Select(cmd => string.Format(format, cmd.Key, cmd.Value.Description)); } public IEnumerable<ClassificationSpan> Classify(SnapshotSpan span) { SnapshotSpan prefixSpan, commandSpan, argumentsSpan; var command = TryParseCommand(span.Snapshot.GetExtent(), out prefixSpan, out commandSpan, out argumentsSpan); if (command == null) { yield break; } if (span.OverlapsWith(prefixSpan)) { yield return Classification(span.Snapshot, prefixSpan, _classificationRegistry.Keyword); } if (span.OverlapsWith(commandSpan)) { yield return Classification(span.Snapshot, commandSpan, _classificationRegistry.Keyword); } if (argumentsSpan.Length > 0) { foreach (var classifiedSpan in command.ClassifyArguments(span.Snapshot, argumentsSpan.Span, span.Span)) { yield return classifiedSpan; } } } private ClassificationSpan Classification(ITextSnapshot snapshot, Span span, IClassificationType classificationType) { return new ClassificationSpan(new SnapshotSpan(snapshot, span), classificationType); } /// <returns> /// Null if parsing fails, the result of execution otherwise. /// </returns> public Task<ExecutionResult> TryExecuteCommand() { var span = _window.CurrentLanguageBuffer.CurrentSnapshot.GetExtent(); SnapshotSpan prefixSpan, commandSpan, argumentsSpan; var command = TryParseCommand(span, out prefixSpan, out commandSpan, out argumentsSpan); if (command == null) { return null; } return ExecuteCommandAsync(command, argumentsSpan.GetText()); } private async Task<ExecutionResult> ExecuteCommandAsync(IInteractiveWindowCommand command, string arguments) { try { return await command.Execute(_window, arguments).ConfigureAwait(false); } catch (Exception e) { _window.ErrorOutputWriter.WriteLine($"Command '{command.Names.First()}' failed: {e.Message}"); return ExecutionResult.Failure; } } private const string HelpIndent = " "; private static readonly string[] s_shortcutDescriptions = new[] { "Enter Evaluate the current input if it appears to be complete.", "Ctrl-Enter If the caret is in current pending input submission, evaluate the entire submission.", " If the caret is in a previous input block, copy that input text to the end of the buffer.", "Shift-Enter If the caret is in the current pending input submission, insert a new line.", "Escape If the caret is in the current pending input submission, delete the entire submission.", "Alt-UpArrow Paste previous input at end of buffer, rotate through history.", "Alt-DownArrow Paste next input at end of buffer, rotate through history.", "UpArrow Normal editor buffer navigation.", "DownArrow Normal editor buffer navigation.", "Ctrl-K, Ctrl-Enter Paste the selection at the end of interactive buffer, leave caret at the end of input.", "Ctrl-E, Ctrl-Enter Paste and execute the selection before any pending input in the interactive buffer.", "Ctrl-A Alternatively select the input block containing the caret, or whole buffer.", }; public void DisplayHelp() { _window.WriteLine("Keyboard shortcuts:"); foreach (var line in s_shortcutDescriptions) { _window.Write(HelpIndent); _window.WriteLine(line); } _window.WriteLine("REPL commands:"); foreach (var line in Help()) { _window.Write(HelpIndent); _window.WriteLine(line); } } public void DisplayCommandUsage(IInteractiveWindowCommand command, TextWriter writer, bool displayDetails) { if (displayDetails) { writer.WriteLine(command.Description); writer.WriteLine(string.Empty); } writer.WriteLine("Usage:"); writer.Write(HelpIndent); writer.Write(CommandPrefix); writer.Write(string.Join(_commandSeparator, command.Names)); string commandLine = command.CommandLine; if (commandLine != null) { writer.Write(" "); writer.Write(commandLine); } if (displayDetails) { writer.WriteLine(string.Empty); var paramsDesc = command.ParametersDescription; if (paramsDesc != null && paramsDesc.Any()) { writer.WriteLine(string.Empty); writer.WriteLine("Parameters:"); int maxParamNameLength = paramsDesc.Max(entry => entry.Key.Length); string paramHelpLineFormat = HelpIndent + "{0,-" + maxParamNameLength + "} {1}"; foreach (var paramDesc in paramsDesc) { writer.WriteLine(string.Format(paramHelpLineFormat, paramDesc.Key, paramDesc.Value)); } } IEnumerable<string> details = command.DetailedDescription; if (details != null && details.Any()) { writer.WriteLine(string.Empty); foreach (var line in details) { writer.WriteLine(line); } } } } public void DisplayCommandHelp(IInteractiveWindowCommand command) { DisplayCommandUsage(command, _window.OutputWriter, displayDetails: true); } } }
/* * Copyright (c) 2012 Mario Freitas (imkira@gmail.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 UnityEngine; [ExecuteInEditMode] [AddComponentMenu("SysFont/Text")] public class SysFontText : MonoBehaviour, ISysFontTexturable { [SerializeField] protected SysFontTexture _texture = new SysFontTexture(); #region ISysFontTexturable properties public string Text { get { return _texture.Text; } set { _texture.Text = value; } } public string AppleFontName { get { return _texture.AppleFontName; } set { _texture.AppleFontName = value; } } public string AndroidFontName { get { return _texture.AndroidFontName; } set { _texture.AndroidFontName = value; } } public string FontName { get { return _texture.FontName; } set { _texture.FontName = value; } } public int FontSize { get { return _texture.FontSize; } set { _texture.FontSize = value; } } public bool IsBold { get { return _texture.IsBold; } set { _texture.IsBold = value; } } public bool IsItalic { get { return _texture.IsItalic; } set { _texture.IsItalic = value; } } public SysFont.Alignment Alignment { get { return _texture.Alignment; } set { _texture.Alignment = value; } } public bool IsMultiLine { get { return _texture.IsMultiLine; } set { _texture.IsMultiLine = value; } } public int MaxWidthPixels { get { return _texture.MaxWidthPixels; } set { _texture.MaxWidthPixels = value; } } public int MaxHeightPixels { get { return _texture.MaxHeightPixels; } set { _texture.MaxHeightPixels = value; } } public int WidthPixels { get { return _texture.WidthPixels; } } public int HeightPixels { get { return _texture.HeightPixels; } } public int TextWidthPixels { get { return _texture.TextWidthPixels; } } public int TextHeightPixels { get { return _texture.TextHeightPixels; } } public Texture2D Texture { get { return _texture.Texture; } } public float ScaleSize { get { return _texture.ScaleSize; } set { _texture.ScaleSize = value; } } #endregion [SerializeField] protected Color _fontColor = Color.white; public enum PivotAlignment { TopLeft, Top, TopRight, Left, Center, Right, BottomLeft, Bottom, BottomRight } [SerializeField] protected PivotAlignment _pivot = PivotAlignment.Center; protected Color _lastFontColor; public Color FontColor { get { return _fontColor; } set { if (_fontColor != value) { _fontColor = value; } } } protected PivotAlignment _lastPivot; public PivotAlignment Pivot { get { return _pivot; } set { if (_pivot != value) { _pivot = value; } } } protected Transform _transform; protected Material _createdMaterial = null; protected Material _material = null; protected Vector3[] _vertices = null; protected Vector2[] _uv = null; protected int[] _triangles = null; protected Mesh _mesh = null; protected MeshFilter _filter = null; protected MeshRenderer _renderer = null; static protected Shader _shader = null; protected void UpdateMesh() { if (_filter == null) { _filter = gameObject.GetComponent<MeshFilter>(); if (_filter == null) { _filter = gameObject.AddComponent<MeshFilter>(); _filter.hideFlags = HideFlags.HideInInspector; } } if (_renderer == null) { _renderer = gameObject.GetComponent<MeshRenderer>(); if (_renderer == null) { _renderer = gameObject.AddComponent<MeshRenderer>(); _renderer.hideFlags = HideFlags.HideInInspector; } if (_shader == null) { _shader = Shader.Find("SysFont/Unlit Transparent"); } if (_createdMaterial == null) { _createdMaterial = new Material(_shader); } _createdMaterial.hideFlags = HideFlags.HideInInspector | HideFlags.DontSave; _material = _createdMaterial; _renderer.sharedMaterial = _material; } _material.color = _fontColor; _lastFontColor = _fontColor; if (_uv == null) { _uv = new Vector2[4]; _triangles = new int[6] { 0, 2, 1, 2, 3, 1 }; } Vector2 uv = new Vector2(_texture.TextWidthPixels / (float)_texture.WidthPixels, _texture.TextHeightPixels / (float)_texture.HeightPixels); _uv[0] = Vector2.zero; _uv[1] = new Vector2(uv.x, 0f); _uv[2] = new Vector2(0f, uv.y); _uv[3] = uv; UpdatePivot(); UpdateScale(); } protected void UpdatePivot() { if (_vertices == null) { _vertices = new Vector3[4]; _vertices[0] = Vector3.zero; _vertices[1] = Vector3.zero; _vertices[2] = Vector3.zero; _vertices[3] = Vector3.zero; } // horizontal if ((_pivot == PivotAlignment.TopLeft) || (_pivot == PivotAlignment.Left) || (_pivot == PivotAlignment.BottomLeft)) { _vertices[0].x = _vertices[2].x = 0f; _vertices[1].x = _vertices[3].x = 1f; } else if ((_pivot == PivotAlignment.TopRight) || (_pivot == PivotAlignment.Right) || (_pivot == PivotAlignment.BottomRight)) { _vertices[0].x = _vertices[2].x = -1f; _vertices[1].x = _vertices[3].x = 0f; } else { _vertices[0].x = _vertices[2].x = -0.5f; _vertices[1].x = _vertices[3].x = 0.5f; } // vertical if ((_pivot == PivotAlignment.TopLeft) || (_pivot == PivotAlignment.Top) || (_pivot == PivotAlignment.TopRight)) { _vertices[0].y = _vertices[1].y = -1f; _vertices[2].y = _vertices[3].y = 0f; } else if ((_pivot == PivotAlignment.BottomLeft) || (_pivot == PivotAlignment.Bottom) || (_pivot == PivotAlignment.BottomRight)) { _vertices[0].y = _vertices[1].y = 0f; _vertices[2].y = _vertices[3].y = 1f; } else { _vertices[0].y = _vertices[1].y = -0.5f; _vertices[2].y = _vertices[3].y = 0.5f; } if (_mesh == null) { _mesh = new Mesh(); _mesh.name = "SysFontTextMesh"; _mesh.hideFlags = HideFlags.DontSave | HideFlags.DontSave; } _mesh.vertices = _vertices; _mesh.uv = _uv; _mesh.triangles = _triangles; _mesh.RecalculateBounds(); _filter.mesh = _mesh; _lastPivot = _pivot; } public void UpdateScale() { Vector3 scale = _transform.localScale; scale.x = (float)_texture.TextWidthPixels * _texture.ScaleSize; scale.y = (float)_texture.TextHeightPixels * _texture.ScaleSize; _transform.localScale = scale; } #region MonoBehaviour methods protected virtual void Awake() { _transform = transform; } protected virtual void Update() { if (_texture.NeedsRedraw) { if (_texture.Update() == false) { return; } UpdateMesh(); _material.mainTexture = Texture; } if (_texture.IsUpdated == false) { return; } if ((_fontColor != _lastFontColor) && (_material != null)) { _material.color = _fontColor; _lastFontColor = _fontColor; } if (_lastPivot != _pivot) { UpdatePivot(); } } protected void OnDestroy() { if (_texture != null) { _texture.Destroy(); _texture = null; } SysFont.SafeDestroy(_mesh); SysFont.SafeDestroy(_createdMaterial); _createdMaterial = null; _material = null; _vertices = null; _uv = null; _triangles = null; _mesh = null; _filter = null; _renderer = null; } #endregion }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using gaxgrpc = Google.Api.Gax.Grpc; using lro = Google.LongRunning; using proto = Google.Protobuf; using grpccore = Grpc.Core; using grpcinter = Grpc.Core.Interceptors; using sys = System; using sc = System.Collections; using scg = System.Collections.Generic; using sco = System.Collections.ObjectModel; using st = System.Threading; using stt = System.Threading.Tasks; namespace Google.Cloud.Compute.V1 { /// <summary>Settings for <see cref="RoutesClient"/> instances.</summary> public sealed partial class RoutesSettings : gaxgrpc::ServiceSettingsBase { /// <summary>Get a new instance of the default <see cref="RoutesSettings"/>.</summary> /// <returns>A new instance of the default <see cref="RoutesSettings"/>.</returns> public static RoutesSettings GetDefault() => new RoutesSettings(); /// <summary>Constructs a new <see cref="RoutesSettings"/> object with default settings.</summary> public RoutesSettings() { } private RoutesSettings(RoutesSettings existing) : base(existing) { gax::GaxPreconditions.CheckNotNull(existing, nameof(existing)); DeleteSettings = existing.DeleteSettings; DeleteOperationsSettings = existing.DeleteOperationsSettings.Clone(); GetSettings = existing.GetSettings; InsertSettings = existing.InsertSettings; InsertOperationsSettings = existing.InsertOperationsSettings.Clone(); ListSettings = existing.ListSettings; OnCopy(existing); } partial void OnCopy(RoutesSettings existing); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to <c>RoutesClient.Delete</c> and /// <c>RoutesClient.DeleteAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>This call will not be retried.</description></item> /// <item><description>No timeout is applied.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings DeleteSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.None); /// <summary> /// Long Running Operation settings for calls to <c>RoutesClient.Delete</c> and <c>RoutesClient.DeleteAsync</c>. /// </summary> /// <remarks> /// Uses default <see cref="gax::PollSettings"/> of: /// <list type="bullet"> /// <item><description>Initial delay: 20 seconds.</description></item> /// <item><description>Delay multiplier: 1.5</description></item> /// <item><description>Maximum delay: 45 seconds.</description></item> /// <item><description>Total timeout: 24 hours.</description></item> /// </list> /// </remarks> public lro::OperationsSettings DeleteOperationsSettings { get; set; } = new lro::OperationsSettings { DefaultPollSettings = new gax::PollSettings(gax::Expiration.FromTimeout(sys::TimeSpan.FromHours(24)), sys::TimeSpan.FromSeconds(20), 1.5, sys::TimeSpan.FromSeconds(45)), }; /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to <c>RoutesClient.Get</c> and /// <c>RoutesClient.GetAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>This call will not be retried.</description></item> /// <item><description>No timeout is applied.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings GetSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.None); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to <c>RoutesClient.Insert</c> and /// <c>RoutesClient.InsertAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>This call will not be retried.</description></item> /// <item><description>No timeout is applied.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings InsertSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.None); /// <summary> /// Long Running Operation settings for calls to <c>RoutesClient.Insert</c> and <c>RoutesClient.InsertAsync</c>. /// </summary> /// <remarks> /// Uses default <see cref="gax::PollSettings"/> of: /// <list type="bullet"> /// <item><description>Initial delay: 20 seconds.</description></item> /// <item><description>Delay multiplier: 1.5</description></item> /// <item><description>Maximum delay: 45 seconds.</description></item> /// <item><description>Total timeout: 24 hours.</description></item> /// </list> /// </remarks> public lro::OperationsSettings InsertOperationsSettings { get; set; } = new lro::OperationsSettings { DefaultPollSettings = new gax::PollSettings(gax::Expiration.FromTimeout(sys::TimeSpan.FromHours(24)), sys::TimeSpan.FromSeconds(20), 1.5, sys::TimeSpan.FromSeconds(45)), }; /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to <c>RoutesClient.List</c> and /// <c>RoutesClient.ListAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>This call will not be retried.</description></item> /// <item><description>No timeout is applied.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings ListSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.None); /// <summary>Creates a deep clone of this object, with all the same property values.</summary> /// <returns>A deep clone of this <see cref="RoutesSettings"/> object.</returns> public RoutesSettings Clone() => new RoutesSettings(this); } /// <summary> /// Builder class for <see cref="RoutesClient"/> to provide simple configuration of credentials, endpoint etc. /// </summary> public sealed partial class RoutesClientBuilder : gaxgrpc::ClientBuilderBase<RoutesClient> { /// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary> public RoutesSettings Settings { get; set; } /// <summary>Creates a new builder with default settings.</summary> public RoutesClientBuilder() { UseJwtAccessWithScopes = RoutesClient.UseJwtAccessWithScopes; } partial void InterceptBuild(ref RoutesClient client); partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<RoutesClient> task); /// <summary>Builds the resulting client.</summary> public override RoutesClient Build() { RoutesClient client = null; InterceptBuild(ref client); return client ?? BuildImpl(); } /// <summary>Builds the resulting client asynchronously.</summary> public override stt::Task<RoutesClient> BuildAsync(st::CancellationToken cancellationToken = default) { stt::Task<RoutesClient> task = null; InterceptBuildAsync(cancellationToken, ref task); return task ?? BuildAsyncImpl(cancellationToken); } private RoutesClient BuildImpl() { Validate(); grpccore::CallInvoker callInvoker = CreateCallInvoker(); return RoutesClient.Create(callInvoker, Settings); } private async stt::Task<RoutesClient> BuildAsyncImpl(st::CancellationToken cancellationToken) { Validate(); grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false); return RoutesClient.Create(callInvoker, Settings); } /// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary> protected override string GetDefaultEndpoint() => RoutesClient.DefaultEndpoint; /// <summary> /// Returns the default scopes for this builder type, used if no scopes are otherwise specified. /// </summary> protected override scg::IReadOnlyList<string> GetDefaultScopes() => RoutesClient.DefaultScopes; /// <summary>Returns the channel pool to use when no other options are specified.</summary> protected override gaxgrpc::ChannelPool GetChannelPool() => RoutesClient.ChannelPool; /// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary> protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => ComputeRestAdapter.ComputeAdapter; } /// <summary>Routes client wrapper, for convenient use.</summary> /// <remarks> /// The Routes API. /// </remarks> public abstract partial class RoutesClient { /// <summary> /// The default endpoint for the Routes service, which is a host of "compute.googleapis.com" and a port of 443. /// </summary> public static string DefaultEndpoint { get; } = "compute.googleapis.com:443"; /// <summary>The default Routes scopes.</summary> /// <remarks> /// The default Routes scopes are: /// <list type="bullet"> /// <item><description>https://www.googleapis.com/auth/compute</description></item> /// <item><description>https://www.googleapis.com/auth/cloud-platform</description></item> /// </list> /// </remarks> public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[] { "https://www.googleapis.com/auth/compute", "https://www.googleapis.com/auth/cloud-platform", }); internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes); internal static bool UseJwtAccessWithScopes { get { bool useJwtAccessWithScopes = true; MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes); return useJwtAccessWithScopes; } } static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes); /// <summary> /// Asynchronously creates a <see cref="RoutesClient"/> using the default credentials, endpoint and settings. To /// specify custom credentials or other settings, use <see cref="RoutesClientBuilder"/>. /// </summary> /// <param name="cancellationToken"> /// The <see cref="st::CancellationToken"/> to use while creating the client. /// </param> /// <returns>The task representing the created <see cref="RoutesClient"/>.</returns> public static stt::Task<RoutesClient> CreateAsync(st::CancellationToken cancellationToken = default) => new RoutesClientBuilder().BuildAsync(cancellationToken); /// <summary> /// Synchronously creates a <see cref="RoutesClient"/> using the default credentials, endpoint and settings. To /// specify custom credentials or other settings, use <see cref="RoutesClientBuilder"/>. /// </summary> /// <returns>The created <see cref="RoutesClient"/>.</returns> public static RoutesClient Create() => new RoutesClientBuilder().Build(); /// <summary> /// Creates a <see cref="RoutesClient"/> which uses the specified call invoker for remote operations. /// </summary> /// <param name="callInvoker"> /// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null. /// </param> /// <param name="settings">Optional <see cref="RoutesSettings"/>.</param> /// <returns>The created <see cref="RoutesClient"/>.</returns> internal static RoutesClient Create(grpccore::CallInvoker callInvoker, RoutesSettings settings = null) { gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker)); grpcinter::Interceptor interceptor = settings?.Interceptor; if (interceptor != null) { callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor); } Routes.RoutesClient grpcClient = new Routes.RoutesClient(callInvoker); return new RoutesClientImpl(grpcClient, settings); } /// <summary> /// Shuts down any channels automatically created by <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not /// affected. /// </summary> /// <remarks> /// After calling this method, further calls to <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down /// by another call to this method. /// </remarks> /// <returns>A task representing the asynchronous shutdown operation.</returns> public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync(); /// <summary>The underlying gRPC Routes client</summary> public virtual Routes.RoutesClient GrpcClient => throw new sys::NotImplementedException(); /// <summary> /// Deletes the specified Route resource. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual lro::Operation<Operation, Operation> Delete(DeleteRouteRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Deletes the specified Route resource. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<lro::Operation<Operation, Operation>> DeleteAsync(DeleteRouteRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Deletes the specified Route resource. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<lro::Operation<Operation, Operation>> DeleteAsync(DeleteRouteRequest request, st::CancellationToken cancellationToken) => DeleteAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary>The long-running operations client for <c>Delete</c>.</summary> public virtual lro::OperationsClient DeleteOperationsClient => throw new sys::NotImplementedException(); /// <summary> /// Poll an operation once, using an <c>operationName</c> from a previous invocation of <c>Delete</c>. /// </summary> /// <param name="operationName"> /// The name of a previously invoked operation. Must not be <c>null</c> or empty. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The result of polling the operation.</returns> public virtual lro::Operation<Operation, Operation> PollOnceDelete(string operationName, gaxgrpc::CallSettings callSettings = null) => lro::Operation<Operation, Operation>.PollOnceFromName(gax::GaxPreconditions.CheckNotNullOrEmpty(operationName, nameof(operationName)), DeleteOperationsClient, callSettings); /// <summary> /// Asynchronously poll an operation once, using an <c>operationName</c> from a previous invocation of <c>Delete</c> /// . /// </summary> /// <param name="operationName"> /// The name of a previously invoked operation. Must not be <c>null</c> or empty. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A task representing the result of polling the operation.</returns> public virtual stt::Task<lro::Operation<Operation, Operation>> PollOnceDeleteAsync(string operationName, gaxgrpc::CallSettings callSettings = null) => lro::Operation<Operation, Operation>.PollOnceFromNameAsync(gax::GaxPreconditions.CheckNotNullOrEmpty(operationName, nameof(operationName)), DeleteOperationsClient, callSettings); /// <summary> /// Deletes the specified Route resource. /// </summary> /// <param name="project"> /// Project ID for this request. /// </param> /// <param name="route"> /// Name of the Route resource to delete. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual lro::Operation<Operation, Operation> Delete(string project, string route, gaxgrpc::CallSettings callSettings = null) => Delete(new DeleteRouteRequest { Project = gax::GaxPreconditions.CheckNotNullOrEmpty(project, nameof(project)), Route = gax::GaxPreconditions.CheckNotNullOrEmpty(route, nameof(route)), }, callSettings); /// <summary> /// Deletes the specified Route resource. /// </summary> /// <param name="project"> /// Project ID for this request. /// </param> /// <param name="route"> /// Name of the Route resource to delete. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<lro::Operation<Operation, Operation>> DeleteAsync(string project, string route, gaxgrpc::CallSettings callSettings = null) => DeleteAsync(new DeleteRouteRequest { Project = gax::GaxPreconditions.CheckNotNullOrEmpty(project, nameof(project)), Route = gax::GaxPreconditions.CheckNotNullOrEmpty(route, nameof(route)), }, callSettings); /// <summary> /// Deletes the specified Route resource. /// </summary> /// <param name="project"> /// Project ID for this request. /// </param> /// <param name="route"> /// Name of the Route resource to delete. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<lro::Operation<Operation, Operation>> DeleteAsync(string project, string route, st::CancellationToken cancellationToken) => DeleteAsync(project, route, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Returns the specified Route resource. Gets a list of available routes by making a list() request. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual Route Get(GetRouteRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns the specified Route resource. Gets a list of available routes by making a list() request. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<Route> GetAsync(GetRouteRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns the specified Route resource. Gets a list of available routes by making a list() request. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<Route> GetAsync(GetRouteRequest request, st::CancellationToken cancellationToken) => GetAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Returns the specified Route resource. Gets a list of available routes by making a list() request. /// </summary> /// <param name="project"> /// Project ID for this request. /// </param> /// <param name="route"> /// Name of the Route resource to return. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual Route Get(string project, string route, gaxgrpc::CallSettings callSettings = null) => Get(new GetRouteRequest { Project = gax::GaxPreconditions.CheckNotNullOrEmpty(project, nameof(project)), Route = gax::GaxPreconditions.CheckNotNullOrEmpty(route, nameof(route)), }, callSettings); /// <summary> /// Returns the specified Route resource. Gets a list of available routes by making a list() request. /// </summary> /// <param name="project"> /// Project ID for this request. /// </param> /// <param name="route"> /// Name of the Route resource to return. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<Route> GetAsync(string project, string route, gaxgrpc::CallSettings callSettings = null) => GetAsync(new GetRouteRequest { Project = gax::GaxPreconditions.CheckNotNullOrEmpty(project, nameof(project)), Route = gax::GaxPreconditions.CheckNotNullOrEmpty(route, nameof(route)), }, callSettings); /// <summary> /// Returns the specified Route resource. Gets a list of available routes by making a list() request. /// </summary> /// <param name="project"> /// Project ID for this request. /// </param> /// <param name="route"> /// Name of the Route resource to return. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<Route> GetAsync(string project, string route, st::CancellationToken cancellationToken) => GetAsync(project, route, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Creates a Route resource in the specified project using the data included in the request. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual lro::Operation<Operation, Operation> Insert(InsertRouteRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Creates a Route resource in the specified project using the data included in the request. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<lro::Operation<Operation, Operation>> InsertAsync(InsertRouteRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Creates a Route resource in the specified project using the data included in the request. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<lro::Operation<Operation, Operation>> InsertAsync(InsertRouteRequest request, st::CancellationToken cancellationToken) => InsertAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary>The long-running operations client for <c>Insert</c>.</summary> public virtual lro::OperationsClient InsertOperationsClient => throw new sys::NotImplementedException(); /// <summary> /// Poll an operation once, using an <c>operationName</c> from a previous invocation of <c>Insert</c>. /// </summary> /// <param name="operationName"> /// The name of a previously invoked operation. Must not be <c>null</c> or empty. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The result of polling the operation.</returns> public virtual lro::Operation<Operation, Operation> PollOnceInsert(string operationName, gaxgrpc::CallSettings callSettings = null) => lro::Operation<Operation, Operation>.PollOnceFromName(gax::GaxPreconditions.CheckNotNullOrEmpty(operationName, nameof(operationName)), InsertOperationsClient, callSettings); /// <summary> /// Asynchronously poll an operation once, using an <c>operationName</c> from a previous invocation of <c>Insert</c> /// . /// </summary> /// <param name="operationName"> /// The name of a previously invoked operation. Must not be <c>null</c> or empty. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A task representing the result of polling the operation.</returns> public virtual stt::Task<lro::Operation<Operation, Operation>> PollOnceInsertAsync(string operationName, gaxgrpc::CallSettings callSettings = null) => lro::Operation<Operation, Operation>.PollOnceFromNameAsync(gax::GaxPreconditions.CheckNotNullOrEmpty(operationName, nameof(operationName)), InsertOperationsClient, callSettings); /// <summary> /// Creates a Route resource in the specified project using the data included in the request. /// </summary> /// <param name="project"> /// Project ID for this request. /// </param> /// <param name="routeResource"> /// The body resource for this request /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual lro::Operation<Operation, Operation> Insert(string project, Route routeResource, gaxgrpc::CallSettings callSettings = null) => Insert(new InsertRouteRequest { Project = gax::GaxPreconditions.CheckNotNullOrEmpty(project, nameof(project)), RouteResource = gax::GaxPreconditions.CheckNotNull(routeResource, nameof(routeResource)), }, callSettings); /// <summary> /// Creates a Route resource in the specified project using the data included in the request. /// </summary> /// <param name="project"> /// Project ID for this request. /// </param> /// <param name="routeResource"> /// The body resource for this request /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<lro::Operation<Operation, Operation>> InsertAsync(string project, Route routeResource, gaxgrpc::CallSettings callSettings = null) => InsertAsync(new InsertRouteRequest { Project = gax::GaxPreconditions.CheckNotNullOrEmpty(project, nameof(project)), RouteResource = gax::GaxPreconditions.CheckNotNull(routeResource, nameof(routeResource)), }, callSettings); /// <summary> /// Creates a Route resource in the specified project using the data included in the request. /// </summary> /// <param name="project"> /// Project ID for this request. /// </param> /// <param name="routeResource"> /// The body resource for this request /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<lro::Operation<Operation, Operation>> InsertAsync(string project, Route routeResource, st::CancellationToken cancellationToken) => InsertAsync(project, routeResource, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Retrieves the list of Route resources available to the specified project. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable sequence of <see cref="Route"/> resources.</returns> public virtual gax::PagedEnumerable<RouteList, Route> List(ListRoutesRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Retrieves the list of Route resources available to the specified project. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable asynchronous sequence of <see cref="Route"/> resources.</returns> public virtual gax::PagedAsyncEnumerable<RouteList, Route> ListAsync(ListRoutesRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Retrieves the list of Route resources available to the specified project. /// </summary> /// <param name="project"> /// Project ID for this request. /// </param> /// <param name="pageToken"> /// The token returned from the previous request. A value of <c>null</c> or an empty string retrieves the first /// page. /// </param> /// <param name="pageSize"> /// The size of page to request. The response will not be larger than this, but may be smaller. A value of /// <c>null</c> or <c>0</c> uses a server-defined page size. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable sequence of <see cref="Route"/> resources.</returns> public virtual gax::PagedEnumerable<RouteList, Route> List(string project, string pageToken = null, int? pageSize = null, gaxgrpc::CallSettings callSettings = null) => List(new ListRoutesRequest { Project = gax::GaxPreconditions.CheckNotNullOrEmpty(project, nameof(project)), PageToken = pageToken ?? "", PageSize = pageSize ?? 0, }, callSettings); /// <summary> /// Retrieves the list of Route resources available to the specified project. /// </summary> /// <param name="project"> /// Project ID for this request. /// </param> /// <param name="pageToken"> /// The token returned from the previous request. A value of <c>null</c> or an empty string retrieves the first /// page. /// </param> /// <param name="pageSize"> /// The size of page to request. The response will not be larger than this, but may be smaller. A value of /// <c>null</c> or <c>0</c> uses a server-defined page size. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable asynchronous sequence of <see cref="Route"/> resources.</returns> public virtual gax::PagedAsyncEnumerable<RouteList, Route> ListAsync(string project, string pageToken = null, int? pageSize = null, gaxgrpc::CallSettings callSettings = null) => ListAsync(new ListRoutesRequest { Project = gax::GaxPreconditions.CheckNotNullOrEmpty(project, nameof(project)), PageToken = pageToken ?? "", PageSize = pageSize ?? 0, }, callSettings); } /// <summary>Routes client wrapper implementation, for convenient use.</summary> /// <remarks> /// The Routes API. /// </remarks> public sealed partial class RoutesClientImpl : RoutesClient { private readonly gaxgrpc::ApiCall<DeleteRouteRequest, Operation> _callDelete; private readonly gaxgrpc::ApiCall<GetRouteRequest, Route> _callGet; private readonly gaxgrpc::ApiCall<InsertRouteRequest, Operation> _callInsert; private readonly gaxgrpc::ApiCall<ListRoutesRequest, RouteList> _callList; /// <summary> /// Constructs a client wrapper for the Routes service, with the specified gRPC client and settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings">The base <see cref="RoutesSettings"/> used within this client.</param> public RoutesClientImpl(Routes.RoutesClient grpcClient, RoutesSettings settings) { GrpcClient = grpcClient; RoutesSettings effectiveSettings = settings ?? RoutesSettings.GetDefault(); gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings); DeleteOperationsClient = new lro::OperationsClientImpl(grpcClient.CreateOperationsClientForGlobalOperations(), effectiveSettings.DeleteOperationsSettings); InsertOperationsClient = new lro::OperationsClientImpl(grpcClient.CreateOperationsClientForGlobalOperations(), effectiveSettings.InsertOperationsSettings); _callDelete = clientHelper.BuildApiCall<DeleteRouteRequest, Operation>(grpcClient.DeleteAsync, grpcClient.Delete, effectiveSettings.DeleteSettings).WithGoogleRequestParam("project", request => request.Project).WithGoogleRequestParam("route", request => request.Route); Modify_ApiCall(ref _callDelete); Modify_DeleteApiCall(ref _callDelete); _callGet = clientHelper.BuildApiCall<GetRouteRequest, Route>(grpcClient.GetAsync, grpcClient.Get, effectiveSettings.GetSettings).WithGoogleRequestParam("project", request => request.Project).WithGoogleRequestParam("route", request => request.Route); Modify_ApiCall(ref _callGet); Modify_GetApiCall(ref _callGet); _callInsert = clientHelper.BuildApiCall<InsertRouteRequest, Operation>(grpcClient.InsertAsync, grpcClient.Insert, effectiveSettings.InsertSettings).WithGoogleRequestParam("project", request => request.Project); Modify_ApiCall(ref _callInsert); Modify_InsertApiCall(ref _callInsert); _callList = clientHelper.BuildApiCall<ListRoutesRequest, RouteList>(grpcClient.ListAsync, grpcClient.List, effectiveSettings.ListSettings).WithGoogleRequestParam("project", request => request.Project); Modify_ApiCall(ref _callList); Modify_ListApiCall(ref _callList); OnConstruction(grpcClient, effectiveSettings, clientHelper); } partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>; partial void Modify_DeleteApiCall(ref gaxgrpc::ApiCall<DeleteRouteRequest, Operation> call); partial void Modify_GetApiCall(ref gaxgrpc::ApiCall<GetRouteRequest, Route> call); partial void Modify_InsertApiCall(ref gaxgrpc::ApiCall<InsertRouteRequest, Operation> call); partial void Modify_ListApiCall(ref gaxgrpc::ApiCall<ListRoutesRequest, RouteList> call); partial void OnConstruction(Routes.RoutesClient grpcClient, RoutesSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper); /// <summary>The underlying gRPC Routes client</summary> public override Routes.RoutesClient GrpcClient { get; } partial void Modify_DeleteRouteRequest(ref DeleteRouteRequest request, ref gaxgrpc::CallSettings settings); partial void Modify_GetRouteRequest(ref GetRouteRequest request, ref gaxgrpc::CallSettings settings); partial void Modify_InsertRouteRequest(ref InsertRouteRequest request, ref gaxgrpc::CallSettings settings); partial void Modify_ListRoutesRequest(ref ListRoutesRequest request, ref gaxgrpc::CallSettings settings); /// <summary>The long-running operations client for <c>Delete</c>.</summary> public override lro::OperationsClient DeleteOperationsClient { get; } /// <summary> /// Deletes the specified Route resource. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override lro::Operation<Operation, Operation> Delete(DeleteRouteRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_DeleteRouteRequest(ref request, ref callSettings); Operation response = _callDelete.Sync(request, callSettings); GetGlobalOperationRequest pollRequest = GetGlobalOperationRequest.FromInitialResponse(response); request.PopulatePollRequestFields(pollRequest); return new lro::Operation<Operation, Operation>(response.ToLroResponse(pollRequest.ToLroOperationName()), DeleteOperationsClient); } /// <summary> /// Deletes the specified Route resource. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override async stt::Task<lro::Operation<Operation, Operation>> DeleteAsync(DeleteRouteRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_DeleteRouteRequest(ref request, ref callSettings); Operation response = await _callDelete.Async(request, callSettings).ConfigureAwait(false); GetGlobalOperationRequest pollRequest = GetGlobalOperationRequest.FromInitialResponse(response); request.PopulatePollRequestFields(pollRequest); return new lro::Operation<Operation, Operation>(response.ToLroResponse(pollRequest.ToLroOperationName()), DeleteOperationsClient); } /// <summary> /// Returns the specified Route resource. Gets a list of available routes by making a list() request. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override Route Get(GetRouteRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetRouteRequest(ref request, ref callSettings); return _callGet.Sync(request, callSettings); } /// <summary> /// Returns the specified Route resource. Gets a list of available routes by making a list() request. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override stt::Task<Route> GetAsync(GetRouteRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetRouteRequest(ref request, ref callSettings); return _callGet.Async(request, callSettings); } /// <summary>The long-running operations client for <c>Insert</c>.</summary> public override lro::OperationsClient InsertOperationsClient { get; } /// <summary> /// Creates a Route resource in the specified project using the data included in the request. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override lro::Operation<Operation, Operation> Insert(InsertRouteRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_InsertRouteRequest(ref request, ref callSettings); Operation response = _callInsert.Sync(request, callSettings); GetGlobalOperationRequest pollRequest = GetGlobalOperationRequest.FromInitialResponse(response); request.PopulatePollRequestFields(pollRequest); return new lro::Operation<Operation, Operation>(response.ToLroResponse(pollRequest.ToLroOperationName()), InsertOperationsClient); } /// <summary> /// Creates a Route resource in the specified project using the data included in the request. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override async stt::Task<lro::Operation<Operation, Operation>> InsertAsync(InsertRouteRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_InsertRouteRequest(ref request, ref callSettings); Operation response = await _callInsert.Async(request, callSettings).ConfigureAwait(false); GetGlobalOperationRequest pollRequest = GetGlobalOperationRequest.FromInitialResponse(response); request.PopulatePollRequestFields(pollRequest); return new lro::Operation<Operation, Operation>(response.ToLroResponse(pollRequest.ToLroOperationName()), InsertOperationsClient); } /// <summary> /// Retrieves the list of Route resources available to the specified project. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable sequence of <see cref="Route"/> resources.</returns> public override gax::PagedEnumerable<RouteList, Route> List(ListRoutesRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_ListRoutesRequest(ref request, ref callSettings); return new gaxgrpc::GrpcPagedEnumerable<ListRoutesRequest, RouteList, Route>(_callList, request, callSettings); } /// <summary> /// Retrieves the list of Route resources available to the specified project. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable asynchronous sequence of <see cref="Route"/> resources.</returns> public override gax::PagedAsyncEnumerable<RouteList, Route> ListAsync(ListRoutesRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_ListRoutesRequest(ref request, ref callSettings); return new gaxgrpc::GrpcPagedAsyncEnumerable<ListRoutesRequest, RouteList, Route>(_callList, request, callSettings); } } public partial class ListRoutesRequest : gaxgrpc::IPageRequest { /// <inheritdoc/> public int PageSize { get => checked((int)MaxResults); set => MaxResults = checked((uint)value); } } public partial class RouteList : gaxgrpc::IPageResponse<Route> { /// <summary>Returns an enumerator that iterates through the resources in this response.</summary> public scg::IEnumerator<Route> GetEnumerator() => Items.GetEnumerator(); sc::IEnumerator sc::IEnumerable.GetEnumerator() => GetEnumerator(); } public static partial class Routes { public partial class RoutesClient { /// <summary> /// Creates a new instance of <see cref="lro::Operations.OperationsClient"/> using the same call invoker as /// this client, delegating to GlobalOperations. /// </summary> /// <returns>A new Operations client for the same target as this client.</returns> public virtual lro::Operations.OperationsClient CreateOperationsClientForGlobalOperations() => GlobalOperations.GlobalOperationsClient.CreateOperationsClient(CallInvoker); } } }
/* Copyright 2010 Google Inc Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using Google.Apis.Json; using NUnit.Framework; namespace Google.Apis.Tests.Json { /// <summary> /// This is a test class for TokenStreamTest and is intended /// to contain all TokenStreamTest Unit Tests ///</summary> [TestFixture] public class TokenStreamTest { /// <summary> /// Tests if numbers with exponents are supported as values /// </summary> [Test] public void GetNextTokenExponent() { TokenStream target = new TokenStream("-1234.5678e1"); JsonToken actual = target.GetNextToken(); Assert.AreEqual(JsonToken.TokenType.Number, actual.Type); Assert.AreEqual(-12345.678, actual.Number); Assert.AreEqual("-1234.5678e1", actual.Value); } /// <summary> /// Tests if negative exponent numbers are supported as token values /// </summary> [Test] public void GetNextTokenExponentNegative() { TokenStream target = new TokenStream("-1234.5678e-1"); JsonToken actual = target.GetNextToken(); Assert.AreEqual(JsonToken.TokenType.Number, actual.Type); Assert.AreEqual(-123.45678, actual.Number); Assert.AreEqual("-1234.5678e-1", actual.Value); } /// <summary> /// Tests if positive exponent values are supported for tokens /// </summary> [Test] public void GetNextTokenExponentPositive() { TokenStream target = new TokenStream("-1234.5678e+1"); JsonToken actual = target.GetNextToken(); Assert.AreEqual(JsonToken.TokenType.Number, actual.Type); Assert.AreEqual(-12345.678, actual.Number); Assert.AreEqual("-1234.5678e+1", actual.Value); } /// <summary> /// Tests if negative numbers are supported as token values /// </summary> [Test] public void GetNextTokenNegativeNumber() { TokenStream target = new TokenStream("\"utc_offset\":-18000"); JsonToken actual = target.GetNextToken(); Assert.AreEqual(JsonToken.TokenType.String, actual.Type); Assert.AreEqual("utc_offset", actual.Value); actual = target.GetNextToken(); Assert.AreEqual(JsonToken.TokenType.NameSeperator, actual.Type); actual = target.GetNextToken(); Assert.AreEqual(JsonToken.TokenType.Number, actual.Type); Assert.AreEqual("-18000", actual.Value); Assert.AreEqual(-18000, actual.Number); } /// <summary> /// Tests if negative numbers without decimal are supported as values /// </summary> [Test] public void GetNextTokenNegativeNumberWithDecimals() { TokenStream target = new TokenStream("-1234.5678"); JsonToken actual = target.GetNextToken(); Assert.AreEqual(JsonToken.TokenType.Number, actual.Type); Assert.AreEqual(-1234.5678, actual.Number); Assert.AreEqual("-1234.5678", actual.Value); } /// <summary> /// Tests if strings with backslashes are supported as tokens /// </summary> [Test] public void GetNextTokenStringsWithBackSlash() { TokenStream target = new TokenStream( "{ \"source\":\"\\u003Ca href=\\\"http:\\/\\/blackberry.com\\/twitter\\\" rel=\\\"nofollow\\\"\\u003ETwitter for BlackBerry\\u00ae\\u003C\\/a\\u003E\" }"); JsonToken actual = target.GetNextToken(); Assert.AreEqual(JsonToken.TokenType.ObjectStart, actual.Type); actual = target.GetNextToken(); Assert.AreEqual(JsonToken.TokenType.String, actual.Type); Assert.AreEqual("source", actual.Value); actual = target.GetNextToken(); Assert.AreEqual(JsonToken.TokenType.NameSeperator, actual.Type); actual = target.GetNextToken(); Assert.AreEqual(JsonToken.TokenType.String, actual.Type); Assert.AreEqual( "\u003Ca href=\"http://blackberry.com/twitter\" rel=\"nofollow\"\u003ETwitter for BlackBerry\u00ae\u003C/a\u003E", actual.Value); actual = target.GetNextToken(); Assert.AreEqual(JsonToken.TokenType.ObjectEnd, actual.Type); } /// <summary> /// Tests if single quote escaped strings work /// </summary> [Test] public void GetNextTokenTestEscapeSingleQuoteFull() { TokenStream target = new TokenStream( "'{\\'id\\':\\'Activitiylist\\',\\'properties\\':{\\'id\\':{\\'type\\':\\'any\\'},\\'title\\':{\\'type\\':\\'any\\'},\\'items\\':{\\'items\\':{\\'$ref\\':\\'ChiliActivitiesResourceJson\\'},\\'type\\':\\'array\\'},\\'updated\\':{\\'type\\':\\'string\\'},\\'links\\':{\\'additionalProperties\\':{\\'items\\':{\\'properties\\':{\\'title\\':{\\'type\\':\\'any\\'},\\'height\\':{\\'type\\':\\'any\\'},\\'count\\':{\\'type\\':\\'any\\'},\\'updated\\':{\\'type\\':\\'string\\'},\\'width\\':{\\'type\\':\\'any\\'},\\'type\\':{\\'type\\':\\'any\\'},\\'href\\':{\\'type\\':\\'any\\'}},\\'type\\':\\'object\\'},\\'type\\':\\'array\\'},\\'type\\':\\'object\\'},\\'kind\\':{\\'default\\':\\'buzz#activityFeed\\',\\'type\\':\\'string\\'}},\\'type\\':\\'object\\'}'"); var actual = target.GetNextToken(); Assert.AreEqual(JsonToken.TokenType.String, actual.Type); Assert.AreEqual( "{\'id\':\'Activitiylist\',\'properties\':{\'id\':{\'type\':\'any\'},\'title\':{\'type\':\'any\'},\'items\':{\'items\':{\'$ref\':\'ChiliActivitiesResourceJson\'},\'type\':\'array\'},\'updated\':{\'type\':\'string\'},\'links\':{\'additionalProperties\':{\'items\':{\'properties\':{\'title\':{\'type\':\'any\'},\'height\':{\'type\':\'any\'},\'count\':{\'type\':\'any\'},\'updated\':{\'type\':\'string\'},\'width\':{\'type\':\'any\'},\'type\':{\'type\':\'any\'},\'href\':{\'type\':\'any\'}},\'type\':\'object\'},\'type\':\'array\'},\'type\':\'object\'},\'kind\':{\'default\':\'buzz#activityFeed\',\'type\':\'string\'}},\'type\':\'object\'}", actual.Value); } /// <summary> /// Tests for single escaped quote strings /// </summary> [Test] public void GetNextTokenTestEscapeSingleQuoteSimple() { TokenStream target = new TokenStream("'{\\'id\\':\\'Activitiylist\\'}'"); var actual = target.GetNextToken(); Assert.AreEqual(JsonToken.TokenType.String, actual.Type); Assert.AreEqual("{'id':'Activitiylist'}", actual.Value); } /// <summary> /// Tests if tabs are supported as tokens /// </summary> [Test] public void GetNextTokenTestEscapeTab() { TokenStream target = new TokenStream("'\\t'"); var actual = target.GetNextToken(); Assert.AreEqual(JsonToken.TokenType.String, actual.Type); Assert.AreEqual("\t", actual.Value); } /// <summary> /// Tests if unicode escape characters are supported as tokens /// </summary> [Test] public void GetNextTokenTestEscapeUniCode() { TokenStream target = new TokenStream("'\\uABCD'"); var actual = target.GetNextToken(); Assert.AreEqual(JsonToken.TokenType.String, actual.Type); Assert.AreEqual("\uABCD", actual.Value); target = new TokenStream("'\\u0000'"); actual = target.GetNextToken(); Assert.AreEqual(JsonToken.TokenType.String, actual.Type); Assert.AreEqual("\u0000", actual.Value); target = new TokenStream("'\\uFFFF'"); actual = target.GetNextToken(); Assert.AreEqual(JsonToken.TokenType.String, actual.Type); Assert.AreEqual("\uFFFF", actual.Value); } /// <summary> /// A test for GetNextToken ///</summary> [Test] public void GetNextTokenTestNestedObjects() { TokenStream target = new TokenStream("{ \"name\" : [ true, \"Value2\", false ], \"sub\" : { \"subname\" : 1234 } }"); JsonToken actual; actual = target.GetNextToken(); Assert.AreEqual(JsonToken.TokenType.ObjectStart, actual.Type); actual = target.GetNextToken(); Assert.AreEqual(JsonToken.TokenType.String, actual.Type); Assert.AreEqual("name", actual.Value); actual = target.GetNextToken(); Assert.AreEqual(JsonToken.TokenType.NameSeperator, actual.Type); actual = target.GetNextToken(); Assert.AreEqual(JsonToken.TokenType.ArrayStart, actual.Type); actual = target.GetNextToken(); Assert.AreEqual(JsonToken.TokenType.True, actual.Type); actual = target.GetNextToken(); Assert.AreEqual(JsonToken.TokenType.MemberSeperator, actual.Type); actual = target.GetNextToken(); Assert.AreEqual(JsonToken.TokenType.String, actual.Type); Assert.AreEqual("Value2", actual.Value); actual = target.GetNextToken(); Assert.AreEqual(JsonToken.TokenType.MemberSeperator, actual.Type); actual = target.GetNextToken(); Assert.AreEqual(JsonToken.TokenType.False, actual.Type); actual = target.GetNextToken(); Assert.AreEqual(JsonToken.TokenType.ArrayEnd, actual.Type); actual = target.GetNextToken(); Assert.AreEqual(JsonToken.TokenType.MemberSeperator, actual.Type); actual = target.GetNextToken(); Assert.AreEqual(JsonToken.TokenType.String, actual.Type); Assert.AreEqual("sub", actual.Value); actual = target.GetNextToken(); Assert.AreEqual(JsonToken.TokenType.NameSeperator, actual.Type); actual = target.GetNextToken(); Assert.AreEqual(JsonToken.TokenType.ObjectStart, actual.Type); actual = target.GetNextToken(); Assert.AreEqual(JsonToken.TokenType.String, actual.Type); Assert.AreEqual("subname", actual.Value); actual = target.GetNextToken(); Assert.AreEqual(JsonToken.TokenType.NameSeperator, actual.Type); actual = target.GetNextToken(); Assert.AreEqual(JsonToken.TokenType.Number, actual.Type); Assert.AreEqual("1234", actual.Value); Assert.AreEqual(1234, actual.Number); actual = target.GetNextToken(); Assert.AreEqual(JsonToken.TokenType.ObjectEnd, actual.Type); actual = target.GetNextToken(); Assert.AreEqual(JsonToken.TokenType.ObjectEnd, actual.Type); actual = target.GetNextToken(); Assert.AreEqual(null, actual); } /// <summary> /// A test for GetNextToken ///</summary> [Test] public void GetNextTokenTestSimpleArray() { TokenStream target = new TokenStream("[ \"Value1\", \"Value2\" ]"); JsonToken actual; actual = target.GetNextToken(); Assert.AreEqual(JsonToken.TokenType.ArrayStart, actual.Type); actual = target.GetNextToken(); Assert.AreEqual(JsonToken.TokenType.String, actual.Type); Assert.AreEqual("Value1", actual.Value); actual = target.GetNextToken(); Assert.AreEqual(JsonToken.TokenType.MemberSeperator, actual.Type); actual = target.GetNextToken(); Assert.AreEqual(JsonToken.TokenType.String, actual.Type); Assert.AreEqual("Value2", actual.Value); actual = target.GetNextToken(); Assert.AreEqual(JsonToken.TokenType.ArrayEnd, actual.Type); actual = target.GetNextToken(); Assert.AreEqual(null, actual); } /// <summary> /// A test for GetNextToken ///</summary> [Test] public void GetNextTokenTestSimpleObject() { TokenStream target = new TokenStream("{ \"Member\": \"Value\" }"); JsonToken actual; actual = target.GetNextToken(); Assert.AreEqual(JsonToken.TokenType.ObjectStart, actual.Type); actual = target.GetNextToken(); Assert.AreEqual(JsonToken.TokenType.String, actual.Type); Assert.AreEqual("Member", actual.Value); actual = target.GetNextToken(); Assert.AreEqual(JsonToken.TokenType.NameSeperator, actual.Type); actual = target.GetNextToken(); Assert.AreEqual(JsonToken.TokenType.String, actual.Type); Assert.AreEqual("Value", actual.Value); actual = target.GetNextToken(); Assert.AreEqual(JsonToken.TokenType.ObjectEnd, actual.Type); } /// <summary> /// A test for GetNextToken ///</summary> [Test] public void GetNextTokenTestSpecialValues() { TokenStream target = new TokenStream("[ true, \"Value2\", false, null ]"); JsonToken actual; actual = target.GetNextToken(); Assert.AreEqual(JsonToken.TokenType.ArrayStart, actual.Type); actual = target.GetNextToken(); Assert.AreEqual(JsonToken.TokenType.True, actual.Type); actual = target.GetNextToken(); Assert.AreEqual(JsonToken.TokenType.MemberSeperator, actual.Type); actual = target.GetNextToken(); Assert.AreEqual(JsonToken.TokenType.String, actual.Type); Assert.AreEqual("Value2", actual.Value); actual = target.GetNextToken(); Assert.AreEqual(JsonToken.TokenType.MemberSeperator, actual.Type); actual = target.GetNextToken(); Assert.AreEqual(JsonToken.TokenType.False, actual.Type); actual = target.GetNextToken(); Assert.AreEqual(JsonToken.TokenType.MemberSeperator, actual.Type); actual = target.GetNextToken(); Assert.AreEqual(JsonToken.TokenType.Null, actual.Type); actual = target.GetNextToken(); Assert.AreEqual(JsonToken.TokenType.ArrayEnd, actual.Type); actual = target.GetNextToken(); Assert.AreEqual(null, actual); } } }
using CrystalDecisions.CrystalReports.Engine; using CrystalDecisions.Windows.Forms; using DpSdkEngLib; using DPSDKOPSLib; using Microsoft.VisualBasic; using System; using System.Collections; using System.Collections.Generic; using System.Drawing; using System.Diagnostics; using System.Windows.Forms; using System.Linq; using System.Xml.Linq; namespace _4PosBackOffice.NET { [Microsoft.VisualBasic.CompilerServices.DesignerGenerated()] partial class frmPersonFPVerify { #region "Windows Form Designer generated code " [System.Diagnostics.DebuggerNonUserCode()] public frmPersonFPVerify() : base() { FormClosed += frmPersonFPVerify_FormClosed; Load += frmPersonFPVerify_Load; //This call is required by the Windows Form Designer. InitializeComponent(); } //Form overrides dispose to clean up the component list. [System.Diagnostics.DebuggerNonUserCode()] protected override void Dispose(bool Disposing) { if (Disposing) { if ((components != null)) { components.Dispose(); } } base.Dispose(Disposing); } //Required by the Windows Form Designer private System.ComponentModel.IContainer components; public System.Windows.Forms.ToolTip ToolTip1; private System.Windows.Forms.Button withEventsField_cmdExit; public System.Windows.Forms.Button cmdExit { get { return withEventsField_cmdExit; } set { if (withEventsField_cmdExit != null) { withEventsField_cmdExit.Click -= cmdExit_Click; } withEventsField_cmdExit = value; if (withEventsField_cmdExit != null) { withEventsField_cmdExit.Click += cmdExit_Click; } } } public System.Windows.Forms.Panel picButtons; public System.Windows.Forms.TextBox eName; private System.Windows.Forms.Button withEventsField_Command1; public System.Windows.Forms.Button Command1 { get { return withEventsField_Command1; } set { if (withEventsField_Command1 != null) { withEventsField_Command1.Click -= Command1_Click; } withEventsField_Command1 = value; if (withEventsField_Command1 != null) { withEventsField_Command1.Click += Command1_Click; } } } public System.Windows.Forms.PictureBox Picture1; public System.Windows.Forms.Label label2; public System.Windows.Forms.Label Label1; //NOTE: The following procedure is required by the Windows Form Designer //It can be modified using the Windows Form Designer. //Do not modify it using the code editor. [System.Diagnostics.DebuggerStepThrough()] private void InitializeComponent() { System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(frmPersonFPVerify)); this.components = new System.ComponentModel.Container(); this.ToolTip1 = new System.Windows.Forms.ToolTip(components); this.picButtons = new System.Windows.Forms.Panel(); this.cmdExit = new System.Windows.Forms.Button(); this.eName = new System.Windows.Forms.TextBox(); this.Command1 = new System.Windows.Forms.Button(); this.Picture1 = new System.Windows.Forms.PictureBox(); this.label2 = new System.Windows.Forms.Label(); this.Label1 = new System.Windows.Forms.Label(); this.picButtons.SuspendLayout(); this.SuspendLayout(); this.ToolTip1.Active = true; this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.Text = "Verify Form"; this.ClientSize = new System.Drawing.Size(271, 251); this.Location = new System.Drawing.Point(3, 22); this.ControlBox = false; this.KeyPreview = true; this.MaximizeBox = false; this.MinimizeBox = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackColor = System.Drawing.SystemColors.Control; this.Enabled = true; this.Cursor = System.Windows.Forms.Cursors.Default; this.RightToLeft = System.Windows.Forms.RightToLeft.No; this.ShowInTaskbar = true; this.HelpButton = false; this.WindowState = System.Windows.Forms.FormWindowState.Normal; this.Name = "frmPersonFPVerify"; this.picButtons.Dock = System.Windows.Forms.DockStyle.Top; this.picButtons.BackColor = System.Drawing.Color.Blue; this.picButtons.Size = new System.Drawing.Size(271, 39); this.picButtons.Location = new System.Drawing.Point(0, 0); this.picButtons.TabIndex = 5; this.picButtons.TabStop = false; this.picButtons.CausesValidation = true; this.picButtons.Enabled = true; this.picButtons.ForeColor = System.Drawing.SystemColors.ControlText; this.picButtons.Cursor = System.Windows.Forms.Cursors.Default; this.picButtons.RightToLeft = System.Windows.Forms.RightToLeft.No; this.picButtons.Visible = true; this.picButtons.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.picButtons.Name = "picButtons"; this.cmdExit.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.cmdExit.Text = "E&xit"; this.cmdExit.Size = new System.Drawing.Size(73, 29); this.cmdExit.Location = new System.Drawing.Point(184, 3); this.cmdExit.TabIndex = 6; this.cmdExit.TabStop = false; this.cmdExit.BackColor = System.Drawing.SystemColors.Control; this.cmdExit.CausesValidation = true; this.cmdExit.Enabled = true; this.cmdExit.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdExit.Cursor = System.Windows.Forms.Cursors.Default; this.cmdExit.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdExit.Name = "cmdExit"; this.eName.AutoSize = false; this.eName.BackColor = System.Drawing.Color.Blue; this.eName.ForeColor = System.Drawing.Color.White; this.eName.Size = new System.Drawing.Size(257, 17); this.eName.Location = new System.Drawing.Point(8, 48); this.eName.ReadOnly = true; this.eName.TabIndex = 4; this.eName.Text = "name"; this.eName.AcceptsReturn = true; this.eName.TextAlign = System.Windows.Forms.HorizontalAlignment.Left; this.eName.CausesValidation = true; this.eName.Enabled = true; this.eName.HideSelection = true; this.eName.MaxLength = 0; this.eName.Cursor = System.Windows.Forms.Cursors.IBeam; this.eName.Multiline = false; this.eName.RightToLeft = System.Windows.Forms.RightToLeft.No; this.eName.ScrollBars = System.Windows.Forms.ScrollBars.None; this.eName.TabStop = true; this.eName.Visible = true; this.eName.BorderStyle = System.Windows.Forms.BorderStyle.None; this.eName.Name = "eName"; this.Command1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.Command1.Text = "Verify Again ?"; this.Command1.Size = new System.Drawing.Size(113, 41); this.Command1.Location = new System.Drawing.Point(152, 200); this.Command1.TabIndex = 1; this.Command1.BackColor = System.Drawing.SystemColors.Control; this.Command1.CausesValidation = true; this.Command1.Enabled = true; this.Command1.ForeColor = System.Drawing.SystemColors.ControlText; this.Command1.Cursor = System.Windows.Forms.Cursors.Default; this.Command1.RightToLeft = System.Windows.Forms.RightToLeft.No; this.Command1.TabStop = true; this.Command1.Name = "Command1"; this.Picture1.Size = new System.Drawing.Size(129, 161); this.Picture1.Location = new System.Drawing.Point(8, 80); this.Picture1.TabIndex = 0; this.Picture1.Dock = System.Windows.Forms.DockStyle.None; this.Picture1.BackColor = System.Drawing.SystemColors.Control; this.Picture1.CausesValidation = true; this.Picture1.Enabled = true; this.Picture1.ForeColor = System.Drawing.SystemColors.ControlText; this.Picture1.Cursor = System.Windows.Forms.Cursors.Default; this.Picture1.RightToLeft = System.Windows.Forms.RightToLeft.No; this.Picture1.TabStop = true; this.Picture1.Visible = true; this.Picture1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Normal; this.Picture1.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.Picture1.Name = "Picture1"; this.label2.Text = "Name"; this.label2.Size = new System.Drawing.Size(41, 17); this.label2.Location = new System.Drawing.Point(80, 160); this.label2.TabIndex = 3; this.label2.TextAlign = System.Drawing.ContentAlignment.TopLeft; this.label2.BackColor = System.Drawing.SystemColors.Control; this.label2.Enabled = true; this.label2.ForeColor = System.Drawing.SystemColors.ControlText; this.label2.Cursor = System.Windows.Forms.Cursors.Default; this.label2.RightToLeft = System.Windows.Forms.RightToLeft.No; this.label2.UseMnemonic = true; this.label2.Visible = true; this.label2.AutoSize = false; this.label2.BorderStyle = System.Windows.Forms.BorderStyle.None; this.label2.Name = "label2"; this.Label1.Text = "Please put your finger on the sensor ..."; this.Label1.ForeColor = System.Drawing.Color.Red; this.Label1.Size = new System.Drawing.Size(105, 105); this.Label1.Location = new System.Drawing.Point(152, 80); this.Label1.TabIndex = 2; this.Label1.TextAlign = System.Drawing.ContentAlignment.TopLeft; this.Label1.BackColor = System.Drawing.SystemColors.Control; this.Label1.Enabled = true; this.Label1.Cursor = System.Windows.Forms.Cursors.Default; this.Label1.RightToLeft = System.Windows.Forms.RightToLeft.No; this.Label1.UseMnemonic = true; this.Label1.Visible = true; this.Label1.AutoSize = false; this.Label1.BorderStyle = System.Windows.Forms.BorderStyle.None; this.Label1.Name = "Label1"; this.Controls.Add(picButtons); this.Controls.Add(eName); this.Controls.Add(Command1); this.Controls.Add(Picture1); this.Controls.Add(label2); this.Controls.Add(Label1); this.picButtons.Controls.Add(cmdExit); this.picButtons.ResumeLayout(false); this.ResumeLayout(false); this.PerformLayout(); } #endregion } }
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ namespace TestCases.SS.Util { using NPOI.SS.UserModel; using NPOI.SS.Util; using NUnit.Framework; using System; using System.Collections.Generic; using TestCases.SS; public abstract class BaseTestCellUtil { protected ITestDataProvider _testDataProvider; //public BaseTestCellUtil() // : this(HSSFITestDataProvider.Instance) //{ //} protected BaseTestCellUtil(ITestDataProvider testDataProvider) { _testDataProvider = testDataProvider; } [Test] public void SetCellStyleProperty() { IWorkbook wb = _testDataProvider.CreateWorkbook(); ISheet s = wb.CreateSheet(); IRow r = s.CreateRow(0); ICell c = r.CreateCell(0); // Add a border should create a new style int styCnt1 = wb.NumCellStyles; CellUtil.SetCellStyleProperty(c, CellUtil.BORDER_BOTTOM, BorderStyle.Thin); int styCnt2 = wb.NumCellStyles; Assert.AreEqual(styCnt1 + 1, styCnt2); // Add same border to another cell, should not create another style c = r.CreateCell(1); CellUtil.SetCellStyleProperty(c, CellUtil.BORDER_BOTTOM, BorderStyle.Thin); int styCnt3 = wb.NumCellStyles; Assert.AreEqual(styCnt2, styCnt3); wb.Close(); } [Test]//(expected=RuntimeException.class) public void SetCellStylePropertyWithInvalidValue() { IWorkbook wb = _testDataProvider.CreateWorkbook(); ISheet s = wb.CreateSheet(); IRow r = s.CreateRow(0); ICell c = r.CreateCell(0); // An invalid BorderStyle constant CellUtil.SetCellStyleProperty(c, CellUtil.BORDER_BOTTOM, 42); wb.Close(); } [Test] public void SetCellStylePropertyBorderWithShortAndEnum() { IWorkbook wb = _testDataProvider.CreateWorkbook(); ISheet s = wb.CreateSheet(); IRow r = s.CreateRow(0); ICell c = r.CreateCell(0); // A valid BorderStyle constant, as a Short CellUtil.SetCellStyleProperty(c, CellUtil.BORDER_BOTTOM, (short)BorderStyle.DashDot); Assert.AreEqual(BorderStyle.DashDot, c.CellStyle.BorderBottom); // A valid BorderStyle constant, as an Enum CellUtil.SetCellStyleProperty(c, CellUtil.BORDER_TOP, BorderStyle.MediumDashDot); Assert.AreEqual(BorderStyle.MediumDashDot, c.CellStyle.BorderTop); wb.Close(); } [Test] public void SetCellStyleProperties() { IWorkbook wb = _testDataProvider.CreateWorkbook(); ISheet s = wb.CreateSheet(); IRow r = s.CreateRow(0); ICell c = r.CreateCell(0); // Add multiple border properties to cell should create a single new style int styCnt1 = wb.NumCellStyles; Dictionary<String, Object> props = new Dictionary<String, Object>(); props.Add(CellUtil.BORDER_TOP, BorderStyle.Thin); props.Add(CellUtil.BORDER_BOTTOM, BorderStyle.Thin); props.Add(CellUtil.BORDER_LEFT, BorderStyle.Thin); props.Add(CellUtil.BORDER_RIGHT, BorderStyle.Thin); props.Add(CellUtil.ALIGNMENT, HorizontalAlignment.Center); // try it both with a Short (deprecated) props.Add(CellUtil.VERTICAL_ALIGNMENT, VerticalAlignment.Center); // and with an enum CellUtil.SetCellStyleProperties(c, props); int styCnt2 = wb.NumCellStyles; Assert.AreEqual(styCnt1 + 1, styCnt2, "Only one additional style should have been created"); // Add same border another to same cell, should not create another style c = r.CreateCell(1); CellUtil.SetCellStyleProperties(c, props); int styCnt3 = wb.NumCellStyles; Assert.AreEqual(styCnt3, styCnt2, "No additional styles should have been created"); wb.Close(); } [Test] public void GetRow() { IWorkbook wb = _testDataProvider.CreateWorkbook(); ISheet sh = wb.CreateSheet(); IRow row1 = sh.CreateRow(0); // Get row that already exists IRow r1 = CellUtil.GetRow(0, sh); Assert.IsNotNull(r1); Assert.AreSame(row1, r1, "An existing row should not be reCreated"); // Get row that does not exist yet Assert.IsNotNull(CellUtil.GetRow(1, sh)); wb.Close(); } [Test] public void GetCell() { IWorkbook wb = _testDataProvider.CreateWorkbook(); ISheet sh = wb.CreateSheet(); IRow row = sh.CreateRow(0); ICell A1 = row.CreateCell(0); // Get cell that already exists ICell a1 = CellUtil.GetCell(row, 0); Assert.IsNotNull(a1); Assert.AreSame(A1, a1, "An existing cell should not be reCreated"); // Get cell that does not exist yet Assert.IsNotNull(CellUtil.GetCell(row, 1)); wb.Close(); } [Test] public void CreateCell() { IWorkbook wb = _testDataProvider.CreateWorkbook(); ISheet sh = wb.CreateSheet(); IRow row = sh.CreateRow(0); ICellStyle style = wb.CreateCellStyle(); style.WrapText = (/*setter*/true); // calling CreateCell on a non-existing cell should create a cell and Set the cell value and style. ICell F1 = CellUtil.CreateCell(row, 5, "Cell Value", style); Assert.AreSame(row.GetCell(5), F1); Assert.AreEqual("Cell Value", F1.StringCellValue); Assert.AreEqual(style, F1.CellStyle); // should be Assert.AreSame, but a new HSSFCellStyle is returned for each GetCellStyle() call. // HSSFCellStyle wraps an underlying style record, and the underlying // style record is the same between multiple GetCellStyle() calls. // calling CreateCell on an existing cell should return the existing cell and modify the cell value and style. ICell f1 = CellUtil.CreateCell(row, 5, "Overwritten cell value", null); Assert.AreSame(row.GetCell(5), f1); Assert.AreSame(F1, f1); Assert.AreEqual("Overwritten cell value", f1.StringCellValue); Assert.AreEqual("Overwritten cell value", F1.StringCellValue); Assert.AreEqual(style, f1.CellStyle, "cell style should be unChanged with CreateCell(..., null)"); Assert.AreEqual(style, F1.CellStyle, "cell style should be unChanged with CreateCell(..., null)"); // test CreateCell(row, column, value) (no CellStyle) f1 = CellUtil.CreateCell(row, 5, "Overwritten cell with default style"); Assert.AreSame(F1, f1); wb.Close(); } [Test] public void SetAlignmentEnum() { IWorkbook wb = _testDataProvider.CreateWorkbook(); ISheet sh = wb.CreateSheet(); IRow row = sh.CreateRow(0); ICell A1 = row.CreateCell(0); ICell B1 = row.CreateCell(1); // Assumptions Assert.AreEqual(A1.CellStyle, B1.CellStyle); // should be assertSame, but a new HSSFCellStyle is returned for each getCellStyle() call. // HSSFCellStyle wraps an underlying style record, and the underlying // style record is the same between multiple getCellStyle() calls. Assert.AreEqual(HorizontalAlignment.General, A1.CellStyle.Alignment); Assert.AreEqual(HorizontalAlignment.General, B1.CellStyle.Alignment); // get/set alignment modifies the cell's style CellUtil.SetAlignment(A1, HorizontalAlignment.Right); Assert.AreEqual(HorizontalAlignment.Right, A1.CellStyle.Alignment); // get/set alignment doesn't affect the style of cells with // the same style prior to modifying the style Assert.AreNotEqual(A1.CellStyle, B1.CellStyle); Assert.AreEqual(HorizontalAlignment.General, B1.CellStyle.Alignment); wb.Close(); } [Test] public void SetVerticalAlignmentEnum() { IWorkbook wb = _testDataProvider.CreateWorkbook(); ISheet sh = wb.CreateSheet(); IRow row = sh.CreateRow(0); ICell A1 = row.CreateCell(0); ICell B1 = row.CreateCell(1); // Assumptions Assert.AreEqual(A1.CellStyle, B1.CellStyle); // should be assertSame, but a new HSSFCellStyle is returned for each getCellStyle() call. // HSSFCellStyle wraps an underlying style record, and the underlying // style record is the same between multiple getCellStyle() calls. Assert.AreEqual(VerticalAlignment.Bottom, A1.CellStyle.VerticalAlignment); Assert.AreEqual(VerticalAlignment.Bottom, B1.CellStyle.VerticalAlignment); // get/set alignment modifies the cell's style CellUtil.SetVerticalAlignment(A1, VerticalAlignment.Top); Assert.AreEqual(VerticalAlignment.Top, A1.CellStyle.VerticalAlignment); // get/set alignment doesn't affect the style of cells with // the same style prior to modifying the style Assert.AreNotEqual(A1.CellStyle, B1.CellStyle); Assert.AreEqual(VerticalAlignment.Bottom, B1.CellStyle.VerticalAlignment); wb.Close(); } [Test] public void SetFont() { IWorkbook wb = _testDataProvider.CreateWorkbook(); ISheet sh = wb.CreateSheet(); IRow row = sh.CreateRow(0); ICell A1 = row.CreateCell(0); ICell B1 = row.CreateCell(1); short defaultFontIndex = 0; IFont font = wb.CreateFont(); font.IsItalic = true; short customFontIndex = font.Index; // Assumptions Assert.AreNotEqual(defaultFontIndex, customFontIndex); Assert.AreEqual(A1.CellStyle, B1.CellStyle); // should be Assert.AreSame, but a new HSSFCellStyle is returned for each GetCellStyle() call. // HSSFCellStyle wraps an underlying style record, and the underlying // style record is the same between multiple GetCellStyle() calls. Assert.AreEqual(defaultFontIndex, A1.CellStyle.FontIndex); Assert.AreEqual(defaultFontIndex, B1.CellStyle.FontIndex); // Get/set alignment modifies the cell's style CellUtil.SetFont(A1, font); Assert.AreEqual(customFontIndex, A1.CellStyle.FontIndex); // Get/set alignment doesn't affect the style of cells with // the same style prior to modifying the style Assert.AreNotEqual(A1.CellStyle, B1.CellStyle); Assert.AreEqual(defaultFontIndex, B1.CellStyle.FontIndex); wb.Close(); } [Test] public void SetFontFromDifferentWorkbook() { IWorkbook wb1 = _testDataProvider.CreateWorkbook(); IWorkbook wb2 = _testDataProvider.CreateWorkbook(); IFont font1 = wb1.CreateFont(); IFont font2 = wb2.CreateFont(); // do something to make font1 and font2 different // so they are not same or Equal. font1.IsItalic = true; ICell A1 = wb1.CreateSheet().CreateRow(0).CreateCell(0); // okay CellUtil.SetFont(A1, font1); // font belongs to different workbook try { CellUtil.SetFont(A1, font2); Assert.Fail("setFont not allowed if font belongs to a different workbook"); } catch (ArgumentException e) { if (e.Message.StartsWith("Font does not belong to this workbook")) { // expected } else { throw e; } } finally { wb1.Close(); wb2.Close(); } } /** * bug 55555 * @since POI 3.15 beta 3 */ [Test] public void SetFillForegroundColorBeforeFillBackgroundColorEnum() { IWorkbook wb1 = _testDataProvider.CreateWorkbook(); ICell A1 = wb1.CreateSheet().CreateRow(0).CreateCell(0); Dictionary<String, Object> properties = new Dictionary<String, Object>(); // FIXME: Use FillPattern.BRICKS enum properties.Add(CellUtil.FILL_PATTERN, FillPattern.Bricks); properties.Add(CellUtil.FILL_FOREGROUND_COLOR, IndexedColors.Blue.Index); properties.Add(CellUtil.FILL_BACKGROUND_COLOR, IndexedColors.Red.Index); CellUtil.SetCellStyleProperties(A1, properties); ICellStyle style = A1.CellStyle; // FIXME: Use FillPattern.BRICKS enum Assert.AreEqual(FillPattern.Bricks, style.FillPattern, "fill pattern"); Assert.AreEqual(IndexedColors.Blue, IndexedColors.FromInt(style.FillForegroundColor), "fill foreground color"); Assert.AreEqual(IndexedColors.Red, IndexedColors.FromInt(style.FillBackgroundColor), "fill background color"); } } }
using System; using System.Collections; using System.Runtime.InteropServices; using WbemClient_v1; using System.Diagnostics; using System.ComponentModel; using System.Threading; namespace System.Management { /// <summary> /// <para>Represents the method that will handle the <see cref='E:System.Management.ManagementEventWatcher.EventArrived'/> event.</para> /// </summary> public delegate void EventArrivedEventHandler(object sender, EventArrivedEventArgs e); /// <summary> /// <para>Represents the method that will handle the <see cref='E:System.Management.ManagementEventWatcher.Stopped'/> event.</para> /// </summary> public delegate void StoppedEventHandler (object sender, StoppedEventArgs e); //CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC// /// <summary> /// <para> Subscribes to temporary event notifications /// based on a specified event query.</para> /// </summary> /// <example> /// <code lang='C#'>using System; /// using System.Management; /// /// // This example demonstrates how to subscribe to an event using the ManagementEventWatcher object. /// class Sample_ManagementEventWatcher /// { /// public static int Main(string[] args) { /// /// //For the example, we'll put a class into the repository, and watch /// //for class deletion events when the class is deleted. /// ManagementClass newClass = new ManagementClass(); /// newClass["__CLASS"] = "TestDeletionClass"; /// newClass.Put(); /// /// //Set up an event watcher and a handler for the event /// ManagementEventWatcher watcher = new ManagementEventWatcher( /// new WqlEventQuery("__ClassDeletionEvent")); /// MyHandler handler = new MyHandler(); /// watcher.EventArrived += new EventArrivedEventHandler(handler.Arrived); /// /// //Start watching for events /// watcher.Start(); /// /// // For the purpose of this sample, we delete the class to trigger the event /// // and wait for two seconds before terminating the consumer /// newClass.Delete(); /// /// System.Threading.Thread.Sleep(2000); /// /// //Stop watching /// watcher.Stop(); /// /// return 0; /// } /// /// public class MyHandler { /// public void Arrived(object sender, EventArrivedEventArgs e) { /// Console.WriteLine("Class Deleted = " + /// ((ManagementBaseObject)e.NewEvent["TargetClass"])["__CLASS"]); /// } /// } /// } /// </code> /// <code lang='VB'>Imports System /// Imports System.Management /// /// ' This example demonstrates how to subscribe an event using the ManagementEventWatcher object. /// Class Sample_ManagementEventWatcher /// Public Shared Sub Main() /// /// ' For the example, we'll put a class into the repository, and watch /// ' for class deletion events when the class is deleted. /// Dim newClass As New ManagementClass() /// newClass("__CLASS") = "TestDeletionClass" /// newClass.Put() /// /// ' Set up an event watcher and a handler for the event /// Dim watcher As _ /// New ManagementEventWatcher(New WqlEventQuery("__ClassDeletionEvent")) /// Dim handler As New MyHandler() /// AddHandler watcher.EventArrived, AddressOf handler.Arrived /// /// ' Start watching for events /// watcher.Start() /// /// ' For the purpose of this sample, we delete the class to trigger the event /// ' and wait for two seconds before terminating the consumer /// newClass.Delete() /// /// System.Threading.Thread.Sleep(2000) /// /// ' Stop watching /// watcher.Stop() /// /// End Sub /// /// Public Class MyHandler /// Public Sub Arrived(sender As Object, e As EventArrivedEventArgs) /// Console.WriteLine("Class Deleted = " &amp; _ /// CType(e.NewEvent("TargetClass"), ManagementBaseObject)("__CLASS")) /// End Sub /// End Class /// End Class /// </code> /// </example> //CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC// [ToolboxItem(false)] public class ManagementEventWatcher : Component { //fields private ManagementScope scope; private EventQuery query; private EventWatcherOptions options; private IEnumWbemClassObject enumWbem; private IWbemClassObjectFreeThreaded[] cachedObjects; //points to objects currently available in cache private uint cachedCount; //says how many objects are in the cache (when using BlockSize option) private uint cacheIndex; //used to walk the cache private SinkForEventQuery sink; // the sink implementation for event queries private WmiDelegateInvoker delegateInvoker; //Called when IdentifierChanged() event fires private void HandleIdentifierChange(object sender, IdentifierChangedEventArgs e) { // Invalidate any [....] or async call in progress Stop(); } //default constructor /// <overload> /// Initializes a new instance of the <see cref='System.Management.ManagementEventWatcher'/> class. /// </overload> /// <summary> /// <para> Initializes a new instance of the <see cref='System.Management.ManagementEventWatcher'/> class. For further /// initialization, set the properties on the object. This is the default constructor.</para> /// </summary> public ManagementEventWatcher() : this((ManagementScope)null, null, null) {} //parameterized constructors /// <summary> /// <para>Initializes a new instance of the <see cref='System.Management.ManagementEventWatcher'/> class when given a WMI event query.</para> /// </summary> /// <param name='query'>An <see cref='System.Management.EventQuery'/> object representing a WMI event query, which determines the events for which the watcher will listen.</param> /// <remarks> /// <para>The namespace in which the watcher will be listening for /// events is the default namespace that is currently set.</para> /// </remarks> public ManagementEventWatcher ( EventQuery query) : this(null, query, null) {} /// <summary> /// <para>Initializes a new instance of the <see cref='System.Management.ManagementEventWatcher'/> class when given a WMI event query in the /// form of a string.</para> /// </summary> /// <param name='query'> A WMI event query, which defines the events for which the watcher will listen.</param> /// <remarks> /// <para>The namespace in which the watcher will be listening for /// events is the default namespace that is currently set.</para> /// </remarks> public ManagementEventWatcher ( string query) : this(null, new EventQuery(query), null) {} /// <summary> /// <para> Initializes a new instance of the <see cref='System.Management.ManagementEventWatcher'/> /// class that listens for events conforming to the given WMI event query.</para> /// </summary> /// <param name='scope'>A <see cref='System.Management.ManagementScope'/> object representing the scope (namespace) in which the watcher will listen for events.</param> /// <param name=' query'>An <see cref='System.Management.EventQuery'/> object representing a WMI event query, which determines the events for which the watcher will listen.</param> public ManagementEventWatcher( ManagementScope scope, EventQuery query) : this(scope, query, null) {} /// <summary> /// <para> Initializes a new instance of the <see cref='System.Management.ManagementEventWatcher'/> /// class that listens for events conforming to the given WMI event query. For this /// variant, the query and the scope are specified as strings.</para> /// </summary> /// <param name='scope'> The management scope (namespace) in which the watcher will listen for events.</param> /// <param name=' query'> The query that defines the events for which the watcher will listen.</param> public ManagementEventWatcher( string scope, string query) : this(new ManagementScope(scope), new EventQuery(query), null) {} /// <summary> /// <para> Initializes a new instance of the <see cref='System.Management.ManagementEventWatcher'/> class that listens for /// events conforming to the given WMI event query, according to the specified options. For /// this variant, the query and the scope are specified as strings. The options /// object can specify options such as a timeout and context information.</para> /// </summary> /// <param name='scope'>The management scope (namespace) in which the watcher will listen for events.</param> /// <param name=' query'>The query that defines the events for which the watcher will listen.</param> /// <param name='options'>An <see cref='System.Management.EventWatcherOptions'/> object representing additional options used to watch for events. </param> public ManagementEventWatcher( string scope, string query, EventWatcherOptions options) : this(new ManagementScope(scope), new EventQuery(query), options) {} /// <summary> /// <para> Initializes a new instance of the <see cref='System.Management.ManagementEventWatcher'/> class /// that listens for events conforming to the given WMI event query, according to the specified /// options. For this variant, the query and the scope are specified objects. The /// options object can specify options such as timeout and context information.</para> /// </summary> /// <param name='scope'>A <see cref='System.Management.ManagementScope'/> object representing the scope (namespace) in which the watcher will listen for events.</param> /// <param name=' query'>An <see cref='System.Management.EventQuery'/> object representing a WMI event query, which determines the events for which the watcher will listen.</param> /// <param name='options'>An <see cref='System.Management.EventWatcherOptions'/> object representing additional options used to watch for events. </param> public ManagementEventWatcher( ManagementScope scope, EventQuery query, EventWatcherOptions options) { if (null != scope) this.scope = ManagementScope._Clone(scope, new IdentifierChangedEventHandler(HandleIdentifierChange)); else this.scope = ManagementScope._Clone(null, new IdentifierChangedEventHandler(HandleIdentifierChange)); if (null != query) this.query = (EventQuery)query.Clone(); else this.query = new EventQuery(); this.query.IdentifierChanged += new IdentifierChangedEventHandler(HandleIdentifierChange); if (null != options) this.options = (EventWatcherOptions)options.Clone(); else this.options = new EventWatcherOptions(); this.options.IdentifierChanged += new IdentifierChangedEventHandler(HandleIdentifierChange); enumWbem = null; cachedCount = 0; cacheIndex = 0; sink = null; delegateInvoker = new WmiDelegateInvoker (this); } /// <summary> /// <para>Ensures that outstanding calls are cleared. This is the destructor for the object.</para> /// </summary> ~ManagementEventWatcher () { // Ensure any outstanding calls are cleared Stop (); if (null != scope) scope.IdentifierChanged -= new IdentifierChangedEventHandler (HandleIdentifierChange); if (null != options) options.IdentifierChanged -= new IdentifierChangedEventHandler (HandleIdentifierChange); if (null != query) query.IdentifierChanged -= new IdentifierChangedEventHandler (HandleIdentifierChange); } // // Events // /// <summary> /// <para> Occurs when a new event arrives.</para> /// </summary> public event EventArrivedEventHandler EventArrived; /// <summary> /// <para> Occurs when a subscription is canceled.</para> /// </summary> public event StoppedEventHandler Stopped; // //Public Properties // /// <summary> /// <para>Gets or sets the scope in which to watch for events (namespace or scope).</para> /// </summary> /// <value> /// <para> The scope in which to watch for events (namespace or scope).</para> /// </value> public ManagementScope Scope { get { return scope; } set { if (null != value) { ManagementScope oldScope = scope; scope = (ManagementScope)value.Clone (); // Unregister ourselves from the previous scope object if (null != oldScope) oldScope.IdentifierChanged -= new IdentifierChangedEventHandler(HandleIdentifierChange); //register for change events in this object scope.IdentifierChanged += new IdentifierChangedEventHandler(HandleIdentifierChange); //the scope property has changed so act like we fired the event HandleIdentifierChange(this, null); } else throw new ArgumentNullException("value"); } } /// <summary> /// <para>Gets or sets the criteria to apply to events.</para> /// </summary> /// <value> /// <para> The criteria to apply to the events, which is equal to the event query.</para> /// </value> public EventQuery Query { get { return query; } set { if (null != value) { ManagementQuery oldQuery = query; query = (EventQuery)value.Clone (); // Unregister ourselves from the previous query object if (null != oldQuery) oldQuery.IdentifierChanged -= new IdentifierChangedEventHandler(HandleIdentifierChange); //register for change events in this object query.IdentifierChanged += new IdentifierChangedEventHandler(HandleIdentifierChange); //the query property has changed so act like we fired the event HandleIdentifierChange(this, null); } else throw new ArgumentNullException("value"); } } /// <summary> /// <para>Gets or sets the options used to watch for events.</para> /// </summary> /// <value> /// <para>The options used to watch for events.</para> /// </value> public EventWatcherOptions Options { get { return options; } set { if (null != value) { EventWatcherOptions oldOptions = options; options = (EventWatcherOptions)value.Clone (); // Unregister ourselves from the previous scope object if (null != oldOptions) oldOptions.IdentifierChanged -= new IdentifierChangedEventHandler(HandleIdentifierChange); cachedObjects = new IWbemClassObjectFreeThreaded[options.BlockSize]; //register for change events in this object options.IdentifierChanged += new IdentifierChangedEventHandler(HandleIdentifierChange); //the options property has changed so act like we fired the event HandleIdentifierChange(this, null); } else throw new ArgumentNullException("value"); } } /// <summary> /// <para>Waits for the next event that matches the specified query to arrive, and /// then returns it.</para> /// </summary> /// <returns> /// <para>A <see cref='System.Management.ManagementBaseObject'/> representing the /// newly arrived event.</para> /// </returns> /// <remarks> /// <para>If the event watcher object contains options with /// a specified timeout, the API will wait for the next event only for the specified /// amount of time; otherwise, the API will be blocked until the next event occurs.</para> /// </remarks> public ManagementBaseObject WaitForNextEvent() { ManagementBaseObject obj = null; Initialize (); lock(this) { SecurityHandler securityHandler = Scope.GetSecurityHandler(); int status = (int)ManagementStatus.NoError; try { if (null == enumWbem) //don't have an enumerator yet - get it { //Execute the query status = scope.GetSecuredIWbemServicesHandler( Scope.GetIWbemServices() ).ExecNotificationQuery_( query.QueryLanguage, query.QueryString, options.Flags, options.GetContext (), ref enumWbem); } if (status >= 0) { if ((cachedCount - cacheIndex) == 0) //cache is empty - need to get more objects { #if true //Because Interop doesn't support custom marshalling for arrays, we have to use //the "DoNotMarshal" objects in the interop and then convert to the "FreeThreaded" //counterparts afterwards. IWbemClassObject_DoNotMarshal[] tempArray = new IWbemClassObject_DoNotMarshal[options.BlockSize]; int timeout = (ManagementOptions.InfiniteTimeout == options.Timeout) ? (int) tag_WBEM_TIMEOUT_TYPE.WBEM_INFINITE : (int) options.Timeout.TotalMilliseconds; status = scope.GetSecuredIEnumWbemClassObjectHandler(enumWbem).Next_(timeout, (uint)options.BlockSize, tempArray, ref cachedCount); cacheIndex = 0; if (status >= 0) { //Convert results and put them in cache. Note that we may have timed out //in which case we might not have all the objects. If no object can be returned //we throw a timeout exception... - if (cachedCount == 0) ManagementException.ThrowWithExtendedInfo(ManagementStatus.Timedout); for (int i = 0; i < cachedCount; i++) cachedObjects[i] = new IWbemClassObjectFreeThreaded(Marshal.GetIUnknownForObject(tempArray[i])); } #else //This was workaround when using TLBIMP we couldn't pass in arrays... IWbemClassObjectFreeThreaded cachedObject = cachedObjects[0]; int timeout = (ManagementOptions.InfiniteTimeout == options.Timeout) ? (int) tag_WBEM_TIMEOUT_TYPE.WBEM_INFINITE : (int) options.Timeout.TotalMilliseconds; status = scope.GetSecuredIEnumWbemClassObjectHandler(enumWbem).Next_(timeout, 1, out cachedObjects, out cachedCount); cacheIndex = 0; if (status >= 0) { //Create ManagementObject for result. Note that we may have timed out //in which case we won't have an object if (null == cachedObject) ManagementException.ThrowWithExtendedInfo(ManagementStatus.Timedout); cachedObjects[0] = cachedObject; } #endif } if (status >= 0) { obj = new ManagementBaseObject(cachedObjects[cacheIndex]); cacheIndex++; } } } finally { securityHandler.Reset(); } if (status < 0) { if ((status & 0xfffff000) == 0x80041000) ManagementException.ThrowWithExtendedInfo((ManagementStatus)status); else Marshal.ThrowExceptionForHR(status); } } return obj; } //******************************************** //Start //******************************************** /// <summary> /// <para>Subscribes to events with the given query and delivers /// them, asynchronously, through the <see cref='System.Management.ManagementEventWatcher.EventArrived'/> event.</para> /// </summary> public void Start() { Initialize (); // Cancel any current event query Stop (); // Submit a new query SecurityHandler securityHandler = Scope.GetSecurityHandler(); IWbemServices wbemServices = scope.GetIWbemServices(); try { sink = new SinkForEventQuery(this, options.Context, wbemServices); if (sink.Status < 0) { Marshal.ThrowExceptionForHR(sink.Status); } // For async event queries we should ensure 0 flags as this is // the only legal value int status = scope.GetSecuredIWbemServicesHandler(wbemServices).ExecNotificationQueryAsync_( query.QueryLanguage, query.QueryString, 0, options.GetContext(), sink.Stub); if (status < 0) { if (sink != null) { sink.ReleaseStub(); sink = null; } if ((status & 0xfffff000) == 0x80041000) ManagementException.ThrowWithExtendedInfo((ManagementStatus)status); else Marshal.ThrowExceptionForHR(status); } } finally { securityHandler.Reset(); } } //******************************************** //Stop //******************************************** /// <summary> /// <para>Cancels the subscription whether it is synchronous or asynchronous.</para> /// </summary> public void Stop() { //For semi-synchronous, release the WMI enumerator to cancel the subscription if (null != enumWbem) { Marshal.ReleaseComObject(enumWbem); enumWbem = null; FireStopped (new StoppedEventArgs (options.Context, (int)ManagementStatus.OperationCanceled)); } // In async mode cancel the call to the sink - this will // unwind the operation and cause a Stopped message if (null != sink) { sink.Cancel (); sink = null; } } private void Initialize () { //If the query is not set yet we can't do it if (null == query) throw new InvalidOperationException(); if (null == options) Options = new EventWatcherOptions (); //If we're not connected yet, this is the time to do it... lock (this) { if (null == scope) Scope = new ManagementScope (); if (null == cachedObjects) cachedObjects = new IWbemClassObjectFreeThreaded[options.BlockSize]; } lock (scope) { scope.Initialize (); } } internal void FireStopped (StoppedEventArgs args) { try { delegateInvoker.FireEventToDelegates (Stopped, args); } catch { } } internal void FireEventArrived (EventArrivedEventArgs args) { try { delegateInvoker.FireEventToDelegates (EventArrived, args); } catch { } } } internal class SinkForEventQuery : IWmiEventSource { private ManagementEventWatcher eventWatcher; private object context; private IWbemServices services; private IWbemObjectSink stub; // The secured IWbemObjectSink private int status; private bool isLocal; public int Status {get {return status;} set {status=value;}} public SinkForEventQuery (ManagementEventWatcher eventWatcher, object context, IWbemServices services) { this.services = services; this.context = context; this.eventWatcher = eventWatcher; this.status = 0; this.isLocal = false; // determine if the server is local, and if so don't create a real stub using unsecap if((0==String.Compare(eventWatcher.Scope.Path.Server, ".", StringComparison.OrdinalIgnoreCase)) || (0==String.Compare(eventWatcher.Scope.Path.Server, System.Environment.MachineName, StringComparison.OrdinalIgnoreCase))) { this.isLocal = true; } if(MTAHelper.IsNoContextMTA()) // Bug#110141 - Checking for MTA is not enough. We need to make sure we are not in a COM+ Context HackToCreateStubInMTA(this); else { // // [marioh, RAID: 111108] // Ensure we are able to trap exceptions from worker thread. // ThreadDispatch disp = new ThreadDispatch ( new ThreadDispatch.ThreadWorkerMethodWithParam ( HackToCreateStubInMTA ) ) ; disp.Parameter = this ; disp.Start ( ) ; // Thread thread = new Thread(new ThreadStart(HackToCreateStubInMTA)); // thread.ApartmentState = ApartmentState.MTA; // thread.Start(); // thread.Join(); } } void HackToCreateStubInMTA(object param) { SinkForEventQuery obj = (SinkForEventQuery) param ; object dmuxStub = null; obj.Status = WmiNetUtilsHelper.GetDemultiplexedStub_f (obj, obj.isLocal, out dmuxStub); obj.stub = (IWbemObjectSink) dmuxStub; } internal IWbemObjectSink Stub { get { return stub; } } public void Indicate(IntPtr pWbemClassObject) { Marshal.AddRef(pWbemClassObject); IWbemClassObjectFreeThreaded obj = new IWbemClassObjectFreeThreaded(pWbemClassObject); try { EventArrivedEventArgs args = new EventArrivedEventArgs(context, new ManagementBaseObject(obj)); eventWatcher.FireEventArrived(args); } catch { } } public void SetStatus ( int flags, int hResult, String message, IntPtr pErrObj) { #if TODO_ERROBJ_NEVER_USED IWbemClassObjectFreeThreaded errObj = null; if(pErrObj != IntPtr.Zero) { Marshal.AddRef(pErrObj); errObj = new IWbemClassObjectFreeThreaded(pErrObj); } #endif // try { // Fire Stopped event eventWatcher.FireStopped(new StoppedEventArgs(context, hResult)); //This handles cases in which WMI calls SetStatus to indicate a problem, for example //a queue overflow due to slow client processing. //Currently we just cancel the subscription in this case. // if ( hResult != (int)tag_WBEMSTATUS.WBEM_E_CALL_CANCELLED && hResult != (int)tag_WBEMSTATUS.WBEM_S_OPERATION_CANCELLED) ThreadPool.QueueUserWorkItem(new WaitCallback(Cancel2));// Cancel(); // } catch { } } // void Cancel2(object o) { // // Try catch the call to cancel. In this case the cancel is being done without the client // knowing about it so catching all exceptions is not a bad thing to do. If a client calls // Stop (which calls Cancel), they will still recieve any exceptions that may have occured. // try { Cancel(); } catch { } } internal void Cancel () { if (null != stub) { lock(this) { if (null != stub) { int status = services.CancelAsyncCall_(stub); // Release prior to throwing an exception. ReleaseStub(); if (status < 0) { if ((status & 0xfffff000) == 0x80041000) ManagementException.ThrowWithExtendedInfo((ManagementStatus)status); else Marshal.ThrowExceptionForHR(status); } } } } } internal void ReleaseStub () { if (null != stub) { lock(this) { /* * We force a release of the stub here so as to allow * unsecapp.exe to die as soon as possible. * however if it is local, unsecap won't be started */ if (null != stub) { try { System.Runtime.InteropServices.Marshal.ReleaseComObject(stub); stub = null; } catch { } } } } } } }
// // CTFontCollection.cs: Implements the managed CTFontCollection // // Authors: Mono Team // // Copyright 2010 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.Drawing; using System.Runtime.InteropServices; using MonoMac.ObjCRuntime; using MonoMac.Foundation; using MonoMac.CoreFoundation; using MonoMac.CoreGraphics; using CFIndex = System.Int32; namespace MonoMac.CoreText { [Since (3,2)] public static class CTFontCollectionOptionKey { public static readonly NSString RemoveDuplicates; static CTFontCollectionOptionKey () { var handle = Dlfcn.dlopen (Constants.CoreTextLibrary, 0); if (handle == IntPtr.Zero) return; try { RemoveDuplicates = Dlfcn.GetStringConstant (handle, "kCTFontCollectionRemoveDuplicatesOption"); } finally { Dlfcn.dlclose (handle); } } } [Since (3,2)] public class CTFontCollectionOptions { public CTFontCollectionOptions () : this (new NSMutableDictionary ()) { } public CTFontCollectionOptions (NSDictionary dictionary) { if (dictionary == null) throw new ArgumentNullException ("dictionary"); Dictionary = dictionary; } public NSDictionary Dictionary {get; private set;} public bool RemoveDuplicates { get { var v = Adapter.GetInt32Value (Dictionary, CTFontCollectionOptionKey.RemoveDuplicates); return v.HasValue ? v.Value != 0 : false; } set { var v = value ? (int?) 1 : null; Adapter.SetValue (Dictionary, CTFontCollectionOptionKey.RemoveDuplicates, v); } } } [Since (3,2)] public class CTFontCollection : INativeObject, IDisposable { internal IntPtr handle; internal CTFontCollection (IntPtr handle, bool owns) { if (handle == IntPtr.Zero) throw ConstructorError.ArgumentNull (this, "handle"); this.handle = handle; if (!owns) CFObject.CFRetain (handle); } ~CTFontCollection () { Dispose (false); } public void Dispose () { Dispose (true); GC.SuppressFinalize (this); } public IntPtr Handle { get { return handle; } } protected virtual void Dispose (bool disposing) { if (handle != IntPtr.Zero){ CFObject.CFRelease (handle); handle = IntPtr.Zero; } } #region Collection Creation [DllImport (Constants.CoreTextLibrary)] static extern IntPtr CTFontCollectionCreateFromAvailableFonts (IntPtr options); public CTFontCollection (CTFontCollectionOptions options) { handle = CTFontCollectionCreateFromAvailableFonts ( options == null ? IntPtr.Zero : options.Dictionary.Handle); if (handle == IntPtr.Zero) throw ConstructorError.Unknown (this); } [DllImport (Constants.CoreTextLibrary)] static extern IntPtr CTFontCollectionCreateWithFontDescriptors (IntPtr queryDescriptors, IntPtr options); public CTFontCollection (CTFontDescriptor[] queryDescriptors, CTFontCollectionOptions options) { using (var descriptors = queryDescriptors == null ? null : CFArray.FromNativeObjects (queryDescriptors)) handle = CTFontCollectionCreateWithFontDescriptors ( descriptors == null ? IntPtr.Zero : descriptors.Handle, options == null ? IntPtr.Zero : options.Dictionary.Handle); if (handle == IntPtr.Zero) throw ConstructorError.Unknown (this); } [DllImport (Constants.CoreTextLibrary)] static extern IntPtr CTFontCollectionCreateCopyWithFontDescriptors (IntPtr original, IntPtr queryDescriptors, IntPtr options); public CTFontCollection WithFontDescriptors (CTFontDescriptor[] queryDescriptors, CTFontCollectionOptions options) { IntPtr h; using (var descriptors = queryDescriptors == null ? null : CFArray.FromNativeObjects (queryDescriptors)) { h = CTFontCollectionCreateCopyWithFontDescriptors ( handle, descriptors == null ? IntPtr.Zero : descriptors.Handle, options == null ? IntPtr.Zero : options.Dictionary.Handle); } if (h == IntPtr.Zero) return null; return new CTFontCollection (h, true); } #endregion #region Retrieving Matching Descriptors [DllImport (Constants.CoreTextLibrary)] static extern IntPtr CTFontCollectionCreateMatchingFontDescriptors (IntPtr collection); public CTFontDescriptor[] GetMatchingFontDescriptors () { var cfArrayRef = CTFontCollectionCreateMatchingFontDescriptors (handle); if (cfArrayRef == IntPtr.Zero) return new CTFontDescriptor [0]; var matches = NSArray.ArrayFromHandle (cfArrayRef, fd => new CTFontDescriptor (fd, false)); CFObject.CFRelease (cfArrayRef); return matches; } [DllImport (Constants.CoreTextLibrary)] static extern IntPtr CTFontCollectionCreateMatchingFontDescriptorsSortedWithCallback ( IntPtr collection, CTFontCollectionSortDescriptorsCallback sortCallback, IntPtr refCon); delegate CFIndex CTFontCollectionSortDescriptorsCallback (IntPtr first, IntPtr second, IntPtr refCon); [MonoPInvokeCallback (typeof (CTFontCollectionSortDescriptorsCallback))] static int CompareDescriptors (IntPtr first, IntPtr second, IntPtr context) { GCHandle c = GCHandle.FromIntPtr (context); var comparer = c.Target as Comparison<CTFontDescriptor>; if (comparer == null) return 0; return comparer (new CTFontDescriptor (first, false), new CTFontDescriptor (second, false)); } public CTFontDescriptor[] GetMatchingFontDescriptors (Comparison<CTFontDescriptor> comparer) { GCHandle comparison = GCHandle.Alloc (comparer); try { var cfArrayRef = CTFontCollectionCreateMatchingFontDescriptorsSortedWithCallback ( handle, new CTFontCollectionSortDescriptorsCallback (CompareDescriptors), GCHandle.ToIntPtr (comparison)); if (cfArrayRef == IntPtr.Zero) return new CTFontDescriptor [0]; var matches = NSArray.ArrayFromHandle (cfArrayRef, fd => new CTFontDescriptor (cfArrayRef, false)); CFObject.CFRelease (cfArrayRef); return matches; } finally { comparison.Free (); } } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void CompareScalarEqualSingle() { var test = new SimpleBinaryOpTest__CompareScalarEqualSingle(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); if (Sse.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (Sse.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (Sse.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (Sse.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (Sse.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__CompareScalarEqualSingle { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(Single[] inArray1, Single[] inArray2, Single[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Single>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Single>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Single>(); if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Single, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Single, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<Single> _fld1; public Vector128<Single> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref testStruct._fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref testStruct._fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__CompareScalarEqualSingle testClass) { var result = Sse.CompareScalarEqual(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__CompareScalarEqualSingle testClass) { fixed (Vector128<Single>* pFld1 = &_fld1) fixed (Vector128<Single>* pFld2 = &_fld2) { var result = Sse.CompareScalarEqual( Sse.LoadVector128((Single*)(pFld1)), Sse.LoadVector128((Single*)(pFld2)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single); private static Single[] _data1 = new Single[Op1ElementCount]; private static Single[] _data2 = new Single[Op2ElementCount]; private static Vector128<Single> _clsVar1; private static Vector128<Single> _clsVar2; private Vector128<Single> _fld1; private Vector128<Single> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__CompareScalarEqualSingle() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); } public SimpleBinaryOpTest__CompareScalarEqualSingle() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } _dataTable = new DataTable(_data1, _data2, new Single[RetElementCount], LargestVectorSize); } public bool IsSupported => Sse.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Sse.CompareScalarEqual( Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Sse.CompareScalarEqual( Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Sse.CompareScalarEqual( Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Sse).GetMethod(nameof(Sse.CompareScalarEqual), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Sse).GetMethod(nameof(Sse.CompareScalarEqual), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) }) .Invoke(null, new object[] { Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Sse).GetMethod(nameof(Sse.CompareScalarEqual), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) }) .Invoke(null, new object[] { Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Sse.CompareScalarEqual( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Single>* pClsVar1 = &_clsVar1) fixed (Vector128<Single>* pClsVar2 = &_clsVar2) { var result = Sse.CompareScalarEqual( Sse.LoadVector128((Single*)(pClsVar1)), Sse.LoadVector128((Single*)(pClsVar2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr); var result = Sse.CompareScalarEqual(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)); var op2 = Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr)); var result = Sse.CompareScalarEqual(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)); var op2 = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)); var result = Sse.CompareScalarEqual(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__CompareScalarEqualSingle(); var result = Sse.CompareScalarEqual(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleBinaryOpTest__CompareScalarEqualSingle(); fixed (Vector128<Single>* pFld1 = &test._fld1) fixed (Vector128<Single>* pFld2 = &test._fld2) { var result = Sse.CompareScalarEqual( Sse.LoadVector128((Single*)(pFld1)), Sse.LoadVector128((Single*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Sse.CompareScalarEqual(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Single>* pFld1 = &_fld1) fixed (Vector128<Single>* pFld2 = &_fld2) { var result = Sse.CompareScalarEqual( Sse.LoadVector128((Single*)(pFld1)), Sse.LoadVector128((Single*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Sse.CompareScalarEqual(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Sse.CompareScalarEqual( Sse.LoadVector128((Single*)(&test._fld1)), Sse.LoadVector128((Single*)(&test._fld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<Single> op1, Vector128<Single> op2, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] inArray2 = new Single[Op2ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] inArray2 = new Single[Op2ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Single>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Single>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Single[] left, Single[] right, Single[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (BitConverter.SingleToInt32Bits(result[0]) != ((left[0] == right[0]) ? -1 : 0)) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (BitConverter.SingleToInt32Bits(left[i]) != BitConverter.SingleToInt32Bits(result[i])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Sse)}.{nameof(Sse.CompareScalarEqual)}<Single>(Vector128<Single>, Vector128<Single>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
using ColossalFramework; using ColossalFramework.UI; using ColossalFramework.Globalization; using ICities; using UnityEngine; using System; using System.Collections.Generic; using System.Threading; namespace FavoriteCims { public class VechiclePassengersButton : UIButton { InstanceID VehicleID = InstanceID.Empty; VehicleManager MyVehicle = Singleton<VehicleManager>.instance; public UIAlignAnchor Alignment; public UIPanel RefPanel; FavCimsVechiclePanel VehiclePanel; public override void Start() { var uiView = UIView.GetAView(); //////////////////////////////////////////////// ////////////Passengers Button/////////////////// /////////////////////////////////////////////// this.name = "FavCimsVehPassButton"; this.normalBgSprite = "vehicleButton"; this.hoveredBgSprite = "vehicleButtonHovered"; this.focusedBgSprite = "vehicleButtonHovered"; this.pressedBgSprite = "vehicleButtonHovered"; this.disabledBgSprite = "vehicleButtonDisabled"; this.atlas = MyAtlas.FavCimsAtlas; this.size = new Vector2(36,36); this.playAudioEvents = true; this.AlignTo (RefPanel, Alignment); this.tooltipBox = uiView.defaultTooltipBox; if (FavCimsMainClass.FullScreenContainer.GetComponentInChildren<FavCimsVechiclePanel> () != null) { this.VehiclePanel = FavCimsMainClass.FullScreenContainer.GetComponentInChildren<FavCimsVechiclePanel>(); } else { this.VehiclePanel = FavCimsMainClass.FullScreenContainer.AddUIComponent(typeof(FavCimsVechiclePanel)) as FavCimsVechiclePanel; } this.VehiclePanel.VehicleID = InstanceID.Empty; this.VehiclePanel.Hide(); this.eventClick += (component, eventParam) => { if(!VehicleID.IsEmpty && !VehiclePanel.isVisible) { this.VehiclePanel.VehicleID = VehicleID; this.VehiclePanel.RefPanel = RefPanel; this.VehiclePanel.Show(); } else { this.VehiclePanel.VehicleID = InstanceID.Empty; this.VehiclePanel.Hide(); } }; } public override void Update() { if (FavCimsMainClass.UnLoading) return; if (this.isVisible) { this.tooltip = FavCimsLang.text("View_NoPassengers"); if(CitizenVehicleWorldInfoPanel.GetCurrentInstanceID() != InstanceID.Empty) { VehicleID = CitizenVehicleWorldInfoPanel.GetCurrentInstanceID(); } if(VehiclePanel != null) { if(!VehiclePanel.isVisible) { this.Unfocus(); } else { this.Focus(); } } if (!VehicleID.IsEmpty && VehicleID.Type == InstanceType.Vehicle) { this.isEnabled = true; //normal sprite this.tooltip = FavCimsLang.text("View_PassengersList"); } else { //Parked or VehicleID.Empty VehiclePanel.Hide (); this.Unfocus (); this.isEnabled = false; //disabled sprite } } else { this.isEnabled = false; //disabled sprite VehiclePanel.Hide (); VehicleID = InstanceID.Empty; } } } public class FavCimsVechiclePanel : UIPanel { const float Run = 0.5f; float seconds = Run; bool execute = false; bool firstRun = true; public static bool Wait = false; bool Garbage = false; public InstanceID VehicleID; public UIPanel RefPanel; VehicleManager MyVehicle = Singleton<VehicleManager>.instance; CitizenManager MyCitizen = Singleton<CitizenManager>.instance; public static Dictionary<uint, uint> CimsOnVeh = new Dictionary<uint, uint> (); UIPanel DriverPanel; UIPanel DriverPanelSubRow; UIButton DriverPanelIcon; UIButton DriverPanelText; DriverPrivateVehiclePanelRow DriverPrivateBodyRow; UIPanel PassengersPanel; UIPanel PassengersPanelSubRow; UIButton PassengersPanelIcon; UIButton PassengersPanelText; PassengersPrivateVehiclePanelRow[] PassengersPrivateBodyRow = new PassengersPrivateVehiclePanelRow[5]; uint VehicleUnits; UIPanel Title; UITextureSprite TitleSpriteBg; UIButton TitleVehicleName; UIPanel Body; UITextureSprite BodySpriteBg; UIScrollablePanel BodyRows; UIPanel Footer; UITextureSprite FooterSpriteBg; UIScrollablePanel BodyPanelScrollBar; UIScrollbar BodyScrollBar; UISlicedSprite BodyPanelTrackSprite; UISlicedSprite thumbSprite; //////////////////////////////////////////////// ////////////Passengers Panel/////////////////// /////////////////////////////////////////////// public override void Start() { try { this.width = 250; this.height = 0; this.name = "FavCimsVechiclePanel"; //this.backgroundSprite = "PoliciesBubble"; this.absolutePosition = new Vector3(0, 0); this.Hide (); Title = this.AddUIComponent<UIPanel> (); Title.name = "FavCimsVechiclePanelTitle"; Title.width = this.width; Title.height = 41; Title.relativePosition = Vector3.zero; TitleSpriteBg = Title.AddUIComponent<UITextureSprite> (); TitleSpriteBg.name = "FavCimsVechiclePanelTitleBG"; TitleSpriteBg.width = Title.width; TitleSpriteBg.height = Title.height; TitleSpriteBg.texture = TextureDB.VehiclePanelTitleBackground; TitleSpriteBg.relativePosition = Vector3.zero; //UIButton Vehicle Name TitleVehicleName = Title.AddUIComponent<UIButton> (); TitleVehicleName.name = "TitleVehicleName"; TitleVehicleName.width = Title.width; TitleVehicleName.height = Title.height; TitleVehicleName.textVerticalAlignment = UIVerticalAlignment.Middle; TitleVehicleName.textHorizontalAlignment = UIHorizontalAlignment.Center; TitleVehicleName.playAudioEvents = false; TitleVehicleName.font = UIDynamicFont.FindByName ("OpenSans-Regular"); TitleVehicleName.font.size = 15; TitleVehicleName.textScale = 1f; TitleVehicleName.wordWrap = true; TitleVehicleName.textPadding.left = 5; TitleVehicleName.textPadding.right = 5; TitleVehicleName.textColor = new Color32 (204, 204, 51, 40); //r,g,b,a TitleVehicleName.hoveredTextColor = new Color32 (204, 204, 51, 40); //r,g,b,a TitleVehicleName.pressedTextColor = new Color32 (204, 204, 51, 40); //r,g,b,a TitleVehicleName.focusedTextColor = new Color32 (204, 204, 51, 40); //r,g,b,a TitleVehicleName.useDropShadow = true; TitleVehicleName.dropShadowOffset = new Vector2 (1, -1); TitleVehicleName.dropShadowColor = new Color32 (0, 0, 0, 0); TitleVehicleName.relativePosition = Vector3.zero; Body = this.AddUIComponent<UIPanel> (); Body.name = "VechiclePanelBody"; Body.width = this.width; Body.autoLayoutDirection = LayoutDirection.Vertical; Body.autoLayout = true; Body.clipChildren = true; Body.height = 0; Body.relativePosition = new Vector3(0,Title.height); BodySpriteBg = Body.AddUIComponent<UITextureSprite> (); BodySpriteBg.name = "VechiclePanelDataContainer"; BodySpriteBg.width = Body.width; BodySpriteBg.height = Body.height; BodySpriteBg.texture = TextureDB.VehiclePanelBackground; BodySpriteBg.relativePosition = Vector3.zero; BodyRows = BodySpriteBg.AddUIComponent<UIScrollablePanel> (); BodyRows.name = "BodyRows"; BodyRows.width = BodySpriteBg.width - 24; BodyRows.autoLayoutDirection = LayoutDirection.Vertical; BodyRows.autoLayout = true; BodyRows.relativePosition = new Vector3(12,0); DriverPanel = BodyRows.AddUIComponent<UIPanel>(); DriverPanel.width = 226; DriverPanel.height = 25; DriverPanel.name = "LabelPanel_Driver"; DriverPanel.autoLayoutDirection = LayoutDirection.Vertical; DriverPanel.autoLayout = true; DriverPanel.Hide(); DriverPanelSubRow = DriverPanel.AddUIComponent<UIPanel>(); DriverPanelSubRow.width = 226; DriverPanelSubRow.height = 25; DriverPanelSubRow.name = "TitlePanel_Driver"; DriverPanelSubRow.atlas = MyAtlas.FavCimsAtlas; DriverPanelSubRow.backgroundSprite = "bg_row2"; DriverPanelIcon = DriverPanelSubRow.AddUIComponent<UIButton> (); DriverPanelIcon.name = "LabelPanelIcon_Driver"; DriverPanelIcon.width = 17; DriverPanelIcon.height = 17; DriverPanelIcon.atlas = MyAtlas.FavCimsAtlas; DriverPanelIcon.normalFgSprite = "driverIcon"; DriverPanelIcon.relativePosition = new Vector3(5,4); DriverPanelText = DriverPanelSubRow.AddUIComponent<UIButton> (); DriverPanelText.name = "LabelPanelText_Driver"; DriverPanelText.width = 200; DriverPanelText.height = 25; DriverPanelText.textVerticalAlignment = UIVerticalAlignment.Middle; DriverPanelText.textHorizontalAlignment = UIHorizontalAlignment.Left; DriverPanelText.playAudioEvents = true; DriverPanelText.font = UIDynamicFont.FindByName ("OpenSans-Regular"); DriverPanelText.font.size = 15; DriverPanelText.textScale = 0.80f; DriverPanelText.useDropShadow = true; DriverPanelText.dropShadowOffset = new Vector2 (1, -1); DriverPanelText.dropShadowColor = new Color32 (0, 0, 0, 0); DriverPanelText.textPadding.left = 5; DriverPanelText.textPadding.right = 5; DriverPanelText.textColor = new Color32 (51, 51, 51, 160); //r,g,b,a DriverPanelText.isInteractive = false; DriverPanelText.relativePosition = new Vector3 (DriverPanelIcon.relativePosition.x + DriverPanelIcon.width, 1); DriverPrivateBodyRow = BodyRows.AddUIComponent (typeof(DriverPrivateVehiclePanelRow)) as DriverPrivateVehiclePanelRow; DriverPrivateBodyRow.name = "RowPanel_Driver"; DriverPrivateBodyRow.OnVehicle = 0; DriverPrivateBodyRow.citizen = 0; DriverPrivateBodyRow.Hide(); PassengersPanel = BodyRows.AddUIComponent<UIPanel>(); PassengersPanel.width = 226; PassengersPanel.height = 25; PassengersPanel.name = "LabelPanel_Passengers"; PassengersPanel.autoLayoutDirection = LayoutDirection.Vertical; PassengersPanel.autoLayout = true; PassengersPanel.Hide(); PassengersPanelSubRow = PassengersPanel.AddUIComponent<UIPanel>(); PassengersPanelSubRow.width = 226; PassengersPanelSubRow.height = 25; PassengersPanelSubRow.name = "TitlePanel_Passengers"; PassengersPanelSubRow.atlas = MyAtlas.FavCimsAtlas; PassengersPanelSubRow.backgroundSprite = "bg_row2"; PassengersPanelIcon = PassengersPanelSubRow.AddUIComponent<UIButton> (); PassengersPanelIcon.name = "LabelPanelIcon_Passengers"; PassengersPanelIcon.width = 17; PassengersPanelIcon.height = 17; PassengersPanelIcon.atlas = MyAtlas.FavCimsAtlas; PassengersPanelIcon.normalFgSprite = "passengerIcon"; PassengersPanelIcon.relativePosition = new Vector3(5,4); PassengersPanelText = PassengersPanelSubRow.AddUIComponent<UIButton> (); PassengersPanelText.name = "LabelPanelText_Passengers"; PassengersPanelText.width = 200; PassengersPanelText.height = 25; PassengersPanelText.textVerticalAlignment = UIVerticalAlignment.Middle; PassengersPanelText.textHorizontalAlignment = UIHorizontalAlignment.Left; PassengersPanelText.playAudioEvents = true; PassengersPanelText.font = UIDynamicFont.FindByName ("OpenSans-Regular"); PassengersPanelText.font.size = 15; PassengersPanelText.textScale = 0.80f; PassengersPanelText.useDropShadow = true; PassengersPanelText.dropShadowOffset = new Vector2 (1, -1); PassengersPanelText.dropShadowColor = new Color32 (0, 0, 0, 0); PassengersPanelText.textPadding.left = 5; PassengersPanelText.textPadding.right = 5; PassengersPanelText.textColor = new Color32 (51, 51, 51, 160); //r,g,b,a PassengersPanelText.isInteractive = false; PassengersPanelText.relativePosition = new Vector3 (PassengersPanelIcon.relativePosition.x + PassengersPanelIcon.width, 1); for(int a = 1; a < 5; a++) { PassengersPrivateBodyRow[a] = BodyRows.AddUIComponent (typeof(PassengersPrivateVehiclePanelRow)) as PassengersPrivateVehiclePanelRow; PassengersPrivateBodyRow[a].name = "RowPanel_Passengers_" + a.ToString(); PassengersPrivateBodyRow[a].OnVehicle = 0; PassengersPrivateBodyRow[a].citizen = 0; PassengersPrivateBodyRow[a].Hide(); } BodyPanelScrollBar = BodySpriteBg.AddUIComponent<UIScrollablePanel> (); BodyPanelScrollBar.name = "BodyPanelScrollBar"; BodyPanelScrollBar.width = 10; BodyPanelScrollBar.relativePosition = new Vector3 (BodyRows.width + 12, 0); BodyScrollBar = BodyPanelScrollBar.AddUIComponent<UIScrollbar> (); BodyScrollBar.width = 10; BodyScrollBar.name = "BodyScrollBar"; BodyScrollBar.orientation = UIOrientation.Vertical; BodyScrollBar.pivot = UIPivotPoint.TopRight; BodyScrollBar.AlignTo (BodyScrollBar.parent, UIAlignAnchor.TopRight); BodyScrollBar.minValue = 0; BodyScrollBar.value = 0; BodyScrollBar.incrementAmount = 25; BodyPanelTrackSprite = BodyScrollBar.AddUIComponent<UISlicedSprite> (); BodyPanelTrackSprite.autoSize = true; BodyPanelTrackSprite.name = "BodyScrollBarTrackSprite"; //BodyPanelTrackSprite.size = BodyPanelTrackSprite.parent.size; BodyPanelTrackSprite.fillDirection = UIFillDirection.Vertical; BodyPanelTrackSprite.atlas = MyAtlas.FavCimsAtlas; BodyPanelTrackSprite.spriteName = "scrollbartrack"; //BodyPanelTrackSprite.spriteName = "ScrollbarTrack"; BodyPanelTrackSprite.relativePosition = BodyScrollBar.relativePosition; BodyScrollBar.trackObject = BodyPanelTrackSprite; thumbSprite = BodyScrollBar.AddUIComponent<UISlicedSprite> (); thumbSprite.name = "BodyScrollBarThumbSprite"; thumbSprite.autoSize = true; thumbSprite.width = thumbSprite.parent.width; thumbSprite.fillDirection = UIFillDirection.Vertical; thumbSprite.atlas = MyAtlas.FavCimsAtlas; thumbSprite.spriteName = "scrollbarthumb"; //thumbSprite.spriteName = "ScrollbarThumb"; thumbSprite.relativePosition = BodyScrollBar.relativePosition; BodyScrollBar.thumbObject = thumbSprite; BodyRows.verticalScrollbar = BodyScrollBar; /* Thx to CNightwing for this piece of code */ BodyRows.eventMouseWheel += (component, eventParam) => { var sign = Math.Sign (eventParam.wheelDelta); BodyRows.scrollPosition += new Vector2 (0, sign * (-1) * BodyScrollBar.incrementAmount); }; /* End */ Footer = this.AddUIComponent<UIPanel> (); Footer.name = "VechiclePanelPTFooter"; Footer.width = this.width; Footer.height = 12; Footer.relativePosition = new Vector3(0, Title.height + Body.height); FooterSpriteBg = Footer.AddUIComponent<UITextureSprite> (); FooterSpriteBg.width = Footer.width; FooterSpriteBg.height = Footer.height; FooterSpriteBg.texture = TextureDB.VehiclePanelFooterBackground; FooterSpriteBg.relativePosition = Vector3.zero; UIComponent FavCimsVechiclePanelTrigger_esc = UIView.Find<UIButton> ("Esc"); if (FavCimsVechiclePanelTrigger_esc != null) { FavCimsVechiclePanelTrigger_esc.eventClick += (component, eventParam) => this.Hide(); } }catch (Exception ex) { Debug.Error(" Passengers Panel Start() : " + ex.ToString()); } } public override void Update() { if (FavCimsMainClass.UnLoading) return; if(VehicleID.IsEmpty) { if(Garbage) { Wait = true; CimsOnVeh.Clear(); try { DriverPanel.Hide(); PassengersPanel.Hide(); DriverPrivateBodyRow.Hide(); DriverPrivateBodyRow.citizen = 0; DriverPrivateBodyRow.OnVehicle = 0; DriverPrivateBodyRow.firstRun = true; for(int a = 1; a < 5; a++) { PassengersPrivateBodyRow[a].Hide(); PassengersPrivateBodyRow[a].citizen = 0; PassengersPrivateBodyRow[a].OnVehicle = 0; PassengersPrivateBodyRow[a].firstRun = true; } Wait = false; }catch /*(Exception ex)*/ { //Debug.Error(" Flush Error : " + ex.ToString()); } Garbage = false; } firstRun = true; return; } try { if(!CitizenVehicleWorldInfoPanel.GetCurrentInstanceID().IsEmpty && CitizenVehicleWorldInfoPanel.GetCurrentInstanceID() != VehicleID) { Wait = true; CimsOnVeh.Clear(); try { DriverPanel.Hide(); PassengersPanel.Hide(); DriverPrivateBodyRow.Hide(); DriverPrivateBodyRow.citizen = 0; DriverPrivateBodyRow.OnVehicle = 0; DriverPrivateBodyRow.firstRun = true; for(int a = 1; a < 5; a++) { PassengersPrivateBodyRow[a].Hide(); PassengersPrivateBodyRow[a].citizen = 0; PassengersPrivateBodyRow[a].OnVehicle = 0; PassengersPrivateBodyRow[a].firstRun = true; } VehicleID = CitizenVehicleWorldInfoPanel.GetCurrentInstanceID(); if(VehicleID.IsEmpty) { return; } Wait = false; }catch /*(Exception ex)*/ { //Debug.Error(" Flush Error : " + ex.ToString()); } } if (this.isVisible && !VehicleID.IsEmpty) { Garbage = true; TitleVehicleName.text = FavCimsLang.text ("Vehicle_Passengers"); this.absolutePosition = new Vector3 (RefPanel.absolutePosition.x + RefPanel.width + 5, RefPanel.absolutePosition.y); this.height = RefPanel.height - 15; if(50 + ((float)CimsOnVeh.Count * 25) < (this.height - Title.height - Footer.height)) { Body.height = this.height - Title.height - Footer.height; } else if(50 + ((float)CimsOnVeh.Count * 25) > 400) { Body.height = 400; } else { Body.height = 50 + ((float)CimsOnVeh.Count * 25); } BodySpriteBg.height = Body.height; Footer.relativePosition = new Vector3(0, Title.height + Body.height); BodyRows.height = Body.height; BodyPanelScrollBar.height = Body.height; BodyScrollBar.height = Body.height; BodyPanelTrackSprite.size = BodyPanelTrackSprite.parent.size; seconds -= 1 * Time.deltaTime; if (seconds <= 0 || firstRun) { execute = true; seconds = Run; } else { execute = false; } if(execute) { firstRun = false; VehicleUnits = MyVehicle.m_vehicles.m_buffer [VehicleID.Vehicle].m_citizenUnits; int unitnum = 0; if(CimsOnVeh.Count == 0) { PassengersPanelText.text = FavCimsLang.text("View_NoPassengers"); } DriverPanel.Show(); DriverPanelText.text = FavCimsLang.text("Vehicle_DriverIconText"); PassengersPanel.Show(); while (VehicleUnits != 0) { uint nextUnit = MyCitizen.m_units.m_buffer [VehicleUnits].m_nextUnit; for (int i = 0; i < 5; i++) { uint citizen = MyCitizen.m_units.m_buffer [VehicleUnits].GetCitizen (i); if (citizen != 0 && !CimsOnVeh.ContainsKey(citizen)) { if(i == 0) { if(DriverPanel != null && DriverPrivateBodyRow != null) { CimsOnVeh.Add(citizen, VehicleUnits); DriverPrivateBodyRow.citizen = citizen; DriverPrivateBodyRow.OnVehicle = VehicleID.Vehicle; DriverPrivateBodyRow.firstRun = true; DriverPrivateBodyRow.Show(); } } else { PassengersPanelText.text = FavCimsLang.text("Vehicle_PasssengerIconText"); if(PassengersPanel != null && PassengersPrivateBodyRow[i] != null) { CimsOnVeh.Add(citizen, VehicleUnits); PassengersPrivateBodyRow[i].citizen = citizen; PassengersPrivateBodyRow[i].OnVehicle = VehicleID.Vehicle; PassengersPrivateBodyRow[i].firstRun = true; PassengersPrivateBodyRow[i].Show(); } } } } VehicleUnits = nextUnit; if (++unitnum > 0x80000) { break; } } } } //non mettere else che tanto non si esegue per via dell'event click sul bottone. }catch /*(Exception ex)*/ { //Debug.Error(" FavCimsVechiclePanelPT Update Error : " + ex.ToString()); } } } public class DriverPrivateVehiclePanelRow : PassengersVehiclePanelRow { const float Run = 0.1f; public override bool Wait() { if (FavCimsVechiclePanel.Wait) { return true; } return false; } public override Dictionary<uint,uint> GetCimsDict() { return FavCimsVechiclePanel.CimsOnVeh; } } public class PassengersPrivateVehiclePanelRow : DriverPrivateVehiclePanelRow { } }