context
stringlengths
2.52k
185k
gt
stringclasses
1 value
using Signum.Entities.Workflow; using Signum.Engine.DynamicQuery; using Signum.Engine.Maps; using Signum.Engine.Operations; using Signum.Entities; using Signum.Entities.Authorization; using Signum.Utilities; using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using Signum.Engine.Authorization; using Signum.Entities.Dynamic; using System.Text.RegularExpressions; using Signum.Entities.Reflection; using Signum.Engine.Basics; using Signum.Engine; using Signum.Engine.UserAssets; using Signum.Entities.Basics; namespace Signum.Engine.Workflow { public static class WorkflowLogic { public static Action<ICaseMainEntity, WorkflowTransitionContext>? OnTransition; public static ResetLazy<Dictionary<Lite<WorkflowEntity>, WorkflowEntity>> Workflows = null!; [AutoExpressionField] public static bool HasExpired(this WorkflowEntity w) => As.Expression(() => w.ExpirationDate.HasValue && w.ExpirationDate.Value < TimeZoneManager.Now); [AutoExpressionField] public static IQueryable<WorkflowPoolEntity> WorkflowPools(this WorkflowEntity e) => As.Expression(() => Database.Query<WorkflowPoolEntity>().Where(a => a.Workflow == e)); [AutoExpressionField] public static IQueryable<WorkflowActivityEntity> WorkflowActivities(this WorkflowEntity e) => As.Expression(() => Database.Query<WorkflowActivityEntity>().Where(a => a.Lane.Pool.Workflow == e)); public static IEnumerable<WorkflowActivityEntity> WorkflowActivitiesFromCache(this WorkflowEntity e) { return GetWorkflowNodeGraph(e.ToLite()).NextGraph.OfType<WorkflowActivityEntity>(); } [AutoExpressionField] public static IQueryable<WorkflowEventEntity> WorkflowEvents(this WorkflowEntity e) => As.Expression(() => Database.Query<WorkflowEventEntity>().Where(a => a.Lane.Pool.Workflow == e)); [AutoExpressionField] public static WorkflowEventEntity? WorkflowStartEvent(this WorkflowEntity e) => As.Expression(() => e.WorkflowEvents().Where(we => we.Type == WorkflowEventType.Start).SingleOrDefault()); public static IEnumerable<WorkflowEventEntity> WorkflowEventsFromCache(this WorkflowEntity e) { return GetWorkflowNodeGraph(e.ToLite()).NextGraph.OfType<WorkflowEventEntity>(); } [AutoExpressionField] public static IQueryable<WorkflowGatewayEntity> WorkflowGateways(this WorkflowEntity e) => As.Expression(() => Database.Query<WorkflowGatewayEntity>().Where(a => a.Lane.Pool.Workflow == e)); public static IEnumerable<WorkflowGatewayEntity> WorkflowGatewaysFromCache(this WorkflowEntity e) { return GetWorkflowNodeGraph(e.ToLite()).NextGraph.OfType<WorkflowGatewayEntity>(); } [AutoExpressionField] public static IQueryable<WorkflowConnectionEntity> WorkflowConnections(this WorkflowEntity e) => As.Expression(() => Database.Query<WorkflowConnectionEntity>().Where(a => a.From.Lane.Pool.Workflow == e && a.To.Lane.Pool.Workflow == e)); public static IEnumerable<WorkflowConnectionEntity> WorkflowConnectionsFromCache(this WorkflowEntity e) { return GetWorkflowNodeGraph(e.ToLite()).NextGraph.EdgesWithValue.SelectMany(edge => edge.Value); } [AutoExpressionField] public static IQueryable<WorkflowConnectionEntity> WorkflowMessageConnections(this WorkflowEntity e) => As.Expression(() => e.WorkflowConnections().Where(a => a.From.Lane.Pool != a.To.Lane.Pool)); [AutoExpressionField] public static IQueryable<WorkflowLaneEntity> WorkflowLanes(this WorkflowPoolEntity e) => As.Expression(() => Database.Query<WorkflowLaneEntity>().Where(a => a.Pool == e)); [AutoExpressionField] public static IQueryable<WorkflowConnectionEntity> WorkflowConnections(this WorkflowPoolEntity e) => As.Expression(() => Database.Query<WorkflowConnectionEntity>().Where(a => a.From.Lane.Pool == e && a.To.Lane.Pool == e)); [AutoExpressionField] public static IQueryable<WorkflowGatewayEntity> WorkflowGateways(this WorkflowLaneEntity e) => As.Expression(() => Database.Query<WorkflowGatewayEntity>().Where(a => a.Lane == e)); [AutoExpressionField] public static IQueryable<WorkflowEventEntity> WorkflowEvents(this WorkflowLaneEntity e) => As.Expression(() => Database.Query<WorkflowEventEntity>().Where(a => a.Lane == e)); [AutoExpressionField] public static IQueryable<WorkflowActivityEntity> WorkflowActivities(this WorkflowLaneEntity e) => As.Expression(() => Database.Query<WorkflowActivityEntity>().Where(a => a.Lane == e)); [AutoExpressionField] public static IQueryable<WorkflowConnectionEntity> NextConnections(this IWorkflowNodeEntity e) => As.Expression(() => Database.Query<WorkflowConnectionEntity>().Where(a => a.From == e)); [AutoExpressionField] public static WorkflowEntity Workflow(this CaseActivityEntity ca) => As.Expression(() => ca.Case.Workflow); public static IEnumerable<WorkflowConnectionEntity> NextConnectionsFromCache(this IWorkflowNodeEntity e, ConnectionType? type) { var result = GetWorkflowNodeGraph(e.Lane.Pool.Workflow.ToLite()).NextConnections(e); if (type == null) return result; return result.Where(a => a.Type == type); } [AutoExpressionField] public static IQueryable<WorkflowConnectionEntity> PreviousConnections(this IWorkflowNodeEntity e) => As.Expression(() => Database.Query<WorkflowConnectionEntity>().Where(a => a.To == e)); public static IEnumerable<WorkflowConnectionEntity> PreviousConnectionsFromCache(this IWorkflowNodeEntity e) { return GetWorkflowNodeGraph(e.Lane.Pool.Workflow.ToLite()).PreviousConnections(e); } public static ResetLazy<Dictionary<Lite<WorkflowEntity>, WorkflowNodeGraph>> WorkflowGraphLazy = null!; public static List<Lite<IWorkflowNodeEntity>> AutocompleteNodes(Lite<WorkflowEntity> workflow, string subString, int count, List<Lite<IWorkflowNodeEntity>> excludes) { return WorkflowGraphLazy.Value.GetOrThrow(workflow).Autocomplete(subString, count, excludes); } public static WorkflowNodeGraph GetWorkflowNodeGraph(Lite<WorkflowEntity> workflow) { var graph = WorkflowGraphLazy.Value.GetOrThrow(workflow); if (graph.TrackId != null) return graph; lock (graph) { if (graph.TrackId != null) return graph; var issues = new List<WorkflowIssue>(); graph.Validate(issues, (g, newDirection) => { throw new InvalidOperationException($"Unexpected direction of gateway '{g}' (Should be '{newDirection.NiceToString()}'). Consider saving Workflow '{workflow}'."); }); var errors = issues.Where(a => a.Type == WorkflowIssueType.Error); if (errors.HasItems()) throw new ApplicationException("Errors in Workflow '" + workflow + "':\r\n" + errors.ToString("\r\n").Indent(4)); return graph; } } static Func<WorkflowConfigurationEmbedded> getConfiguration = null!; public static WorkflowConfigurationEmbedded Configuration { get { return getConfiguration(); } } static Regex CurrentIsRegex = new Regex($@"{nameof(WorkflowActivityInfo)}\s*\.\s*{nameof(WorkflowActivityInfo.Current)}\s*\.\s*{nameof(WorkflowActivityInfo.Is)}\s*\(\s*""(?<workflowName>[^""]*)""\s*,\s*""(?<activityName>[^""]*)""\s*\)"); internal static List<CustomCompilerError> GetCustomErrors(string code) { var matches = CurrentIsRegex.Matches(code).Cast<Match>().ToList(); return matches.Select(m => { var workflowName = m.Groups["workflowName"].Value; var wa = WorkflowLogic.WorkflowGraphLazy.Value.Values.SingleOrDefault(w => w.Workflow.Name == workflowName); if (wa == null) return CreateCompilerError(code, m, $"No workflow with Name '{workflowName}' found."); var activityName = m.Groups["activityName"].Value; if (!wa.Activities.Values.Any(a => a.Name == activityName)) return CreateCompilerError(code, m, $"No activity with Name '{activityName}' found in workflow '{workflowName}'."); return null; }).NotNull().ToList(); } private static CustomCompilerError CreateCompilerError(string code, Match m, string errorText) { int index = 0; int line = 1; while (true) { var newIndex = code.IndexOf('\n', index + 1); if (newIndex >= m.Index || newIndex == -1) return new CustomCompilerError { ErrorText = errorText, Line = line }; index = newIndex; line++; } } public static void Start(SchemaBuilder sb, Func<WorkflowConfigurationEmbedded> getConfiguration) { if (sb.NotDefined(MethodInfo.GetCurrentMethod())) { PermissionAuthLogic.RegisterPermissions(WorkflowPermission.ViewWorkflowPanel); PermissionAuthLogic.RegisterPermissions(WorkflowPermission.ViewCaseFlow); WorkflowLogic.getConfiguration = getConfiguration; UserAssetsImporter.Register<WorkflowEntity>("Workflow", WorkflowOperation.Save); UserAssetsImporter.Register<WorkflowScriptEntity>("WorkflowScript", WorkflowScriptOperation.Save); UserAssetsImporter.Register<WorkflowTimerConditionEntity>("WorkflowTimerCondition", WorkflowTimerConditionOperation.Save); UserAssetsImporter.Register<WorkflowConditionEntity>("WorkflowCondition", WorkflowConditionOperation.Save); UserAssetsImporter.Register<WorkflowActionEntity>("WorkflowAction", WorkflowActionOperation.Save); sb.Include<WorkflowEntity>() .WithConstruct(WorkflowOperation.Create) .WithQuery(() => DynamicQueryCore.Auto( from e in Database.Query<WorkflowEntity>() select new { Entity = e, e.Id, e.Name, e.MainEntityType, HasExpired = e.HasExpired(), e.ExpirationDate, }) .ColumnDisplayName(a => a.HasExpired, () => WorkflowMessage.HasExpired.NiceToString())) .WithExpressionFrom((CaseActivityEntity ca) => ca.Workflow()); WorkflowGraph.Register(); QueryLogic.Expressions.Register((WorkflowEntity wf) => wf.WorkflowStartEvent()); QueryLogic.Expressions.Register((WorkflowEntity wf) => wf.HasExpired(), () => WorkflowMessage.HasExpired.NiceToString()); sb.AddIndex((WorkflowEntity wf) => wf.ExpirationDate); DynamicCode.GetCustomErrors += GetCustomErrors; Workflows = sb.GlobalLazy(() => Database.Query<WorkflowEntity>().ToDictionary(a => a.ToLite()), new InvalidateWith(typeof(WorkflowEntity))); sb.Include<WorkflowPoolEntity>() .WithUniqueIndex(wp => new { wp.Workflow, wp.Name }) .WithSave(WorkflowPoolOperation.Save) .WithDelete(WorkflowPoolOperation.Delete) .WithExpressionFrom((WorkflowEntity p) => p.WorkflowPools()) .WithQuery(() => e => new { Entity = e, e.Id, e.Name, e.BpmnElementId, e.Workflow, }); sb.Include<WorkflowLaneEntity>() .WithUniqueIndex(wp => new { wp.Pool, wp.Name }) .WithSave(WorkflowLaneOperation.Save) .WithDelete(WorkflowLaneOperation.Delete) .WithExpressionFrom((WorkflowPoolEntity p) => p.WorkflowLanes()) .WithQuery(() => e => new { Entity = e, e.Id, e.Name, e.BpmnElementId, e.Pool, e.Pool.Workflow, }); sb.Include<WorkflowActivityEntity>() .WithUniqueIndex(w => new { w.Lane, w.Name }) .WithSave(WorkflowActivityOperation.Save) .WithDelete(WorkflowActivityOperation.Delete) .WithExpressionFrom((WorkflowEntity p) => p.WorkflowActivities()) .WithExpressionFrom((WorkflowLaneEntity p) => p.WorkflowActivities()) .WithVirtualMList(wa => wa.BoundaryTimers, e => e.BoundaryOf, WorkflowEventOperation.Save, WorkflowEventOperation.Delete) .WithQuery(() => e => new { Entity = e, e.Id, e.Name, e.BpmnElementId, e.Comments, e.Lane, e.Lane.Pool.Workflow, }); sb.Include<WorkflowEventEntity>() .WithExpressionFrom((WorkflowEntity p) => p.WorkflowEvents()) .WithExpressionFrom((WorkflowLaneEntity p) => p.WorkflowEvents()) .WithQuery(() => e => new { Entity = e, e.Id, e.Type, e.Name, e.BpmnElementId, e.Lane, e.Lane.Pool.Workflow, }); new Graph<WorkflowEventEntity>.Execute(WorkflowEventOperation.Save) { CanBeNew = true, CanBeModified = true, Execute = (e, _) => { if (e.Timer == null && e.Type.IsTimer()) throw new InvalidOperationException(ValidationMessage._0IsMandatoryWhen1IsSetTo2.NiceToString(e.NicePropertyName(a => a.Timer), e.NicePropertyName(a => a.Type), e.Type.NiceToString())); if (e.Timer != null && !e.Type.IsTimer()) throw new InvalidOperationException(ValidationMessage._0ShouldBeNullWhen1IsSetTo2.NiceToString(e.NicePropertyName(a => a.Timer), e.NicePropertyName(a => a.Type), e.Type.NiceToString())); if (e.BoundaryOf == null && e.Type.IsBoundaryTimer()) throw new InvalidOperationException(ValidationMessage._0IsMandatoryWhen1IsSetTo2.NiceToString(e.NicePropertyName(a => a.BoundaryOf), e.NicePropertyName(a => a.Type), e.Type.NiceToString())); if (e.BoundaryOf != null && !e.Type.IsBoundaryTimer()) throw new InvalidOperationException(ValidationMessage._0ShouldBeNullWhen1IsSetTo2.NiceToString(e.NicePropertyName(a => a.BoundaryOf), e.NicePropertyName(a => a.Type), e.Type.NiceToString())); e.Save(); }, }.Register(); new Graph<WorkflowEventEntity>.Delete(WorkflowEventOperation.Delete) { Delete = (e, _) => { if (e.Type.IsScheduledStart()) { var scheduled = e.ScheduledTask(); if (scheduled != null) WorkflowEventTaskLogic.DeleteWorkflowEventScheduledTask(scheduled); } e.Delete(); }, }.Register(); sb.Include<WorkflowGatewayEntity>() .WithSave(WorkflowGatewayOperation.Save) .WithDelete(WorkflowGatewayOperation.Delete) .WithExpressionFrom((WorkflowEntity p) => p.WorkflowGateways()) .WithExpressionFrom((WorkflowLaneEntity p) => p.WorkflowGateways()) .WithQuery(() => e => new { Entity = e, e.Id, e.Type, e.Name, e.BpmnElementId, e.Lane, e.Lane.Pool.Workflow, }); sb.Include<WorkflowConnectionEntity>() .WithSave(WorkflowConnectionOperation.Save) .WithDelete(WorkflowConnectionOperation.Delete) .WithExpressionFrom((WorkflowEntity p) => p.WorkflowConnections()) .WithExpressionFrom((WorkflowEntity p) => p.WorkflowMessageConnections(), null!) .WithExpressionFrom((WorkflowPoolEntity p) => p.WorkflowConnections()) .WithExpressionFrom((IWorkflowNodeEntity p) => p.NextConnections(), null!) .WithExpressionFrom((IWorkflowNodeEntity p) => p.PreviousConnections(), null!) .WithQuery(() => e => new { Entity = e, e.Id, e.Name, e.BpmnElementId, e.From, e.To, }); WorkflowEventTaskEntity.GetWorkflowEntity = lite => WorkflowGraphLazy.Value.GetOrThrow(lite).Workflow; WorkflowGraphLazy = sb.GlobalLazy(() => { using (new EntityCache()) { var events = Database.RetrieveAll<WorkflowEventEntity>().GroupToDictionary(a => a.Lane.Pool.Workflow.ToLite()); var gateways = Database.RetrieveAll<WorkflowGatewayEntity>().GroupToDictionary(a => a.Lane.Pool.Workflow.ToLite()); var activities = Database.RetrieveAll<WorkflowActivityEntity>().GroupToDictionary(a => a.Lane.Pool.Workflow.ToLite()); var connections = Database.RetrieveAll<WorkflowConnectionEntity>().GroupToDictionary(a => a.From.Lane.Pool.Workflow.ToLite()); var result = Database.RetrieveAll<WorkflowEntity>().ToDictionary(workflow => workflow.ToLite(), workflow => { var w = workflow.ToLite(); var nodeGraph = new WorkflowNodeGraph { Workflow = workflow, Events = events.TryGetC(w).EmptyIfNull().ToDictionary(e => e.ToLite()), Gateways = gateways.TryGetC(w).EmptyIfNull().ToDictionary(g => g.ToLite()), Activities = activities.TryGetC(w).EmptyIfNull().ToDictionary(a => a.ToLite()), Connections = connections.TryGetC(w).EmptyIfNull().ToDictionary(c => c.ToLite()), }; nodeGraph.FillGraphs(); return nodeGraph; }); return result; } }, new InvalidateWith(typeof(WorkflowConnectionEntity))); WorkflowGraphLazy.OnReset += (e, args) => DynamicCode.OnInvalidated?.Invoke(); Validator.PropertyValidator((WorkflowConnectionEntity c) => c.Condition).StaticPropertyValidation = (e, pi) => { if (e.Condition != null && e.From != null) { var conditionType = (e.Condition.EntityOrNull ?? Conditions.Value.GetOrThrow(e.Condition)).MainEntityType; var workflowType = e.From.Lane.Pool.Workflow.MainEntityType; if (!conditionType.Is(workflowType)) return WorkflowMessage.Condition0IsDefinedFor1Not2.NiceToString(conditionType, workflowType); } return null; }; StartWorkflowConditions(sb); StartWorkflowTimerConditions(sb); StartWorkflowActions(sb); StartWorkflowScript(sb); } } public static ResetLazy<Dictionary<Lite<WorkflowTimerConditionEntity>, WorkflowTimerConditionEntity>> TimerConditions = null!; public static WorkflowTimerConditionEntity RetrieveFromCache(this Lite<WorkflowTimerConditionEntity> wc) => TimerConditions.Value.GetOrThrow(wc); private static void StartWorkflowTimerConditions(SchemaBuilder sb) { sb.Include<WorkflowTimerConditionEntity>() .WithQuery(() => e => new { Entity = e, e.Id, e.Name, e.MainEntityType, e.Eval.Script }); new Graph<WorkflowTimerConditionEntity>.Execute(WorkflowTimerConditionOperation.Save) { CanBeNew = true, CanBeModified = true, Execute = (e, _) => { if (!e.IsNew) { var oldMainEntityType = e.InDB(a => a.MainEntityType); if (!oldMainEntityType.Is(e.MainEntityType)) ThrowConnectionError(Database.Query<WorkflowEventEntity>().Where(a => a.Timer!.Condition == e.ToLite()), e, WorkflowTimerConditionOperation.Save); } e.Save(); }, }.Register(); new Graph<WorkflowTimerConditionEntity>.Delete(WorkflowTimerConditionOperation.Delete) { Delete = (e, _) => { ThrowConnectionError(Database.Query<WorkflowEventEntity>().Where(a => a.Timer!.Condition == e.ToLite()), e, WorkflowTimerConditionOperation.Delete); e.Delete(); }, }.Register(); new Graph<WorkflowTimerConditionEntity>.ConstructFrom<WorkflowTimerConditionEntity>(WorkflowTimerConditionOperation.Clone) { Construct = (e, args) => { return new WorkflowTimerConditionEntity { MainEntityType = e.MainEntityType, Eval = new WorkflowTimerConditionEval { Script = e.Eval.Script } }; }, }.Register(); TimerConditions = sb.GlobalLazy(() => Database.Query<WorkflowTimerConditionEntity>().ToDictionary(a => a.ToLite()), new InvalidateWith(typeof(WorkflowTimerConditionEntity))); } public static ResetLazy<Dictionary<Lite<WorkflowActionEntity>, WorkflowActionEntity>> Actions = null!; public static WorkflowActionEntity RetrieveFromCache(this Lite<WorkflowActionEntity> wa) => Actions.Value.GetOrThrow(wa); private static void StartWorkflowActions(SchemaBuilder sb) { sb.Include<WorkflowActionEntity>() .WithQuery(() => e => new { Entity = e, e.Id, e.Name, e.MainEntityType, e.Eval.Script }); new Graph<WorkflowActionEntity>.Execute(WorkflowActionOperation.Save) { CanBeNew = true, CanBeModified = true, Execute = (e, _) => { if (!e.IsNew) { var oldMainEntityType = e.InDB(a => a.MainEntityType); if (!oldMainEntityType.Is(e.MainEntityType)) ThrowConnectionError(Database.Query<WorkflowConnectionEntity>().Where(a => a.Action == e.ToLite()), e, WorkflowActionOperation.Save); } e.Save(); }, }.Register(); new Graph<WorkflowActionEntity>.Delete(WorkflowActionOperation.Delete) { Delete = (e, _) => { ThrowConnectionError(Database.Query<WorkflowConnectionEntity>().Where(a => a.Action == e.ToLite()), e, WorkflowActionOperation.Delete); e.Delete(); }, }.Register(); new Graph<WorkflowActionEntity>.ConstructFrom<WorkflowActionEntity>(WorkflowActionOperation.Clone) { Construct = (e, args) => { return new WorkflowActionEntity { MainEntityType = e.MainEntityType, Eval = new WorkflowActionEval { Script = e.Eval.Script } }; }, }.Register(); Actions = sb.GlobalLazy(() => Database.Query<WorkflowActionEntity>().ToDictionary(a => a.ToLite()), new InvalidateWith(typeof(WorkflowActionEntity))); } public static ResetLazy<Dictionary<Lite<WorkflowConditionEntity>, WorkflowConditionEntity>> Conditions = null!; public static WorkflowConditionEntity RetrieveFromCache(this Lite<WorkflowConditionEntity> wc) => Conditions.Value.GetOrThrow(wc); private static void StartWorkflowConditions(SchemaBuilder sb) { sb.Include<WorkflowConditionEntity>() .WithQuery(() => e => new { Entity = e, e.Id, e.Name, e.MainEntityType, e.Eval.Script }); new Graph<WorkflowConditionEntity>.Execute(WorkflowConditionOperation.Save) { CanBeNew = true, CanBeModified = true, Execute = (e, _) => { if (!e.IsNew) { var oldMainEntityType = e.InDB(a => a.MainEntityType); if (!oldMainEntityType.Is(e.MainEntityType)) ThrowConnectionError(Database.Query<WorkflowConnectionEntity>().Where(a => a.Condition == e.ToLite()), e, WorkflowConditionOperation.Save); } e.Save(); }, }.Register(); new Graph<WorkflowConditionEntity>.Delete(WorkflowConditionOperation.Delete) { Delete = (e, _) => { ThrowConnectionError(Database.Query<WorkflowConnectionEntity>().Where(a => a.Condition == e.ToLite()), e, WorkflowConditionOperation.Delete); e.Delete(); }, }.Register(); new Graph<WorkflowConditionEntity>.ConstructFrom<WorkflowConditionEntity>(WorkflowConditionOperation.Clone) { Construct = (e, args) => { return new WorkflowConditionEntity { MainEntityType = e.MainEntityType, Eval = new WorkflowConditionEval { Script = e.Eval.Script } }; }, }.Register(); Conditions = sb.GlobalLazy(() => Database.Query<WorkflowConditionEntity>().ToDictionary(a => a.ToLite()), new InvalidateWith(typeof(WorkflowConditionEntity))); } public static ResetLazy<Dictionary<Lite<WorkflowScriptEntity>, WorkflowScriptEntity>> Scripts = null!; public static WorkflowScriptEntity RetrieveFromCache(this Lite<WorkflowScriptEntity> ws)=> Scripts.Value.GetOrThrow(ws); private static void StartWorkflowScript(SchemaBuilder sb) { sb.Include<WorkflowScriptEntity>() .WithQuery(() => s => new { Entity = s, s.Id, s.Name, s.MainEntityType, }); new Graph<WorkflowScriptEntity>.Execute(WorkflowScriptOperation.Save) { CanBeNew = true, CanBeModified = true, Execute = (e, _) => { if (!e.IsNew) { var oldMainEntityType = e.InDB(a => a.MainEntityType); if (!oldMainEntityType.Is(e.MainEntityType)) ThrowConnectionError(Database.Query<WorkflowActivityEntity>().Where(a => a.Script!.Script == e.ToLite()), e, WorkflowScriptOperation.Save); } e.Save(); }, }.Register(); new Graph<WorkflowScriptEntity>.ConstructFrom<WorkflowScriptEntity>(WorkflowScriptOperation.Clone) { Construct = (s, _) => new WorkflowScriptEntity() { MainEntityType = s.MainEntityType, Eval = new WorkflowScriptEval() { Script = s.Eval.Script } } }.Register(); new Graph<WorkflowScriptEntity>.Delete(WorkflowScriptOperation.Delete) { Delete = (s, _) => { ThrowConnectionError(Database.Query<WorkflowActivityEntity>().Where(a => a.Script!.Script == s.ToLite()), s, WorkflowScriptOperation.Delete); s.Delete(); }, }.Register(); Scripts = sb.GlobalLazy(() => Database.Query<WorkflowScriptEntity>().ToDictionary(a => a.ToLite()), new InvalidateWith(typeof(WorkflowScriptEntity))); sb.Include<WorkflowScriptRetryStrategyEntity>() .WithSave(WorkflowScriptRetryStrategyOperation.Save) .WithDelete(WorkflowScriptRetryStrategyOperation.Delete) .WithQuery(() => e => new { Entity = e, e.Id, e.Rule }); } private static void ThrowConnectionError(IQueryable<WorkflowConnectionEntity> queryable, Entity entity, IOperationSymbolContainer operation) { if (queryable.Count() == 0) return; var errors = queryable.Select(a => new { Connection = a.ToLite(), From = a.From.ToLite(), To = a.To.ToLite(), Workflow = a.From.Lane.Pool.Workflow.ToLite() }).ToList(); var formattedErrors = errors.GroupBy(a => a.Workflow).ToString(gr => $"Workflow '{gr.Key}':" + gr.ToString(a => $"Connection {a.Connection!.Id} ({a.Connection}): {a.From} -> {a.To}", "\r\n").Indent(4), "\r\n\r\n").Indent(4); throw new ApplicationException($"Impossible to {operation.Symbol.Key.After('.')} '{entity}' because is used in some connections: \r\n" + formattedErrors); } private static void ThrowConnectionError<T>(IQueryable<T> queryable, Entity entity, IOperationSymbolContainer operation) where T : Entity, IWorkflowNodeEntity { if (queryable.Count() == 0) return; var errors = queryable.Select(a => new { Entity = a.ToLite(), Workflow = a.Lane.Pool.Workflow.ToLite() }).ToList(); var formattedErrors = errors.GroupBy(a => a.Workflow).ToString(gr => $"Workflow '{gr.Key}':" + gr.ToString(a => $"{typeof(T).NiceName()} {a.Entity}", "\r\n").Indent(4), "\r\n\r\n").Indent(4); throw new ApplicationException($"Impossible to {operation.Symbol.Key.After('.')} '{entity}' because is used in some {typeof(T).NicePluralName()}: \r\n" + formattedErrors); } public class WorkflowGraph : Graph<WorkflowEntity> { public static void Register() { new Execute(WorkflowOperation.Save) { CanBeNew = true, CanBeModified = true, Execute = (e, args) => { if (e.MainEntityStrategies.Contains(WorkflowMainEntityStrategy.CreateNew)) { var type = e.MainEntityType.ToType(); if (CaseActivityLogic.Options.TryGetC(type)?.Constructor == null) throw new ApplicationException(WorkflowMessage._0NotAllowedFor1NoConstructorHasBeenDefinedInWithWorkflow.NiceToString(WorkflowMainEntityStrategy.CreateNew.NiceToString(), type.NiceName())); } WorkflowLogic.ApplyDocument(e, args.TryGetArgC<WorkflowModel>(), args.TryGetArgC<WorkflowReplacementModel>(), args.TryGetArgC<List<WorkflowIssue>>() ?? new List<WorkflowIssue>()); DynamicCode.OnInvalidated?.Invoke(); } }.Register(); new ConstructFrom<WorkflowEntity>(WorkflowOperation.Clone) { Construct = (w, args) => { WorkflowBuilder wb = new WorkflowBuilder(w); var result = wb.Clone(); return result; } }.Register(); new Delete(WorkflowOperation.Delete) { CanDelete = w => { var usedWorkflows = Database.Query<CaseEntity>() .Where(c => c.Workflow.Is(w) && c.ParentCase != null) .Select(c => c.ParentCase!.Entity.Workflow.ToLite()) .Distinct() .ToList(); if (usedWorkflows.Any()) return WorkflowMessage.WorkflowUsedIn0ForDecompositionOrCallWorkflow.NiceToString(usedWorkflows.ToString(", ")); return null; }, Delete = (w, _) => { var wb = new WorkflowBuilder(w); wb.Delete(); DynamicCode.OnInvalidated?.Invoke(); } }.Register(); new Execute(WorkflowOperation.Activate) { CanExecute = w => w.HasExpired() ? null : WorkflowMessage.Workflow0AlreadyActivated.NiceToString(w), Execute = (w, _) => { w.ExpirationDate = null; w.Save(); w.SuspendWorkflowScheduledTasks(suspended: false); } }.Register(); new Execute(WorkflowOperation.Deactivate) { CanExecute = w => w.HasExpired() ? WorkflowMessage.Workflow0HasExpiredOn1.NiceToString(w, w.ExpirationDate!.Value.ToString()) : w.Cases().SelectMany(c => c.CaseActivities()).Any(ca => ca.DoneDate == null) ? CaseActivityMessage.ThereAreInprogressActivities.NiceToString() : null, Execute = (w, args) => { w.ExpirationDate = args.GetArg<DateTime>(); w.Save(); w.SuspendWorkflowScheduledTasks(suspended: true); } }.Register(); } } public static void SuspendWorkflowScheduledTasks(this WorkflowEntity workflow, bool suspended) { workflow.WorkflowEvents() .Where(a => a.Type == WorkflowEventType.ScheduledStart) .Select(a => a.ScheduledTask()!) .UnsafeUpdate() .Set(a => a.Suspended, a => suspended) .Execute(); } public static Func<UserEntity, Lite<Entity>, bool> IsUserActor = (user, actor) => actor.Is(user) || (actor is Lite<RoleEntity> && AuthLogic.IndirectlyRelated(user.Role).Contains((Lite<RoleEntity>)actor)); public static Expression<Func<UserEntity, Lite<Entity>, bool>> IsUserActorForNotifications = (user, actorConstant) => actorConstant.Is(user) || (actorConstant is Lite<RoleEntity> && AuthLogic.InverseIndirectlyRelated((Lite<RoleEntity>)actorConstant).Contains(user.Role)); public static List<WorkflowEntity> GetAllowedStarts() { return WorkflowGraphLazy.Value.Values.Where(wg => wg.IsStartCurrentUser()).Select(wg => wg.Workflow).ToList(); } public static WorkflowModel GetWorkflowModel(WorkflowEntity workflow) { var wb = new WorkflowBuilder(workflow); return wb.GetWorkflowModel(); } public static WorkflowReplacementModel PreviewChanges(WorkflowEntity workflow, WorkflowModel model) { if (model == null) throw new ArgumentNullException(nameof(model)); var document = WorkflowBuilder.ParseDocument(model.DiagramXml); var wb = new WorkflowBuilder(workflow); return wb.PreviewChanges(document, model); } public static void ApplyDocument(WorkflowEntity workflow, WorkflowModel? model, WorkflowReplacementModel? replacements, List<WorkflowIssue> issuesContainer) { if (issuesContainer.Any()) throw new InvalidOperationException("issuesContainer should be empty"); var wb = new WorkflowBuilder(workflow); if (workflow.IsNew) workflow.Save(); if (model != null) { wb.ApplyChanges(model, replacements); } wb.ValidateGraph(issuesContainer); if (issuesContainer.Any(a => a.Type == WorkflowIssueType.Error)) throw new IntegrityCheckException(new Dictionary<Guid, IntegrityCheck>()); workflow.FullDiagramXml = new WorkflowXmlEmbedded { DiagramXml = wb.GetXDocument().ToString() }; workflow.Save(); } } }
using System; using System.IO; using UnityEditorInternal; using UnityEngine; using UnityEditor; using System.Collections; using System.Collections.Generic; using Projeny.Internal; using System.Linq; namespace Projeny.Internal { public class PmView { public event Action ViewStateChanged = delegate {}; public event Action ProjectConfigTypeChanged = delegate {}; public event Action<ProjectConfigTypes> ClickedProjectType = delegate {}; public event Action ClickedRefreshReleaseList = delegate {}; public event Action ClickedRefreshPackages = delegate {}; public event Action ClickedCreateNewPackage = delegate {}; public event Action ClickedProjectApplyButton = delegate {}; public event Action ClickedProjectRevertButton = delegate {}; public event Action ClickedProjectSaveButton = delegate {}; public event Action ClickedProjectEditButton = delegate {}; public event Action ClickedUpdateSolution = delegate {}; public event Action<int> ClickedPackageFolder = delegate {}; public event Action ClickedOpenSolution = delegate {}; public event Action<DragListTypes, DragListTypes, List<DragListEntry>> DraggedDroppedListEntries = delegate {}; readonly Dictionary<DragListTypes, Func<IEnumerable<ContextMenuItem>>> _contextMenuHandlers = new Dictionary<DragListTypes, Func<IEnumerable<ContextMenuItem>>>(); readonly List<PopupInfo> _popupHandlers = new List<PopupInfo>(); readonly List<DragList> _lists = new List<DragList>(); readonly Model _model; readonly Settings _settings; readonly PmSettings _pmSettings; float _split1 = 0; float _split2 = 0.5f; float _split3 = 1.0f; float _lastTime = 0.5f; int _popupIdCount; public PmView( Model model, PmSettings settings) { _settings = settings.View; _pmSettings = settings; _model = model; for (int i = 0; i < (int)DragListTypes.Count; i++) { Assert.That(i <= _model.ListModels.Count - 1, "Could not find drag list type '{0}' in model", (DragListTypes)i); var list = new DragList( this, (DragListTypes)i, _model.ListModels[i], settings); _lists.Add(list); } } public bool IsSaveEnabled { get; set; } public bool IsRevertEnabled { get; set; } public bool IsEditEnabled { get; set; } public int CurrentPackageFolderIndex { get { return _model.PackageFolderIndex; } set { _model.PackageFolderIndex = value; } } public List<string> PackageFolderPaths { get { return _model.PackageFolderPaths; } set { _model.PackageFolderPaths = value; } } public PmViewStates ViewState { get { return _model.ViewState; } set { if (_model.ViewState != value) { _model.ViewState = value; ViewStateChanged(); } } } public IEnumerable<DragList> Lists { get { return _lists; } } public ProjectConfigTypes ProjectConfigType { get { return _model.ProjectConfigType; } set { if (_model.ProjectConfigType != value) { _model.ProjectConfigType = value; ProjectConfigTypeChanged(); } } } public string BlockedStatusMessage { get; set; } public string BlockedStatusTitle { get; set; } public void AddContextMenuHandler(DragListTypes listType, Func<IEnumerable<ContextMenuItem>> handler) { _contextMenuHandlers.Add(listType, handler); } public void RemoveContextMenuHandler(DragListTypes listType) { _contextMenuHandlers.RemoveWithConfirm(listType); } public List<DragListEntry> GetSelected(DragListTypes listType) { return GetSelected().Where(x => x.ListType == listType).ToList(); } public List<DragListEntry> GetSelected() { return _lists.SelectMany(x => x.GetSelected()).ToList(); } public void ClearOtherListSelected(DragListTypes type) { foreach (var list in _lists) { if (list.ListType != type) { list.ClearSelected(); } } } public void ClearSelected() { foreach (var list in _lists) { list.ClearSelected(); } } public bool ShowBlockedPopup { get; set; } public bool IsBlocked { get; set; } public void SetListItems( DragListTypes listType, List<DragList.ItemDescriptor> items) { GetList(listType).SetItems(items); } public DragList GetList(DragListTypes listType) { return _lists[(int)listType]; } public bool IsDragAllowed(DragList.DragData data, DragList list) { var sourceListType = data.SourceList.ListType; var dropListType = list.ListType; if (sourceListType == dropListType) { return true; } switch (dropListType) { case DragListTypes.Package: { return sourceListType == DragListTypes.Release || sourceListType == DragListTypes.AssetItem || sourceListType == DragListTypes.PluginItem; } case DragListTypes.Release: { return false; } case DragListTypes.AssetItem: { return sourceListType == DragListTypes.Package || sourceListType == DragListTypes.PluginItem; } case DragListTypes.PluginItem: { return sourceListType == DragListTypes.Package || sourceListType == DragListTypes.AssetItem; } case DragListTypes.VsSolution: { return sourceListType == DragListTypes.AssetItem || sourceListType == DragListTypes.PluginItem; } } Assert.Throw(); return true; } public void Update() { var deltaTime = Time.realtimeSinceStartup - _lastTime; _lastTime = Time.realtimeSinceStartup; var px = Mathf.Clamp(deltaTime * _settings.InterpSpeed, 0, 1); _split1 = Mathf.Lerp(_split1, GetDesiredSplit1(), px); _split2 = Mathf.Lerp(_split2, GetDesiredSplit2(), px); _split3 = Mathf.Lerp(_split3, GetDesiredSplit3(), px); } float GetDesiredSplit2() { if (ViewState == PmViewStates.ReleasesAndPackages) { return 1.0f; } if (ViewState == PmViewStates.PackagesAndProject) { return 0.4f; } Assert.That(ViewState == PmViewStates.Project || ViewState == PmViewStates.ProjectAndVisualStudio); return 0; } float GetDesiredSplit1() { if (ViewState == PmViewStates.ReleasesAndPackages) { return 0.5f; } return 0; } float GetDesiredSplit3() { if (ViewState == PmViewStates.ProjectAndVisualStudio) { return 0.5f; } return 1.0f; } public void DrawPopupCommon(Rect fullRect, Rect popupRect) { ImguiUtil.DrawColoredQuad(popupRect, _settings.Theme.LoadingOverlapPopupColor); } string[] GetConfigTypesDisplayValues() { return new[] { ProjenyEditorUtil.ProjectConfigFileName, ProjenyEditorUtil.ProjectConfigUserFileName, ProjenyEditorUtil.ProjectConfigFileName + " (global)", ProjenyEditorUtil.ProjectConfigUserFileName + " (global)", }; } public void OnDragDrop(DragList.DragData data, DragList dropList) { if (data.SourceList == dropList || !IsDragAllowed(data, dropList)) { return; } var sourceListType = data.SourceList.ListType; var dropListType = dropList.ListType; DraggedDroppedListEntries(sourceListType, dropListType, data.Entries); } public void OpenContextMenu(DragList dropList) { var itemGetter = _contextMenuHandlers.TryGetValue(dropList.ListType); if (itemGetter != null) { ImguiUtil.OpenContextMenu(itemGetter()); } } void DrawFileDropdown(Rect rect) { var dropDownRect = Rect.MinMaxRect( rect.xMin, rect.yMin, rect.xMax - _settings.FileButtonsPercentWidth * rect.width, rect.yMax); var displayValues = GetConfigTypesDisplayValues(); var desiredConfigType = (ProjectConfigTypes)EditorGUI.Popup(dropDownRect, (int)_model.ProjectConfigType, displayValues, _settings.DropdownTextStyle); GUI.Button(dropDownRect, displayValues[(int)desiredConfigType], _settings.DropdownTextButtonStyle); if (desiredConfigType != _model.ProjectConfigType) { ClickedProjectType(desiredConfigType); } GUI.DrawTexture(new Rect(dropDownRect.xMax - _settings.ArrowSize.x + _settings.ArrowOffset.x, dropDownRect.yMin + _settings.ArrowOffset.y, _settings.ArrowSize.x, _settings.ArrowSize.y), _settings.FileDropdownArrow); var startX = rect.xMax - _settings.FileButtonsPercentWidth * rect.width; var startY = rect.yMin; var endX = rect.xMax; var endY = rect.yMax; var buttonPadding = _settings.FileButtonsPadding; var buttonWidth = ((endX - startX) - 3 * buttonPadding) / 3.0f; var buttonHeight = endY - startY; startX = startX + buttonPadding; bool wasEnabled; wasEnabled = GUI.enabled; GUI.enabled = IsRevertEnabled; if (GUI.Button(new Rect(startX, startY, buttonWidth, buttonHeight), "Revert")) { ClickedProjectRevertButton(); } GUI.enabled = wasEnabled; startX = startX + buttonWidth + buttonPadding; wasEnabled = GUI.enabled; GUI.enabled = IsSaveEnabled; if (GUI.Button(new Rect(startX, startY, buttonWidth, buttonHeight), "Save")) { ClickedProjectSaveButton(); } GUI.enabled = wasEnabled; startX = startX + buttonWidth + buttonPadding; wasEnabled = GUI.enabled; GUI.enabled = IsEditEnabled; if (GUI.Button(new Rect(startX, startY, buttonWidth, buttonHeight), "Edit")) { ClickedProjectEditButton(); } GUI.enabled = wasEnabled; } public IEnumerator AlertUser(string message, string title = null) { return PromptForUserChoice(message, new[] { "Ok" }, title, null, 0, 0); } public IEnumerator<int> PromptForUserChoice( string question, string[] choices, string title = null, string styleOverride = null, int enterChoice = -1, int exitChoice = -1) { return CoRoutine.Wrap<int>( PromptForUserChoiceInternal(question, choices, title, styleOverride, enterChoice, exitChoice)); } public int AddPopup(Action<Rect> handler) { _popupIdCount++; int newId = _popupIdCount; Assert.That(_popupHandlers.Where(x => x.Id == newId).IsEmpty()); _popupHandlers.Add(new PopupInfo(newId, handler)); return newId; } public void RemovePopup(int id) { var info = _popupHandlers.Where(x => x.Id == id).Single(); _popupHandlers.RemoveWithConfirm(info); } public IEnumerator PromptForUserChoiceInternal( string question, string[] choices, string title = null, string styleOverride = null, int enterChoice = -1, int escapeChoice = -1) { int choice = -1; var skin = _pmSettings.GenericPromptDialog; var popupId = AddPopup(delegate(Rect fullRect) { GUILayout.BeginArea(fullRect); { GUILayout.FlexibleSpace(); GUILayout.BeginHorizontal(); { GUILayout.FlexibleSpace(); GUILayout.BeginVertical(skin.BackgroundStyle, GUILayout.Width(skin.PopupWidth)); { GUILayout.Space(skin.PanelPadding); GUILayout.BeginHorizontal(); { GUILayout.Space(skin.PanelPadding); GUILayout.BeginVertical(); { if (title != null) { GUILayout.Label(title, skin.TitleStyle); GUILayout.Space(skin.TitleBottomPadding); } GUILayout.Label(question, styleOverride == null ? skin.LabelStyle : GUI.skin.GetStyle(styleOverride)); GUILayout.Space(skin.ButtonTopPadding); GUILayout.BeginHorizontal(); { GUILayout.FlexibleSpace(); for (int i = 0; i < choices.Length; i++) { if (i > 0) { GUILayout.Space(skin.ButtonSpacing); } if (GUILayout.Button(choices[i], GUILayout.Width(skin.ButtonWidth))) { choice = i; } } GUILayout.FlexibleSpace(); } GUILayout.EndHorizontal(); } GUILayout.EndVertical(); GUILayout.Space(skin.PanelPadding); } GUILayout.EndHorizontal(); GUILayout.Space(skin.PanelPadding); } GUILayout.EndVertical(); GUILayout.FlexibleSpace(); } GUILayout.EndHorizontal(); GUILayout.FlexibleSpace(); } GUILayout.EndArea(); if (Event.current.type == EventType.KeyDown) { switch (Event.current.keyCode) { case KeyCode.Return: { if (enterChoice >= 0) { Assert.That(enterChoice <= choices.Length-1); choice = enterChoice; } break; } case KeyCode.Escape: { if (escapeChoice >= 0) { Assert.That(escapeChoice <= choices.Length-1); choice = escapeChoice; } break; } } } }); while (choice == -1) { yield return null; } RemovePopup(popupId); yield return choice; } public IEnumerator<string> PromptForInput(string label, string defaultValue) { string userInput = defaultValue; InputDialogStates state = InputDialogStates.None; bool isFirst = true; var popupId = AddPopup(delegate(Rect fullRect) { if (Event.current.type == EventType.KeyDown) { switch (Event.current.keyCode) { case KeyCode.Return: { state = InputDialogStates.Submitted; break; } case KeyCode.Escape: { state = InputDialogStates.Cancelled; break; } } } var popupRect = ImguiUtil.CenterRectInRect(fullRect, _pmSettings.InputDialog.PopupSize); DrawPopupCommon(fullRect, popupRect); var contentRect = ImguiUtil.CreateContentRectWithPadding( popupRect, _pmSettings.InputDialog.PanelPadding); GUILayout.BeginArea(contentRect); { GUILayout.Label(label, _pmSettings.InputDialog.LabelStyle); GUI.SetNextControlName("PopupTextField"); userInput = GUILayout.TextField(userInput, 100); GUI.SetNextControlName(""); GUILayout.Space(5); GUILayout.BeginHorizontal(); { GUILayout.FlexibleSpace(); if (GUILayout.Button("Submit", GUILayout.MaxWidth(100))) { state = InputDialogStates.Submitted; } if (GUILayout.Button("Cancel", GUILayout.MaxWidth(100))) { state = InputDialogStates.Cancelled; } } GUILayout.EndHorizontal(); } GUILayout.EndArea(); if (isFirst) { isFirst = false; // Need to remove focus then regain focus on the text box for it to select the whole contents GUI.FocusControl(""); } else if (string.IsNullOrEmpty(GUI.GetNameOfFocusedControl())) { GUI.FocusControl("PopupTextField"); } }); while (state == InputDialogStates.None) { yield return null; } RemovePopup(popupId); if (state == InputDialogStates.Submitted) { yield return userInput; } else { // Just return null } } public void OnGUI(Rect fullRect) { GUI.skin = _pmSettings.GUISkin; if (IsBlocked) { // Do not allow any input processing when running an async task GUI.enabled = false; } DrawArrowColumns(fullRect); var windowRect = Rect.MinMaxRect( _settings.ListVerticalSpacing + _settings.ArrowWidth, _settings.MarginTop, fullRect.width - _settings.ListVerticalSpacing - _settings.ArrowWidth, fullRect.height - _settings.MarginBottom); if (_split1 >= 0.1f) { DrawReleasePane(windowRect); } if (_split2 >= 0.1f) { DrawPackagesPane(windowRect); } if (_split2 <= 0.92f) { DrawProjectPane(windowRect); } GUI.enabled = true; if (IsBlocked) { if (ShowBlockedPopup || !_popupHandlers.IsEmpty()) { ImguiUtil.DrawColoredQuad(fullRect, _settings.Theme.LoadingOverlayColor); if (_popupHandlers.IsEmpty()) { DisplayGenericProcessingDialog(fullRect); } else { foreach (var info in _popupHandlers) { info.Handler(fullRect); } } } } } void DisplayGenericProcessingDialog(Rect fullRect) { var skin = _pmSettings.AsyncPopupPane; var popupRect = ImguiUtil.CenterRectInRect(fullRect, skin.PopupSize); DrawPopupCommon(fullRect, popupRect); var contentRect = ImguiUtil.CreateContentRectWithPadding( popupRect, skin.PanelPadding); GUILayout.BeginArea(contentRect); { string title; if (string.IsNullOrEmpty(BlockedStatusTitle)) { title = "Processing"; } else { title = BlockedStatusTitle; } GUILayout.Label(title, skin.HeadingTextStyle, GUILayout.ExpandWidth(true)); GUILayout.Space(skin.HeadingBottomPadding); string statusMessage = ""; if (!string.IsNullOrEmpty(BlockedStatusMessage)) { statusMessage = BlockedStatusMessage; int numExtraDots = (int)(Time.realtimeSinceStartup * skin.DotRepeatRate) % 4; statusMessage += new String('.', numExtraDots); // This is very hacky but the only way I can figure out how to keep the message a fixed length // so that the text doesn't jump around as the number of dots change // I tried using spaces instead of _ but that didn't work statusMessage += ImguiUtil.WrapWithColor(new String('_', 3 - numExtraDots), _settings.Theme.LoadingOverlapPopupColor); } GUILayout.Label(statusMessage, skin.StatusMessageTextStyle, GUILayout.ExpandWidth(true)); } GUILayout.EndArea(); } void DrawArrowColumns(Rect fullRect) { var halfHeight = 0.5f * fullRect.height; var rect1 = new Rect( _settings.ListVerticalSpacing, halfHeight - 0.5f * _settings.ArrowHeight, _settings.ArrowWidth, _settings.ArrowHeight); if ((int)ViewState > 0) { if (GUI.Button(rect1, "")) { ViewState = (PmViewStates)((int)ViewState - 1); } if (_settings.ArrowLeftTexture != null) { GUI.DrawTexture(new Rect(rect1.xMin + 0.5f * rect1.width - 0.5f * _settings.ArrowButtonIconWidth, rect1.yMin + 0.5f * rect1.height - 0.5f * _settings.ArrowButtonIconHeight, _settings.ArrowButtonIconWidth, _settings.ArrowButtonIconHeight), _settings.ArrowLeftTexture); } } var rect2 = new Rect(fullRect.xMax - _settings.ListVerticalSpacing - _settings.ArrowWidth, halfHeight - 0.5f * _settings.ArrowHeight, _settings.ArrowWidth, _settings.ArrowHeight); var numValues = Enum.GetValues(typeof(PmViewStates)).Length; if ((int)ViewState < numValues-1) { if (GUI.Button(rect2, "")) { ViewState = (PmViewStates)((int)ViewState + 1); } if (_settings.ArrowRightTexture != null) { GUI.DrawTexture(new Rect(rect2.xMin + 0.5f * rect2.width - 0.5f * _settings.ArrowButtonIconWidth, rect2.yMin + 0.5f * rect2.height - 0.5f * _settings.ArrowButtonIconHeight, _settings.ArrowButtonIconWidth, _settings.ArrowButtonIconHeight), _settings.ArrowRightTexture); } } } void DrawReleasePane(Rect windowRect) { var startX = windowRect.xMin; var endX = windowRect.xMin + _split1 * windowRect.width - _settings.ListVerticalSpacing; var startY = windowRect.yMin; var endY = windowRect.yMax; DrawReleasePane2(Rect.MinMaxRect(startX, startY, endX, endY)); } void DrawReleasePane2(Rect rect) { var startX = rect.xMin; var endX = rect.xMax; var startY = rect.yMin; var endY = startY + _settings.HeaderHeight; GUI.Label(Rect.MinMaxRect(startX, startY, endX, endY), "Releases", _settings.HeaderTextStyle); var skin = _pmSettings.ReleasesPane; startY = endY; endY = rect.yMax - _settings.ApplyButtonHeight - _settings.ApplyButtonTopPadding; GetList(DragListTypes.Release).Draw(Rect.MinMaxRect(startX, startY, endX, endY)); startY = endY + _settings.ApplyButtonTopPadding; endY = rect.yMax; if (GUI.Button(Rect.MinMaxRect(startX, startY, endX, endY), "Refresh")) { ClickedRefreshReleaseList(); } } void DrawVisualStudioPane(Rect windowRect) { var startX = windowRect.xMin + _split3 * windowRect.width + _settings.ListVerticalSpacing; var endX = windowRect.xMax - _settings.ListVerticalSpacing; var startY = windowRect.yMin + _settings.HeaderHeight + _settings.FileDropdownHeight + _settings.FileDropDownBottomPadding; var endY = windowRect.yMax; var rect = Rect.MinMaxRect(startX, startY, endX, endY); DrawVisualStudioPane2(rect); } void DrawVisualStudioPane2(Rect rect) { var startX = rect.xMin; var endX = rect.xMax; var startY = rect.yMin; var endY = startY + _settings.HeaderHeight; GUI.Label(Rect.MinMaxRect(startX, startY, endX, endY), "Visual Studio Solution", _settings.HeaderTextStyle); startY = endY + _settings.PackageDropdownBottomPadding; endY = rect.yMax - _settings.ApplyButtonHeight - _settings.ApplyButtonTopPadding; GetList(DragListTypes.VsSolution).Draw(Rect.MinMaxRect(startX, startY, endX, endY)); startY = endY + _settings.ApplyButtonTopPadding; endY = rect.yMax; var horizMiddle = 0.5f * (rect.xMax + rect.xMin); endX = horizMiddle - 0.5f * _pmSettings.PackagesPane.ButtonPadding; if (GUI.Button(Rect.MinMaxRect(startX, startY, endX, endY), "Update Solution")) { ClickedUpdateSolution(); } startX = endX + _pmSettings.PackagesPane.ButtonPadding; endX = rect.xMax; if (GUI.Button(Rect.MinMaxRect(startX, startY, endX, endY), "Open Solution")) { ClickedOpenSolution(); } } void DrawProjectPane(Rect windowRect) { var startX = windowRect.xMin + _split2 * windowRect.width + _settings.ListVerticalSpacing; var endX = windowRect.xMax - _settings.ListVerticalSpacing; var startY = windowRect.yMin; var endY = windowRect.yMax; var headerRect = Rect.MinMaxRect(startX, startY, endX, endY); endX = windowRect.xMin + _split3 * windowRect.width - _settings.ListVerticalSpacing; var contentRect = Rect.MinMaxRect(startX, startY, endX, endY); DrawProjectPane2(headerRect, contentRect); if (_split3 <= 0.92f) { DrawVisualStudioPane(windowRect); } } void DrawProjectPane2(Rect headerRect, Rect contentRect) { var startY = headerRect.yMin; var endY = startY + _settings.HeaderHeight; GUI.Label(Rect.MinMaxRect(headerRect.xMin, startY, headerRect.xMax, endY), "Project", _settings.HeaderTextStyle); startY = endY; endY = startY + _settings.FileDropdownHeight; DrawFileDropdown(Rect.MinMaxRect(headerRect.xMin, startY, headerRect.xMax, endY)); startY = endY + _settings.FileDropDownBottomPadding; endY = startY + _settings.HeaderHeight; GUI.Label(Rect.MinMaxRect(contentRect.xMin, startY, contentRect.xMax, endY), "Assets Folder", _settings.HeaderTextStyle); startY = endY + _settings.PackageDropdownBottomPadding; endY = contentRect.yMax - _settings.ApplyButtonHeight - _settings.ApplyButtonTopPadding; DrawProjectPane3(Rect.MinMaxRect(contentRect.xMin, startY, contentRect.xMax, endY)); startY = endY + _settings.ApplyButtonTopPadding; endY = contentRect.yMax; DrawProjectButtons(Rect.MinMaxRect(contentRect.xMin, startY, contentRect.xMax, endY)); } void DrawProjectPane3(Rect listRect) { var halfHeight = 0.5f * listRect.height; var rect1 = new Rect(listRect.x, listRect.y, listRect.width, halfHeight - 0.5f * _settings.ListHorizontalSpacing); var rect2 = new Rect(listRect.x, listRect.y + halfHeight + 0.5f * _settings.ListHorizontalSpacing, listRect.width, listRect.height - halfHeight - 0.5f * _settings.ListHorizontalSpacing); GetList(DragListTypes.AssetItem).Draw(rect1); GetList(DragListTypes.PluginItem).Draw(rect2); GUI.Label(Rect.MinMaxRect(rect1.xMin, rect1.yMax, rect1.xMax, rect2.yMin), "Plugins Folder", _settings.HeaderTextStyle); } void DrawPackagesPane(Rect windowRect) { var startX = windowRect.xMin + _split1 * windowRect.width + _settings.ListVerticalSpacing; var endX = windowRect.xMin + _split2 * windowRect.width - _settings.ListVerticalSpacing; var startY = windowRect.yMin; var endY = windowRect.yMax; DrawPackagesPane2(Rect.MinMaxRect(startX, startY, endX, endY)); } void DrawPackagesPane2(Rect rect) { var startX = rect.xMin; var endX = rect.xMax; var startY = rect.yMin; var endY = startY + _settings.HeaderHeight; GUI.Label(Rect.MinMaxRect(startX, startY, endX, endY), "Packages", _settings.HeaderTextStyle); startY = endY; endY = startY + _settings.FileDropdownHeight; DrawPackageFolderDropdown( Rect.MinMaxRect(startX, startY, endX, endY)); startY = endY + _settings.PackageDropdownBottomPadding; endY = rect.yMax - _settings.ApplyButtonHeight - _settings.ApplyButtonTopPadding; GetList(DragListTypes.Package).Draw(Rect.MinMaxRect(startX, startY, endX, endY)); startY = endY + _settings.ApplyButtonTopPadding; endY = rect.yMax; var horizMiddle = 0.5f * (rect.xMax + rect.xMin); endX = horizMiddle - 0.5f * _pmSettings.PackagesPane.ButtonPadding; if (GUI.Button(Rect.MinMaxRect(startX, startY, endX, endY), "Refresh")) { ClickedRefreshPackages(); } startX = endX + _pmSettings.PackagesPane.ButtonPadding; endX = rect.xMax; if (GUI.Button(Rect.MinMaxRect(startX, startY, endX, endY), "New")) { ClickedCreateNewPackage(); } } void DrawPackageFolderDropdown(Rect dropDownRect) { var displayValues = _model.PackageFolderPaths.ToArray(); int selectedIndex = EditorGUI.Popup(dropDownRect, _model.PackageFolderIndex, displayValues, _settings.DropdownTextStyle); if (displayValues.Length == 0) { GUI.Button(dropDownRect, "(empty)", _settings.DropdownTextButtonStyle); } else { GUI.Button(dropDownRect, displayValues[selectedIndex], _settings.DropdownTextButtonStyle); if (selectedIndex != _model.PackageFolderIndex) { ClickedPackageFolder(selectedIndex); } GUI.DrawTexture( new Rect(dropDownRect.xMax - _settings.ArrowSize.x + _settings.ArrowOffset.x, dropDownRect.yMin + _settings.ArrowOffset.y, _settings.ArrowSize.x, _settings.ArrowSize.y), _settings.FileDropdownArrow); } } void DrawProjectButtons(Rect rect) { var halfWidth = rect.width * 0.5f; var padding = 0.5f * _settings.ProjectButtonsPadding; var buttonWidth = 0.7f * rect.width; if (GUI.Button(new Rect(rect.x + halfWidth - 0.5f * buttonWidth, rect.y, buttonWidth, rect.height), "Update Directories")) { ClickedProjectApplyButton(); } } public enum InputDialogStates { None, Cancelled, Submitted } class PopupInfo { public readonly int Id; public readonly Action<Rect> Handler; public PopupInfo(int id, Action<Rect> handler) { Id = id; Handler = handler; } } // View data that needs to be saved and restored [Serializable] public class Model { public int PackageFolderIndex = 0; public List<string> PackageFolderPaths = new List<string>(); public PmViewStates ViewState = PmViewStates.Project; public ProjectConfigTypes ProjectConfigType = ProjectConfigTypes.LocalProject; public List<DragList.Model> ListModels = new List<DragList.Model>(); } [Serializable] public class Settings { public float InterpSpeed; public float ProcessingPopupDelayTime; public float HeaderHeight; public float ListVerticalSpacing; public float ListHorizontalSpacing; public float MarginTop; public float MarginBottom; public float ArrowWidth; public float ArrowHeight; public float FileButtonsPadding; public float FileButtonsPercentWidth; public float ApplyButtonHeight; public float ApplyButtonTopPadding; public float ProjectButtonsPadding; public float PackageDropdownBottomPadding; public float FileDropdownHeight; public float FileDropDownBottomPadding; public Texture2D FileDropdownArrow; public float ArrowButtonIconWidth; public float ArrowButtonIconHeight; public Texture2D ArrowLeftTexture; public Texture2D ArrowRightTexture; public Vector2 ArrowSize; public Vector2 ArrowOffset; public ThemeProperties Light; public ThemeProperties Dark; public ThemeProperties Theme { get { return EditorGUIUtility.isProSkin ? Dark : Light; } } [Serializable] public class ThemeProperties { public Color VersionColor; public Color LoadingOverlayColor; public Color LoadingOverlapPopupColor; public Color DraggableItemAlreadyAddedColor; public GUIStyle DropdownTextStyle; public GUIStyle HeaderTextStyle; } public GUIStyle HeaderTextStyle { get { return GUI.skin.GetStyle("HeaderTextStyle"); } } public GUIStyle DropdownTextStyle { get { return GUI.skin.GetStyle("DropdownTextStyle"); } } public GUIStyle DropdownTextButtonStyle { get { return GUI.skin.GetStyle("DropdownTextButtonStyle"); } } } } }
using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.Dnx.Compilation; using Microsoft.Dnx.Compilation.Caching; using Microsoft.Dnx.Compilation.CSharp; using Microsoft.Dnx.Runtime; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Syntax; using System.Globalization; using System.Xml.Linq; using Srclib.Nuget.Documentation; using Newtonsoft.Json; namespace Srclib.Nuget.Graph { /// <summary> /// C# syntax walker that produces graph output. /// </summary> public class GraphRunner : CSharpSyntaxWalker { readonly Output _output = new Output(); readonly List<Tuple<SyntaxToken, ISymbol, string>> _refs = new List<Tuple<SyntaxToken, ISymbol, string>>(); readonly HashSet<ISymbol> _defined = new HashSet<ISymbol>(); readonly HashSet<string> keys = new HashSet<string>(); readonly static Dictionary<string, string> dllToProjectUrl = new Dictionary<string, string>(); readonly static Dictionary<string, string> projectUrlToRepo = new Dictionary<string, string>(); SemanticModel _sm; string _path; private GraphRunner() : base(SyntaxWalkerDepth.Token) { projectUrlToRepo["http://www.newtonsoft.com/json"] = "github.com/JamesNK/Newtonsoft.Json"; projectUrlToRepo["http://autofac.org/"] = "github.com/autofac/Autofac"; projectUrlToRepo["http://msdn.com/roslyn"] = "github.com/dotnet/roslyn"; // multiple dlls from different repositories have www.asp.net as projectUrl // so we probably need a multimap here // TODO($ildarisaev): implement a correct mapping for all dlls projectUrlToRepo["http://www.asp.net/"] = "github.com/aspnet/dnx"; } /// <summary> /// Add a definition to the output. /// Also adds a ref to the def, and /// potentially a doc. /// </summary> /// <param name="def">The def to add.</param> /// <param name="symbol">The symbol the def was created from.</param> void AddDef(Def def, Doc doc = null) { string key = def.DefKey; if (!keys.Contains(key)) { keys.Add(key); var r = Ref.AtDef(def); _output.Defs.Add(def); _output.Refs.Add(r); if (doc != null) { doc.UnitType = r.DefUnitType; doc.Unit = r.DefUnit; doc.Path = r.DefPath; _output.Docs.Add(doc); } } } /// <summary> /// Scan a collection of resolved tokens and generate a ref for all /// tokens that have a corresponding def or set up a link to external repo /// </summary> void RunTokens() { foreach(var r in _refs) { try { var token = r.Item1; var definition = r.Item2; var file = r.Item3; if (_defined.Contains(definition)) { var reference = Ref.To(definition).At(file, token.Span); _output.Refs.Add(reference); } else { _defined.Add(definition); var reference = Ref.To(definition).At(file, token.Span); if ((definition.ContainingAssembly != null) && (definition.ContainingAssembly.Identity != null) && (definition.ContainingAssembly.Identity.Name != null)) { if (dllToProjectUrl.ContainsKey(definition.ContainingAssembly.Identity.Name + ".dll")) { string url = dllToProjectUrl[definition.ContainingAssembly.Identity.Name + ".dll"]; if (projectUrlToRepo.ContainsKey(url)) { url = projectUrlToRepo[url]; } // Sourcegraph needs to clone a repo, so filter out non cloneable urls // Currently consider only github urls as cloneable // TODO($ildarisaev): think of a more sophisticated check if (url.IndexOf("github.com") != -1) { reference.DefRepo = url; reference.DefUnit = definition.ContainingAssembly.Identity.Name; reference.DefUnitType = "NugetPackage"; } } } _output.Refs.Add(reference); } } catch (Exception e) { } } } internal static void HandleNuspec(string path, string dll) { DirectoryInfo di = new DirectoryInfo(path); string nuspec = DepresolveConsoleCommand.FindNuspec(di); if (nuspec != null) { var content = File.ReadAllText(nuspec); int i = content.IndexOf("<projectUrl>"); if (i != -1) { int j = content.IndexOf("</projectUrl>"); string projectUrl = content.Substring(i + 12, j - i - 12); dllToProjectUrl[dll + ".dll"] = projectUrl; } } } internal static async Task<Output> Graph(GraphContext context) { if (context.Project == null) { Project project; if (!Project.TryGetProject(context.ProjectDirectory, out project)) { //not a DNX project DirectoryInfo di = new DirectoryInfo(context.ProjectDirectory); FileInfo[] fis = DepresolveConsoleCommand.FindSources(di); string[] files = new string[fis.Length]; for (int i = 0; i < fis.Length; i++) { files[i] = fis[i].FullName; } Microsoft.CodeAnalysis.Text.SourceText[] sources = new Microsoft.CodeAnalysis.Text.SourceText[files.Length]; SyntaxTree[] trees = new SyntaxTree[files.Length]; Dictionary<SyntaxTree, string> dict = new Dictionary<SyntaxTree, string>(); var compilation = CSharpCompilation.Create("name"); for (int i = 0; i < files.Length; i++) { try { sources[i] = Microsoft.CodeAnalysis.Text.SourceText.From(new FileStream(files[i], FileMode.Open)); trees[i] = CSharpSyntaxTree.ParseText(sources[i]); if (trees[i] != null) { compilation = compilation.AddSyntaxTrees(trees[i]); dict[trees[i]] = files[i]; } } catch (Exception e) { } } var gr = new GraphRunner(); foreach (var st in compilation.SyntaxTrees) { var path = dict[st]; if (!string.IsNullOrWhiteSpace(path)) { path = Utils.GetRelativePath(path, context.ProjectDirectory); if (!string.IsNullOrWhiteSpace(path) && (path.Substring(0, 3) != ".." + Path.DirectorySeparatorChar) && !path.Equals("file://applyprojectinfo.cs/")) { // this is a source code file we want to grap gr._sm = compilation.GetSemanticModel(st, false); gr._path = path; var root = await st.GetRootAsync(); gr.Visit(root); } } } gr._sm = null; gr._path = null; gr.RunTokens(); return gr._output; } context.Project = project; } context.ApplicationHostContext = new ApplicationHostContext { ProjectDirectory = context.ProjectDirectory, Project = context.Project, TargetFramework = context.Project.GetTargetFrameworks().First().FrameworkName }; context.ApplicationEnvironment = new ApplicationEnvironment( context.Project, context.ApplicationHostContext.TargetFramework, "Debug", context.HostEnvironment); context.CompilationContext = new CompilationEngineContext(context.ApplicationEnvironment, context.RuntimeEnvironment, context.LoadContextAccessor.Default, new CompilationCache()); context.CompilationEngine = new CompilationEngine(context.CompilationContext); context.LibraryExporter = context.CompilationEngine.CreateProjectExporter(context.Project, context.ApplicationHostContext.TargetFramework, "Debug"); context.Export = context.LibraryExporter.GetExport(context.Project.Name); if (!(context.Export.MetadataReferences[0] is IRoslynMetadataReference)) { return new Output(); } var roslynRef = (IRoslynMetadataReference)context.Export.MetadataReferences[0]; var compilationRef = (CompilationReference)roslynRef.MetadataReference; var csCompilation = (CSharpCompilation)compilationRef.Compilation; context.Compilation = csCompilation; IEnumerable<LibraryDescription> deps = DepresolveConsoleCommand.DepResolve(context.Project); HashSet<PortableExecutableReference> libs = new HashSet<PortableExecutableReference>(); try { libs.Add(MetadataReference.CreateFromFile("/opt/DNX_BRANCH/runtimes/dnx-coreclr-linux-x64.1.0.0-rc1-update1/bin/mscorlib.dll")); } catch (Exception e) { } foreach (LibraryDescription ld in deps) { PortableExecutableReference r = null; try { string path = ""; if (ld.Path.EndsWith("project.json") && (ld.Path.IndexOf("wrap") != -1)) { if (File.Exists(ld.Path)) { var content = File.ReadAllText(ld.Path); var spec = JsonConvert.DeserializeObject<Wrap>(content); path = ld.Path.Substring(0, ld.Path.Length - 12) + spec.frameworks.net451.bin.assembly; } } else { DirectoryInfo di = new DirectoryInfo(ld.Path); path = DepresolveConsoleCommand.FindDll(di, ld.Identity.Name); HandleNuspec(ld.Path, ld.Identity.Name); } r = MetadataReference.CreateFromFile(path); } catch (Exception e) { try { string name = ld.Identity.Name; string path = ld.Path; string cd = path.Substring(0, path.LastIndexOf('/')); DirectoryInfo di = new DirectoryInfo(cd); string newpath = DepresolveConsoleCommand.FindDll(di, ld.Identity.Name); HandleNuspec(cd, ld.Identity.Name); r = MetadataReference.CreateFromFile(newpath); } catch (Exception ee) { } } if (r != null) { libs.Add(r); } } context.Compilation = context.Compilation.WithReferences(libs); var runner = new GraphRunner(); foreach (var st in context.Compilation.SyntaxTrees) { var path = st.FilePath; if (!string.IsNullOrWhiteSpace(path)) { path = Utils.GetRelativePath(path, context.RootPath); if (!string.IsNullOrWhiteSpace(path) && (path.Substring(0, 3) != ".." + Path.DirectorySeparatorChar) && !path.Equals("file://applyprojectinfo.cs/")) { // this is a source code file we want to grap runner._sm = context.Compilation.GetSemanticModel(st, false); runner._path = path; var root = await st.GetRootAsync(); runner.Visit(root); } } } runner._sm = null; runner._path = null; runner.RunTokens(); return runner._output; } /// <summary> /// Traverse AST node that represents class declaration /// </summary> /// <param name="node">AST node.</param> public override void VisitClassDeclaration(ClassDeclarationSyntax node) { try { if (!node.Identifier.Span.IsEmpty) { var symbol = _sm.GetDeclaredSymbol(node); // Classes can be partial, however, currently, srclib only support one definition per symbol if (!_defined.Contains(symbol)) { _defined.Add(symbol); var def = Def.For(symbol: symbol, type: "class", name: symbol.Name).At(_path, node.Identifier.Span); if (symbol.IsExported()) { def.Exported = true; } AddDef(def, DocProcessor.ForClass(symbol)); } } base.VisitClassDeclaration(node); } catch (Exception e) { } } /// <summary> /// Traverse AST node that represents interface declaration /// </summary> /// <param name="node">AST node.</param> public override void VisitInterfaceDeclaration(InterfaceDeclarationSyntax node) { try { if (!node.Identifier.Span.IsEmpty) { var symbol = _sm.GetDeclaredSymbol(node); // Interfaces can be partial as well: this is a problem if (!_defined.Contains(symbol)) { _defined.Add(symbol); var def = Def.For(symbol: symbol, type: "interface", name: symbol.Name).At(_path, node.Identifier.Span); if (symbol.IsExported()) { def.Exported = true; } AddDef(def, DocProcessor.ForClass(symbol)); } } base.VisitInterfaceDeclaration(node); } catch (Exception e) { } } /// <summary> /// Traverse AST node that represents struct declaration /// </summary> /// <param name="node">AST node.</param> public override void VisitStructDeclaration(StructDeclarationSyntax node) { try { if (!node.Identifier.Span.IsEmpty) { var symbol = _sm.GetDeclaredSymbol(node); // Structs can also be partial if (!_defined.Contains(symbol)) { _defined.Add(symbol); var def = Def.For(symbol: symbol, type: "struct", name: symbol.Name).At(_path, node.Identifier.Span); if (symbol.IsExported()) { def.Exported = true; } AddDef(def, DocProcessor.ForClass(symbol)); } } base.VisitStructDeclaration(node); } catch (Exception e) { } } /// <summary> /// Traverse AST node that represents enumeration declaration /// </summary> /// <param name="node">AST node.</param> public override void VisitEnumDeclaration(EnumDeclarationSyntax node) { try { if (!node.Identifier.Span.IsEmpty) { var symbol = _sm.GetDeclaredSymbol(node); if (!_defined.Contains(symbol)) { _defined.Add(symbol); var def = Def.For(symbol: symbol, type: "enum", name: symbol.Name).At(_path, node.Identifier.Span); if (symbol.IsExported()) { def.Exported = true; } AddDef(def, DocProcessor.ForClass(symbol)); } } base.VisitEnumDeclaration(node); } catch (Exception e) { } } /// <summary> /// Traverse AST node that represents enumeration constant declaration /// </summary> /// <param name="node">AST node.</param> public override void VisitEnumMemberDeclaration(EnumMemberDeclarationSyntax node) { try { if (!node.Identifier.Span.IsEmpty) { var symbol = _sm.GetDeclaredSymbol(node); if (!_defined.Contains(symbol)) { _defined.Add(symbol); var def = Def.For(symbol: symbol, type: "enum field", name: symbol.Name).At(_path, node.Identifier.Span); def.Exported = true; AddDef(def); } } base.VisitEnumMemberDeclaration(node); } catch (Exception e) { } } /// <summary> /// Traverse AST node that represents method declaration /// </summary> /// <param name="node">AST node.</param> public override void VisitMethodDeclaration(MethodDeclarationSyntax node) { try { if (!node.Identifier.Span.IsEmpty) { var symbol = _sm.GetDeclaredSymbol(node); _defined.Add(symbol); var def = Def.For(symbol: symbol, type: "method", name: symbol.Name).At(_path, node.Identifier.Span); if (symbol.IsExported()) { def.Exported = true; } AddDef(def, DocProcessor.ForMethod(symbol)); } base.VisitMethodDeclaration(node); } catch (Exception e) { } } /// <summary> /// Traverse AST node that represents constructor declaration /// </summary> /// <param name="node">AST node.</param> public override void VisitConstructorDeclaration(ConstructorDeclarationSyntax node) { try { if (!node.Identifier.Span.IsEmpty) { var symbol = _sm.GetDeclaredSymbol(node); _defined.Add(symbol); var def = Def.For(symbol: symbol, type: "ctor", name: symbol.Name).At(_path, node.Identifier.Span); if (symbol.IsExported()) { def.Exported = true; } AddDef(def); } base.VisitConstructorDeclaration(node); } catch (Exception e) { } } /// <summary> /// Traverse AST node that represents property declaration /// </summary> /// <param name="node">AST node.</param> public override void VisitPropertyDeclaration(PropertyDeclarationSyntax node) { try { if (!node.Identifier.Span.IsEmpty) { var symbol = _sm.GetDeclaredSymbol(node); _defined.Add(symbol); var def = Def.For(symbol: symbol, type: "property", name: symbol.Name).At(_path, node.Identifier.Span); if (symbol.IsExported()) { def.Exported = true; } AddDef(def); } base.VisitPropertyDeclaration(node); } catch (Exception e) { } } /// <summary> /// Traverse AST node that represents event declaration /// </summary> /// <param name="node">AST node.</param> public override void VisitEventDeclaration(EventDeclarationSyntax node) { try { if (!node.Identifier.Span.IsEmpty) { var symbol = _sm.GetDeclaredSymbol(node); _defined.Add(symbol); var def = Def.For(symbol: symbol, type: "event", name: symbol.Name).At(_path, node.Identifier.Span); if (symbol.IsExported()) { def.Exported = true; } AddDef(def); } base.VisitEventDeclaration(node); } catch (Exception e) { } } /// <summary> /// Traverse AST node that represents method or constructor parameter /// </summary> /// <param name="node">AST node.</param> public override void VisitParameter(ParameterSyntax node) { try { if (!node.Identifier.Span.IsEmpty) { var symbol = _sm.GetDeclaredSymbol(node); _defined.Add(symbol); var def = Def.For(symbol: symbol, type: "param", name: symbol.Name).At(_path, node.Identifier.Span); def.Local = true; AddDef(def); } base.VisitParameter(node); } catch (Exception e) { } } /// <summary> /// Traverse AST node that represents type parameter (in generic declarations) /// </summary> /// <param name="node">AST node.</param> public override void VisitTypeParameter(TypeParameterSyntax node) { try { if (!node.Identifier.Span.IsEmpty) { var symbol = _sm.GetDeclaredSymbol(node); _defined.Add(symbol); var def = Def.For(symbol: symbol, type: "typeparam", name: symbol.Name).At(_path, node.Identifier.Span); def.Local = true; AddDef(def); } base.VisitTypeParameter(node); } catch (Exception e) { } } /// <summary> /// Traverse AST node that represents field and variable declarations /// </summary> /// <param name="node">AST node.</param> public override void VisitVariableDeclarator(VariableDeclaratorSyntax node) { try { if (!node.Identifier.Span.IsEmpty) { var symbol = _sm.GetDeclaredSymbol(node); _defined.Add(symbol); string type; bool local = false; bool exported = false; if (symbol is ILocalSymbol) { type = "local"; local = true; } else if (symbol is IFieldSymbol) { type = "field"; exported = symbol.IsExported(); if (((IFieldSymbol)symbol).IsConst) { type = "const"; } } else { goto skip; } var def = Def.For(symbol: symbol, type: type, name: symbol.Name).At(_path, node.Identifier.Span); def.Local = local; def.Exported = exported; AddDef(def); } skip: base.VisitVariableDeclarator(node); } catch (Exception e) { } } /// <summary> /// If a token is resolved by parser, add a token to collection of resolved tokens /// </summary> /// <param name="token">token to check</param> public override void VisitToken(SyntaxToken token) { try { if (token.IsKind(SyntaxKind.IdentifierToken) || token.IsKind(SyntaxKind.IdentifierName)) { var node = token.Parent; if (node == null) { goto skip; } var symbol = _sm.GetSymbolInfo(node); if (symbol.Symbol == null) { if (symbol.CandidateSymbols.Length > 0) { var definition = symbol.CandidateSymbols[0].OriginalDefinition; if (definition != null) { _refs.Add(Tuple.Create(token, definition, _path)); } } else { goto skip; } } else { var definition = symbol.Symbol.OriginalDefinition; if (definition != null) { _refs.Add(Tuple.Create(token, definition, _path)); } } } skip: base.VisitToken(token); } catch (Exception e) { } } } class Wrap { [JsonProperty] public string version; [JsonProperty] public Framework frameworks; } class Framework { [JsonProperty] public Net451 net451; } class Net451 { [JsonProperty] public Bin bin; } class Bin { [JsonProperty] public string assembly; } }
// Generated by ProtoGen, Version=2.4.1.555, Culture=neutral, PublicKeyToken=55f7125234beb589. DO NOT EDIT! #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.ProtocolBuffers; using pbc = global::Google.ProtocolBuffers.Collections; using pbd = global::Google.ProtocolBuffers.Descriptors; using scg = global::System.Collections.Generic; namespace Google.ProtocolBuffers.Examples.AddressBook { [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public static partial class AddressBookProtos { #region Extension registration public static void RegisterAllExtensions(pb::ExtensionRegistry registry) { } #endregion #region Static variables internal static pbd::MessageDescriptor internal__static_tutorial_Person__Descriptor; internal static pb::FieldAccess.FieldAccessorTable<global::Google.ProtocolBuffers.Examples.AddressBook.Person, global::Google.ProtocolBuffers.Examples.AddressBook.Person.Builder> internal__static_tutorial_Person__FieldAccessorTable; internal static pbd::MessageDescriptor internal__static_tutorial_Person_PhoneNumber__Descriptor; internal static pb::FieldAccess.FieldAccessorTable<global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneNumber, global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneNumber.Builder> internal__static_tutorial_Person_PhoneNumber__FieldAccessorTable; internal static pbd::MessageDescriptor internal__static_tutorial_AddressBook__Descriptor; internal static pb::FieldAccess.FieldAccessorTable<global::Google.ProtocolBuffers.Examples.AddressBook.AddressBook, global::Google.ProtocolBuffers.Examples.AddressBook.AddressBook.Builder> internal__static_tutorial_AddressBook__FieldAccessorTable; #endregion #region Descriptor public static pbd::FileDescriptor Descriptor { get { return descriptor; } } private static pbd::FileDescriptor descriptor; static AddressBookProtos() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "Chp0dXRvcmlhbC9hZGRyZXNzYm9vay5wcm90bxIIdHV0b3JpYWwaJGdvb2ds", "ZS9wcm90b2J1Zi9jc2hhcnBfb3B0aW9ucy5wcm90byLaAQoGUGVyc29uEgwK", "BG5hbWUYASACKAkSCgoCaWQYAiACKAUSDQoFZW1haWwYAyABKAkSKwoFcGhv", "bmUYBCADKAsyHC50dXRvcmlhbC5QZXJzb24uUGhvbmVOdW1iZXIaTQoLUGhv", "bmVOdW1iZXISDgoGbnVtYmVyGAEgAigJEi4KBHR5cGUYAiABKA4yGi50dXRv", "cmlhbC5QZXJzb24uUGhvbmVUeXBlOgRIT01FIisKCVBob25lVHlwZRIKCgZN", "T0JJTEUQABIICgRIT01FEAESCAoEV09SSxACIi8KC0FkZHJlc3NCb29rEiAK", "BnBlcnNvbhgBIAMoCzIQLnR1dG9yaWFsLlBlcnNvbkJFSAHCPkAKK0dvb2ds", "ZS5Qcm90b2NvbEJ1ZmZlcnMuRXhhbXBsZXMuQWRkcmVzc0Jvb2sSEUFkZHJl", "c3NCb29rUHJvdG9z")); pbd::FileDescriptor.InternalDescriptorAssigner assigner = delegate(pbd::FileDescriptor root) { descriptor = root; internal__static_tutorial_Person__Descriptor = Descriptor.MessageTypes[0]; internal__static_tutorial_Person__FieldAccessorTable = new pb::FieldAccess.FieldAccessorTable<global::Google.ProtocolBuffers.Examples.AddressBook.Person, global::Google.ProtocolBuffers.Examples.AddressBook.Person.Builder>(internal__static_tutorial_Person__Descriptor, new string[] { "Name", "Id", "Email", "Phone", }); internal__static_tutorial_Person_PhoneNumber__Descriptor = internal__static_tutorial_Person__Descriptor.NestedTypes[0]; internal__static_tutorial_Person_PhoneNumber__FieldAccessorTable = new pb::FieldAccess.FieldAccessorTable<global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneNumber, global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneNumber.Builder>(internal__static_tutorial_Person_PhoneNumber__Descriptor, new string[] { "Number", "Type", }); internal__static_tutorial_AddressBook__Descriptor = Descriptor.MessageTypes[1]; internal__static_tutorial_AddressBook__FieldAccessorTable = new pb::FieldAccess.FieldAccessorTable<global::Google.ProtocolBuffers.Examples.AddressBook.AddressBook, global::Google.ProtocolBuffers.Examples.AddressBook.AddressBook.Builder>(internal__static_tutorial_AddressBook__Descriptor, new string[] { "Person", }); pb::ExtensionRegistry registry = pb::ExtensionRegistry.CreateInstance(); RegisterAllExtensions(registry); global::Google.ProtocolBuffers.DescriptorProtos.CSharpOptions.RegisterAllExtensions(registry); return registry; }; pbd::FileDescriptor.InternalBuildGeneratedFileFrom(descriptorData, new pbd::FileDescriptor[] { global::Google.ProtocolBuffers.DescriptorProtos.CSharpOptions.Descriptor, }, assigner); } #endregion } #region Messages [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class Person : pb::GeneratedMessage<Person, Person.Builder> { private Person() { } private static readonly Person defaultInstance = new Person().MakeReadOnly(); private static readonly string[] _personFieldNames = new string[] { "email", "id", "name", "phone" }; private static readonly uint[] _personFieldTags = new uint[] { 26, 16, 10, 34 }; public static Person DefaultInstance { get { return defaultInstance; } } public override Person DefaultInstanceForType { get { return DefaultInstance; } } protected override Person ThisMessage { get { return this; } } public static pbd::MessageDescriptor Descriptor { get { return global::Google.ProtocolBuffers.Examples.AddressBook.AddressBookProtos.internal__static_tutorial_Person__Descriptor; } } protected override pb::FieldAccess.FieldAccessorTable<Person, Person.Builder> InternalFieldAccessors { get { return global::Google.ProtocolBuffers.Examples.AddressBook.AddressBookProtos.internal__static_tutorial_Person__FieldAccessorTable; } } #region Nested types [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public static partial class Types { public enum PhoneType { MOBILE = 0, HOME = 1, WORK = 2, } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class PhoneNumber : pb::GeneratedMessage<PhoneNumber, PhoneNumber.Builder> { private PhoneNumber() { } private static readonly PhoneNumber defaultInstance = new PhoneNumber().MakeReadOnly(); private static readonly string[] _phoneNumberFieldNames = new string[] { "number", "type" }; private static readonly uint[] _phoneNumberFieldTags = new uint[] { 10, 16 }; public static PhoneNumber DefaultInstance { get { return defaultInstance; } } public override PhoneNumber DefaultInstanceForType { get { return DefaultInstance; } } protected override PhoneNumber ThisMessage { get { return this; } } public static pbd::MessageDescriptor Descriptor { get { return global::Google.ProtocolBuffers.Examples.AddressBook.AddressBookProtos.internal__static_tutorial_Person_PhoneNumber__Descriptor; } } protected override pb::FieldAccess.FieldAccessorTable<PhoneNumber, PhoneNumber.Builder> InternalFieldAccessors { get { return global::Google.ProtocolBuffers.Examples.AddressBook.AddressBookProtos.internal__static_tutorial_Person_PhoneNumber__FieldAccessorTable; } } public const int NumberFieldNumber = 1; private bool hasNumber; private string number_ = ""; public bool HasNumber { get { return hasNumber; } } public string Number { get { return number_; } } public const int TypeFieldNumber = 2; private bool hasType; private global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneType type_ = global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneType.HOME; public bool HasType { get { return hasType; } } public global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneType Type { get { return type_; } } public override bool IsInitialized { get { if (!hasNumber) return false; return true; } } public override void WriteTo(pb::ICodedOutputStream output) { CalcSerializedSize(); string[] field_names = _phoneNumberFieldNames; if (hasNumber) { output.WriteString(1, field_names[0], Number); } if (hasType) { output.WriteEnum(2, field_names[1], (int) Type, Type); } UnknownFields.WriteTo(output); } private int memoizedSerializedSize = -1; public override int SerializedSize { get { int size = memoizedSerializedSize; if (size != -1) return size; return CalcSerializedSize(); } } private int CalcSerializedSize() { int size = memoizedSerializedSize; if (size != -1) return size; size = 0; if (hasNumber) { size += pb::CodedOutputStream.ComputeStringSize(1, Number); } if (hasType) { size += pb::CodedOutputStream.ComputeEnumSize(2, (int) Type); } size += UnknownFields.SerializedSize; memoizedSerializedSize = size; return size; } public static PhoneNumber ParseFrom(pb::ByteString data) { return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed(); } public static PhoneNumber ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed(); } public static PhoneNumber ParseFrom(byte[] data) { return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed(); } public static PhoneNumber ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed(); } public static PhoneNumber ParseFrom(global::System.IO.Stream input) { return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed(); } public static PhoneNumber ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed(); } public static PhoneNumber ParseDelimitedFrom(global::System.IO.Stream input) { return CreateBuilder().MergeDelimitedFrom(input).BuildParsed(); } public static PhoneNumber ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) { return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed(); } public static PhoneNumber ParseFrom(pb::ICodedInputStream input) { return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed(); } public static PhoneNumber ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed(); } private PhoneNumber MakeReadOnly() { return this; } public static Builder CreateBuilder() { return new Builder(); } public override Builder ToBuilder() { return CreateBuilder(this); } public override Builder CreateBuilderForType() { return new Builder(); } public static Builder CreateBuilder(PhoneNumber prototype) { return new Builder(prototype); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class Builder : pb::GeneratedBuilder<PhoneNumber, Builder> { protected override Builder ThisBuilder { get { return this; } } public Builder() { result = DefaultInstance; resultIsReadOnly = true; } internal Builder(PhoneNumber cloneFrom) { result = cloneFrom; resultIsReadOnly = true; } private bool resultIsReadOnly; private PhoneNumber result; private PhoneNumber PrepareBuilder() { if (resultIsReadOnly) { PhoneNumber original = result; result = new PhoneNumber(); resultIsReadOnly = false; MergeFrom(original); } return result; } public override bool IsInitialized { get { return result.IsInitialized; } } protected override PhoneNumber MessageBeingBuilt { get { return PrepareBuilder(); } } public override Builder Clear() { result = DefaultInstance; resultIsReadOnly = true; return this; } public override Builder Clone() { if (resultIsReadOnly) { return new Builder(result); } else { return new Builder().MergeFrom(result); } } public override pbd::MessageDescriptor DescriptorForType { get { return global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneNumber.Descriptor; } } public override PhoneNumber DefaultInstanceForType { get { return global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneNumber.DefaultInstance; } } public override PhoneNumber BuildPartial() { if (resultIsReadOnly) { return result; } resultIsReadOnly = true; return result.MakeReadOnly(); } public override Builder MergeFrom(pb::IMessage other) { if (other is PhoneNumber) { return MergeFrom((PhoneNumber) other); } else { base.MergeFrom(other); return this; } } public override Builder MergeFrom(PhoneNumber other) { if (other == global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneNumber.DefaultInstance) return this; PrepareBuilder(); if (other.HasNumber) { Number = other.Number; } if (other.HasType) { Type = other.Type; } this.MergeUnknownFields(other.UnknownFields); return this; } public override Builder MergeFrom(pb::ICodedInputStream input) { return MergeFrom(input, pb::ExtensionRegistry.Empty); } public override Builder MergeFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) { PrepareBuilder(); pb::UnknownFieldSet.Builder unknownFields = null; uint tag; string field_name; while (input.ReadTag(out tag, out field_name)) { if(tag == 0 && field_name != null) { int field_ordinal = global::System.Array.BinarySearch(_phoneNumberFieldNames, field_name, global::System.StringComparer.Ordinal); if(field_ordinal >= 0) tag = _phoneNumberFieldTags[field_ordinal]; else { if (unknownFields == null) { unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields); } ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name); continue; } } switch (tag) { case 0: { throw pb::InvalidProtocolBufferException.InvalidTag(); } default: { if (pb::WireFormat.IsEndGroupTag(tag)) { if (unknownFields != null) { this.UnknownFields = unknownFields.Build(); } return this; } if (unknownFields == null) { unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields); } ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name); break; } case 10: { result.hasNumber = input.ReadString(ref result.number_); break; } case 16: { object unknown; if(input.ReadEnum(ref result.type_, out unknown)) { result.hasType = true; } else if(unknown is int) { if (unknownFields == null) { unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields); } unknownFields.MergeVarintField(2, (ulong)(int)unknown); } break; } } } if (unknownFields != null) { this.UnknownFields = unknownFields.Build(); } return this; } public bool HasNumber { get { return result.hasNumber; } } public string Number { get { return result.Number; } set { SetNumber(value); } } public Builder SetNumber(string value) { pb::ThrowHelper.ThrowIfNull(value, "value"); PrepareBuilder(); result.hasNumber = true; result.number_ = value; return this; } public Builder ClearNumber() { PrepareBuilder(); result.hasNumber = false; result.number_ = ""; return this; } public bool HasType { get { return result.hasType; } } public global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneType Type { get { return result.Type; } set { SetType(value); } } public Builder SetType(global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneType value) { PrepareBuilder(); result.hasType = true; result.type_ = value; return this; } public Builder ClearType() { PrepareBuilder(); result.hasType = false; result.type_ = global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneType.HOME; return this; } } static PhoneNumber() { object.ReferenceEquals(global::Google.ProtocolBuffers.Examples.AddressBook.AddressBookProtos.Descriptor, null); } } } #endregion public const int NameFieldNumber = 1; private bool hasName; private string name_ = ""; public bool HasName { get { return hasName; } } public string Name { get { return name_; } } public const int IdFieldNumber = 2; private bool hasId; private int id_; public bool HasId { get { return hasId; } } public int Id { get { return id_; } } public const int EmailFieldNumber = 3; private bool hasEmail; private string email_ = ""; public bool HasEmail { get { return hasEmail; } } public string Email { get { return email_; } } public const int PhoneFieldNumber = 4; private pbc::PopsicleList<global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneNumber> phone_ = new pbc::PopsicleList<global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneNumber>(); public scg::IList<global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneNumber> PhoneList { get { return phone_; } } public int PhoneCount { get { return phone_.Count; } } public global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneNumber GetPhone(int index) { return phone_[index]; } public override bool IsInitialized { get { if (!hasName) return false; if (!hasId) return false; foreach (global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneNumber element in PhoneList) { if (!element.IsInitialized) return false; } return true; } } public override void WriteTo(pb::ICodedOutputStream output) { CalcSerializedSize(); string[] field_names = _personFieldNames; if (hasName) { output.WriteString(1, field_names[2], Name); } if (hasId) { output.WriteInt32(2, field_names[1], Id); } if (hasEmail) { output.WriteString(3, field_names[0], Email); } if (phone_.Count > 0) { output.WriteMessageArray(4, field_names[3], phone_); } UnknownFields.WriteTo(output); } private int memoizedSerializedSize = -1; public override int SerializedSize { get { int size = memoizedSerializedSize; if (size != -1) return size; return CalcSerializedSize(); } } private int CalcSerializedSize() { int size = memoizedSerializedSize; if (size != -1) return size; size = 0; if (hasName) { size += pb::CodedOutputStream.ComputeStringSize(1, Name); } if (hasId) { size += pb::CodedOutputStream.ComputeInt32Size(2, Id); } if (hasEmail) { size += pb::CodedOutputStream.ComputeStringSize(3, Email); } foreach (global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneNumber element in PhoneList) { size += pb::CodedOutputStream.ComputeMessageSize(4, element); } size += UnknownFields.SerializedSize; memoizedSerializedSize = size; return size; } public static Person ParseFrom(pb::ByteString data) { return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed(); } public static Person ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed(); } public static Person ParseFrom(byte[] data) { return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed(); } public static Person ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed(); } public static Person ParseFrom(global::System.IO.Stream input) { return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed(); } public static Person ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed(); } public static Person ParseDelimitedFrom(global::System.IO.Stream input) { return CreateBuilder().MergeDelimitedFrom(input).BuildParsed(); } public static Person ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) { return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed(); } public static Person ParseFrom(pb::ICodedInputStream input) { return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed(); } public static Person ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed(); } private Person MakeReadOnly() { phone_.MakeReadOnly(); return this; } public static Builder CreateBuilder() { return new Builder(); } public override Builder ToBuilder() { return CreateBuilder(this); } public override Builder CreateBuilderForType() { return new Builder(); } public static Builder CreateBuilder(Person prototype) { return new Builder(prototype); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class Builder : pb::GeneratedBuilder<Person, Builder> { protected override Builder ThisBuilder { get { return this; } } public Builder() { result = DefaultInstance; resultIsReadOnly = true; } internal Builder(Person cloneFrom) { result = cloneFrom; resultIsReadOnly = true; } private bool resultIsReadOnly; private Person result; private Person PrepareBuilder() { if (resultIsReadOnly) { Person original = result; result = new Person(); resultIsReadOnly = false; MergeFrom(original); } return result; } public override bool IsInitialized { get { return result.IsInitialized; } } protected override Person MessageBeingBuilt { get { return PrepareBuilder(); } } public override Builder Clear() { result = DefaultInstance; resultIsReadOnly = true; return this; } public override Builder Clone() { if (resultIsReadOnly) { return new Builder(result); } else { return new Builder().MergeFrom(result); } } public override pbd::MessageDescriptor DescriptorForType { get { return global::Google.ProtocolBuffers.Examples.AddressBook.Person.Descriptor; } } public override Person DefaultInstanceForType { get { return global::Google.ProtocolBuffers.Examples.AddressBook.Person.DefaultInstance; } } public override Person BuildPartial() { if (resultIsReadOnly) { return result; } resultIsReadOnly = true; return result.MakeReadOnly(); } public override Builder MergeFrom(pb::IMessage other) { if (other is Person) { return MergeFrom((Person) other); } else { base.MergeFrom(other); return this; } } public override Builder MergeFrom(Person other) { if (other == global::Google.ProtocolBuffers.Examples.AddressBook.Person.DefaultInstance) return this; PrepareBuilder(); if (other.HasName) { Name = other.Name; } if (other.HasId) { Id = other.Id; } if (other.HasEmail) { Email = other.Email; } if (other.phone_.Count != 0) { result.phone_.Add(other.phone_); } this.MergeUnknownFields(other.UnknownFields); return this; } public override Builder MergeFrom(pb::ICodedInputStream input) { return MergeFrom(input, pb::ExtensionRegistry.Empty); } public override Builder MergeFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) { PrepareBuilder(); pb::UnknownFieldSet.Builder unknownFields = null; uint tag; string field_name; while (input.ReadTag(out tag, out field_name)) { if(tag == 0 && field_name != null) { int field_ordinal = global::System.Array.BinarySearch(_personFieldNames, field_name, global::System.StringComparer.Ordinal); if(field_ordinal >= 0) tag = _personFieldTags[field_ordinal]; else { if (unknownFields == null) { unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields); } ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name); continue; } } switch (tag) { case 0: { throw pb::InvalidProtocolBufferException.InvalidTag(); } default: { if (pb::WireFormat.IsEndGroupTag(tag)) { if (unknownFields != null) { this.UnknownFields = unknownFields.Build(); } return this; } if (unknownFields == null) { unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields); } ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name); break; } case 10: { result.hasName = input.ReadString(ref result.name_); break; } case 16: { result.hasId = input.ReadInt32(ref result.id_); break; } case 26: { result.hasEmail = input.ReadString(ref result.email_); break; } case 34: { input.ReadMessageArray(tag, field_name, result.phone_, global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneNumber.DefaultInstance, extensionRegistry); break; } } } if (unknownFields != null) { this.UnknownFields = unknownFields.Build(); } return this; } public bool HasName { get { return result.hasName; } } public string Name { get { return result.Name; } set { SetName(value); } } public Builder SetName(string value) { pb::ThrowHelper.ThrowIfNull(value, "value"); PrepareBuilder(); result.hasName = true; result.name_ = value; return this; } public Builder ClearName() { PrepareBuilder(); result.hasName = false; result.name_ = ""; return this; } public bool HasId { get { return result.hasId; } } public int Id { get { return result.Id; } set { SetId(value); } } public Builder SetId(int value) { PrepareBuilder(); result.hasId = true; result.id_ = value; return this; } public Builder ClearId() { PrepareBuilder(); result.hasId = false; result.id_ = 0; return this; } public bool HasEmail { get { return result.hasEmail; } } public string Email { get { return result.Email; } set { SetEmail(value); } } public Builder SetEmail(string value) { pb::ThrowHelper.ThrowIfNull(value, "value"); PrepareBuilder(); result.hasEmail = true; result.email_ = value; return this; } public Builder ClearEmail() { PrepareBuilder(); result.hasEmail = false; result.email_ = ""; return this; } public pbc::IPopsicleList<global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneNumber> PhoneList { get { return PrepareBuilder().phone_; } } public int PhoneCount { get { return result.PhoneCount; } } public global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneNumber GetPhone(int index) { return result.GetPhone(index); } public Builder SetPhone(int index, global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneNumber value) { pb::ThrowHelper.ThrowIfNull(value, "value"); PrepareBuilder(); result.phone_[index] = value; return this; } public Builder SetPhone(int index, global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneNumber.Builder builderForValue) { pb::ThrowHelper.ThrowIfNull(builderForValue, "builderForValue"); PrepareBuilder(); result.phone_[index] = builderForValue.Build(); return this; } public Builder AddPhone(global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneNumber value) { pb::ThrowHelper.ThrowIfNull(value, "value"); PrepareBuilder(); result.phone_.Add(value); return this; } public Builder AddPhone(global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneNumber.Builder builderForValue) { pb::ThrowHelper.ThrowIfNull(builderForValue, "builderForValue"); PrepareBuilder(); result.phone_.Add(builderForValue.Build()); return this; } public Builder AddRangePhone(scg::IEnumerable<global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneNumber> values) { PrepareBuilder(); result.phone_.Add(values); return this; } public Builder ClearPhone() { PrepareBuilder(); result.phone_.Clear(); return this; } } static Person() { object.ReferenceEquals(global::Google.ProtocolBuffers.Examples.AddressBook.AddressBookProtos.Descriptor, null); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class AddressBook : pb::GeneratedMessage<AddressBook, AddressBook.Builder> { private AddressBook() { } private static readonly AddressBook defaultInstance = new AddressBook().MakeReadOnly(); private static readonly string[] _addressBookFieldNames = new string[] { "person" }; private static readonly uint[] _addressBookFieldTags = new uint[] { 10 }; public static AddressBook DefaultInstance { get { return defaultInstance; } } public override AddressBook DefaultInstanceForType { get { return DefaultInstance; } } protected override AddressBook ThisMessage { get { return this; } } public static pbd::MessageDescriptor Descriptor { get { return global::Google.ProtocolBuffers.Examples.AddressBook.AddressBookProtos.internal__static_tutorial_AddressBook__Descriptor; } } protected override pb::FieldAccess.FieldAccessorTable<AddressBook, AddressBook.Builder> InternalFieldAccessors { get { return global::Google.ProtocolBuffers.Examples.AddressBook.AddressBookProtos.internal__static_tutorial_AddressBook__FieldAccessorTable; } } public const int PersonFieldNumber = 1; private pbc::PopsicleList<global::Google.ProtocolBuffers.Examples.AddressBook.Person> person_ = new pbc::PopsicleList<global::Google.ProtocolBuffers.Examples.AddressBook.Person>(); public scg::IList<global::Google.ProtocolBuffers.Examples.AddressBook.Person> PersonList { get { return person_; } } public int PersonCount { get { return person_.Count; } } public global::Google.ProtocolBuffers.Examples.AddressBook.Person GetPerson(int index) { return person_[index]; } public override bool IsInitialized { get { foreach (global::Google.ProtocolBuffers.Examples.AddressBook.Person element in PersonList) { if (!element.IsInitialized) return false; } return true; } } public override void WriteTo(pb::ICodedOutputStream output) { CalcSerializedSize(); string[] field_names = _addressBookFieldNames; if (person_.Count > 0) { output.WriteMessageArray(1, field_names[0], person_); } UnknownFields.WriteTo(output); } private int memoizedSerializedSize = -1; public override int SerializedSize { get { int size = memoizedSerializedSize; if (size != -1) return size; return CalcSerializedSize(); } } private int CalcSerializedSize() { int size = memoizedSerializedSize; if (size != -1) return size; size = 0; foreach (global::Google.ProtocolBuffers.Examples.AddressBook.Person element in PersonList) { size += pb::CodedOutputStream.ComputeMessageSize(1, element); } size += UnknownFields.SerializedSize; memoizedSerializedSize = size; return size; } public static AddressBook ParseFrom(pb::ByteString data) { return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed(); } public static AddressBook ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed(); } public static AddressBook ParseFrom(byte[] data) { return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed(); } public static AddressBook ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed(); } public static AddressBook ParseFrom(global::System.IO.Stream input) { return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed(); } public static AddressBook ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed(); } public static AddressBook ParseDelimitedFrom(global::System.IO.Stream input) { return CreateBuilder().MergeDelimitedFrom(input).BuildParsed(); } public static AddressBook ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) { return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed(); } public static AddressBook ParseFrom(pb::ICodedInputStream input) { return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed(); } public static AddressBook ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed(); } private AddressBook MakeReadOnly() { person_.MakeReadOnly(); return this; } public static Builder CreateBuilder() { return new Builder(); } public override Builder ToBuilder() { return CreateBuilder(this); } public override Builder CreateBuilderForType() { return new Builder(); } public static Builder CreateBuilder(AddressBook prototype) { return new Builder(prototype); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class Builder : pb::GeneratedBuilder<AddressBook, Builder> { protected override Builder ThisBuilder { get { return this; } } public Builder() { result = DefaultInstance; resultIsReadOnly = true; } internal Builder(AddressBook cloneFrom) { result = cloneFrom; resultIsReadOnly = true; } private bool resultIsReadOnly; private AddressBook result; private AddressBook PrepareBuilder() { if (resultIsReadOnly) { AddressBook original = result; result = new AddressBook(); resultIsReadOnly = false; MergeFrom(original); } return result; } public override bool IsInitialized { get { return result.IsInitialized; } } protected override AddressBook MessageBeingBuilt { get { return PrepareBuilder(); } } public override Builder Clear() { result = DefaultInstance; resultIsReadOnly = true; return this; } public override Builder Clone() { if (resultIsReadOnly) { return new Builder(result); } else { return new Builder().MergeFrom(result); } } public override pbd::MessageDescriptor DescriptorForType { get { return global::Google.ProtocolBuffers.Examples.AddressBook.AddressBook.Descriptor; } } public override AddressBook DefaultInstanceForType { get { return global::Google.ProtocolBuffers.Examples.AddressBook.AddressBook.DefaultInstance; } } public override AddressBook BuildPartial() { if (resultIsReadOnly) { return result; } resultIsReadOnly = true; return result.MakeReadOnly(); } public override Builder MergeFrom(pb::IMessage other) { if (other is AddressBook) { return MergeFrom((AddressBook) other); } else { base.MergeFrom(other); return this; } } public override Builder MergeFrom(AddressBook other) { if (other == global::Google.ProtocolBuffers.Examples.AddressBook.AddressBook.DefaultInstance) return this; PrepareBuilder(); if (other.person_.Count != 0) { result.person_.Add(other.person_); } this.MergeUnknownFields(other.UnknownFields); return this; } public override Builder MergeFrom(pb::ICodedInputStream input) { return MergeFrom(input, pb::ExtensionRegistry.Empty); } public override Builder MergeFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) { PrepareBuilder(); pb::UnknownFieldSet.Builder unknownFields = null; uint tag; string field_name; while (input.ReadTag(out tag, out field_name)) { if(tag == 0 && field_name != null) { int field_ordinal = global::System.Array.BinarySearch(_addressBookFieldNames, field_name, global::System.StringComparer.Ordinal); if(field_ordinal >= 0) tag = _addressBookFieldTags[field_ordinal]; else { if (unknownFields == null) { unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields); } ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name); continue; } } switch (tag) { case 0: { throw pb::InvalidProtocolBufferException.InvalidTag(); } default: { if (pb::WireFormat.IsEndGroupTag(tag)) { if (unknownFields != null) { this.UnknownFields = unknownFields.Build(); } return this; } if (unknownFields == null) { unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields); } ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name); break; } case 10: { input.ReadMessageArray(tag, field_name, result.person_, global::Google.ProtocolBuffers.Examples.AddressBook.Person.DefaultInstance, extensionRegistry); break; } } } if (unknownFields != null) { this.UnknownFields = unknownFields.Build(); } return this; } public pbc::IPopsicleList<global::Google.ProtocolBuffers.Examples.AddressBook.Person> PersonList { get { return PrepareBuilder().person_; } } public int PersonCount { get { return result.PersonCount; } } public global::Google.ProtocolBuffers.Examples.AddressBook.Person GetPerson(int index) { return result.GetPerson(index); } public Builder SetPerson(int index, global::Google.ProtocolBuffers.Examples.AddressBook.Person value) { pb::ThrowHelper.ThrowIfNull(value, "value"); PrepareBuilder(); result.person_[index] = value; return this; } public Builder SetPerson(int index, global::Google.ProtocolBuffers.Examples.AddressBook.Person.Builder builderForValue) { pb::ThrowHelper.ThrowIfNull(builderForValue, "builderForValue"); PrepareBuilder(); result.person_[index] = builderForValue.Build(); return this; } public Builder AddPerson(global::Google.ProtocolBuffers.Examples.AddressBook.Person value) { pb::ThrowHelper.ThrowIfNull(value, "value"); PrepareBuilder(); result.person_.Add(value); return this; } public Builder AddPerson(global::Google.ProtocolBuffers.Examples.AddressBook.Person.Builder builderForValue) { pb::ThrowHelper.ThrowIfNull(builderForValue, "builderForValue"); PrepareBuilder(); result.person_.Add(builderForValue.Build()); return this; } public Builder AddRangePerson(scg::IEnumerable<global::Google.ProtocolBuffers.Examples.AddressBook.Person> values) { PrepareBuilder(); result.person_.Add(values); return this; } public Builder ClearPerson() { PrepareBuilder(); result.person_.Clear(); return this; } } static AddressBook() { object.ReferenceEquals(global::Google.ProtocolBuffers.Examples.AddressBook.AddressBookProtos.Descriptor, null); } } #endregion } #endregion Designer generated code
using System; using System.Collections.Generic; using System.ComponentModel; using System.IO; using System.Linq; using System.Text; using NDesk.Options; using Sep.Git.Tfs.Core; using StructureMap; namespace Sep.Git.Tfs.Commands { [Pluggable("subtree")] [Description("subtree [add|pull|split] [options] [remote | ( [tfs-url] [repository-path] )]")] [RequiresValidGitRepository] public class Subtree : GitTfsCommand { private readonly TextWriter _stdout; private readonly Fetch _fetch; private readonly QuickFetch _quickFetch; private readonly Globals _globals; private readonly RemoteOptions _remoteOptions; private string Prefix; private bool Squash = false; public OptionSet OptionSet { get { return new OptionSet { { "p|prefix=", v => Prefix = v}, { "squash", v => Squash = v != null}, // { "r|revision=", // v => RevisionToFetch = Convert.ToInt32(v) }, } .Merge(_fetch.OptionSet); } } public Subtree(TextWriter stdout, Fetch fetch, QuickFetch quickFetch, Globals globals, RemoteOptions remoteOptions) { this._stdout = stdout; this._fetch = fetch; this._quickFetch = quickFetch; this._globals = globals; this._remoteOptions = remoteOptions; } public int Run(IList<string> args) { string command = args.FirstOrDefault() ?? ""; _stdout.WriteLine("executing subtree " + command); if (string.IsNullOrEmpty(Prefix)) { _stdout.WriteLine("Prefix must be specified, use -p or -prefix"); return GitTfsExitCodes.InvalidArguments; } switch (command.ToLower()) { case "add": return DoAdd(args.ElementAtOrDefault(1) ?? "", args.ElementAtOrDefault(2) ?? ""); break; case "pull": return DoPull(args.ElementAtOrDefault(1)); case "split": return DoSplit(); default: _stdout.WriteLine("Expected one of [add, pull, split]"); return GitTfsExitCodes.InvalidArguments; break; } } public int DoAdd(string tfsUrl, string tfsRepositoryPath) { if (File.Exists(Prefix) || Directory.Exists(Prefix)) { _stdout.WriteLine(string.Format("Directory {0} already exists", Prefix)); return GitTfsExitCodes.InvalidArguments; } var fetch = Squash ? this._quickFetch : this._fetch; IGitTfsRemote owner = null; string ownerId = _globals.RemoteId; if (!string.IsNullOrEmpty(ownerId)) { //check for the specified remote owner = _globals.Repository.HasRemote(_globals.RemoteId) ? _globals.Repository.ReadTfsRemote(_globals.RemoteId) : null; if (owner != null && !string.IsNullOrEmpty(owner.TfsRepositoryPath)) { owner = null; ownerId = null; } } if(string.IsNullOrEmpty(ownerId)) { //check for any remote that has no TfsRepositoryPath owner = _globals.Repository.ReadAllTfsRemotes().FirstOrDefault(x => string.IsNullOrEmpty(x.TfsRepositoryPath) && !x.IsSubtree); } if (owner == null) { owner = _globals.Repository.CreateTfsRemote(new RemoteInfo { Id = ownerId ?? GitTfsConstants.DefaultRepositoryId, Url = tfsUrl, Repository = null, RemoteOptions = _remoteOptions }); _stdout.WriteLine("-> new owning remote " + owner.Id); } else { ownerId = owner.Id; _stdout.WriteLine("Attaching subtree to owning remote " + owner.Id); } //create a remote for the new subtree string remoteId = string.Format(GitTfsConstants.RemoteSubtreeFormat, owner.Id, Prefix); IGitTfsRemote remote = _globals.Repository.HasRemote(remoteId) ? _globals.Repository.ReadTfsRemote(remoteId) : _globals.Repository.CreateTfsRemote(new RemoteInfo { Id = remoteId, Url = tfsUrl, Repository = tfsRepositoryPath, RemoteOptions = _remoteOptions, }); _stdout.WriteLine("-> new remote " + remote.Id); int result = fetch.Run(remote.Id); if (result == GitTfsExitCodes.OK) { var p = Prefix.Replace(" ", "\\ "); long latest = Math.Max(owner.MaxChangesetId, remote.MaxChangesetId); string msg = string.Format(GitTfsConstants.TfsCommitInfoFormat, owner.TfsUrl, owner.TfsRepositoryPath, latest); msg = string.Format(@"Add '{0}/' from commit '{1}' {2}", Prefix, remote.MaxCommitHash, msg); _globals.Repository.CommandNoisy( "subtree", "add", "--prefix=" + p, string.Format("-m {0}", msg), remote.RemoteRef); //update the owner remote to point at the commit where the newly created subtree was merged. var commit = _globals.Repository.GetCurrentCommit(); owner.UpdateTfsHead(commit, latest); result = GitTfsExitCodes.OK; } return result; } public int DoPull(string remoteId) { ValidatePrefix(); remoteId = remoteId ?? string.Format(GitTfsConstants.RemoteSubtreeFormat, _globals.RemoteId ?? GitTfsConstants.DefaultRepositoryId, Prefix); IGitTfsRemote remote = _globals.Repository.ReadTfsRemote(remoteId); int result = this._fetch.Run(remote.Id); if (result == GitTfsExitCodes.OK) { var p = Prefix.Replace(" ", "\\ "); _globals.Repository.CommandNoisy("subtree", "merge", "--prefix=" + p, remote.RemoteRef); result = GitTfsExitCodes.OK; } return result; } public int DoSplit() { ValidatePrefix(); var p = Prefix.Replace(" ", "\\ "); _globals.Repository.CommandNoisy("subtree", "split", "--prefix=" + p, "-b", p); _globals.Repository.CommandNoisy("checkout", p); //update subtree refs if needed var owners = _globals.Repository.GetLastParentTfsCommits("HEAD").Where(x => !x.Remote.IsSubtree && x.Remote.TfsRepositoryPath == null).ToList(); foreach (var subtree in _globals.Repository.ReadAllTfsRemotes().Where(x => x.IsSubtree && string.Equals(x.Prefix, Prefix))) { var updateTo = owners.FirstOrDefault(x => string.Equals(x.Remote.Id, subtree.OwningRemoteId)); if (updateTo != null && updateTo.ChangesetId > subtree.MaxChangesetId) { subtree.UpdateTfsHead(updateTo.GitCommit, updateTo.ChangesetId); } } return GitTfsExitCodes.OK; } private void ValidatePrefix() { if (!Directory.Exists(Prefix)) { throw new GitTfsException(string.Format("Directory {0} does not exist", Prefix)) .WithRecommendation("Add the subtree using 'git tfs subtree add -p=<prefix> [tfs-server] [tfs-repository]'"); } } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="Backlog.Issue.cs"> // bl4n - Backlog.jp API Client library // this file is part of bl4n, license under MIT license. http://t-ashula.mit-license.org/2015 // </copyright> // -------------------------------------------------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using BL4N.Data; using Newtonsoft.Json; namespace BL4N { /// <summary> The backlog. for Issue API </summary> public partial class Backlog { /// <summary> /// Get Issue List /// Returns list of issues. /// </summary> /// <param name="options">search option</param> /// <returns>list of <see cref="IIssue"/></returns> public IList<IIssue> GetIssues(IssueSearchConditions options) { var query = options.ToKeyValuePairs(); var api = GetApiUri(new[] { "issues" }, query); var jss = new JsonSerializerSettings { DateFormatHandling = DateFormatHandling.IsoDateFormat, NullValueHandling = NullValueHandling.Ignore }; var res = GetApiResult<List<Issue>>(api, jss); return res.Result.ToList<IIssue>(); } /// <summary> /// Get Issue List /// Returns list of issues. /// </summary> /// <param name="projectIds">Project Ids</param> /// <param name="conditions">search option</param> /// <returns>list of <see cref="IIssue"/></returns> [Obsolete("use IssueSearchConditions only API")] public IList<IIssue> GetIssues(long[] projectIds, IssueSearchConditions conditions) { conditions.ProjectIds.AddRange(projectIds); return GetIssues(conditions); } /// <summary> /// Count Issue /// Returns number of issues. /// </summary> /// <param name="options">search condtions</param> /// <returns>issue count as <see cref="ICounter"/></returns> public ICounter GetIssuesCount(IssueSearchConditions options) { var query = options.ToKeyValuePairs(); var api = GetApiUri(new[] { "issues", "count" }, query); var jss = new JsonSerializerSettings(); var res = GetApiResult<Counter>(api, jss); return res.Result; } /// <summary> /// Count Issue /// Returns number of issues. /// </summary> /// <param name="projectIds">Project Ids</param> /// <param name="conditions">search condtions</param> /// <returns>issue count as <see cref="ICounter"/></returns> [Obsolete("use IssueSearchConditions only API")] public ICounter GetIssuesCount(long[] projectIds, IssueSearchConditions conditions) { conditions.ProjectIds.AddRange(projectIds); return GetIssuesCount(conditions); } /// <summary> /// Add Issue /// Adds new issue. /// </summary> /// <param name="settings">new issue setting</param> /// <returns>created <see cref="IIssue"/></returns> public IIssue AddIssue(NewIssueSettings settings) { var api = GetApiUri(new[] { "issues" }); var jss = new JsonSerializerSettings { DateFormatHandling = DateFormatHandling.IsoDateFormat, NullValueHandling = NullValueHandling.Ignore }; var hc = new FormUrlEncodedContent(settings.ToKeyValuePairs()); var res = PostApiResult<Issue>(api, hc, jss); return res.Result; } /// <summary> /// Get Issue /// Returns information about issue. /// </summary> /// <param name="issueId">issue id</param> /// <returns><see cref="IIssue"/></returns> public IIssue GetIssue(long issueId) { return GetIssue(string.Format("{0}", issueId)); } /// <summary> /// Get Issue /// Returns information about issue. /// </summary> /// <param name="issueKey">issue key to get (like XXX-123)</param> /// <returns><see cref="IIssue"/></returns> public IIssue GetIssue(string issueKey) { var api = GetApiUri(new[] { "issues", issueKey }); var jss = new JsonSerializerSettings { DateFormatHandling = DateFormatHandling.IsoDateFormat, NullValueHandling = NullValueHandling.Ignore }; var res = GetApiResult<Issue>(api, jss); return res.Result; } /// <summary> /// Update Issue /// Updates information about issue. /// </summary> /// <param name="issueId">issue id to update</param> /// <param name="issueUpdateSettings">update settings</param> /// <returns>updated <see cref="IIssue"/></returns> public IIssue UpdateIssue(long issueId, IssueUpdateSettings issueUpdateSettings) { return UpdateIssue(string.Format("{0}", issueId), issueUpdateSettings); } /// <summary> /// Update Issue /// Updates information about issue. /// </summary> /// <param name="issueKey">issue key to update (like XXX-123)</param> /// <param name="issueUpdateSettings">update settings</param> /// <returns>updated <see cref="IIssue"/></returns> public IIssue UpdateIssue(string issueKey, IssueUpdateSettings issueUpdateSettings) { var api = GetApiUri(new[] { "issues", issueKey }); var jss = new JsonSerializerSettings { DateFormatHandling = DateFormatHandling.IsoDateFormat, NullValueHandling = NullValueHandling.Ignore }; var kvs = issueUpdateSettings.ToKeyValuePairs(); var hc = new FormUrlEncodedContent(kvs); var res = PatchApiResult<Issue>(api, hc, jss); return res.Result; } /// <summary> /// Delete Issue /// Deletes issue. /// </summary> /// <param name="issueId">issue id to delete</param> /// <returns>deleted <see cref="IIssue"/></returns> public IIssue DeleteIssue(long issueId) { return DeleteIssue(string.Format("{0}", issueId)); } /// <summary> /// Delete Issue /// Deletes issue. /// </summary> /// <param name="issueKey">issue key to delete (like XXX-123)</param> /// <returns>deleted <see cref="IIssue"/></returns> public IIssue DeleteIssue(string issueKey) { var api = GetApiUri(new[] { "issues", issueKey }); var jss = new JsonSerializerSettings { DateFormatHandling = DateFormatHandling.IsoDateFormat, NullValueHandling = NullValueHandling.Ignore }; var res = DeleteApiResult<Issue>(api, jss); return res.Result; } #region issues/comments /// <summary> /// Get Comment List /// Returns list of comments in issue. /// </summary> /// <param name="issueId">issue id</param> /// <param name="filter">result paging option</param> /// <returns>list of <see cref="IIssueComment"/></returns> public IList<IIssueComment> GetIssueComments(long issueId, ResultPagingOptions filter = null) { return GetIssueComments(string.Format("{0}", issueId), filter); } /// <summary> /// Get Comment List /// Returns list of comments in issue. /// </summary> /// <param name="issueKey">issue key (like XXX-123)</param> /// <param name="filter">result paging option</param> /// <returns>list of <see cref="IIssueComment"/></returns> public IList<IIssueComment> GetIssueComments(string issueKey, ResultPagingOptions filter = null) { var query = filter == null ? null : filter.ToKeyValuePairs(); var api = GetApiUri(new[] { "issues", issueKey, "comments" }, query); var jss = new JsonSerializerSettings { DateFormatHandling = DateFormatHandling.IsoDateFormat, NullValueHandling = NullValueHandling.Ignore }; var res = GetApiResult<List<IssueComment>>(api, jss); return res.Result.ToList<IIssueComment>(); } /// <summary> /// Add Comment /// Adds a comment to the issue. /// </summary> /// <param name="issueId">issue id</param> /// <param name="options">comment content</param> /// <returns>list of <see cref="IIssueComment"/></returns> public IIssueComment AddIssueComment(long issueId, CommentAddContent options) { return AddIssueComment(string.Format("{0}", issueId), options); } /// <summary> /// Add Comment /// Adds a comment to the issue. /// </summary> /// <param name="issueKey">issue key (like XXX-123)</param> /// <param name="options">comment content</param> /// <returns>list of <see cref="IIssueComment"/></returns> public IIssueComment AddIssueComment(string issueKey, CommentAddContent options) { var api = GetApiUri(new[] { "issues", issueKey, "comments" }); var jss = new JsonSerializerSettings { DateFormatHandling = DateFormatHandling.IsoDateFormat, NullValueHandling = NullValueHandling.Ignore }; var kvs = options.ToKeyValuePairs(); var hc = new FormUrlEncodedContent(kvs); var res = PostApiResult<IssueComment>(api, hc, jss); return res.Result; } /// <summary> /// Count Comment /// Returns number of comments in issue. /// </summary> /// <param name="issueId">issue id</param> /// <returns>number of comments</returns> public ICounter GetIssueCommentCount(long issueId) { return GetIssueCommentCount(string.Format("{0}", issueId)); } /// <summary> /// Count Comment /// Returns number of comments in issue. /// </summary> /// <param name="issueKey">issue key (like XXX-123)</param> /// <returns>number of comments</returns> public ICounter GetIssueCommentCount(string issueKey) { var api = GetApiUri(new[] { "issues", issueKey, "comments", "count" }); var res = GetApiResult<Counter>(api, new JsonSerializerSettings()); return res.Result; } /// <summary> /// Get Comment /// Returns information about comment. /// </summary> /// <param name="issueId">issue id</param> /// <param name="commentId">comment id</param> /// <returns>comment <see cref="IIssueComment"/></returns> public IIssueComment GetIssueComment(long issueId, long commentId) { return GetIssueComment(string.Format("{0}", issueId), commentId); } /// <summary> /// Get Comment /// Returns information about comment. /// </summary> /// <param name="issueKey">issue key (like XXX-123)</param> /// <param name="commentId">comment id</param> /// <returns>comment <see cref="IIssueComment"/></returns> public IIssueComment GetIssueComment(string issueKey, long commentId) { var api = GetApiUri(new[] { "issues", issueKey, "comments", commentId.ToString("D") }); var jss = new JsonSerializerSettings { DateFormatHandling = DateFormatHandling.IsoDateFormat, NullValueHandling = NullValueHandling.Ignore }; var res = GetApiResult<IssueComment>(api, jss); return res.Result; } /// <summary> /// Update comment /// Updates content of comment. /// User can update own comment. /// </summary> /// <param name="issueId">issue id</param> /// <param name="commentId">comment id</param> /// <param name="content">comment content</param> /// <returns>updated <see cref="IIssueComment"/></returns> public IIssueComment UpdateIssueComment(long issueId, long commentId, string content) { return UpdateIssueComment(string.Format("{0}", issueId), commentId, content); } /// <summary> /// Update comment /// Updates content of comment. /// User can update own comment. /// </summary> /// <param name="issueKey">issue key (like XXX-123)</param> /// <param name="commentId">comment id</param> /// <param name="content">comment content</param> /// <returns>updated <see cref="IIssueComment"/></returns> public IIssueComment UpdateIssueComment(string issueKey, long commentId, string content) { var api = GetApiUri(new[] { "issues", issueKey, "comments", commentId.ToString("D") }); var jss = new JsonSerializerSettings { DateFormatHandling = DateFormatHandling.IsoDateFormat, NullValueHandling = NullValueHandling.Ignore }; var kvs = new[] { new KeyValuePair<string, string>("content", content) }; var hc = new FormUrlEncodedContent(kvs); var res = PatchApiResult<IssueComment>(api, hc, jss); return res.Result; } /// <summary> /// Get List of Comment Notifications /// Returns the list of comment notifications. /// </summary> /// <param name="issueId">issue id</param> /// <param name="commentId">comment id</param> /// <returns>list of <see cref="ICommentNotification"/></returns> public IList<ICommentNotification> GetIssueCommentNotifications(long issueId, long commentId) { var issueKey = issueId.ToString("D"); return GetIssueCommentNotifications(issueKey, commentId); } /// <summary> /// Get List of Comment Notifications /// Returns the list of comment notifications. /// </summary> /// <param name="issueKey">issue key (like XXX-123)</param> /// <param name="commentId">comment id</param> /// <returns>list of <see cref="ICommentNotification"/></returns> public IList<ICommentNotification> GetIssueCommentNotifications(string issueKey, long commentId) { var api = GetApiUri(new[] { "issues", issueKey, "comments", commentId.ToString("D"), "notifications" }); var jss = new JsonSerializerSettings { DateFormatHandling = DateFormatHandling.IsoDateFormat, NullValueHandling = NullValueHandling.Ignore }; var res = GetApiResult<List<CommentNotification>>(api, jss); return res.Result.ToList<ICommentNotification>(); } /// <summary> /// Add Comment Notification /// Adds notifications to the comment. /// Only the user who added the comment can add notifications. /// </summary> /// <param name="issueId">issue id </param> /// <param name="commentId">comment id</param> /// <param name="userIds">user id who to notify</param> /// <returns>comment id <see cref="IIssueComment"/></returns> /// <remarks> /// <paramref name="userIds"/> shall not contain comment created user. </remarks> public IIssueComment AddIssueCommentNotification(long issueId, long commentId, List<long> userIds) { return AddIssueCommentNotification(string.Format("{0}", issueId), commentId, userIds); } /// <summary> /// Add Comment Notification /// Adds notifications to the comment. /// Only the user who added the comment can add notifications. /// </summary> /// <param name="issueKey">issue key (like XXX-123)</param> /// <param name="commentId">comment id</param> /// <param name="userIds">user id who to notify</param> /// <returns>comment id <see cref="IIssueComment"/></returns> /// <remarks> /// <paramref name="userIds"/> shall not contain comment created user. </remarks> public IIssueComment AddIssueCommentNotification(string issueKey, long commentId, List<long> userIds) { var api = GetApiUri(new[] { "issues", issueKey, "comments", commentId.ToString(), "notifications" }); var jss = new JsonSerializerSettings { DateFormatHandling = DateFormatHandling.IsoDateFormat, NullValueHandling = NullValueHandling.Ignore }; var kvs = userIds.ToKeyValuePairs("notifiedUserId[]"); var hc = new FormUrlEncodedContent(kvs); var res = PostApiResult<IssueComment>(api, hc, jss); return res.Result; } #endregion #region issues/attachments /// <summary> /// Get List of Issue Attachments /// Returns the list of issue attachments. /// </summary> /// <param name="issueId">issue id</param> /// <returns>list of <see cref="IAttachment"/></returns> public IList<IAttachment> GetIssueAttachments(long issueId) { return GetIssueAttachments(string.Format("{0}", issueId)); } /// <summary> /// Get List of Issue Attachments /// Returns the list of issue attachments. /// </summary> /// <param name="issueKey">issue key (like XXX-123)</param> /// <returns>list of <see cref="IAttachment"/></returns> public IList<IAttachment> GetIssueAttachments(string issueKey) { var api = GetApiUri(new[] { "issues", issueKey, "attachments" }); var jss = new JsonSerializerSettings { DateFormatHandling = DateFormatHandling.IsoDateFormat, NullValueHandling = NullValueHandling.Ignore }; var res = GetApiResult<List<Attachment>>(api, jss); return res.Result.ToList<IAttachment>(); } /// <summary> /// Get Issue Attachment /// Downloads issue's attachment file. /// </summary> /// <param name="issueId">issue id</param> /// <param name="attachmentId">attachment id</param> /// <returns>file content and name</returns> public ISharedFileData GetIssueAttachment(long issueId, long attachmentId) { return GetIssueAttachment(string.Format("{0}", issueId), attachmentId); } /// <summary> /// Get Issue Attachment /// Downloads issue's attachment file. /// </summary> /// <param name="issueKey">issue key (like XXX-123)</param> /// <param name="attachmentId">attachment id</param> /// <returns>file content and name</returns> public ISharedFileData GetIssueAttachment(string issueKey, long attachmentId) { var api = GetApiUri(new[] { "issues", issueKey, "attachments", attachmentId.ToString("D") }); var res = GetApiResultAsFile(api); var fileName = res.Result.Item1; var content = res.Result.Item2; return new SharedFileData(fileName, content); } /// <summary> /// Delete Issue Attachment /// Deletes an attachment of issue. /// </summary> /// <param name="issueId">issue id</param> /// <param name="attachmentId">attachment id</param> /// <returns>deleted <see cref="IAttachment"/></returns> public IAttachment DeleteIssueAttachment(long issueId, long attachmentId) { return DeleteIssueAttachment(string.Format("{0}", issueId), attachmentId); } /// <summary> /// Delete Issue Attachment /// Deletes an attachment of issue. /// </summary> /// <param name="issueKey">issue key (like XXX-123)</param> /// <param name="attachmentId">attachment id</param> /// <returns>deleted <see cref="IAttachment"/></returns> public IAttachment DeleteIssueAttachment(string issueKey, long attachmentId) { var api = GetApiUri(new[] { "issues", issueKey, "attachments", attachmentId.ToString("D") }); var jss = new JsonSerializerSettings { DateFormatHandling = DateFormatHandling.IsoDateFormat, NullValueHandling = NullValueHandling.Ignore }; var res = DeleteApiResult<Attachment>(api, jss); return res.Result; } #endregion #region issues/sharedfiles /// <summary> /// Get List of Linked Shared Files /// Returns the list of linked Shared Files to issues. /// </summary> /// <param name="issueId">issue id</param> /// <returns>list of <see cref="ISharedFile"/></returns> public IList<ISharedFile> GetIssueLinkedSharedFiles(long issueId) { return GetIssueLinkedSharedFiles(string.Format("{0}", issueId)); } /// <summary> /// Get List of Linked Shared Files /// Returns the list of linked Shared Files to issues. /// </summary> /// <param name="issueKey">issue key (like XXX-123)</param> /// <returns>list of <see cref="ISharedFile"/></returns> public IList<ISharedFile> GetIssueLinkedSharedFiles(string issueKey) { var api = GetApiUri(new[] { "issues", issueKey, "sharedFiles" }); var jss = new JsonSerializerSettings { DateFormatHandling = DateFormatHandling.IsoDateFormat, NullValueHandling = NullValueHandling.Ignore }; var res = GetApiResult<List<SharedFile>>(api, jss); return res.Result.ToList<ISharedFile>(); } /// <summary> /// Link Shared Files to Issue /// Links shared files to issue. /// </summary> /// <param name="issueId">issue id</param> /// <param name="fileIds">shared file ids</param> /// <returns>list of linked <see cref="ISharedFile"/></returns> public IList<ISharedFile> AddIssueLinkedSharedFiles(long issueId, IEnumerable<long> fileIds) { return AddIssueLinkedSharedFiles(string.Format("{0}", issueId), fileIds); } /// <summary> /// Link Shared Files to Issue /// Links shared files to issue. /// </summary> /// <param name="issueKey">issue key (like XXX-123)</param> /// <param name="fileIds">shared file ids</param> /// <returns>list of linked <see cref="ISharedFile"/></returns> public IList<ISharedFile> AddIssueLinkedSharedFiles(string issueKey, IEnumerable<long> fileIds) { var api = GetApiUri(new[] { "issues", issueKey, "sharedFiles" }); var jss = new JsonSerializerSettings { DateFormatHandling = DateFormatHandling.IsoDateFormat, NullValueHandling = NullValueHandling.Ignore }; var kvs = fileIds.ToKeyValuePairs("fileId[]"); var hc = new FormUrlEncodedContent(kvs); var res = PostApiResult<List<SharedFile>>(api, hc, jss); return res.Result.ToList<ISharedFile>(); } /// <summary> /// Remove Link to Shared File from Issue /// Removes link to shared file from issue. /// </summary> /// <param name="issueId">issue id</param> /// <param name="fileId">shared file id</param> /// <returns>removed <see cref="ISharedFile"/></returns> public ISharedFile RemoveIssueLinkedSharedFile(long issueId, long fileId) { return RemoveIssueLinkedSharedFile(string.Format("{0}", issueId), fileId); } /// <summary> /// Remove Link to Shared File from Issue /// Removes link to shared file from issue. /// </summary> /// <param name="issueKey">issue key (like XXX-123)</param> /// <param name="fileId">shared file id</param> /// <returns>removed <see cref="ISharedFile"/></returns> public ISharedFile RemoveIssueLinkedSharedFile(string issueKey, long fileId) { var api = GetApiUri(new[] { "issues", issueKey, "sharedFiles", fileId.ToString("D") }); var jss = new JsonSerializerSettings { DateFormatHandling = DateFormatHandling.IsoDateFormat, NullValueHandling = NullValueHandling.Ignore }; var res = DeleteApiResult<SharedFile>(api, jss); return res.Result; } #endregion } }
using System; using System.Collections.Generic; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Media; using System.Windows.Shapes; using Microsoft.Msagl.Drawing; using Microsoft.Msagl.Core.Layout; using Microsoft.Msagl.Core.DataStructures; using GeometryEdge = Microsoft.Msagl.Core.Layout.Edge; using DrawingEdge = Microsoft.Msagl.Drawing.Edge; using GeometryNode = Microsoft.Msagl.Core.Layout.Node; using DrawingNode = Microsoft.Msagl.Drawing.Node; namespace Microsoft.Msagl.GraphControlSilverlight { /// <summary> /// This class represents a rendering node. It contains the Microsoft.Msagl.Drawing.Node and Microsoft.Msagl.Node. /// The rendering node is a XAML user control. Its template is stored in Themes/generic.xaml. /// </summary> public class DNode : DObject, IViewerNode, IHavingDLabel { private DLabel _Label; /// <summary> /// Gets or sets the rendering label. /// </summary> public DLabel Label { get { return _Label; } set { _Label = value; // Also set the drawing label and geometry label. DrawingNode.Label = value.DrawingLabel; //DrawingNode.Attr.GeometryNode.Label = value.DrawingLabel.GeometryLabel; // NEWMSAGL no label in the geometry node?? } } /// <summary> /// the corresponding drawing node /// </summary> public Microsoft.Msagl.Drawing.Node DrawingNode { get; set; } public IEnumerable<IViewerEdge> OutEdges { get { foreach (DEdge e in _OutEdges) yield return e; } } public IEnumerable<IViewerEdge> InEdges { get { foreach (DEdge e in _InEdges) yield return e; } } public IEnumerable<IViewerEdge> SelfEdges { get { foreach (DEdge e in _SelfEdges) yield return e; } } public IEnumerable<DEdge> Edges { get { foreach (DEdge e in _OutEdges) yield return e; foreach (DEdge e in _InEdges) yield return e; foreach (DEdge e in _SelfEdges) yield return e; } } internal List<DEdge> _OutEdges { get; private set; } internal List<DEdge> _InEdges { get; private set; } internal List<DEdge> _SelfEdges { get; private set; } internal DNode(DObject graph, DrawingNode drawingNode) : base(graph) { this.DrawingNode = drawingNode; _OutEdges = new List<DEdge>(); _InEdges = new List<DEdge>(); _SelfEdges = new List<DEdge>(); PortsToDraw = new Set<Port>(); if (drawingNode.Label != null && drawingNode.Label.GeometryLabel != null) Label = new DTextLabel(this, drawingNode.Label); if (!(this is DCluster)) Canvas.SetZIndex(this, 10000); } public override void MakeVisual() { if (GeometryNode == null || GeometryNode.BoundaryCurve == null) return; SetValue(Canvas.LeftProperty, Node.BoundingBox.Left); SetValue(Canvas.TopProperty, Node.BoundingBox.Bottom); // Note that Draw.CreateGraphicsPath returns a curve with coordinates in graph space. var pathFigure = Draw.CreateGraphicsPath((DrawingNode.GeometryNode).BoundaryCurve); pathFigure.IsFilled = Node.Attr.FillColor.A != 0; pathFigure.IsClosed = true; var pathGeometry = new PathGeometry(); pathGeometry.Figures.Add(pathFigure); // Apply a translation to bring the coordinates in node space (i.e. top left corner is 0,0). pathGeometry.Transform = new TranslateTransform() { X = -Node.BoundingBox.Left, Y = -Node.BoundingBox.Bottom }; // I'm using the max of my LineWidth and MSAGL's LineWidth; this way, when the MSAGL bug is fixed (see below), my workaround shouldn't // interfere with the fix. var path = new Path() { Data = pathGeometry, StrokeThickness = Math.Max(LineWidth, Node.Attr.LineWidth), Stroke = BoundaryBrush, Fill = new SolidColorBrush(Draw.MsaglColorToDrawingColor(Node.Attr.FillColor)), StrokeLineJoin = PenLineJoin.Miter }; Content = path; } // Workaround for MSAGL bug which causes Node.Attr.LineWidth to be ignored (it always returns 1 unless the GeometryNode is null). public int LineWidth { get; set; } /// <summary> /// Gets or sets the boundary brush. /// </summary> public Brush BoundaryBrush { get { return (Brush)GetValue(BoundaryBrushProperty); } set { SetValue(BoundaryBrushProperty, value); } } public static readonly DependencyProperty BoundaryBrushProperty = DependencyProperty.Register("BoundaryBrush", typeof(Brush), typeof(DNode), new PropertyMetadata(DGraph.BlackBrush)); internal void AddOutEdge(DEdge edge) { _OutEdges.Add(edge); } internal void AddInEdge(DEdge edge) { _InEdges.Add(edge); } internal void AddSelfEdge(DEdge edge) { _SelfEdges.Add(edge); } /// <summary> /// return the color of a node /// </summary> public System.Windows.Media.Color Color { get { return Draw.MsaglColorToDrawingColor(this.DrawingNode.Attr.Color); } } /// <summary> /// Fillling color of a node /// </summary> public System.Windows.Media.Color FillColor { get { return Draw.MsaglColorToDrawingColor(this.DrawingNode.Attr.FillColor); } } /// <summary> /// /// </summary> public void SetStrokeFill() { } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public GeometryNode GeometryNode { get { return this.DrawingNode.GeometryNode; } } /// <summary> /// returns the corresponding DrawingNode /// </summary> public DrawingNode Node { get { return this.DrawingNode; } } /// <summary> /// returns the corresponding drawing object /// </summary> override public DrawingObject DrawingObject { get { return Node; } } internal void RemoveOutEdge(DEdge de) { _OutEdges.Remove(de); } internal void RemoveInEdge(DEdge de) { _InEdges.Remove(de); } internal void RemoveSelfEdge(DEdge de) { _SelfEdges.Remove(de); } internal Set<Port> PortsToDraw { get; private set; } /// <summary> /// /// </summary> public void AddPort(Port port) { PortsToDraw.Insert(port); } /// <summary> /// it is a class holding Microsoft.Msagl.Drawing.Node and Microsoft.Msagl.Node /// </summary> public void RemovePort(Port port) { if (port != null) PortsToDraw.Remove(port); } // not used at the moment; not sure what it does public event Action<IViewerNode> IsCollapsedChanged; } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.Remoting.Messaging; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Orleans; using Orleans.CodeGeneration; using Orleans.Configuration; using Orleans.Hosting; using Orleans.Runtime; using Orleans.Runtime.Configuration; using Orleans.TestingHost; using Tester; using TestExtensions; using UnitTests.GrainInterfaces; using Xunit; using Xunit.Abstractions; namespace UnitTests.General { public class RequestContextTests_Silo : OrleansTestingBase, IClassFixture<RequestContextTests_Silo.Fixture>, IDisposable { private readonly ITestOutputHelper output; private readonly Fixture fixture; private OutsideRuntimeClient runtimeClient; public class Fixture : BaseTestClusterFixture { protected override void ConfigureTestCluster(TestClusterBuilder builder) { builder.Options.InitialSilosCount = 1; builder.AddSiloBuilderConfigurator<SiloConfigurator>(); builder.AddClientBuilderConfigurator<ClientConfigurator>(); } } public class SiloConfigurator : ISiloBuilderConfigurator { public void Configure(ISiloHostBuilder hostBuilder) { hostBuilder.Configure<SiloMessagingOptions>(options => options.PropagateActivityId = true); } } public class ClientConfigurator : IClientBuilderConfigurator { public void Configure(IConfiguration configuration, IClientBuilder clientBuilder) { clientBuilder.Configure<SiloMessagingOptions>(options => options.PropagateActivityId = true); } } public RequestContextTests_Silo(ITestOutputHelper output, Fixture fixture) { this.output = output; this.fixture = fixture; this.runtimeClient = this.fixture.Client.ServiceProvider.GetRequiredService<OutsideRuntimeClient>(); RequestContext.PropagateActivityId = true; // Client-side setting RequestContextTestUtils.ClearActivityId(); RequestContext.Clear(); } public void Dispose() { RequestContextTestUtils.ClearActivityId(); RequestContext.Clear(); } [Fact, TestCategory("Functional"), TestCategory("RequestContext")] public async Task RequestContext_ActivityId_Simple() { Guid activityId = Guid.NewGuid(); IRequestContextTestGrain grain = this.fixture.GrainFactory.GetGrain<IRequestContextTestGrain>(GetRandomGrainId()); RequestContextTestUtils.SetActivityId(activityId); Guid result = await grain.E2EActivityId(); Assert.Equal(activityId, result); // "E2E ActivityId not propagated correctly" } [Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("RequestContext")] public async Task RequestContext_LegacyActivityId_Simple() { Guid activityId = Guid.NewGuid(); IRequestContextTestGrain grain = this.fixture.GrainFactory.GetGrain<IRequestContextTestGrain>(GetRandomGrainId()); Trace.CorrelationManager.ActivityId = activityId; Assert.True(RequestContext.PropagateActivityId); // "Verify activityId propagation is enabled." Guid result = await grain.E2ELegacyActivityId(); Assert.Equal(activityId, result); // "E2E ActivityId not propagated correctly" } [Fact, TestCategory("Functional"), TestCategory("RequestContext")] public async Task RequestContext_AC_Test1() { long id = GetRandomGrainId(); const string key = "TraceId"; string val = "TraceValue-" + id; string val2 = val + "-2"; var grain = this.fixture.GrainFactory.GetGrain<IRequestContextTestGrain>(id); RequestContext.Set(key, val); var result = await grain.TraceIdEcho(); Assert.Equal(val, result); // "Immediate RequestContext echo was not correct" RequestContext.Set(key, val2); result = await grain.TraceIdDoubleEcho(); Assert.Equal(val2, result); // "Transitive RequestContext echo was not correct" RequestContext.Set(key, val); result = await grain.TraceIdDelayedEcho1(); Assert.Equal(val, result); // "Delayed (StartNew) RequestContext echo was not correct"); RequestContext.Set(key, val2); result = await grain.TraceIdDelayedEcho2(); Assert.Equal(val2, result); // "Delayed (ContinueWith) RequestContext echo was not correct"); } [Fact, TestCategory("Functional"), TestCategory("RequestContext")] public async Task RequestContext_Task_Test1() { long id = GetRandomGrainId(); const string key = "TraceId"; string val = "TraceValue-" + id; string val2 = val + "-2"; var grain = this.fixture.GrainFactory.GetGrain<IRequestContextTaskGrain>(id); RequestContext.Set(key, val); var result = await grain.TraceIdEcho(); Assert.Equal(val, result); // "Immediate RequestContext echo was not correct" RequestContext.Set(key, val2); result = await grain.TraceIdDoubleEcho(); Assert.Equal(val2, result); // "Transitive RequestContext echo was not correct" RequestContext.Set(key, val); result = await grain.TraceIdDelayedEcho1(); Assert.Equal(val, result); // "Delayed (StartNew) RequestContext echo was not correct"); RequestContext.Set(key, val2); result = await grain.TraceIdDelayedEcho2(); Assert.Equal(val2, result); // "Delayed (ContinueWith) RequestContext echo was not correct"); RequestContext.Set(key, val); result = await grain.TraceIdDelayedEchoAwait(); Assert.Equal(val, result); // "Delayed (Await) RequestContext echo was not correct"); // Expected behaviour is this won't work, because Task.Run by design does not use Orleans task scheduler //RequestContext.Set(key, val2); //result = await grain.TraceIdDelayedEchoTaskRun(); //Assert.Equal(val2, result); // "Delayed (Task.Run) RequestContext echo was not correct"); } [Fact, TestCategory("Functional"), TestCategory("RequestContext")] public async Task RequestContext_Task_TestRequestContext() { var grain = this.fixture.GrainFactory.GetGrain<IRequestContextTaskGrain>(1); Tuple<string, string> requestContext = await grain.TestRequestContext(); this.fixture.Logger.Info("Request Context is: " + requestContext); Assert.Equal("binks", requestContext.Item1); // "Item1=" + requestContext.Item1 Assert.Equal("binks", requestContext.Item2); // "Item2=" + requestContext.Item2 } [Fact, TestCategory("Functional"), TestCategory("RequestContext")] public async Task RequestContext_ActivityId_RC_Set_E2E() { Guid activityId = Guid.NewGuid(); Guid activityId2 = Guid.NewGuid(); Guid nullActivityId = Guid.Empty; IRequestContextTestGrain grain = this.fixture.GrainFactory.GetGrain<IRequestContextTestGrain>(GetRandomGrainId()); RequestContext.Set(RequestContext.E2_E_TRACING_ACTIVITY_ID_HEADER, activityId); Guid result = await grain.E2EActivityId(); Assert.Equal(activityId, result); // "E2E ActivityId not propagated correctly" RequestContext.Clear(); RequestContext.Set(RequestContext.E2_E_TRACING_ACTIVITY_ID_HEADER, nullActivityId); result = await grain.E2EActivityId(); Assert.Equal(nullActivityId, result); // "Null ActivityId propagated E2E incorrectly" RequestContext.Clear(); RequestContext.Set(RequestContext.E2_E_TRACING_ACTIVITY_ID_HEADER, activityId2); result = await grain.E2EActivityId(); Assert.Equal(activityId2, result); // "E2E ActivityId 2 not propagated correctly" RequestContext.Clear(); } [Fact, TestCategory("Functional"), TestCategory("RequestContext")] public async Task RequestContext_ActivityId_CM_E2E() { Guid activityId = Guid.NewGuid(); Guid activityId2 = Guid.NewGuid(); Guid nullActivityId = Guid.Empty; IRequestContextTestGrain grain = this.fixture.GrainFactory.GetGrain<IRequestContextTestGrain>(GetRandomGrainId()); Trace.CorrelationManager.ActivityId = activityId; Assert.Null(RequestContext.Get(RequestContext.E2_E_TRACING_ACTIVITY_ID_HEADER)); Guid result = await grain.E2EActivityId(); Assert.Equal(activityId, result); // "E2E ActivityId not propagated correctly" RequestContext.Clear(); Trace.CorrelationManager.ActivityId = nullActivityId; Assert.Null(RequestContext.Get(RequestContext.E2_E_TRACING_ACTIVITY_ID_HEADER)); for (int i = 0; i < Environment.ProcessorCount; i++) { result = await grain.E2EActivityId(); Assert.Equal(nullActivityId, result); // "Null ActivityId propagated E2E incorrectly" } RequestContext.Clear(); Trace.CorrelationManager.ActivityId = activityId2; Assert.Null(RequestContext.Get(RequestContext.E2_E_TRACING_ACTIVITY_ID_HEADER)); result = await grain.E2EActivityId(); Assert.Equal(activityId2, result); // "E2E ActivityId 2 not propagated correctly" RequestContext.Clear(); } [Fact, TestCategory("Functional"), TestCategory("RequestContext")] public async Task RequestContext_ActivityId_CM_E2E_ViaProxy() { Guid activityId = Guid.NewGuid(); Guid activityId2 = Guid.NewGuid(); Guid nullActivityId = Guid.Empty; IRequestContextProxyGrain grain = this.fixture.GrainFactory.GetGrain<IRequestContextProxyGrain>(GetRandomGrainId()); Trace.CorrelationManager.ActivityId = activityId; Assert.Null(RequestContext.Get(RequestContext.E2_E_TRACING_ACTIVITY_ID_HEADER)); Guid result = await grain.E2EActivityId(); Assert.Equal(activityId, result); // "E2E ActivityId not propagated correctly" RequestContext.Clear(); Trace.CorrelationManager.ActivityId = nullActivityId; Assert.Null(RequestContext.Get(RequestContext.E2_E_TRACING_ACTIVITY_ID_HEADER)); for (int i = 0; i < Environment.ProcessorCount; i++) { result = await grain.E2EActivityId(); Assert.Equal(nullActivityId, result); // "Null ActivityId propagated E2E incorrectly" } RequestContext.Clear(); Trace.CorrelationManager.ActivityId = activityId2; Assert.Null(RequestContext.Get(RequestContext.E2_E_TRACING_ACTIVITY_ID_HEADER)); result = await grain.E2EActivityId(); Assert.Equal(activityId2, result); // "E2E ActivityId 2 not propagated correctly" RequestContext.Clear(); } [Fact, TestCategory("Functional"), TestCategory("RequestContext")] public async Task RequestContext_ActivityId_RC_None_E2E() { Guid nullActivityId = Guid.Empty; RequestContext.Clear(); IRequestContextTestGrain grain = this.fixture.GrainFactory.GetGrain<IRequestContextTestGrain>(GetRandomGrainId()); Guid result = await grain.E2EActivityId(); Assert.Equal(nullActivityId, result); // "E2E ActivityId should not exist" result = await grain.E2EActivityId(); Assert.Equal(nullActivityId, result); // "Null ActivityId propagated E2E incorrectly" RequestContext.Clear(); result = await grain.E2EActivityId(); Assert.Equal(nullActivityId, result); // "E2E ActivityId 2 should not exist" Assert.Null(RequestContext.Get(RequestContext.E2_E_TRACING_ACTIVITY_ID_HEADER)); // "No ActivityId context should be set" for (int i = 0; i < Environment.ProcessorCount; i++) { Assert.Null(RequestContext.Get(RequestContext.E2_E_TRACING_ACTIVITY_ID_HEADER)); // "No ActivityId context should be set" result = await grain.E2EActivityId(); Assert.Equal(nullActivityId, result); // "Null ActivityId propagated E2E incorrectly" RequestContext.Clear(); } } [Fact, TestCategory("Functional"), TestCategory("RequestContext")] public async Task RequestContext_ActivityId_CM_None_E2E() { Guid nullActivityId = Guid.Empty; IRequestContextTestGrain grain = this.fixture.GrainFactory.GetGrain<IRequestContextTestGrain>(GetRandomGrainId()); Guid result = grain.E2EActivityId().Result; Assert.Equal(nullActivityId, result); // "E2E ActivityId should not exist" RequestContextTestUtils.SetActivityId(nullActivityId); Assert.Null(RequestContext.Get(RequestContext.E2_E_TRACING_ACTIVITY_ID_HEADER)); result = await grain.E2EActivityId(); Assert.Equal(nullActivityId, result); // "Null ActivityId propagated E2E incorrectly" RequestContext.Clear(); RequestContextTestUtils.SetActivityId(nullActivityId); Assert.Null(RequestContext.Get(RequestContext.E2_E_TRACING_ACTIVITY_ID_HEADER)); for (int i = 0; i < Environment.ProcessorCount; i++) { result = await grain.E2EActivityId(); Assert.Equal(nullActivityId, result); // "Null ActivityId propagated E2E incorrectly" } RequestContext.Clear(); RequestContextTestUtils.SetActivityId(nullActivityId); Assert.Null(RequestContext.Get(RequestContext.E2_E_TRACING_ACTIVITY_ID_HEADER)); result = await grain.E2EActivityId(); Assert.Equal(nullActivityId, result); // "Null ActivityId propagated E2E incorrectly" RequestContext.Clear(); } [Fact, TestCategory("Functional"), TestCategory("RequestContext")] public async Task RequestContext_ActivityId_CM_DynamicChange_Client() { Guid activityId = Guid.NewGuid(); Guid activityId2 = Guid.NewGuid(); IRequestContextTestGrain grain = this.fixture.GrainFactory.GetGrain<IRequestContextTestGrain>(GetRandomGrainId()); Trace.CorrelationManager.ActivityId = activityId; Guid result = await grain.E2EActivityId(); Assert.Equal(activityId, result); // "E2E ActivityId #1 not propagated correctly" RequestContext.Clear(); RequestContext.PropagateActivityId = false; output.WriteLine("Set RequestContext.PropagateActivityId={0}", RequestContext.PropagateActivityId); Trace.CorrelationManager.ActivityId = activityId2; result = await grain.E2EActivityId(); Assert.Equal(Guid.Empty, result); // "E2E ActivityId #2 not not have been propagated" RequestContext.Clear(); RequestContext.PropagateActivityId = true; output.WriteLine("Set RequestContext.PropagateActivityId={0}", RequestContext.PropagateActivityId); Trace.CorrelationManager.ActivityId = activityId2; result = await grain.E2EActivityId(); Assert.Equal(activityId2, result); // "E2E ActivityId #2 should have been propagated" RequestContext.Clear(); Trace.CorrelationManager.ActivityId = activityId; result = await grain.E2EActivityId(); Assert.Equal(activityId, result); // "E2E ActivityId #1 not propagated correctly after #2" RequestContext.Clear(); } [Fact, TestCategory("Functional"), TestCategory("RequestContext")] public async Task ClientInvokeCallback_CountCallbacks() { TestClientInvokeCallback callback = new TestClientInvokeCallback(output, Guid.Empty); this.runtimeClient.ClientInvokeCallback = callback.OnInvoke; IRequestContextProxyGrain grain = this.fixture.GrainFactory.GetGrain<IRequestContextProxyGrain>(GetRandomGrainId()); RequestContextTestUtils.SetActivityId(Guid.Empty); Guid activityId = await grain.E2EActivityId(); Assert.Equal(Guid.Empty, activityId); // "E2EActivityId Call#1" Assert.Equal(1, callback.TotalCalls); // "Number of callbacks" this.runtimeClient.ClientInvokeCallback = null; activityId = await grain.E2EActivityId(); Assert.Equal(Guid.Empty, activityId); // "E2EActivityId Call#2" Assert.Equal(1, callback.TotalCalls); // "Number of callbacks - should be unchanged" } [Fact, TestCategory("Functional"), TestCategory("RequestContext")] public async Task ClientInvokeCallback_SetActivityId() { Guid setActivityId = Guid.NewGuid(); Guid activityId2 = Guid.NewGuid(); RequestContextTestUtils.SetActivityId(activityId2); TestClientInvokeCallback callback = new TestClientInvokeCallback(output, setActivityId); this.runtimeClient.ClientInvokeCallback = callback.OnInvoke; IRequestContextProxyGrain grain = this.fixture.GrainFactory.GetGrain<IRequestContextProxyGrain>(GetRandomGrainId()); Guid activityId = await grain.E2EActivityId(); Assert.Equal(setActivityId, activityId); // "E2EActivityId Call#1" Assert.Equal(1, callback.TotalCalls); // "Number of callbacks" RequestContextTestUtils.SetActivityId(Guid.Empty); RequestContext.Clear(); // Need this to clear out any old ActivityId value cached in RequestContext. Code optimization in RequestContext does not unset entry if Trace.CorrelationManager.ActivityId == Guid.Empty [which is the "normal" case] this.runtimeClient.ClientInvokeCallback = null; activityId = await grain.E2EActivityId(); Assert.Equal(Guid.Empty, activityId); // "E2EActivityId Call#2 == Zero" Assert.Equal(1, callback.TotalCalls); // "Number of callbacks - should be unchanged" } [Fact, TestCategory("Functional"), TestCategory("RequestContext")] public async Task ClientInvokeCallback_GrainObserver() { TestClientInvokeCallback callback = new TestClientInvokeCallback(output, Guid.Empty); this.runtimeClient.ClientInvokeCallback = callback.OnInvoke; RequestContextGrainObserver observer = new RequestContextGrainObserver(output, null, null); // CreateObjectReference will result in system target call to IClientObserverRegistrar. // We want to make sure this does not invoke ClientInvokeCallback. ISimpleGrainObserver reference = await this.fixture.GrainFactory.CreateObjectReference<ISimpleGrainObserver>(observer); GC.KeepAlive(observer); Assert.Equal(0, callback.TotalCalls); // "Number of callbacks" } } internal class RequestContextGrainObserver : ISimpleGrainObserver { private readonly ITestOutputHelper output; readonly Action<int, int, object> action; readonly object result; public RequestContextGrainObserver(ITestOutputHelper output, Action<int, int, object> action, object result) { this.output = output; this.action = action; this.result = result; } public void StateChanged(int a, int b) { output.WriteLine("RequestContextGrainObserver.StateChanged a={0} b={1}", a, b); this.action?.Invoke(a, b, this.result); } } public class Halo_RequestContextTests : OrleansTestingBase { private readonly ITestOutputHelper output; public Halo_RequestContextTests(ITestOutputHelper output) { this.output = output; } [Fact, TestCategory("Functional"), TestCategory("RequestContext")] public async Task Halo_RequestContextShouldBeMaintainedWhenThreadHoppingOccurs() { int numTasks = 20; Task[] tasks = new Task[numTasks]; for (int i = 0; i < numTasks; i++) { var closureInt = i; Func<Task> func = async () => { await ContextTester(closureInt); }; tasks[i] = Task.Run(func); } await Task.WhenAll(tasks); } private async Task ContextTester(int i) { RequestContext.Set("threadId", i); int contextId = (int)(RequestContext.Get("threadId") ?? -1); output.WriteLine("ExplicitId={0}, ContextId={2}, ManagedThreadId={1}", i, Thread.CurrentThread.ManagedThreadId, contextId); await FrameworkContextVerification(i).ConfigureAwait(false); } private async Task FrameworkContextVerification(int id) { for (int i = 0; i < 10; i++) { await Task.Delay(10); int contextId = (int)(RequestContext.Get("threadId") ?? -1); output.WriteLine("Inner, in loop {0}, Explicit Id={2}, ContextId={3}, ManagedThreadId={1}", i, Thread.CurrentThread.ManagedThreadId, id, contextId); Assert.Equal(id, contextId); } } } public class Halo_CallContextTests : OrleansTestingBase { private readonly ITestOutputHelper output; public Halo_CallContextTests(ITestOutputHelper output) { this.output = output; } [Fact, TestCategory("Functional"), TestCategory("RequestContext")] public async Task Halo_LogicalCallContextShouldBeMaintainedWhenThreadHoppingOccurs() { int numTasks = 20; Task[] tasks = new Task[numTasks]; for (int i = 0; i < numTasks; i++) { var closureInt = i; Func<Task> func = async () => { await ContextTester(closureInt); }; tasks[i] = Task.Run(func); } await Task.WhenAll(tasks); } private async Task ContextTester(int i) { CallContext.LogicalSetData("threadId", i); int contextId = (int)(CallContext.LogicalGetData("threadId") ?? -1); output.WriteLine("ExplicitId={0}, ContextId={2}, ManagedThreadId={1}", i, Thread.CurrentThread.ManagedThreadId, contextId); await FrameworkContextVerification(i).ConfigureAwait(false); } private async Task FrameworkContextVerification(int id) { for (int i = 0; i < 10; i++) { await Task.Delay(10); int contextId = (int)(CallContext.LogicalGetData("threadId") ?? -1); output.WriteLine("Inner, in loop {0}, Explicit Id={2}, ContextId={3}, ManagedThreadId={1}", i, Thread.CurrentThread.ManagedThreadId, id, contextId); Assert.Equal(id, contextId); } } } public class TestClientInvokeCallback { public int TotalCalls; private readonly ITestOutputHelper output; private readonly Guid setActivityId; public TestClientInvokeCallback(ITestOutputHelper output, Guid setActivityId) { this.output = output; this.setActivityId = setActivityId; } public void OnInvoke(InvokeMethodRequest request, IGrain grain) { // (NOT YET AVAILABLE) Interface name is available from: <c>grainReference.InterfaceName</c> // (NOT YET AVAILABLE) Method name is available from: <c>grainReference.GetMethodName(request.InterfaceId, request.MethodId)</c> // GrainId is available from: <c>grainReference.GrainId</c> // PrimaryKey is availabe from: <c>grainReference.GrainId.GetPrimaryKeyLong()</c> or <c>grainReference.GrainId.GetPrimaryKey()</c> depending on key type. // Call arguments are available from: <c>request.Arguments</c> array TotalCalls++; output.WriteLine("OnInvoke TotalCalls={0}", TotalCalls); try { output.WriteLine("OnInvoke called for Grain={0} PrimaryKey={1} GrainId={2} with {3} arguments", grain.GetType().FullName, ((GrainReference)grain).GrainId.GetPrimaryKeyLong(), ((GrainReference)grain).GrainId, request.Arguments != null ? request.Arguments.Length : 0); } catch (Exception exc) { output.WriteLine("**** Error OnInvoke for Grain={0} GrainId={1} with {2} arguments. Exception = {3}", grain.GetType().FullName, ((GrainReference)grain).GrainId, request.Arguments != null ? request.Arguments.Length : 0, exc); } if (setActivityId != Guid.Empty) { RequestContextTestUtils.SetActivityId(setActivityId); output.WriteLine("OnInvoke Set ActivityId={0}", setActivityId); } output.WriteLine("OnInvoke Current ActivityId={0}", RequestContextTestUtils.GetActivityId()); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Net.Security; using System.Runtime.CompilerServices; using System.Security.Authentication; using System.Security.Cryptography.X509Certificates; using System.Threading; using System.Threading.Tasks; using CURLAUTH = Interop.Http.CURLAUTH; using CURLcode = Interop.Http.CURLcode; using CURLMcode = Interop.Http.CURLMcode; using CURLoption = Interop.Http.CURLoption; namespace System.Net.Http { // Object model: // ------------- // CurlHandler provides an HttpMessageHandler implementation that wraps libcurl. The core processing for CurlHandler // is handled via a CurlHandler.MultiAgent instance, where currently a CurlHandler instance stores and uses a single // MultiAgent for the lifetime of the handler (with the MultiAgent lazily initialized on first use, so that it can // be initialized with all of the configured options on the handler). The MultiAgent is named as such because it wraps // a libcurl multi handle that's responsible for handling all requests on the instance. When a request arrives, it's // queued to the MultiAgent, which ensures that a thread is running to continually loop and process all work associated // with the multi handle until no more work is required; at that point, the thread is retired until more work arrives, // at which point another thread will be spun up. Any number of requests will have their handling multiplexed onto // this one event loop thread. Each request is represented by a CurlHandler.EasyRequest, so named because it wraps // a libcurl easy handle, libcurl's representation of a request. The EasyRequest stores all state associated with // the request, including the CurlHandler.CurlResponseMessage and CurlHandler.CurlResponseStream that are handed // back to the caller to provide access to the HTTP response information. // // Lifetime: // --------- // The MultiAgent is initialized on first use and is kept referenced by the CurlHandler for the remainder of the // handler's lifetime. Both are disposable, and disposing of the CurlHandler will dispose of the MultiAgent. // However, libcurl is not thread safe in that two threads can't be using the same multi or easy handles concurrently, // so any interaction with the multi handle must happen on the MultiAgent's thread. For this reason, the // SafeHandle storing the underlying multi handle has its ref count incremented when the MultiAgent worker is running // and decremented when it stops running, enabling any disposal requests to be delayed until the worker has quiesced. // To enable that to happen quickly when a dispose operation occurs, an "incoming request" (how all other threads // communicate with the MultiAgent worker) is queued to the worker to request a shutdown; upon receiving that request, // the worker will exit and allow the multi handle to be disposed of. // // An EasyRequest itself doesn't govern its own lifetime. Since an easy handle is added to a multi handle for // the multi handle to process, the easy handle must not be destroyed until after it's been removed from the multi handle. // As such, once the SafeHandle for an easy handle is created, although its stored in the EasyRequest instance, // it's also stored into a dictionary on the MultiAgent and has its ref count incremented to prevent it from being // disposed of while it's in use by the multi handle. // // When a request is made to the CurlHandler, callbacks are registered with libcurl, including state that will // be passed back into managed code and used to identify the associated EasyRequest. This means that the native // code needs to be able both to keep the EasyRequest alive and to refer to it using an IntPtr. For this, we // use a GCHandle to the EasyRequest. However, the native code needs to be able to refer to the EasyRequest for the // lifetime of the request, but we also need to avoid keeping the EasyRequest (and all state it references) alive artificially. // For the beginning phase of the request, the native code may be the only thing referencing the managed objects, since // when a caller invokes "Task<HttpResponseMessage> SendAsync(...)", there's nothing handed back to the caller that represents // the request until at least the HTTP response headers are received and the returned Task is completed with the response // message object. However, after that point, if the caller drops the HttpResponseMessage, we also want to cancel and // dispose of the associated state, which means something needs to be finalizable and not kept rooted while at the same // time still allowing the native code to continue using its GCHandle and lookup the associated state as long as it's alive. // Yet then when an async read is made on the response message, we want to postpone such finalization and ensure that the async // read can be appropriately completed with control and reference ownership given back to the reader. As such, we do two things: // we make the response stream finalizable, and we make the GCHandle be to a wrapper object for the EasyRequest rather than to // the EasyRequest itself. That wrapper object maintains a weak reference to the EasyRequest as well as sometimes maintaining // a strong reference. When the request starts out, the GCHandle is created to the wrapper, which has a strong reference to // the EasyRequest (which also back references to the wrapper so that the wrapper can be accessed via it). The GCHandle is // thus keeping the EasyRequest and all of the state it references alive, e.g. the CurlResponseStream, which itself has a reference // back to the EasyRequest. Once the request progresses to the point of receiving HTTP response headers and the HttpResponseMessage // is handed back to the caller, the wrapper object drops its strong reference and maintains only a weak reference. At this // point, if the caller were to drop its HttpResponseMessage object, that would also drop the only strong reference to the // CurlResponseStream; the CurlResponseStream would be available for collection and finalization, and its finalization would // request cancellation of the easy request to the multi agent. The multi agent would then in response remove the easy handle // from the multi handle and decrement the ref count on the SafeHandle for the easy handle, allowing it to be finalized and // the underlying easy handle released. If instead of dropping the HttpResponseMessage the caller makes a read request on the // response stream, the wrapper object is transitioned back to having a strong reference, so that even if the caller then drops // the HttpResponseMessage, the read Task returned from the read operation will still be completed eventually, at which point // the wrapper will transition back to being a weak reference. // // Even with that, of course, Dispose is still the recommended way of cleaning things up. Disposing the CurlResponseMessage // will Dispose the CurlResponseStream, which will Dispose of the SafeHandle for the easy handle and request that the MultiAgent // cancel the operation. Once canceled and removed, the SafeHandle will have its ref count decremented and the previous disposal // will proceed to release the underlying handle. internal partial class CurlHandler : HttpMessageHandler { #region Constants private const char SpaceChar = ' '; private const int StatusCodeLength = 3; private const string UriSchemeHttp = "http"; private const string UriSchemeHttps = "https"; private const string EncodingNameGzip = "gzip"; private const string EncodingNameDeflate = "deflate"; private const int MaxRequestBufferSize = 16384; // Default used by libcurl private const string NoTransferEncoding = HttpKnownHeaderNames.TransferEncoding + ":"; private const string NoContentType = HttpKnownHeaderNames.ContentType + ":"; private const int CurlAge = 5; private const int MinCurlAge = 3; #endregion #region Fields private static readonly KeyValuePair<string,CURLAUTH>[] s_orderedAuthTypes = new KeyValuePair<string, CURLAUTH>[] { new KeyValuePair<string,CURLAUTH>("Negotiate", CURLAUTH.Negotiate), new KeyValuePair<string,CURLAUTH>("NTLM", CURLAUTH.NTLM), new KeyValuePair<string,CURLAUTH>("Digest", CURLAUTH.Digest), new KeyValuePair<string,CURLAUTH>("Basic", CURLAUTH.Basic), }; // Max timeout value used by WinHttp handler, so mapping to that here. private static readonly TimeSpan s_maxTimeout = TimeSpan.FromMilliseconds(int.MaxValue); private static readonly char[] s_newLineCharArray = new char[] { HttpRuleParser.CR, HttpRuleParser.LF }; private static readonly bool s_supportsAutomaticDecompression; private static readonly bool s_supportsSSL; private static readonly bool s_supportsHttp2Multiplexing; private static volatile StrongBox<CURLMcode> s_supportsMaxConnectionsPerServer; private static string s_curlVersionDescription; private static string s_curlSslVersionDescription; private static readonly DiagnosticListener s_diagnosticListener = new DiagnosticListener(HttpHandlerLoggingStrings.DiagnosticListenerName); private readonly MultiAgent _agent; private volatile bool _anyOperationStarted; private volatile bool _disposed; private IWebProxy _proxy = null; private ICredentials _serverCredentials = null; private bool _useProxy = HttpHandlerDefaults.DefaultUseProxy; private ICredentials _defaultProxyCredentials = null; private DecompressionMethods _automaticDecompression = HttpHandlerDefaults.DefaultAutomaticDecompression; private bool _preAuthenticate = HttpHandlerDefaults.DefaultPreAuthenticate; private CredentialCache _credentialCache = null; // protected by LockObject private CookieContainer _cookieContainer = new CookieContainer(); private bool _useCookie = HttpHandlerDefaults.DefaultUseCookies; private TimeSpan _connectTimeout = Timeout.InfiniteTimeSpan; private bool _automaticRedirection = HttpHandlerDefaults.DefaultAutomaticRedirection; private int _maxAutomaticRedirections = HttpHandlerDefaults.DefaultMaxAutomaticRedirections; private int _maxConnectionsPerServer = HttpHandlerDefaults.DefaultMaxConnectionsPerServer; private int _maxResponseHeadersLength = HttpHandlerDefaults.DefaultMaxResponseHeaderLength; private ClientCertificateOption _clientCertificateOption = HttpHandlerDefaults.DefaultClientCertificateOption; private X509Certificate2Collection _clientCertificates; private Func<HttpRequestMessage, X509Certificate2, X509Chain, SslPolicyErrors, bool> _serverCertificateValidationCallback; private bool _checkCertificateRevocationList; private SslProtocols _sslProtocols = SslProtocols.None; // use default private IDictionary<String, Object> _properties; // Only create dictionary when required. private object LockObject { get { return _agent; } } #endregion static CurlHandler() { // curl_global_init call handled by Interop.LibCurl's cctor Interop.Http.CurlFeatures features = Interop.Http.GetSupportedFeatures(); s_supportsSSL = (features & Interop.Http.CurlFeatures.CURL_VERSION_SSL) != 0; s_supportsAutomaticDecompression = (features & Interop.Http.CurlFeatures.CURL_VERSION_LIBZ) != 0; s_supportsHttp2Multiplexing = (features & Interop.Http.CurlFeatures.CURL_VERSION_HTTP2) != 0 && Interop.Http.GetSupportsHttp2Multiplexing(); if (HttpEventSource.Log.IsEnabled()) { EventSourceTrace($"libcurl: {CurlVersionDescription} {CurlSslVersionDescription} {features}"); } } public CurlHandler() { _agent = new MultiAgent(this); } #region Properties private static string CurlVersionDescription => s_curlVersionDescription ?? (s_curlVersionDescription = Interop.Http.GetVersionDescription() ?? string.Empty); private static string CurlSslVersionDescription => s_curlSslVersionDescription ?? (s_curlSslVersionDescription = Interop.Http.GetSslVersionDescription() ?? string.Empty); internal bool AutomaticRedirection { get { return _automaticRedirection; } set { CheckDisposedOrStarted(); _automaticRedirection = value; } } internal bool SupportsProxy => true; internal bool SupportsRedirectConfiguration => true; internal bool UseProxy { get { return _useProxy; } set { CheckDisposedOrStarted(); _useProxy = value; } } internal IWebProxy Proxy { get { return _proxy; } set { CheckDisposedOrStarted(); _proxy = value; } } internal ICredentials DefaultProxyCredentials { get { return _defaultProxyCredentials; } set { CheckDisposedOrStarted(); _defaultProxyCredentials = value; } } internal ICredentials Credentials { get { return _serverCredentials; } set { _serverCredentials = value; } } internal ClientCertificateOption ClientCertificateOptions { get { return _clientCertificateOption; } set { if (value != ClientCertificateOption.Manual && value != ClientCertificateOption.Automatic) { throw new ArgumentOutOfRangeException(nameof(value)); } CheckDisposedOrStarted(); _clientCertificateOption = value; } } internal X509Certificate2Collection ClientCertificates => _clientCertificates ?? (_clientCertificates = new X509Certificate2Collection()); internal Func<HttpRequestMessage, X509Certificate2, X509Chain, SslPolicyErrors, bool> ServerCertificateValidationCallback { get { return _serverCertificateValidationCallback; } set { CheckDisposedOrStarted(); _serverCertificateValidationCallback = value; } } internal bool CheckCertificateRevocationList { get { return _checkCertificateRevocationList; } set { CheckDisposedOrStarted(); _checkCertificateRevocationList = value; } } internal SslProtocols SslProtocols { get { return _sslProtocols; } set { SecurityProtocol.ThrowOnNotAllowed(value, allowNone: true); CheckDisposedOrStarted(); _sslProtocols = value; } } private SslProtocols ActualSslProtocols => this.SslProtocols != SslProtocols.None ? this.SslProtocols : SecurityProtocol.DefaultSecurityProtocols; internal bool SupportsAutomaticDecompression => s_supportsAutomaticDecompression; internal DecompressionMethods AutomaticDecompression { get { return _automaticDecompression; } set { CheckDisposedOrStarted(); _automaticDecompression = value; } } internal bool PreAuthenticate { get { return _preAuthenticate; } set { CheckDisposedOrStarted(); _preAuthenticate = value; if (value && _credentialCache == null) { _credentialCache = new CredentialCache(); } } } internal bool UseCookie { get { return _useCookie; } set { CheckDisposedOrStarted(); _useCookie = value; } } internal CookieContainer CookieContainer { get { return _cookieContainer; } set { CheckDisposedOrStarted(); _cookieContainer = value; } } internal int MaxAutomaticRedirections { get { return _maxAutomaticRedirections; } set { if (value <= 0) { throw new ArgumentOutOfRangeException(nameof(value), value, SR.Format(SR.net_http_value_must_be_greater_than, 0)); } CheckDisposedOrStarted(); _maxAutomaticRedirections = value; } } internal int MaxConnectionsPerServer { get { return _maxConnectionsPerServer; } set { if (value < 1) { throw new ArgumentOutOfRangeException(nameof(value), value, SR.Format(SR.net_http_value_must_be_greater_than, 0)); } // Make sure the libcurl version we're using supports the option, by setting the value on a temporary multi handle. // We do this once and cache the result. StrongBox<CURLMcode> supported = s_supportsMaxConnectionsPerServer; // benign race condition to read and set this if (supported == null) { using (Interop.Http.SafeCurlMultiHandle multiHandle = Interop.Http.MultiCreate()) { s_supportsMaxConnectionsPerServer = supported = new StrongBox<CURLMcode>( Interop.Http.MultiSetOptionLong(multiHandle, Interop.Http.CURLMoption.CURLMOPT_MAX_HOST_CONNECTIONS, value)); } } if (supported.Value != CURLMcode.CURLM_OK) { throw new PlatformNotSupportedException(CurlException.GetCurlErrorString((int)supported.Value, isMulti: true)); } CheckDisposedOrStarted(); _maxConnectionsPerServer = value; } } internal int MaxResponseHeadersLength { get { return _maxResponseHeadersLength; } set { if (value <= 0) { throw new ArgumentOutOfRangeException(nameof(value), value, SR.Format(SR.net_http_value_must_be_greater_than, 0)); } CheckDisposedOrStarted(); _maxResponseHeadersLength = value; } } internal bool UseDefaultCredentials { get { return false; } set { } } public IDictionary<string, object> Properties { get { if (_properties == null) { _properties = new Dictionary<String, object>(); } return _properties; } } #endregion protected override void Dispose(bool disposing) { _disposed = true; if (disposing) { _agent.Dispose(); } base.Dispose(disposing); } protected internal override Task<HttpResponseMessage> SendAsync( HttpRequestMessage request, CancellationToken cancellationToken) { if (request == null) { throw new ArgumentNullException(nameof(request), SR.net_http_handler_norequest); } if (request.RequestUri.Scheme == UriSchemeHttps) { if (!s_supportsSSL) { throw new PlatformNotSupportedException(SR.Format(SR.net_http_unix_https_support_unavailable_libcurl, CurlVersionDescription)); } } else { Debug.Assert(request.RequestUri.Scheme == UriSchemeHttp, "HttpClient expected to validate scheme as http or https."); } if (request.Headers.TransferEncodingChunked.GetValueOrDefault() && (request.Content == null)) { throw new InvalidOperationException(SR.net_http_chunked_not_allowed_with_empty_content); } if (_useCookie && _cookieContainer == null) { throw new InvalidOperationException(SR.net_http_invalid_cookiecontainer); } CheckDisposed(); SetOperationStarted(); // Do an initial cancellation check to avoid initiating the async operation if // cancellation has already been requested. After this, we'll rely on CancellationToken.Register // to notify us of cancellation requests and shut down the operation if possible. if (cancellationToken.IsCancellationRequested) { return Task.FromCanceled<HttpResponseMessage>(cancellationToken); } Guid loggingRequestId = s_diagnosticListener.LogHttpRequest(request); // Create the easy request. This associates the easy request with this handler and configures // it based on the settings configured for the handler. var easy = new EasyRequest(this, request, cancellationToken); try { EventSourceTrace("{0}", request, easy: easy, agent: _agent); _agent.Queue(new MultiAgent.IncomingRequest { Easy = easy, Type = MultiAgent.IncomingRequestType.New }); } catch (Exception exc) { easy.FailRequestAndCleanup(exc); } s_diagnosticListener.LogHttpResponse(easy.Task, loggingRequestId); return easy.Task; } #region Private methods private void SetOperationStarted() { if (!_anyOperationStarted) { _anyOperationStarted = true; } } private KeyValuePair<NetworkCredential, CURLAUTH> GetCredentials(Uri requestUri) { // If preauthentication is enabled, we may have populated our internal credential cache, // so first check there to see if we have any credentials for this uri. if (_preAuthenticate) { KeyValuePair<NetworkCredential, CURLAUTH> ncAndScheme; lock (LockObject) { Debug.Assert(_credentialCache != null, "Expected non-null credential cache"); ncAndScheme = GetCredentials(requestUri, _credentialCache, s_orderedAuthTypes); } if (ncAndScheme.Key != null) { return ncAndScheme; } } // We either weren't preauthenticating or we didn't have any cached credentials // available, so check the credentials on the handler. return GetCredentials(requestUri, _serverCredentials, s_orderedAuthTypes); } private void TransferCredentialsToCache(Uri serverUri, CURLAUTH serverAuthAvail) { if (_serverCredentials == null) { // No credentials, nothing to put into the cache. return; } lock (LockObject) { // For each auth type we allow, check whether it's one supported by the server. KeyValuePair<string, CURLAUTH>[] validAuthTypes = s_orderedAuthTypes; for (int i = 0; i < validAuthTypes.Length; i++) { // Is it supported by the server? if ((serverAuthAvail & validAuthTypes[i].Value) != 0) { // And do we have a credential for it? NetworkCredential nc = _serverCredentials.GetCredential(serverUri, validAuthTypes[i].Key); if (nc != null) { // We have a credential for it, so add it, and we're done. Debug.Assert(_credentialCache != null, "Expected non-null credential cache"); try { _credentialCache.Add(serverUri, validAuthTypes[i].Key, nc); } catch (ArgumentException) { // Ignore the case of key already present } break; } } } } } private void AddResponseCookies(EasyRequest state, string cookieHeader) { if (!_useCookie) { return; } try { _cookieContainer.SetCookies(state._requestMessage.RequestUri, cookieHeader); state.SetCookieOption(state._requestMessage.RequestUri); } catch (CookieException e) { EventSourceTrace( "Malformed cookie parsing failed: {0}, server: {1}, cookie: {2}", e.Message, state._requestMessage.RequestUri, cookieHeader, easy: state); } } private static KeyValuePair<NetworkCredential, CURLAUTH> GetCredentials(Uri requestUri, ICredentials credentials, KeyValuePair<string, CURLAUTH>[] validAuthTypes) { NetworkCredential nc = null; CURLAUTH curlAuthScheme = CURLAUTH.None; if (credentials != null) { // For each auth type we consider valid, try to get a credential for it. // Union together the auth types for which we could get credentials, but validate // that the found credentials are all the same, as libcurl doesn't support differentiating // by auth type. for (int i = 0; i < validAuthTypes.Length; i++) { NetworkCredential networkCredential = credentials.GetCredential(requestUri, validAuthTypes[i].Key); if (networkCredential != null) { curlAuthScheme |= validAuthTypes[i].Value; if (nc == null) { nc = networkCredential; } else if(!AreEqualNetworkCredentials(nc, networkCredential)) { throw new PlatformNotSupportedException(SR.Format(SR.net_http_unix_invalid_credential, CurlVersionDescription)); } } } } EventSourceTrace("Authentication scheme: {0}", curlAuthScheme); return new KeyValuePair<NetworkCredential, CURLAUTH>(nc, curlAuthScheme); ; } private void CheckDisposed() { if (_disposed) { throw new ObjectDisposedException(GetType().FullName); } } private void CheckDisposedOrStarted() { CheckDisposed(); if (_anyOperationStarted) { throw new InvalidOperationException(SR.net_http_operation_started); } } private static void ThrowIfCURLEError(CURLcode error) { if (error != CURLcode.CURLE_OK) // success { string msg = CurlException.GetCurlErrorString((int)error, isMulti: false); EventSourceTrace(msg); switch (error) { case CURLcode.CURLE_OPERATION_TIMEDOUT: throw new OperationCanceledException(msg); case CURLcode.CURLE_OUT_OF_MEMORY: throw new OutOfMemoryException(msg); default: throw new CurlException((int)error, msg); } } } private static void ThrowIfCURLMError(CURLMcode error) { if (error != CURLMcode.CURLM_OK && // success error != CURLMcode.CURLM_CALL_MULTI_PERFORM) // success + a hint to try curl_multi_perform again { string msg = CurlException.GetCurlErrorString((int)error, isMulti: true); EventSourceTrace(msg); switch (error) { case CURLMcode.CURLM_ADDED_ALREADY: case CURLMcode.CURLM_BAD_EASY_HANDLE: case CURLMcode.CURLM_BAD_HANDLE: case CURLMcode.CURLM_BAD_SOCKET: throw new ArgumentException(msg); case CURLMcode.CURLM_UNKNOWN_OPTION: throw new ArgumentOutOfRangeException(msg); case CURLMcode.CURLM_OUT_OF_MEMORY: throw new OutOfMemoryException(msg); case CURLMcode.CURLM_INTERNAL_ERROR: default: throw new CurlException((int)error, msg); } } } private static bool AreEqualNetworkCredentials(NetworkCredential credential1, NetworkCredential credential2) { Debug.Assert(credential1 != null && credential2 != null, "arguments are non-null in network equality check"); return credential1.UserName == credential2.UserName && credential1.Domain == credential2.Domain && string.Equals(credential1.Password, credential2.Password, StringComparison.Ordinal); } private static bool EventSourceTracingEnabled { get { return HttpEventSource.Log.IsEnabled(); } } // PERF NOTE: // These generic overloads of EventSourceTrace (and similar wrapper methods in some of the other CurlHandler // nested types) exist to allow call sites to call EventSourceTrace without boxing and without checking // EventSourceTracingEnabled. Do not remove these without fixing the call sites accordingly. private static void EventSourceTrace<TArg0>( string formatMessage, TArg0 arg0, MultiAgent agent = null, EasyRequest easy = null, [CallerMemberName] string memberName = null) { if (EventSourceTracingEnabled) { EventSourceTraceCore(string.Format(formatMessage, arg0), agent, easy, memberName); } } private static void EventSourceTrace<TArg0, TArg1, TArg2> (string formatMessage, TArg0 arg0, TArg1 arg1, TArg2 arg2, MultiAgent agent = null, EasyRequest easy = null, [CallerMemberName] string memberName = null) { if (EventSourceTracingEnabled) { EventSourceTraceCore(string.Format(formatMessage, arg0, arg1, arg2), agent, easy, memberName); } } private static void EventSourceTrace( string message, MultiAgent agent = null, EasyRequest easy = null, [CallerMemberName] string memberName = null) { if (EventSourceTracingEnabled) { EventSourceTraceCore(message, agent, easy, memberName); } } private static void EventSourceTraceCore(string message, MultiAgent agent, EasyRequest easy, string memberName) { // If we weren't handed a multi agent, see if we can get one from the EasyRequest if (agent == null && easy != null) { agent = easy._associatedMultiAgent; } HttpEventSource.Log.HandlerMessage( (agent?.RunningWorkerId).GetValueOrDefault(), easy != null ? easy.Task.Id : 0, memberName, message); } private static HttpRequestException CreateHttpRequestException(Exception inner) { return new HttpRequestException(SR.net_http_client_execution_error, inner); } private static IOException MapToReadWriteIOException(Exception error, bool isRead) { return new IOException( isRead ? SR.net_http_io_read : SR.net_http_io_write, error is HttpRequestException && error.InnerException != null ? error.InnerException : error); } private static void SetChunkedModeForSend(HttpRequestMessage request) { bool chunkedMode = request.Headers.TransferEncodingChunked.GetValueOrDefault(); HttpContent requestContent = request.Content; Debug.Assert(requestContent != null, "request is null"); // Deal with conflict between 'Content-Length' vs. 'Transfer-Encoding: chunked' semantics. // libcurl adds a Transfer-Encoding header by default and the request fails if both are set. if (requestContent.Headers.ContentLength.HasValue) { if (chunkedMode) { // Same behaviour as WinHttpHandler requestContent.Headers.ContentLength = null; } else { // Prevent libcurl from adding Transfer-Encoding header request.Headers.TransferEncodingChunked = false; } } else if (!chunkedMode) { // Make sure Transfer-Encoding: chunked header is set, // as we have content to send but no known length for it. request.Headers.TransferEncodingChunked = true; } } #endregion } }
/* **************************************************************************** * * 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 * [email protected]. 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.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Text; using System.Text.RegularExpressions; using Microsoft.Scripting; using Microsoft.Scripting.Runtime; using Microsoft.Scripting.Utils; using IronPython.Runtime; using IronPython.Runtime.Exceptions; using IronPython.Runtime.Operations; using IronPython.Runtime.Types; [assembly: PythonModule("re", typeof(IronPython.Modules.PythonRegex))] namespace IronPython.Modules { /// <summary> /// Python regular expression module. /// </summary> public static class PythonRegex { private static CacheDict<PatternKey, RE_Pattern> _cachedPatterns = new CacheDict<PatternKey, RE_Pattern>(100); [SpecialName] public static void PerformModuleReload(PythonContext/*!*/ context, PythonDictionary/*!*/ dict) { context.EnsureModuleException("reerror", dict, "error", "re"); PythonCopyReg.GetDispatchTable(context.SharedContext)[DynamicHelpers.GetPythonTypeFromType(typeof(RE_Pattern))] = dict["_pickle"]; } private static readonly Random r = new Random(DateTime.Now.Millisecond); #region CONSTANTS // short forms public const int I = 0x02; public const int L = 0x04; public const int M = 0x08; public const int S = 0x10; public const int U = 0x20; public const int X = 0x40; public const int A = 0x100; // long forms public const int IGNORECASE = 0x02; public const int LOCALE = 0x04; public const int MULTILINE = 0x08; public const int DOTALL = 0x10; public const int UNICODE = 0x20; public const int VERBOSE = 0x40; public const int ASCII = 0x100; #endregion #region Public API Surface public static RE_Pattern compile(CodeContext/*!*/ context, object pattern) { try { return GetPattern(context, pattern, 0, true); } catch (ArgumentException e) { throw PythonExceptions.CreateThrowable(error(context), e.Message); } } public static RE_Pattern compile(CodeContext/*!*/ context, object pattern, object flags) { try { return GetPattern(context, pattern, PythonContext.GetContext(context).ConvertToInt32(flags), true); } catch (ArgumentException e) { throw PythonExceptions.CreateThrowable(error(context), e.Message); } } public const string engine = "cli reg ex"; public static string escape(string text) { if (text == null) throw PythonOps.TypeError("text must not be None"); for (int i = 0; i < text.Length; i++) { if (!Char.IsLetterOrDigit(text[i])) { StringBuilder sb = new StringBuilder(text, 0, i, text.Length); char ch = text[i]; do { sb.Append('\\'); sb.Append(ch); i++; int last = i; while (i < text.Length) { ch = text[i]; if (!Char.IsLetterOrDigit(ch)) { break; } i++; } sb.Append(text, last, i - last); } while (i < text.Length); return sb.ToString(); } } return text; } public static List findall(CodeContext/*!*/ context, object pattern, string @string) { return findall(context, pattern, @string, 0); } public static List findall(CodeContext/*!*/ context, object pattern, string @string, int flags) { RE_Pattern pat = GetPattern(context, ValidatePattern(pattern), flags); ValidateString(@string, "string"); MatchCollection mc = pat.FindAllWorker(context, @string, 0, @string.Length); return FixFindAllMatch(pat, mc, null); } public static List findall(CodeContext/*!*/ context, object pattern, IList<byte> @string) { return findall(context, pattern, @string, 0); } public static List findall(CodeContext/*!*/ context, object pattern, IList<byte> @string, int flags) { RE_Pattern pat = GetPattern(context, ValidatePattern (pattern), flags); ValidateString (@string, "string"); MatchCollection mc = pat.FindAllWorker(context, @string, 0, @string.Count); return FixFindAllMatch (pat, mc, FindMaker(@string)); } private static Func<string, object> FindMaker (object input) { Func<string, object> maker = null; if (input is ByteArray) { maker = delegate (string x) { return new ByteArray (x.MakeByteArray ()); }; } return maker; } private static List FixFindAllMatch(RE_Pattern pat, MatchCollection mc, Func<string, object> maker) { object[] matches = new object[mc.Count]; int numgrps = pat._re.GetGroupNumbers().Length; for (int i = 0; i < mc.Count; i++) { if (numgrps > 2) { // CLR gives us a "bonus" group of 0 - the entire expression // at this point we have more than one group in the pattern; // need to return a list of tuples in this case // for each match item in the matchcollection, create a tuple representing what was matched // e.g. findall("(\d+)|(\w+)", "x = 99y") == [('', 'x'), ('99', ''), ('', 'y')] // in the example above, ('', 'x') did not match (\d+) as indicated by '' but did // match (\w+) as indicated by 'x' and so on... int k = 0; List<object> tpl = new List<object>(); foreach (Group g in mc[i].Groups) { // here also the CLR gives us a "bonus" match as the first item which is the // group that was actually matched in the tuple e.g. we get 'x', '', 'x' for // the first match object...so we'll skip the first item when creating the // tuple if (k++ != 0) { tpl.Add(maker != null ? maker(g.Value) : g.Value); } } matches[i] = PythonTuple.Make(tpl); } else if (numgrps == 2) { // at this point we have exactly one group in the pattern (including the "bonus" one given // by the CLR // skip the first match since that contains the entire match and not the group match // e.g. re.findall(r"(\w+)\s+fish\b", "green fish") will have "green fish" in the 0 // index and "green" as the (\w+) group match matches[i] = maker != null ? maker(mc[i].Groups[1].Value) : mc[i].Groups[1].Value; } else { matches[i] = maker != null ? maker (mc[i].Value) : mc[i].Value; } } return List.FromArrayNoCopy(matches); } public static object finditer(CodeContext/*!*/ context, object pattern, object @string) { return finditer(context, pattern, @string, 0); } public static object finditer(CodeContext/*!*/ context, object pattern, object @string, int flags) { RE_Pattern pat = GetPattern(context, ValidatePattern(pattern), flags); string str = ValidateString(@string, "string"); return MatchIterator(pat.FindAllWorker(context, str, 0, str.Length), pat, str); } public static RE_Match match(CodeContext/*!*/ context, object pattern, object @string) { return match(context, pattern, @string, 0); } public static RE_Match match(CodeContext/*!*/ context, object pattern, object @string, int flags) { return GetPattern(context, ValidatePattern(pattern), flags).match(ValidateString(@string, "string")); } public static RE_Match search(CodeContext/*!*/ context, object pattern, object @string) { return search(context, pattern, @string, 0); } public static RE_Match search(CodeContext/*!*/ context, object pattern, object @string, int flags) { return GetPattern(context, ValidatePattern(pattern), flags).search(ValidateString(@string, "string")); } [return: SequenceTypeInfo(typeof(string))] public static List split(CodeContext/*!*/ context, object pattern, object @string) { return split(context, ValidatePattern(pattern), ValidateString(@string, "string"), 0); } [return: SequenceTypeInfo(typeof(string))] public static List split(CodeContext/*!*/ context, object pattern, object @string, int maxsplit) { return GetPattern(context, ValidatePattern(pattern), 0).split(ValidateString(@string, "string"), maxsplit); } public static string sub(CodeContext/*!*/ context, object pattern, object repl, object @string) { return sub(context, pattern, repl, @string, Int32.MaxValue); } public static string sub(CodeContext/*!*/ context, object pattern, object repl, object @string, int count) { return GetPattern(context, ValidatePattern(pattern), 0).sub(context, repl, ValidateString(@string, "string"), count); } public static object subn(CodeContext/*!*/ context, object pattern, object repl, object @string) { return subn(context, pattern, repl, @string, Int32.MaxValue); } public static object subn(CodeContext/*!*/ context, object pattern, object repl, object @string, int count) { return GetPattern(context, ValidatePattern(pattern), 0).subn(context, repl, ValidateString(@string, "string"), count); } public static void purge() { _cachedPatterns = new CacheDict<PatternKey, RE_Pattern>(100); } #endregion #region Public classes /// <summary> /// Compiled reg-ex pattern /// </summary> [PythonType] public class RE_Pattern : IWeakReferenceable { internal Regex _re; private PythonDictionary _groups; private int _compileFlags; private WeakRefTracker _weakRefTracker; internal ParsedRegex _pre; internal RE_Pattern(CodeContext/*!*/ context, object pattern) : this(context, pattern, 0) { } internal RE_Pattern(CodeContext/*!*/ context, object pattern, int flags) : this(context, pattern, flags, false) { } internal RE_Pattern(CodeContext/*!*/ context, object pattern, int flags, bool compiled) { _pre = PreParseRegex(context, ValidatePatternAsString(pattern)); try { flags |= OptionToFlags(_pre.Options); RegexOptions opts = FlagsToOption(flags); #if SILVERLIGHT this._re = new Regex(_pre.Pattern, opts); #else this._re = new Regex(_pre.Pattern, opts | (compiled ? RegexOptions.Compiled : RegexOptions.None)); #endif } catch (ArgumentException e) { throw PythonExceptions.CreateThrowable(error(context), e.Message); } this._compileFlags = flags; } public RE_Match match(object text) { string input = ValidateString(text, "text"); return RE_Match.makeMatch(_re.Match(input), this, input, 0, input.Length); } private static int FixPosition(string text, int position) { if (position < 0) return 0; if (position > text.Length) return text.Length; return position; } public RE_Match match(object text, int pos) { string input = ValidateString(text, "text"); pos = FixPosition(input, pos); return RE_Match.makeMatch(_re.Match(input, pos), this, input, pos, input.Length); } public RE_Match match(object text, [DefaultParameterValue(0)]int pos, int endpos) { string input = ValidateString(text, "text"); pos = FixPosition(input, pos); endpos = FixPosition(input, endpos); return RE_Match.makeMatch( _re.Match(input.Substring(0, endpos), pos), this, input, pos, endpos); } public RE_Match search(object text) { string input = ValidateString(text, "text"); return RE_Match.make(_re.Match(input), this, input); } public RE_Match search(object text, int pos) { string input = ValidateString(text, "text"); return RE_Match.make(_re.Match(input, pos, input.Length - pos), this, input); } public RE_Match search(object text, int pos, int endpos) { string input = ValidateString(text, "text"); return RE_Match.make(_re.Match(input, pos, Math.Min(Math.Max(endpos - pos, 0), input.Length - pos)), this, input); } public object findall(CodeContext/*!*/ context, string @string) { return findall(context, @string, 0, null); } public object findall(CodeContext/*!*/ context, string @string, int pos) { return findall(context, @string, pos, null); } public object findall(CodeContext/*!*/ context, object @string, int pos, object endpos) { MatchCollection mc = FindAllWorker(context, ValidateString(@string, "text"), pos, endpos); return FixFindAllMatch(this, mc, FindMaker(@string)); } internal MatchCollection FindAllWorker(CodeContext/*!*/ context, string str, int pos, object endpos) { string against = str; if (endpos != null) { int end = PythonContext.GetContext(context).ConvertToInt32(endpos); against = against.Substring(0, Math.Max(end, 0)); } return _re.Matches(against, pos); } internal MatchCollection FindAllWorker(CodeContext/*!*/ context, IList<byte> str, int pos, object endpos) { string against = str.MakeString(); if (endpos != null) { int end = PythonContext.GetContext(context).ConvertToInt32(endpos); against = against.Substring(0, Math.Max(end, 0)); } return _re.Matches(against, pos); } public object finditer(CodeContext/*!*/ context, object @string) { string input = ValidateString(@string, "string"); return MatchIterator(FindAllWorker(context, input, 0, input.Length), this, input); } public object finditer(CodeContext/*!*/ context, object @string, int pos) { string input = ValidateString(@string, "string"); return MatchIterator(FindAllWorker(context, input, pos, input.Length), this, input); } public object finditer(CodeContext/*!*/ context, object @string, int pos, int endpos) { string input = ValidateString(@string, "string"); return MatchIterator(FindAllWorker(context, input, pos, endpos), this, input); } [return: SequenceTypeInfo(typeof(string))] public List split(string @string) { return split(@string, 0); } [return: SequenceTypeInfo(typeof(string))] public List split(object @string, int maxsplit) { List result = new List(); // fast path for negative maxSplit ( == "make no splits") if (maxsplit < 0) { result.AddNoLock(ValidateString(@string, "string")); } else { // iterate over all matches string theStr = ValidateString(@string, "string"); MatchCollection matches = _re.Matches(theStr); int lastPos = 0; // is either start of the string, or first position *after* the last match int nSplits = 0; // how many splits have occurred? foreach (Match m in matches) { if (m.Length > 0) { // add substring from lastPos to beginning of current match result.AddNoLock(theStr.Substring(lastPos, m.Index - lastPos)); // if there are subgroups of the match, add their match or None if (m.Groups.Count > 1) for (int i = 1; i < m.Groups.Count; i++) if (m.Groups[i].Success) result.AddNoLock(m.Groups[i].Value); else result.AddNoLock(null); // update lastPos, nSplits lastPos = m.Index + m.Length; nSplits++; if (nSplits == maxsplit) break; } } // add tail following last match result.AddNoLock(theStr.Substring(lastPos)); } return result; } public string sub(CodeContext/*!*/ context, object repl, object @string) { return sub(context, repl, ValidateString(@string, "string"), Int32.MaxValue); } public string sub(CodeContext/*!*/ context, object repl, object @string, int count) { if (repl == null) throw PythonOps.TypeError("NoneType is not valid repl"); // if 'count' is omitted or 0, all occurrences are replaced if (count == 0) count = Int32.MaxValue; string replacement = repl as string; if (replacement == null) { if (repl is ExtensibleString) { replacement = ((ExtensibleString)repl).Value; } else if (repl is Bytes) { replacement = ((Bytes)repl).ToString(); } } Match prev = null; string input = ValidateString(@string, "string"); return _re.Replace( input, delegate(Match match) { // from the docs: Empty matches for the pattern are replaced // only when not adjacent to a previous match if (String.IsNullOrEmpty(match.Value) && prev != null && (prev.Index + prev.Length) == match.Index) { return ""; }; prev = match; if (replacement != null) return UnescapeGroups(match, replacement); return PythonCalls.Call(context, repl, RE_Match.make(match, this, input)) as string; }, count); } public object subn(CodeContext/*!*/ context, object repl, string @string) { return subn(context, repl, @string, Int32.MaxValue); } public object subn(CodeContext/*!*/ context, object repl, object @string, int count) { if (repl == null) throw PythonOps.TypeError("NoneType is not valid repl"); // if 'count' is omitted or 0, all occurrences are replaced if (count == 0) count = Int32.MaxValue; int totalCount = 0; string res; string replacement = repl as string; if (replacement == null) { if (repl is ExtensibleString) { replacement = ((ExtensibleString)repl).Value; } else if (repl is Bytes) { replacement = ((Bytes)repl).ToString(); } } Match prev = null; string input = ValidateString(@string, "string"); res = _re.Replace( input, delegate(Match match) { // from the docs: Empty matches for the pattern are replaced // only when not adjacent to a previous match if (String.IsNullOrEmpty(match.Value) && prev != null && (prev.Index + prev.Length) == match.Index) { return ""; }; prev = match; totalCount++; if (replacement != null) return UnescapeGroups(match, replacement); return PythonCalls.Call(context, repl, RE_Match.make(match, this, input)) as string; }, count); return PythonTuple.MakeTuple(res, totalCount); } public int flags { get { return _compileFlags; } } public PythonDictionary groupindex { get { if (_groups == null) { PythonDictionary d = new PythonDictionary(); string[] names = _re.GetGroupNames(); int[] nums = _re.GetGroupNumbers(); for (int i = 1; i < names.Length; i++) { if (Char.IsDigit(names[i][0]) || names[i].StartsWith(_mangledNamedGroup)) { // skip numeric names and our mangling for unnamed groups mixed w/ named groups. continue; } d[names[i]] = nums[i]; } _groups = d; } return _groups; } } public int groups { get { return _re.GetGroupNumbers().Length - 1; } } public string pattern { get { return _pre.UserPattern; } } public override bool Equals(object obj) { RE_Pattern other = obj as RE_Pattern; if (other == null) { return false; } return other.pattern == pattern && other.flags == flags; } public override int GetHashCode() { return pattern.GetHashCode() ^ flags; } #region IWeakReferenceable Members WeakRefTracker IWeakReferenceable.GetWeakRef() { return _weakRefTracker; } bool IWeakReferenceable.SetWeakRef(WeakRefTracker value) { _weakRefTracker = value; return true; } void IWeakReferenceable.SetFinalizer(WeakRefTracker value) { ((IWeakReferenceable)this).SetWeakRef(value); } #endregion } public static PythonTuple _pickle(CodeContext/*!*/ context, RE_Pattern pattern) { object scope = Importer.ImportModule(context, new PythonDictionary(), "re", false, 0); object compile; if (scope is PythonModule && ((PythonModule)scope).__dict__.TryGetValue("compile", out compile)) { return PythonTuple.MakeTuple(compile, PythonTuple.MakeTuple(pattern.pattern, pattern.flags)); } throw new InvalidOperationException("couldn't find compile method"); } [PythonType] public class RE_Match { RE_Pattern _pattern; private Match _m; private string _text; private int _lastindex = -1; private int _pos, _endPos; #region Internal makers internal static RE_Match make(Match m, RE_Pattern pattern, string input) { if (m.Success) return new RE_Match(m, pattern, input, 0, input.Length); return null; } internal static RE_Match make(Match m, RE_Pattern pattern, string input, int offset, int endpos) { if (m.Success) return new RE_Match(m, pattern, input, offset, endpos); return null; } internal static RE_Match makeMatch(Match m, RE_Pattern pattern, string input, int offset, int endpos) { if (m.Success && m.Index == offset) return new RE_Match(m, pattern, input, offset, endpos); return null; } #endregion #region Public ctors public RE_Match(Match m, RE_Pattern pattern, string text) { _m = m; _pattern = pattern; _text = text; } public RE_Match(Match m, RE_Pattern pattern, string text, int pos, int endpos) { _m = m; _pattern = pattern; _text = text; _pos = pos; _endPos = endpos; } #endregion // public override bool __bool__() { // return m.Success; // } #region Public API Surface public int end() { return _m.Index + _m.Length; } public int start() { return _m.Index; } public int start(object group) { int grpIndex = GetGroupIndex(group); if (!_m.Groups[grpIndex].Success) { return -1; } return _m.Groups[grpIndex].Index; } public int end(object group) { int grpIndex = GetGroupIndex(group); if (!_m.Groups[grpIndex].Success) { return -1; } return _m.Groups[grpIndex].Index + _m.Groups[grpIndex].Length; } public object group(object index, params object[] additional) { if (additional.Length == 0) { return group(index); } object[] res = new object[additional.Length + 1]; res[0] = _m.Groups[GetGroupIndex(index)].Success ? _m.Groups[GetGroupIndex(index)].Value : null; for (int i = 1; i < res.Length; i++) { int grpIndex = GetGroupIndex(additional[i - 1]); res[i] = _m.Groups[grpIndex].Success ? _m.Groups[grpIndex].Value : null; } return PythonTuple.MakeTuple(res); } public string group(object index) { int pos = GetGroupIndex(index); Group g = _m.Groups[pos]; return g.Success ? g.Value : null; } public string group() { return group(0); } [return: SequenceTypeInfo(typeof(string))] public PythonTuple groups() { return groups(null); } public PythonTuple groups(object @default) { object[] ret = new object[_m.Groups.Count - 1]; for (int i = 1; i < _m.Groups.Count; i++) { if (!_m.Groups[i].Success) { ret[i - 1] = @default; } else { ret[i - 1] = _m.Groups[i].Value; } } return PythonTuple.MakeTuple(ret); } public string expand(object template) { string strTmp = ValidateString(template, "template"); StringBuilder res = new StringBuilder(); for (int i = 0; i < strTmp.Length; i++) { if (strTmp[i] != '\\') { res.Append(strTmp[i]); continue; } if (++i == strTmp.Length) { res.Append(strTmp[i - 1]); continue; } if (Char.IsDigit(strTmp[i])) { AppendGroup(res, (int)(strTmp[i] - '0')); } else if (strTmp[i] == 'g') { if (++i == strTmp.Length) { res.Append("\\g"); return res.ToString(); } if (strTmp[i] != '<') { res.Append("\\g<"); continue; } else { // '<' StringBuilder name = new StringBuilder(); i++; while (strTmp[i] != '>' && i < strTmp.Length) { name.Append(strTmp[i++]); } AppendGroup(res, _pattern._re.GroupNumberFromName(name.ToString())); } } else { switch (strTmp[i]) { case 'n': res.Append('\n'); break; case 'r': res.Append('\r'); break; case 't': res.Append('\t'); break; case '\\': res.Append('\\'); break; } } } return res.ToString(); } [return: DictionaryTypeInfo(typeof(string), typeof(string))] public PythonDictionary groupdict() { return groupdict(null); } private static bool IsGroupNumber(string name) { foreach (char c in name) { if (!Char.IsNumber(c)) return false; } return true; } [return: DictionaryTypeInfo(typeof(string), typeof(string))] public PythonDictionary groupdict([NotNull]string value) { return groupdict((object)value); } [return: DictionaryTypeInfo(typeof(string), typeof(object))] public PythonDictionary groupdict(object value) { string[] groupNames = this._pattern._re.GetGroupNames(); Debug.Assert(groupNames.Length == this._m.Groups.Count); PythonDictionary d = new PythonDictionary(); for (int i = 0; i < groupNames.Length; i++) { if (IsGroupNumber(groupNames[i])) continue; // python doesn't report group numbers if (_m.Groups[i].Captures.Count != 0) { d[groupNames[i]] = _m.Groups[i].Value; } else { d[groupNames[i]] = value; } } return d; } [return: SequenceTypeInfo(typeof(int))] public PythonTuple span() { return PythonTuple.MakeTuple(this.start(), this.end()); } [return: SequenceTypeInfo(typeof(int))] public PythonTuple span(object group) { return PythonTuple.MakeTuple(this.start(group), this.end(group)); } public int pos { get { return _pos; } } public int endpos { get { return _endPos; } } public string @string { get { return _text; } } public PythonTuple regs { get { object[] res = new object[_m.Groups.Count]; for (int i = 0; i < res.Length; i++) { res[i] = PythonTuple.MakeTuple(start(i), end(i)); } return PythonTuple.MakeTuple(res); } } public RE_Pattern re { get { return _pattern; } } public object lastindex { get { // -1 : initial value of lastindex // 0 : no match found //other : the true lastindex // Match.Groups contains "lower" level matched groups, which has to be removed if (_lastindex == -1) { int i = 1; while (i < _m.Groups.Count) { if (_m.Groups[i].Success) { _lastindex = i; int start = _m.Groups[i].Index; int end = start + _m.Groups[i].Length; i++; // skip any group which fall into the range [start, end], // no matter match succeed or fail while (i < _m.Groups.Count && (_m.Groups[i].Index < end)) { i++; } } else { i++; } } if (_lastindex == -1) { _lastindex = 0; } } if (_lastindex == 0) { return null; } else { return _lastindex; } } } public string lastgroup { get { if (lastindex == null) return null; // when group was not explicitly named, RegEx assigns the number as name // This is different from C-Python, which returns None in such cases return this._pattern._re.GroupNameFromNumber((int)lastindex); } } #endregion #region Private helper functions private void AppendGroup(StringBuilder sb, int index) { sb.Append(_m.Groups[index].Value); } private int GetGroupIndex(object group) { int grpIndex; if (!Converter.TryConvertToInt32(group, out grpIndex)) { grpIndex = _pattern._re.GroupNumberFromName(ValidateString(group, "group")); } if (grpIndex < 0 || grpIndex >= _m.Groups.Count) { throw PythonOps.IndexError("no such group"); } return grpIndex; } #endregion } #endregion #region Private helper functions private static RE_Pattern GetPattern(CodeContext/*!*/ context, object pattern, int flags) { return GetPattern(context, pattern, flags, false); } private static RE_Pattern GetPattern(CodeContext/*!*/ context, object pattern, int flags, bool compiled) { RE_Pattern res = pattern as RE_Pattern; if (res != null) { return res; } string strPattern = ValidatePatternAsString(pattern); PatternKey key = new PatternKey(strPattern, flags); lock (_cachedPatterns) { if (_cachedPatterns.TryGetValue(new PatternKey(strPattern, flags), out res)) { #if SILVERLIGHT return res; #else if ( ! compiled || (res._re.Options & RegexOptions.Compiled) == RegexOptions.Compiled) { return res; } #endif } res = new RE_Pattern(context, strPattern, flags, compiled); _cachedPatterns[key] = res; return res; } } private static IEnumerator MatchIterator(MatchCollection matches, RE_Pattern pattern, string input) { for (int i = 0; i < matches.Count; i++) { yield return RE_Match.make(matches[i], pattern, input, 0, input.Length); } } private static RegexOptions FlagsToOption(int flags) { RegexOptions opts = RegexOptions.None; if ((flags & (int)IGNORECASE) != 0) opts |= RegexOptions.IgnoreCase; if ((flags & (int)MULTILINE) != 0) opts |= RegexOptions.Multiline; if (((flags & (int)LOCALE)) == 0) opts &= (~RegexOptions.CultureInvariant); if ((flags & (int)DOTALL) != 0) opts |= RegexOptions.Singleline; if ((flags & (int)VERBOSE) != 0) opts |= RegexOptions.IgnorePatternWhitespace; return opts; } private static int OptionToFlags(RegexOptions options) { int flags = 0; if ((options & RegexOptions.IgnoreCase) != 0) { flags |= IGNORECASE; } if ((options & RegexOptions.Multiline) != 0) { flags |= MULTILINE; } if ((options & RegexOptions.CultureInvariant) == 0) { flags |= LOCALE; } if ((options & RegexOptions.Singleline) != 0) { flags |= DOTALL; } if ((options & RegexOptions.IgnorePatternWhitespace) != 0) { flags |= VERBOSE; } return flags; } internal class ParsedRegex { public ParsedRegex(string pattern) { this.UserPattern = pattern; } public string UserPattern; public string Pattern; public RegexOptions Options = RegexOptions.CultureInvariant; } private static char[] _preParsedChars = new[] { '(', '{', '[', ']' }; private const string _mangledNamedGroup = "___PyRegexNameMangled"; /// <summary> /// Preparses a regular expression text returning a ParsedRegex class /// that can be used for further regular expressions. /// </summary> private static ParsedRegex PreParseRegex(CodeContext/*!*/ context, string pattern) { ParsedRegex res = new ParsedRegex(pattern); //string newPattern; int cur = 0, nameIndex; int curGroup = 0; bool isCharList = false; bool containsNamedGroup = false; for (; ; ) { nameIndex = pattern.IndexOfAny(_preParsedChars, cur); if (nameIndex > 0 && pattern[nameIndex - 1] == '\\') { int curIndex = nameIndex - 2; int backslashCount = 1; while (curIndex >= 0 && pattern[curIndex] == '\\') { backslashCount++; curIndex--; } // odd number of back slashes, this is an optional // paren that we should ignore. if ((backslashCount & 0x01) != 0) { cur++; continue; } } if (nameIndex == -1) break; if (nameIndex == pattern.Length - 1) break; switch (pattern[nameIndex]) { case '{': if (pattern[++nameIndex] == ',') { // no beginning specified for the n-m quntifier, add the // default 0 value. pattern = pattern.Insert(nameIndex, "0"); } break; case '[': nameIndex++; isCharList = true; break; case ']': nameIndex++; isCharList = false; break; case '(': // make sure we're not dealing with [(] if (!isCharList) { switch (pattern[++nameIndex]) { case '?': // extension syntax if (nameIndex == pattern.Length - 1) throw PythonExceptions.CreateThrowable(error(context), "unexpected end of regex"); switch (pattern[++nameIndex]) { case 'P': // named regex, .NET doesn't expect the P so we'll remove it; // also, once we see a named group i.e. ?P then we need to start artificially // naming all unnamed groups from then on---this is to get around the fact that // the CLR RegEx support orders all the unnamed groups before all the named // groups, even if the named groups are before the unnamed ones in the pattern; // the artificial naming preserves the order of the groups and thus the order of // the matches if (nameIndex + 1 < pattern.Length && pattern[nameIndex + 1] == '=') { // match whatever was previously matched by the named group // remove the (?P= pattern = pattern.Remove(nameIndex - 2, 4); pattern = pattern.Insert(nameIndex - 2, "\\k<"); int tmpIndex = nameIndex; while (tmpIndex < pattern.Length && pattern[tmpIndex] != ')') tmpIndex++; if (tmpIndex == pattern.Length) throw PythonExceptions.CreateThrowable(error(context), "unexpected end of regex"); pattern = pattern.Substring(0, tmpIndex) + ">" + pattern.Substring(tmpIndex + 1); } else { containsNamedGroup = true; pattern = pattern.Remove(nameIndex, 1); } break; case 'i': res.Options |= RegexOptions.IgnoreCase; RemoveOption(ref pattern, ref nameIndex); break; case 'L': res.Options &= ~(RegexOptions.CultureInvariant); RemoveOption(ref pattern, ref nameIndex); break; case 'm': res.Options |= RegexOptions.Multiline; RemoveOption(ref pattern, ref nameIndex); break; case 's': res.Options |= RegexOptions.Singleline; RemoveOption(ref pattern, ref nameIndex); break; case 'u': // specify unicode; not relevant and not valid under .NET as we're always unicode // -- so the option needs to be removed RemoveOption(ref pattern, ref nameIndex); break; case 'x': res.Options |= RegexOptions.IgnorePatternWhitespace; RemoveOption(ref pattern, ref nameIndex); break; case ':': break; // non-capturing case '=': break; // look ahead assertion case '<': break; // positive look behind assertion case '!': break; // negative look ahead assertion case '#': break; // inline comment case '(': // conditional match alternation (?(id/name)yes-pattern|no-pattern) // move past ?( so we don't preparse the name. nameIndex++; break; default: throw PythonExceptions.CreateThrowable(error(context), "Unrecognized extension " + pattern[nameIndex]); } break; default: // just another group curGroup++; if (containsNamedGroup) { // need to name this unnamed group pattern = pattern.Insert(nameIndex, "?<" + _mangledNamedGroup + GetRandomString() + ">"); } break; } } else { nameIndex++; } break; } cur = nameIndex; } cur = 0; for (; ; ) { nameIndex = pattern.IndexOf('\\', cur); if (nameIndex == -1 || nameIndex == pattern.Length - 1) break; cur = ++nameIndex; char curChar = pattern[cur]; switch (curChar) { case 'x': case 'u': case 'a': case 'b': case 'e': case 'f': case 'k': case 'n': case 'r': case 't': case 'v': case 'c': case 's': case 'W': case 'w': case 'p': case 'P': case 'S': case 'd': case 'D': case 'A': case 'Z': case '\\': // known escape sequences, leave escaped. break; default: System.Globalization.UnicodeCategory charClass = Char.GetUnicodeCategory(curChar); switch (charClass) { // recognized word characters, always unescape. case System.Globalization.UnicodeCategory.ModifierLetter: case System.Globalization.UnicodeCategory.LowercaseLetter: case System.Globalization.UnicodeCategory.UppercaseLetter: case System.Globalization.UnicodeCategory.TitlecaseLetter: case System.Globalization.UnicodeCategory.OtherLetter: case System.Globalization.UnicodeCategory.LetterNumber: case System.Globalization.UnicodeCategory.OtherNumber: case System.Globalization.UnicodeCategory.ConnectorPunctuation: pattern = pattern.Remove(nameIndex - 1, 1); cur--; break; case System.Globalization.UnicodeCategory.DecimalDigitNumber: // actually don't want to unescape '\1', '\2' etc. which are references to groups break; } break; } if (++cur >= pattern.Length) { break; } } res.Pattern = pattern; return res; } private static void RemoveOption(ref string pattern, ref int nameIndex) { if (pattern[nameIndex - 1] == '?' && nameIndex < (pattern.Length - 1) && pattern[nameIndex + 1] == ')') { pattern = pattern.Remove(nameIndex - 2, 4); nameIndex -= 2; } else { pattern = pattern.Remove(nameIndex, 1); nameIndex -= 2; } } private static string GetRandomString() { return r.Next(Int32.MaxValue / 2, Int32.MaxValue).ToString(); } private static string UnescapeGroups(Match m, string text) { for (int i = 0; i < text.Length; i++) { if (text[i] == '\\') { StringBuilder sb = new StringBuilder(text, 0, i, text.Length); do { if (text[i] == '\\') { i++; if (i == text.Length) { sb.Append('\\'); break; } switch (text[i]) { case 'n': sb.Append('\n'); break; case 'r': sb.Append('\r'); break; case 't': sb.Append('\t'); break; case '\\': sb.Append('\\'); break; case '\'': sb.Append('\''); break; case 'b': sb.Append('\b'); break; case 'g': // \g<#>, \g<name> need to be substituted by the groups they // matched if (text[i + 1] == '<') { int anglebrkStart = i + 1; int anglebrkEnd = text.IndexOf('>', i + 2); if (anglebrkEnd != -1) { // grab the # or 'name' of the group between '< >' int lengrp = anglebrkEnd - (anglebrkStart + 1); string grp = text.Substring(anglebrkStart + 1, lengrp); int num; Group g; if (StringUtils.TryParseInt32(grp, out num)) { g = m.Groups[num]; if (String.IsNullOrEmpty(g.Value)) { throw PythonOps.IndexError("unknown group reference"); } sb.Append(g.Value); } else { g = m.Groups[grp]; if (String.IsNullOrEmpty(g.Value)) { throw PythonOps.IndexError("unknown group reference"); } sb.Append(g.Value); } i = anglebrkEnd; } break; } sb.Append('\\'); sb.Append((char)text[i]); break; default: if (Char.IsDigit(text[i]) && text[i] <= '7') { int val = 0; int digitCount = 0; while (i < text.Length && Char.IsDigit(text[i]) && text[i] <= '7') { digitCount++; val += val * 8 + (text[i] - '0'); i++; } i--; if (digitCount == 1 && val > 0 && val < m.Groups.Count) { sb.Append(m.Groups[val].Value); } else { sb.Append((char)val); } } else { sb.Append('\\'); sb.Append((char)text[i]); } break; } } else { sb.Append(text[i]); } } while (++i < text.Length); return sb.ToString(); } } return text; } private static object ValidatePattern(object pattern) { if (pattern is string) return pattern as string; ExtensibleString es = pattern as ExtensibleString; if (es != null) return es.Value; Bytes bytes = pattern as Bytes; if (bytes != null) { return bytes.ToString(); } RE_Pattern rep = pattern as RE_Pattern; if (rep != null) return rep; throw PythonOps.TypeError("pattern must be a string or compiled pattern"); } private static string ValidatePatternAsString(object pattern) { if (pattern is string) return pattern as string; ExtensibleString es = pattern as ExtensibleString; if (es != null) return es.Value; Bytes bytes = pattern as Bytes; if (bytes != null) { return bytes.ToString(); } RE_Pattern rep = pattern as RE_Pattern; if (rep != null) return rep._pre.UserPattern; throw PythonOps.TypeError("pattern must be a string or compiled pattern"); } private static string ValidateString(object str, string param) { if (str is string) return str as string; ExtensibleString es = str as ExtensibleString; if (es != null) return es.Value; PythonBuffer buf = str as PythonBuffer; if (buf != null) { return buf.ToString(); } Bytes bytes = str as Bytes; if (bytes != null) { return bytes.ToString(); } ByteArray byteArray = str as ByteArray; if (byteArray != null) { return byteArray.MakeString(); } #if FEATURE_MMAP MmapModule.mmap mmapFile = str as MmapModule.mmap; if (mmapFile != null) { return mmapFile.GetSearchString(); } #endif throw PythonOps.TypeError("expected string for parameter '{0}' but got '{1}'", param, PythonOps.GetPythonTypeName(str)); } private static PythonType error(CodeContext/*!*/ context) { return (PythonType)PythonContext.GetContext(context).GetModuleState("reerror"); } class PatternKey : IEquatable<PatternKey> { public string Pattern; public int Flags; public PatternKey(string pattern, int flags) { Pattern = pattern; Flags = flags; } public override bool Equals(object obj) { PatternKey key = obj as PatternKey; if (key != null) { return Equals(key); } return false; } public override int GetHashCode() { return Pattern.GetHashCode() ^ Flags; } #region IEquatable<PatternKey> Members public bool Equals(PatternKey other) { return other.Pattern == Pattern && other.Flags == Flags; } #endregion } #endregion } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: POGOProtos/Settings/Master/Pokemon/CameraAttributes.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 POGOProtos.Settings.Master.Pokemon { /// <summary>Holder for reflection information generated from POGOProtos/Settings/Master/Pokemon/CameraAttributes.proto</summary> public static partial class CameraAttributesReflection { #region Descriptor /// <summary>File descriptor for POGOProtos/Settings/Master/Pokemon/CameraAttributes.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static CameraAttributesReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "CjlQT0dPUHJvdG9zL1NldHRpbmdzL01hc3Rlci9Qb2tlbW9uL0NhbWVyYUF0", "dHJpYnV0ZXMucHJvdG8SIlBPR09Qcm90b3MuU2V0dGluZ3MuTWFzdGVyLlBv", "a2Vtb24ilwEKEENhbWVyYUF0dHJpYnV0ZXMSFQoNZGlza19yYWRpdXNfbRgB", "IAEoAhIZChFjeWxpbmRlcl9yYWRpdXNfbRgCIAEoAhIZChFjeWxpbmRlcl9o", "ZWlnaHRfbRgDIAEoAhIZChFjeWxpbmRlcl9ncm91bmRfbRgEIAEoAhIbChNz", "aG91bGRlcl9tb2RlX3NjYWxlGAUgASgCYgZwcm90bzM=")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::POGOProtos.Settings.Master.Pokemon.CameraAttributes), global::POGOProtos.Settings.Master.Pokemon.CameraAttributes.Parser, new[]{ "DiskRadiusM", "CylinderRadiusM", "CylinderHeightM", "CylinderGroundM", "ShoulderModeScale" }, null, null, null) })); } #endregion } #region Messages public sealed partial class CameraAttributes : pb::IMessage<CameraAttributes> { private static readonly pb::MessageParser<CameraAttributes> _parser = new pb::MessageParser<CameraAttributes>(() => new CameraAttributes()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<CameraAttributes> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::POGOProtos.Settings.Master.Pokemon.CameraAttributesReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public CameraAttributes() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public CameraAttributes(CameraAttributes other) : this() { diskRadiusM_ = other.diskRadiusM_; cylinderRadiusM_ = other.cylinderRadiusM_; cylinderHeightM_ = other.cylinderHeightM_; cylinderGroundM_ = other.cylinderGroundM_; shoulderModeScale_ = other.shoulderModeScale_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public CameraAttributes Clone() { return new CameraAttributes(this); } /// <summary>Field number for the "disk_radius_m" field.</summary> public const int DiskRadiusMFieldNumber = 1; private float diskRadiusM_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public float DiskRadiusM { get { return diskRadiusM_; } set { diskRadiusM_ = value; } } /// <summary>Field number for the "cylinder_radius_m" field.</summary> public const int CylinderRadiusMFieldNumber = 2; private float cylinderRadiusM_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public float CylinderRadiusM { get { return cylinderRadiusM_; } set { cylinderRadiusM_ = value; } } /// <summary>Field number for the "cylinder_height_m" field.</summary> public const int CylinderHeightMFieldNumber = 3; private float cylinderHeightM_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public float CylinderHeightM { get { return cylinderHeightM_; } set { cylinderHeightM_ = value; } } /// <summary>Field number for the "cylinder_ground_m" field.</summary> public const int CylinderGroundMFieldNumber = 4; private float cylinderGroundM_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public float CylinderGroundM { get { return cylinderGroundM_; } set { cylinderGroundM_ = value; } } /// <summary>Field number for the "shoulder_mode_scale" field.</summary> public const int ShoulderModeScaleFieldNumber = 5; private float shoulderModeScale_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public float ShoulderModeScale { get { return shoulderModeScale_; } set { shoulderModeScale_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as CameraAttributes); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(CameraAttributes other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (DiskRadiusM != other.DiskRadiusM) return false; if (CylinderRadiusM != other.CylinderRadiusM) return false; if (CylinderHeightM != other.CylinderHeightM) return false; if (CylinderGroundM != other.CylinderGroundM) return false; if (ShoulderModeScale != other.ShoulderModeScale) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (DiskRadiusM != 0F) hash ^= DiskRadiusM.GetHashCode(); if (CylinderRadiusM != 0F) hash ^= CylinderRadiusM.GetHashCode(); if (CylinderHeightM != 0F) hash ^= CylinderHeightM.GetHashCode(); if (CylinderGroundM != 0F) hash ^= CylinderGroundM.GetHashCode(); if (ShoulderModeScale != 0F) hash ^= ShoulderModeScale.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 (DiskRadiusM != 0F) { output.WriteRawTag(13); output.WriteFloat(DiskRadiusM); } if (CylinderRadiusM != 0F) { output.WriteRawTag(21); output.WriteFloat(CylinderRadiusM); } if (CylinderHeightM != 0F) { output.WriteRawTag(29); output.WriteFloat(CylinderHeightM); } if (CylinderGroundM != 0F) { output.WriteRawTag(37); output.WriteFloat(CylinderGroundM); } if (ShoulderModeScale != 0F) { output.WriteRawTag(45); output.WriteFloat(ShoulderModeScale); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (DiskRadiusM != 0F) { size += 1 + 4; } if (CylinderRadiusM != 0F) { size += 1 + 4; } if (CylinderHeightM != 0F) { size += 1 + 4; } if (CylinderGroundM != 0F) { size += 1 + 4; } if (ShoulderModeScale != 0F) { size += 1 + 4; } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(CameraAttributes other) { if (other == null) { return; } if (other.DiskRadiusM != 0F) { DiskRadiusM = other.DiskRadiusM; } if (other.CylinderRadiusM != 0F) { CylinderRadiusM = other.CylinderRadiusM; } if (other.CylinderHeightM != 0F) { CylinderHeightM = other.CylinderHeightM; } if (other.CylinderGroundM != 0F) { CylinderGroundM = other.CylinderGroundM; } if (other.ShoulderModeScale != 0F) { ShoulderModeScale = other.ShoulderModeScale; } } [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: { DiskRadiusM = input.ReadFloat(); break; } case 21: { CylinderRadiusM = input.ReadFloat(); break; } case 29: { CylinderHeightM = input.ReadFloat(); break; } case 37: { CylinderGroundM = input.ReadFloat(); break; } case 45: { ShoulderModeScale = input.ReadFloat(); break; } } } } } #endregion } #endregion Designer generated code
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using HelloWorlds.Areas.HelpPage.ModelDescriptions; using HelloWorlds.Areas.HelpPage.Models; namespace HelloWorlds.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
// // HyenaSqliteConnection.cs // // Authors: // Aaron Bockover <[email protected]> // Gabriel Burt <[email protected]> // // Copyright (C) 2005-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.Data; using System.Threading; using System.Collections.Generic; using Mono.Data.Sqlite; namespace Hyena.Data.Sqlite { public class HyenaDataReader : IDisposable { private IDataReader reader; private bool read = false; public IDataReader Reader { get { return reader; } } public HyenaDataReader (IDataReader reader) { this.reader = reader; } public T Get<T> (int i) { if (!read) { Read (); } return (T) SqliteUtils.FromDbFormat (typeof(T), reader[i]); } public bool Read () { read = true; return reader.Read (); } public void Dispose () { reader.Dispose (); reader = null; } } public class ExecutingEventArgs : EventArgs { public readonly SqliteCommand Command; public ExecutingEventArgs (SqliteCommand command) { Command = command; } } public enum HyenaCommandType { Reader, Scalar, Execute, } public class HyenaSqliteConnection : IDisposable { private SqliteConnection connection; private string dbpath; // These are 'parallel' queues; that is, when a value is pushed or popped to // one, a value is pushed or popped to all three. // The 1st contains the command object itself, and the 2nd and 3rd contain the // arguments to be applied to that command (filled in for any ? placeholder in the command). // The 3rd exists as an optimization to avoid making an object [] for a single arg. private Queue<HyenaSqliteCommand> command_queue = new Queue<HyenaSqliteCommand>(); private Queue<object[]> args_queue = new Queue<object[]>(); private Queue<object> arg_queue = new Queue<object>(); private Thread queue_thread; private volatile bool dispose_requested = false; private volatile int results_ready = 0; private AutoResetEvent queue_signal = new AutoResetEvent (false); internal ManualResetEvent ResultReadySignal = new ManualResetEvent (false); private volatile Thread transaction_thread = null; private ManualResetEvent transaction_signal = new ManualResetEvent (true); private Thread warn_if_called_from_thread; public Thread WarnIfCalledFromThread { get { return warn_if_called_from_thread; } set { warn_if_called_from_thread = value; } } public string ServerVersion { get { return connection.ServerVersion; } } public event EventHandler<ExecutingEventArgs> Executing; public HyenaSqliteConnection(string dbpath) { this.dbpath = dbpath; queue_thread = new Thread(ProcessQueue); queue_thread.Name = String.Format ("HyenaSqliteConnection ({0})", dbpath); queue_thread.IsBackground = true; queue_thread.Start(); } #region Public Query Methods // TODO special case for single object param to avoid object [] // SELECT multiple column queries public IDataReader Query (HyenaSqliteCommand command) { command.CommandType = HyenaCommandType.Reader; QueueCommand (command); return command.WaitForResult (this) as IDataReader; } public IDataReader Query (HyenaSqliteCommand command, params object [] param_values) { command.CommandType = HyenaCommandType.Reader; QueueCommand (command, param_values); return command.WaitForResult (this) as IDataReader; } public IDataReader Query (string command_str, params object [] param_values) { return Query (new HyenaSqliteCommand (command_str, param_values)); } public IDataReader Query (object command) { return Query (new HyenaSqliteCommand (command.ToString ())); } // SELECT single column, multiple rows queries public IEnumerable<T> QueryEnumerable<T> (HyenaSqliteCommand command) { Type type = typeof (T); using (IDataReader reader = Query (command)) { while (reader.Read ()) { yield return (T) SqliteUtils.FromDbFormat (type, reader[0]); } } } public IEnumerable<T> QueryEnumerable<T> (HyenaSqliteCommand command, params object [] param_values) { Type type = typeof (T); using (IDataReader reader = Query (command, param_values)) { while (reader.Read ()) { yield return (T) SqliteUtils.FromDbFormat (type, reader[0]); } } } public IEnumerable<T> QueryEnumerable<T> (string command_str, params object [] param_values) { return QueryEnumerable<T> (new HyenaSqliteCommand (command_str, param_values)); } public IEnumerable<T> QueryEnumerable<T> (object command) { return QueryEnumerable<T> (new HyenaSqliteCommand (command.ToString ())); } // SELECT single column, single row queries public T Query<T> (HyenaSqliteCommand command) { command.CommandType = HyenaCommandType.Scalar; QueueCommand (command); object result = command.WaitForResult (this); return (T)SqliteUtils.FromDbFormat (typeof (T), result); } public T Query<T> (HyenaSqliteCommand command, params object [] param_values) { command.CommandType = HyenaCommandType.Scalar; QueueCommand (command, param_values); object result = command.WaitForResult (this); return (T)SqliteUtils.FromDbFormat (typeof (T), result); } public T Query<T> (string command_str, params object [] param_values) { return Query<T> (new HyenaSqliteCommand (command_str, param_values)); } public T Query<T> (object command) { return Query<T> (new HyenaSqliteCommand (command.ToString ())); } // INSERT, UPDATE, DELETE queries public int Execute (HyenaSqliteCommand command) { command.CommandType = HyenaCommandType.Execute;; QueueCommand(command); return Convert.ToInt32 (command.WaitForResult (this)); } public int Execute (HyenaSqliteCommand command, params object [] param_values) { command.CommandType = HyenaCommandType.Execute;; QueueCommand(command, param_values); return Convert.ToInt32 (command.WaitForResult (this)); } public int Execute (string command_str, params object [] param_values) { return Execute (new HyenaSqliteCommand (command_str, param_values)); } public int Execute (object command) { return Execute (new HyenaSqliteCommand (command.ToString ())); } #endregion #region Public Utility Methods public void BeginTransaction () { if (transaction_thread == Thread.CurrentThread) { throw new Exception ("Can't start a recursive transaction"); } while (transaction_thread != Thread.CurrentThread) { if (transaction_thread != null) { // Wait for the existing transaction to finish before this thread proceeds transaction_signal.WaitOne (); } lock (command_queue) { if (transaction_thread == null) { transaction_thread = Thread.CurrentThread; transaction_signal.Reset (); } } } Execute ("BEGIN TRANSACTION"); } public void CommitTransaction () { if (transaction_thread != Thread.CurrentThread) { throw new Exception ("Can't commit from outside a transaction"); } Execute ("COMMIT TRANSACTION"); lock (command_queue) { transaction_thread = null; // Let any other threads continue transaction_signal.Set (); } } public void RollbackTransaction () { if (transaction_thread != Thread.CurrentThread) { throw new Exception ("Can't rollback from outside a transaction"); } Execute ("ROLLBACK"); lock (command_queue) { transaction_thread = null; // Let any other threads continue transaction_signal.Set (); } } public bool TableExists (string tableName) { return Exists ("table", tableName); } public bool IndexExists (string indexName) { return Exists ("index", indexName); } private bool Exists (string type, string name) { return Exists (type, name, "sqlite_master") || Exists (type, name, "sqlite_temp_master"); } private bool Exists (string type, string name, string master) { return Query<int> (String.Format ( "SELECT COUNT(*) FROM {0} WHERE Type='{1}' AND Name='{2}'", master, type, name) ) > 0; } private delegate void SchemaHandler (string column); private void SchemaClosure (string table_name, SchemaHandler code) { string sql = Query<string> (String.Format ( "SELECT sql FROM sqlite_master WHERE Name='{0}'", table_name)); if (String.IsNullOrEmpty (sql)) { return; } sql = sql.Substring (sql.IndexOf ('(') + 1); foreach (string column_def in sql.Split (',')) { string column_def_t = column_def.Trim (); int ws_index = column_def_t.IndexOfAny (ws_chars); code (column_def_t.Substring (0, ws_index)); } } public bool ColumnExists (string tableName, string columnName) { bool value = false; SchemaClosure (tableName, delegate (string column) { if (column == columnName) { value = true; return; } }); return value; } private static readonly char [] ws_chars = new char [] { ' ', '\t', '\n', '\r' }; public IDictionary<string, string> GetSchema (string table_name) { Dictionary<string, string> schema = new Dictionary<string,string> (); SchemaClosure (table_name, delegate (string column) { schema.Add (column.ToLower (), null); }); return schema; } #endregion #region Private Queue Methods private void QueueCommand(HyenaSqliteCommand command, object [] args) { QueueCommand (command, null, args); } // TODO optimize object vs object [] code paths? /*private void QueueCommand(HyenaSqliteCommand command, object arg) { QueueCommand (command, arg, null); }*/ private void QueueCommand(HyenaSqliteCommand command) { QueueCommand (command, null, null); } private void QueueCommand(HyenaSqliteCommand command, object arg, object [] args) { if (warn_if_called_from_thread != null && Thread.CurrentThread == warn_if_called_from_thread) { Hyena.Log.Warning ("HyenaSqliteConnection command issued from the main thread"); } while (true) { lock (command_queue) { if (dispose_requested) { // No point in queueing the command if we're already disposing. // This helps avoid using the probably-disposed queue_signal below too return; } else if (transaction_thread == null || Thread.CurrentThread == transaction_thread) { command_queue.Enqueue (command); args_queue.Enqueue (args); arg_queue.Enqueue (arg); break; } } transaction_signal.WaitOne (); } queue_signal.Set (); } internal void ClaimResult () { lock (command_queue) { results_ready--; if (results_ready == 0) { ResultReadySignal.Reset (); } } } private void ProcessQueue() { if (connection == null) { connection = new SqliteConnection (String.Format ("Version=3,URI=file:{0}", dbpath)); connection.Open (); } // Keep handling queries while (!dispose_requested) { while (command_queue.Count > 0) { HyenaSqliteCommand command; object [] args; object arg; lock (command_queue) { command = command_queue.Dequeue (); args = args_queue.Dequeue (); arg = arg_queue.Dequeue (); } // Ensure the command is not altered while applying values or executing lock (command) { command.WaitIfNotFinished (); if (arg != null) { command.ApplyValues (arg); } else if (args != null) { command.ApplyValues (args); } command.Execute (this, connection); } lock (command_queue) { results_ready++; ResultReadySignal.Set (); } } queue_signal.WaitOne (); } // Finish connection.Close (); } internal void OnExecuting (SqliteCommand command) { EventHandler<ExecutingEventArgs> handler = Executing; if (handler != null) { handler (this, new ExecutingEventArgs (command)); } } #endregion public void Dispose() { dispose_requested = true; queue_signal.Set (); queue_thread.Join (); queue_signal.Close (); ResultReadySignal.Close (); transaction_signal.Close (); } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Xml; using OpenMetaverse; using log4net; using OpenSim.Framework; using OpenSim.Region.Framework.Scenes; using OpenSim.Region.Physics.Manager; namespace OpenSim.Region.Framework.Scenes.Serialization { /// <summary> /// Static methods to serialize and deserialize scene objects to and from XML /// </summary> public class SceneXmlLoader { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); public static void LoadPrimsFromXml(Scene scene, string fileName, bool newIDS, Vector3 loadOffset) { XmlDocument doc = new XmlDocument(); XmlNode rootNode; if (fileName.StartsWith("http:") || File.Exists(fileName)) { XmlTextReader reader = new XmlTextReader(fileName); reader.WhitespaceHandling = WhitespaceHandling.None; doc.Load(reader); reader.Close(); rootNode = doc.FirstChild; foreach (XmlNode aPrimNode in rootNode.ChildNodes) { SceneObjectGroup obj = SceneObjectSerializer.FromOriginalXmlFormat(aPrimNode.OuterXml); if (newIDS) { obj.ResetIDs(); } //if we want this to be a import method then we need new uuids for the object to avoid any clashes //obj.RegenerateFullIDs(); scene.AddNewSceneObject(obj, true); } } else { throw new Exception("Could not open file " + fileName + " for reading"); } } public static void SavePrimsToXml(Scene scene, string fileName) { FileStream file = new FileStream(fileName, FileMode.Create); StreamWriter stream = new StreamWriter(file); int primCount = 0; stream.WriteLine("<scene>\n"); List<EntityBase> EntityList = scene.GetEntities(); foreach (EntityBase ent in EntityList) { if (ent is SceneObjectGroup) { stream.WriteLine(SceneObjectSerializer.ToOriginalXmlFormat((SceneObjectGroup)ent)); primCount++; } } stream.WriteLine("</scene>\n"); stream.Close(); file.Close(); } public static string SaveGroupToXml2(SceneObjectGroup grp) { return SceneObjectSerializer.ToXml2Format(grp); } public static SceneObjectGroup DeserializeGroupFromXml2(string xmlString) { XmlDocument doc = new XmlDocument(); XmlNode rootNode; XmlTextReader reader = new XmlTextReader(new StringReader(xmlString)); reader.WhitespaceHandling = WhitespaceHandling.None; doc.Load(reader); reader.Close(); rootNode = doc.FirstChild; // This is to deal with neighbouring regions that are still surrounding the group xml with the <scene> // tag. It should be possible to remove the first part of this if statement once we go past 0.5.9 (or // when some other changes forces all regions to upgrade). // This might seem rather pointless since prim crossing from this revision to an earlier revision remains // broken. But it isn't much work to accomodate the old format here. if (rootNode.LocalName.Equals("scene")) { foreach (XmlNode aPrimNode in rootNode.ChildNodes) { // There is only ever one prim. This oddity should be removeable post 0.5.9 return SceneObjectSerializer.FromXml2Format(aPrimNode.OuterXml); } return null; } else { return SceneObjectSerializer.FromXml2Format(rootNode.OuterXml); } } /// <summary> /// Load prims from the xml2 format /// </summary> /// <param name="scene"></param> /// <param name="fileName"></param> public static void LoadPrimsFromXml2(Scene scene, string fileName) { LoadPrimsFromXml2(scene, new XmlTextReader(fileName), false); } /// <summary> /// Load prims from the xml2 format /// </summary> /// <param name="scene"></param> /// <param name="reader"></param> /// <param name="startScripts"></param> public static void LoadPrimsFromXml2(Scene scene, TextReader reader, bool startScripts) { LoadPrimsFromXml2(scene, new XmlTextReader(reader), startScripts); } /// <summary> /// Load prims from the xml2 format. This method will close the reader /// </summary> /// <param name="scene"></param> /// <param name="reader"></param> /// <param name="startScripts"></param> protected static void LoadPrimsFromXml2(Scene scene, XmlTextReader reader, bool startScripts) { XmlDocument doc = new XmlDocument(); reader.WhitespaceHandling = WhitespaceHandling.None; doc.Load(reader); reader.Close(); XmlNode rootNode = doc.FirstChild; ICollection<SceneObjectGroup> sceneObjects = new List<SceneObjectGroup>(); foreach (XmlNode aPrimNode in rootNode.ChildNodes) { SceneObjectGroup obj = CreatePrimFromXml2(scene, aPrimNode.OuterXml); if (obj != null && startScripts) sceneObjects.Add(obj); } foreach (SceneObjectGroup sceneObject in sceneObjects) { sceneObject.CreateScriptInstances(0, true, scene.DefaultScriptEngine, 0); sceneObject.ResumeScripts(); } } /// <summary> /// Create a prim from the xml2 representation. /// </summary> /// <param name="scene"></param> /// <param name="xmlData"></param> /// <returns>The scene object created. null if the scene object already existed</returns> protected static SceneObjectGroup CreatePrimFromXml2(Scene scene, string xmlData) { SceneObjectGroup obj = SceneObjectSerializer.FromXml2Format(xmlData); if (scene.AddRestoredSceneObject(obj, true, false)) return obj; else return null; } public static void SavePrimsToXml2(Scene scene, string fileName) { List<EntityBase> EntityList = scene.GetEntities(); SavePrimListToXml2(EntityList, fileName); } public static void SavePrimsToXml2(Scene scene, TextWriter stream, Vector3 min, Vector3 max) { List<EntityBase> EntityList = scene.GetEntities(); SavePrimListToXml2(EntityList, stream, min, max); } public static void SaveNamedPrimsToXml2(Scene scene, string primName, string fileName) { m_log.InfoFormat( "[SERIALISER]: Saving prims with name {0} in xml2 format for region {1} to {2}", primName, scene.RegionInfo.RegionName, fileName); List<EntityBase> entityList = scene.GetEntities(); List<EntityBase> primList = new List<EntityBase>(); foreach (EntityBase ent in entityList) { if (ent is SceneObjectGroup) { if (ent.Name == primName) { primList.Add(ent); } } } SavePrimListToXml2(primList, fileName); } public static void SavePrimListToXml2(List<EntityBase> entityList, string fileName) { FileStream file = new FileStream(fileName, FileMode.Create); try { StreamWriter stream = new StreamWriter(file); try { SavePrimListToXml2(entityList, stream, Vector3.Zero, Vector3.Zero); } finally { stream.Close(); } } finally { file.Close(); } } public static void SavePrimListToXml2(List<EntityBase> entityList, TextWriter stream, Vector3 min, Vector3 max) { int primCount = 0; stream.WriteLine("<scene>\n"); foreach (EntityBase ent in entityList) { if (ent is SceneObjectGroup) { SceneObjectGroup g = (SceneObjectGroup)ent; if (!min.Equals(Vector3.Zero) || !max.Equals(Vector3.Zero)) { Vector3 pos = g.RootPart.GetWorldPosition(); if (min.X > pos.X || min.Y > pos.Y || min.Z > pos.Z) continue; if (max.X < pos.X || max.Y < pos.Y || max.Z < pos.Z) continue; } stream.WriteLine(SceneObjectSerializer.ToXml2Format(g)); primCount++; } } stream.WriteLine("</scene>\n"); stream.Flush(); } } }
using System; using System.Collections; using System.Collections.Concurrent; using System.ComponentModel; using System.Data; using System.Globalization; using System.Threading; using System.Xml; using System.Linq; using Umbraco.Core; using umbraco.cms.businesslogic.language; using Umbraco.Core.Models; using Umbraco.Core.Services; using umbraco.DataLayer; using umbraco.BusinessLogic; using System.Runtime.CompilerServices; using Language = umbraco.cms.businesslogic.language.Language; namespace umbraco.cms.businesslogic { [Obsolete("Obsolete, Umbraco.Core.Services.ILocalizationService")] public class Dictionary { private static readonly Guid TopLevelParent = new Guid(Constants.Conventions.Localization.DictionaryItemRootId); [Obsolete("Obsolete, For querying the database use the new UmbracoDatabase object ApplicationContext.Current.DatabaseContext.Database")] protected static ISqlHelper SqlHelper { get { return Application.SqlHelper; } } /// <summary> /// Retrieve a list of toplevel DictionaryItems /// </summary> public static DictionaryItem[] getTopMostItems { get { return ApplicationContext.Current.Services.LocalizationService.GetRootDictionaryItems() .Select(x => new DictionaryItem(x)) .ToArray(); } } /// <summary> /// A DictionaryItem is basically a key/value pair (key/language key/value) which holds the data /// associated to a key in various language translations /// </summary> public class DictionaryItem { public DictionaryItem() { } internal DictionaryItem(IDictionaryItem item) { _dictionaryItem = item; } private readonly IDictionaryItem _dictionaryItem; private DictionaryItem _parent; public DictionaryItem(string key) { _dictionaryItem = ApplicationContext.Current.Services.LocalizationService.GetDictionaryItemByKey(key); if (_dictionaryItem == null) { throw new ArgumentException("No key " + key + " exists in dictionary"); } } public DictionaryItem(Guid id) { _dictionaryItem = ApplicationContext.Current.Services.LocalizationService.GetDictionaryItemById(id); if (_dictionaryItem == null) { throw new ArgumentException("No unique id " + id + " exists in dictionary"); } } public DictionaryItem(int id) { _dictionaryItem = ApplicationContext.Current.Services.LocalizationService.GetDictionaryItemById(id); if (_dictionaryItem == null) { throw new ArgumentException("No id " + id + " exists in dictionary"); } } [Obsolete("This is no longer used and will be removed from the codebase in future versions")] public bool IsTopMostItem() { return _dictionaryItem.ParentId == new Guid(Constants.Conventions.Localization.DictionaryItemRootId); } /// <summary> /// Returns the parent. /// </summary> public DictionaryItem Parent { get { //EnsureCache(); if (_parent == null) { var p = ApplicationContext.Current.Services.LocalizationService.GetDictionaryItemById(_dictionaryItem.ParentId); if (p == null) { throw new ArgumentException("Top most dictionary items doesn't have a parent"); } else { _parent = new DictionaryItem(p); } } return _parent; } } /// <summary> /// The primary key in the database /// </summary> public int id { get { return _dictionaryItem.Id; } } public DictionaryItem[] Children { get { return ApplicationContext.Current.Services.LocalizationService.GetDictionaryItemChildren(_dictionaryItem.Key) .WhereNotNull() .Select(x => new DictionaryItem(x)) .ToArray(); } } public static bool hasKey(string key) { return ApplicationContext.Current.Services.LocalizationService.DictionaryItemExists(key); } public bool hasChildren { get { return Children.Any(); } } /// <summary> /// Returns or sets the key. /// </summary> public string key { get { return _dictionaryItem.ItemKey; } set { if (hasKey(value) == false) { _dictionaryItem.ItemKey = value; } else throw new ArgumentException("New value of key already exists (is key)"); } } public string Value(int languageId) { if (languageId == 0) return Value(); var translation = _dictionaryItem.Translations.FirstOrDefault(x => x.Language.Id == languageId); return translation == null ? string.Empty : translation.Value; } public void setValue(int languageId, string value) { ApplicationContext.Current.Services.LocalizationService.AddOrUpdateDictionaryValue( _dictionaryItem, ApplicationContext.Current.Services.LocalizationService.GetLanguageById(languageId), value); Save(); } /// <summary> /// Returns the default value based on the default language for this item /// </summary> /// <returns></returns> public string Value() { var defaultTranslation = _dictionaryItem.Translations.FirstOrDefault(x => x.Language.Id == 1); return defaultTranslation == null ? string.Empty : defaultTranslation.Value; } [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("This is not used and should never be used, it will be removed from the codebase in future versions")] public void setValue(string value) { if (Item.hasText(_dictionaryItem.Key, 0)) Item.setText(0, _dictionaryItem.Key, value); else Item.addText(0, _dictionaryItem.Key, value); Save(); } public static int addKey(string key, string defaultValue, string parentKey) { //EnsureCache(); if (hasKey(parentKey)) { int retval = CreateKey(key, new DictionaryItem(parentKey)._dictionaryItem.Key, defaultValue); return retval; } else throw new ArgumentException("Parentkey doesnt exist"); } public static int addKey(string key, string defaultValue) { int retval = CreateKey(key, TopLevelParent, defaultValue); return retval; } public void delete() { OnDeleting(EventArgs.Empty); ApplicationContext.Current.Services.LocalizationService.Delete(_dictionaryItem); OnDeleted(EventArgs.Empty); } /// <summary> /// ensures events fire after setting proeprties /// </summary> public void Save() { OnSaving(EventArgs.Empty); ApplicationContext.Current.Services.LocalizationService.Save(_dictionaryItem); } public XmlNode ToXml(XmlDocument xd) { var serializer = new EntityXmlSerializer(); var xml = serializer.Serialize(_dictionaryItem); var xmlNode = xml.GetXmlNode(xd); if (this.hasChildren) { foreach (var di in this.Children) { xmlNode.AppendChild(di.ToXml(xd)); } } return xmlNode; } public static DictionaryItem Import(XmlNode xmlData) { return Import(xmlData, null); } public static DictionaryItem Import(XmlNode xmlData, DictionaryItem parent) { string key = xmlData.Attributes["Key"].Value; XmlNodeList values = xmlData.SelectNodes("./Value"); XmlNodeList childItems = xmlData.SelectNodes("./DictionaryItem"); DictionaryItem newItem; bool retVal = false; if (!hasKey(key)) { if (parent != null) addKey(key, " ", parent.key); else addKey(key, " "); if (values.Count > 0) { //Set language values on the dictionary item newItem = new DictionaryItem(key); foreach (XmlNode xn in values) { string cA = xn.Attributes["LanguageCultureAlias"].Value; string keyValue = xmlHelper.GetNodeValue(xn); Language valueLang = Language.GetByCultureCode(cA); if (valueLang != null) { newItem.setValue(valueLang.id, keyValue); } } } if (parent == null) retVal = true; } newItem = new DictionaryItem(key); foreach (XmlNode childItem in childItems) { Import(childItem, newItem); } if (retVal) return newItem; else return null; } private static int CreateKey(string key, Guid parentId, string defaultValue) { if (!hasKey(key)) { var item = ApplicationContext.Current.Services.LocalizationService.CreateDictionaryItemWithIdentity( key, parentId, defaultValue); return item.Id; } else { throw new ArgumentException("Key being added already exists!"); } } #region Events public delegate void SaveEventHandler(DictionaryItem sender, EventArgs e); public delegate void NewEventHandler(DictionaryItem sender, EventArgs e); public delegate void DeleteEventHandler(DictionaryItem sender, EventArgs e); public static event SaveEventHandler Saving; protected virtual void OnSaving(EventArgs e) { if (Saving != null) Saving(this, e); } public static event NewEventHandler New; protected virtual void OnNew(EventArgs e) { if (New != null) New(this, e); } public static event DeleteEventHandler Deleting; protected virtual void OnDeleting(EventArgs e) { if (Deleting != null) Deleting(this, e); } public static event DeleteEventHandler Deleted; protected virtual void OnDeleted(EventArgs e) { if (Deleted != null) Deleted(this, e); } #endregion } // zb023 - utility method public static string ReplaceKey(string text) { if (text.StartsWith("#") == false) return text; var lang = Language.GetByCultureCode(Thread.CurrentThread.CurrentCulture.Name); if (lang == null) return "[" + text + "]"; if (DictionaryItem.hasKey(text.Substring(1, text.Length - 1)) == false) return "[" + text + "]"; var di = new DictionaryItem(text.Substring(1, text.Length - 1)); return di.Value(lang.id); } } }
/* * 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.Reflection; using log4net; using Nini.Config; using Nwc.XmlRpc; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Communications; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Services.Interfaces; using OpenSim.Services.Connectors.Friends; using OpenSim.Server.Base; using OpenSim.Framework.Servers.HttpServer; using FriendInfo = OpenSim.Services.Interfaces.FriendInfo; using PresenceInfo = OpenSim.Services.Interfaces.PresenceInfo; using GridRegion = OpenSim.Services.Interfaces.GridRegion; namespace OpenSim.Region.CoreModules.Avatar.Friends { public class FriendsModule : ISharedRegionModule, IFriendsModule { protected class UserFriendData { public UUID PrincipalID; public FriendInfo[] Friends; public int Refcount; public UUID RegionID; public bool IsFriend(string friend) { foreach (FriendInfo fi in Friends) { if (fi.Friend == friend) return true; } return false; } } private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); protected List<Scene> m_Scenes = new List<Scene>(); protected IPresenceService m_PresenceService = null; protected IFriendsService m_FriendsService = null; protected FriendsSimConnector m_FriendsSimConnector; protected Dictionary<UUID, UserFriendData> m_Friends = new Dictionary<UUID, UserFriendData>(); protected List<UUID> m_NeedsListOfFriends = new List<UUID>(); protected IPresenceService PresenceService { get { if (m_PresenceService == null) { if (m_Scenes.Count > 0) m_PresenceService = m_Scenes[0].RequestModuleInterface<IPresenceService>(); } return m_PresenceService; } } protected IFriendsService FriendsService { get { if (m_FriendsService == null) { if (m_Scenes.Count > 0) m_FriendsService = m_Scenes[0].RequestModuleInterface<IFriendsService>(); } return m_FriendsService; } } protected IGridService GridService { get { return m_Scenes[0].GridService; } } public IScene Scene { get { if (m_Scenes.Count > 0) return m_Scenes[0]; else return null; } } public void Initialise(IConfigSource config) { IConfig friendsConfig = config.Configs["Friends"]; if (friendsConfig != null) { int mPort = friendsConfig.GetInt("Port", 0); string connector = friendsConfig.GetString("Connector", String.Empty); Object[] args = new Object[] { config }; m_FriendsService = ServerUtils.LoadPlugin<IFriendsService>(connector, args); m_FriendsSimConnector = new FriendsSimConnector(); // Instantiate the request handler IHttpServer server = MainServer.GetHttpServer((uint)mPort); server.AddStreamHandler(new FriendsRequestHandler(this)); } if (m_FriendsService == null) { m_log.Error("[FRIENDS]: No Connector defined in section Friends, or failed to load, cannot continue"); throw new Exception("Connector load error"); } } public void PostInitialise() { } public void Close() { } public void AddRegion(Scene scene) { m_Scenes.Add(scene); scene.RegisterModuleInterface<IFriendsModule>(this); scene.EventManager.OnNewClient += OnNewClient; scene.EventManager.OnClientClosed += OnClientClosed; scene.EventManager.OnMakeRootAgent += OnMakeRootAgent; scene.EventManager.OnMakeChildAgent += OnMakeChildAgent; scene.EventManager.OnClientLogin += OnClientLogin; } public void RegionLoaded(Scene scene) { } public void RemoveRegion(Scene scene) { m_Scenes.Remove(scene); } public string Name { get { return "FriendsModule"; } } public Type ReplaceableInterface { get { return null; } } public uint GetFriendPerms(UUID principalID, UUID friendID) { if (!m_Friends.ContainsKey(principalID)) return 0; UserFriendData data = m_Friends[principalID]; foreach (FriendInfo fi in data.Friends) { if (fi.Friend == friendID.ToString()) return (uint)fi.TheirFlags; } return 0; } private void OnNewClient(IClientAPI client) { client.OnInstantMessage += OnInstantMessage; client.OnApproveFriendRequest += OnApproveFriendRequest; client.OnDenyFriendRequest += OnDenyFriendRequest; client.OnTerminateFriendship += OnTerminateFriendship; client.OnGrantUserRights += OnGrantUserRights; client.OnLogout += OnLogout; if (m_Friends.ContainsKey(client.AgentId)) { m_Friends[client.AgentId].Refcount++; return; } UserFriendData newFriends = new UserFriendData(); newFriends.PrincipalID = client.AgentId; newFriends.Friends = m_FriendsService.GetFriends(client.AgentId); newFriends.Refcount = 1; newFriends.RegionID = UUID.Zero; m_Friends.Add(client.AgentId, newFriends); //StatusChange(client.AgentId, true); } private void OnClientClosed(UUID agentID, Scene scene) { if (m_Friends.ContainsKey(agentID)) { if (m_Friends[agentID].Refcount == 1) m_Friends.Remove(agentID); else m_Friends[agentID].Refcount--; } } private void OnLogout(IClientAPI client) { StatusChange(client.AgentId, false); m_Friends.Remove(client.AgentId); } private void OnMakeRootAgent(ScenePresence sp) { UUID agentID = sp.ControllingClient.AgentId; if (m_Friends.ContainsKey(agentID)) { if (m_Friends[agentID].RegionID == UUID.Zero && m_Friends[agentID].Friends == null) { m_Friends[agentID].Friends = m_FriendsService.GetFriends(agentID); } m_Friends[agentID].RegionID = sp.ControllingClient.Scene.RegionInfo.RegionID; } } private void OnMakeChildAgent(ScenePresence sp) { UUID agentID = sp.ControllingClient.AgentId; if (m_Friends.ContainsKey(agentID)) { if (m_Friends[agentID].RegionID == sp.ControllingClient.Scene.RegionInfo.RegionID) m_Friends[agentID].RegionID = UUID.Zero; } } private void OnClientLogin(IClientAPI client) { UUID agentID = client.AgentId; // Inform the friends that this user is online StatusChange(agentID, true); // Register that we need to send the list of online friends to this user lock (m_NeedsListOfFriends) if (!m_NeedsListOfFriends.Contains(agentID)) { m_NeedsListOfFriends.Add(agentID); } } public void SendFriendsOnlineIfNeeded(IClientAPI client) { UUID agentID = client.AgentId; if (m_NeedsListOfFriends.Contains(agentID)) { if (!m_Friends.ContainsKey(agentID)) { m_log.DebugFormat("[FRIENDS MODULE]: agent {0} not found in local cache", agentID); return; } // // Send the friends online // List<UUID> online = GetOnlineFriends(agentID); if (online.Count > 0) { m_log.DebugFormat("[FRIENDS MODULE]: User {0} in region {1} has {2} friends online", client.AgentId, client.Scene.RegionInfo.RegionName, online.Count); client.SendAgentOnline(online.ToArray()); } // // Send outstanding friendship offers // if (m_Friends.ContainsKey(agentID)) { List<string> outstanding = new List<string>(); foreach (FriendInfo fi in m_Friends[agentID].Friends) if (fi.TheirFlags == -1) outstanding.Add(fi.Friend); GridInstantMessage im = new GridInstantMessage(client.Scene, UUID.Zero, "", agentID, (byte)InstantMessageDialog.FriendshipOffered, "Will you be my friend?", true, Vector3.Zero); foreach (string fid in outstanding) { try { im.fromAgentID = new Guid(fid); } catch { continue; } UserAccount account = m_Scenes[0].UserAccountService.GetUserAccount(client.Scene.RegionInfo.ScopeID, new UUID(im.fromAgentID)); im.fromAgentName = account.FirstName + " " + account.LastName; PresenceInfo presence = null; PresenceInfo[] presences = PresenceService.GetAgents(new string[] { fid }); if (presences != null && presences.Length > 0) presence = presences[0]; if (presence != null) im.offline = 0; im.imSessionID = im.fromAgentID; // Finally LocalFriendshipOffered(agentID, im); } } lock (m_NeedsListOfFriends) m_NeedsListOfFriends.Remove(agentID); } } List<UUID> GetOnlineFriends(UUID userID) { List<string> friendList = new List<string>(); List<UUID> online = new List<UUID>(); foreach (FriendInfo fi in m_Friends[userID].Friends) { if (((fi.TheirFlags & 1) != 0) && (fi.TheirFlags != -1)) friendList.Add(fi.Friend); } if (friendList.Count == 0) // no friends whatsoever return online; PresenceInfo[] presence = PresenceService.GetAgents(friendList.ToArray()); foreach (PresenceInfo pi in presence) online.Add(new UUID(pi.UserID)); //m_log.DebugFormat("[XXX] {0} friend online {1}", userID, pi.UserID); return online; } // // Find the client for a ID // public IClientAPI LocateClientObject(UUID agentID) { Scene scene = GetClientScene(agentID); if (scene == null) return null; ScenePresence presence = scene.GetScenePresence(agentID); if (presence == null) return null; return presence.ControllingClient; } // // Find the scene for an agent // private Scene GetClientScene(UUID agentId) { lock (m_Scenes) { foreach (Scene scene in m_Scenes) { ScenePresence presence = scene.GetScenePresence(agentId); if (presence != null) { if (!presence.IsChildAgent) return scene; } } } return null; } /// <summary> /// Caller beware! Call this only for root agents. /// </summary> /// <param name="agentID"></param> /// <param name="online"></param> private void StatusChange(UUID agentID, bool online) { if (m_Friends.ContainsKey(agentID)) { List<FriendInfo> friendList = new List<FriendInfo>(); foreach (FriendInfo fi in m_Friends[agentID].Friends) { if (((fi.MyFlags & 1) != 0) && (fi.TheirFlags != -1)) friendList.Add(fi); } foreach (FriendInfo fi in friendList) { // Notify about this user status StatusNotify(fi, agentID, online); } } } private void StatusNotify(FriendInfo friend, UUID userID, bool online) { UUID friendID = UUID.Zero; if (UUID.TryParse(friend.Friend, out friendID)) { // Try local if (LocalStatusNotification(userID, friendID, online)) return; // The friend is not here [as root]. Let's forward. PresenceInfo[] friendSessions = PresenceService.GetAgents(new string[] { friendID.ToString() }); if (friendSessions != null && friendSessions.Length > 0) { PresenceInfo friendSession = friendSessions[0]; if (friendSession != null) { GridRegion region = GridService.GetRegionByUUID(m_Scenes[0].RegionInfo.ScopeID, friendSession.RegionID); m_FriendsSimConnector.StatusNotify(region, userID, friendID, online); } } // Friend is not online. Ignore. } } private void OnInstantMessage(IClientAPI client, GridInstantMessage im) { if (im.dialog == (byte)OpenMetaverse.InstantMessageDialog.FriendshipOffered) { // we got a friendship offer UUID principalID = new UUID(im.fromAgentID); UUID friendID = new UUID(im.toAgentID); m_log.DebugFormat("[FRIENDS]: {0} offered friendship to {1}", principalID, friendID); // This user wants to be friends with the other user. // Let's add the relation backwards, in case the other is not online FriendsService.StoreFriend(friendID, principalID.ToString(), 0); // Now let's ask the other user to be friends with this user ForwardFriendshipOffer(principalID, friendID, im); } } private void ForwardFriendshipOffer(UUID agentID, UUID friendID, GridInstantMessage im) { // !!!!!!!! This is a hack so that we don't have to keep state (transactionID/imSessionID) // We stick this agent's ID as imSession, so that it's directly available on the receiving end im.imSessionID = im.fromAgentID; // Try the local sim if (LocalFriendshipOffered(friendID, im)) return; // The prospective friend is not here [as root]. Let's forward. PresenceInfo[] friendSessions = PresenceService.GetAgents(new string[] { friendID.ToString() }); if (friendSessions != null && friendSessions.Length > 0) { PresenceInfo friendSession = friendSessions[0]; if (friendSession != null) { GridRegion region = GridService.GetRegionByUUID(m_Scenes[0].RegionInfo.ScopeID, friendSession.RegionID); m_FriendsSimConnector.FriendshipOffered(region, agentID, friendID, im.message); } } // If the prospective friend is not online, he'll get the message upon login. } private void OnApproveFriendRequest(IClientAPI client, UUID agentID, UUID friendID, List<UUID> callingCardFolders) { FriendsService.StoreFriend(agentID, friendID.ToString(), 1); FriendsService.StoreFriend(friendID, agentID.ToString(), 1); // update the local cache m_Friends[agentID].Friends = FriendsService.GetFriends(agentID); m_log.DebugFormat("[FRIENDS]: {0} accepted friendship from {1}", agentID, friendID); // // Notify the friend // // Try Local if (LocalFriendshipApproved(agentID, client.Name, friendID)) { client.SendAgentOnline(new UUID[] { friendID }); return; } // The friend is not here PresenceInfo[] friendSessions = PresenceService.GetAgents(new string[] { friendID.ToString() }); if (friendSessions != null && friendSessions.Length > 0) { PresenceInfo friendSession = friendSessions[0]; if (friendSession != null) { GridRegion region = GridService.GetRegionByUUID(m_Scenes[0].RegionInfo.ScopeID, friendSession.RegionID); m_FriendsSimConnector.FriendshipApproved(region, agentID, client.Name, friendID); client.SendAgentOnline(new UUID[] { friendID }); } } } private void OnDenyFriendRequest(IClientAPI client, UUID agentID, UUID friendID, List<UUID> callingCardFolders) { m_log.DebugFormat("[FRIENDS]: {0} denied friendship to {1}", agentID, friendID); FriendsService.Delete(agentID, friendID.ToString()); FriendsService.Delete(friendID, agentID.ToString()); // // Notify the friend // // Try local if (LocalFriendshipDenied(agentID, client.Name, friendID)) return; PresenceInfo[] friendSessions = PresenceService.GetAgents(new string[] { friendID.ToString() }); if (friendSessions != null && friendSessions.Length > 0) { PresenceInfo friendSession = friendSessions[0]; if (friendSession != null) { GridRegion region = GridService.GetRegionByUUID(m_Scenes[0].RegionInfo.ScopeID, friendSession.RegionID); m_FriendsSimConnector.FriendshipDenied(region, agentID, client.Name, friendID); } } } private void OnTerminateFriendship(IClientAPI client, UUID agentID, UUID exfriendID) { FriendsService.Delete(agentID, exfriendID.ToString()); FriendsService.Delete(exfriendID, agentID.ToString()); // Update local cache m_Friends[agentID].Friends = FriendsService.GetFriends(agentID); client.SendTerminateFriend(exfriendID); // // Notify the friend // // Try local if (LocalFriendshipTerminated(exfriendID)) return; PresenceInfo[] friendSessions = PresenceService.GetAgents(new string[] { exfriendID.ToString() }); if (friendSessions != null && friendSessions.Length > 0) { PresenceInfo friendSession = friendSessions[0]; if (friendSession != null) { GridRegion region = GridService.GetRegionByUUID(m_Scenes[0].RegionInfo.ScopeID, friendSession.RegionID); m_FriendsSimConnector.FriendshipTerminated(region, agentID, exfriendID); } } } private void OnGrantUserRights(IClientAPI remoteClient, UUID requester, UUID target, int rights) { if (!m_Friends.ContainsKey(remoteClient.AgentId)) return; m_log.DebugFormat("[FRIENDS MODULE]: User {0} changing rights to {1} for friend {2}", requester, rights, target); // Let's find the friend in this user's friend list UserFriendData fd = m_Friends[remoteClient.AgentId]; FriendInfo friend = null; foreach (FriendInfo fi in fd.Friends) if (fi.Friend == target.ToString()) friend = fi; if (friend != null) // Found it { // Store it on the DB FriendsService.StoreFriend(requester, target.ToString(), rights); // Store it in the local cache int myFlags = friend.MyFlags; friend.MyFlags = rights; // Always send this back to the original client remoteClient.SendChangeUserRights(requester, target, rights); // // Notify the friend // // Try local if (LocalGrantRights(requester, target, myFlags, rights)) return; PresenceInfo[] friendSessions = PresenceService.GetAgents(new string[] { target.ToString() }); if (friendSessions != null && friendSessions.Length > 0) { PresenceInfo friendSession = friendSessions[0]; if (friendSession != null) { GridRegion region = GridService.GetRegionByUUID(m_Scenes[0].RegionInfo.ScopeID, friendSession.RegionID); // TODO: You might want to send the delta to save the lookup // on the other end!! m_FriendsSimConnector.GrantRights(region, requester, target, myFlags, rights); } } } } #region Local public bool LocalFriendshipOffered(UUID toID, GridInstantMessage im) { IClientAPI friendClient = LocateClientObject(toID); if (friendClient != null) { // the prospective friend in this sim as root agent friendClient.SendInstantMessage(im); // we're done return true; } return false; } public bool LocalFriendshipApproved(UUID userID, string userName, UUID friendID) { IClientAPI friendClient = LocateClientObject(friendID); if (friendClient != null) { // the prospective friend in this sim as root agent GridInstantMessage im = new GridInstantMessage(Scene, userID, userName, friendID, (byte)OpenMetaverse.InstantMessageDialog.FriendshipAccepted, userID.ToString(), false, Vector3.Zero); friendClient.SendInstantMessage(im); // update the local cache m_Friends[friendID].Friends = FriendsService.GetFriends(friendID); // we're done return true; } return false; } public bool LocalFriendshipDenied(UUID userID, string userName, UUID friendID) { IClientAPI friendClient = LocateClientObject(friendID); if (friendClient != null) { // the prospective friend in this sim as root agent GridInstantMessage im = new GridInstantMessage(Scene, userID, userName, friendID, (byte)OpenMetaverse.InstantMessageDialog.FriendshipDeclined, userID.ToString(), false, Vector3.Zero); friendClient.SendInstantMessage(im); // we're done return true; } return false; } public bool LocalFriendshipTerminated(UUID exfriendID) { IClientAPI friendClient = LocateClientObject(exfriendID); if (friendClient != null) { // the friend in this sim as root agent friendClient.SendTerminateFriend(exfriendID); // update local cache m_Friends[exfriendID].Friends = FriendsService.GetFriends(exfriendID); // we're done return true; } return false; } public bool LocalGrantRights(UUID userID, UUID friendID, int userFlags, int rights) { IClientAPI friendClient = LocateClientObject(friendID); if (friendClient != null) { bool onlineBitChanged = ((rights ^ userFlags) & (int)FriendRights.CanSeeOnline) != 0; if (onlineBitChanged) { if ((rights & (int)FriendRights.CanSeeOnline) == 1) friendClient.SendAgentOnline(new UUID[] { new UUID(userID) }); else friendClient.SendAgentOffline(new UUID[] { new UUID(userID) }); } else { bool canEditObjectsChanged = ((rights ^ userFlags) & (int)FriendRights.CanModifyObjects) != 0; if (canEditObjectsChanged) friendClient.SendChangeUserRights(userID, friendID, rights); } return true; } return false; } public bool LocalStatusNotification(UUID userID, UUID friendID, bool online) { IClientAPI friendClient = LocateClientObject(friendID); if (friendClient != null) { //m_log.DebugFormat("[FRIENDS]: Notify {0} that user {1} is {2}", friend.Friend, userID, online); // the friend in this sim as root agent if (online) friendClient.SendAgentOnline(new UUID[] { userID }); else friendClient.SendAgentOffline(new UUID[] { userID }); // we're done return true; } 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 Xunit; namespace System.Reflection.Tests { // MemberInfo.MemberType Property // When overridden in a derived class, gets a MemberTypes value indicating // the type of the member method, constructor, event, and so on. public class ReflectionMemberInfoMemberType { // PosTest1: get accessor of public static property [Fact] public void PosTest1() { bool expectedValue = true; bool actualValue = false; MethodInfo methodInfo; MemberInfo memberInfo; methodInfo = typeof(TestClass1).GetProperty("InstanceCount").GetGetMethod(); memberInfo = methodInfo as MemberInfo; actualValue = memberInfo.Name.Equals("get_InstanceCount"); Assert.Equal(expectedValue, actualValue); } // PosTest2: set accessor of public instance property [Fact] public void PosTest2() { bool expectedValue = true; bool actualValue = false; MethodInfo methodInfo; MemberInfo memberInfo; methodInfo = typeof(TestClass1).GetProperty("Data1").GetSetMethod(); memberInfo = methodInfo as MemberInfo; actualValue = memberInfo.Name.Equals("set_Data1"); Assert.Equal(expectedValue, actualValue); } // PosTest3: public static property [Fact] public void PosTest3() { bool expectedValue = true; bool actualValue = false; PropertyInfo propertyInfo; MemberInfo memberInfo; propertyInfo = typeof(TestClass1).GetProperty("InstanceCount"); memberInfo = propertyInfo as MemberInfo; actualValue = memberInfo.Name.Equals("InstanceCount"); Assert.Equal(expectedValue, actualValue); } // PosTest4: public instance property [Fact] public void PosTest4() { bool expectedValue = true; bool actualValue = false; PropertyInfo propertyInfo; MemberInfo memberInfo; propertyInfo = typeof(TestClass1).GetProperty("Data1"); memberInfo = propertyInfo as MemberInfo; actualValue = memberInfo.Name.Equals("Data1"); Assert.Equal(expectedValue, actualValue); } // PosTest5: public constructor [Fact] public void PosTest5() { bool expectedValue = true; bool actualValue = false; ConstructorInfo constructorInfo; MemberInfo memberInfo; Type[] parameterTypes = { typeof(int) }; constructorInfo = typeof(TestClass1).GetConstructor(parameterTypes); memberInfo = constructorInfo as MemberInfo; actualValue = memberInfo.Name.Equals(".ctor"); ; Assert.Equal(expectedValue, actualValue); } // PosTest6: private instance field [Fact] public void PosTest6() { bool expectedValue = true; bool actualValue = false; Type testType; FieldInfo fieldInfo; MemberInfo memberInfo; testType = typeof(TestClass1); fieldInfo = testType.GetField("_data1", BindingFlags.NonPublic | BindingFlags.Instance); memberInfo = fieldInfo as MemberInfo; actualValue = memberInfo.Name.Equals("_data1"); Assert.Equal(expectedValue, actualValue); } // PosTest7: private static field [Fact] public void PosTest7() { bool expectedValue = true; bool actualValue = false; Type testType; FieldInfo fieldInfo; MemberInfo memberInfo; testType = typeof(TestClass1); fieldInfo = testType.GetField("s_count", BindingFlags.NonPublic | BindingFlags.Static); memberInfo = fieldInfo as MemberInfo; actualValue = memberInfo.Name.Equals("s_count"); ; Assert.Equal(expectedValue, actualValue); } // PosTest8: private instance event [Fact] public void PosTest8() { bool expectedValue = true; bool actualValue = false; Type testType; EventInfo eventInfo; MemberInfo memberInfo; testType = typeof(TestButton); eventInfo = testType.GetEvent("Click"); memberInfo = eventInfo as MemberInfo; actualValue = memberInfo.Name.Equals("Click"); ; Assert.Equal(expectedValue, actualValue); } // PosTest9: nested type [Fact] public void PosTest9() { bool expectedValue = true; bool actualValue = false; Type testType; Type nestedType; testType = typeof(ReflectionMemberInfoMemberType); nestedType = testType.GetNestedType("TestClass1", BindingFlags.NonPublic); actualValue = nestedType.IsNested; Assert.Equal(expectedValue, actualValue); } // PosTest10: unnested type [Fact] public void PosTest10() { bool expectedValue = true; bool actualValue = false; Type testType; testType = typeof(ReflectionMemberInfoMemberType); actualValue = testType.Name.Equals("ReflectionMemberInfoMemberType"); Assert.Equal(expectedValue, actualValue); } private class TestClass1 { private static int s_count = 0; //Defualt constructor public TestClass1() { ++s_count; } public TestClass1(int data1) { ++s_count; _data1 = data1; } public static int InstanceCount { get { return s_count; } } public int Data1 { get { return _data1; } set { _data1 = value; } } private int _data1; public void Do() { } } private class TestButton { public event EventHandler Click; protected void OnClick(EventArgs e) { if (null != Click) { Click(this, e); } } } } }
// Copyright 2017, Google LLC All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using Google.Api.Gax; using Google.Api.Gax.Grpc; using Google.Cloud.Iam.V1; using Google.Cloud.Spanner.Admin.Instance.V1; using Google.LongRunning; using Google.Protobuf; using Google.Protobuf.WellKnownTypes; using Grpc.Core; using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace Google.Cloud.Spanner.Admin.Instance.V1.Snippets { /// <summary>Generated snippets</summary> public class GeneratedInstanceAdminClientSnippets { /// <summary>Snippet for ListInstanceConfigsAsync</summary> public async Task ListInstanceConfigsAsync() { // Snippet: ListInstanceConfigsAsync(ProjectName,string,int?,CallSettings) // Create client InstanceAdminClient instanceAdminClient = await InstanceAdminClient.CreateAsync(); // Initialize request argument(s) ProjectName parent = new ProjectName("[PROJECT]"); // Make the request PagedAsyncEnumerable<ListInstanceConfigsResponse, InstanceConfig> response = instanceAdminClient.ListInstanceConfigsAsync(parent); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((InstanceConfig item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListInstanceConfigsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (InstanceConfig item in page) { Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<InstanceConfig> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (InstanceConfig item in singlePage) { Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListInstanceConfigs</summary> public void ListInstanceConfigs() { // Snippet: ListInstanceConfigs(ProjectName,string,int?,CallSettings) // Create client InstanceAdminClient instanceAdminClient = InstanceAdminClient.Create(); // Initialize request argument(s) ProjectName parent = new ProjectName("[PROJECT]"); // Make the request PagedEnumerable<ListInstanceConfigsResponse, InstanceConfig> response = instanceAdminClient.ListInstanceConfigs(parent); // Iterate over all response items, lazily performing RPCs as required foreach (InstanceConfig item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListInstanceConfigsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (InstanceConfig item in page) { Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<InstanceConfig> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (InstanceConfig item in singlePage) { Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListInstanceConfigsAsync</summary> public async Task ListInstanceConfigsAsync_RequestObject() { // Snippet: ListInstanceConfigsAsync(ListInstanceConfigsRequest,CallSettings) // Create client InstanceAdminClient instanceAdminClient = await InstanceAdminClient.CreateAsync(); // Initialize request argument(s) ListInstanceConfigsRequest request = new ListInstanceConfigsRequest { ParentAsProjectName = new ProjectName("[PROJECT]"), }; // Make the request PagedAsyncEnumerable<ListInstanceConfigsResponse, InstanceConfig> response = instanceAdminClient.ListInstanceConfigsAsync(request); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((InstanceConfig item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListInstanceConfigsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (InstanceConfig item in page) { Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<InstanceConfig> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (InstanceConfig item in singlePage) { Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListInstanceConfigs</summary> public void ListInstanceConfigs_RequestObject() { // Snippet: ListInstanceConfigs(ListInstanceConfigsRequest,CallSettings) // Create client InstanceAdminClient instanceAdminClient = InstanceAdminClient.Create(); // Initialize request argument(s) ListInstanceConfigsRequest request = new ListInstanceConfigsRequest { ParentAsProjectName = new ProjectName("[PROJECT]"), }; // Make the request PagedEnumerable<ListInstanceConfigsResponse, InstanceConfig> response = instanceAdminClient.ListInstanceConfigs(request); // Iterate over all response items, lazily performing RPCs as required foreach (InstanceConfig item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListInstanceConfigsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (InstanceConfig item in page) { Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<InstanceConfig> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (InstanceConfig item in singlePage) { Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for GetInstanceConfigAsync</summary> public async Task GetInstanceConfigAsync() { // Snippet: GetInstanceConfigAsync(InstanceConfigName,CallSettings) // Additional: GetInstanceConfigAsync(InstanceConfigName,CancellationToken) // Create client InstanceAdminClient instanceAdminClient = await InstanceAdminClient.CreateAsync(); // Initialize request argument(s) InstanceConfigName name = new InstanceConfigName("[PROJECT]", "[INSTANCE_CONFIG]"); // Make the request InstanceConfig response = await instanceAdminClient.GetInstanceConfigAsync(name); // End snippet } /// <summary>Snippet for GetInstanceConfig</summary> public void GetInstanceConfig() { // Snippet: GetInstanceConfig(InstanceConfigName,CallSettings) // Create client InstanceAdminClient instanceAdminClient = InstanceAdminClient.Create(); // Initialize request argument(s) InstanceConfigName name = new InstanceConfigName("[PROJECT]", "[INSTANCE_CONFIG]"); // Make the request InstanceConfig response = instanceAdminClient.GetInstanceConfig(name); // End snippet } /// <summary>Snippet for GetInstanceConfigAsync</summary> public async Task GetInstanceConfigAsync_RequestObject() { // Snippet: GetInstanceConfigAsync(GetInstanceConfigRequest,CallSettings) // Create client InstanceAdminClient instanceAdminClient = await InstanceAdminClient.CreateAsync(); // Initialize request argument(s) GetInstanceConfigRequest request = new GetInstanceConfigRequest { InstanceConfigName = new InstanceConfigName("[PROJECT]", "[INSTANCE_CONFIG]"), }; // Make the request InstanceConfig response = await instanceAdminClient.GetInstanceConfigAsync(request); // End snippet } /// <summary>Snippet for GetInstanceConfig</summary> public void GetInstanceConfig_RequestObject() { // Snippet: GetInstanceConfig(GetInstanceConfigRequest,CallSettings) // Create client InstanceAdminClient instanceAdminClient = InstanceAdminClient.Create(); // Initialize request argument(s) GetInstanceConfigRequest request = new GetInstanceConfigRequest { InstanceConfigName = new InstanceConfigName("[PROJECT]", "[INSTANCE_CONFIG]"), }; // Make the request InstanceConfig response = instanceAdminClient.GetInstanceConfig(request); // End snippet } /// <summary>Snippet for ListInstancesAsync</summary> public async Task ListInstancesAsync() { // Snippet: ListInstancesAsync(ProjectName,string,int?,CallSettings) // Create client InstanceAdminClient instanceAdminClient = await InstanceAdminClient.CreateAsync(); // Initialize request argument(s) ProjectName parent = new ProjectName("[PROJECT]"); // Make the request PagedAsyncEnumerable<ListInstancesResponse, Instance> response = instanceAdminClient.ListInstancesAsync(parent); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Instance item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListInstancesResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Instance item in page) { Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Instance> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Instance item in singlePage) { Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListInstances</summary> public void ListInstances() { // Snippet: ListInstances(ProjectName,string,int?,CallSettings) // Create client InstanceAdminClient instanceAdminClient = InstanceAdminClient.Create(); // Initialize request argument(s) ProjectName parent = new ProjectName("[PROJECT]"); // Make the request PagedEnumerable<ListInstancesResponse, Instance> response = instanceAdminClient.ListInstances(parent); // Iterate over all response items, lazily performing RPCs as required foreach (Instance item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListInstancesResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Instance item in page) { Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Instance> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Instance item in singlePage) { Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListInstancesAsync</summary> public async Task ListInstancesAsync_RequestObject() { // Snippet: ListInstancesAsync(ListInstancesRequest,CallSettings) // Create client InstanceAdminClient instanceAdminClient = await InstanceAdminClient.CreateAsync(); // Initialize request argument(s) ListInstancesRequest request = new ListInstancesRequest { ParentAsProjectName = new ProjectName("[PROJECT]"), }; // Make the request PagedAsyncEnumerable<ListInstancesResponse, Instance> response = instanceAdminClient.ListInstancesAsync(request); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Instance item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListInstancesResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Instance item in page) { Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Instance> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Instance item in singlePage) { Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListInstances</summary> public void ListInstances_RequestObject() { // Snippet: ListInstances(ListInstancesRequest,CallSettings) // Create client InstanceAdminClient instanceAdminClient = InstanceAdminClient.Create(); // Initialize request argument(s) ListInstancesRequest request = new ListInstancesRequest { ParentAsProjectName = new ProjectName("[PROJECT]"), }; // Make the request PagedEnumerable<ListInstancesResponse, Instance> response = instanceAdminClient.ListInstances(request); // Iterate over all response items, lazily performing RPCs as required foreach (Instance item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListInstancesResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Instance item in page) { Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Instance> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Instance item in singlePage) { Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for GetInstanceAsync</summary> public async Task GetInstanceAsync() { // Snippet: GetInstanceAsync(InstanceName,CallSettings) // Additional: GetInstanceAsync(InstanceName,CancellationToken) // Create client InstanceAdminClient instanceAdminClient = await InstanceAdminClient.CreateAsync(); // Initialize request argument(s) InstanceName name = new InstanceName("[PROJECT]", "[INSTANCE]"); // Make the request Instance response = await instanceAdminClient.GetInstanceAsync(name); // End snippet } /// <summary>Snippet for GetInstance</summary> public void GetInstance() { // Snippet: GetInstance(InstanceName,CallSettings) // Create client InstanceAdminClient instanceAdminClient = InstanceAdminClient.Create(); // Initialize request argument(s) InstanceName name = new InstanceName("[PROJECT]", "[INSTANCE]"); // Make the request Instance response = instanceAdminClient.GetInstance(name); // End snippet } /// <summary>Snippet for GetInstanceAsync</summary> public async Task GetInstanceAsync_RequestObject() { // Snippet: GetInstanceAsync(GetInstanceRequest,CallSettings) // Create client InstanceAdminClient instanceAdminClient = await InstanceAdminClient.CreateAsync(); // Initialize request argument(s) GetInstanceRequest request = new GetInstanceRequest { InstanceName = new InstanceName("[PROJECT]", "[INSTANCE]"), }; // Make the request Instance response = await instanceAdminClient.GetInstanceAsync(request); // End snippet } /// <summary>Snippet for GetInstance</summary> public void GetInstance_RequestObject() { // Snippet: GetInstance(GetInstanceRequest,CallSettings) // Create client InstanceAdminClient instanceAdminClient = InstanceAdminClient.Create(); // Initialize request argument(s) GetInstanceRequest request = new GetInstanceRequest { InstanceName = new InstanceName("[PROJECT]", "[INSTANCE]"), }; // Make the request Instance response = instanceAdminClient.GetInstance(request); // End snippet } /// <summary>Snippet for CreateInstanceAsync</summary> public async Task CreateInstanceAsync() { // Snippet: CreateInstanceAsync(ProjectName,InstanceName,Instance,CallSettings) // Additional: CreateInstanceAsync(ProjectName,InstanceName,Instance,CancellationToken) // Create client InstanceAdminClient instanceAdminClient = await InstanceAdminClient.CreateAsync(); // Initialize request argument(s) ProjectName parent = new ProjectName("[PROJECT]"); InstanceName instanceId = new InstanceName("[PROJECT]", "[INSTANCE]"); Instance instance = new Instance(); // Make the request Operation<Instance, CreateInstanceMetadata> response = await instanceAdminClient.CreateInstanceAsync(parent, instanceId, instance); // Poll until the returned long-running operation is complete Operation<Instance, CreateInstanceMetadata> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Instance result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<Instance, CreateInstanceMetadata> retrievedResponse = await instanceAdminClient.PollOnceCreateInstanceAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Instance retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for CreateInstance</summary> public void CreateInstance() { // Snippet: CreateInstance(ProjectName,InstanceName,Instance,CallSettings) // Create client InstanceAdminClient instanceAdminClient = InstanceAdminClient.Create(); // Initialize request argument(s) ProjectName parent = new ProjectName("[PROJECT]"); InstanceName instanceId = new InstanceName("[PROJECT]", "[INSTANCE]"); Instance instance = new Instance(); // Make the request Operation<Instance, CreateInstanceMetadata> response = instanceAdminClient.CreateInstance(parent, instanceId, instance); // Poll until the returned long-running operation is complete Operation<Instance, CreateInstanceMetadata> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Instance result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<Instance, CreateInstanceMetadata> retrievedResponse = instanceAdminClient.PollOnceCreateInstance(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Instance retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for CreateInstanceAsync</summary> public async Task CreateInstanceAsync_RequestObject() { // Snippet: CreateInstanceAsync(CreateInstanceRequest,CallSettings) // Create client InstanceAdminClient instanceAdminClient = await InstanceAdminClient.CreateAsync(); // Initialize request argument(s) CreateInstanceRequest request = new CreateInstanceRequest { ParentAsProjectName = new ProjectName("[PROJECT]"), InstanceIdAsInstanceName = new InstanceName("[PROJECT]", "[INSTANCE]"), Instance = new Instance(), }; // Make the request Operation<Instance, CreateInstanceMetadata> response = await instanceAdminClient.CreateInstanceAsync(request); // Poll until the returned long-running operation is complete Operation<Instance, CreateInstanceMetadata> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Instance result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<Instance, CreateInstanceMetadata> retrievedResponse = await instanceAdminClient.PollOnceCreateInstanceAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Instance retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for CreateInstance</summary> public void CreateInstance_RequestObject() { // Snippet: CreateInstance(CreateInstanceRequest,CallSettings) // Create client InstanceAdminClient instanceAdminClient = InstanceAdminClient.Create(); // Initialize request argument(s) CreateInstanceRequest request = new CreateInstanceRequest { ParentAsProjectName = new ProjectName("[PROJECT]"), InstanceIdAsInstanceName = new InstanceName("[PROJECT]", "[INSTANCE]"), Instance = new Instance(), }; // Make the request Operation<Instance, CreateInstanceMetadata> response = instanceAdminClient.CreateInstance(request); // Poll until the returned long-running operation is complete Operation<Instance, CreateInstanceMetadata> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Instance result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<Instance, CreateInstanceMetadata> retrievedResponse = instanceAdminClient.PollOnceCreateInstance(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Instance retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for UpdateInstanceAsync</summary> public async Task UpdateInstanceAsync() { // Snippet: UpdateInstanceAsync(Instance,FieldMask,CallSettings) // Additional: UpdateInstanceAsync(Instance,FieldMask,CancellationToken) // Create client InstanceAdminClient instanceAdminClient = await InstanceAdminClient.CreateAsync(); // Initialize request argument(s) Instance instance = new Instance(); FieldMask fieldMask = new FieldMask(); // Make the request Operation<Instance, UpdateInstanceMetadata> response = await instanceAdminClient.UpdateInstanceAsync(instance, fieldMask); // Poll until the returned long-running operation is complete Operation<Instance, UpdateInstanceMetadata> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Instance result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<Instance, UpdateInstanceMetadata> retrievedResponse = await instanceAdminClient.PollOnceUpdateInstanceAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Instance retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for UpdateInstance</summary> public void UpdateInstance() { // Snippet: UpdateInstance(Instance,FieldMask,CallSettings) // Create client InstanceAdminClient instanceAdminClient = InstanceAdminClient.Create(); // Initialize request argument(s) Instance instance = new Instance(); FieldMask fieldMask = new FieldMask(); // Make the request Operation<Instance, UpdateInstanceMetadata> response = instanceAdminClient.UpdateInstance(instance, fieldMask); // Poll until the returned long-running operation is complete Operation<Instance, UpdateInstanceMetadata> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Instance result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<Instance, UpdateInstanceMetadata> retrievedResponse = instanceAdminClient.PollOnceUpdateInstance(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Instance retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for UpdateInstanceAsync</summary> public async Task UpdateInstanceAsync_RequestObject() { // Snippet: UpdateInstanceAsync(UpdateInstanceRequest,CallSettings) // Create client InstanceAdminClient instanceAdminClient = await InstanceAdminClient.CreateAsync(); // Initialize request argument(s) UpdateInstanceRequest request = new UpdateInstanceRequest { Instance = new Instance(), FieldMask = new FieldMask(), }; // Make the request Operation<Instance, UpdateInstanceMetadata> response = await instanceAdminClient.UpdateInstanceAsync(request); // Poll until the returned long-running operation is complete Operation<Instance, UpdateInstanceMetadata> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Instance result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<Instance, UpdateInstanceMetadata> retrievedResponse = await instanceAdminClient.PollOnceUpdateInstanceAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Instance retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for UpdateInstance</summary> public void UpdateInstance_RequestObject() { // Snippet: UpdateInstance(UpdateInstanceRequest,CallSettings) // Create client InstanceAdminClient instanceAdminClient = InstanceAdminClient.Create(); // Initialize request argument(s) UpdateInstanceRequest request = new UpdateInstanceRequest { Instance = new Instance(), FieldMask = new FieldMask(), }; // Make the request Operation<Instance, UpdateInstanceMetadata> response = instanceAdminClient.UpdateInstance(request); // Poll until the returned long-running operation is complete Operation<Instance, UpdateInstanceMetadata> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Instance result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<Instance, UpdateInstanceMetadata> retrievedResponse = instanceAdminClient.PollOnceUpdateInstance(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Instance retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for DeleteInstanceAsync</summary> public async Task DeleteInstanceAsync() { // Snippet: DeleteInstanceAsync(InstanceName,CallSettings) // Additional: DeleteInstanceAsync(InstanceName,CancellationToken) // Create client InstanceAdminClient instanceAdminClient = await InstanceAdminClient.CreateAsync(); // Initialize request argument(s) InstanceName name = new InstanceName("[PROJECT]", "[INSTANCE]"); // Make the request await instanceAdminClient.DeleteInstanceAsync(name); // End snippet } /// <summary>Snippet for DeleteInstance</summary> public void DeleteInstance() { // Snippet: DeleteInstance(InstanceName,CallSettings) // Create client InstanceAdminClient instanceAdminClient = InstanceAdminClient.Create(); // Initialize request argument(s) InstanceName name = new InstanceName("[PROJECT]", "[INSTANCE]"); // Make the request instanceAdminClient.DeleteInstance(name); // End snippet } /// <summary>Snippet for DeleteInstanceAsync</summary> public async Task DeleteInstanceAsync_RequestObject() { // Snippet: DeleteInstanceAsync(DeleteInstanceRequest,CallSettings) // Create client InstanceAdminClient instanceAdminClient = await InstanceAdminClient.CreateAsync(); // Initialize request argument(s) DeleteInstanceRequest request = new DeleteInstanceRequest { InstanceName = new InstanceName("[PROJECT]", "[INSTANCE]"), }; // Make the request await instanceAdminClient.DeleteInstanceAsync(request); // End snippet } /// <summary>Snippet for DeleteInstance</summary> public void DeleteInstance_RequestObject() { // Snippet: DeleteInstance(DeleteInstanceRequest,CallSettings) // Create client InstanceAdminClient instanceAdminClient = InstanceAdminClient.Create(); // Initialize request argument(s) DeleteInstanceRequest request = new DeleteInstanceRequest { InstanceName = new InstanceName("[PROJECT]", "[INSTANCE]"), }; // Make the request instanceAdminClient.DeleteInstance(request); // End snippet } /// <summary>Snippet for SetIamPolicyAsync</summary> public async Task SetIamPolicyAsync() { // Snippet: SetIamPolicyAsync(string,Policy,CallSettings) // Additional: SetIamPolicyAsync(string,Policy,CancellationToken) // Create client InstanceAdminClient instanceAdminClient = await InstanceAdminClient.CreateAsync(); // Initialize request argument(s) string formattedResource = new InstanceName("[PROJECT]", "[INSTANCE]").ToString(); Policy policy = new Policy(); // Make the request Policy response = await instanceAdminClient.SetIamPolicyAsync(formattedResource, policy); // End snippet } /// <summary>Snippet for SetIamPolicy</summary> public void SetIamPolicy() { // Snippet: SetIamPolicy(string,Policy,CallSettings) // Create client InstanceAdminClient instanceAdminClient = InstanceAdminClient.Create(); // Initialize request argument(s) string formattedResource = new InstanceName("[PROJECT]", "[INSTANCE]").ToString(); Policy policy = new Policy(); // Make the request Policy response = instanceAdminClient.SetIamPolicy(formattedResource, policy); // End snippet } /// <summary>Snippet for SetIamPolicyAsync</summary> public async Task SetIamPolicyAsync_RequestObject() { // Snippet: SetIamPolicyAsync(SetIamPolicyRequest,CallSettings) // Create client InstanceAdminClient instanceAdminClient = await InstanceAdminClient.CreateAsync(); // Initialize request argument(s) SetIamPolicyRequest request = new SetIamPolicyRequest { Resource = new InstanceName("[PROJECT]", "[INSTANCE]").ToString(), Policy = new Policy(), }; // Make the request Policy response = await instanceAdminClient.SetIamPolicyAsync(request); // End snippet } /// <summary>Snippet for SetIamPolicy</summary> public void SetIamPolicy_RequestObject() { // Snippet: SetIamPolicy(SetIamPolicyRequest,CallSettings) // Create client InstanceAdminClient instanceAdminClient = InstanceAdminClient.Create(); // Initialize request argument(s) SetIamPolicyRequest request = new SetIamPolicyRequest { Resource = new InstanceName("[PROJECT]", "[INSTANCE]").ToString(), Policy = new Policy(), }; // Make the request Policy response = instanceAdminClient.SetIamPolicy(request); // End snippet } /// <summary>Snippet for GetIamPolicyAsync</summary> public async Task GetIamPolicyAsync() { // Snippet: GetIamPolicyAsync(string,CallSettings) // Additional: GetIamPolicyAsync(string,CancellationToken) // Create client InstanceAdminClient instanceAdminClient = await InstanceAdminClient.CreateAsync(); // Initialize request argument(s) string formattedResource = new InstanceName("[PROJECT]", "[INSTANCE]").ToString(); // Make the request Policy response = await instanceAdminClient.GetIamPolicyAsync(formattedResource); // End snippet } /// <summary>Snippet for GetIamPolicy</summary> public void GetIamPolicy() { // Snippet: GetIamPolicy(string,CallSettings) // Create client InstanceAdminClient instanceAdminClient = InstanceAdminClient.Create(); // Initialize request argument(s) string formattedResource = new InstanceName("[PROJECT]", "[INSTANCE]").ToString(); // Make the request Policy response = instanceAdminClient.GetIamPolicy(formattedResource); // End snippet } /// <summary>Snippet for GetIamPolicyAsync</summary> public async Task GetIamPolicyAsync_RequestObject() { // Snippet: GetIamPolicyAsync(GetIamPolicyRequest,CallSettings) // Create client InstanceAdminClient instanceAdminClient = await InstanceAdminClient.CreateAsync(); // Initialize request argument(s) GetIamPolicyRequest request = new GetIamPolicyRequest { Resource = new InstanceName("[PROJECT]", "[INSTANCE]").ToString(), }; // Make the request Policy response = await instanceAdminClient.GetIamPolicyAsync(request); // End snippet } /// <summary>Snippet for GetIamPolicy</summary> public void GetIamPolicy_RequestObject() { // Snippet: GetIamPolicy(GetIamPolicyRequest,CallSettings) // Create client InstanceAdminClient instanceAdminClient = InstanceAdminClient.Create(); // Initialize request argument(s) GetIamPolicyRequest request = new GetIamPolicyRequest { Resource = new InstanceName("[PROJECT]", "[INSTANCE]").ToString(), }; // Make the request Policy response = instanceAdminClient.GetIamPolicy(request); // End snippet } /// <summary>Snippet for TestIamPermissionsAsync</summary> public async Task TestIamPermissionsAsync() { // Snippet: TestIamPermissionsAsync(string,IEnumerable<string>,CallSettings) // Additional: TestIamPermissionsAsync(string,IEnumerable<string>,CancellationToken) // Create client InstanceAdminClient instanceAdminClient = await InstanceAdminClient.CreateAsync(); // Initialize request argument(s) string formattedResource = new InstanceName("[PROJECT]", "[INSTANCE]").ToString(); IEnumerable<string> permissions = new List<string>(); // Make the request TestIamPermissionsResponse response = await instanceAdminClient.TestIamPermissionsAsync(formattedResource, permissions); // End snippet } /// <summary>Snippet for TestIamPermissions</summary> public void TestIamPermissions() { // Snippet: TestIamPermissions(string,IEnumerable<string>,CallSettings) // Create client InstanceAdminClient instanceAdminClient = InstanceAdminClient.Create(); // Initialize request argument(s) string formattedResource = new InstanceName("[PROJECT]", "[INSTANCE]").ToString(); IEnumerable<string> permissions = new List<string>(); // Make the request TestIamPermissionsResponse response = instanceAdminClient.TestIamPermissions(formattedResource, permissions); // End snippet } /// <summary>Snippet for TestIamPermissionsAsync</summary> public async Task TestIamPermissionsAsync_RequestObject() { // Snippet: TestIamPermissionsAsync(TestIamPermissionsRequest,CallSettings) // Create client InstanceAdminClient instanceAdminClient = await InstanceAdminClient.CreateAsync(); // Initialize request argument(s) TestIamPermissionsRequest request = new TestIamPermissionsRequest { Resource = new InstanceName("[PROJECT]", "[INSTANCE]").ToString(), Permissions = { }, }; // Make the request TestIamPermissionsResponse response = await instanceAdminClient.TestIamPermissionsAsync(request); // End snippet } /// <summary>Snippet for TestIamPermissions</summary> public void TestIamPermissions_RequestObject() { // Snippet: TestIamPermissions(TestIamPermissionsRequest,CallSettings) // Create client InstanceAdminClient instanceAdminClient = InstanceAdminClient.Create(); // Initialize request argument(s) TestIamPermissionsRequest request = new TestIamPermissionsRequest { Resource = new InstanceName("[PROJECT]", "[INSTANCE]").ToString(), Permissions = { }, }; // Make the request TestIamPermissionsResponse response = instanceAdminClient.TestIamPermissions(request); // End snippet } } }
using Autofac; using System; using System.Globalization; using System.Linq; using System.Xml.Linq; using TeaCommerce.Api.Common; using TeaCommerce.Api.Dependency; using TeaCommerce.Api.InformationExtractors; using TeaCommerce.Api.Models; using TeaCommerce.Api.Services; using TeaCommerce.Umbraco.Configuration.Services; using TeaCommerce.Umbraco.Configuration.Variants.Models; using Umbraco.Core; using Umbraco.Core.Models; using Umbraco.Web; using Constants = TeaCommerce.Api.Constants; namespace TeaCommerce.Umbraco.Configuration.InformationExtractors { public class ContentProductInformationExtractor : IProductInformationExtractor<IContent, VariantPublishedContent>, IProductInformationExtractor<IContent> { protected readonly IStoreService StoreService; protected readonly ICurrencyService CurrencyService; protected readonly IVatGroupService VatGroupService; public static IProductInformationExtractor<IContent, VariantPublishedContent> Instance { get { return DependencyContainer.Instance.Resolve<IProductInformationExtractor<IContent, VariantPublishedContent>>(); } } #region IProductInformationExtractor<IPublishedContent, VariantPublishedContent> public ContentProductInformationExtractor( IStoreService storeService, ICurrencyService currencyService, IVatGroupService vatGroupService ) { StoreService = storeService; CurrencyService = currencyService; VatGroupService = vatGroupService; } public virtual long GetStoreId( IContent model , VariantPublishedContent variant ) { long? storeId = GetPropertyValue<long?>( model, Constants.ProductPropertyAliases.StorePropertyAlias ); if ( storeId == null ) { throw new ArgumentException( "The model doesn't have a store id associated with it - remember to add the Tea Commerce store picker to your Umbraco content tree" ); } return storeId.Value; } public virtual string GetSku( IContent model, VariantPublishedContent variant = null ) { string sku = GetPropertyValue<string>( model, Constants.ProductPropertyAliases.SkuPropertyAlias, variant ); //If no sku is found - default to umbraco node id if ( string.IsNullOrEmpty( sku ) ) { sku = model.Id.ToString( CultureInfo.InvariantCulture ) + ( variant != null ? "_" + variant.VariantIdentifier : "" ); } return sku; } public virtual string GetName( IContent product, VariantPublishedContent variant = null ) { string name = GetPropertyValue<string>( product, Constants.ProductPropertyAliases.NamePropertyAlias, variant ); //If no name is found - default to the umbraco node name if ( string.IsNullOrEmpty( name ) ) { if ( variant != null ) { name = GetPropertyValue<string>( product, Constants.ProductPropertyAliases.NamePropertyAlias ); } if ( string.IsNullOrEmpty( name ) ) { name = product.Name; } if ( variant != null ) { name += " - " + variant.Name; } } return name; } public virtual long? GetVatGroupId( IContent model, VariantPublishedContent variant = null ) { long storeId = GetStoreId( model ); long? vatGroupId = GetPropertyValue<long?>( model, Constants.ProductPropertyAliases.VatGroupPropertyAlias, variant ); //In umbraco a product can have a relation to a delete marked vat group if ( vatGroupId != null ) { VatGroup vatGroup = VatGroupService.Get( storeId, vatGroupId.Value ); if ( vatGroup == null || vatGroup.IsDeleted ) { vatGroupId = null; } } return vatGroupId; } public virtual OriginalUnitPriceCollection GetOriginalUnitPrices( IContent product, VariantPublishedContent variant = null ) { OriginalUnitPriceCollection prices = new OriginalUnitPriceCollection(); foreach ( Currency currency in CurrencyService.GetAll( GetStoreId( product ) ) ) { prices.Add( new OriginalUnitPrice( GetPropertyValue<string>( product, currency.PricePropertyAlias, variant ).ParseToDecimal() ?? 0M, currency.Id ) ); } return prices; } protected bool CheckNullOrEmpty<T>( T value ) { if ( typeof( T ) == typeof( string ) ) return string.IsNullOrEmpty( value as string ); return value == null || value.Equals( default( T ) ); } public virtual long? GetLanguageId( IContent model, VariantPublishedContent variant ) { return LanguageService.Instance.GetLanguageIdByNodePath( model.Path ); } public virtual CustomPropertyCollection GetProperties( IContent product, VariantPublishedContent variant = null ) { CustomPropertyCollection properties = new CustomPropertyCollection(); foreach ( string productPropertyAlias in StoreService.Get( GetStoreId( product ) ).ProductSettings.ProductPropertyAliases ) { properties.Add( new CustomProperty( productPropertyAlias, GetPropertyValue<string>( product, productPropertyAlias, variant ) ) { IsReadOnly = true } ); } return properties; } #endregion #region IProductInformationExtractor<IPublishedContent> public long GetStoreId( IContent product ) { return GetStoreId( product, null ); } public string GetSku( IContent product ) { return GetSku( product, null ); } public string GetName( IContent product ) { return GetName( product, null ); } public long? GetVatGroupId( IContent product ) { return GetVatGroupId( product, null ); } public OriginalUnitPriceCollection GetOriginalUnitPrices( IContent product ) { return GetOriginalUnitPrices( product, null ); } public long? GetLanguageId( IContent product ) { return GetLanguageId( product, null ); } public CustomPropertyCollection GetProperties( IContent product ) { return GetProperties( product, null ); } public string GetPropertyValue( IContent product, string propertyAlias ) { return GetPropertyValue( product, propertyAlias, null ); } #endregion public virtual string GetPropertyValue( IContent product, string propertyAlias, VariantPublishedContent variant = null ) { return GetPropertyValue<string>( product, Constants.ProductPropertyAliases.NamePropertyAlias, variant ); } public virtual T GetPropertyValue<T>( IContent model, string propertyAlias, VariantPublishedContent variant = null, Func<IContent, bool> func = null ) { T rtnValue = default( T ); if ( model != null && !string.IsNullOrEmpty( propertyAlias ) ) { if ( variant != null ) { rtnValue = variant.GetPropertyValue<T>( propertyAlias ); } if ( CheckNullOrEmpty( rtnValue ) ) { //Check if this node or ancestor has it IContent currentNode = func != null ? model.Ancestors().FirstOrDefault( func ) : model; if ( currentNode != null ) { rtnValue = GetPropertyValueInternal<T>( currentNode, propertyAlias, func == null ); } //Check if we found the value if ( CheckNullOrEmpty( rtnValue ) ) { //Check if we can find a master relation string masterRelationNodeIdStr = GetPropertyValueInternal<string>( model, Constants.ProductPropertyAliases.MasterRelationPropertyAlias, true ); int masterRelationNodeId = 0; if ( !string.IsNullOrEmpty( masterRelationNodeIdStr ) && int.TryParse( masterRelationNodeIdStr, out masterRelationNodeId ) ) { rtnValue = GetPropertyValue<T>( ApplicationContext.Current.Services.ContentService.GetById( masterRelationNodeId ), propertyAlias, variant, func ); } } } } return rtnValue; } protected virtual T GetPropertyValueInternal<T>( IContent content, string propertyAlias, bool recursive ) { T rtnValue = default( T ); if ( content != null && !string.IsNullOrEmpty( propertyAlias ) ) { if ( !recursive ) { rtnValue = content.GetValue<T>( propertyAlias ); } else { //We need to go recursive IContent tempModel = content; T tempProperty = default( T ); try { tempProperty = tempModel.GetValue<T>( propertyAlias ); } catch { } if ( !CheckNullOrEmpty( tempProperty ) ) { rtnValue = tempProperty; } while ( CheckNullOrEmpty( rtnValue ) && tempModel != null && tempModel.Id > 0 ) { tempModel = tempModel.Parent(); if ( tempModel != null ) { try { tempProperty = tempModel.GetValue<T>( propertyAlias ); } catch { } if ( !CheckNullOrEmpty( tempProperty ) ) { rtnValue = tempProperty; } } } } } return rtnValue; } } }
using System; using System.Collections.Generic; using System.Text.RegularExpressions; using System.Web.Routing; using System.Web.Mvc; using Cuyahoga.Core; using Cuyahoga.Core.Domain; using Cuyahoga.Core.Service.Content; using Cuyahoga.Core.Util; using Cuyahoga.Core.Communication; using Cuyahoga.Modules.Articles.Domain; using Cuyahoga.Web.Mvc; using Cuyahoga.Web.Mvc.Areas; using Cuyahoga.Core.DataAccess; using Castle.Services.Transaction; namespace Cuyahoga.Modules.Articles { /// <summary> /// The ArticleModule provides a news system (articles, comments, content expiration, rss feed). /// </summary> [Transactional] public class ArticleModule : ModuleBase, IActionProvider, INHibernateModule, IMvcModule { private readonly IContentItemService<Article> _contentItemService; private readonly ICategoryService _categoryService; private readonly ICommentService _commentService; private long _currentArticleId; private int _currentCategoryId; private bool _isArchive; private bool _allowComments; private bool _allowAnonymousComments; private bool _allowSyndication; private bool _showArchive; private bool _showCategory; private bool _showAuthor; private bool _showDateTime; private int _numberOfArticlesInList; private DisplayType _displayType; private SortBy _sortBy; private SortDirection _sortDirection; private ArticleModuleAction _currentAction; #region properties /// <summary> /// Property CurrentArticleId (int) /// </summary> public long CurrentArticleId { get { return this._currentArticleId; } } /// <summary> /// Property CurrentCategory (int) /// </summary> public int CurrentCategoryId { get { return this._currentCategoryId; } } /// <summary> /// /// </summary> public ArticleModuleAction CurrentAction { get { return this._currentAction; } } /// <summary> /// Show archived articles instead of the current ones. /// </summary> public bool IsArchive { get { return this._isArchive; } } /// <summary> /// Allow syndication of articles? /// </summary> public bool AllowSyndication { get { return this._allowSyndication; } } /// <summary> /// /// </summary> public bool AllowComments { get { return this._allowComments; } } /// <summary> /// /// </summary> public bool AllowAnonymousComments { get { return this._allowAnonymousComments; } } /// <summary> /// /// </summary> public int NumberOfArticlesInList { get { return this._numberOfArticlesInList; } } /// <summary> /// Show a link to archived articles? /// </summary> public bool ShowArchive { get { return this._showArchive; } } /// <summary> /// Show the article category? /// </summary> public bool ShowCategory { get { return _showCategory; } } /// <summary> /// Show article author? /// </summary> public bool ShowAuthor { get { return this._showAuthor; } } /// <summary> /// Show article date and time? /// </summary> public bool ShowDateTime { get { return _showDateTime; } } #endregion /// <summary> /// Default constructor. /// </summary> public ArticleModule(IContentItemService<Article> contentItemService, ICategoryService categoryService, ICommentService commentService) { this._contentItemService = contentItemService; this._categoryService = categoryService; this._commentService = commentService; this._currentArticleId = -1; this._currentCategoryId = -1; this._currentAction = ArticleModuleAction.List; } #region ModuleBase overrides public override void ReadSectionSettings() { base.ReadSectionSettings(); try { this._allowComments = Convert.ToBoolean(base.Section.Settings["ALLOW_COMMENTS"]); this._allowAnonymousComments = Convert.ToBoolean(base.Section.Settings["ALLOW_ANONYMOUS_COMMENTS"]); this._allowSyndication = Convert.ToBoolean(base.Section.Settings["ALLOW_SYNDICATION"]); this._showArchive = Convert.ToBoolean(base.Section.Settings["SHOW_ARCHIVE"]); this._showAuthor = Convert.ToBoolean(base.Section.Settings["SHOW_AUTHOR"]); this._showCategory = Convert.ToBoolean(base.Section.Settings["SHOW_CATEGORY"]); this._showDateTime = Convert.ToBoolean(base.Section.Settings["SHOW_DATETIME"]); this._numberOfArticlesInList = Convert.ToInt32(base.Section.Settings["NUMBER_OF_ARTICLES_IN_LIST"]); this._displayType = (DisplayType)Enum.Parse(typeof(DisplayType), base.Section.Settings["DISPLAY_TYPE"].ToString()); this._sortBy = (SortBy)Enum.Parse(typeof(SortBy), base.Section.Settings["SORT_BY"].ToString()); this._sortDirection = (SortDirection)Enum.Parse(typeof(SortDirection), base.Section.Settings["SORT_DIRECTION"].ToString()); } catch { // Only if the module settings are not in the database yet for some reason. this._sortBy = SortBy.DateOnline; this._sortDirection = SortDirection.DESC; } } /// <summary> /// This module doesn't automatically delete content. /// </summary> public override void DeleteModuleContent() { if (this._contentItemService.FindContentItemsBySection(base.Section).Count > 0) { throw new ActionForbiddenException("You have to manually delete the related Articles before you can delete the Section."); } } /// <summary> /// Parse the pathinfo. Translate pathinfo parameters into member variables. /// </summary> protected override void ParsePathInfo() { if (base.ModulePathInfo != null) { // try to find an articleId string expression = @"^\/(\d+)"; if (Regex.IsMatch(base.ModulePathInfo, expression, RegexOptions.Singleline | RegexOptions.CultureInvariant | RegexOptions.Compiled)) { this._currentArticleId = Int32.Parse(Regex.Match(base.ModulePathInfo, expression).Groups[1].Value); this._currentAction = ArticleModuleAction.Details; return; } // try to find a categoryid expression = @"^\/category\/(\d+)"; if (Regex.IsMatch(base.ModulePathInfo, expression, RegexOptions.Singleline | RegexOptions.CultureInvariant | RegexOptions.Compiled)) { this._currentCategoryId = Int32.Parse(Regex.Match(base.ModulePathInfo, expression).Groups[1].Value); this._currentAction = ArticleModuleAction.Category; return; } expression = @"^\/archive"; if (Regex.IsMatch(base.ModulePathInfo, expression, RegexOptions.Singleline | RegexOptions.CultureInvariant | RegexOptions.Compiled)) { this._isArchive = true; this._currentAction = ArticleModuleAction.Archive; return; } } } /// <summary> /// The current view user control based on the action that was set while parsing the pathinfo. /// </summary> public override string CurrentViewControlPath { get { string basePath = "Modules/Articles/"; switch (this._currentAction) { case ArticleModuleAction.List: case ArticleModuleAction.Category: case ArticleModuleAction.Archive: return basePath + "Articles.ascx"; case ArticleModuleAction.Details: return basePath + "ArticleDetails.ascx"; default: return basePath + "Articles.ascx"; } } } #endregion #region DataAccess for WebForms controls /// <summary> /// Get this list of articles /// </summary> /// <returns></returns> public IList<Article> GetArticleList() { switch (this._currentAction) { case ArticleModuleAction.List: return this._contentItemService.FindVisibleContentItemsBySection(base.Section, CreateQuerySettingsForModule()); case ArticleModuleAction.Category: return this._contentItemService.FindVisibleContentItemsByCategory( this._categoryService.GetCategoryById(this._currentCategoryId), CreateQuerySettingsForModule()); case ArticleModuleAction.Archive: return this._contentItemService.FindArchivedContentItemsBySection(base.Section, CreateQuerySettingsForModule()); default: return null; } } /// <summary> /// Gets a single article by Id. /// </summary> /// <param name="id"></param> /// <returns></returns> public Article GetArticleById(long id) { return this._contentItemService.GetById(id); } /// <summary> /// Get the url of a user profile. This only works if this module is connected to a UserProfile module. /// </summary> /// <param name="userId"></param> /// <returns></returns> public string GetProfileUrl(int userId) { if (this.Section.Connections.ContainsKey("ViewProfile")) { return String.Format("{0}/ViewProfile/{1}", UrlUtil.GetUrlFromSection(this.Section.Connections["ViewProfile"]), userId); } return null; } public void SaveComment(Comment comment) { this._commentService.SaveComment(comment); } public Category GetCategoryById(int categoryId) { return this._categoryService.GetCategoryById(categoryId); } #endregion #region IActionProvider Members /// <summary> /// Returns a list of outbound actions. /// </summary> /// <returns></returns> public ModuleActionCollection GetOutboundActions() { ModuleActionCollection moduleActions = new ModuleActionCollection(); // This action is for example compatible with the ViewProfile inbound action of // the ProfileModule but it's also possible to write your own Profile module that // has a compatible inbound action. moduleActions.Add(new ModuleAction("ViewProfile", new string[1] {"UserId"})); return moduleActions; } #endregion #region IMvcModule members public void RegisterRoutes(RouteCollection routes) { routes.CreateArea("Modules/Articles", "Cuyahoga.Modules.Articles.Controllers", routes.MapRoute("ArticlesRoute", "Modules/Articles/{controller}/{action}/{id}", new { action = "Index", controller = "", id = "" }) ); } #endregion private ContentItemQuerySettings CreateQuerySettingsForModule() { return CreateQuerySettingsForModule(null, null); } private ContentItemQuerySettings CreateQuerySettingsForModule(int? pageSize, int? pageNumber) { // Map sortby and sortdirection to the ones of the content item. We don't use these in the articles module // because we need to convert all module settings for. Maybe sometime in the future. ContentItemSortBy sortBy = ContentItemSortBy.None; switch(this._sortBy) { case SortBy.CreatedBy: sortBy = ContentItemSortBy.CreatedBy; break; case SortBy.DateCreated: sortBy = ContentItemSortBy.CreatedAt; break; case SortBy.DateModified: sortBy = ContentItemSortBy.ModifiedAt; break; case SortBy.DateOnline: sortBy = ContentItemSortBy.PublishedAt; break; case SortBy.ModifiedBy: sortBy = ContentItemSortBy.ModifiedBy; break; case SortBy.Title: sortBy = ContentItemSortBy.Title; break; } ContentItemSortDirection sortDirection = this._sortDirection == SortDirection.ASC ? ContentItemSortDirection.ASC : ContentItemSortDirection.DESC; return new ContentItemQuerySettings(sortBy, sortDirection, pageSize, pageNumber); } } /// <summary> /// The displaytype of the articles in the list. /// </summary> public enum DisplayType { HeadersOnly, HeadersAndSummary, FullContent, } /// <summary> /// The property to sort the articles by. /// </summary> public enum SortBy { /// <summary> /// Sort by DateOnline. /// </summary> DateOnline, /// <summary> /// Sort by DateCreated. /// </summary> DateCreated, /// <summary> /// Sort by DateModified. /// </summary> DateModified, /// <summary> /// Sort by Title. /// </summary> Title, /// <summary> /// Sort by Category. /// </summary> Category, /// <summary> /// Sort by the user who created the article. /// </summary> CreatedBy, /// <summary> /// Sort by the user who modified the article most recently. /// </summary> ModifiedBy, /// <summary> /// Don't sort the articles. /// </summary> None } /// <summary> /// The sort direction of the articles in the list. /// </summary> public enum SortDirection { /// <summary> /// Sort descending. /// </summary> DESC, /// <summary> /// Sort ascending. /// </summary> ASC } public enum ArticleModuleAction { /// <summary> /// Show the list of articles. /// </summary> List, /// <summary> /// Show a single article. /// </summary> Details, /// <summary> /// Show all articles for a particular category. /// </summary> Category, /// <summary> /// Show all expired articles. /// </summary> Archive } }
// 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.Contracts; using System.Collections; using System.Globalization; using System.Threading; namespace System.Text { // This class overrides Encoding with the things we need for our NLS Encodings // // All of the GetBytes/Chars GetByte/CharCount methods are just wrappers for the pointer // plus decoder/encoder method that is our real workhorse. Note that this is an internal // class, so our public classes cannot derive from this class. Because of this, all of the // GetBytes/Chars GetByte/CharCount wrapper methods are duplicated in all of our public // encodings, which currently include: // // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, & UnicodeEncoding // // So if you change the wrappers in this class, you must change the wrappers in the other classes // as well because they should have the same behavior. [Serializable] internal abstract class EncodingNLS : Encoding { protected EncodingNLS(int codePage) : base(codePage) { } // Returns the number of bytes required to encode a range of characters in // a character array. // // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe public override unsafe int GetByteCount(char[] chars, int index, int count) { // Validate input parameters if (chars == null) throw new ArgumentNullException("chars", SR.ArgumentNull_Array); if (index < 0 || count < 0) throw new ArgumentOutOfRangeException((index < 0 ? "index" : "count"), SR.ArgumentOutOfRange_NeedNonNegNum); if (chars.Length - index < count) throw new ArgumentOutOfRangeException("chars", SR.ArgumentOutOfRange_IndexCountBuffer); Contract.EndContractBlock(); // If no input, return 0, avoid fixed empty array problem if (count == 0) return 0; // Just call the pointer version fixed (char* pChars = chars) return GetByteCount(pChars + index, count, null); } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe public override unsafe int GetByteCount(String s) { // Validate input if (s==null) throw new ArgumentNullException("s"); Contract.EndContractBlock(); fixed (char* pChars = s) return GetByteCount(pChars, s.Length, null); } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding public override unsafe int GetByteCount(char* chars, int count) { // Validate Parameters if (chars == null) throw new ArgumentNullException("chars", SR.ArgumentNull_Array); if (count < 0) throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum); Contract.EndContractBlock(); // Call it with empty encoder return GetByteCount(chars, count, null); } // Parent method is safe. // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding public override unsafe int GetBytes(String s, int charIndex, int charCount, byte[] bytes, int byteIndex) { if (s == null || bytes == null) throw new ArgumentNullException((s == null ? "s" : "bytes"), SR.ArgumentNull_Array); if (charIndex < 0 || charCount < 0) throw new ArgumentOutOfRangeException((charIndex < 0 ? "charIndex" : "charCount"), SR.ArgumentOutOfRange_NeedNonNegNum); if (s.Length - charIndex < charCount) throw new ArgumentOutOfRangeException("s", SR.ArgumentOutOfRange_IndexCount); if (byteIndex < 0 || byteIndex > bytes.Length) throw new ArgumentOutOfRangeException("byteIndex", SR.ArgumentOutOfRange_Index); Contract.EndContractBlock(); int byteCount = bytes.Length - byteIndex; // Fixed doesn't like empty arrays if (bytes.Length == 0) bytes = new byte[1]; fixed (char* pChars = s) fixed (byte* pBytes = &bytes[0]) return GetBytes(pChars + charIndex, charCount, pBytes + byteIndex, byteCount, null); } // Encodes a range of characters in a character array into a range of bytes // in a byte array. An exception occurs if the byte array is not large // enough to hold the complete encoding of the characters. The // GetByteCount method can be used to determine the exact number of // bytes that will be produced for a given range of characters. // Alternatively, the GetMaxByteCount method can be used to // determine the maximum number of bytes that will be produced for a given // number of characters, regardless of the actual character values. // // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe public override unsafe int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex) { // Validate parameters if (chars == null || bytes == null) throw new ArgumentNullException((chars == null ? "chars" : "bytes"), SR.ArgumentNull_Array); if (charIndex < 0 || charCount < 0) throw new ArgumentOutOfRangeException((charIndex < 0 ? "charIndex" : "charCount"), SR.ArgumentOutOfRange_NeedNonNegNum); if (chars.Length - charIndex < charCount) throw new ArgumentOutOfRangeException("chars", SR.ArgumentOutOfRange_IndexCountBuffer); if (byteIndex < 0 || byteIndex > bytes.Length) throw new ArgumentOutOfRangeException("byteIndex", SR.ArgumentOutOfRange_Index); Contract.EndContractBlock(); // If nothing to encode return 0, avoid fixed problem if (charCount == 0) return 0; // Just call pointer version int byteCount = bytes.Length - byteIndex; // Fixed doesn't like empty arrays if (bytes.Length == 0) bytes = new byte[1]; fixed (char* pChars = chars) fixed (byte* pBytes = &bytes[0]) // Remember that byteCount is # to decode, not size of array. return GetBytes(pChars + charIndex, charCount, pBytes + byteIndex, byteCount, null); } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding public override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount) { // Validate Parameters if (bytes == null || chars == null) throw new ArgumentNullException(bytes == null ? "bytes" : "chars", SR.ArgumentNull_Array); if (charCount < 0 || byteCount < 0) throw new ArgumentOutOfRangeException((charCount < 0 ? "charCount" : "byteCount"), SR.ArgumentOutOfRange_NeedNonNegNum); Contract.EndContractBlock(); return GetBytes(chars, charCount, bytes, byteCount, null); } // Returns the number of characters produced by decoding a range of bytes // in a byte array. // // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe public override unsafe int GetCharCount(byte[] bytes, int index, int count) { // Validate Parameters if (bytes == null) throw new ArgumentNullException("bytes", SR.ArgumentNull_Array); if (index < 0 || count < 0) throw new ArgumentOutOfRangeException((index < 0 ? "index" : "count"), SR.ArgumentOutOfRange_NeedNonNegNum); if (bytes.Length - index < count) throw new ArgumentOutOfRangeException("bytes", SR.ArgumentOutOfRange_IndexCountBuffer); Contract.EndContractBlock(); // If no input just return 0, fixed doesn't like 0 length arrays if (count == 0) return 0; // Just call pointer version fixed (byte* pBytes = bytes) return GetCharCount(pBytes + index, count, null); } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding public override unsafe int GetCharCount(byte* bytes, int count) { // Validate Parameters if (bytes == null) throw new ArgumentNullException("bytes", SR.ArgumentNull_Array); if (count < 0) throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum); Contract.EndContractBlock(); return GetCharCount(bytes, count, null); } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe public override unsafe int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) { // Validate Parameters if (bytes == null || chars == null) throw new ArgumentNullException(bytes == null ? "bytes" : "chars", SR.ArgumentNull_Array); if (byteIndex < 0 || byteCount < 0) throw new ArgumentOutOfRangeException((byteIndex < 0 ? "byteIndex" : "byteCount"), SR.ArgumentOutOfRange_NeedNonNegNum); if ( bytes.Length - byteIndex < byteCount) throw new ArgumentOutOfRangeException("bytes", SR.ArgumentOutOfRange_IndexCountBuffer); if (charIndex < 0 || charIndex > chars.Length) throw new ArgumentOutOfRangeException("charIndex", SR.ArgumentOutOfRange_Index); Contract.EndContractBlock(); // If no input, return 0 & avoid fixed problem if (byteCount == 0) return 0; // Just call pointer version int charCount = chars.Length - charIndex; // Fixed doesn't like empty arrays if (chars.Length == 0) chars = new char[1]; fixed (byte* pBytes = bytes) fixed (char* pChars = &chars[0]) // Remember that charCount is # to decode, not size of array return GetChars(pBytes + byteIndex, byteCount, pChars + charIndex, charCount, null); } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding public unsafe override int GetChars(byte* bytes, int byteCount, char* chars, int charCount) { // Validate Parameters if (bytes == null || chars == null) throw new ArgumentNullException(bytes == null ? "bytes" : "chars", SR.ArgumentNull_Array); if (charCount < 0 || byteCount < 0) throw new ArgumentOutOfRangeException((charCount < 0 ? "charCount" : "byteCount"), SR.ArgumentOutOfRange_NeedNonNegNum); Contract.EndContractBlock(); return GetChars(bytes, byteCount, chars, charCount, null); } // Returns a string containing the decoded representation of a range of // bytes in a byte array. // // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe public override unsafe String GetString(byte[] bytes, int index, int count) { // Validate Parameters if (bytes == null) throw new ArgumentNullException("bytes", SR.ArgumentNull_Array); if (index < 0 || count < 0) throw new ArgumentOutOfRangeException((index < 0 ? "index" : "count"), SR.ArgumentOutOfRange_NeedNonNegNum); if (bytes.Length - index < count) throw new ArgumentOutOfRangeException("bytes", SR.ArgumentOutOfRange_IndexCountBuffer); Contract.EndContractBlock(); // Avoid problems with empty input buffer if (count == 0) return String.Empty; fixed (byte* pBytes = bytes) return String.CreateStringFromEncoding( pBytes + index, count, this); } public override Decoder GetDecoder() { return new DecoderNLS(this); } public override Encoder GetEncoder() { return new EncoderNLS(this); } } }
// // Copyright (c) 2004-2011 Jaroslaw Kowalski <[email protected]> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // #if !SILVERLIGHT namespace NLog.UnitTests.Targets { using System; using System.Collections.Generic; using System.Net; using System.Net.Mail; using NLog.Internal; using NLog.Layouts; using NLog.Targets; using Xunit; using System.IO; public class MailTargetTests : NLogTestBase { [Fact] public void SimpleEmailTest() { var mmt = new MockMailTarget { From = "[email protected]", To = "[email protected]", CC = "[email protected];[email protected]", Bcc = "[email protected];[email protected]", Subject = "Hello from NLog", SmtpServer = "server1", SmtpPort = 27, Body = "${level} ${logger} ${message}" }; mmt.Initialize(null); var exceptions = new List<Exception>(); mmt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "MyLogger", "log message 1").WithContinuation(exceptions.Add)); Assert.Null(exceptions[0]); Assert.Equal(1, mmt.CreatedMocks.Count); var mock = mmt.CreatedMocks[0]; Assert.Equal(1, mock.MessagesSent.Count); Assert.Equal("server1", mock.Host); Assert.Equal(27, mock.Port); Assert.False(mock.EnableSsl); Assert.Null(mock.Credentials); var msg = mock.MessagesSent[0]; Assert.Equal("Hello from NLog", msg.Subject); Assert.Equal("[email protected]", msg.From.Address); Assert.Equal(1, msg.To.Count); Assert.Equal("[email protected]", msg.To[0].Address); Assert.Equal(2, msg.CC.Count); Assert.Equal("[email protected]", msg.CC[0].Address); Assert.Equal("[email protected]", msg.CC[1].Address); Assert.Equal(2, msg.Bcc.Count); Assert.Equal("[email protected]", msg.Bcc[0].Address); Assert.Equal("[email protected]", msg.Bcc[1].Address); Assert.Equal(msg.Body, "Info MyLogger log message 1"); } [Fact] public void MailTarget_WithNewlineInSubject_SendsMail() { var mmt = new MockMailTarget { From = "[email protected]", To = "[email protected]", CC = "[email protected];[email protected]", Bcc = "[email protected];[email protected]", Subject = "Hello from NLog\n", SmtpServer = "server1", SmtpPort = 27, Body = "${level} ${logger} ${message}" }; mmt.Initialize(null); var exceptions = new List<Exception>(); mmt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "MyLogger", "log message 1").WithContinuation(exceptions.Add)); Assert.Null(exceptions[0]); Assert.Equal(1, mmt.CreatedMocks.Count); var mock = mmt.CreatedMocks[0]; Assert.Equal(1, mock.MessagesSent.Count); var msg = mock.MessagesSent[0]; } [Fact] public void NtlmEmailTest() { var mmt = new MockMailTarget { From = "[email protected]", To = "[email protected]", SmtpServer = "server1", SmtpAuthentication = SmtpAuthenticationMode.Ntlm, }; mmt.Initialize(null); var exceptions = new List<Exception>(); mmt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "MyLogger", "log message 1").WithContinuation(exceptions.Add)); Assert.Null(exceptions[0]); Assert.Equal(1, mmt.CreatedMocks.Count); var mock = mmt.CreatedMocks[0]; Assert.Equal(CredentialCache.DefaultNetworkCredentials, mock.Credentials); } [Fact] public void BasicAuthEmailTest() { try { var mmt = new MockMailTarget { From = "[email protected]", To = "[email protected]", SmtpServer = "server1", SmtpAuthentication = SmtpAuthenticationMode.Basic, SmtpUserName = "${mdc:username}", SmtpPassword = "${mdc:password}", }; mmt.Initialize(null); var exceptions = new List<Exception>(); MappedDiagnosticsContext.Set("username", "u1"); MappedDiagnosticsContext.Set("password", "p1"); mmt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "MyLogger", "log message 1").WithContinuation(exceptions.Add)); Assert.Null(exceptions[0]); Assert.Equal(1, mmt.CreatedMocks.Count); var mock = mmt.CreatedMocks[0]; var credential = mock.Credentials as NetworkCredential; Assert.NotNull(credential); Assert.Equal("u1", credential.UserName); Assert.Equal("p1", credential.Password); Assert.Equal(string.Empty, credential.Domain); } finally { MappedDiagnosticsContext.Clear(); } } [Fact] public void CsvLayoutTest() { var layout = new CsvLayout() { Delimiter = CsvColumnDelimiterMode.Semicolon, WithHeader = true, Columns = { new CsvColumn("name", "${logger}"), new CsvColumn("level", "${level}"), new CsvColumn("message", "${message}"), } }; var mmt = new MockMailTarget { From = "[email protected]", To = "[email protected]", SmtpServer = "server1", AddNewLines = true, Layout = layout, }; layout.Initialize(null); mmt.Initialize(null); var exceptions = new List<Exception>(); mmt.WriteAsyncLogEvents( new LogEventInfo(LogLevel.Info, "MyLogger1", "log message 1").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Debug, "MyLogger2", "log message 2").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Error, "MyLogger3", "log message 3").WithContinuation(exceptions.Add)); Assert.Null(exceptions[0]); Assert.Equal(1, mmt.CreatedMocks.Count); var mock = mmt.CreatedMocks[0]; Assert.Equal(1, mock.MessagesSent.Count); var msg = mock.MessagesSent[0]; string expectedBody = "name;level;message\nMyLogger1;Info;log message 1\nMyLogger2;Debug;log message 2\nMyLogger3;Error;log message 3\n"; Assert.Equal(expectedBody, msg.Body); } [Fact] public void PerMessageServer() { var mmt = new MockMailTarget { From = "[email protected]", To = "[email protected]", SmtpServer = "${logger}.mydomain.com", Body = "${message}", AddNewLines = true, }; mmt.Initialize(null); var exceptions = new List<Exception>(); mmt.WriteAsyncLogEvents( new LogEventInfo(LogLevel.Info, "MyLogger1", "log message 1").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Debug, "MyLogger2", "log message 2").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Error, "MyLogger1", "log message 3").WithContinuation(exceptions.Add)); Assert.Null(exceptions[0]); // 2 messages are sent, one using MyLogger1.mydomain.com, another using MyLogger2.mydomain.com Assert.Equal(2, mmt.CreatedMocks.Count); var mock1 = mmt.CreatedMocks[0]; Assert.Equal("MyLogger1.mydomain.com", mock1.Host); Assert.Equal(1, mock1.MessagesSent.Count); var msg1 = mock1.MessagesSent[0]; Assert.Equal("log message 1\nlog message 3\n", msg1.Body); var mock2 = mmt.CreatedMocks[1]; Assert.Equal("MyLogger2.mydomain.com", mock2.Host); Assert.Equal(1, mock2.MessagesSent.Count); var msg2 = mock2.MessagesSent[0]; Assert.Equal("log message 2\n", msg2.Body); } [Fact] public void ErrorHandlingTest() { var mmt = new MockMailTarget { From = "[email protected]", To = "[email protected]", SmtpServer = "${logger}", Body = "${message}", AddNewLines = true, }; mmt.Initialize(null); var exceptions = new List<Exception>(); var exceptions2 = new List<Exception>(); mmt.WriteAsyncLogEvents( new LogEventInfo(LogLevel.Info, "MyLogger1", "log message 1").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Debug, "ERROR", "log message 2").WithContinuation(exceptions2.Add), new LogEventInfo(LogLevel.Error, "MyLogger1", "log message 3").WithContinuation(exceptions.Add)); Assert.Null(exceptions[0]); Assert.Null(exceptions[1]); Assert.NotNull(exceptions2[0]); Assert.Equal("Some SMTP error.", exceptions2[0].Message); // 2 messages are sent, one using MyLogger1.mydomain.com, another using MyLogger2.mydomain.com Assert.Equal(2, mmt.CreatedMocks.Count); var mock1 = mmt.CreatedMocks[0]; Assert.Equal("MyLogger1", mock1.Host); Assert.Equal(1, mock1.MessagesSent.Count); var msg1 = mock1.MessagesSent[0]; Assert.Equal("log message 1\nlog message 3\n", msg1.Body); var mock2 = mmt.CreatedMocks[1]; Assert.Equal("ERROR", mock2.Host); Assert.Equal(1, mock2.MessagesSent.Count); var msg2 = mock2.MessagesSent[0]; Assert.Equal("log message 2\n", msg2.Body); } /// <summary> /// Tests that it is possible to user different email address for each log message, /// for example by using ${logger}, ${event-context} or any other layout renderer. /// </summary> [Fact] public void PerMessageAddress() { var mmt = new MockMailTarget { From = "[email protected]", To = "${logger}@foo.com", Body = "${message}", SmtpServer = "server1.mydomain.com", AddNewLines = true, }; mmt.Initialize(null); var exceptions = new List<Exception>(); mmt.WriteAsyncLogEvents( new LogEventInfo(LogLevel.Info, "MyLogger1", "log message 1").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Debug, "MyLogger2", "log message 2").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Error, "MyLogger1", "log message 3").WithContinuation(exceptions.Add)); Assert.Null(exceptions[0]); // 2 messages are sent, one using MyLogger1.mydomain.com, another using MyLogger2.mydomain.com Assert.Equal(2, mmt.CreatedMocks.Count); var mock1 = mmt.CreatedMocks[0]; Assert.Equal(1, mock1.MessagesSent.Count); var msg1 = mock1.MessagesSent[0]; Assert.Equal("[email protected]", msg1.To[0].Address); Assert.Equal("log message 1\nlog message 3\n", msg1.Body); var mock2 = mmt.CreatedMocks[1]; Assert.Equal(1, mock2.MessagesSent.Count); var msg2 = mock2.MessagesSent[0]; Assert.Equal("[email protected]", msg2.To[0].Address); Assert.Equal("log message 2\n", msg2.Body); } [Fact] public void CustomHeaderAndFooter() { var mmt = new MockMailTarget { From = "[email protected]", To = "[email protected]", SmtpServer = "server1", AddNewLines = true, Layout = "${message}", Header = "First event: ${logger}", Footer = "Last event: ${logger}", }; mmt.Initialize(null); var exceptions = new List<Exception>(); mmt.WriteAsyncLogEvents( new LogEventInfo(LogLevel.Info, "MyLogger1", "log message 1").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Debug, "MyLogger2", "log message 2").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Error, "MyLogger3", "log message 3").WithContinuation(exceptions.Add)); Assert.Null(exceptions[0]); Assert.Equal(1, mmt.CreatedMocks.Count); var mock = mmt.CreatedMocks[0]; Assert.Equal(1, mock.MessagesSent.Count); var msg = mock.MessagesSent[0]; string expectedBody = "First event: MyLogger1\nlog message 1\nlog message 2\nlog message 3\nLast event: MyLogger3\n"; Assert.Equal(expectedBody, msg.Body); } [Fact] public void DefaultSmtpClientTest() { var mailTarget = new MailTarget(); var client = mailTarget.CreateSmtpClient(); Assert.IsType(typeof(MySmtpClient), client); } [Fact] public void ReplaceNewlinesWithBreakInHtmlMail() { var mmt = new MockMailTarget { From = "[email protected]", To = "[email protected]", Subject = "Hello from NLog", SmtpServer = "server1", Body = "${level}${newline}${logger}${newline}${message}", Html = true, ReplaceNewlineWithBrTagInHtml = true }; mmt.Initialize(null); var exceptions = new List<Exception>(); mmt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "MyLogger", "log message 1").WithContinuation(exceptions.Add)); var messageSent = mmt.CreatedMocks[0].MessagesSent[0]; Assert.True(messageSent.IsBodyHtml); var lines = messageSent.Body.Split(new[] { "<br/>" }, StringSplitOptions.RemoveEmptyEntries); Assert.True(lines.Length == 3); } [Fact] public void NoReplaceNewlinesWithBreakInHtmlMail() { var mmt = new MockMailTarget { From = "[email protected]", To = "[email protected]", Subject = "Hello from NLog", SmtpServer = "server1", Body = "${level}${newline}${logger}${newline}${message}", Html = true, ReplaceNewlineWithBrTagInHtml = false }; mmt.Initialize(null); var exceptions = new List<Exception>(); mmt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "MyLogger", "log message 1").WithContinuation(exceptions.Add)); var messageSent = mmt.CreatedMocks[0].MessagesSent[0]; Assert.True(messageSent.IsBodyHtml); var lines = messageSent.Body.Split(new[] {Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries); Assert.True(lines.Length == 3); } [Fact] public void MailTarget_WithPriority_SendsMailWithPrioritySet() { var mmt = new MockMailTarget { From = "[email protected]", To = "[email protected]", Subject = "Hello from NLog", SmtpServer = "server1", Priority = "high" }; mmt.Initialize(null); mmt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "MyLogger", "log message 1").WithContinuation(_ => { })); var messageSent = mmt.CreatedMocks[0].MessagesSent[0]; Assert.Equal(MailPriority.High, messageSent.Priority); } [Fact] public void MailTarget_WithoutPriority_SendsMailWithNormalPriority() { var mmt = new MockMailTarget { From = "[email protected]", To = "[email protected]", Subject = "Hello from NLog", SmtpServer = "server1", }; mmt.Initialize(null); mmt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "MyLogger", "log message 1").WithContinuation(_ => { })); var messageSent = mmt.CreatedMocks[0].MessagesSent[0]; Assert.Equal(MailPriority.Normal, messageSent.Priority); } [Fact] public void MailTarget_WithInvalidPriority_SendsMailWithNormalPriority() { var mmt = new MockMailTarget { From = "[email protected]", To = "[email protected]", Subject = "Hello from NLog", SmtpServer = "server1", Priority = "invalidPriority" }; mmt.Initialize(null); mmt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "MyLogger", "log message 1").WithContinuation(_ => { })); var messageSent = mmt.CreatedMocks[0].MessagesSent[0]; Assert.Equal(MailPriority.Normal, messageSent.Priority); } [Fact] public void MailTarget_WithValidToAndEmptyCC_SendsMail() { var mmt = new MockMailTarget { From = "[email protected]", To = "[email protected]", CC = "", Subject = "Hello from NLog", SmtpServer = "server1", SmtpPort = 27, Body = "${level} ${logger} ${message}", }; mmt.Initialize(null); var exceptions = new List<Exception>(); mmt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "MyLogger", "log message 1").WithContinuation(exceptions.Add)); Assert.Null(exceptions[0]); Assert.Equal(1, mmt.CreatedMocks.Count); Assert.Equal(1, mmt.CreatedMocks[0].MessagesSent.Count); } [Fact] public void MailTarget_WithValidToAndEmptyBcc_SendsMail() { var mmt = new MockMailTarget { From = "[email protected]", To = "[email protected]", Bcc = "", Subject = "Hello from NLog", SmtpServer = "server1", SmtpPort = 27, Body = "${level} ${logger} ${message}", }; mmt.Initialize(null); var exceptions = new List<Exception>(); mmt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "MyLogger", "log message 1").WithContinuation(exceptions.Add)); Assert.Null(exceptions[0]); Assert.Equal(1, mmt.CreatedMocks.Count); Assert.Equal(1, mmt.CreatedMocks[0].MessagesSent.Count); } [Fact] public void MailTarget_WithEmptyTo_ThrowsNLogRuntimeException() { var mmt = new MockMailTarget { From = "[email protected]", To = "", Subject = "Hello from NLog", SmtpServer = "server1", SmtpPort = 27, Body = "${level} ${logger} ${message}", }; mmt.Initialize(null); var exceptions = new List<Exception>(); mmt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "MyLogger", "log message 1").WithContinuation(exceptions.Add)); Assert.NotNull(exceptions[0]); Assert.IsType<NLogRuntimeException>(exceptions[0]); } [Fact] public void MailTarget_WithEmptyFrom_ThrowsNLogRuntimeException() { var mmt = new MockMailTarget { From = "", To = "[email protected]", Subject = "Hello from NLog", SmtpServer = "server1", SmtpPort = 27, Body = "${level} ${logger} ${message}" }; mmt.Initialize(null); var exceptions = new List<Exception>(); mmt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "MyLogger", "log message 1").WithContinuation(exceptions.Add)); Assert.NotNull(exceptions[0]); Assert.IsType<NLogRuntimeException>(exceptions[0]); } [Fact] public void MailTarget_WithEmptySmtpServer_ThrowsNLogRuntimeException() { var mmt = new MockMailTarget { From = "[email protected]", To = "[email protected]", Subject = "Hello from NLog", SmtpServer = "", SmtpPort = 27, Body = "${level} ${logger} ${message}" }; mmt.Initialize(null); var exceptions = new List<Exception>(); mmt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "MyLogger", "log message 1").WithContinuation(exceptions.Add)); Assert.NotNull(exceptions[0]); Assert.IsType<NLogRuntimeException>(exceptions[0]); } [Fact] public void MailTargetInitialize_WithoutSpecifiedTo_ThrowsConfigException() { var mmt = new MockMailTarget { From = "[email protected]", Subject = "Hello from NLog", SmtpServer = "server1", SmtpPort = 27, Body = "${level} ${logger} ${message}" }; Assert.Throws<NLogConfigurationException>(() => mmt.Initialize(null)); } [Fact] public void MailTargetInitialize_WithoutSpecifiedFrom_ThrowsConfigException() { var mmt = new MockMailTarget { To = "[email protected]", Subject = "Hello from NLog", SmtpServer = "server1", SmtpPort = 27, Body = "${level} ${logger} ${message}" }; Assert.Throws<NLogConfigurationException>(() => mmt.Initialize(null)); } [Fact] public void MailTargetInitialize_WithoutSpecifiedSmtpServer_should_not_ThrowsConfigException() { var mmt = new MockMailTarget { From = "[email protected]", To = "[email protected]", Subject = "Hello from NLog", SmtpPort = 27, Body = "${level} ${logger} ${message}", UseSystemNetMailSettings = true }; } [Fact] public void MailTargetInitialize_WithoutSpecifiedSmtpServer_ThrowsConfigException_if_UseSystemNetMailSettings() { var mmt = new MockMailTarget { From = "[email protected]", To = "[email protected]", Subject = "Hello from NLog", SmtpPort = 27, Body = "${level} ${logger} ${message}", UseSystemNetMailSettings = false }; Assert.Throws<NLogConfigurationException>(() => mmt.Initialize(null)); } /// <summary> /// Test for https://github.com/NLog/NLog/issues/690 /// </summary> [Fact] public void MailTarget_UseSystemNetMailSettings_False_Override_ThrowsNLogRuntimeException_if_DeliveryMethodNotSpecified() { var inConfigVal = @"C:\config"; var mmt = new MockMailTarget(inConfigVal) { From = "[email protected]", To = "[email protected]", Subject = "Hello from NLog", SmtpPort = 27, Body = "${level} ${logger} ${message}", PickupDirectoryLocation = @"C:\TEMP", UseSystemNetMailSettings = false }; Assert.Throws<NLogRuntimeException>(() => mmt.ConfigureMailClient()); } /// <summary> /// Test for https://github.com/NLog/NLog/issues/690 /// </summary> [Fact] public void MailTarget_UseSystemNetMailSettings_False_Override_DeliveryMethod_SpecifiedDeliveryMethod() { var inConfigVal = @"C:\config"; var mmt = new MockMailTarget(inConfigVal) { From = "[email protected]", To = "[email protected]", Subject = "Hello from NLog", SmtpPort = 27, Body = "${level} ${logger} ${message}", PickupDirectoryLocation = @"C:\TEMP", UseSystemNetMailSettings = false, DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory }; mmt.ConfigureMailClient(); Assert.NotEqual(mmt.PickupDirectoryLocation, inConfigVal); } [Fact] public void MailTarget_UseSystemNetMailSettings_True() { var inConfigVal = @"C:\config"; var mmt = new MockMailTarget(inConfigVal) { From = "[email protected]", To = "[email protected]", Subject = "Hello from NLog", Body = "${level} ${logger} ${message}", UseSystemNetMailSettings = true }; mmt.ConfigureMailClient(); Assert.Equal(mmt.SmtpClientPickUpDirectory, inConfigVal); } [Fact] public void MailTarget_UseSystemNetMailSettings_True_WithVirtualPath() { var inConfigVal = @"~/App_Data/Mail"; var mmt = new MockMailTarget(inConfigVal) { From = "[email protected]", To = "[email protected]", Subject = "Hello from NLog", Body = "${level} ${logger} ${message}", UseSystemNetMailSettings = false, PickupDirectoryLocation = inConfigVal, DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory }; mmt.ConfigureMailClient(); Assert.NotEqual(inConfigVal, mmt.SmtpClientPickUpDirectory); var separator = Path.DirectorySeparatorChar; Assert.Contains(string.Format("{0}App_Data{0}Mail", separator), mmt.SmtpClientPickUpDirectory); } [Fact] public void MailTarget_WithoutSubject_SendsMessageWithDefaultSubject() { var mmt = new MockMailTarget { From = "[email protected]", To = "[email protected]", SmtpServer = "server1", SmtpPort = 27, Body = "${level} ${logger} ${message}" }; mmt.Initialize(null); var exceptions = new List<Exception>(); mmt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "MyLogger", "log message 1").WithContinuation(exceptions.Add)); Assert.Null(exceptions[0]); Assert.Equal(1, mmt.CreatedMocks.Count); var mock = mmt.CreatedMocks[0]; Assert.Equal(1, mock.MessagesSent.Count); Assert.Equal(string.Format("Message from NLog on {0}", Environment.MachineName), mock.MessagesSent[0].Subject); } public class MockSmtpClient : ISmtpClient { public MockSmtpClient() { this.MessagesSent = new List<MailMessage>(); } public SmtpDeliveryMethod DeliveryMethod { get; set; } public string Host { get; set; } public int Port { get; set; } public int Timeout { get; set; } public string PickupDirectoryLocation { get; set; } public ICredentialsByHost Credentials { get; set; } public bool EnableSsl { get; set; } public List<MailMessage> MessagesSent { get; private set; } public void Send(MailMessage msg) { if (string.IsNullOrEmpty(this.Host) && string.IsNullOrEmpty(this.PickupDirectoryLocation)) { throw new InvalidOperationException("[Host/Pickup directory] is null or empty."); } this.MessagesSent.Add(msg); if (Host == "ERROR") { throw new InvalidOperationException("Some SMTP error."); } } public void Dispose() { } } public class MockMailTarget : MailTarget { private const string RequiredPropertyIsEmptyFormat = "After the processing of the MailTarget's '{0}' property it appears to be empty. The email message will not be sent."; public MockSmtpClient Client; public MockMailTarget() { Client = new MockSmtpClient(); } public MockMailTarget(string configPickUpdirectory) { Client = new MockSmtpClient { PickupDirectoryLocation = configPickUpdirectory }; } public List<MockSmtpClient> CreatedMocks = new List<MockSmtpClient>(); internal override ISmtpClient CreateSmtpClient() { var client = new MockSmtpClient(); CreatedMocks.Add(client); return client; } public void ConfigureMailClient() { if (UseSystemNetMailSettings) return; if (this.SmtpServer == null && string.IsNullOrEmpty(this.PickupDirectoryLocation)) { throw new NLogRuntimeException(string.Format(RequiredPropertyIsEmptyFormat, "SmtpServer/PickupDirectoryLocation")); } if (this.DeliveryMethod == SmtpDeliveryMethod.Network && this.SmtpServer == null) { throw new NLogRuntimeException(string.Format(RequiredPropertyIsEmptyFormat, "SmtpServer")); } if (this.DeliveryMethod == SmtpDeliveryMethod.SpecifiedPickupDirectory && string.IsNullOrEmpty(this.PickupDirectoryLocation)) { throw new NLogRuntimeException(string.Format(RequiredPropertyIsEmptyFormat, "PickupDirectoryLocation")); } if (!string.IsNullOrEmpty(this.PickupDirectoryLocation) && this.DeliveryMethod == SmtpDeliveryMethod.SpecifiedPickupDirectory) { Client.PickupDirectoryLocation = ConvertDirectoryLocation(PickupDirectoryLocation); } Client.DeliveryMethod = this.DeliveryMethod; } public string SmtpClientPickUpDirectory { get { return Client.PickupDirectoryLocation; } } } } } #endif
/* * * (c) Copyright Ascensio System Limited 2010-2021 * * 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 ASC.Common.Caching; namespace ASC.Core.Caching { public class CachedSubscriptionService : ISubscriptionService { private readonly ISubscriptionService service; private readonly ICache cache; private readonly ICacheNotify notify; public TimeSpan CacheExpiration { get; set; } public CachedSubscriptionService(ISubscriptionService service) { if (service == null) throw new ArgumentNullException("service"); this.service = service; cache = AscCache.Memory; notify = AscCache.Notify; CacheExpiration = TimeSpan.FromMinutes(5); notify.Subscribe<SubscriptionRecord>((s, a) => { var store = GetSubsciptionsStore(s.Tenant, s.SourceId, s.ActionId); lock (store) { if (a == CacheNotifyAction.InsertOrUpdate) { store.SaveSubscription(s); } else if (a == CacheNotifyAction.Remove) { if (s.ObjectId == null) { store.RemoveSubscriptions(); } else { store.RemoveSubscriptions(s.ObjectId); } } } }); notify.Subscribe<SubscriptionMethod>((m, a) => { var store = GetSubsciptionsStore(m.Tenant, m.SourceId, m.ActionId); lock (store) { store.SetSubscriptionMethod(m); } }); } public IEnumerable<SubscriptionRecord> GetSubscriptions(int tenant, string sourceId, string actionId) { var store = GetSubsciptionsStore(tenant, sourceId, actionId); lock (store) { return store.GetSubscriptions(); } } public IEnumerable<SubscriptionRecord> GetSubscriptions(int tenant, string sourceId, string actionId, string recipientId, string objectId) { var store = GetSubsciptionsStore(tenant, sourceId, actionId); lock (store) { return store.GetSubscriptions(recipientId, objectId); } } public string[] GetRecipients(int tenant, string sourceID, string actionID, string objectID) { return service.GetRecipients(tenant, sourceID, actionID, objectID); } public string[] GetSubscriptions(int tenant, string sourceId, string actionId, string recipientId, bool checkSubscribe) { return service.GetSubscriptions(tenant, sourceId, actionId, recipientId, checkSubscribe); } public SubscriptionRecord GetSubscription(int tenant, string sourceId, string actionId, string recipientId, string objectId) { var store = GetSubsciptionsStore(tenant, sourceId, actionId); lock (store) { return store.GetSubscription(recipientId, objectId); } } public void SaveSubscription(SubscriptionRecord s) { service.SaveSubscription(s); notify.Publish(s, CacheNotifyAction.InsertOrUpdate); } public void RemoveSubscriptions(int tenant, string sourceId, string actionId) { service.RemoveSubscriptions(tenant, sourceId, actionId); notify.Publish(new SubscriptionRecord { Tenant = tenant, SourceId = sourceId, ActionId = actionId }, CacheNotifyAction.Remove); } public void RemoveSubscriptions(int tenant, string sourceId, string actionId, string objectId) { service.RemoveSubscriptions(tenant, sourceId, actionId, objectId); notify.Publish(new SubscriptionRecord { Tenant = tenant, SourceId = sourceId, ActionId = actionId, ObjectId = objectId }, CacheNotifyAction.Remove); } public IEnumerable<SubscriptionMethod> GetSubscriptionMethods(int tenant, string sourceId, string actionId, string recipientId) { var store = GetSubsciptionsStore(tenant, sourceId, actionId); lock (store) { return store.GetSubscriptionMethods(recipientId); } } public void SetSubscriptionMethod(SubscriptionMethod m) { service.SetSubscriptionMethod(m); notify.Publish(m, CacheNotifyAction.Any); } private SubsciptionsStore GetSubsciptionsStore(int tenant, string sourceId, string actionId) { var key = string.Format("sub/{0}/{1}/{2}", tenant, sourceId, actionId); var store = cache.Get<SubsciptionsStore>(key); if (store == null) { var records = service.GetSubscriptions(tenant, sourceId, actionId); var methods = service.GetSubscriptionMethods(tenant, sourceId, actionId, null); cache.Insert(key, store = new SubsciptionsStore(records, methods), DateTime.UtcNow.Add(CacheExpiration)); } return store; } public bool IsUnsubscribe(int tenant, string sourceId, string actionId, string recipientId, string objectId) { return service.IsUnsubscribe(tenant, sourceId, actionId, recipientId, objectId); } private class SubsciptionsStore { private readonly List<SubscriptionRecord> records; private IDictionary<string, List<SubscriptionRecord>> recordsByRec; private IDictionary<string, List<SubscriptionRecord>> recordsByObj; private readonly List<SubscriptionMethod> methods; private IDictionary<string, List<SubscriptionMethod>> methodsByRec; public SubsciptionsStore(IEnumerable<SubscriptionRecord> records, IEnumerable<SubscriptionMethod> methods) { this.records = records.ToList(); this.methods = methods.ToList(); BuildSubscriptionsIndex(records); BuildMethodsIndex(methods); } public IEnumerable<SubscriptionRecord> GetSubscriptions() { return records.ToList(); } public IEnumerable<SubscriptionRecord> GetSubscriptions(string recipientId, string objectId) { return recipientId != null ? recordsByRec.ContainsKey(recipientId) ? recordsByRec[recipientId].ToList() : new List<SubscriptionRecord>() : recordsByObj.ContainsKey(objectId ?? string.Empty) ? recordsByObj[objectId ?? string.Empty].ToList() : new List<SubscriptionRecord>(); } public SubscriptionRecord GetSubscription(string recipientId, string objectId) { return recordsByRec.ContainsKey(recipientId) ? recordsByRec[recipientId].Where(s => s.ObjectId == objectId).FirstOrDefault() : null; } public void SaveSubscription(SubscriptionRecord s) { var old = GetSubscription(s.RecipientId, s.ObjectId); if (old != null) { old.Subscribed = s.Subscribed; } else { records.Add(s); BuildSubscriptionsIndex(records); } } public void RemoveSubscriptions() { records.Clear(); BuildSubscriptionsIndex(records); } public void RemoveSubscriptions(string objectId) { records.RemoveAll(s => s.ObjectId == objectId); BuildSubscriptionsIndex(records); } public IEnumerable<SubscriptionMethod> GetSubscriptionMethods(string recipientId) { return string.IsNullOrEmpty(recipientId) ? methods.ToList() : methodsByRec.ContainsKey(recipientId) ? methodsByRec[recipientId].ToList() : new List<SubscriptionMethod>(); } public void SetSubscriptionMethod(SubscriptionMethod m) { methods.RemoveAll(r => r.Tenant == m.Tenant && r.SourceId == m.SourceId && r.ActionId == m.ActionId && r.RecipientId == m.RecipientId); if (m.Methods != null && 0 < m.Methods.Length) { methods.Add(m); } BuildMethodsIndex(methods); } private void BuildSubscriptionsIndex(IEnumerable<SubscriptionRecord> records) { recordsByRec = records.GroupBy(r => r.RecipientId).ToDictionary(g => g.Key, g => g.ToList()); recordsByObj = records.GroupBy(r => r.ObjectId ?? string.Empty).ToDictionary(g => g.Key, g => g.ToList()); } private void BuildMethodsIndex(IEnumerable<SubscriptionMethod> methods) { methodsByRec = methods.GroupBy(r => r.RecipientId).ToDictionary(g => g.Key, g => g.ToList()); } } } }
#if (UNITY_WINRT || UNITY_WP_8_1) && !UNITY_EDITOR && !UNITY_WP8 #region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Runtime.Serialization.Formatters; using PlayFab.Json.Converters; using PlayFab.Json.Serialization; using PlayFab.Json.Utilities; using System.Runtime.Serialization; using ErrorEventArgs=PlayFab.Json.Serialization.ErrorEventArgs; namespace PlayFab.Json { /// <summary> /// Serializes and deserializes objects into and from the JSON format. /// The <see cref="JsonSerializer"/> enables you to control how objects are encoded into JSON. /// </summary> public class JsonSerializer { #region Properties_binder internal TypeNameHandling _typeNameHandling; internal FormatterAssemblyStyle _typeNameAssemblyFormat; internal PreserveReferencesHandling _preserveReferencesHandling; internal ReferenceLoopHandling _referenceLoopHandling; internal MissingMemberHandling _missingMemberHandling; internal ObjectCreationHandling _objectCreationHandling; internal NullValueHandling _nullValueHandling; internal DefaultValueHandling _defaultValueHandling; internal ConstructorHandling _constructorHandling; internal JsonConverterCollection _converters; internal IContractResolver _contractResolver; internal ITraceWriter _traceWriter; internal SerializationBinder _binder; internal StreamingContext _context; private IReferenceResolver _referenceResolver; private Formatting? _formatting; private DateFormatHandling? _dateFormatHandling; private DateTimeZoneHandling? _dateTimeZoneHandling; private DateParseHandling? _dateParseHandling; private FloatFormatHandling? _floatFormatHandling; private FloatParseHandling? _floatParseHandling; private StringEscapeHandling? _stringEscapeHandling; private CultureInfo _culture; private int? _maxDepth; private bool _maxDepthSet; private bool? _checkAdditionalContent; private string _dateFormatString; private bool _dateFormatStringSet; /// <summary> /// Occurs when the <see cref="JsonSerializer"/> errors during serialization and deserialization. /// </summary> public virtual event EventHandler<ErrorEventArgs> Error; /// <summary> /// Gets or sets the <see cref="IReferenceResolver"/> used by the serializer when resolving references. /// </summary> public virtual IReferenceResolver ReferenceResolver { get { return GetReferenceResolver(); } set { if (value == null) throw new ArgumentNullException("value", "Reference resolver cannot be null."); _referenceResolver = value; } } /// <summary> /// Gets or sets the <see cref="SerializationBinder"/> used by the serializer when resolving type names. /// </summary> public virtual SerializationBinder Binder { get { return _binder; } set { if (value == null) throw new ArgumentNullException("value", "Serialization binder cannot be null."); _binder = value; } } /// <summary> /// Gets or sets the <see cref="ITraceWriter"/> used by the serializer when writing trace messages. /// </summary> /// <value>The trace writer.</value> public virtual ITraceWriter TraceWriter { get { return _traceWriter; } set { _traceWriter = value; } } /// <summary> /// Gets or sets how type name writing and reading is handled by the serializer. /// </summary> public virtual TypeNameHandling TypeNameHandling { get { return _typeNameHandling; } set { if (value < TypeNameHandling.None || value > TypeNameHandling.Auto) throw new ArgumentOutOfRangeException("value"); _typeNameHandling = value; } } /// <summary> /// Gets or sets how a type name assembly is written and resolved by the serializer. /// </summary> /// <value>The type name assembly format.</value> public virtual FormatterAssemblyStyle TypeNameAssemblyFormat { get { return _typeNameAssemblyFormat; } set { if (value < FormatterAssemblyStyle.Simple || value > FormatterAssemblyStyle.Full) throw new ArgumentOutOfRangeException("value"); _typeNameAssemblyFormat = value; } } /// <summary> /// Gets or sets how object references are preserved by the serializer. /// </summary> public virtual PreserveReferencesHandling PreserveReferencesHandling { get { return _preserveReferencesHandling; } set { if (value < PreserveReferencesHandling.None || value > PreserveReferencesHandling.All) throw new ArgumentOutOfRangeException("value"); _preserveReferencesHandling = value; } } /// <summary> /// Get or set how reference loops (e.g. a class referencing itself) is handled. /// </summary> public virtual ReferenceLoopHandling ReferenceLoopHandling { get { return _referenceLoopHandling; } set { if (value < ReferenceLoopHandling.Error || value > ReferenceLoopHandling.Serialize) throw new ArgumentOutOfRangeException("value"); _referenceLoopHandling = value; } } /// <summary> /// Get or set how missing members (e.g. JSON contains a property that isn't a member on the object) are handled during deserialization. /// </summary> public virtual MissingMemberHandling MissingMemberHandling { get { return _missingMemberHandling; } set { if (value < MissingMemberHandling.Ignore || value > MissingMemberHandling.Error) throw new ArgumentOutOfRangeException("value"); _missingMemberHandling = value; } } /// <summary> /// Get or set how null values are handled during serialization and deserialization. /// </summary> public virtual NullValueHandling NullValueHandling { get { return _nullValueHandling; } set { if (value < NullValueHandling.Include || value > NullValueHandling.Ignore) throw new ArgumentOutOfRangeException("value"); _nullValueHandling = value; } } /// <summary> /// Get or set how null default are handled during serialization and deserialization. /// </summary> public virtual DefaultValueHandling DefaultValueHandling { get { return _defaultValueHandling; } set { if (value < DefaultValueHandling.Include || value > DefaultValueHandling.IgnoreAndPopulate) throw new ArgumentOutOfRangeException("value"); _defaultValueHandling = value; } } /// <summary> /// Gets or sets how objects are created during deserialization. /// </summary> /// <value>The object creation handling.</value> public virtual ObjectCreationHandling ObjectCreationHandling { get { return _objectCreationHandling; } set { if (value < ObjectCreationHandling.Auto || value > ObjectCreationHandling.Replace) throw new ArgumentOutOfRangeException("value"); _objectCreationHandling = value; } } /// <summary> /// Gets or sets how constructors are used during deserialization. /// </summary> /// <value>The constructor handling.</value> public virtual ConstructorHandling ConstructorHandling { get { return _constructorHandling; } set { if (value < ConstructorHandling.Default || value > ConstructorHandling.AllowNonPublicDefaultConstructor) throw new ArgumentOutOfRangeException("value"); _constructorHandling = value; } } /// <summary> /// Gets a collection <see cref="JsonConverter"/> that will be used during serialization. /// </summary> /// <value>Collection <see cref="JsonConverter"/> that will be used during serialization.</value> public virtual JsonConverterCollection Converters { get { if (_converters == null) _converters = new JsonConverterCollection(); return _converters; } } /// <summary> /// Gets or sets the contract resolver used by the serializer when /// serializing .NET objects to JSON and vice versa. /// </summary> public virtual IContractResolver ContractResolver { get { return _contractResolver; } set { _contractResolver = value ?? DefaultContractResolver.Instance; } } /// <summary> /// Gets or sets the <see cref="StreamingContext"/> used by the serializer when invoking serialization callback methods. /// </summary> /// <value>The context.</value> public virtual StreamingContext Context { get { return _context; } set { _context = value; } } /// <summary> /// Indicates how JSON text output is formatted. /// </summary> public virtual Formatting Formatting { get { return _formatting ?? JsonSerializerSettings.DefaultFormatting; } set { _formatting = value; } } /// <summary> /// Get or set how dates are written to JSON text. /// </summary> public virtual DateFormatHandling DateFormatHandling { get { return _dateFormatHandling ?? JsonSerializerSettings.DefaultDateFormatHandling; } set { _dateFormatHandling = value; } } /// <summary> /// Get or set how <see cref="DateTime"/> time zones are handling during serialization and deserialization. /// </summary> public virtual DateTimeZoneHandling DateTimeZoneHandling { get { return _dateTimeZoneHandling ?? JsonSerializerSettings.DefaultDateTimeZoneHandling; } set { _dateTimeZoneHandling = value; } } /// <summary> /// Get or set how date formatted strings, e.g. "\/Date(1198908717056)\/" and "2012-03-21T05:40Z", are parsed when reading JSON. /// </summary> public virtual DateParseHandling DateParseHandling { get { return _dateParseHandling ?? JsonSerializerSettings.DefaultDateParseHandling; } set { _dateParseHandling = value; } } /// <summary> /// Get or set how floating point numbers, e.g. 1.0 and 9.9, are parsed when reading JSON text. /// </summary> public virtual FloatParseHandling FloatParseHandling { get { return _floatParseHandling ?? JsonSerializerSettings.DefaultFloatParseHandling; } set { _floatParseHandling = value; } } /// <summary> /// Get or set how special floating point numbers, e.g. <see cref="F:System.Double.NaN"/>, /// <see cref="F:System.Double.PositiveInfinity"/> and <see cref="F:System.Double.NegativeInfinity"/>, /// are written as JSON text. /// </summary> public virtual FloatFormatHandling FloatFormatHandling { get { return _floatFormatHandling ?? JsonSerializerSettings.DefaultFloatFormatHandling; } set { _floatFormatHandling = value; } } /// <summary> /// Get or set how strings are escaped when writing JSON text. /// </summary> public virtual StringEscapeHandling StringEscapeHandling { get { return _stringEscapeHandling ?? JsonSerializerSettings.DefaultStringEscapeHandling; } set { _stringEscapeHandling = value; } } /// <summary> /// Get or set how <see cref="DateTime"/> and <see cref="DateTimeOffset"/> values are formatting when writing JSON text. /// </summary> public virtual string DateFormatString { get { return _dateFormatString ?? JsonSerializerSettings.DefaultDateFormatString; } set { _dateFormatString = value; _dateFormatStringSet = true; } } /// <summary> /// Gets or sets the culture used when reading JSON. Defaults to <see cref="CultureInfo.InvariantCulture"/>. /// </summary> public virtual CultureInfo Culture { get { return _culture ?? JsonSerializerSettings.DefaultCulture; } set { _culture = value; } } /// <summary> /// Gets or sets the maximum depth allowed when reading JSON. Reading past this depth will throw a <see cref="JsonReaderException"/>. /// </summary> public virtual int? MaxDepth { get { return _maxDepth; } set { if (value <= 0) throw new ArgumentException("Value must be positive.", "value"); _maxDepth = value; _maxDepthSet = true; } } /// <summary> /// Gets a value indicating whether there will be a check for additional JSON content after deserializing an object. /// </summary> /// <value> /// <c>true</c> if there will be a check for additional JSON content after deserializing an object; otherwise, <c>false</c>. /// </value> public virtual bool CheckAdditionalContent { get { return _checkAdditionalContent ?? JsonSerializerSettings.DefaultCheckAdditionalContent; } set { _checkAdditionalContent = value; } } internal bool IsCheckAdditionalContentSet() { return (_checkAdditionalContent != null); } #endregion /// <summary> /// Initializes a new instance of the <see cref="JsonSerializer"/> class. /// </summary> public JsonSerializer() { _referenceLoopHandling = JsonSerializerSettings.DefaultReferenceLoopHandling; _missingMemberHandling = JsonSerializerSettings.DefaultMissingMemberHandling; _nullValueHandling = JsonSerializerSettings.DefaultNullValueHandling; _defaultValueHandling = JsonSerializerSettings.DefaultDefaultValueHandling; _objectCreationHandling = JsonSerializerSettings.DefaultObjectCreationHandling; _preserveReferencesHandling = JsonSerializerSettings.DefaultPreserveReferencesHandling; _constructorHandling = JsonSerializerSettings.DefaultConstructorHandling; _typeNameHandling = JsonSerializerSettings.DefaultTypeNameHandling; _context = JsonSerializerSettings.DefaultContext; _binder = DefaultSerializationBinder.Instance; _culture = JsonSerializerSettings.DefaultCulture; _contractResolver = DefaultContractResolver.Instance; } /// <summary> /// Creates a new <see cref="JsonSerializer"/> instance. /// The <see cref="JsonSerializer"/> will not use default settings. /// </summary> /// <returns> /// A new <see cref="JsonSerializer"/> instance. /// The <see cref="JsonSerializer"/> will not use default settings. /// </returns> public static JsonSerializer Create() { return new JsonSerializer(); } /// <summary> /// Creates a new <see cref="JsonSerializer"/> instance using the specified <see cref="JsonSerializerSettings"/>. /// The <see cref="JsonSerializer"/> will not use default settings. /// </summary> /// <param name="settings">The settings to be applied to the <see cref="JsonSerializer"/>.</param> /// <returns> /// A new <see cref="JsonSerializer"/> instance using the specified <see cref="JsonSerializerSettings"/>. /// The <see cref="JsonSerializer"/> will not use default settings. /// </returns> public static JsonSerializer Create(JsonSerializerSettings settings) { JsonSerializer serializer = Create(); if (settings != null) ApplySerializerSettings(serializer, settings); return serializer; } /// <summary> /// Creates a new <see cref="JsonSerializer"/> instance. /// The <see cref="JsonSerializer"/> will use default settings. /// </summary> /// <returns> /// A new <see cref="JsonSerializer"/> instance. /// The <see cref="JsonSerializer"/> will use default settings. /// </returns> public static JsonSerializer CreateDefault() { // copy static to local variable to avoid concurrency issues Func<JsonSerializerSettings> defaultSettingsCreator = JsonConvert.DefaultSettings; JsonSerializerSettings defaultSettings = (defaultSettingsCreator != null) ? defaultSettingsCreator() : null; return Create(defaultSettings); } /// <summary> /// Creates a new <see cref="JsonSerializer"/> instance using the specified <see cref="JsonSerializerSettings"/>. /// The <see cref="JsonSerializer"/> will use default settings. /// </summary> /// <param name="settings">The settings to be applied to the <see cref="JsonSerializer"/>.</param> /// <returns> /// A new <see cref="JsonSerializer"/> instance using the specified <see cref="JsonSerializerSettings"/>. /// The <see cref="JsonSerializer"/> will use default settings. /// </returns> public static JsonSerializer CreateDefault(JsonSerializerSettings settings) { JsonSerializer serializer = CreateDefault(); if (settings != null) ApplySerializerSettings(serializer, settings); return serializer; } private static void ApplySerializerSettings(JsonSerializer serializer, JsonSerializerSettings settings) { if (!CollectionUtils.IsNullOrEmpty(settings.Converters)) { // insert settings converters at the beginning so they take precedence // if user wants to remove one of the default converters they will have to do it manually for (int i = 0; i < settings.Converters.Count; i++) { serializer.Converters.Insert(i, settings.Converters[i]); } } // serializer specific if (settings._typeNameHandling != null) serializer.TypeNameHandling = settings.TypeNameHandling; if (settings._typeNameAssemblyFormat != null) serializer.TypeNameAssemblyFormat = settings.TypeNameAssemblyFormat; if (settings._preserveReferencesHandling != null) serializer.PreserveReferencesHandling = settings.PreserveReferencesHandling; if (settings._referenceLoopHandling != null) serializer.ReferenceLoopHandling = settings.ReferenceLoopHandling; if (settings._missingMemberHandling != null) serializer.MissingMemberHandling = settings.MissingMemberHandling; if (settings._objectCreationHandling != null) serializer.ObjectCreationHandling = settings.ObjectCreationHandling; if (settings._nullValueHandling != null) serializer.NullValueHandling = settings.NullValueHandling; if (settings._defaultValueHandling != null) serializer.DefaultValueHandling = settings.DefaultValueHandling; if (settings._constructorHandling != null) serializer.ConstructorHandling = settings.ConstructorHandling; if (settings._context != null) serializer.Context = settings.Context; if (settings._checkAdditionalContent != null) serializer._checkAdditionalContent = settings._checkAdditionalContent; if (settings.Error != null) serializer.Error += settings.Error; if (settings.ContractResolver != null) serializer.ContractResolver = settings.ContractResolver; if (settings.ReferenceResolver != null) serializer.ReferenceResolver = settings.ReferenceResolver; if (settings.TraceWriter != null) serializer.TraceWriter = settings.TraceWriter; if (settings.Binder != null) serializer.Binder = settings.Binder; // reader/writer specific // unset values won't override reader/writer set values if (settings._formatting != null) serializer._formatting = settings._formatting; if (settings._dateFormatHandling != null) serializer._dateFormatHandling = settings._dateFormatHandling; if (settings._dateTimeZoneHandling != null) serializer._dateTimeZoneHandling = settings._dateTimeZoneHandling; if (settings._dateParseHandling != null) serializer._dateParseHandling = settings._dateParseHandling; if (settings._dateFormatStringSet) { serializer._dateFormatString = settings._dateFormatString; serializer._dateFormatStringSet = settings._dateFormatStringSet; } if (settings._floatFormatHandling != null) serializer._floatFormatHandling = settings._floatFormatHandling; if (settings._floatParseHandling != null) serializer._floatParseHandling = settings._floatParseHandling; if (settings._stringEscapeHandling != null) serializer._stringEscapeHandling = settings._stringEscapeHandling; if (settings._culture != null) serializer._culture = settings._culture; if (settings._maxDepthSet) { serializer._maxDepth = settings._maxDepth; serializer._maxDepthSet = settings._maxDepthSet; } } /// <summary> /// Populates the JSON values onto the target object. /// </summary> /// <param name="reader">The <see cref="TextReader"/> that contains the JSON structure to reader values from.</param> /// <param name="target">The target object to populate values onto.</param> public void Populate(TextReader reader, object target) { Populate(new JsonTextReader(reader), target); } /// <summary> /// Populates the JSON values onto the target object. /// </summary> /// <param name="reader">The <see cref="JsonReader"/> that contains the JSON structure to reader values from.</param> /// <param name="target">The target object to populate values onto.</param> public void Populate(JsonReader reader, object target) { PopulateInternal(reader, target); } internal virtual void PopulateInternal(JsonReader reader, object target) { ValidationUtils.ArgumentNotNull(reader, "reader"); ValidationUtils.ArgumentNotNull(target, "target"); JsonSerializerInternalReader serializerReader = new JsonSerializerInternalReader(this); serializerReader.Populate(reader, target); } /// <summary> /// Deserializes the Json structure contained by the specified <see cref="JsonReader"/>. /// </summary> /// <param name="reader">The <see cref="JsonReader"/> that contains the JSON structure to deserialize.</param> /// <returns>The <see cref="Object"/> being deserialized.</returns> public object Deserialize(JsonReader reader) { return Deserialize(reader, null); } /// <summary> /// Deserializes the Json structure contained by the specified <see cref="StringReader"/> /// into an instance of the specified type. /// </summary> /// <param name="reader">The <see cref="TextReader"/> containing the object.</param> /// <param name="objectType">The <see cref="Type"/> of object being deserialized.</param> /// <returns>The instance of <paramref name="objectType"/> being deserialized.</returns> public object Deserialize(TextReader reader, Type objectType) { return Deserialize(new JsonTextReader(reader), objectType); } /// <summary> /// Deserializes the Json structure contained by the specified <see cref="JsonReader"/> /// into an instance of the specified type. /// </summary> /// <param name="reader">The <see cref="JsonReader"/> containing the object.</param> /// <typeparam name="T">The type of the object to deserialize.</typeparam> /// <returns>The instance of <typeparamref name="T"/> being deserialized.</returns> public T Deserialize<T>(JsonReader reader) { return (T)Deserialize(reader, typeof(T)); } /// <summary> /// Deserializes the Json structure contained by the specified <see cref="JsonReader"/> /// into an instance of the specified type. /// </summary> /// <param name="reader">The <see cref="JsonReader"/> containing the object.</param> /// <param name="objectType">The <see cref="Type"/> of object being deserialized.</param> /// <returns>The instance of <paramref name="objectType"/> being deserialized.</returns> public object Deserialize(JsonReader reader, Type objectType) { return DeserializeInternal(reader, objectType); } internal virtual object DeserializeInternal(JsonReader reader, Type objectType) { ValidationUtils.ArgumentNotNull(reader, "reader"); // set serialization options onto reader CultureInfo previousCulture = null; if (_culture != null && !_culture.Equals(reader.Culture)) { previousCulture = reader.Culture; reader.Culture = _culture; } DateTimeZoneHandling? previousDateTimeZoneHandling = null; if (_dateTimeZoneHandling != null && reader.DateTimeZoneHandling != _dateTimeZoneHandling) { previousDateTimeZoneHandling = reader.DateTimeZoneHandling; reader.DateTimeZoneHandling = _dateTimeZoneHandling.Value; } DateParseHandling? previousDateParseHandling = null; if (_dateParseHandling != null && reader.DateParseHandling != _dateParseHandling) { previousDateParseHandling = reader.DateParseHandling; reader.DateParseHandling = _dateParseHandling.Value; } FloatParseHandling? previousFloatParseHandling = null; if (_floatParseHandling != null && reader.FloatParseHandling != _floatParseHandling) { previousFloatParseHandling = reader.FloatParseHandling; reader.FloatParseHandling = _floatParseHandling.Value; } int? previousMaxDepth = null; if (_maxDepthSet && reader.MaxDepth != _maxDepth) { previousMaxDepth = reader.MaxDepth; reader.MaxDepth = _maxDepth; } TraceJsonReader traceJsonReader = (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) ? new TraceJsonReader(reader) : null; JsonSerializerInternalReader serializerReader = new JsonSerializerInternalReader(this); object value = serializerReader.Deserialize(traceJsonReader ?? reader, objectType, CheckAdditionalContent); if (traceJsonReader != null) TraceWriter.Trace(TraceLevel.Verbose, "Deserialized JSON: " + Environment.NewLine + traceJsonReader.GetJson(), null); // reset reader back to previous options if (previousCulture != null) reader.Culture = previousCulture; if (previousDateTimeZoneHandling != null) reader.DateTimeZoneHandling = previousDateTimeZoneHandling.Value; if (previousDateParseHandling != null) reader.DateParseHandling = previousDateParseHandling.Value; if (previousFloatParseHandling != null) reader.FloatParseHandling = previousFloatParseHandling.Value; if (_maxDepthSet) reader.MaxDepth = previousMaxDepth; return value; } /// <summary> /// Serializes the specified <see cref="Object"/> and writes the Json structure /// to a <c>Stream</c> using the specified <see cref="TextWriter"/>. /// </summary> /// <param name="textWriter">The <see cref="TextWriter"/> used to write the Json structure.</param> /// <param name="value">The <see cref="Object"/> to serialize.</param> public void Serialize(TextWriter textWriter, object value) { Serialize(new JsonTextWriter(textWriter), value); } /// <summary> /// Serializes the specified <see cref="Object"/> and writes the Json structure /// to a <c>Stream</c> using the specified <see cref="TextWriter"/>. /// </summary> /// <param name="jsonWriter">The <see cref="JsonWriter"/> used to write the Json structure.</param> /// <param name="value">The <see cref="Object"/> to serialize.</param> /// <param name="objectType"> /// The type of the value being serialized. /// This parameter is used when <see cref="TypeNameHandling"/> is Auto to write out the type name if the type of the value does not match. /// Specifing the type is optional. /// </param> public void Serialize(JsonWriter jsonWriter, object value, Type objectType) { SerializeInternal(jsonWriter, value, objectType); } /// <summary> /// Serializes the specified <see cref="Object"/> and writes the Json structure /// to a <c>Stream</c> using the specified <see cref="TextWriter"/>. /// </summary> /// <param name="textWriter">The <see cref="TextWriter"/> used to write the Json structure.</param> /// <param name="value">The <see cref="Object"/> to serialize.</param> /// <param name="objectType"> /// The type of the value being serialized. /// This parameter is used when <see cref="TypeNameHandling"/> is Auto to write out the type name if the type of the value does not match. /// Specifing the type is optional. /// </param> public void Serialize(TextWriter textWriter, object value, Type objectType) { Serialize(new JsonTextWriter(textWriter), value, objectType); } /// <summary> /// Serializes the specified <see cref="Object"/> and writes the Json structure /// to a <c>Stream</c> using the specified <see cref="JsonWriter"/>. /// </summary> /// <param name="jsonWriter">The <see cref="JsonWriter"/> used to write the Json structure.</param> /// <param name="value">The <see cref="Object"/> to serialize.</param> public void Serialize(JsonWriter jsonWriter, object value) { SerializeInternal(jsonWriter, value, null); } internal virtual void SerializeInternal(JsonWriter jsonWriter, object value, Type objectType) { ValidationUtils.ArgumentNotNull(jsonWriter, "jsonWriter"); // set serialization options onto writer Formatting? previousFormatting = null; if (_formatting != null && jsonWriter.Formatting != _formatting) { previousFormatting = jsonWriter.Formatting; jsonWriter.Formatting = _formatting.Value; } DateFormatHandling? previousDateFormatHandling = null; if (_dateFormatHandling != null && jsonWriter.DateFormatHandling != _dateFormatHandling) { previousDateFormatHandling = jsonWriter.DateFormatHandling; jsonWriter.DateFormatHandling = _dateFormatHandling.Value; } DateTimeZoneHandling? previousDateTimeZoneHandling = null; if (_dateTimeZoneHandling != null && jsonWriter.DateTimeZoneHandling != _dateTimeZoneHandling) { previousDateTimeZoneHandling = jsonWriter.DateTimeZoneHandling; jsonWriter.DateTimeZoneHandling = _dateTimeZoneHandling.Value; } FloatFormatHandling? previousFloatFormatHandling = null; if (_floatFormatHandling != null && jsonWriter.FloatFormatHandling != _floatFormatHandling) { previousFloatFormatHandling = jsonWriter.FloatFormatHandling; jsonWriter.FloatFormatHandling = _floatFormatHandling.Value; } StringEscapeHandling? previousStringEscapeHandling = null; if (_stringEscapeHandling != null && jsonWriter.StringEscapeHandling != _stringEscapeHandling) { previousStringEscapeHandling = jsonWriter.StringEscapeHandling; jsonWriter.StringEscapeHandling = _stringEscapeHandling.Value; } CultureInfo previousCulture = null; if (_culture != null && !_culture.Equals(jsonWriter.Culture)) { previousCulture = jsonWriter.Culture; jsonWriter.Culture = _culture; } string previousDateFormatString = null; if (_dateFormatStringSet && jsonWriter.DateFormatString != _dateFormatString) { previousDateFormatString = jsonWriter.DateFormatString; jsonWriter.DateFormatString = _dateFormatString; } TraceJsonWriter traceJsonWriter = (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) ? new TraceJsonWriter(jsonWriter) : null; JsonSerializerInternalWriter serializerWriter = new JsonSerializerInternalWriter(this); serializerWriter.Serialize(traceJsonWriter ?? jsonWriter, value, objectType); if (traceJsonWriter != null) TraceWriter.Trace(TraceLevel.Verbose, "Serialized JSON: " + Environment.NewLine + traceJsonWriter.GetJson(), null); // reset writer back to previous options if (previousFormatting != null) jsonWriter.Formatting = previousFormatting.Value; if (previousDateFormatHandling != null) jsonWriter.DateFormatHandling = previousDateFormatHandling.Value; if (previousDateTimeZoneHandling != null) jsonWriter.DateTimeZoneHandling = previousDateTimeZoneHandling.Value; if (previousFloatFormatHandling != null) jsonWriter.FloatFormatHandling = previousFloatFormatHandling.Value; if (previousStringEscapeHandling != null) jsonWriter.StringEscapeHandling = previousStringEscapeHandling.Value; if (_dateFormatStringSet) jsonWriter.DateFormatString = previousDateFormatString; if (previousCulture != null) jsonWriter.Culture = previousCulture; } internal IReferenceResolver GetReferenceResolver() { if (_referenceResolver == null) _referenceResolver = new DefaultReferenceResolver(); return _referenceResolver; } internal JsonConverter GetMatchingConverter(Type type) { return GetMatchingConverter(_converters, type); } internal static JsonConverter GetMatchingConverter(IList<JsonConverter> converters, Type objectType) { #if DEBUG ValidationUtils.ArgumentNotNull(objectType, "objectType"); #endif if (converters != null) { for (int i = 0; i < converters.Count; i++) { JsonConverter converter = converters[i]; if (converter.CanConvert(objectType)) return converter; } } return null; } internal void OnError(ErrorEventArgs e) { EventHandler<ErrorEventArgs> error = Error; if (error != null) error(this, e); } } } #endif
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; internal class TestApp { private static long test_0_0(long num, AA init, AA zero) { return init.q; } private static long test_0_1(long num, AA init, AA zero) { zero.q = num; return zero.q; } private static long test_0_2(long num, AA init, AA zero) { return init.q + zero.q; } private static long test_0_3(long num, AA init, AA zero) { return checked(init.q - zero.q); } private static long test_0_4(long num, AA init, AA zero) { zero.q += num; return zero.q; } private static long test_0_5(long num, AA init, AA zero) { zero.q += init.q; return zero.q; } private static long test_0_6(long num, AA init, AA zero) { if (init.q == num) return 100; else return zero.q; } private static long test_0_7(long num, AA init, AA zero) { return init.q < num + 1 ? 100 : -1; } private static long test_0_8(long num, AA init, AA zero) { return (init.q > zero.q ? 1 : 0) + 99; } private static long test_0_9(long num, AA init, AA zero) { return (init.q ^ zero.q) | num; } private static long test_0_10(long num, AA init, AA zero) { zero.q |= init.q; return zero.q & num; } private static long test_0_11(long num, AA init, AA zero) { return init.q >> (int)zero.q; } private static long test_0_12(long num, AA init, AA zero) { return AA.a_init[init.q].q; } private static long test_0_13(long num, AA init, AA zero) { return AA.aa_init[num - 100, (init.q | 1) - 2, 1 + zero.q].q; } private static long test_0_14(long num, AA init, AA zero) { object bb = init.q; return (long)bb; } private static long test_0_15(long num, AA init, AA zero) { double dbl = init.q; return (long)dbl; } private static long test_0_16(long num, AA init, AA zero) { return AA.call_target(init.q); } private static long test_0_17(long num, AA init, AA zero) { return AA.call_target_ref(ref init.q); } private static long test_1_0(long num, ref AA r_init, ref AA r_zero) { return r_init.q; } private static long test_1_1(long num, ref AA r_init, ref AA r_zero) { r_zero.q = num; return r_zero.q; } private static long test_1_2(long num, ref AA r_init, ref AA r_zero) { return r_init.q + r_zero.q; } private static long test_1_3(long num, ref AA r_init, ref AA r_zero) { return checked(r_init.q - r_zero.q); } private static long test_1_4(long num, ref AA r_init, ref AA r_zero) { r_zero.q += num; return r_zero.q; } private static long test_1_5(long num, ref AA r_init, ref AA r_zero) { r_zero.q += r_init.q; return r_zero.q; } private static long test_1_6(long num, ref AA r_init, ref AA r_zero) { if (r_init.q == num) return 100; else return r_zero.q; } private static long test_1_7(long num, ref AA r_init, ref AA r_zero) { return r_init.q < num + 1 ? 100 : -1; } private static long test_1_8(long num, ref AA r_init, ref AA r_zero) { return (r_init.q > r_zero.q ? 1 : 0) + 99; } private static long test_1_9(long num, ref AA r_init, ref AA r_zero) { return (r_init.q ^ r_zero.q) | num; } private static long test_1_10(long num, ref AA r_init, ref AA r_zero) { r_zero.q |= r_init.q; return r_zero.q & num; } private static long test_1_11(long num, ref AA r_init, ref AA r_zero) { return r_init.q >> (int)r_zero.q; } private static long test_1_12(long num, ref AA r_init, ref AA r_zero) { return AA.a_init[r_init.q].q; } private static long test_1_13(long num, ref AA r_init, ref AA r_zero) { return AA.aa_init[num - 100, (r_init.q | 1) - 2, 1 + r_zero.q].q; } private static long test_1_14(long num, ref AA r_init, ref AA r_zero) { object bb = r_init.q; return (long)bb; } private static long test_1_15(long num, ref AA r_init, ref AA r_zero) { double dbl = r_init.q; return (long)dbl; } private static long test_1_16(long num, ref AA r_init, ref AA r_zero) { return AA.call_target(r_init.q); } private static long test_1_17(long num, ref AA r_init, ref AA r_zero) { return AA.call_target_ref(ref r_init.q); } private static long test_2_0(long num) { return AA.a_init[num].q; } private static long test_2_1(long num) { AA.a_zero[num].q = num; return AA.a_zero[num].q; } private static long test_2_2(long num) { return AA.a_init[num].q + AA.a_zero[num].q; } private static long test_2_3(long num) { return checked(AA.a_init[num].q - AA.a_zero[num].q); } private static long test_2_4(long num) { AA.a_zero[num].q += num; return AA.a_zero[num].q; } private static long test_2_5(long num) { AA.a_zero[num].q += AA.a_init[num].q; return AA.a_zero[num].q; } private static long test_2_6(long num) { if (AA.a_init[num].q == num) return 100; else return AA.a_zero[num].q; } private static long test_2_7(long num) { return AA.a_init[num].q < num + 1 ? 100 : -1; } private static long test_2_8(long num) { return (AA.a_init[num].q > AA.a_zero[num].q ? 1 : 0) + 99; } private static long test_2_9(long num) { return (AA.a_init[num].q ^ AA.a_zero[num].q) | num; } private static long test_2_10(long num) { AA.a_zero[num].q |= AA.a_init[num].q; return AA.a_zero[num].q & num; } private static long test_2_11(long num) { return AA.a_init[num].q >> (int)AA.a_zero[num].q; } private static long test_2_12(long num) { return AA.a_init[AA.a_init[num].q].q; } private static long test_2_13(long num) { return AA.aa_init[num - 100, (AA.a_init[num].q | 1) - 2, 1 + AA.a_zero[num].q].q; } private static long test_2_14(long num) { object bb = AA.a_init[num].q; return (long)bb; } private static long test_2_15(long num) { double dbl = AA.a_init[num].q; return (long)dbl; } private static long test_2_16(long num) { return AA.call_target(AA.a_init[num].q); } private static long test_2_17(long num) { return AA.call_target_ref(ref AA.a_init[num].q); } private static long test_3_0(long num) { return AA.aa_init[0, num - 1, num / 100].q; } private static long test_3_1(long num) { AA.aa_zero[0, num - 1, num / 100].q = num; return AA.aa_zero[0, num - 1, num / 100].q; } private static long test_3_2(long num) { return AA.aa_init[0, num - 1, num / 100].q + AA.aa_zero[0, num - 1, num / 100].q; } private static long test_3_3(long num) { return checked(AA.aa_init[0, num - 1, num / 100].q - AA.aa_zero[0, num - 1, num / 100].q); } private static long test_3_4(long num) { AA.aa_zero[0, num - 1, num / 100].q += num; return AA.aa_zero[0, num - 1, num / 100].q; } private static long test_3_5(long num) { AA.aa_zero[0, num - 1, num / 100].q += AA.aa_init[0, num - 1, num / 100].q; return AA.aa_zero[0, num - 1, num / 100].q; } private static long test_3_6(long num) { if (AA.aa_init[0, num - 1, num / 100].q == num) return 100; else return AA.aa_zero[0, num - 1, num / 100].q; } private static long test_3_7(long num) { return AA.aa_init[0, num - 1, num / 100].q < num + 1 ? 100 : -1; } private static long test_3_8(long num) { return (AA.aa_init[0, num - 1, num / 100].q > AA.aa_zero[0, num - 1, num / 100].q ? 1 : 0) + 99; } private static long test_3_9(long num) { return (AA.aa_init[0, num - 1, num / 100].q ^ AA.aa_zero[0, num - 1, num / 100].q) | num; } private static long test_3_10(long num) { AA.aa_zero[0, num - 1, num / 100].q |= AA.aa_init[0, num - 1, num / 100].q; return AA.aa_zero[0, num - 1, num / 100].q & num; } private static long test_3_11(long num) { return AA.aa_init[0, num - 1, num / 100].q >> (int)AA.aa_zero[0, num - 1, num / 100].q; } private static long test_3_12(long num) { return AA.a_init[AA.aa_init[0, num - 1, num / 100].q].q; } private static long test_3_13(long num) { return AA.aa_init[num - 100, (AA.aa_init[0, num - 1, num / 100].q | 1) - 2, 1 + AA.aa_zero[0, num - 1, num / 100].q].q; } private static long test_3_14(long num) { object bb = AA.aa_init[0, num - 1, num / 100].q; return (long)bb; } private static long test_3_15(long num) { double dbl = AA.aa_init[0, num - 1, num / 100].q; return (long)dbl; } private static long test_3_16(long num) { return AA.call_target(AA.aa_init[0, num - 1, num / 100].q); } private static long test_3_17(long num) { return AA.call_target_ref(ref AA.aa_init[0, num - 1, num / 100].q); } private static long test_4_0(long num) { return BB.f_init.q; } private static long test_4_1(long num) { BB.f_zero.q = num; return BB.f_zero.q; } private static long test_4_2(long num) { return BB.f_init.q + BB.f_zero.q; } private static long test_4_3(long num) { return checked(BB.f_init.q - BB.f_zero.q); } private static long test_4_4(long num) { BB.f_zero.q += num; return BB.f_zero.q; } private static long test_4_5(long num) { BB.f_zero.q += BB.f_init.q; return BB.f_zero.q; } private static long test_4_6(long num) { if (BB.f_init.q == num) return 100; else return BB.f_zero.q; } private static long test_4_7(long num) { return BB.f_init.q < num + 1 ? 100 : -1; } private static long test_4_8(long num) { return (BB.f_init.q > BB.f_zero.q ? 1 : 0) + 99; } private static long test_4_9(long num) { return (BB.f_init.q ^ BB.f_zero.q) | num; } private static long test_4_10(long num) { BB.f_zero.q |= BB.f_init.q; return BB.f_zero.q & num; } private static long test_4_11(long num) { return BB.f_init.q >> (int)BB.f_zero.q; } private static long test_4_12(long num) { return AA.a_init[BB.f_init.q].q; } private static long test_4_13(long num) { return AA.aa_init[num - 100, (BB.f_init.q | 1) - 2, 1 + BB.f_zero.q].q; } private static long test_4_14(long num) { object bb = BB.f_init.q; return (long)bb; } private static long test_4_15(long num) { double dbl = BB.f_init.q; return (long)dbl; } private static long test_4_16(long num) { return AA.call_target(BB.f_init.q); } private static long test_4_17(long num) { return AA.call_target_ref(ref BB.f_init.q); } private static long test_5_0(long num) { return ((AA)AA.b_init).q; } private static long test_6_0(long num, TypedReference tr_init) { return __refvalue(tr_init, AA).q; } private static unsafe long test_7_0(long num, void* ptr_init, void* ptr_zero) { return (*((AA*)ptr_init)).q; } private static unsafe long test_7_1(long num, void* ptr_init, void* ptr_zero) { (*((AA*)ptr_zero)).q = num; return (*((AA*)ptr_zero)).q; } private static unsafe long test_7_2(long num, void* ptr_init, void* ptr_zero) { return (*((AA*)ptr_init)).q + (*((AA*)ptr_zero)).q; } private static unsafe long test_7_3(long num, void* ptr_init, void* ptr_zero) { return checked((*((AA*)ptr_init)).q - (*((AA*)ptr_zero)).q); } private static unsafe long test_7_4(long num, void* ptr_init, void* ptr_zero) { (*((AA*)ptr_zero)).q += num; return (*((AA*)ptr_zero)).q; } private static unsafe long test_7_5(long num, void* ptr_init, void* ptr_zero) { (*((AA*)ptr_zero)).q += (*((AA*)ptr_init)).q; return (*((AA*)ptr_zero)).q; } private static unsafe long test_7_6(long num, void* ptr_init, void* ptr_zero) { if ((*((AA*)ptr_init)).q == num) return 100; else return (*((AA*)ptr_zero)).q; } private static unsafe long test_7_7(long num, void* ptr_init, void* ptr_zero) { return (*((AA*)ptr_init)).q < num + 1 ? 100 : -1; } private static unsafe long test_7_8(long num, void* ptr_init, void* ptr_zero) { return ((*((AA*)ptr_init)).q > (*((AA*)ptr_zero)).q ? 1 : 0) + 99; } private static unsafe long test_7_9(long num, void* ptr_init, void* ptr_zero) { return ((*((AA*)ptr_init)).q ^ (*((AA*)ptr_zero)).q) | num; } private static unsafe long test_7_10(long num, void* ptr_init, void* ptr_zero) { (*((AA*)ptr_zero)).q |= (*((AA*)ptr_init)).q; return (*((AA*)ptr_zero)).q & num; } private static unsafe long test_7_11(long num, void* ptr_init, void* ptr_zero) { return (*((AA*)ptr_init)).q >> (int)(*((AA*)ptr_zero)).q; } private static unsafe long test_7_12(long num, void* ptr_init, void* ptr_zero) { return AA.a_init[(*((AA*)ptr_init)).q].q; } private static unsafe long test_7_13(long num, void* ptr_init, void* ptr_zero) { return AA.aa_init[num - 100, ((*((AA*)ptr_init)).q | 1) - 2, 1 + (*((AA*)ptr_zero)).q].q; } private static unsafe long test_7_14(long num, void* ptr_init, void* ptr_zero) { object bb = (*((AA*)ptr_init)).q; return (long)bb; } private static unsafe long test_7_15(long num, void* ptr_init, void* ptr_zero) { double dbl = (*((AA*)ptr_init)).q; return (long)dbl; } private static unsafe long test_7_16(long num, void* ptr_init, void* ptr_zero) { return AA.call_target((*((AA*)ptr_init)).q); } private static unsafe long test_7_17(long num, void* ptr_init, void* ptr_zero) { return AA.call_target_ref(ref (*((AA*)ptr_init)).q); } private static unsafe int Main() { AA.reset(); if (test_0_0(100, new AA(100), new AA(0)) != 100) { Console.WriteLine("test_0_0() failed."); return 101; } AA.verify_all(); AA.reset(); if (test_0_1(100, new AA(100), new AA(0)) != 100) { Console.WriteLine("test_0_1() failed."); return 102; } AA.verify_all(); AA.reset(); if (test_0_2(100, new AA(100), new AA(0)) != 100) { Console.WriteLine("test_0_2() failed."); return 103; } AA.verify_all(); AA.reset(); if (test_0_3(100, new AA(100), new AA(0)) != 100) { Console.WriteLine("test_0_3() failed."); return 104; } AA.verify_all(); AA.reset(); if (test_0_4(100, new AA(100), new AA(0)) != 100) { Console.WriteLine("test_0_4() failed."); return 105; } AA.verify_all(); AA.reset(); if (test_0_5(100, new AA(100), new AA(0)) != 100) { Console.WriteLine("test_0_5() failed."); return 106; } AA.verify_all(); AA.reset(); if (test_0_6(100, new AA(100), new AA(0)) != 100) { Console.WriteLine("test_0_6() failed."); return 107; } AA.verify_all(); AA.reset(); if (test_0_7(100, new AA(100), new AA(0)) != 100) { Console.WriteLine("test_0_7() failed."); return 108; } AA.verify_all(); AA.reset(); if (test_0_8(100, new AA(100), new AA(0)) != 100) { Console.WriteLine("test_0_8() failed."); return 109; } AA.verify_all(); AA.reset(); if (test_0_9(100, new AA(100), new AA(0)) != 100) { Console.WriteLine("test_0_9() failed."); return 110; } AA.verify_all(); AA.reset(); if (test_0_10(100, new AA(100), new AA(0)) != 100) { Console.WriteLine("test_0_10() failed."); return 111; } AA.verify_all(); AA.reset(); if (test_0_11(100, new AA(100), new AA(0)) != 100) { Console.WriteLine("test_0_11() failed."); return 112; } AA.verify_all(); AA.reset(); if (test_0_12(100, new AA(100), new AA(0)) != 100) { Console.WriteLine("test_0_12() failed."); return 113; } AA.verify_all(); AA.reset(); if (test_0_13(100, new AA(100), new AA(0)) != 100) { Console.WriteLine("test_0_13() failed."); return 114; } AA.verify_all(); AA.reset(); if (test_0_14(100, new AA(100), new AA(0)) != 100) { Console.WriteLine("test_0_14() failed."); return 115; } AA.verify_all(); AA.reset(); if (test_0_15(100, new AA(100), new AA(0)) != 100) { Console.WriteLine("test_0_15() failed."); return 116; } AA.verify_all(); AA.reset(); if (test_0_16(100, new AA(100), new AA(0)) != 100) { Console.WriteLine("test_0_16() failed."); return 117; } AA.verify_all(); AA.reset(); if (test_0_17(100, new AA(100), new AA(0)) != 100) { Console.WriteLine("test_0_17() failed."); return 118; } AA.verify_all(); AA.reset(); if (test_1_0(100, ref AA._init, ref AA._zero) != 100) { Console.WriteLine("test_1_0() failed."); return 119; } AA.verify_all(); AA.reset(); if (test_1_1(100, ref AA._init, ref AA._zero) != 100) { Console.WriteLine("test_1_1() failed."); return 120; } AA.verify_all(); AA.reset(); if (test_1_2(100, ref AA._init, ref AA._zero) != 100) { Console.WriteLine("test_1_2() failed."); return 121; } AA.verify_all(); AA.reset(); if (test_1_3(100, ref AA._init, ref AA._zero) != 100) { Console.WriteLine("test_1_3() failed."); return 122; } AA.verify_all(); AA.reset(); if (test_1_4(100, ref AA._init, ref AA._zero) != 100) { Console.WriteLine("test_1_4() failed."); return 123; } AA.verify_all(); AA.reset(); if (test_1_5(100, ref AA._init, ref AA._zero) != 100) { Console.WriteLine("test_1_5() failed."); return 124; } AA.verify_all(); AA.reset(); if (test_1_6(100, ref AA._init, ref AA._zero) != 100) { Console.WriteLine("test_1_6() failed."); return 125; } AA.verify_all(); AA.reset(); if (test_1_7(100, ref AA._init, ref AA._zero) != 100) { Console.WriteLine("test_1_7() failed."); return 126; } AA.verify_all(); AA.reset(); if (test_1_8(100, ref AA._init, ref AA._zero) != 100) { Console.WriteLine("test_1_8() failed."); return 127; } AA.verify_all(); AA.reset(); if (test_1_9(100, ref AA._init, ref AA._zero) != 100) { Console.WriteLine("test_1_9() failed."); return 128; } AA.verify_all(); AA.reset(); if (test_1_10(100, ref AA._init, ref AA._zero) != 100) { Console.WriteLine("test_1_10() failed."); return 129; } AA.verify_all(); AA.reset(); if (test_1_11(100, ref AA._init, ref AA._zero) != 100) { Console.WriteLine("test_1_11() failed."); return 130; } AA.verify_all(); AA.reset(); if (test_1_12(100, ref AA._init, ref AA._zero) != 100) { Console.WriteLine("test_1_12() failed."); return 131; } AA.verify_all(); AA.reset(); if (test_1_13(100, ref AA._init, ref AA._zero) != 100) { Console.WriteLine("test_1_13() failed."); return 132; } AA.verify_all(); AA.reset(); if (test_1_14(100, ref AA._init, ref AA._zero) != 100) { Console.WriteLine("test_1_14() failed."); return 133; } AA.verify_all(); AA.reset(); if (test_1_15(100, ref AA._init, ref AA._zero) != 100) { Console.WriteLine("test_1_15() failed."); return 134; } AA.verify_all(); AA.reset(); if (test_1_16(100, ref AA._init, ref AA._zero) != 100) { Console.WriteLine("test_1_16() failed."); return 135; } AA.verify_all(); AA.reset(); if (test_1_17(100, ref AA._init, ref AA._zero) != 100) { Console.WriteLine("test_1_17() failed."); return 136; } AA.verify_all(); AA.reset(); if (test_2_0(100) != 100) { Console.WriteLine("test_2_0() failed."); return 137; } AA.verify_all(); AA.reset(); if (test_2_1(100) != 100) { Console.WriteLine("test_2_1() failed."); return 138; } AA.verify_all(); AA.reset(); if (test_2_2(100) != 100) { Console.WriteLine("test_2_2() failed."); return 139; } AA.verify_all(); AA.reset(); if (test_2_3(100) != 100) { Console.WriteLine("test_2_3() failed."); return 140; } AA.verify_all(); AA.reset(); if (test_2_4(100) != 100) { Console.WriteLine("test_2_4() failed."); return 141; } AA.verify_all(); AA.reset(); if (test_2_5(100) != 100) { Console.WriteLine("test_2_5() failed."); return 142; } AA.verify_all(); AA.reset(); if (test_2_6(100) != 100) { Console.WriteLine("test_2_6() failed."); return 143; } AA.verify_all(); AA.reset(); if (test_2_7(100) != 100) { Console.WriteLine("test_2_7() failed."); return 144; } AA.verify_all(); AA.reset(); if (test_2_8(100) != 100) { Console.WriteLine("test_2_8() failed."); return 145; } AA.verify_all(); AA.reset(); if (test_2_9(100) != 100) { Console.WriteLine("test_2_9() failed."); return 146; } AA.verify_all(); AA.reset(); if (test_2_10(100) != 100) { Console.WriteLine("test_2_10() failed."); return 147; } AA.verify_all(); AA.reset(); if (test_2_11(100) != 100) { Console.WriteLine("test_2_11() failed."); return 148; } AA.verify_all(); AA.reset(); if (test_2_12(100) != 100) { Console.WriteLine("test_2_12() failed."); return 149; } AA.verify_all(); AA.reset(); if (test_2_13(100) != 100) { Console.WriteLine("test_2_13() failed."); return 150; } AA.verify_all(); AA.reset(); if (test_2_14(100) != 100) { Console.WriteLine("test_2_14() failed."); return 151; } AA.verify_all(); AA.reset(); if (test_2_15(100) != 100) { Console.WriteLine("test_2_15() failed."); return 152; } AA.verify_all(); AA.reset(); if (test_2_16(100) != 100) { Console.WriteLine("test_2_16() failed."); return 153; } AA.verify_all(); AA.reset(); if (test_2_17(100) != 100) { Console.WriteLine("test_2_17() failed."); return 154; } AA.verify_all(); AA.reset(); if (test_3_0(100) != 100) { Console.WriteLine("test_3_0() failed."); return 155; } AA.verify_all(); AA.reset(); if (test_3_1(100) != 100) { Console.WriteLine("test_3_1() failed."); return 156; } AA.verify_all(); AA.reset(); if (test_3_2(100) != 100) { Console.WriteLine("test_3_2() failed."); return 157; } AA.verify_all(); AA.reset(); if (test_3_3(100) != 100) { Console.WriteLine("test_3_3() failed."); return 158; } AA.verify_all(); AA.reset(); if (test_3_4(100) != 100) { Console.WriteLine("test_3_4() failed."); return 159; } AA.verify_all(); AA.reset(); if (test_3_5(100) != 100) { Console.WriteLine("test_3_5() failed."); return 160; } AA.verify_all(); AA.reset(); if (test_3_6(100) != 100) { Console.WriteLine("test_3_6() failed."); return 161; } AA.verify_all(); AA.reset(); if (test_3_7(100) != 100) { Console.WriteLine("test_3_7() failed."); return 162; } AA.verify_all(); AA.reset(); if (test_3_8(100) != 100) { Console.WriteLine("test_3_8() failed."); return 163; } AA.verify_all(); AA.reset(); if (test_3_9(100) != 100) { Console.WriteLine("test_3_9() failed."); return 164; } AA.verify_all(); AA.reset(); if (test_3_10(100) != 100) { Console.WriteLine("test_3_10() failed."); return 165; } AA.verify_all(); AA.reset(); if (test_3_11(100) != 100) { Console.WriteLine("test_3_11() failed."); return 166; } AA.verify_all(); AA.reset(); if (test_3_12(100) != 100) { Console.WriteLine("test_3_12() failed."); return 167; } AA.verify_all(); AA.reset(); if (test_3_13(100) != 100) { Console.WriteLine("test_3_13() failed."); return 168; } AA.verify_all(); AA.reset(); if (test_3_14(100) != 100) { Console.WriteLine("test_3_14() failed."); return 169; } AA.verify_all(); AA.reset(); if (test_3_15(100) != 100) { Console.WriteLine("test_3_15() failed."); return 170; } AA.verify_all(); AA.reset(); if (test_3_16(100) != 100) { Console.WriteLine("test_3_16() failed."); return 171; } AA.verify_all(); AA.reset(); if (test_3_17(100) != 100) { Console.WriteLine("test_3_17() failed."); return 172; } AA.verify_all(); AA.reset(); if (test_4_0(100) != 100) { Console.WriteLine("test_4_0() failed."); return 173; } AA.verify_all(); AA.reset(); if (test_4_1(100) != 100) { Console.WriteLine("test_4_1() failed."); return 174; } AA.verify_all(); AA.reset(); if (test_4_2(100) != 100) { Console.WriteLine("test_4_2() failed."); return 175; } AA.verify_all(); AA.reset(); if (test_4_3(100) != 100) { Console.WriteLine("test_4_3() failed."); return 176; } AA.verify_all(); AA.reset(); if (test_4_4(100) != 100) { Console.WriteLine("test_4_4() failed."); return 177; } AA.verify_all(); AA.reset(); if (test_4_5(100) != 100) { Console.WriteLine("test_4_5() failed."); return 178; } AA.verify_all(); AA.reset(); if (test_4_6(100) != 100) { Console.WriteLine("test_4_6() failed."); return 179; } AA.verify_all(); AA.reset(); if (test_4_7(100) != 100) { Console.WriteLine("test_4_7() failed."); return 180; } AA.verify_all(); AA.reset(); if (test_4_8(100) != 100) { Console.WriteLine("test_4_8() failed."); return 181; } AA.verify_all(); AA.reset(); if (test_4_9(100) != 100) { Console.WriteLine("test_4_9() failed."); return 182; } AA.verify_all(); AA.reset(); if (test_4_10(100) != 100) { Console.WriteLine("test_4_10() failed."); return 183; } AA.verify_all(); AA.reset(); if (test_4_11(100) != 100) { Console.WriteLine("test_4_11() failed."); return 184; } AA.verify_all(); AA.reset(); if (test_4_12(100) != 100) { Console.WriteLine("test_4_12() failed."); return 185; } AA.verify_all(); AA.reset(); if (test_4_13(100) != 100) { Console.WriteLine("test_4_13() failed."); return 186; } AA.verify_all(); AA.reset(); if (test_4_14(100) != 100) { Console.WriteLine("test_4_14() failed."); return 187; } AA.verify_all(); AA.reset(); if (test_4_15(100) != 100) { Console.WriteLine("test_4_15() failed."); return 188; } AA.verify_all(); AA.reset(); if (test_4_16(100) != 100) { Console.WriteLine("test_4_16() failed."); return 189; } AA.verify_all(); AA.reset(); if (test_4_17(100) != 100) { Console.WriteLine("test_4_17() failed."); return 190; } AA.verify_all(); AA.reset(); if (test_5_0(100) != 100) { Console.WriteLine("test_5_0() failed."); return 191; } AA.verify_all(); AA.reset(); if (test_6_0(100, __makeref(AA._init)) != 100) { Console.WriteLine("test_6_0() failed."); return 192; } AA.verify_all(); AA.reset(); fixed (void* p_init = &AA._init, p_zero = &AA._zero) { if (test_7_0(100, p_init, p_zero) != 100) { Console.WriteLine("test_7_0() failed."); return 193; } } AA.verify_all(); AA.reset(); fixed (void* p_init = &AA._init, p_zero = &AA._zero) { if (test_7_1(100, p_init, p_zero) != 100) { Console.WriteLine("test_7_1() failed."); return 194; } } AA.verify_all(); AA.reset(); fixed (void* p_init = &AA._init, p_zero = &AA._zero) { if (test_7_2(100, p_init, p_zero) != 100) { Console.WriteLine("test_7_2() failed."); return 195; } } AA.verify_all(); AA.reset(); fixed (void* p_init = &AA._init, p_zero = &AA._zero) { if (test_7_3(100, p_init, p_zero) != 100) { Console.WriteLine("test_7_3() failed."); return 196; } } AA.verify_all(); AA.reset(); fixed (void* p_init = &AA._init, p_zero = &AA._zero) { if (test_7_4(100, p_init, p_zero) != 100) { Console.WriteLine("test_7_4() failed."); return 197; } } AA.verify_all(); AA.reset(); fixed (void* p_init = &AA._init, p_zero = &AA._zero) { if (test_7_5(100, p_init, p_zero) != 100) { Console.WriteLine("test_7_5() failed."); return 198; } } AA.verify_all(); AA.reset(); fixed (void* p_init = &AA._init, p_zero = &AA._zero) { if (test_7_6(100, p_init, p_zero) != 100) { Console.WriteLine("test_7_6() failed."); return 199; } } AA.verify_all(); AA.reset(); fixed (void* p_init = &AA._init, p_zero = &AA._zero) { if (test_7_7(100, p_init, p_zero) != 100) { Console.WriteLine("test_7_7() failed."); return 200; } } AA.verify_all(); AA.reset(); fixed (void* p_init = &AA._init, p_zero = &AA._zero) { if (test_7_8(100, p_init, p_zero) != 100) { Console.WriteLine("test_7_8() failed."); return 201; } } AA.verify_all(); AA.reset(); fixed (void* p_init = &AA._init, p_zero = &AA._zero) { if (test_7_9(100, p_init, p_zero) != 100) { Console.WriteLine("test_7_9() failed."); return 202; } } AA.verify_all(); AA.reset(); fixed (void* p_init = &AA._init, p_zero = &AA._zero) { if (test_7_10(100, p_init, p_zero) != 100) { Console.WriteLine("test_7_10() failed."); return 203; } } AA.verify_all(); AA.reset(); fixed (void* p_init = &AA._init, p_zero = &AA._zero) { if (test_7_11(100, p_init, p_zero) != 100) { Console.WriteLine("test_7_11() failed."); return 204; } } AA.verify_all(); AA.reset(); fixed (void* p_init = &AA._init, p_zero = &AA._zero) { if (test_7_12(100, p_init, p_zero) != 100) { Console.WriteLine("test_7_12() failed."); return 205; } } AA.verify_all(); AA.reset(); fixed (void* p_init = &AA._init, p_zero = &AA._zero) { if (test_7_13(100, p_init, p_zero) != 100) { Console.WriteLine("test_7_13() failed."); return 206; } } AA.verify_all(); AA.reset(); fixed (void* p_init = &AA._init, p_zero = &AA._zero) { if (test_7_14(100, p_init, p_zero) != 100) { Console.WriteLine("test_7_14() failed."); return 207; } } AA.verify_all(); AA.reset(); fixed (void* p_init = &AA._init, p_zero = &AA._zero) { if (test_7_15(100, p_init, p_zero) != 100) { Console.WriteLine("test_7_15() failed."); return 208; } } AA.verify_all(); AA.reset(); fixed (void* p_init = &AA._init, p_zero = &AA._zero) { if (test_7_16(100, p_init, p_zero) != 100) { Console.WriteLine("test_7_16() failed."); return 209; } } AA.verify_all(); AA.reset(); fixed (void* p_init = &AA._init, p_zero = &AA._zero) { if (test_7_17(100, p_init, p_zero) != 100) { Console.WriteLine("test_7_17() failed."); return 210; } } AA.verify_all(); Console.WriteLine("All tests passed."); return 100; } }
// 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.Security.Permissions { using System; #if FEATURE_CAS_POLICY using SecurityElement = System.Security.SecurityElement; #endif // FEATURE_CAS_POLICY using System.Security.Util; using System.IO; using System.Text; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Runtime.Serialization; using System.Diagnostics.Contracts; [System.Runtime.InteropServices.ComVisible(true)] #if FEATURE_SERIALIZATION [Serializable] #endif sealed public class UrlIdentityPermission : CodeAccessPermission, IBuiltInPermission { //------------------------------------------------------ // // PRIVATE STATE DATA // //------------------------------------------------------ [OptionalField(VersionAdded = 2)] private bool m_unrestricted; [OptionalField(VersionAdded = 2)] private URLString[] m_urls; #if FEATURE_REMOTING // This field will be populated only for non X-AD scenarios where we create a XML-ised string of the Permission [OptionalField(VersionAdded = 2)] private String m_serializedPermission; // This field is legacy info from v1.x and is never used in v2.0 and beyond: purely for serialization purposes private URLString m_url; [OnDeserialized] private void OnDeserialized(StreamingContext ctx) { // v2.0 and beyond XML case if (m_serializedPermission != null) { FromXml(SecurityElement.FromString(m_serializedPermission)); m_serializedPermission = null; } else if (m_url != null) //v1.x case where we read the m_site value { m_unrestricted = false; m_urls = new URLString[1]; m_urls[0] = m_url; m_url = null; } } [OnSerializing] private void OnSerializing(StreamingContext ctx) { if ((ctx.State & ~(StreamingContextStates.Clone|StreamingContextStates.CrossAppDomain)) != 0) { m_serializedPermission = ToXml().ToString(); //for the v2 and beyond case if (m_urls != null && m_urls.Length == 1) // for the v1.x case m_url = m_urls[0]; } } [OnSerialized] private void OnSerialized(StreamingContext ctx) { if ((ctx.State & ~(StreamingContextStates.Clone|StreamingContextStates.CrossAppDomain)) != 0) { m_serializedPermission = null; m_url = null; } } #endif // FEATURE_REMOTING //------------------------------------------------------ // // PUBLIC CONSTRUCTORS // //------------------------------------------------------ public UrlIdentityPermission(PermissionState state) { if (state == PermissionState.Unrestricted) { m_unrestricted = true; } else if (state == PermissionState.None) { m_unrestricted = false; } else { throw new ArgumentException(Environment.GetResourceString("Argument_InvalidPermissionState")); } } public UrlIdentityPermission( String site ) { if (site == null) throw new ArgumentNullException( nameof(site) ); Contract.EndContractBlock(); Url = site; } internal UrlIdentityPermission( URLString site ) { m_unrestricted = false; m_urls = new URLString[1]; m_urls[0] = site; } // Internal function to append all the urls in m_urls to the input originList internal void AppendOrigin(ArrayList originList) { if (m_urls == null) originList.Add(""); else { int n; for(n = 0; n < this.m_urls.Length; n++) originList.Add(m_urls[n].ToString()); } } //------------------------------------------------------ // // PUBLIC ACCESSOR METHODS // //------------------------------------------------------ public String Url { set { m_unrestricted = false; if(value == null || value.Length == 0) m_urls = null; else { m_urls = new URLString[1]; m_urls[0] = new URLString( value ); } } get { if(m_urls == null) return ""; if(m_urls.Length == 1) return m_urls[0].ToString(); throw new NotSupportedException(Environment.GetResourceString("NotSupported_AmbiguousIdentity")); } } //------------------------------------------------------ // // PRIVATE AND PROTECTED HELPERS FOR ACCESSORS AND CONSTRUCTORS // //------------------------------------------------------ //------------------------------------------------------ // // CODEACCESSPERMISSION IMPLEMENTATION // //------------------------------------------------------ //------------------------------------------------------ // // IPERMISSION IMPLEMENTATION // //------------------------------------------------------ public override IPermission Copy() { UrlIdentityPermission perm = new UrlIdentityPermission( PermissionState.None ); perm.m_unrestricted = this.m_unrestricted; if (this.m_urls != null) { perm.m_urls = new URLString[this.m_urls.Length]; int n; for(n = 0; n < this.m_urls.Length; n++) perm.m_urls[n] = (URLString)this.m_urls[n].Copy(); } return perm; } public override bool IsSubsetOf(IPermission target) { if (target == null) { if(m_unrestricted) return false; if(m_urls == null) return true; if(m_urls.Length == 0) return true; return false; } UrlIdentityPermission that = target as UrlIdentityPermission; if(that == null) throw new ArgumentException(Environment.GetResourceString("Argument_WrongType", this.GetType().FullName)); if(that.m_unrestricted) return true; if(m_unrestricted) return false; if(this.m_urls != null) { foreach(URLString usThis in this.m_urls) { bool bOK = false; if(that.m_urls != null) { foreach(URLString usThat in that.m_urls) { if(usThis.IsSubsetOf(usThat)) { bOK = true; break; } } } if(!bOK) return false; } } return true; } public override IPermission Intersect(IPermission target) { if (target == null) return null; UrlIdentityPermission that = target as UrlIdentityPermission; if(that == null) throw new ArgumentException(Environment.GetResourceString("Argument_WrongType", this.GetType().FullName)); if(this.m_unrestricted && that.m_unrestricted) { UrlIdentityPermission res = new UrlIdentityPermission(PermissionState.None); res.m_unrestricted = true; return res; } if(this.m_unrestricted) return that.Copy(); if(that.m_unrestricted) return this.Copy(); if(this.m_urls == null || that.m_urls == null || this.m_urls.Length == 0 || that.m_urls.Length == 0) return null; List<URLString> alUrls = new List<URLString>(); foreach(URLString usThis in this.m_urls) { foreach(URLString usThat in that.m_urls) { URLString usInt = (URLString)usThis.Intersect(usThat); if(usInt != null) alUrls.Add(usInt); } } if(alUrls.Count == 0) return null; UrlIdentityPermission result = new UrlIdentityPermission(PermissionState.None); result.m_urls = alUrls.ToArray(); return result; } public override IPermission Union(IPermission target) { if (target == null) { if((this.m_urls == null || this.m_urls.Length == 0) && !this.m_unrestricted) return null; return this.Copy(); } UrlIdentityPermission that = target as UrlIdentityPermission; if(that == null) throw new ArgumentException(Environment.GetResourceString("Argument_WrongType", this.GetType().FullName)); if(this.m_unrestricted || that.m_unrestricted) { UrlIdentityPermission res = new UrlIdentityPermission(PermissionState.None); res.m_unrestricted = true; return res; } if (this.m_urls == null || this.m_urls.Length == 0) { if(that.m_urls == null || that.m_urls.Length == 0) return null; return that.Copy(); } if(that.m_urls == null || that.m_urls.Length == 0) return this.Copy(); List<URLString> alUrls = new List<URLString>(); foreach(URLString usThis in this.m_urls) alUrls.Add(usThis); foreach(URLString usThat in that.m_urls) { bool bDupe = false; foreach(URLString us in alUrls) { if(usThat.Equals(us)) { bDupe = true; break; } } if(!bDupe) alUrls.Add(usThat); } UrlIdentityPermission result = new UrlIdentityPermission(PermissionState.None); result.m_urls = alUrls.ToArray(); return result; } #if FEATURE_CAS_POLICY public override void FromXml(SecurityElement esd) { m_unrestricted = false; m_urls = null; CodeAccessPermission.ValidateElement( esd, this ); String unr = esd.Attribute( "Unrestricted" ); if(unr != null && String.Compare(unr, "true", StringComparison.OrdinalIgnoreCase) == 0) { m_unrestricted = true; return; } String elem = esd.Attribute( "Url" ); List<URLString> al = new List<URLString>(); if(elem != null) al.Add(new URLString( elem, true )); ArrayList alChildren = esd.Children; if(alChildren != null) { foreach(SecurityElement child in alChildren) { elem = child.Attribute( "Url" ); if(elem != null) al.Add(new URLString( elem, true )); } } if(al.Count != 0) m_urls = al.ToArray(); } public override SecurityElement ToXml() { SecurityElement esd = CodeAccessPermission.CreatePermissionElement( this, "System.Security.Permissions.UrlIdentityPermission" ); if (m_unrestricted) esd.AddAttribute( "Unrestricted", "true" ); else if (m_urls != null) { if (m_urls.Length == 1) esd.AddAttribute( "Url", m_urls[0].ToString() ); else { int n; for(n = 0; n < m_urls.Length; n++) { SecurityElement child = new SecurityElement("Url"); child.AddAttribute( "Url", m_urls[n].ToString() ); esd.AddChild(child); } } } return esd; } #endif // FEATURE_CAS_POLICY /// <internalonly/> int IBuiltInPermission.GetTokenIndex() { return UrlIdentityPermission.GetTokenIndex(); } internal static int GetTokenIndex() { return BuiltInPermissionIndex.UrlIdentityPermissionIndex; } } }
using System; using System.Collections; using System.IO; using Raksha.Crypto.IO; using Raksha.Crypto; using Raksha.Crypto.Parameters; using Raksha.Security; using Raksha.Utilities; using Raksha.Utilities.Collections; namespace Raksha.Bcpg.OpenPgp { /// <remarks>General class to handle a PGP public key object.</remarks> public class PgpPublicKey { private static readonly int[] MasterKeyCertificationTypes = new int[] { PgpSignature.PositiveCertification, PgpSignature.CasualCertification, PgpSignature.NoCertification, PgpSignature.DefaultCertification }; private long keyId; private byte[] fingerprint; private int keyStrength; internal PublicKeyPacket publicPk; internal TrustPacket trustPk; internal IList keySigs = Platform.CreateArrayList(); internal IList ids = Platform.CreateArrayList(); internal IList idTrusts = Platform.CreateArrayList(); internal IList idSigs = Platform.CreateArrayList(); internal IList subSigs; private void Init() { IBcpgKey key = publicPk.Key; if (publicPk.Version <= 3) { RsaPublicBcpgKey rK = (RsaPublicBcpgKey) key; this.keyId = rK.Modulus.LongValue; try { IDigest digest = DigestUtilities.GetDigest("MD5"); byte[] bytes = rK.Modulus.ToByteArrayUnsigned(); digest.BlockUpdate(bytes, 0, bytes.Length); bytes = rK.PublicExponent.ToByteArrayUnsigned(); digest.BlockUpdate(bytes, 0, bytes.Length); this.fingerprint = DigestUtilities.DoFinal(digest); } //catch (NoSuchAlgorithmException) catch (Exception e) { throw new IOException("can't find MD5", e); } this.keyStrength = rK.Modulus.BitLength; } else { byte[] kBytes = publicPk.GetEncodedContents(); try { IDigest digest = DigestUtilities.GetDigest("SHA1"); digest.Update(0x99); digest.Update((byte)(kBytes.Length >> 8)); digest.Update((byte)kBytes.Length); digest.BlockUpdate(kBytes, 0, kBytes.Length); this.fingerprint = DigestUtilities.DoFinal(digest); } catch (Exception e) { throw new IOException("can't find SHA1", e); } this.keyId = (long)(((ulong)fingerprint[fingerprint.Length - 8] << 56) | ((ulong)fingerprint[fingerprint.Length - 7] << 48) | ((ulong)fingerprint[fingerprint.Length - 6] << 40) | ((ulong)fingerprint[fingerprint.Length - 5] << 32) | ((ulong)fingerprint[fingerprint.Length - 4] << 24) | ((ulong)fingerprint[fingerprint.Length - 3] << 16) | ((ulong)fingerprint[fingerprint.Length - 2] << 8) | (ulong)fingerprint[fingerprint.Length - 1]); if (key is RsaPublicBcpgKey) { this.keyStrength = ((RsaPublicBcpgKey)key).Modulus.BitLength; } else if (key is DsaPublicBcpgKey) { this.keyStrength = ((DsaPublicBcpgKey)key).P.BitLength; } else if (key is ElGamalPublicBcpgKey) { this.keyStrength = ((ElGamalPublicBcpgKey)key).P.BitLength; } } } /// <summary> /// Create a PgpPublicKey from the passed in lightweight one. /// </summary> /// <remarks> /// Note: the time passed in affects the value of the key's keyId, so you probably only want /// to do this once for a lightweight key, or make sure you keep track of the time you used. /// </remarks> /// <param name="algorithm">Asymmetric algorithm type representing the public key.</param> /// <param name="pubKey">Actual public key to associate.</param> /// <param name="time">Date of creation.</param> /// <exception cref="ArgumentException">If <c>pubKey</c> is not public.</exception> /// <exception cref="PgpException">On key creation problem.</exception> public PgpPublicKey( PublicKeyAlgorithmTag algorithm, AsymmetricKeyParameter pubKey, DateTime time) { if (pubKey.IsPrivate) throw new ArgumentException("Expected a public key", "pubKey"); IBcpgKey bcpgKey; if (pubKey is RsaKeyParameters) { RsaKeyParameters rK = (RsaKeyParameters) pubKey; bcpgKey = new RsaPublicBcpgKey(rK.Modulus, rK.Exponent); } else if (pubKey is DsaPublicKeyParameters) { DsaPublicKeyParameters dK = (DsaPublicKeyParameters) pubKey; DsaParameters dP = dK.Parameters; bcpgKey = new DsaPublicBcpgKey(dP.P, dP.Q, dP.G, dK.Y); } else if (pubKey is ElGamalPublicKeyParameters) { ElGamalPublicKeyParameters eK = (ElGamalPublicKeyParameters) pubKey; ElGamalParameters eS = eK.Parameters; bcpgKey = new ElGamalPublicBcpgKey(eS.P, eS.G, eK.Y); } else { throw new PgpException("unknown key class"); } this.publicPk = new PublicKeyPacket(algorithm, time, bcpgKey); this.ids = Platform.CreateArrayList(); this.idSigs = Platform.CreateArrayList(); try { Init(); } catch (IOException e) { throw new PgpException("exception calculating keyId", e); } } /// <summary>Constructor for a sub-key.</summary> internal PgpPublicKey( PublicKeyPacket publicPk, TrustPacket trustPk, IList sigs) { this.publicPk = publicPk; this.trustPk = trustPk; this.subSigs = sigs; Init(); } internal PgpPublicKey( PgpPublicKey key, TrustPacket trust, IList subSigs) { this.publicPk = key.publicPk; this.trustPk = trust; this.subSigs = subSigs; this.fingerprint = key.fingerprint; this.keyId = key.keyId; this.keyStrength = key.keyStrength; } /// <summary>Copy constructor.</summary> /// <param name="pubKey">The public key to copy.</param> internal PgpPublicKey( PgpPublicKey pubKey) { this.publicPk = pubKey.publicPk; this.keySigs = Platform.CreateArrayList(pubKey.keySigs); this.ids = Platform.CreateArrayList(pubKey.ids); this.idTrusts = Platform.CreateArrayList(pubKey.idTrusts); this.idSigs = Platform.CreateArrayList(pubKey.idSigs.Count); for (int i = 0; i != pubKey.idSigs.Count; i++) { this.idSigs.Add(Platform.CreateArrayList((IList)pubKey.idSigs[i])); } if (pubKey.subSigs != null) { this.subSigs = Platform.CreateArrayList(pubKey.subSigs.Count); for (int i = 0; i != pubKey.subSigs.Count; i++) { this.subSigs.Add(pubKey.subSigs[i]); } } this.fingerprint = pubKey.fingerprint; this.keyId = pubKey.keyId; this.keyStrength = pubKey.keyStrength; } internal PgpPublicKey( PublicKeyPacket publicPk, TrustPacket trustPk, IList keySigs, IList ids, IList idTrusts, IList idSigs) { this.publicPk = publicPk; this.trustPk = trustPk; this.keySigs = keySigs; this.ids = ids; this.idTrusts = idTrusts; this.idSigs = idSigs; Init(); } internal PgpPublicKey( PublicKeyPacket publicPk, IList ids, IList idSigs) { this.publicPk = publicPk; this.ids = ids; this.idSigs = idSigs; Init(); } /// <summary>The version of this key.</summary> public int Version { get { return publicPk.Version; } } /// <summary>The creation time of this key.</summary> public DateTime CreationTime { get { return publicPk.GetTime(); } } /// <summary>The number of valid days from creation time - zero means no expiry.</summary> public int ValidDays { get { if (publicPk.Version > 3) { return (int)(GetValidSeconds() / (24 * 60 * 60)); } return publicPk.ValidDays; } } /// <summary>Return the trust data associated with the public key, if present.</summary> /// <returns>A byte array with trust data, null otherwise.</returns> public byte[] GetTrustData() { if (trustPk == null) { return null; } return trustPk.GetLevelAndTrustAmount(); } /// <summary>The number of valid seconds from creation time - zero means no expiry.</summary> public long GetValidSeconds() { if (publicPk.Version > 3) { if (IsMasterKey) { for (int i = 0; i != MasterKeyCertificationTypes.Length; i++) { long seconds = GetExpirationTimeFromSig(true, MasterKeyCertificationTypes[i]); if (seconds >= 0) { return seconds; } } } else { long seconds = GetExpirationTimeFromSig(false, PgpSignature.SubkeyBinding); if (seconds >= 0) { return seconds; } } return 0; } return (long) publicPk.ValidDays * 24 * 60 * 60; } private long GetExpirationTimeFromSig( bool selfSigned, int signatureType) { foreach (PgpSignature sig in GetSignaturesOfType(signatureType)) { if (!selfSigned || sig.KeyId == KeyId) { PgpSignatureSubpacketVector hashed = sig.GetHashedSubPackets(); if (hashed != null) { return hashed.GetKeyExpirationTime(); } return 0; } } return -1; } /// <summary>The keyId associated with the public key.</summary> public long KeyId { get { return keyId; } } /// <summary>The fingerprint of the key</summary> public byte[] GetFingerprint() { return (byte[]) fingerprint.Clone(); } /// <summary> /// Check if this key has an algorithm type that makes it suitable to use for encryption. /// </summary> /// <remarks> /// Note: with version 4 keys KeyFlags subpackets should also be considered when present for /// determining the preferred use of the key. /// </remarks> /// <returns> /// <c>true</c> if this key algorithm is suitable for encryption. /// </returns> public bool IsEncryptionKey { get { switch (publicPk.Algorithm) { case PublicKeyAlgorithmTag.ElGamalEncrypt: case PublicKeyAlgorithmTag.ElGamalGeneral: case PublicKeyAlgorithmTag.RsaEncrypt: case PublicKeyAlgorithmTag.RsaGeneral: return true; default: return false; } } } /// <summary>True, if this is a master key.</summary> public bool IsMasterKey { get { return subSigs == null; } } /// <summary>The algorithm code associated with the public key.</summary> public PublicKeyAlgorithmTag Algorithm { get { return publicPk.Algorithm; } } /// <summary>The strength of the key in bits.</summary> public int BitStrength { get { return keyStrength; } } /// <summary>The public key contained in the object.</summary> /// <returns>A lightweight public key.</returns> /// <exception cref="PgpException">If the key algorithm is not recognised.</exception> public AsymmetricKeyParameter GetKey() { try { switch (publicPk.Algorithm) { case PublicKeyAlgorithmTag.RsaEncrypt: case PublicKeyAlgorithmTag.RsaGeneral: case PublicKeyAlgorithmTag.RsaSign: RsaPublicBcpgKey rsaK = (RsaPublicBcpgKey) publicPk.Key; return new RsaKeyParameters(false, rsaK.Modulus, rsaK.PublicExponent); case PublicKeyAlgorithmTag.Dsa: DsaPublicBcpgKey dsaK = (DsaPublicBcpgKey) publicPk.Key; return new DsaPublicKeyParameters(dsaK.Y, new DsaParameters(dsaK.P, dsaK.Q, dsaK.G)); case PublicKeyAlgorithmTag.ElGamalEncrypt: case PublicKeyAlgorithmTag.ElGamalGeneral: ElGamalPublicBcpgKey elK = (ElGamalPublicBcpgKey) publicPk.Key; return new ElGamalPublicKeyParameters(elK.Y, new ElGamalParameters(elK.P, elK.G)); default: throw new PgpException("unknown public key algorithm encountered"); } } catch (PgpException e) { throw e; } catch (Exception e) { throw new PgpException("exception constructing public key", e); } } /// <summary>Allows enumeration of any user IDs associated with the key.</summary> /// <returns>An <c>IEnumerable</c> of <c>string</c> objects.</returns> public IEnumerable GetUserIds() { IList temp = Platform.CreateArrayList(); foreach (object o in ids) { if (o is string) { temp.Add(o); } } return new EnumerableProxy(temp); } /// <summary>Allows enumeration of any user attribute vectors associated with the key.</summary> /// <returns>An <c>IEnumerable</c> of <c>PgpUserAttributeSubpacketVector</c> objects.</returns> public IEnumerable GetUserAttributes() { IList temp = Platform.CreateArrayList(); foreach (object o in ids) { if (o is PgpUserAttributeSubpacketVector) { temp.Add(o); } } return new EnumerableProxy(temp); } /// <summary>Allows enumeration of any signatures associated with the passed in id.</summary> /// <param name="id">The ID to be matched.</param> /// <returns>An <c>IEnumerable</c> of <c>PgpSignature</c> objects.</returns> public IEnumerable GetSignaturesForId( string id) { if (id == null) throw new ArgumentNullException("id"); for (int i = 0; i != ids.Count; i++) { if (id.Equals(ids[i])) { return new EnumerableProxy((IList)idSigs[i]); } } return null; } /// <summary>Allows enumeration of signatures associated with the passed in user attributes.</summary> /// <param name="userAttributes">The vector of user attributes to be matched.</param> /// <returns>An <c>IEnumerable</c> of <c>PgpSignature</c> objects.</returns> public IEnumerable GetSignaturesForUserAttribute( PgpUserAttributeSubpacketVector userAttributes) { for (int i = 0; i != ids.Count; i++) { if (userAttributes.Equals(ids[i])) { return new EnumerableProxy((IList) idSigs[i]); } } return null; } /// <summary>Allows enumeration of signatures of the passed in type that are on this key.</summary> /// <param name="signatureType">The type of the signature to be returned.</param> /// <returns>An <c>IEnumerable</c> of <c>PgpSignature</c> objects.</returns> public IEnumerable GetSignaturesOfType( int signatureType) { IList temp = Platform.CreateArrayList(); foreach (PgpSignature sig in GetSignatures()) { if (sig.SignatureType == signatureType) { temp.Add(sig); } } return new EnumerableProxy(temp); } /// <summary>Allows enumeration of all signatures/certifications associated with this key.</summary> /// <returns>An <c>IEnumerable</c> with all signatures/certifications.</returns> public IEnumerable GetSignatures() { IList sigs; if (subSigs != null) { sigs = subSigs; } else { sigs = Platform.CreateArrayList(keySigs); foreach (ICollection extraSigs in idSigs) { CollectionUtilities.AddRange(sigs, extraSigs); } } return new EnumerableProxy(sigs); } public byte[] GetEncoded() { MemoryStream bOut = new MemoryStream(); Encode(bOut); return bOut.ToArray(); } public void Encode( Stream outStr) { BcpgOutputStream bcpgOut = BcpgOutputStream.Wrap(outStr); bcpgOut.WritePacket(publicPk); if (trustPk != null) { bcpgOut.WritePacket(trustPk); } if (subSigs == null) // not a sub-key { foreach (PgpSignature keySig in keySigs) { keySig.Encode(bcpgOut); } for (int i = 0; i != ids.Count; i++) { if (ids[i] is string) { string id = (string) ids[i]; bcpgOut.WritePacket(new UserIdPacket(id)); } else { PgpUserAttributeSubpacketVector v = (PgpUserAttributeSubpacketVector)ids[i]; bcpgOut.WritePacket(new UserAttributePacket(v.ToSubpacketArray())); } if (idTrusts[i] != null) { bcpgOut.WritePacket((ContainedPacket)idTrusts[i]); } foreach (PgpSignature sig in (IList) idSigs[i]) { sig.Encode(bcpgOut); } } } else { foreach (PgpSignature subSig in subSigs) { subSig.Encode(bcpgOut); } } } /// <summary>Check whether this (sub)key has a revocation signature on it.</summary> /// <returns>True, if this (sub)key has been revoked.</returns> public bool IsRevoked() { int ns = 0; bool revoked = false; if (IsMasterKey) // Master key { while (!revoked && (ns < keySigs.Count)) { if (((PgpSignature)keySigs[ns++]).SignatureType == PgpSignature.KeyRevocation) { revoked = true; } } } else // Sub-key { while (!revoked && (ns < subSigs.Count)) { if (((PgpSignature)subSigs[ns++]).SignatureType == PgpSignature.SubkeyRevocation) { revoked = true; } } } return revoked; } /// <summary>Add a certification for an id to the given public key.</summary> /// <param name="key">The key the certification is to be added to.</param> /// <param name="id">The ID the certification is associated with.</param> /// <param name="certification">The new certification.</param> /// <returns>The re-certified key.</returns> public static PgpPublicKey AddCertification( PgpPublicKey key, string id, PgpSignature certification) { return AddCert(key, id, certification); } /// <summary>Add a certification for the given UserAttributeSubpackets to the given public key.</summary> /// <param name="key">The key the certification is to be added to.</param> /// <param name="userAttributes">The attributes the certification is associated with.</param> /// <param name="certification">The new certification.</param> /// <returns>The re-certified key.</returns> public static PgpPublicKey AddCertification( PgpPublicKey key, PgpUserAttributeSubpacketVector userAttributes, PgpSignature certification) { return AddCert(key, userAttributes, certification); } private static PgpPublicKey AddCert( PgpPublicKey key, object id, PgpSignature certification) { PgpPublicKey returnKey = new PgpPublicKey(key); IList sigList = null; for (int i = 0; i != returnKey.ids.Count; i++) { if (id.Equals(returnKey.ids[i])) { sigList = (IList) returnKey.idSigs[i]; } } if (sigList != null) { sigList.Add(certification); } else { sigList = Platform.CreateArrayList(); sigList.Add(certification); returnKey.ids.Add(id); returnKey.idTrusts.Add(null); returnKey.idSigs.Add(sigList); } return returnKey; } /// <summary> /// Remove any certifications associated with a user attribute subpacket on a key. /// </summary> /// <param name="key">The key the certifications are to be removed from.</param> /// <param name="userAttributes">The attributes to be removed.</param> /// <returns> /// The re-certified key, or null if the user attribute subpacket was not found on the key. /// </returns> public static PgpPublicKey RemoveCertification( PgpPublicKey key, PgpUserAttributeSubpacketVector userAttributes) { return RemoveCert(key, userAttributes); } /// <summary>Remove any certifications associated with a given ID on a key.</summary> /// <param name="key">The key the certifications are to be removed from.</param> /// <param name="id">The ID that is to be removed.</param> /// <returns>The re-certified key, or null if the ID was not found on the key.</returns> public static PgpPublicKey RemoveCertification( PgpPublicKey key, string id) { return RemoveCert(key, id); } private static PgpPublicKey RemoveCert( PgpPublicKey key, object id) { PgpPublicKey returnKey = new PgpPublicKey(key); bool found = false; for (int i = 0; i < returnKey.ids.Count; i++) { if (id.Equals(returnKey.ids[i])) { found = true; returnKey.ids.RemoveAt(i); returnKey.idTrusts.RemoveAt(i); returnKey.idSigs.RemoveAt(i); } } return found ? returnKey : null; } /// <summary>Remove a certification associated with a given ID on a key.</summary> /// <param name="key">The key the certifications are to be removed from.</param> /// <param name="id">The ID that the certfication is to be removed from.</param> /// <param name="certification">The certfication to be removed.</param> /// <returns>The re-certified key, or null if the certification was not found.</returns> public static PgpPublicKey RemoveCertification( PgpPublicKey key, string id, PgpSignature certification) { return RemoveCert(key, id, certification); } /// <summary>Remove a certification associated with a given user attributes on a key.</summary> /// <param name="key">The key the certifications are to be removed from.</param> /// <param name="userAttributes">The user attributes that the certfication is to be removed from.</param> /// <param name="certification">The certification to be removed.</param> /// <returns>The re-certified key, or null if the certification was not found.</returns> public static PgpPublicKey RemoveCertification( PgpPublicKey key, PgpUserAttributeSubpacketVector userAttributes, PgpSignature certification) { return RemoveCert(key, userAttributes, certification); } private static PgpPublicKey RemoveCert( PgpPublicKey key, object id, PgpSignature certification) { PgpPublicKey returnKey = new PgpPublicKey(key); bool found = false; for (int i = 0; i < returnKey.ids.Count; i++) { if (id.Equals(returnKey.ids[i])) { IList certs = (IList) returnKey.idSigs[i]; found = certs.Contains(certification); if (found) { certs.Remove(certification); } } } return found ? returnKey : null; } /// <summary>Add a revocation or some other key certification to a key.</summary> /// <param name="key">The key the revocation is to be added to.</param> /// <param name="certification">The key signature to be added.</param> /// <returns>The new changed public key object.</returns> public static PgpPublicKey AddCertification( PgpPublicKey key, PgpSignature certification) { if (key.IsMasterKey) { if (certification.SignatureType == PgpSignature.SubkeyRevocation) { throw new ArgumentException("signature type incorrect for master key revocation."); } } else { if (certification.SignatureType == PgpSignature.KeyRevocation) { throw new ArgumentException("signature type incorrect for sub-key revocation."); } } PgpPublicKey returnKey = new PgpPublicKey(key); if (returnKey.subSigs != null) { returnKey.subSigs.Add(certification); } else { returnKey.keySigs.Add(certification); } return returnKey; } /// <summary>Remove a certification from the key.</summary> /// <param name="key">The key the certifications are to be removed from.</param> /// <param name="certification">The certfication to be removed.</param> /// <returns>The modified key, null if the certification was not found.</returns> public static PgpPublicKey RemoveCertification( PgpPublicKey key, PgpSignature certification) { PgpPublicKey returnKey = new PgpPublicKey(key); IList sigs = returnKey.subSigs != null ? returnKey.subSigs : returnKey.keySigs; // bool found = sigs.Remove(certification); int pos = sigs.IndexOf(certification); bool found = pos >= 0; if (found) { sigs.RemoveAt(pos); } else { foreach (String id in key.GetUserIds()) { foreach (object sig in key.GetSignaturesForId(id)) { // TODO Is this the right type of equality test? if (certification == sig) { found = true; returnKey = PgpPublicKey.RemoveCertification(returnKey, id, certification); } } } if (!found) { foreach (PgpUserAttributeSubpacketVector id in key.GetUserAttributes()) { foreach (object sig in key.GetSignaturesForUserAttribute(id)) { // TODO Is this the right type of equality test? if (certification == sig) { found = true; returnKey = PgpPublicKey.RemoveCertification(returnKey, id, certification); } } } } } return returnKey; } } }
/********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Management.Automation; using System.Management.Automation.Internal; using System.Security; using System.Text; using System.Xml; using Dbg = System.Management.Automation.Diagnostics; namespace Microsoft.PowerShell.Commands { /// <summary> /// implementation for the Export-Clixml command /// </summary> [Cmdlet(VerbsData.Export, "Clixml", SupportsShouldProcess = true, DefaultParameterSetName = "ByPath", HelpUri = "http://go.microsoft.com/fwlink/?LinkID=113297")] public sealed class ExportClixmlCommand : PSCmdlet, IDisposable { #region Command Line Parameters // If a Passthru parameter is added, the SupportsShouldProcess // implementation will need to be modified. /// <summary> /// Depth of serialization /// </summary> [Parameter] [ValidateRange(1, int.MaxValue)] public int Depth { get; set; } = 0; /// <summary> /// mandatory file name to write to /// </summary> [Parameter(Mandatory = true, Position = 0, ParameterSetName = "ByPath")] public string Path { get; set; } /// <summary> /// mandatory file name to write to /// </summary> [Parameter(Mandatory = true, ParameterSetName = "ByLiteralPath")] [Alias("PSPath")] public string LiteralPath { get { return Path; } set { Path = value; _isLiteralPath = true; } } private bool _isLiteralPath = false; /// <summary> /// Input object to be exported /// </summary> [Parameter(ValueFromPipeline = true, Mandatory = true)] [AllowNull] public PSObject InputObject { get; set; } /// <summary> /// Property that sets force parameter. /// </summary> [Parameter] public SwitchParameter Force { get { return _force; } set { _force = value; } } private bool _force; /// <summary> /// Property that prevents file overwrite. /// </summary> [Parameter] [Alias("NoOverwrite")] public SwitchParameter NoClobber { get { return _noclobber; } set { _noclobber = value; } } private bool _noclobber; /// <summary> /// Encoding optional flag /// </summary> /// [Parameter] [ValidateSetAttribute(new string[] { "Unicode", "UTF7", "UTF8", "ASCII", "UTF32", "BigEndianUnicode", "Default", "OEM" })] public string Encoding { get; set; } = "Unicode"; #endregion Command Line Parameters #region Overrides /// <summary> /// BeginProcessing override /// </summary> protected override void BeginProcessing() { CreateFileStream(); } /// <summary> /// /// </summary> protected override void ProcessRecord() { if (null != _serializer) { _serializer.Serialize(InputObject); _xw.Flush(); } } /// <summary> /// /// </summary> protected override void EndProcessing() { if (_serializer != null) { _serializer.Done(); _serializer = null; } CleanUp(); } /// <summary> /// /// </summary> protected override void StopProcessing() { base.StopProcessing(); _serializer.Stop(); } #endregion Overrides #region file /// <summary> /// handle to file stream /// </summary> private FileStream _fs; /// <summary> /// stream writer used to write to file /// </summary> private XmlWriter _xw; /// <summary> /// Serializer used for serialization /// </summary> private Serializer _serializer; /// <summary> /// FileInfo of file to clear read-only flag when operation is complete /// </summary> private FileInfo _readOnlyFileInfo = null; private void CreateFileStream() { Dbg.Assert(Path != null, "FileName is mandatory parameter"); if (!ShouldProcess(Path)) return; StreamWriter sw; PathUtils.MasterStreamOpen( this, this.Path, this.Encoding, false, // default encoding false, // append this.Force, this.NoClobber, out _fs, out sw, out _readOnlyFileInfo, _isLiteralPath ); // create xml writer XmlWriterSettings xmlSettings = new XmlWriterSettings(); xmlSettings.CloseOutput = true; xmlSettings.Encoding = sw.Encoding; xmlSettings.Indent = true; xmlSettings.OmitXmlDeclaration = true; _xw = XmlWriter.Create(sw, xmlSettings); if (Depth == 0) { _serializer = new Serializer(_xw); } else { _serializer = new Serializer(_xw, Depth, true); } } private void CleanUp() { if (_fs != null) { if (_xw != null) { _xw.Dispose(); _xw = null; } _fs.Dispose(); _fs = null; } // reset the read-only attribute if (null != _readOnlyFileInfo) { _readOnlyFileInfo.Attributes |= FileAttributes.ReadOnly; _readOnlyFileInfo = null; } } #endregion file #region IDisposable Members /// <summary> /// Set to true when object is disposed /// </summary> private bool _disposed; /// <summary> /// public dispose method /// </summary> public void Dispose() { if (_disposed == false) { CleanUp(); } _disposed = true; } #endregion IDisposable Members } /// <summary> /// Implements Import-Clixml command /// </summary> [Cmdlet(VerbsData.Import, "Clixml", SupportsPaging = true, DefaultParameterSetName = "ByPath", HelpUri = "http://go.microsoft.com/fwlink/?LinkID=113340")] public sealed class ImportClixmlCommand : PSCmdlet, IDisposable { #region Command Line Parameters /// <summary> /// mandatory file name to read from /// </summary> [Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, ParameterSetName = "ByPath")] public String[] Path { get; set; } /// <summary> /// mandatory file name to read from /// </summary> [Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, ParameterSetName = "ByLiteralPath")] [Alias("PSPath")] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public String[] LiteralPath { get { return Path; } set { Path = value; _isLiteralPath = true; } } private bool _isLiteralPath = false; #endregion Command Line Parameters #region IDisposable Members private bool _disposed = false; /// <summary> /// public dispose method /// </summary> public void Dispose() { if (!_disposed) { GC.SuppressFinalize(this); if (_helper != null) { _helper.Dispose(); _helper = null; } _disposed = true; } } #endregion private ImportXmlHelper _helper; /// <summary> /// ProcessRecord overload /// </summary> protected override void ProcessRecord() { if (Path != null) { foreach (string path in Path) { _helper = new ImportXmlHelper(path, this, _isLiteralPath); _helper.Import(); } } } /// <summary> /// /// </summary> protected override void StopProcessing() { base.StopProcessing(); _helper.Stop(); } } /// <summary> /// implementation for the convertto-xml command /// </summary> [Cmdlet(VerbsData.ConvertTo, "Xml", SupportsShouldProcess = false, HelpUri = "http://go.microsoft.com/fwlink/?LinkID=135204", RemotingCapability = RemotingCapability.None)] [OutputType(typeof(XmlDocument), typeof(String))] public sealed class ConvertToXmlCommand : PSCmdlet, IDisposable { #region Command Line Parameters /// <summary> /// Depth of serialization /// </summary> [Parameter(HelpMessage = "Specifies how many levels of contained objects should be included in the XML representation")] [ValidateRange(1, int.MaxValue)] public int Depth { get; set; } = 0; /// <summary> /// Input Object which is written to XML format /// </summary> [Parameter(Position = 0, ValueFromPipeline = true, Mandatory = true)] [AllowNull] public PSObject InputObject { get; set; } /// <summary> /// Property that sets NoTypeInformation parameter. /// </summary> [Parameter(HelpMessage = "Specifies not to include the Type information in the XML representation")] public SwitchParameter NoTypeInformation { get { return _notypeinformation; } set { _notypeinformation = value; } } private bool _notypeinformation; /// <summary> /// Property that sets As parameter. /// </summary> [Parameter] [ValidateNotNullOrEmpty] [ValidateSet("Stream", "String", "Document")] public string As { get; set; } = "Document"; #endregion Command Line Parameters #region Overrides /// <summary> /// BeginProcessing override /// </summary> protected override void BeginProcessing() { if (!As.Equals("Stream", StringComparison.OrdinalIgnoreCase)) { CreateMemoryStream(); } else { WriteObject(string.Format(CultureInfo.InvariantCulture, "<?xml version=\"1.0\" encoding=\"{0}\"?>", Encoding.UTF8.WebName)); WriteObject("<Objects>"); } } /// <summary> /// override ProcessRecord /// </summary> protected override void ProcessRecord() { if (As.Equals("Stream", StringComparison.OrdinalIgnoreCase)) { CreateMemoryStream(); if (null != _serializer) _serializer.SerializeAsStream(InputObject); if (null != _serializer) { _serializer.DoneAsStream(); _serializer = null; } //Loading to the XML Document _ms.Position = 0; StreamReader read = new StreamReader(_ms); string data = read.ReadToEnd(); WriteObject(data); //Cleanup CleanUp(); } else { if (null != _serializer) _serializer.Serialize(InputObject); } } /// <summary> /// /// </summary> protected override void EndProcessing() { if (null != _serializer) { _serializer.Done(); _serializer = null; } if (As.Equals("Stream", StringComparison.OrdinalIgnoreCase)) { WriteObject("</Objects>"); } else { //Loading to the XML Document _ms.Position = 0; if (As.Equals("Document", StringComparison.OrdinalIgnoreCase)) { // this is a trusted xml doc - the cmdlet generated the doc into a private memory stream XmlDocument xmldoc = new XmlDocument(); xmldoc.Load(_ms); WriteObject(xmldoc); } else if (As.Equals("String", StringComparison.OrdinalIgnoreCase)) { StreamReader read = new StreamReader(_ms); string data = read.ReadToEnd(); WriteObject(data); } } //Cleaning up CleanUp(); } /// <summary> /// /// </summary> protected override void StopProcessing() { _serializer.Stop(); } #endregion Overrides #region memory /// <summary> /// XmlText writer /// </summary> private XmlWriter _xw; /// <summary> /// Serializer used for serialization /// </summary> private CustomSerialization _serializer; /// <summary> ///Memory Stream used for serialization /// </summary> private MemoryStream _ms; private void CreateMemoryStream() { // Memory Stream _ms = new MemoryStream(); // We use XmlTextWriter originally: // _xw = new XmlTextWriter(_ms, null); // _xw.Formatting = Formatting.Indented; // This implies the following settings: // - Encoding is null -> use the default encoding 'UTF-8' when creating the writer from the stream; // - XmlTextWriter closes the underlying stream / writer when 'Close/Dispose' is called on it; // - Use the default indentation setting -- two space characters. // // We configure the same settings in XmlWriterSettings when refactoring this code to use XmlWriter: // - The default encoding used by XmlWriterSettings is 'UTF-8', but we call it out explicitly anyway; // - Set CloseOutput to true; // - Set Indent to true, and by default, IndentChars is two space characters. // // We use XmlWriterSettings.OmitXmlDeclaration instead of XmlWriter.WriteStartDocument because the // xml writer created by calling XmlWriter.Create(Stream, XmlWriterSettings) will write out the xml // declaration even without calling WriteStartDocument(). var xmlSettings = new XmlWriterSettings(); xmlSettings.Encoding = Encoding.UTF8; xmlSettings.CloseOutput = true; xmlSettings.Indent = true; if (As.Equals("Stream", StringComparison.OrdinalIgnoreCase)) { // Omit xml declaration in this case becuase we will write out the declaration string in BeginProcess. xmlSettings.OmitXmlDeclaration = true; } _xw = XmlWriter.Create(_ms, xmlSettings); if (Depth == 0) { _serializer = new CustomSerialization(_xw, _notypeinformation); } else { _serializer = new CustomSerialization(_xw, _notypeinformation, Depth); } } /// <summary> ///Cleaning up the MemoryStream /// </summary> private void CleanUp() { if (_ms != null) { if (_xw != null) { _xw.Dispose(); _xw = null; } _ms.Dispose(); _ms = null; } } #endregion memory #region IDisposable Members /// <summary> /// Set to true when object is disposed /// </summary> private bool _disposed; /// <summary> /// public dispose method /// </summary> public void Dispose() { if (_disposed == false) { CleanUp(); } _disposed = true; } #endregion IDisposable Members } /// <summary> /// Helper class to import single XML file /// </summary> internal class ImportXmlHelper : IDisposable { #region constructor /// <summary> /// XML file to import /// </summary> private readonly string _path; /// <summary> /// Reference to cmdlet which is using this helper class /// </summary> private readonly PSCmdlet _cmdlet; private bool _isLiteralPath; internal ImportXmlHelper(string fileName, PSCmdlet cmdlet, bool isLiteralPath) { if (fileName == null) { throw PSTraceSource.NewArgumentNullException("fileName"); } if (cmdlet == null) { throw PSTraceSource.NewArgumentNullException("cmdlet"); } _path = fileName; _cmdlet = cmdlet; _isLiteralPath = isLiteralPath; } #endregion constructor #region file /// <summary> /// handle to file stream /// </summary> internal FileStream _fs; /// <summary> /// XmlReader used to read file /// </summary> internal XmlReader _xr; private static XmlReader CreateXmlReader(Stream stream) { TextReader textReader = new StreamReader(stream); // skip #< CLIXML directive const string cliXmlDirective = "#< CLIXML"; if (textReader.Peek() == (int)cliXmlDirective[0]) { string line = textReader.ReadLine(); if (!line.Equals(cliXmlDirective, StringComparison.Ordinal)) { stream.Seek(0, SeekOrigin.Begin); } } return XmlReader.Create(textReader, InternalDeserializer.XmlReaderSettingsForCliXml); } internal void CreateFileStream() { _fs = PathUtils.OpenFileStream(_path, _cmdlet, _isLiteralPath); _xr = CreateXmlReader(_fs); } private void CleanUp() { if (_fs != null) { _fs.Dispose(); _fs = null; } } #endregion file #region IDisposable Members /// <summary> /// Set to true when object is disposed /// </summary> private bool _disposed; /// <summary> /// public dispose method /// </summary> public void Dispose() { if (_disposed == false) { CleanUp(); } _disposed = true; GC.SuppressFinalize(this); } #endregion IDisposable Members private Deserializer _deserializer; internal void Import() { CreateFileStream(); _deserializer = new Deserializer(_xr); // If total count has been requested, return a dummy object with zero confidence if (_cmdlet.PagingParameters.IncludeTotalCount) { PSObject totalCount = _cmdlet.PagingParameters.NewTotalCount(0, 0); _cmdlet.WriteObject(totalCount); } ulong skip = _cmdlet.PagingParameters.Skip; ulong first = _cmdlet.PagingParameters.First; // if paging is not specified then keep the old V2 behavior if (skip == 0 && first == ulong.MaxValue) { ulong item = 0; while (!_deserializer.Done()) { object result = _deserializer.Deserialize(); if (item++ < skip) continue; if (first == 0) break; _cmdlet.WriteObject(result); first--; } } // else try to flatten the output if possible else { ulong skipped = 0; ulong count = 0; while (!_deserializer.Done() && count < first) { object result = _deserializer.Deserialize(); PSObject psObject = result as PSObject; if (psObject == null && skipped++ >= skip) { count++; _cmdlet.WriteObject(result); continue; } ICollection c = psObject.BaseObject as ICollection; if (c != null) { foreach (object o in c) { if (count >= first) break; if (skipped++ >= skip) { count++; _cmdlet.WriteObject(o); } } } else { if (skipped++ >= skip) { count++; _cmdlet.WriteObject(result); } } } } } internal void Stop() { if (_deserializer != null) { _deserializer.Stop(); } } } // ImportXmlHelper #region Select-Xml ///<summary> ///This cmdlet is used to search an xml document based on the XPath Query. ///</summary> [Cmdlet(VerbsCommon.Select, "Xml", DefaultParameterSetName = "Xml", HelpUri = "http://go.microsoft.com/fwlink/?LinkID=135255")] [OutputType(typeof(SelectXmlInfo))] public class SelectXmlCommand : PSCmdlet { # region parameters /// <summary> /// Specifies the path which contains the xml files. The default is the current /// user directory /// </summary> [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] [Parameter(Position = 1, Mandatory = true, ValueFromPipelineByPropertyName = true, ParameterSetName = "Path")] [ValidateNotNullOrEmpty] public String[] Path { get; set; } /// <summary> /// Specifies the literal path which contains the xml files. The default is the current /// user directory /// </summary> [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] [Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, ParameterSetName = "LiteralPath")] [ValidateNotNullOrEmpty] [Alias("PSPath")] public String[] LiteralPath { get { return Path; } set { Path = value; _isLiteralPath = true; } } private bool _isLiteralPath = false; /// <summary> /// The following is the definition of the input parameter "XML". /// Specifies the xml Node /// </summary> [Parameter(Position = 1, Mandatory = true, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true, ParameterSetName = "Xml")] [ValidateNotNullOrEmpty] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] [SuppressMessage("Microsoft.Design", "CA1059:MembersShouldNotExposeCertainConcreteTypes", MessageId = "System.Xml.XmlNode")] [Alias("Node")] public System.Xml.XmlNode[] Xml { get; set; } /// <summary> /// The following is the definition of the input parameter in string format. /// Specifies the string format of a fully qualified xml. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] [Parameter(Mandatory = true, ValueFromPipeline = true, ParameterSetName = "Content")] [ValidateNotNullOrEmpty] public string[] Content { get; set; } /// <summary> /// The following is the definition of the input parameter "Xpath". /// Specifies the String in XPath language syntax. The xml documents will be /// searched for the nodes/values represented by this parameter. /// </summary> [Parameter(Mandatory = true, Position = 0)] [ValidateNotNullOrEmpty] public string XPath { get; set; } /// <summary> /// The following definition used to specify the /// NameSpace of xml. /// </summary> [Parameter] [ValidateNotNullOrEmpty] [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public Hashtable Namespace { get; set; } # endregion parameters # region private private void WriteResults(XmlNodeList foundXmlNodes, string filePath) { Dbg.Assert(foundXmlNodes != null, "Caller should verify foundNodes != null"); foreach (XmlNode foundXmlNode in foundXmlNodes) { SelectXmlInfo selectXmlInfo = new SelectXmlInfo(); selectXmlInfo.Node = foundXmlNode; selectXmlInfo.Pattern = XPath; selectXmlInfo.Path = filePath; this.WriteObject(selectXmlInfo); } } private void ProcessXmlNode(XmlNode xmlNode, string filePath) { Dbg.Assert(xmlNode != null, "Caller should verify xmlNode != null"); XmlNodeList xList; if (Namespace != null) { XmlNamespaceManager xmlns = AddNameSpaceTable(this.ParameterSetName, xmlNode as XmlDocument, Namespace); xList = xmlNode.SelectNodes(XPath, xmlns); } else { xList = xmlNode.SelectNodes(XPath); } this.WriteResults(xList, filePath); } private void ProcessXmlFile(string filePath) { //Cannot use ImportXMLHelper because it will throw terminating error which will //not be inline with Select-String //So doing self processing of the file. try { XmlDocument xmlDocument = InternalDeserializer.LoadUnsafeXmlDocument( new FileInfo(filePath), true, /* preserve whitespace, comments, etc. */ null); /* default maxCharactersInDocument */ this.ProcessXmlNode(xmlDocument, filePath); } catch (NotSupportedException notSupportedException) { this.WriteFileReadError(filePath, notSupportedException); } catch (IOException ioException) { this.WriteFileReadError(filePath, ioException); } catch (SecurityException securityException) { this.WriteFileReadError(filePath, securityException); } catch (UnauthorizedAccessException unauthorizedAccessException) { this.WriteFileReadError(filePath, unauthorizedAccessException); } catch (XmlException xmlException) { this.WriteFileReadError(filePath, xmlException); } catch (InvalidOperationException invalidOperationException) { this.WriteFileReadError(filePath, invalidOperationException); } } private void WriteFileReadError(string filePath, Exception exception) { string errorMessage = string.Format( CultureInfo.InvariantCulture, // filePath is culture invariant, exception message is to be copied verbatim UtilityCommonStrings.FileReadError, filePath, exception.Message); ArgumentException argumentException = new ArgumentException(errorMessage, exception); ErrorRecord errorRecord = new ErrorRecord(argumentException, "ProcessingFile", ErrorCategory.InvalidArgument, filePath); this.WriteError(errorRecord); } private XmlNamespaceManager AddNameSpaceTable(string parametersetname, XmlDocument xDoc, Hashtable namespacetable) { XmlNamespaceManager xmlns; if (parametersetname.Equals("Xml")) { XmlNameTable xmlnt = new NameTable(); xmlns = new XmlNamespaceManager(xmlnt); } else { xmlns = new XmlNamespaceManager(xDoc.NameTable); } foreach (DictionaryEntry row in namespacetable) { try { xmlns.AddNamespace(row.Key.ToString(), row.Value.ToString()); } catch (NullReferenceException) { string message = StringUtil.Format(UtilityCommonStrings.SearchXMLPrefixNullError); InvalidOperationException e = new InvalidOperationException(message); ErrorRecord er = new ErrorRecord(e, "PrefixError", ErrorCategory.InvalidOperation, namespacetable); WriteError(er); } catch (ArgumentNullException) { string message = StringUtil.Format(UtilityCommonStrings.SearchXMLPrefixNullError); InvalidOperationException e = new InvalidOperationException(message); ErrorRecord er = new ErrorRecord(e, "PrefixError", ErrorCategory.InvalidOperation, namespacetable); WriteError(er); } } return xmlns; } # endregion private #region overrdies /// <summary> /// ProcessRecord method. /// </summary> protected override void ProcessRecord() { if (ParameterSetName.Equals("Xml", StringComparison.OrdinalIgnoreCase)) { foreach (XmlNode xmlNode in this.Xml) { ProcessXmlNode(xmlNode, string.Empty); } } else if ( (ParameterSetName.Equals("Path", StringComparison.OrdinalIgnoreCase) || (ParameterSetName.Equals("LiteralPath", StringComparison.OrdinalIgnoreCase)))) { //If any file not resolved, execution stops. this is to make consistent with select-string. List<string> fullresolvedPaths = new List<string>(); foreach (string fpath in Path) { if (_isLiteralPath) { string resolvedPath = GetUnresolvedProviderPathFromPSPath(fpath); fullresolvedPaths.Add(resolvedPath); } else { ProviderInfo provider; Collection<string> resolvedPaths = GetResolvedProviderPathFromPSPath(fpath, out provider); if (!provider.NameEquals(this.Context.ProviderNames.FileSystem)) { //Cannot open File error string message = StringUtil.Format(UtilityCommonStrings.FileOpenError, provider.FullName); InvalidOperationException e = new InvalidOperationException(message); ErrorRecord er = new ErrorRecord(e, "ProcessingFile", ErrorCategory.InvalidOperation, fpath); WriteError(er); continue; } fullresolvedPaths.AddRange(resolvedPaths); } } foreach (string file in fullresolvedPaths) { ProcessXmlFile(file); } } else if (ParameterSetName.Equals("Content", StringComparison.OrdinalIgnoreCase)) { foreach (string xmlstring in Content) { XmlDocument xmlDocument; try { xmlDocument = (XmlDocument)LanguagePrimitives.ConvertTo(xmlstring, typeof(XmlDocument), CultureInfo.InvariantCulture); } catch (PSInvalidCastException invalidCastException) { this.WriteError(invalidCastException.ErrorRecord); continue; } this.ProcessXmlNode(xmlDocument, string.Empty); } } else { Dbg.Assert(false, "Unrecognized parameterset"); } }//End ProcessRecord() #endregion overrides }//End Class /// <summary> /// The object returned by Select-Xml representing the result of a match. /// </summary> public sealed class SelectXmlInfo { /// <summary> /// If the object is InputObject, Input Stream is used. /// </summary> private const string inputStream = "InputStream"; private const string MatchFormat = "{0}:{1}"; private const string SimpleFormat = "{0}"; /// <summary> /// The XmlNode that matches search /// </summary> [SuppressMessage("Microsoft.Design", "CA1059:MembersShouldNotExposeCertainConcreteTypes", MessageId = "System.Xml.XmlNode")] public XmlNode Node { get; set; } /// <summary> /// The FileName from which the match is found. /// </summary> public string Path { get { return _path; } set { if (String.IsNullOrEmpty(value)) { _path = inputStream; } else { _path = value; } } } private string _path; /// <summary> /// The pattern used to search /// </summary> public string Pattern { get; set; } /// <summary> /// Returns the string representation of this object. The format /// depends on whether a path has been set for this object or not. /// </summary> /// <returns></returns> public override string ToString() { return ToString(null); } /// <summary> /// Return String representation of the object /// </summary> /// <param name="directory"></param> /// <returns></returns> private string ToString(string directory) { string displayPath = (directory != null) ? RelativePath(directory) : _path; return FormatLine(GetNodeText(), displayPath); } /// <summary> /// Returns the XmlNode Value or InnerXml. /// </summary> /// <returns></returns> internal string GetNodeText() { string nodeText = String.Empty; if (Node != null) { if (Node.Value != null) { nodeText = Node.Value.Trim(); } else { nodeText = Node.InnerXml.Trim(); } } return nodeText; } /// <summary> /// Returns the path of the matching file truncated relative to the <paramref name="directory"/> parameter. /// <remarks> /// For example, if the matching path was c:\foo\bar\baz.c and the directory argument was c:\foo /// the routine would return bar\baz.c /// </remarks> /// </summary> /// <param name="directory">The directory base the truncation on.</param> /// <returns>The relative path that was produced.</returns> private string RelativePath(string directory) { string relPath = _path; if (!relPath.Equals(inputStream)) { if (relPath.StartsWith(directory, StringComparison.CurrentCultureIgnoreCase)) { int offset = directory.Length; if (offset < relPath.Length) { if (directory[offset - 1] == '\\' || directory[offset - 1] == '/') relPath = relPath.Substring(offset); else if (relPath[offset] == '\\' || relPath[offset] == '/') relPath = relPath.Substring(offset + 1); } } } return relPath; } /// <summary> /// Formats a line for use in ToString. /// </summary> /// <param name="text"></param> /// <param name="displaypath"></param> /// <returns></returns> private string FormatLine(string text, string displaypath) { if (_path.Equals(inputStream)) { return StringUtil.Format(SimpleFormat, text); } else { return StringUtil.Format(MatchFormat, text, displaypath); } } } #endregion Select-Xml }
using System; using System.Collections.Generic; using System.Diagnostics; using BTDB.FieldHandler; using BTDB.StreamLayer; namespace BTDB.KVDBLayer.BTree { delegate IBTreeNode BuildBranchNodeGenerator(ref SpanReader reader); class BTreeBranch : IBTreeNode { readonly long _transactionId; byte[][] _keys; IBTreeNode[] _children; long[] _pairCounts; internal const int MaxChildren = 30; internal BTreeBranch(long transactionId, IBTreeNode node1, IBTreeNode node2) { _transactionId = transactionId; _children = new[] {node1, node2}; _keys = new[] {node2.GetLeftMostKey()}; var leftCount = node1.CalcKeyCount(); var rightCount = node2.CalcKeyCount(); _pairCounts = new[] {leftCount, leftCount + rightCount}; } BTreeBranch(long transactionId, byte[][] newKeys, IBTreeNode[] newChildren, long[] newPairCounts) { _transactionId = transactionId; _keys = newKeys; _children = newChildren; _pairCounts = newPairCounts; } public BTreeBranch(long transactionId, int count, ref SpanReader reader, BuildBranchNodeGenerator generator) { Debug.Assert(count > 0 && count <= MaxChildren); _transactionId = transactionId; _keys = new byte[count - 1][]; _pairCounts = new long[count]; _children = new IBTreeNode[count]; long pairs = 0; for (var i = 0; i < _children.Length; i++) { var child = generator(ref reader); _children[i] = child; pairs += child.CalcKeyCount(); _pairCounts[i] = pairs; if (i > 0) { _keys[i - 1] = child.GetLeftMostKey(); } } } int Find(in ReadOnlySpan<byte> key) { var left = 0; var right = _keys.Length; while (left < right) { var middle = (left + right) / 2; var currentKey = _keys[middle]; var result = key.SequenceCompareTo(currentKey); if (result < 0) { right = middle; } else { left = middle + 1; } } return left; } public void CreateOrUpdate(ref CreateOrUpdateCtx ctx) { var index = Find(ctx.Key); ctx.Stack!.Add(new NodeIdxPair {Node = this, Idx = index}); ctx.Depth++; _children[index].CreateOrUpdate(ref ctx); ctx.Depth--; var newBranch = this; if (ctx.Split) { ctx.Split = false; var newKeys = new byte[_children.Length][]; var newChildren = new IBTreeNode[_children.Length + 1]; var newPairCounts = new long[_children.Length + 1]; Array.Copy(_keys, 0, newKeys, 0, index); newKeys[index] = ctx.Node2!.GetLeftMostKey(); Array.Copy(_keys, index, newKeys, index + 1, _keys.Length - index); Array.Copy(_children, 0, newChildren, 0, index); newChildren[index] = ctx.Node1!; newChildren[index + 1] = ctx.Node2; Array.Copy(_children, index + 1, newChildren, index + 2, _children.Length - index - 1); Array.Copy(_pairCounts, newPairCounts, index); var previousPairCount = index > 0 ? newPairCounts[index - 1] : 0; for (var i = index; i < newPairCounts.Length; i++) { previousPairCount += newChildren[i].CalcKeyCount(); newPairCounts[i] = previousPairCount; } ctx.Node1 = null; ctx.Node2 = null; if (_children.Length < MaxChildren) { if (_transactionId != ctx.TransactionId) { newBranch = new BTreeBranch(ctx.TransactionId, newKeys, newChildren, newPairCounts); ctx.Node1 = newBranch; ctx.Update = true; } else { _keys = newKeys; _children = newChildren; _pairCounts = newPairCounts; } if (ctx.SplitInRight) index++; ctx.Stack![ctx.Depth] = new NodeIdxPair {Node = newBranch, Idx = index}; return; } if (ctx.SplitInRight) index++; ctx.Split = true; var keyCountLeft = (newChildren.Length + 1) / 2; var keyCountRight = newChildren.Length - keyCountLeft; var splitKeys = new byte[keyCountLeft - 1][]; var splitChildren = new IBTreeNode[keyCountLeft]; var splitPairCounts = new long[keyCountLeft]; Array.Copy(newKeys, splitKeys, splitKeys.Length); Array.Copy(newChildren, splitChildren, splitChildren.Length); Array.Copy(newPairCounts, splitPairCounts, splitPairCounts.Length); ctx.Node1 = new BTreeBranch(ctx.TransactionId, splitKeys, splitChildren, splitPairCounts); splitKeys = new byte[keyCountRight - 1][]; splitChildren = new IBTreeNode[keyCountRight]; splitPairCounts = new long[keyCountRight]; Array.Copy(newKeys, keyCountLeft, splitKeys, 0, splitKeys.Length); Array.Copy(newChildren, keyCountLeft, splitChildren, 0, splitChildren.Length); for (var i = 0; i < splitPairCounts.Length; i++) { splitPairCounts[i] = newPairCounts[keyCountLeft + i] - newPairCounts[keyCountLeft - 1]; } ctx.Node2 = new BTreeBranch(ctx.TransactionId, splitKeys, splitChildren, splitPairCounts); if (index < keyCountLeft) { ctx.Stack![ctx.Depth] = new NodeIdxPair {Node = ctx.Node1, Idx = index}; ctx.SplitInRight = false; } else { ctx.Stack![ctx.Depth] = new NodeIdxPair {Node = ctx.Node2, Idx = index - keyCountLeft}; ctx.SplitInRight = true; } return; } if (ctx.Update) { if (_transactionId != ctx.TransactionId) { var newKeys = new byte[_keys.Length][]; var newChildren = new IBTreeNode[_children.Length]; var newPairCounts = new long[_children.Length]; Array.Copy(_keys, newKeys, _keys.Length); Array.Copy(_children, newChildren, _children.Length); newChildren[index] = ctx.Node1!; Array.Copy(_pairCounts, newPairCounts, _pairCounts.Length); newBranch = new BTreeBranch(ctx.TransactionId, newKeys, newChildren, newPairCounts); ctx.Node1 = newBranch; } else { _children[index] = ctx.Node1!; ctx.Update = false; ctx.Node1 = null; } ctx.Stack![ctx.Depth] = new NodeIdxPair {Node = newBranch, Idx = index}; } Debug.Assert(newBranch._transactionId == ctx.TransactionId); if (!ctx.Created) return; var pairCounts = newBranch._pairCounts; for (var i = index; i < pairCounts.Length; i++) { pairCounts[i]++; } } public FindResult FindKey(List<NodeIdxPair> stack, out long keyIndex, in ReadOnlySpan<byte> key) { var idx = Find(key); stack.Add(new NodeIdxPair {Node = this, Idx = idx}); var result = _children[idx].FindKey(stack, out keyIndex, key); if (idx > 0) keyIndex += _pairCounts[idx - 1]; return result; } public long CalcKeyCount() { return _pairCounts[^1]; } public byte[] GetLeftMostKey() { return _children[0].GetLeftMostKey(); } public void FillStackByIndex(List<NodeIdxPair> stack, long keyIndex) { var left = 0; var right = _pairCounts.Length - 1; while (left < right) { var middle = (left + right) / 2; var currentIndex = _pairCounts[middle]; if (keyIndex < currentIndex) { right = middle; } else { left = middle + 1; } } stack.Add(new NodeIdxPair {Node = this, Idx = left}); _children[left].FillStackByIndex(stack, keyIndex - (left > 0 ? _pairCounts[left - 1] : 0)); } public long FindLastWithPrefix(in ReadOnlySpan<byte> prefix) { var left = 0; var right = _keys.Length; while (left < right) { var middle = (left + right) / 2; var currentKey = _keys[middle]; var result = prefix.SequenceCompareTo(currentKey.AsSpan(0, Math.Min(currentKey.Length, prefix.Length))); if (result < 0) { right = middle; } else { left = middle + 1; } } return _children[left].FindLastWithPrefix(prefix) + (left > 0 ? _pairCounts[left - 1] : 0); } public bool NextIdxValid(int idx) { return idx + 1 < _children.Length; } public void FillStackByLeftMost(List<NodeIdxPair> stack, int idx) { var leftMost = _children[idx]; stack.Add(new NodeIdxPair {Node = leftMost, Idx = 0}); leftMost.FillStackByLeftMost(stack, 0); } public void FillStackByRightMost(List<NodeIdxPair> stack, int idx) { var rightMost = _children[idx]; var lastIdx = rightMost.GetLastChildrenIdx(); stack.Add(new NodeIdxPair {Node = rightMost, Idx = lastIdx}); rightMost.FillStackByRightMost(stack, lastIdx); } public int GetLastChildrenIdx() { return _children.Length - 1; } public IBTreeNode EraseRange(long transactionId, long firstKeyIndex, long lastKeyIndex) { var firstRemoved = -1; var lastRemoved = -1; IBTreeNode firstPartialNode = null; IBTreeNode lastPartialNode = null; for (var i = 0; i < _pairCounts.Length; i++) { var prevPairCount = i > 0 ? _pairCounts[i - 1] : 0; if (lastKeyIndex < prevPairCount) break; var nextPairCount = _pairCounts[i]; if (nextPairCount <= firstKeyIndex) continue; if (firstKeyIndex <= prevPairCount && nextPairCount - 1 <= lastKeyIndex) { if (firstRemoved == -1) firstRemoved = i; lastRemoved = i; continue; } if (prevPairCount <= firstKeyIndex && lastKeyIndex < nextPairCount) { firstRemoved = i; lastRemoved = i; firstPartialNode = _children[i].EraseRange(transactionId, firstKeyIndex - prevPairCount, lastKeyIndex - prevPairCount); lastPartialNode = firstPartialNode; break; } if (firstRemoved == -1 && firstKeyIndex < nextPairCount) { if (prevPairCount > firstKeyIndex) throw new InvalidOperationException(); if (nextPairCount > lastKeyIndex) throw new InvalidOperationException(); firstRemoved = i; firstPartialNode = _children[i].EraseRange(transactionId, firstKeyIndex - prevPairCount, nextPairCount - 1 - prevPairCount); continue; } if (lastKeyIndex >= nextPairCount - 1) throw new InvalidOperationException(); lastRemoved = i; lastPartialNode = _children[i].EraseRange(transactionId, 0, lastKeyIndex - prevPairCount); break; } var finalChildrenCount = firstRemoved - (firstPartialNode == null ? 1 : 0) + _children.Length + 1 - lastRemoved - (lastPartialNode == null ? 1 : 0) - (firstPartialNode == lastPartialNode && firstPartialNode != null ? 1 : 0); var newKeys = new byte[finalChildrenCount - 1][]; var newChildren = new IBTreeNode[finalChildrenCount]; var newPairCounts = new long[finalChildrenCount]; Array.Copy(_children, 0, newChildren, 0, firstRemoved); var idx = firstRemoved; if (firstPartialNode != null && firstPartialNode != lastPartialNode) { newChildren[idx] = firstPartialNode; idx++; } if (lastPartialNode != null) { newChildren[idx] = lastPartialNode; idx++; } Array.Copy(_children, lastRemoved + 1, newChildren, idx, finalChildrenCount - idx); var previousPairCount = 0L; for (var i = 0; i < finalChildrenCount; i++) { previousPairCount += newChildren[i].CalcKeyCount(); newPairCounts[i] = previousPairCount; } for (var i = 0; i < finalChildrenCount - 1; i++) { newKeys[i] = newChildren[i + 1].GetLeftMostKey(); } if (transactionId == _transactionId) { _keys = newKeys; _children = newChildren; _pairCounts = newPairCounts; return this; } return new BTreeBranch(transactionId, newKeys, newChildren, newPairCounts); } public IBTreeNode EraseOne(long transactionId, long keyIndex) { var firstRemoved = -1; IBTreeNode firstPartialNode = null; for (var i = 0; i < _pairCounts.Length; i++) { var nextPairCount = _pairCounts[i]; if (nextPairCount <= keyIndex) continue; var prevPairCount = i > 0 ? _pairCounts[i - 1] : 0; if (prevPairCount <= keyIndex && keyIndex < nextPairCount) { firstRemoved = i; if (prevPairCount + 1 < nextPairCount) firstPartialNode = _children[i].EraseOne(transactionId, keyIndex - prevPairCount); break; } } var finalChildrenCount = _children.Length - (firstPartialNode == null ? 1 : 0); var newKeys = new byte[finalChildrenCount - 1][]; var newChildren = new IBTreeNode[finalChildrenCount]; var newPairCounts = new long[finalChildrenCount]; Array.Copy(_children, 0, newChildren, 0, firstRemoved); var idx = firstRemoved; if (firstPartialNode != null) { newChildren[idx] = firstPartialNode; idx++; } Array.Copy(_children, firstRemoved + 1, newChildren, idx, finalChildrenCount - idx); var previousPairCount = 0L; for (var i = 0; i < finalChildrenCount; i++) { previousPairCount += newChildren[i].CalcKeyCount(); newPairCounts[i] = previousPairCount; } if (firstPartialNode == null) { if (firstRemoved == 0) { Array.Copy(_keys, 1, newKeys, 0, finalChildrenCount - 1); } else { if (firstRemoved > 1) Array.Copy(_keys, 0, newKeys, 0, firstRemoved - 1); if (finalChildrenCount - firstRemoved > 0) Array.Copy(_keys, firstRemoved, newKeys, firstRemoved - 1, finalChildrenCount - firstRemoved); } } else { Array.Copy(_keys, newKeys, finalChildrenCount - 1); if (firstRemoved > 0) newKeys[firstRemoved - 1] = newChildren[firstRemoved].GetLeftMostKey(); } if (transactionId == _transactionId) { _keys = newKeys; _children = newChildren; _pairCounts = newPairCounts; return this; } return new BTreeBranch(transactionId, newKeys, newChildren, newPairCounts); } public void Iterate(ValuesIterateAction action) { foreach (var child in _children) { child.Iterate(action); } } public IBTreeNode ReplaceValues(ReplaceValuesCtx ctx) { var result = this; var children = _children; var i = 0; if (ctx._restartKey != null) { for (; i < _keys.Length; i++) { var compRes = _keys[i].AsSpan().SequenceCompareTo(ctx._restartKey); if (compRes > 0) break; } } for (; i < children.Length; i++) { var child = children[i]; var newChild = child.ReplaceValues(ctx); if (newChild != child) { if (result._transactionId != ctx._transactionId) { var newKeys = new byte[_keys.Length][]; Array.Copy(_keys, newKeys, newKeys.Length); var newChildren = new IBTreeNode[_children.Length]; Array.Copy(_children, newChildren, newChildren.Length); var newPairCounts = new long[_pairCounts.Length]; Array.Copy(_pairCounts, newPairCounts, newPairCounts.Length); result = new BTreeBranch(ctx._transactionId, newKeys, newChildren, newPairCounts); children = newChildren; } children[i] = newChild; } if (ctx._interrupt) break; ctx._restartKey = null; var now = DateTime.UtcNow; if (i < _keys.Length && (now > ctx._iterationTimeOut || ctx._cancellation.IsCancellationRequested)) { ctx._interrupt = true; ctx._restartKey = _keys[i]; break; } } return result; } } }
using Lucene.Net.Support; using System; using System.Collections.Generic; using System.Diagnostics; namespace Lucene.Net.Util { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /// <summary> /// Represents char[], as a slice (offset + Length) into an existing char[]. /// The <seealso cref="#chars"/> member should never be null; use /// <seealso cref="#EMPTY_CHARS"/> if necessary. /// @lucene.internal /// </summary> public sealed class CharsRef : IComparable<CharsRef>, ICharSequence, ICloneable { /// <summary> /// An empty character array for convenience </summary> public static readonly char[] EMPTY_CHARS = new char[0]; /// <summary> /// The contents of the CharsRef. Should never be {@code null}. /// </summary> public char[] Chars { get; internal set; } /// <summary> /// Offset of first valid character. </summary> public int Offset { get; internal set; } /// <summary> /// Length of used characters. </summary> public int Length { get; set; } /// <summary> /// Creates a new <seealso cref="CharsRef"/> initialized an empty array zero-Length /// </summary> public CharsRef() : this(EMPTY_CHARS, 0, 0) { } /// <summary> /// Creates a new <seealso cref="CharsRef"/> initialized with an array of the given /// capacity /// </summary> public CharsRef(int capacity) { Chars = new char[capacity]; } /// <summary> /// Creates a new <seealso cref="CharsRef"/> initialized with the given array, offset and /// Length /// </summary> public CharsRef(char[] chars, int offset, int Length) { this.Chars = chars; this.Offset = offset; this.Length = Length; Debug.Assert(Valid); } /// <summary> /// Creates a new <seealso cref="CharsRef"/> initialized with the given Strings character /// array /// </summary> public CharsRef(string @string) { this.Chars = @string.ToCharArray(); this.Offset = 0; this.Length = Chars.Length; } /// <summary> /// Returns a shallow clone of this instance (the underlying characters are /// <b>not</b> copied and will be shared by both the returned object and this /// object. /// </summary> /// <seealso cref= #deepCopyOf </seealso> public object Clone() { return new CharsRef(Chars, Offset, Length); } public override int GetHashCode() { const int prime = 31; int result = 0; int end = Offset + Length; for (int i = Offset; i < end; i++) { result = prime * result + Chars[i]; } return result; } public override bool Equals(object other) { if (other == null) { return false; } var @ref = other as CharsRef; if (@ref != null) { return this.CharsEquals(@ref); } return false; } public bool CharsEquals(CharsRef other) { if (Length == other.Length) { int otherUpto = other.Offset; char[] otherChars = other.Chars; int end = Offset + Length; for (int upto = Offset; upto < end; upto++, otherUpto++) { if (Chars[upto] != otherChars[otherUpto]) { return false; } } return true; } else { return false; } } /// <summary> /// Signed int order comparison </summary> public int CompareTo(CharsRef other) { if (this == other) { return 0; } char[] aChars = this.Chars; int aUpto = this.Offset; char[] bChars = other.Chars; int bUpto = other.Offset; int aStop = aUpto + Math.Min(this.Length, other.Length); while (aUpto < aStop) { int aInt = aChars[aUpto++]; int bInt = bChars[bUpto++]; if (aInt > bInt) { return 1; } else if (aInt < bInt) { return -1; } } // One is a prefix of the other, or, they are equal: return this.Length - other.Length; } /// <summary> /// Copies the given <seealso cref="CharsRef"/> referenced content into this instance. /// </summary> /// <param name="other"> /// the <seealso cref="CharsRef"/> to copy </param> public void CopyChars(CharsRef other) { CopyChars(other.Chars, other.Offset, other.Length); } /// <summary> /// Used to grow the reference array. /// /// In general this should not be used as it does not take the offset into account. /// @lucene.internal /// </summary> public void Grow(int newLength) { Debug.Assert(Offset == 0); if (Chars.Length < newLength) { Chars = ArrayUtil.Grow(Chars, newLength); } } /// <summary> /// Copies the given array into this CharsRef. /// </summary> public void CopyChars(char[] otherChars, int otherOffset, int otherLength) { if (Chars.Length - Offset < otherLength) { Chars = new char[otherLength]; Offset = 0; } Array.Copy(otherChars, otherOffset, Chars, Offset, otherLength); Length = otherLength; } /// <summary> /// Appends the given array to this CharsRef /// </summary> public void Append(char[] otherChars, int otherOffset, int otherLength) { int newLen = Length + otherLength; if (Chars.Length - Offset < newLen) { var newChars = new char[newLen]; Array.Copy(Chars, Offset, newChars, 0, Length); Offset = 0; Chars = newChars; } Array.Copy(otherChars, otherOffset, Chars, Length + Offset, otherLength); Length = newLen; } public override string ToString() { return new string(Chars, Offset, Length); } public char CharAt(int index) { // NOTE: must do a real check here to meet the specs of CharSequence if (index < 0 || index >= Length) { throw new System.IndexOutOfRangeException(); } return Chars[Offset + index]; } public ICharSequence SubSequence(int start, int end) { // NOTE: must do a real check here to meet the specs of CharSequence if (start < 0 || end > Length || start > end) { throw new System.IndexOutOfRangeException(); } return new CharsRef(Chars, Offset + start, end - start); } /// @deprecated this comparator is only a transition mechanism [Obsolete("this comparator is only a transition mechanism")] private static readonly IComparer<CharsRef> Utf16SortedAsUTF8SortOrder = new UTF16SortedAsUTF8Comparator(); /// @deprecated this comparator is only a transition mechanism [Obsolete("this comparator is only a transition mechanism")] public static IComparer<CharsRef> UTF16SortedAsUTF8Comparer { get { return Utf16SortedAsUTF8SortOrder; } } /// @deprecated this comparator is only a transition mechanism [Obsolete("this comparator is only a transition mechanism")] private class UTF16SortedAsUTF8Comparator : IComparer<CharsRef> { // Only singleton internal UTF16SortedAsUTF8Comparator() { } public virtual int Compare(CharsRef a, CharsRef b) { if (a == b) { return 0; } char[] aChars = a.Chars; int aUpto = a.Offset; char[] bChars = b.Chars; int bUpto = b.Offset; int aStop = aUpto + Math.Min(a.Length, b.Length); while (aUpto < aStop) { char aChar = aChars[aUpto++]; char bChar = bChars[bUpto++]; if (aChar != bChar) { // http://icu-project.org/docs/papers/utf16_code_point_order.html /* aChar != bChar, fix up each one if they're both in or above the surrogate range, then compare them */ if (aChar >= 0xd800 && bChar >= 0xd800) {//LUCENE TO-DO possible truncation or is char 16bit? if (aChar >= 0xe000) { aChar -= (char)0x800; } else { aChar += (char)0x2000; } if (bChar >= 0xe000) { bChar -= (char)0x800; } else { bChar += (char)0x2000; } } /* now aChar and bChar are in code point order */ return (int)aChar - (int)bChar; // int must be 32 bits wide } } // One is a prefix of the other, or, they are equal: return a.Length - b.Length; } } /// <summary> /// Creates a new CharsRef that points to a copy of the chars from /// <code>other</code> /// <p> /// The returned CharsRef will have a Length of other.Length /// and an offset of zero. /// </summary> public static CharsRef DeepCopyOf(CharsRef other) { CharsRef clone = new CharsRef(); clone.CopyChars(other); return clone; } /// <summary> /// Performs internal consistency checks. /// Always returns true (or throws InvalidOperationException) /// </summary> public bool Valid { get { if (Chars == null) { throw new InvalidOperationException("chars is null"); } if (Length < 0) { throw new InvalidOperationException("Length is negative: " + Length); } if (Length > Chars.Length) { throw new InvalidOperationException("Length is out of bounds: " + Length + ",chars.Length=" + Chars.Length); } if (Offset < 0) { throw new InvalidOperationException("offset is negative: " + Offset); } if (Offset > Chars.Length) { throw new InvalidOperationException("offset out of bounds: " + Offset + ",chars.Length=" + Chars.Length); } if (Offset + Length < 0) { throw new InvalidOperationException("offset+Length is negative: offset=" + Offset + ",Length=" + Length); } if (Offset + Length > Chars.Length) { throw new InvalidOperationException("offset+Length out of bounds: offset=" + Offset + ",Length=" + Length + ",chars.Length=" + Chars.Length); } return true; } } } }
// (c) Copyright 2012 Hewlett-Packard Development Company, L.P. // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. using System; using System.Linq; using System.IO; using System.Xml; using QTObjectModelLib; using Resources = HpToolsLauncher.Properties.Resources; using System.Threading; using System.Diagnostics; using System.Collections.Generic; using Microsoft.Win32; namespace HpToolsLauncher { public class GuiTestRunner : IFileSysTestRunner { private readonly IAssetRunner _runNotifier; private readonly object _lockObject = new object(); private TimeSpan _timeLeftUntilTimeout = TimeSpan.MaxValue; private Stopwatch _stopwatch = null; private Application _qtpApplication; private ParameterDefinitions _qtpParamDefs; private Parameters _qtpParameters; private bool _useUFTLicense; private RunCancelledDelegate _runCancelled; /// <summary> /// constructor /// </summary> /// <param name="runNotifier"></param> /// <param name="useUftLicense"></param> /// <param name="timeLeftUntilTimeout"></param> public GuiTestRunner(IAssetRunner runNotifier, bool useUftLicense, TimeSpan timeLeftUntilTimeout) { _timeLeftUntilTimeout = timeLeftUntilTimeout; _stopwatch = Stopwatch.StartNew(); _runNotifier = runNotifier; _useUFTLicense = useUftLicense; } #region QTP /// <summary> /// runs the given test and returns resutls /// </summary> /// <param name="testPath"></param> /// <param name="errorReason"></param> /// <param name="runCanclled"></param> /// <returns></returns> public TestRunResults RunTest(TestInfo testinf, ref string errorReason, RunCancelledDelegate runCanclled) { var testPath = testinf.TestPath; TestRunResults runDesc = new TestRunResults(); ConsoleWriter.ActiveTestRun = runDesc; ConsoleWriter.WriteLine(DateTime.Now.ToString(Launcher.DateFormat) + " Running: " + testPath); runDesc.ReportLocation = testPath; runDesc.TestPath = testPath; runDesc.TestState = TestState.Unknown; _runCancelled = runCanclled; if (!Helper.IsQtpInstalled()) { runDesc.TestState = TestState.Error; runDesc.ErrorDesc = string.Format(Resources.GeneralQtpNotInstalled, System.Environment.MachineName); ConsoleWriter.WriteErrLine(runDesc.ErrorDesc); Environment.ExitCode = (int)Launcher.ExitCodeEnum.Failed; return runDesc; } try { ChangeDCOMSettingToInteractiveUser(); var type = Type.GetTypeFromProgID("Quicktest.Application"); lock (_lockObject) { _qtpApplication = Activator.CreateInstance(type) as Application; Version qtpVersion = Version.Parse(_qtpApplication.Version); if (qtpVersion.Equals(new Version(11, 0))) { runDesc.ReportLocation = Path.Combine(testPath, "Report"); if (Directory.Exists(runDesc.ReportLocation)) { Directory.Delete(runDesc.ReportLocation, true); Directory.CreateDirectory(runDesc.ReportLocation); } } // Check for required Addins LoadNeededAddins(testPath); if (!_qtpApplication.Launched) { if (_runCancelled()) { QTPTestCleanup(); KillQtp(); runDesc.TestState = TestState.Error; return runDesc; } // Launch application after set Addins _qtpApplication.Launch(); _qtpApplication.Visible = false; } } } catch (Exception e) { errorReason = Resources.QtpNotLaunchedError; runDesc.TestState = TestState.Error; runDesc.ReportLocation = ""; runDesc.ErrorDesc = e.Message; return runDesc; } if (_qtpApplication.Test != null && _qtpApplication.Test.Modified) { var message = Resources.QtpNotLaunchedError; errorReason = message; runDesc.TestState = TestState.Error; runDesc.ErrorDesc = errorReason; return runDesc; } _qtpApplication.UseLicenseOfType(_useUFTLicense ? tagUnifiedLicenseType.qtUnifiedFunctionalTesting : tagUnifiedLicenseType.qtNonUnified); if (!HandleInputParameters(testPath, ref errorReason, testinf.GetParameterDictionaryForQTP())) { runDesc.TestState = TestState.Error; runDesc.ErrorDesc = errorReason; return runDesc; } GuiTestRunResult guiTestRunResult = ExecuteQTPRun(runDesc); runDesc.ReportLocation = guiTestRunResult.ReportPath; if (!guiTestRunResult.IsSuccess) { runDesc.TestState = TestState.Error; return runDesc; } if (!HandleOutputArguments(ref errorReason)) { runDesc.TestState = TestState.Error; runDesc.ErrorDesc = errorReason; return runDesc; } QTPTestCleanup(); return runDesc; } /// <summary> /// performs global cleanup code for this type of runner /// </summary> public void CleanUp() { try { //if we don't have a qtp instance, create one if (_qtpApplication == null) { var type = Type.GetTypeFromProgID("Quicktest.Application"); _qtpApplication = Activator.CreateInstance(type) as Application; } //if the app is running, close it. if (_qtpApplication.Launched) _qtpApplication.Quit(); } catch { //nothing to do. (cleanup code should not throw exceptions, and there is no need to log this as an error in the test) } } static HashSet<string> _colLoadedAddinNames = null; /// <summary> /// Set the test Addins /// </summary> private void LoadNeededAddins(string fileName) { bool blnNeedToLoadAddins = false; //if not launched, we have no addins. if (!_qtpApplication.Launched) _colLoadedAddinNames = null; try { HashSet<string> colCurrentTestAddins = new HashSet<string>(); object erroDescription; var testAddinsObj = _qtpApplication.GetAssociatedAddinsForTest(fileName); object[] testAddins = (object[])testAddinsObj; foreach (string addin in testAddins) { colCurrentTestAddins.Add(addin); } if (_colLoadedAddinNames != null) { //check if we have a missing addin (and need to quit Qtp, and reload with new addins) foreach (string addin in testAddins) { if (!_colLoadedAddinNames.Contains(addin)) { blnNeedToLoadAddins = true; break; } } //check if there is no extra addins that need to be removed if (_colLoadedAddinNames.Count != colCurrentTestAddins.Count) { blnNeedToLoadAddins = true; } } else { //first time = load addins. blnNeedToLoadAddins = true; } _colLoadedAddinNames = colCurrentTestAddins; //the addins need to be refreshed, load new addins if (blnNeedToLoadAddins) { if (_qtpApplication.Launched) _qtpApplication.Quit(); _qtpApplication.SetActiveAddins(ref testAddinsObj, out erroDescription); } } catch (Exception) { // Try anyway to run the test } } /// <summary> /// Activate all Installed Addins /// </summary> private void ActivateAllAddins() { try { // Get Addins collection Addins qtInstalledAddins = _qtpApplication.Addins; if (qtInstalledAddins.Count > 0) { string[] qtAddins = new string[qtInstalledAddins.Count]; // Addins Object is 1 base order for (int idx = 1; idx <= qtInstalledAddins.Count; ++idx) { // Our list is 0 base order qtAddins[idx - 1] = qtInstalledAddins[idx].Name; } object erroDescription; var addinNames = (object)qtAddins; _qtpApplication.SetActiveAddins(ref addinNames, out erroDescription); } } catch (Exception) { // Try anyway to run the test } } /// <summary> /// runs the given test QTP and returns results /// </summary> /// <param name="testResults">the test results object containing test info and also receiving run results</param> /// <returns></returns> private GuiTestRunResult ExecuteQTPRun(TestRunResults testResults) { GuiTestRunResult result = new GuiTestRunResult { IsSuccess = true }; try { Type runResultsOptionstype = Type.GetTypeFromProgID("QuickTest.RunResultsOptions"); var options = (RunResultsOptions)Activator.CreateInstance(runResultsOptionstype); options.ResultsLocation = testResults.ReportLocation; _qtpApplication.Options.Run.RunMode = "Fast"; //Check for cancel before executing if (_runCancelled()) { testResults.TestState = TestState.Error; testResults.ErrorDesc = Resources.GeneralTestCanceled; ConsoleWriter.WriteLine(Resources.GeneralTestCanceled); result.IsSuccess = false; return result; } ConsoleWriter.WriteLine(string.Format(Resources.FsRunnerRunningTest, testResults.TestPath)); _qtpApplication.Test.Run(options, false, _qtpParameters); result.ReportPath = Path.Combine(testResults.ReportLocation, "Report"); int slept = 0; while ((slept < 20000 && _qtpApplication.GetStatus().Equals("Ready")) || _qtpApplication.GetStatus().Equals("Waiting")) { Thread.Sleep(50); slept += 50; } while (!_runCancelled() && (_qtpApplication.GetStatus().Equals("Running") || _qtpApplication.GetStatus().Equals("Busy"))) { Thread.Sleep(200); if (_timeLeftUntilTimeout - _stopwatch.Elapsed <= TimeSpan.Zero) { _qtpApplication.Test.Stop(); testResults.TestState = TestState.Error; testResults.ErrorDesc = Resources.GeneralTimeoutExpired; ConsoleWriter.WriteLine(Resources.GeneralTimeoutExpired); result.IsSuccess = false; return result; } } if (_runCancelled()) { QTPTestCleanup(); KillQtp(); testResults.TestState = TestState.Error; testResults.ErrorDesc = Resources.GeneralTestCanceled; ConsoleWriter.WriteLine(Resources.GeneralTestCanceled); Launcher.ExitCode = Launcher.ExitCodeEnum.Aborted; result.IsSuccess = false; return result; } string lastError = _qtpApplication.Test.LastRunResults.LastError; //read the lastError if (!String.IsNullOrEmpty(lastError)) { testResults.TestState = TestState.Error; testResults.ErrorDesc = lastError; } // the way to check the logical success of the target QTP test is: app.Test.LastRunResults.Status == "Passed". if (_qtpApplication.Test.LastRunResults.Status.Equals("Passed")) { testResults.TestState = TestState.Passed; } else if (_qtpApplication.Test.LastRunResults.Status.Equals("Warning")) { testResults.TestState = TestState.Passed; testResults.HasWarnings = true; if (Launcher.ExitCode != Launcher.ExitCodeEnum.Failed && Launcher.ExitCode != Launcher.ExitCodeEnum.Aborted) Launcher.ExitCode = Launcher.ExitCodeEnum.Unstable; } else { testResults.TestState = TestState.Failed; testResults.FailureDesc = "Test failed"; Launcher.ExitCode = Launcher.ExitCodeEnum.Failed; } } catch (NullReferenceException e) { ConsoleWriter.WriteLine(string.Format(Resources.GeneralErrorWithStack, e.Message, e.StackTrace)); testResults.TestState = TestState.Error; testResults.ErrorDesc = Resources.QtpRunError; result.IsSuccess = false; return result; } catch (SystemException e) { KillQtp(); ConsoleWriter.WriteLine(string.Format(Resources.GeneralErrorWithStack, e.Message, e.StackTrace)); testResults.TestState = TestState.Error; testResults.ErrorDesc = Resources.QtpRunError; result.IsSuccess = false; return result; } catch (Exception e2) { ConsoleWriter.WriteLine(string.Format(Resources.GeneralErrorWithStack, e2.Message, e2.StackTrace)); testResults.TestState = TestState.Error; testResults.ErrorDesc = Resources.QtpRunError; result.IsSuccess = false; return result; } return result; } private void KillQtp() { //error during run, process may have crashed (need to cleanup, close QTP and qtpRemote for next test to run correctly) CleanUp(); //kill the qtp automation, to make sure it will run correctly next time Process[] processes = Process.GetProcessesByName("qtpAutomationAgent"); Process qtpAuto = processes.Where(p => p.SessionId == Process.GetCurrentProcess().SessionId).FirstOrDefault(); if (qtpAuto != null) qtpAuto.Kill(); } private bool HandleOutputArguments(ref string errorReason) { try { var outputArguments = new XmlDocument { PreserveWhitespace = true }; outputArguments.LoadXml("<Arguments/>"); for (int i = 1; i <= _qtpParamDefs.Count; ++i) { var pd = _qtpParamDefs[i]; if (pd.InOut == qtParameterDirection.qtParamDirOut) { var node = outputArguments.CreateElement(pd.Name); var value = _qtpParameters[pd.Name].Value; if (value != null) node.InnerText = value.ToString(); outputArguments.DocumentElement.AppendChild(node); } } } catch (Exception e) { errorReason = Resources.QtpNotLaunchedError; return false; } return true; } private bool VerifyParameterValueType(object paramValue, qtParameterType type) { bool legal = false; switch (type) { case qtParameterType.qtParamTypeBoolean: legal = paramValue is bool; break; case qtParameterType.qtParamTypeDate: legal = paramValue is DateTime; break; case qtParameterType.qtParamTypeNumber: legal = ((paramValue is int) || (paramValue is long) || (paramValue is decimal) || (paramValue is float) || (paramValue is double)); break; case qtParameterType.qtParamTypePassword: legal = paramValue is string; break; case qtParameterType.qtParamTypeString: legal = paramValue is string; break; default: legal = true; break; } return legal; } private bool HandleInputParameters(string fileName, ref string errorReason, Dictionary<string, object> inputParams) { try { string path = fileName; if (_runCancelled()) { QTPTestCleanup(); KillQtp(); return false; } _qtpApplication.Open(path, true, false); _qtpParamDefs = _qtpApplication.Test.ParameterDefinitions; _qtpParameters = _qtpParamDefs.GetParameters(); // handle all parameters (index starts with 1 !!!) for (int i = 1; i <= _qtpParamDefs.Count; i++) { // input parameters if (_qtpParamDefs[i].InOut == qtParameterDirection.qtParamDirIn) { string paramName = _qtpParamDefs[i].Name; qtParameterType type = _qtpParamDefs[i].Type; // if the caller supplies value for a parameter we set it if (inputParams.ContainsKey(paramName)) { // first verify that the type is correct object paramValue = inputParams[paramName]; if (!VerifyParameterValueType(paramValue, type)) { ConsoleWriter.WriteErrLine(string.Format("Illegal input parameter type (skipped). param: '{0}'. expected type: '{1}'. actual type: '{2}'", paramName, Enum.GetName(typeof(qtParameterType), type), paramValue.GetType())); } else { _qtpParameters[paramName].Value = paramValue; } } } } } catch (Exception e) { errorReason = Resources.QtpRunError; return false; } return true; } /// <summary> /// stops and closes qtp test, to make sure nothing is left floating after run. /// </summary> private void QTPTestCleanup() { try { lock (_lockObject) { if (_qtpApplication == null) { return; } var qtpTest = _qtpApplication.Test; if (qtpTest != null) { if (_qtpApplication.GetStatus().Equals("Running") || _qtpApplication.GetStatus().Equals("Busy")) { try { _qtpApplication.Test.Stop(); } catch (Exception e) { } finally { } } } } } catch (Exception ex) { } _qtpParameters = null; _qtpParamDefs = null; _qtpApplication = null; } /// <summary> /// Why we need this? If we run jenkins in a master slave node where there is a jenkins service installed in the slave machine, we need to change the DCOM settings as follow: /// dcomcnfg.exe -> My Computer -> DCOM Config -> QuickTest Professional Automation -> Identity -> and select The Interactive User /// </summary> private void ChangeDCOMSettingToInteractiveUser() { string errorMsg = "Unable to change DCOM settings. To chage it manually: " + "run dcomcnfg.exe -> My Computer -> DCOM Config -> QuickTest Professional Automation -> Identity -> and select The Interactive User"; string interactiveUser = "Interactive User"; string runAs = "RunAs"; try { var regKey = GetQuickTestProfessionalAutomationRegKey(RegistryView.Registry32); if (regKey == null) { regKey = GetQuickTestProfessionalAutomationRegKey(RegistryView.Registry64); } if (regKey == null) throw new Exception(@"Unable to find in registry SOFTWARE\Classes\AppID\{A67EB23A-1B8F-487D-8E38-A6A3DD150F0B"); object runAsKey = regKey.GetValue(runAs); if (runAsKey == null || !runAsKey.ToString().Equals(interactiveUser)) { regKey.SetValue(runAs, interactiveUser); } } catch (Exception ex) { throw new Exception(errorMsg + "detailed error is : " + ex.Message); } } private RegistryKey GetQuickTestProfessionalAutomationRegKey(RegistryView registryView) { RegistryKey localKey = RegistryKey.OpenBaseKey(Microsoft.Win32.RegistryHive.LocalMachine, RegistryView.Registry64); localKey = localKey.OpenSubKey(@"SOFTWARE\Classes\AppID\{A67EB23A-1B8F-487D-8E38-A6A3DD150F0B}", true); return localKey; } #endregion /// <summary> /// holds the resutls for a GUI test /// </summary> private class GuiTestRunResult { public GuiTestRunResult() { ReportPath = ""; } public bool IsSuccess { get; set; } public string ReportPath { get; set; } } } }
// 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.IO; using System.Linq; using System.Globalization; using System.Collections.Generic; using System.Security.Cryptography; using System.Runtime.InteropServices; using System.Text; using System.Security.Cryptography.Pkcs; using System.Security.Cryptography.Xml; using System.Security.Cryptography.X509Certificates; using Xunit; using Test.Cryptography; using System.Security.Cryptography.Pkcs.Tests; namespace System.Security.Cryptography.Pkcs.EnvelopedCmsTests.Tests { public static partial class EdgeCasesTests { [Fact] [OuterLoop(/* Leaks key on disk if interrupted */)] public static void ImportEdgeCase() { // // Pfx's imported into a certificate collection propagate their "delete on Dispose" behavior to its cloned instances: // a subtle difference from Pfx's created using the X509Certificate2 constructor that can lead to premature or // double key deletion. Since EnvelopeCms.Decrypt() has no legitimate reason to clone the extraStore certs, this shouldn't // be a problem, but this test will verify that it isn't. // byte[] encodedMessage = ("3082010c06092a864886f70d010703a081fe3081fb0201003181c83081c5020100302e301a311830160603550403130f5253" + "414b65795472616e7366657231021031d935fb63e8cfab48a0bf7b397b67c0300d06092a864886f70d01010105000481805e" + "bb2d08773594be9ec5d30c0707cf339f2b982a4f0797b74d520a0c973d668a9a6ad9d28066ef36e5b5620fef67f4d79ee50c" + "25eb999f0c656548347d5676ac4b779f8fce2b87e6388fbe483bb0fcf78ab1f1ff29169600401fded7b2803a0bf96cc160c4" + "96726216e986869eed578bda652855c85604a056201538ee56b6c4302b06092a864886f70d010701301406082a864886f70d" + "030704083adadf63cd297a86800835edc437e31d0b70").HexToByteArray(); EnvelopedCms ecms = new EnvelopedCms(); ecms.Decode(encodedMessage); using (X509Certificate2 cert = Certificates.RSAKeyTransfer1.LoadPfxUsingCollectionImport()) { X509Certificate2Collection extraStore = new X509Certificate2Collection(cert); ecms.Decrypt(extraStore); byte[] expectedContent = { 1, 2, 3 }; ContentInfo contentInfo = ecms.ContentInfo; Assert.Equal<byte>(expectedContent, contentInfo.Content); } } [Fact] [OuterLoop(/* Leaks key on disk if interrupted */)] public static void ImportEdgeCaseSki() { byte[] encodedMessage = ("3081f206092a864886f70d010703a081e43081e10201023181ae3081ab0201028014f2008aa9fa3742e8370cb1674ce1d158" + "2921dcc3300d06092a864886f70d01010105000481804336e978bc72ba2f5264cd854867fac438f36f2b3df6004528f2df83" + "4fb2113d6f7c07667e7296b029756222d6ced396a8fffed32be838eec7f2e54b9467fa80f85d097f7d1f0fbde57e07ab3d46" + "a60b31f37ef9844dcab2a8eef4fec5579fac5ec1e7ee82409898e17d30c3ac1a407fca15d23c9df2904a707294d78d4300ba" + "302b06092a864886f70d010701301406082a864886f70d03070408355c596e3e8540608008f1f811e862e51bbd").HexToByteArray(); EnvelopedCms ecms = new EnvelopedCms(); ecms.Decode(encodedMessage); using (X509Certificate2 cert = Certificates.RSAKeyTransfer1.LoadPfxUsingCollectionImport()) { X509Certificate2Collection extraStore = new X509Certificate2Collection(cert); ecms.Decrypt(extraStore); byte[] expectedContent = { 1, 2, 3 }; ContentInfo contentInfo = ecms.ContentInfo; Assert.Equal<byte>(new byte[] { 1, 2, 3 }, contentInfo.Content); Assert.Equal<byte>(expectedContent, contentInfo.Content); } } private static X509Certificate2 LoadPfxUsingCollectionImport(this CertLoader certLoader) { byte[] pfxData = certLoader.PfxData; string password = certLoader.Password; X509Certificate2Collection collection = new X509Certificate2Collection(); collection.Import(pfxData, password, X509KeyStorageFlags.DefaultKeySet); Assert.Equal(1, collection.Count); return collection[0]; } [Fact] [OuterLoop(/* Leaks key on disk if interrupted */)] public static void ZeroLengthContent_RoundTrip() { ContentInfo contentInfo = new ContentInfo(Array.Empty<byte>()); EnvelopedCms ecms = new EnvelopedCms(contentInfo); using (X509Certificate2 cert = Certificates.RSAKeyTransfer1.GetCertificate()) { CmsRecipient cmsRecipient = new CmsRecipient(cert); try { ecms.Encrypt(cmsRecipient); } catch (CryptographicException e) { throw new Exception("ecms.Encrypt() threw " + e.Message + ".\nIf you're running on the desktop CLR, this is actually an expected result."); } } byte[] encodedMessage = ecms.Encode(); ValidateZeroLengthContent(encodedMessage); } [Fact] [OuterLoop(/* Leaks key on disk if interrupted */)] public static void ZeroLengthContent_FixedValue() { byte[] encodedMessage = ("3082010406092a864886f70d010703a081f63081f30201003181c83081c5020100302e301a311830160603550403130f5253" + "414b65795472616e7366657231021031d935fb63e8cfab48a0bf7b397b67c0300d06092a864886f70d010101050004818009" + "c16b674495c2c3d4763189c3274cf7a9142fbeec8902abdc9ce29910d541df910e029a31443dc9a9f3b05f02da1c38478c40" + "0261c734d6789c4197c20143c4312ceaa99ecb1849718326d4fc3b7fbb2d1d23281e31584a63e99f2c17132bcd8eddb63296" + "7125cd0a4baa1efa8ce4c855f7c093339211bdf990cef5cce6cd74302306092a864886f70d010701301406082a864886f70d" + "03070408779b3de045826b188000").HexToByteArray(); ValidateZeroLengthContent(encodedMessage); } [Fact] [OuterLoop(/* Leaks key on disk if interrupted */)] public static void Rc4AndCngWrappersDontMixTest() { // // Combination of RC4 over a CAPI certificate. // // This works as long as the PKCS implementation opens the cert using CAPI. If he creates a CNG wrapper handle (by passing CRYPT_ACQUIRE_PREFER_NCRYPT_KEY_FLAG), // the test fails with a NOTSUPPORTED crypto exception inside Decrypt(). The same happens if the key is genuinely CNG. // byte[] content = { 6, 3, 128, 33, 44 }; AlgorithmIdentifier rc4 = new AlgorithmIdentifier(new Oid(Oids.Rc4)); EnvelopedCms ecms = new EnvelopedCms(new ContentInfo(content), rc4); CmsRecipientCollection recipients = new CmsRecipientCollection(new CmsRecipient(Certificates.RSAKeyTransferCapi1.GetCertificate())); ecms.Encrypt(recipients); byte[] encodedMessage = ecms.Encode(); ecms = new EnvelopedCms(); ecms.Decode(encodedMessage); // In order to actually use the CAPI version of the key, perphemeral loading must be specified. using (X509Certificate2 cert = Certificates.RSAKeyTransferCapi1.CloneAsPerphemeralLoader().TryGetCertificateWithPrivateKey()) { if (cert == null) return; // Sorry - CertLoader is not configured to load certs with private keys - we've tested as much as we can. X509Certificate2Collection extraStore = new X509Certificate2Collection(); extraStore.Add(cert); ecms.Decrypt(extraStore); } ContentInfo contentInfo = ecms.ContentInfo; Assert.Equal<byte>(content, contentInfo.Content); } private static void ValidateZeroLengthContent(byte[] encodedMessage) { EnvelopedCms ecms = new EnvelopedCms(); ecms.Decode(encodedMessage); using (X509Certificate2 cert = Certificates.RSAKeyTransfer1.TryGetCertificateWithPrivateKey()) { if (cert == null) return; X509Certificate2Collection extraStore = new X509Certificate2Collection(cert); ecms.Decrypt(extraStore); ContentInfo contentInfo = ecms.ContentInfo; byte[] content = contentInfo.Content; if (content.Length == 6) throw new Exception("ContentInfo expected to be 0 but was actually 6. If you're running on the desktop CLR, this is actually a known bug."); Assert.Equal(0, content.Length); } } [Fact] public static void ReuseEnvelopeCmsEncodeThenDecode() { // Test ability to encrypt, encode and decode all in one EnvelopedCms instance. ContentInfo contentInfo = new ContentInfo(new byte[] { 1, 2, 3 }); EnvelopedCms ecms = new EnvelopedCms(contentInfo); using (X509Certificate2 cert = Certificates.RSAKeyTransfer1.GetCertificate()) { CmsRecipient cmsRecipient = new CmsRecipient(cert); ecms.Encrypt(cmsRecipient); } byte[] encodedMessage = ecms.Encode(); ecms.Decode(encodedMessage); RecipientInfoCollection recipients = ecms.RecipientInfos; Assert.Equal(1, recipients.Count); RecipientInfo recipientInfo = recipients[0]; KeyTransRecipientInfo recipient = recipientInfo as KeyTransRecipientInfo; Assert.NotNull(recipientInfo); SubjectIdentifier subjectIdentifier = recipient.RecipientIdentifier; object value = subjectIdentifier.Value; Assert.True(value is X509IssuerSerial); X509IssuerSerial xis = (X509IssuerSerial)value; Assert.Equal("CN=RSAKeyTransfer1", xis.IssuerName); Assert.Equal("31D935FB63E8CFAB48A0BF7B397B67C0", xis.SerialNumber); } [Fact] public static void ReuseEnvelopeCmsDecodeThenEncode() { byte[] encodedMessage = ("3082010c06092a864886f70d010703a081fe3081fb0201003181c83081c5020100302e301a311830160603550403130f5253" + "414b65795472616e7366657231021031d935fb63e8cfab48a0bf7b397b67c0300d06092a864886f70d01010105000481805e" + "bb2d08773594be9ec5d30c0707cf339f2b982a4f0797b74d520a0c973d668a9a6ad9d28066ef36e5b5620fef67f4d79ee50c" + "25eb999f0c656548347d5676ac4b779f8fce2b87e6388fbe483bb0fcf78ab1f1ff29169600401fded7b2803a0bf96cc160c4" + "96726216e986869eed578bda652855c85604a056201538ee56b6c4302b06092a864886f70d010701301406082a864886f70d" + "030704083adadf63cd297a86800835edc437e31d0b70").HexToByteArray(); EnvelopedCms ecms = new EnvelopedCms(); ecms.Decode(encodedMessage); using (X509Certificate2 cert = Certificates.RSAKeyTransfer1.GetCertificate()) { CmsRecipient cmsRecipient = new CmsRecipient(cert); ecms.Encrypt(cmsRecipient); } encodedMessage = ecms.Encode(); ecms.Decode(encodedMessage); RecipientInfoCollection recipients = ecms.RecipientInfos; Assert.Equal(1, recipients.Count); RecipientInfo recipientInfo = recipients[0]; KeyTransRecipientInfo recipient = recipientInfo as KeyTransRecipientInfo; Assert.NotNull(recipientInfo); SubjectIdentifier subjectIdentifier = recipient.RecipientIdentifier; object value = subjectIdentifier.Value; Assert.True(value is X509IssuerSerial); X509IssuerSerial xis = (X509IssuerSerial)value; Assert.Equal("CN=RSAKeyTransfer1", xis.IssuerName); Assert.Equal("31D935FB63E8CFAB48A0BF7B397B67C0", xis.SerialNumber); } [Fact] public static void EnvelopedCmsNullContent() { object ignore; Assert.Throws<ArgumentNullException>(() => ignore = new EnvelopedCms(null)); Assert.Throws<ArgumentNullException>(() => ignore = new EnvelopedCms(null, new AlgorithmIdentifier(new Oid(Oids.TripleDesCbc)))); } [Fact] public static void EnvelopedCmsNullAlgorithm() { object ignore; ContentInfo contentInfo = new ContentInfo(new byte[3]); Assert.Throws<ArgumentNullException>(() => ignore = new EnvelopedCms(contentInfo, null)); } [Fact] public static void EnvelopedCmsEncryptWithNullRecipient() { EnvelopedCms ecms = new EnvelopedCms(new ContentInfo(new byte[3])); Assert.Throws<ArgumentNullException>(() => ecms.Encrypt((CmsRecipient)null)); } [Fact] public static void EnvelopedCmsEncryptWithNullRecipients() { EnvelopedCms ecms = new EnvelopedCms(new ContentInfo(new byte[3])); Assert.Throws<ArgumentNullException>(() => ecms.Encrypt((CmsRecipientCollection)null)); } [Fact] // On the desktop, this throws up a UI for the user to select a recipient. We don't support that. [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)] public static void EnvelopedCmsEncryptWithZeroRecipients() { EnvelopedCms ecms = new EnvelopedCms(new ContentInfo(new byte[3])); Assert.Throws<PlatformNotSupportedException>(() => ecms.Encrypt(new CmsRecipientCollection())); } [Fact] public static void EnvelopedCmsNullDecode() { EnvelopedCms ecms = new EnvelopedCms(); Assert.Throws<ArgumentNullException>(() => ecms.Decode(null)); } [Fact] public static void EnvelopedCmsDecryptNullary() { byte[] encodedMessage = ("3082010c06092a864886f70d010703a081fe3081fb0201003181c83081c5020100302e301a311830160603550403130f5253" + "414b65795472616e7366657231021031d935fb63e8cfab48a0bf7b397b67c0300d06092a864886f70d01010105000481805e" + "bb2d08773594be9ec5d30c0707cf339f2b982a4f0797b74d520a0c973d668a9a6ad9d28066ef36e5b5620fef67f4d79ee50c" + "25eb999f0c656548347d5676ac4b779f8fce2b87e6388fbe483bb0fcf78ab1f1ff29169600401fded7b2803a0bf96cc160c4" + "96726216e986869eed578bda652855c85604a056201538ee56b6c4302b06092a864886f70d010701301406082a864886f70d" + "030704083adadf63cd297a86800835edc437e31d0b70").HexToByteArray(); EnvelopedCms ecms = new EnvelopedCms(); ecms.Decode(encodedMessage); Assert.ThrowsAny<CryptographicException>(() => ecms.Decrypt()); } [Fact] public static void EnvelopedCmsDecryptNullRecipient() { byte[] encodedMessage = ("3082010c06092a864886f70d010703a081fe3081fb0201003181c83081c5020100302e301a311830160603550403130f5253" + "414b65795472616e7366657231021031d935fb63e8cfab48a0bf7b397b67c0300d06092a864886f70d01010105000481805e" + "bb2d08773594be9ec5d30c0707cf339f2b982a4f0797b74d520a0c973d668a9a6ad9d28066ef36e5b5620fef67f4d79ee50c" + "25eb999f0c656548347d5676ac4b779f8fce2b87e6388fbe483bb0fcf78ab1f1ff29169600401fded7b2803a0bf96cc160c4" + "96726216e986869eed578bda652855c85604a056201538ee56b6c4302b06092a864886f70d010701301406082a864886f70d" + "030704083adadf63cd297a86800835edc437e31d0b70").HexToByteArray(); EnvelopedCms ecms = new EnvelopedCms(); ecms.Decode(encodedMessage); RecipientInfo recipientInfo = null; X509Certificate2Collection extraStore = new X509Certificate2Collection(); Assert.Throws<ArgumentNullException>(() => ecms.Decrypt(recipientInfo)); Assert.Throws<ArgumentNullException>(() => ecms.Decrypt(recipientInfo, extraStore)); } [Fact] public static void EnvelopedCmsDecryptNullExtraStore() { byte[] encodedMessage = ("3082010c06092a864886f70d010703a081fe3081fb0201003181c83081c5020100302e301a311830160603550403130f5253" + "414b65795472616e7366657231021031d935fb63e8cfab48a0bf7b397b67c0300d06092a864886f70d01010105000481805e" + "bb2d08773594be9ec5d30c0707cf339f2b982a4f0797b74d520a0c973d668a9a6ad9d28066ef36e5b5620fef67f4d79ee50c" + "25eb999f0c656548347d5676ac4b779f8fce2b87e6388fbe483bb0fcf78ab1f1ff29169600401fded7b2803a0bf96cc160c4" + "96726216e986869eed578bda652855c85604a056201538ee56b6c4302b06092a864886f70d010701301406082a864886f70d" + "030704083adadf63cd297a86800835edc437e31d0b70").HexToByteArray(); EnvelopedCms ecms = new EnvelopedCms(); ecms.Decode(encodedMessage); RecipientInfo recipientInfo = ecms.RecipientInfos[0]; X509Certificate2Collection extraStore = null; Assert.Throws<ArgumentNullException>(() => ecms.Decrypt(extraStore)); Assert.Throws<ArgumentNullException>(() => ecms.Decrypt(recipientInfo, extraStore)); } [Fact] [OuterLoop(/* Leaks key on disk if interrupted */)] public static void EnvelopedCmsDecryptWithoutMatchingCert() { // You don't have the private key? No message for you. // This is the private key that "we don't have." We want to force it to load anyway, though, to trigger // the "fail the test due to bad machine config" exception if someone left this cert in the MY store check. using (X509Certificate2 ignore = Certificates.RSAKeyTransfer1.TryGetCertificateWithPrivateKey()) { } byte[] encodedMessage = ("3082010c06092a864886f70d010703a081fe3081fb0201003181c83081c5020100302e301a311830160603550403130f5253" + "414b65795472616e7366657231021031d935fb63e8cfab48a0bf7b397b67c0300d06092a864886f70d01010105000481805e" + "bb2d08773594be9ec5d30c0707cf339f2b982a4f0797b74d520a0c973d668a9a6ad9d28066ef36e5b5620fef67f4d79ee50c" + "25eb999f0c656548347d5676ac4b779f8fce2b87e6388fbe483bb0fcf78ab1f1ff29169600401fded7b2803a0bf96cc160c4" + "96726216e986869eed578bda652855c85604a056201538ee56b6c4302b06092a864886f70d010701301406082a864886f70d" + "030704083adadf63cd297a86800835edc437e31d0b70").HexToByteArray(); EnvelopedCms ecms = new EnvelopedCms(); ecms.Decode(encodedMessage); RecipientInfo recipientInfo = ecms.RecipientInfos[0]; X509Certificate2Collection extraStore = new X509Certificate2Collection(); Assert.ThrowsAny<CryptographicException>(() => ecms.Decrypt(recipientInfo)); Assert.ThrowsAny<CryptographicException>(() => ecms.Decrypt(extraStore)); Assert.ThrowsAny<CryptographicException>(() => ecms.Decrypt(recipientInfo, extraStore)); } [Fact] [OuterLoop(/* Leaks key on disk if interrupted */)] public static void EnvelopedCmsDecryptWithoutMatchingCertSki() { // You don't have the private key? No message for you. // This is the private key that "we don't have." We want to force it to load anyway, though, to trigger // the "fail the test due to bad machine config" exception if someone left this cert in the MY store check. using (X509Certificate2 ignore = Certificates.RSAKeyTransfer1.TryGetCertificateWithPrivateKey()) { } byte[] encodedMessage = ("3081f206092a864886f70d010703a081e43081e10201023181ae3081ab0201028014f2008aa9fa3742e8370cb1674ce1d158" + "2921dcc3300d06092a864886f70d01010105000481804336e978bc72ba2f5264cd854867fac438f36f2b3df6004528f2df83" + "4fb2113d6f7c07667e7296b029756222d6ced396a8fffed32be838eec7f2e54b9467fa80f85d097f7d1f0fbde57e07ab3d46" + "a60b31f37ef9844dcab2a8eef4fec5579fac5ec1e7ee82409898e17d30c3ac1a407fca15d23c9df2904a707294d78d4300ba" + "302b06092a864886f70d010701301406082a864886f70d03070408355c596e3e8540608008f1f811e862e51bbd").HexToByteArray(); EnvelopedCms ecms = new EnvelopedCms(); ecms.Decode(encodedMessage); RecipientInfo recipientInfo = ecms.RecipientInfos[0]; X509Certificate2Collection extraStore = new X509Certificate2Collection(); Assert.ThrowsAny<CryptographicException>(() => ecms.Decrypt(recipientInfo)); Assert.ThrowsAny<CryptographicException>(() => ecms.Decrypt(extraStore)); Assert.ThrowsAny<CryptographicException>(() => ecms.Decrypt(recipientInfo, extraStore)); } [Fact] public static void AlgorithmIdentifierNullaryCtor() { AlgorithmIdentifier a = new AlgorithmIdentifier(); Assert.Equal(Oids.TripleDesCbc, a.Oid.Value); Assert.Equal(0, a.KeyLength); } [Fact] public static void CmsRecipient1AryCtor() { using (X509Certificate2 cert = Certificates.RSAKeyTransfer1.GetCertificate()) { CmsRecipient r = new CmsRecipient(cert); Assert.Equal(SubjectIdentifierType.IssuerAndSerialNumber, r.RecipientIdentifierType); Assert.Same(cert, r.Certificate); } } [Fact] public static void CmsRecipientPassUnknown() { using (X509Certificate2 cert = Certificates.RSAKeyTransfer1.GetCertificate()) { CmsRecipient r = new CmsRecipient(SubjectIdentifierType.Unknown, cert); Assert.Equal(SubjectIdentifierType.IssuerAndSerialNumber, r.RecipientIdentifierType); Assert.Same(cert, r.Certificate); } } [Fact] public static void CmsRecipientPassNullCertificate() { object ignore; Assert.Throws<ArgumentNullException>(() => ignore = new CmsRecipient(null)); Assert.Throws<ArgumentNullException>(() => ignore = new CmsRecipient(SubjectIdentifierType.IssuerAndSerialNumber, null)); } [Fact] public static void ContentInfoNullOid() { object ignore; Assert.Throws<ArgumentNullException>(() => ignore = new ContentInfo(null, new byte[3])); } [Fact] public static void ContentInfoNullContent() { object ignore; Assert.Throws<ArgumentNullException>(() => ignore = new ContentInfo(null)); Assert.Throws<ArgumentNullException>(() => ignore = new ContentInfo(null, null)); } [Fact] public static void ContentInfoGetContentTypeNull() { Assert.Throws<ArgumentNullException>(() => ContentInfo.GetContentType(null)); } [Fact] public static void CryptographicAttributeObjectOidCtor() { Oid oid = new Oid(Oids.DocumentDescription); CryptographicAttributeObject cao = new CryptographicAttributeObject(oid); Assert.Equal(oid.Value, cao.Oid.Value); Assert.Equal(0, cao.Values.Count); } [Fact] public static void CryptographicAttributeObjectPassNullValuesToCtor() { Oid oid = new Oid(Oids.DocumentDescription); // This is legal and equivalent to passing a zero-length AsnEncodedDataCollection. CryptographicAttributeObject cao = new CryptographicAttributeObject(oid, null); Assert.Equal(oid.Value, cao.Oid.Value); Assert.Equal(0, cao.Values.Count); } [Fact] public static void CryptographicAttributeObjectMismatch() { Oid oid = new Oid(Oids.DocumentDescription); Oid wrongOid = new Oid(Oids.DocumentName); AsnEncodedDataCollection col = new AsnEncodedDataCollection(); col.Add(new AsnEncodedData(oid, new byte[3])); object ignore; Assert.Throws<InvalidOperationException>(() => ignore = new CryptographicAttributeObject(wrongOid, col)); } } }
// <copyright file="HttpInListenerTests.cs" company="OpenTelemetry Authors"> // Copyright The OpenTelemetry Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Web; using System.Web.Routing; using Moq; using OpenTelemetry.Context.Propagation; using OpenTelemetry.Instrumentation.AspNet.Implementation; using OpenTelemetry.Tests; using OpenTelemetry.Trace; using Xunit; namespace OpenTelemetry.Instrumentation.AspNet.Tests { public class HttpInListenerTests { [Theory] [InlineData("http://localhost/", "http://localhost/", 0, null)] [InlineData("http://localhost/", "http://localhost/", 0, null, true)] [InlineData("https://localhost/", "https://localhost/", 0, null)] [InlineData("https://localhost/", "https://user:pass@localhost/", 0, null)] // Test URL sanitization [InlineData("http://localhost:443/", "http://localhost:443/", 0, null)] // Test http over 443 [InlineData("https://localhost:80/", "https://localhost:80/", 0, null)] // Test https over 80 [InlineData("https://localhost:80/Home/Index.htm?q1=v1&q2=v2#FragmentName", "https://localhost:80/Home/Index.htm?q1=v1&q2=v2#FragmentName", 0, null)] // Test complex URL [InlineData("https://localhost:80/Home/Index.htm?q1=v1&q2=v2#FragmentName", "https://user:password@localhost:80/Home/Index.htm?q1=v1&q2=v2#FragmentName", 0, null)] // Test complex URL sanitization [InlineData("http://localhost:80/Index", "http://localhost:80/Index", 1, "{controller}/{action}/{id}")] [InlineData("https://localhost:443/about_attr_route/10", "https://localhost:443/about_attr_route/10", 2, "about_attr_route/{customerId}")] [InlineData("http://localhost:1880/api/weatherforecast", "http://localhost:1880/api/weatherforecast", 3, "api/{controller}/{id}")] [InlineData("https://localhost:1843/subroute/10", "https://localhost:1843/subroute/10", 4, "subroute/{customerId}")] [InlineData("http://localhost/api/value", "http://localhost/api/value", 0, null, false, "/api/value")] // Request will be filtered [InlineData("http://localhost/api/value", "http://localhost/api/value", 0, null, false, "{ThrowException}")] // Filter user code will throw an exception [InlineData("http://localhost/", "http://localhost/", 0, null, false, null, true)] // Test RecordException option public void AspNetRequestsAreCollectedSuccessfully( string expectedUrl, string url, int routeType, string routeTemplate, bool setStatusToErrorInEnrich = false, string filter = null, bool recordException = false) { IDisposable tracerProvider = null; RouteData routeData; switch (routeType) { case 0: // WebForm, no route data. routeData = new RouteData(); break; case 1: // Traditional MVC. case 2: // Attribute routing MVC. case 3: // Traditional WebAPI. routeData = new RouteData() { Route = new Route(routeTemplate, null), }; break; case 4: // Attribute routing WebAPI. routeData = new RouteData(); var value = new[] { new { Route = new { RouteTemplate = routeTemplate, }, }, }; routeData.Values.Add( "MS_SubRoutes", value); break; default: throw new NotSupportedException(); } var workerRequest = new Mock<HttpWorkerRequest>(); workerRequest.Setup(wr => wr.GetKnownRequestHeader(It.IsAny<int>())).Returns<int>(i => { return i switch { 39 => "Test", // User-Agent _ => null, }; }); HttpContext.Current = new HttpContext( new HttpRequest(string.Empty, url, string.Empty) { RequestContext = new RequestContext() { RouteData = routeData, }, }, new HttpResponse(new StringWriter())); typeof(HttpRequest).GetField("_wr", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(HttpContext.Current.Request, workerRequest.Object); List<Activity> exportedItems = new List<Activity>(16); Sdk.SetDefaultTextMapPropagator(new TraceContextPropagator()); using (tracerProvider = Sdk.CreateTracerProviderBuilder() .AddAspNetInstrumentation((options) => { options.Filter = httpContext => { Assert.True(Activity.Current.IsAllDataRequested); if (string.IsNullOrEmpty(filter)) { return true; } if (filter == "{ThrowException}") { throw new InvalidOperationException(); } return httpContext.Request.Path != filter; }; options.Enrich = GetEnrichmentAction(setStatusToErrorInEnrich ? Status.Error : default); options.RecordException = recordException; }) .AddInMemoryExporter(exportedItems) .Build()) { using var inMemoryEventListener = new InMemoryEventListener(AspNetInstrumentationEventSource.Log); var activity = ActivityHelper.StartAspNetActivity(Propagators.DefaultTextMapPropagator, HttpContext.Current, TelemetryHttpModule.Options.OnRequestStartedCallback); if (filter == "{ThrowException}") { Assert.Single(inMemoryEventListener.Events.Where((e) => e.EventId == 2)); } Assert.Equal(TelemetryHttpModule.AspNetActivityName, Activity.Current.OperationName); if (recordException) { ActivityHelper.WriteActivityException(activity, HttpContext.Current, new InvalidOperationException(), TelemetryHttpModule.Options.OnExceptionCallback); } ActivityHelper.StopAspNetActivity(Propagators.DefaultTextMapPropagator, activity, HttpContext.Current, TelemetryHttpModule.Options.OnRequestStoppedCallback); } if (HttpContext.Current.Request.Path == filter || filter == "{ThrowException}") { Assert.Empty(exportedItems); return; } Assert.Single(exportedItems); Activity span = exportedItems[0]; Assert.Equal(TelemetryHttpModule.AspNetActivityName, span.OperationName); Assert.NotEqual(TimeSpan.Zero, span.Duration); Assert.Equal(routeTemplate ?? HttpContext.Current.Request.Path, span.DisplayName); Assert.Equal(ActivityKind.Server, span.Kind); Assert.True(span.Duration != TimeSpan.Zero); Assert.Equal(200, span.GetTagValue(SemanticConventions.AttributeHttpStatusCode)); var expectedUri = new Uri(expectedUrl); var actualUrl = span.GetTagValue(SemanticConventions.AttributeHttpUrl); Assert.Equal(expectedUri.ToString(), actualUrl); // Url strips 80 or 443 if the scheme matches. if ((expectedUri.Port == 80 && expectedUri.Scheme == "http") || (expectedUri.Port == 443 && expectedUri.Scheme == "https")) { Assert.DoesNotContain($":{expectedUri.Port}", actualUrl as string); } else { Assert.Contains($":{expectedUri.Port}", actualUrl as string); } // Host includes port if it isn't 80 or 443. if (expectedUri.Port is 80 or 443) { Assert.Equal( expectedUri.Host, span.GetTagValue(SemanticConventions.AttributeHttpHost) as string); } else { Assert.Equal( $"{expectedUri.Host}:{expectedUri.Port}", span.GetTagValue(SemanticConventions.AttributeHttpHost) as string); } Assert.Equal(HttpContext.Current.Request.HttpMethod, span.GetTagValue(SemanticConventions.AttributeHttpMethod) as string); Assert.Equal(HttpContext.Current.Request.Path, span.GetTagValue(SemanticConventions.AttributeHttpTarget) as string); Assert.Equal(HttpContext.Current.Request.UserAgent, span.GetTagValue(SemanticConventions.AttributeHttpUserAgent) as string); if (recordException) { var status = span.GetStatus(); Assert.Equal(Status.Error.StatusCode, status.StatusCode); Assert.Equal("Operation is not valid due to the current state of the object.", status.Description); } else if (setStatusToErrorInEnrich) { // This validates that users can override the // status in Enrich. Assert.Equal(Status.Error, span.GetStatus()); // Instrumentation is not expected to set status description // as the reason can be inferred from SemanticConventions.AttributeHttpStatusCode Assert.True(string.IsNullOrEmpty(span.GetStatus().Description)); } else { Assert.Equal(Status.Unset, span.GetStatus()); // Instrumentation is not expected to set status description // as the reason can be inferred from SemanticConventions.AttributeHttpStatusCode Assert.True(string.IsNullOrEmpty(span.GetStatus().Description)); } } [Theory] [InlineData(SamplingDecision.Drop)] [InlineData(SamplingDecision.RecordOnly)] [InlineData(SamplingDecision.RecordAndSample)] public void ExtractContextIrrespectiveOfSamplingDecision(SamplingDecision samplingDecision) { HttpContext.Current = new HttpContext( new HttpRequest(string.Empty, "http://localhost/", string.Empty) { RequestContext = new RequestContext() { RouteData = new RouteData(), }, }, new HttpResponse(new StringWriter())); bool isPropagatorCalled = false; var propagator = new Mock<TextMapPropagator>(); propagator.Setup(m => m.Extract(It.IsAny<PropagationContext>(), It.IsAny<HttpRequest>(), It.IsAny<Func<HttpRequest, string, IEnumerable<string>>>())) .Returns(() => { isPropagatorCalled = true; return default; }); var activityProcessor = new Mock<BaseProcessor<Activity>>(); Sdk.SetDefaultTextMapPropagator(propagator.Object); using (var tracerProvider = Sdk.CreateTracerProviderBuilder() .SetSampler(new TestSampler(samplingDecision)) .AddAspNetInstrumentation() .AddProcessor(activityProcessor.Object).Build()) { var activity = ActivityHelper.StartAspNetActivity(Propagators.DefaultTextMapPropagator, HttpContext.Current, TelemetryHttpModule.Options.OnRequestStartedCallback); ActivityHelper.StopAspNetActivity(Propagators.DefaultTextMapPropagator, activity, HttpContext.Current, TelemetryHttpModule.Options.OnRequestStoppedCallback); } Assert.True(isPropagatorCalled); } [Fact] public void ExtractContextIrrespectiveOfTheFilterApplied() { HttpContext.Current = new HttpContext( new HttpRequest(string.Empty, "http://localhost/", string.Empty) { RequestContext = new RequestContext() { RouteData = new RouteData(), }, }, new HttpResponse(new StringWriter())); bool isPropagatorCalled = false; var propagator = new Mock<TextMapPropagator>(); propagator.Setup(m => m.Extract(It.IsAny<PropagationContext>(), It.IsAny<HttpRequest>(), It.IsAny<Func<HttpRequest, string, IEnumerable<string>>>())) .Returns(() => { isPropagatorCalled = true; return default; }); bool isFilterCalled = false; var activityProcessor = new Mock<BaseProcessor<Activity>>(); Sdk.SetDefaultTextMapPropagator(propagator.Object); using (var tracerProvider = Sdk.CreateTracerProviderBuilder() .AddAspNetInstrumentation(options => { options.Filter = context => { isFilterCalled = true; return false; }; }) .AddProcessor(activityProcessor.Object).Build()) { var activity = ActivityHelper.StartAspNetActivity(Propagators.DefaultTextMapPropagator, HttpContext.Current, TelemetryHttpModule.Options.OnRequestStartedCallback); ActivityHelper.StopAspNetActivity(Propagators.DefaultTextMapPropagator, activity, HttpContext.Current, TelemetryHttpModule.Options.OnRequestStoppedCallback); } Assert.True(isFilterCalled); Assert.True(isPropagatorCalled); } private static Action<Activity, string, object> GetEnrichmentAction(Status statusToBeSet) { void EnrichAction(Activity activity, string method, object obj) { Assert.True(activity.IsAllDataRequested); switch (method) { case "OnStartActivity": Assert.True(obj is HttpRequest); break; case "OnStopActivity": Assert.True(obj is HttpResponse); if (statusToBeSet != default) { activity.SetStatus(statusToBeSet); } break; default: break; } } return EnrichAction; } private class TestSampler : Sampler { private readonly SamplingDecision samplingDecision; public TestSampler(SamplingDecision samplingDecision) { this.samplingDecision = samplingDecision; } public override SamplingResult ShouldSample(in SamplingParameters samplingParameters) { return new SamplingResult(this.samplingDecision); } } } }
// ---------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. // ---------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Linq.Expressions; using System.Reflection; namespace Microsoft.WindowsAzure.MobileServices { internal abstract class ExpressionVisitor { protected ExpressionVisitor() { } public virtual Expression Visit(Expression exp) { if (exp == null) { return exp; } switch (exp.NodeType) { case ExpressionType.UnaryPlus: case ExpressionType.Negate: case ExpressionType.NegateChecked: case ExpressionType.Not: case ExpressionType.Convert: case ExpressionType.ConvertChecked: case ExpressionType.ArrayLength: case ExpressionType.Quote: case ExpressionType.TypeAs: return this.VisitUnary((UnaryExpression)exp); case ExpressionType.Add: case ExpressionType.AddChecked: case ExpressionType.Subtract: case ExpressionType.SubtractChecked: case ExpressionType.Multiply: case ExpressionType.MultiplyChecked: case ExpressionType.Divide: case ExpressionType.Modulo: case ExpressionType.And: case ExpressionType.AndAlso: case ExpressionType.Or: case ExpressionType.OrElse: case ExpressionType.LessThan: case ExpressionType.LessThanOrEqual: case ExpressionType.GreaterThan: case ExpressionType.GreaterThanOrEqual: case ExpressionType.Equal: case ExpressionType.NotEqual: case ExpressionType.Coalesce: case ExpressionType.ArrayIndex: case ExpressionType.RightShift: case ExpressionType.LeftShift: case ExpressionType.ExclusiveOr: return this.VisitBinary((BinaryExpression)exp); case ExpressionType.TypeIs: return this.VisitTypeIs((TypeBinaryExpression)exp); case ExpressionType.Conditional: return this.VisitConditional((ConditionalExpression)exp); case ExpressionType.Constant: return this.VisitConstant((ConstantExpression)exp); case ExpressionType.Parameter: return this.VisitParameter((ParameterExpression)exp); case ExpressionType.MemberAccess: return this.VisitMember((MemberExpression)exp); case ExpressionType.Call: return this.VisitMethodCall((MethodCallExpression)exp); case ExpressionType.Lambda: return this.VisitLambda((LambdaExpression)exp); case ExpressionType.New: return this.VisitNew((NewExpression)exp); case ExpressionType.NewArrayInit: case ExpressionType.NewArrayBounds: return this.VisitNewArray((NewArrayExpression)exp); case ExpressionType.Invoke: return this.VisitInvocation((InvocationExpression)exp); case ExpressionType.MemberInit: return this.VisitMemberInit((MemberInitExpression)exp); case ExpressionType.ListInit: return this.VisitListInit((ListInitExpression)exp); default: throw new NotSupportedException(string.Format("Unhandled expression type: '{0}'", exp.NodeType)); } } protected virtual MemberBinding VisitBinding(MemberBinding binding) { switch (binding.BindingType) { case MemberBindingType.Assignment: return this.VisitMemberAssignment((MemberAssignment)binding); case MemberBindingType.MemberBinding: return this.VisitMemberMemberBinding((MemberMemberBinding)binding); case MemberBindingType.ListBinding: return this.VisitMemberListBinding((MemberListBinding)binding); default: throw new NotSupportedException(string.Format("Unhandled binding type '{0}'", binding.BindingType)); } } protected virtual ElementInit VisitElementInitializer(ElementInit initializer) { ReadOnlyCollection<Expression> arguments = this.VisitExpressionList(initializer.Arguments); if (arguments != initializer.Arguments) { return Expression.ElementInit(initializer.AddMethod, arguments); } return initializer; } protected virtual Expression VisitUnary(UnaryExpression u) { Expression operand = this.Visit(u.Operand); if (operand != u.Operand) { return Expression.MakeUnary(u.NodeType, operand, u.Type, u.Method); } return u; } protected virtual Expression VisitBinary(BinaryExpression b) { Expression left = this.Visit(b.Left); Expression right = this.Visit(b.Right); Expression conversion = this.Visit(b.Conversion); if (left != b.Left || right != b.Right || conversion != b.Conversion) { if (b.NodeType == ExpressionType.Coalesce && b.Conversion != null) { return Expression.Coalesce(left, right, conversion as LambdaExpression); } else { return Expression.MakeBinary(b.NodeType, left, right, b.IsLiftedToNull, b.Method); } } return b; } protected virtual Expression VisitTypeIs(TypeBinaryExpression b) { Expression expr = this.Visit(b.Expression); if (expr != b.Expression) { return Expression.TypeIs(expr, b.TypeOperand); } return b; } protected virtual Expression VisitConstant(ConstantExpression c) { return c; } protected virtual Expression VisitConditional(ConditionalExpression c) { Expression test = this.Visit(c.Test); Expression ifTrue = this.Visit(c.IfTrue); Expression ifFalse = this.Visit(c.IfFalse); if (test != c.Test || ifTrue != c.IfTrue || ifFalse != c.IfFalse) { return Expression.Condition(test, ifTrue, ifFalse); } return c; } protected virtual Expression VisitParameter(ParameterExpression p) { return p; } protected virtual Expression VisitMember(MemberExpression m) { Expression exp = this.Visit(m.Expression); if (exp != m.Expression) { return Expression.MakeMemberAccess(exp, m.Member); } return m; } protected virtual Expression VisitMethodCall(MethodCallExpression m) { Expression obj = this.Visit(m.Object); IEnumerable<Expression> args = this.VisitExpressionList(m.Arguments); if (obj != m.Object || args != m.Arguments) { return Expression.Call(obj, m.Method, args); } return m; } protected virtual ReadOnlyCollection<Expression> VisitExpressionList(ReadOnlyCollection<Expression> original) { List<Expression> list = null; for (int i = 0, n = original.Count; i < n; i++) { Expression p = this.Visit(original[i]); if (list != null) { list.Add(p); } else if (p != original[i]) { list = new List<Expression>(n); for (int j = 0; j < i; j++) { list.Add(original[j]); } list.Add(p); } } if (list != null) { return list.AsReadOnly(); } return original; } protected virtual MemberAssignment VisitMemberAssignment(MemberAssignment assignment) { Expression e = this.Visit(assignment.Expression); if (e != assignment.Expression) { return Expression.Bind(assignment.Member, e); } return assignment; } protected virtual MemberMemberBinding VisitMemberMemberBinding(MemberMemberBinding binding) { IEnumerable<MemberBinding> bindings = this.VisitBindingList(binding.Bindings); if (bindings != binding.Bindings) { return Expression.MemberBind(binding.Member, bindings); } return binding; } protected virtual MemberListBinding VisitMemberListBinding(MemberListBinding binding) { IEnumerable<ElementInit> initializers = this.VisitElementInitializerList(binding.Initializers); if (initializers != binding.Initializers) { return Expression.ListBind(binding.Member, initializers); } return binding; } protected virtual IEnumerable<MemberBinding> VisitBindingList(ReadOnlyCollection<MemberBinding> original) { List<MemberBinding> list = null; for (int i = 0, n = original.Count; i < n; i++) { MemberBinding b = this.VisitBinding(original[i]); if (list != null) { list.Add(b); } else if (b != original[i]) { list = new List<MemberBinding>(n); for (int j = 0; j < i; j++) { list.Add(original[j]); } list.Add(b); } } if (list != null) { return list; } return original; } protected virtual IEnumerable<ElementInit> VisitElementInitializerList(ReadOnlyCollection<ElementInit> original) { List<ElementInit> list = null; for (int i = 0, n = original.Count; i < n; i++) { ElementInit init = this.VisitElementInitializer(original[i]); if (list != null) { list.Add(init); } else if (init != original[i]) { list = new List<ElementInit>(n); for (int j = 0; j < i; j++) { list.Add(original[j]); } list.Add(init); } } if (list != null) { return list; } return original; } protected virtual Expression VisitLambda(LambdaExpression lambda) { Expression body = this.Visit(lambda.Body); // make sure we also visit the ParameterExpressions here. ParameterExpression[] parameters = lambda.Parameters.Select(p => (ParameterExpression)this.Visit(p)).ToArray(); if (body != lambda.Body || !parameters.SequenceEqual(lambda.Parameters)) { return Expression.Lambda(lambda.Type, body, parameters); } return lambda; } protected virtual NewExpression VisitNew(NewExpression nex) { IEnumerable<Expression> args = this.VisitExpressionList(nex.Arguments); if (args != nex.Arguments) { if (nex.Members != null) { return Expression.New(nex.Constructor, args, nex.Members); } else { return Expression.New(nex.Constructor, args); } } return nex; } protected virtual Expression VisitMemberInit(MemberInitExpression init) { NewExpression n = this.VisitNew(init.NewExpression); IEnumerable<MemberBinding> bindings = this.VisitBindingList(init.Bindings); if (n != init.NewExpression || bindings != init.Bindings) { return Expression.MemberInit(n, bindings); } return init; } protected virtual Expression VisitListInit(ListInitExpression init) { NewExpression n = this.VisitNew(init.NewExpression); IEnumerable<ElementInit> initializers = this.VisitElementInitializerList(init.Initializers); if (n != init.NewExpression || initializers != init.Initializers) { return Expression.ListInit(n, initializers); } return init; } protected virtual Expression VisitNewArray(NewArrayExpression na) { IEnumerable<Expression> exprs = this.VisitExpressionList(na.Expressions); if (exprs != na.Expressions) { if (na.NodeType == ExpressionType.NewArrayInit) { return Expression.NewArrayInit(na.Type.GetElementType(), exprs); } else { return Expression.NewArrayBounds(na.Type.GetElementType(), exprs); } } return na; } protected virtual Expression VisitInvocation(InvocationExpression iv) { IEnumerable<Expression> args = this.VisitExpressionList(iv.Arguments); Expression expr = this.Visit(iv.Expression); if (args != iv.Arguments || expr != iv.Expression) { return Expression.Invoke(expr, args); } return iv; } } }
/* MIT License Copyright (c) 2017 Saied Zarrinmehr 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.Linq; using System.Text; using System.Windows; using System.Windows.Media; using System.Windows.Shapes; using System.Windows.Controls; using System.Windows.Input; using SpatialAnalysis.FieldUtility; using SpatialAnalysis.CellularEnvironment; using SpatialAnalysis.Geometry; using System.ComponentModel; using SpatialAnalysis.Visualization; using SpatialAnalysis.Miscellaneous; namespace SpatialAnalysis.Agents.OptionalScenario.Visualization { /// <summary> /// Visualize scene /// </summary> public class AgentBarrierVisualHost : FrameworkElement { private OSMDocument _host { get; set; } private System.Windows.Media.Geometry _geometry; public System.Windows.Media.Geometry Geometry { get { return _geometry; } set { _geometry = value;} } private double boarderThickness { get; set; } private Brush boarderBrush { get; set; } private VisualCollection _children { get; set; } private Brush fillBrush { get; set; } private MenuItem visualizationMenu { get; set; } private MenuItem hide_Show_Menu { get; set; } private MenuItem boarderThickness_Menu { get; set; } private MenuItem boarderBrush_Menu { get; set; } private MenuItem fillBrush_Menu { get; set; } public AgentBarrierVisualHost() { this._children = new VisualCollection(this); this.boarderThickness = 1; this.boarderBrush = Brushes.Black; this.visualizationMenu = new MenuItem(); this.boarderBrush_Menu = new MenuItem() { Header = "Boarder Brush" }; this.boarderThickness_Menu = new MenuItem() { Header = "Boarder Thickness" }; this.fillBrush_Menu = new MenuItem() { Header = "Fill Brush" }; this.hide_Show_Menu = new MenuItem() { Header = "Hide" }; this.visualizationMenu.Items.Add(this.hide_Show_Menu); this.visualizationMenu.Items.Add(this.boarderThickness_Menu); this.visualizationMenu.Items.Add(this.fillBrush_Menu); this.visualizationMenu.Items.Add(this.boarderBrush_Menu); this.boarderThickness_Menu.Click += new RoutedEventHandler(boarderThickness_Menu_Click); this.fillBrush_Menu.Click += new RoutedEventHandler(fillBrush_Menu_Click); this.boarderBrush_Menu.Click += new RoutedEventHandler(boarderBrush_Menu_Click); this.hide_Show_Menu.Click += new RoutedEventHandler(hide_Show_Menu_Click); } private void hide_Show_Menu_Click(object sender, RoutedEventArgs e) { if (this.Visibility == System.Windows.Visibility.Visible) { this.Visibility = System.Windows.Visibility.Collapsed; this.hide_Show_Menu.Header = "Show"; this.boarderBrush_Menu.IsEnabled = false; this.fillBrush_Menu.IsEnabled = false; this.boarderThickness_Menu.IsEnabled = false; } else { this.Visibility = System.Windows.Visibility.Visible; this.hide_Show_Menu.Header = "Hide"; this.boarderBrush_Menu.IsEnabled = true; this.fillBrush_Menu.IsEnabled = true; this.boarderThickness_Menu.IsEnabled = true; } } private void setMenuName(String name) { this.visualizationMenu.Header = name; } private void boarderBrush_Menu_Click(object sender, RoutedEventArgs e) { BrushPicker colorPicker = new BrushPicker(this.boarderBrush); colorPicker.Owner = this._host; colorPicker.ShowDialog(); this.boarderBrush = colorPicker._Brush; this.draw(); colorPicker = null; } private void fillBrush_Menu_Click(object sender, RoutedEventArgs e) { BrushPicker colorPicker = new BrushPicker(this.fillBrush); colorPicker.Owner = this._host; colorPicker.ShowDialog(); this.fillBrush = colorPicker._Brush; this.draw(); colorPicker = null; } private void boarderThickness_Menu_Click(object sender, RoutedEventArgs e) { GetNumber gn = new GetNumber("Enter New Thickness Value", "New thickness value will be applied to the edges of barriers", this.boarderThickness); gn.Owner = this._host; gn.ShowDialog(); this.boarderThickness = gn.NumberValue; this.draw(); gn = null; } // Provide a required override for the VisualChildrenCount property. protected override int VisualChildrenCount { get { return _children.Count; } } // Provide a required override for the GetVisualChild method. protected override Visual GetVisualChild(int index) { if (index < 0 || index >= _children.Count) { throw new ArgumentOutOfRangeException(); } return _children[index]; } private void setGeometry(BarrierPolygon[] barriers) { StreamGeometry sg = new StreamGeometry(); using (StreamGeometryContext sgc = sg.Open()) { foreach (BarrierPolygon barrier in barriers) { sgc.BeginFigure(this.toPoint(barrier.BoundaryPoints[0]), true, true); for (int i = 1; i < barrier.Length; i++) { sgc.LineTo(this.toPoint(barrier.BoundaryPoints[i]), true, true); } } } sg.FillRule = FillRule.EvenOdd; this._geometry = sg; } private void draw() { if (this._geometry == null) { MessageBox.Show("Cannot Draw Null Geometry"); return; } try { this._children.Clear(); //double scale = this.RenderTransform.Value.M11 * this.RenderTransform.Value.M11 + // this.RenderTransform.Value.M12 * this.RenderTransform.Value.M12; //scale = Math.Sqrt(scale); //double t = this.boarderThickness / scale; Pen _pen = new Pen(this.boarderBrush, this.boarderThickness); DrawingVisual drawingVisual = new DrawingVisual(); using (DrawingContext drawingContext = drawingVisual.RenderOpen()) { drawingContext.DrawGeometry(this.fillBrush, _pen, this._geometry); } drawingVisual.Drawing.Freeze(); this._children.Add(drawingVisual); } catch (Exception e) { MessageBox.Show(e.Report()); } } public void Clear() { this._children.Clear(); this._geometry = null; this._host = null; this.boarderBrush = null; this._children = null; this.fillBrush = null; this.visualizationMenu.Items.Clear(); this.boarderThickness_Menu.Click -= boarderThickness_Menu_Click; this.fillBrush_Menu.Click -= fillBrush_Menu_Click; this.boarderBrush_Menu.Click -= boarderBrush_Menu_Click; this.hide_Show_Menu.Click -= hide_Show_Menu_Click; this.hide_Show_Menu = null; this.boarderThickness_Menu = null; this.boarderBrush_Menu = null; this.fillBrush_Menu = null; this.visualizationMenu = null; } private Point toPoint(UV uv) { return new Point(uv.U, uv.V); } public void SetHost(OSMDocument host, string menueName) { this._host = host; this.RenderTransform = this._host.RenderTransformation; this.setMenuName(menueName); this._host.ViewUtil.Items.Add(this.visualizationMenu); this.setGeometry(this._host.cellularFloor.BarrierBuffers); this.boarderBrush = new SolidColorBrush(Colors.Gold) { Opacity = .8 }; this.boarderThickness = this._host.UnitConvertor.Convert(0.25d); this.draw(); } public void ReDraw() { this._geometry = null; this.setGeometry(this._host.cellularFloor.BarrierBuffers); this.draw(); } } }
///////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Tencent is pleased to support the open source community by making behaviac available. // // Copyright (C) 2015-2017 THL A29 Limited, a Tencent company. All rights reserved. // // Licensed under the BSD 3-Clause License (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at http://opensource.org/licenses/BSD-3-Clause // // 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. ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// #if !BEHAVIAC_RELEASE #if !UNITY_WEBPLAYER && (UNITY_EDITOR || UNITY_STANDALONE_WIN || UNITY_STANDALONE_OSX) #define BEHAVIAC_HOTRELOAD #endif #endif // please define BEHAVIAC_NOT_USE_UNITY in your project file if you are not using unity #if !BEHAVIAC_NOT_USE_UNITY // if you have compiling errors complaining the following using 'UnityEngine', //usually, you need to define BEHAVIAC_NOT_USE_UNITY in your project file using UnityEngine; #endif//!BEHAVIAC_NOT_USE_UNITY using System; using System.IO; using System.Collections.Generic; using System.Reflection; using System.Threading; #if BEHAVIAC_USE_SYSTEM_XML using System.Xml; #else using System.Security; using MiniXml; #endif #if UNITY_EDITOR || UNITY_STANDALONE_WIN using System.Runtime.InteropServices; #endif namespace behaviac { #region Config public static class Config { private static bool m_bProfiling = false; public static void LogInfo() { Debug.Log(string.Format("Config::IsProfiling {0}", Config.IsProfiling ? "true" : "false")); Debug.Log(string.Format("Config::IsLogging {0}", Config.IsLogging ? "true" : "false")); Debug.Log(string.Format("Config::IsLoggingFlush {0}", Config.IsLoggingFlush ? "true" : "false")); Debug.Log(string.Format("Config::IsSocketing {0}", Config.IsSocketing ? "true" : "false")); Debug.Log(string.Format("Config::IsSocketBlocking {0}", Config.IsSocketBlocking ? "true" : "false")); Debug.Log(string.Format("Config::IsHotReload {0}", Config.IsHotReload ? "true" : "false")); Debug.Log(string.Format("Config::SocketPort {0}", Config.SocketPort)); } public static bool IsProfiling { get { return m_bProfiling; } set { #if !BEHAVIAC_RELEASE m_bProfiling = value; #else if (m_bProfiling) { behaviac.Debug.LogWarning("Profiling can't be enabled on Release! please don't define BEHAVIAC_RELEASE to enable it!\n"); } #endif } } public static bool IsLoggingOrSocketing { get { return IsLogging || IsSocketing; } } #if !BEHAVIAC_RELEASE private static bool m_bIsLogging = false; #else private static bool m_bIsLogging = false; #endif ///it is disable on pc by default public static bool IsLogging { get { //logging is only enabled on pc platform, it is disabled on android, ios, etc. return m_bIsLogging; } set { #if !BEHAVIAC_RELEASE m_bIsLogging = value; #else if (m_bIsLogging) { behaviac.Debug.LogWarning("Logging can't be enabled on Release! please don't define BEHAVIAC_RELEASE to enable it!\n"); } #endif } } #if !BEHAVIAC_RELEASE private static bool m_bIsLoggingFlush = false; #else private static bool m_bIsLoggingFlush = false; #endif ///it is disable on pc by default public static bool IsLoggingFlush { get { //logging is only enabled on pc platform, it is disabled on android, ios, etc. return m_bIsLoggingFlush; } set { #if !BEHAVIAC_RELEASE m_bIsLoggingFlush = value; #else if (m_bIsLoggingFlush) { behaviac.Debug.LogWarning("Logging can't be enabled on Release! please don't define BEHAVIAC_RELEASE to enable it!\n"); } #endif } } #if !BEHAVIAC_RELEASE private static bool m_bIsSocketing = true; #else private static bool m_bIsSocketing = false; #endif //it is enabled on pc by default public static bool IsSocketing { get { return m_bIsSocketing; } set { Debug.Check(!Workspace.Instance.IsInited, "please call Config.IsSocketing at the very begining!"); #if !BEHAVIAC_RELEASE m_bIsSocketing = value; #else if (m_bIsLogging) { behaviac.Debug.LogWarning("Socketing can't be enabled on Release! please don't define BEHAVIAC_RELEASE to enable it!\n"); } #endif } } private static bool m_bIsSocketBlocking = false; public static bool IsSocketBlocking { get { return m_bIsSocketBlocking; } set { Debug.Check(!Workspace.Instance.IsInited, "please call Config.IsSocketBlocking at the very begining!"); m_bIsSocketBlocking = value; } } private static ushort m_socketPort = 60636; public static ushort SocketPort { get { return m_socketPort; } set { Debug.Check(!Workspace.Instance.IsInited, "please call Config.SocketPort at the very begining!"); m_socketPort = value; } } private static bool m_bIsHotReload = true; public static bool IsHotReload { get { return m_bIsHotReload; } set { Debug.Check(!Workspace.Instance.IsInited, "please call Config.IsHotReload at the very begining!"); m_bIsHotReload = value; } } private static bool m_bIsSuppressingNonPublicWarning; /// <summary> /// Gets or sets a value indicating is supressing non public warning. /// </summary> /// <value><c>true</c> if is supressing non public warning; otherwise, <c>false</c>.</value> public static bool IsSuppressingNonPublicWarning { get { return m_bIsSuppressingNonPublicWarning; } set { m_bIsSuppressingNonPublicWarning = value; } } private static bool m_bPreloadBehaviors = true; public static bool PreloadBehaviors { get { return m_bPreloadBehaviors; } set { m_bPreloadBehaviors = value; } } } #endregion Config public class Workspace : IDisposable { #region Singleton private static Workspace ms_instance = null; public Workspace() { Debug.Check(ms_instance == null); ms_instance = this; } public void Dispose() { ms_instance = null; } public static Workspace Instance { get { if (ms_instance == null) { Workspace instance = new Workspace(); Debug.Check(instance != null); Debug.Check(ms_instance != null); } return ms_instance; } } #endregion Singleton [Flags] public enum EFileFormat { EFF_xml = 1, //specify to use xml EFF_bson = 2, //specify to use bson EFF_cs = 4, //specify to use cs EFF_default = EFF_xml | EFF_bson | EFF_cs, //use the format specified by SetWorkspaceSettings }; private EFileFormat fileFormat_ = EFileFormat.EFF_xml; public EFileFormat FileFormat { get { return fileFormat_; } set { fileFormat_ = value; } } private static string GetDefaultFilePath() { string path = ""; #if !BEHAVIAC_NOT_USE_UNITY string relativePath = "/Resources/behaviac/exported"; if (UnityEngine.Application.platform == UnityEngine.RuntimePlatform.WindowsEditor) { path = UnityEngine.Application.dataPath + relativePath; } else if (UnityEngine.Application.platform == UnityEngine.RuntimePlatform.WindowsPlayer) { path = UnityEngine.Application.dataPath + relativePath; } else { path = "Assets" + relativePath; } #endif return path; } private string m_filePath = null; //read from 'WorkspaceFile', prepending with 'WorkspacePath', relative to the exe's path public string FilePath { get { if (string.IsNullOrEmpty(m_filePath)) { m_filePath = GetDefaultFilePath(); } return this.m_filePath; } set { this.m_filePath = value; } } private string m_metaFile = null; public string MetaFile { get { return this.m_metaFile; } set { this.m_metaFile = value; } } private int m_frameSinceStartup = -1; // // Summary: // The frames since the game started. public virtual int FrameSinceStartup { get { #if !BEHAVIAC_NOT_USE_UNITY return (m_frameSinceStartup < 0) ? UnityEngine.Time.frameCount : m_frameSinceStartup; #else return m_frameSinceStartup; #endif } set { m_frameSinceStartup = value; } } private bool _useIntValue = false; public bool UseIntValue { get { return _useIntValue; } set { _useIntValue = value; } } private double m_doubleValueSinceStartup = -1.0; // Deprecated property, use DoubleValueSinceStartup insteadly. public virtual double TimeSinceStartup { get { Debug.Check(!UseIntValue); #if !BEHAVIAC_NOT_USE_UNITY if (this.m_doubleValueSinceStartup >= 0) { return this.m_doubleValueSinceStartup * 0.001; } return UnityEngine.Time.realtimeSinceStartup; #else return this.m_doubleValueSinceStartup * 0.001; #endif } set { Debug.Check(!UseIntValue); this.m_doubleValueSinceStartup = value * 1000; } } public virtual double DoubleValueSinceStartup { get { Debug.Check(!UseIntValue); #if !BEHAVIAC_NOT_USE_UNITY if (this.m_doubleValueSinceStartup >= 0) { return this.m_doubleValueSinceStartup; } return UnityEngine.Time.realtimeSinceStartup * 1000; #else return this.m_doubleValueSinceStartup; #endif } set { Debug.Check(!UseIntValue); this.m_doubleValueSinceStartup = value; } } private long m_intValueSinceStartup = -1; public virtual long IntValueSinceStartup { get { Debug.Check(UseIntValue); #if !BEHAVIAC_NOT_USE_UNITY if (this.m_intValueSinceStartup >= 0) { return this.m_intValueSinceStartup; } return (long)(UnityEngine.Time.realtimeSinceStartup * 1000); #else return this.m_intValueSinceStartup; #endif } set { Debug.Check(UseIntValue); this.m_intValueSinceStartup = value; } } #if !BEHAVIAC_RELEASE private string m_workspaceExportPathAbs; #endif public delegate void BehaviorNodeLoader(string nodeType, List<property_t> properties); event BehaviorNodeLoader BehaviorNodeLoaded; /** 'BehaviorNodeLoaded' will be called for ever behavior node. */ public void OnBehaviorNodeLoaded(string nodeType, List<property_t> properties) { if (BehaviorNodeLoaded != null) { BehaviorNodeLoaded(nodeType, properties); } } public delegate void DRespondToBreakHandler(string msg, string title); public event DRespondToBreakHandler RespondToBreakHandler; #if UNITY_EDITOR || UNITY_STANDALONE_WIN [DllImport("user32.dll", CharSet = CharSet.Auto)] private static extern int MessageBox(int hWnd, String text, String caption, int options); #endif // respond to msg, where msg = string.Format("BehaviorTreeTask Breakpoints at: '{0}{1}'\n\nOk to continue.", btMsg, actionResultStr); // display a message box to block the execution and then continue the execution after closing the message box public void RespondToBreak(string msg, string title) { if (RespondToBreakHandler != null) { RespondToBreakHandler(msg, title); return; } else { this.WaitforContinue(); //#if UNITY_EDITOR || UNITY_STANDALONE_WIN // if (Application.platform == RuntimePlatform.WindowsPlayer || Application.platform == RuntimePlatform.WindowsEditor) // { // const int MB_SYSTEMMODAL = 0x00001000; // MessageBox(0, msg, title, MB_SYSTEMMODAL); // } //#endif } //MessageBoxEvent System.Threading.Thread.Sleep(500); } private bool m_bRegistered = false; /** set the workspace settings 'workspaceRootPath_' specifies the file path of of the exported path of the workspace file which is configured in the workspace file(.workspace.xml), it can be either an absolute path or relative to the current path. 'format' specify the format to use, xml or bson, the default format is xml. @return false if 'path' is not a valid path holding valid data */ private bool m_bInited = false; internal bool IsInited { get { return m_bInited; } } public bool TryInit() { if (this.m_bInited) { return true; } this.m_bInited = true; ComparerRegister.Init(); ComputerRegister.Init(); Workspace.Instance.RegisterStuff(); Config.LogInfo(); if (string.IsNullOrEmpty(this.FilePath)) { behaviac.Debug.LogError("No FilePath file is specified!"); behaviac.Debug.Check(false); return false; } Debug.Log(string.Format("FilePath: {0}\n", this.FilePath)); Debug.Check(!this.FilePath.EndsWith("\\"), "use '/' instead of '\\'"); m_frameSinceStartup = -1; #if !BEHAVIAC_RELEASE this.m_workspaceExportPathAbs = Path.GetFullPath(this.FilePath).Replace('\\', '/'); if (!this.m_workspaceExportPathAbs.EndsWith("/")) { this.m_workspaceExportPathAbs += '/'; } #if BEHAVIAC_HOTRELOAD // set the file watcher if (behaviac.Config.IsHotReload) { if (this.FileFormat != EFileFormat.EFF_cs) { if (m_DirectoryMonitor == null) { m_DirectoryMonitor = new DirectoryMonitor(); m_DirectoryMonitor.Changed += new DirectoryMonitor.FileSystemEvent(OnFileChanged); } string filter = "*.*"; if (this.FileFormat == EFileFormat.EFF_xml) { filter = "*.xml"; } else if (this.FileFormat == EFileFormat.EFF_bson) { filter = "*.bson.bytes"; } if (File.Exists(this.FilePath)) { m_DirectoryMonitor.Start(this.FilePath, filter); } } } #endif//BEHAVIAC_HOTRELOAD //LogWorkspaceInfo(); #endif if (Config.IsSocketing) { bool isBlockSocket = Config.IsSocketBlocking; ushort port = Config.SocketPort; behaviac.SocketUtils.SetupConnection(isBlockSocket, port); } return true; } public void Cleanup() { if (Config.IsSocketing) { behaviac.SocketUtils.ShutdownConnection(); } this.UnLoadAll(); Debug.Check(this.m_bRegistered); ComparerRegister.Cleanup(); ComputerRegister.Cleanup(); this.UnRegisterStuff(); Context.Cleanup(-1); #if BEHAVIAC_HOTRELOAD if (behaviac.Config.IsHotReload) { m_modifiedFiles.Clear(); if (m_DirectoryMonitor != null) { m_DirectoryMonitor.Changed -= new DirectoryMonitor.FileSystemEvent(OnFileChanged); m_DirectoryMonitor.Stop(); m_DirectoryMonitor = null; } } #endif #if BEHAVIAC_USE_HTN PlannerTask.Cleanup(); #endif// LogManager.Instance.Close(); this.m_bInited = false; } internal void RegisterStuff() { //only register metas and others at the 1st time if (!this.m_bRegistered) { this.m_bRegistered = true; AgentMeta.Register(); //#if !BEHAVIAC_RELEASE // this.RegisterMetas(); //#endif } } private void UnRegisterStuff() { Debug.Check(this.m_bRegistered); this.UnRegisterBehaviorNode(); //#if !BEHAVIAC_RELEASE // this.UnRegisterMetas(); //#endif AgentMeta.UnRegister(); this.m_bRegistered = false; } public void LogWorkspaceInfo() { OperatingSystem osInfo = Environment.OSVersion; string platformID = osInfo.Platform.ToString(); string msg = string.Format("[platform] {0}\n", platformID); LogManager.Instance.LogWorkspace(msg); Workspace.EFileFormat format = this.FileFormat; string formatString = (format == Workspace.EFileFormat.EFF_bson ? "bson.bytes" : (format == Workspace.EFileFormat.EFF_cs ? "cs" : "xml")); msg = string.Format("[workspace] {0} \"{1}\"\n", formatString, ""); LogManager.Instance.LogWorkspace(msg); } private bool LoadWorkspaceSetting(string file, string ext, ref string workspaceFile) { try { byte[] pBuffer = ReadFileToBuffer(file, ext); if (pBuffer != null) { string xml = System.Text.Encoding.UTF8.GetString(pBuffer); #if BEHAVIAC_USE_SYSTEM_XML XmlDocument xmlDoc = new XmlDocument(); xmlDoc.LoadXml(xml); XmlNode rootNode = xmlDoc.DocumentElement; if (rootNode.Name == "workspace") { workspaceFile = rootNode.Attributes["path"].Value; return true; } #else SecurityParser xmlDoc = new SecurityParser(); xmlDoc.LoadXml(xml); SecurityElement rootNode = xmlDoc.ToXml(); if (rootNode.Tag == "workspace") { workspaceFile = rootNode.Attribute("path"); return true; } #endif } } catch (Exception e) { string errorInfo = string.Format("Load Workspace {0} Error : {1}", file, e.Message); behaviac.Debug.LogError(errorInfo); } return false; } #region HotReload #if BEHAVIAC_HOTRELOAD #region DirectoryMonitor public class DirectoryMonitor { public delegate void FileSystemEvent(string path); public event FileSystemEvent Changed; private readonly FileSystemWatcher m_fileSystemWatcher = new FileSystemWatcher(); private readonly Dictionary<string, DateTime> m_pendingEvents = new Dictionary<string, DateTime>(); private readonly Timer m_timer; private bool m_timerStarted = false; public DirectoryMonitor() { m_fileSystemWatcher.IncludeSubdirectories = true; m_fileSystemWatcher.NotifyFilter = NotifyFilters.LastWrite; m_fileSystemWatcher.Changed += new FileSystemEventHandler(OnChanged); m_fileSystemWatcher.EnableRaisingEvents = false; m_timer = new Timer(OnTimeout, null, Timeout.Infinite, Timeout.Infinite); } public void Start(string dirPath, string filter) { m_fileSystemWatcher.Path = dirPath; m_fileSystemWatcher.Filter = filter; m_fileSystemWatcher.EnableRaisingEvents = true; } public void Stop() { m_fileSystemWatcher.EnableRaisingEvents = false; } private void OnChanged(object sender, FileSystemEventArgs e) { // Don't want other threads messing with the pending events right now lock (m_pendingEvents) { // Save a timestamp for the most recent event for this path m_pendingEvents[e.FullPath] = DateTime.Now; // Start a timer if not already started if (!m_timerStarted) { m_timer.Change(100, 100); m_timerStarted = true; } } } private void OnTimeout(object state) { List<string> paths; // Don't want other threads messing with the pending events right now lock (m_pendingEvents) { // Get a list of all paths that should have events thrown paths = FindReadyPaths(m_pendingEvents); // Remove paths that are going to be used now paths.ForEach(delegate(string path) { m_pendingEvents.Remove(path); }); // Stop the timer if there are no more events pending if (m_pendingEvents.Count == 0) { m_timer.Change(Timeout.Infinite, Timeout.Infinite); m_timerStarted = false; } } // Fire an event for each path that has changed paths.ForEach(delegate(string path) { FireEvent(path); }); } private List<string> FindReadyPaths(Dictionary<string, DateTime> events) { List<string> results = new List<string>(); DateTime now = DateTime.Now; var e = events.GetEnumerator(); while (e.MoveNext()) { // If the path has not received a new event in the last 75ms // an event for the path should be fired double diff = now.Subtract(e.Current.Value).TotalMilliseconds; if (diff >= 75) { results.Add(e.Current.Key); } } return results; } private void FireEvent(string path) { FileSystemEvent evt = this.Changed; if (evt != null) { evt(path); } } } #endregion DirectoryMonitor private DirectoryMonitor m_DirectoryMonitor = null; private List<string> m_ModifiedFiles = new List<string>(); private void OnFileChanged(string fullpath) { if (string.IsNullOrEmpty(fullpath)) { return; } //behaviac.behaviac.Debug.LogWarning(string.Format("OnFileChanged:{0}", fullpath)); int index = -1; for (int i = 0; i < fullpath.Length - 1; ++i) { if (fullpath[i] == '.' && fullpath[i + 1] != '.' && fullpath[i + 1] != '/' && fullpath[i + 1] != '\\') { index = i; break; } } if (index >= 0) { string filename = fullpath.Substring(0, index).Replace('\\', '/'); string ext = fullpath.Substring(index).ToLowerInvariant(); if (!string.IsNullOrEmpty(ext) && (this.FileFormat & EFileFormat.EFF_xml) == EFileFormat.EFF_xml && ext == ".xml" || (this.FileFormat & EFileFormat.EFF_bson) == EFileFormat.EFF_bson && ext == ".bson.bytes") { int pos = filename.IndexOf(m_workspaceExportPathAbs); if (pos != -1) { filename = filename.Substring(m_workspaceExportPathAbs.Length + pos); lock (m_ModifiedFiles) { if (!m_ModifiedFiles.Contains(filename)) { m_ModifiedFiles.Add(filename); } } } } } } private List<string> m_modifiedFiles = new List<string>(); private List<string> ModifiedFiles { get { return m_modifiedFiles; } } private bool GetModifiedFiles() { if (m_ModifiedFiles.Count > 0) { lock (m_ModifiedFiles) { m_modifiedFiles.Clear(); m_modifiedFiles.AddRange(m_ModifiedFiles); m_ModifiedFiles.Clear(); } return true; } return false; } protected void HotReload() { #if !BEHAVIAC_RELEASE if (behaviac.Config.IsHotReload) { if (GetModifiedFiles()) { for (int i = 0; i < ModifiedFiles.Count; ++i) { string relativePath = ModifiedFiles[i]; if (m_allBehaviorTreeTasks.ContainsKey(relativePath)) { behaviac.Debug.LogWarning(string.Format("Hotreload:{0}", relativePath)); if (Load(relativePath, true)) { BTItem_t btItem = m_allBehaviorTreeTasks[relativePath]; BehaviorTree behaviorTree = m_behaviortrees[relativePath]; for (int j = 0; j < btItem.bts.Count; ++j) { BehaviorTreeTask behaviorTreeTask = btItem.bts[j]; behaviorTreeTask.reset(null); behaviorTreeTask.Clear(); behaviorTreeTask.Init(behaviorTree); } for (int j = 0; j < btItem.agents.Count; ++j) { Agent agent = btItem.agents[j]; agent.bthotreloaded(behaviorTree); } } } } } } #endif } #else public void SetAutoHotReload(bool enable) { } public bool GetAutoHotReload() { return false; } public void HotReload() { } #endif//#if BEHAVIAC_HOTRELOAD #endregion HotReload #region Development #if !BEHAVIAC_RELEASE private string m_applogFilter; #endif //[breakpoint] set TestBehaviorGroup\btunittest.xml Sequence[3] enter //[breakpoint] set TestBehaviorGroup\btunittest.xml Sequence[3] exit //[breakpoint] clear TestBehaviorGroup\btunittest.xml Sequence[3] enter private class BreakpointInfo_t { public string btname; public ushort hit_config; public EActionResult action_result; public BreakpointInfo_t() { hit_config = 0; action_result = EActionResult.EAR_all; } }; private Dictionary<uint, BreakpointInfo_t> m_breakpoints = new Dictionary<uint, BreakpointInfo_t>(); private Dictionary<CStringID, int> m_actions_count = new Dictionary<CStringID, int>(); //[breakpoint] add TestBehaviorGroup\btunittest.xml.Sequence[3]:enter all Hit=1 //[breakpoint] add TestBehaviorGroup\btunittest.xml.Sequence[3]:exit all Hit=1 //[breakpoint] add TestBehaviorGroup\btunittest.xml.Sequence[3]:exit success Hit=1 //[breakpoint] add TestBehaviorGroup\btunittest.xml.Sequence[3]:exit failure Hit=1 //[breakpoint] remove TestBehaviorGroup\btunittest.x1ml.Sequence[3]:enter all Hit=10 private void ParseBreakpoint(string[] tokens) { BreakpointInfo_t bp = new BreakpointInfo_t(); bool bAdd = false; bool bRemove = false; if (tokens[1] == "add") { bAdd = true; } else if (tokens[1] == "remove") { bRemove = true; } else { Debug.Check(false); } bp.btname = tokens[2]; if (tokens[3] == "all") { Debug.Check(bp.action_result == EActionResult.EAR_all); } else if (tokens[3] == "success") { bp.action_result = EActionResult.EAR_success; } else if (tokens[3] == "failure") { bp.action_result = EActionResult.EAR_failure; } else { Debug.Check(false); } const string kHitNumber = "Hit="; int posb = tokens[4].IndexOf(kHitNumber); if (posb != -1) { posb = tokens[4].IndexOf('='); Debug.Check(posb != -1); int size = -1; //tokens[4] is the last one with '\n' int pose = tokens[4].IndexOf('\n'); if (pose != -1) { size = pose - posb - 1; } else { size = tokens[4].Length - posb - 1; } string numString = tokens[4].Substring(posb + 1, size); bp.hit_config = ushort.Parse(numString); } uint bpid = Utils.MakeVariableId(bp.btname); if (bAdd) { m_breakpoints[bpid] = bp; } else if (bRemove) { m_breakpoints.Remove(bpid); } } private void ParseProfiling(string[] tokens) { if (tokens[1] == "true") { Config.IsProfiling = true; } else if (tokens[1] == "false") { Config.IsProfiling = false; } else { Debug.Check(false); } } private void ParseAppLogFilter(string[] tokens) { #if !BEHAVIAC_RELEASE m_applogFilter = tokens[1]; #endif } //[property]Player#@Player int Index->0 private void ParseProperty(string[] tokens) { #if !BEHAVIAC_RELEASE string agentName = tokens[1]; Agent pAgent = Agent.GetAgent(agentName); //pAgent could be 0 if (!System.Object.ReferenceEquals(pAgent, null) && tokens.Length == 4) { //string varTypeName = tokens[2]; string varNameValue = tokens[3]; int size = -1; int posb = varNameValue.IndexOf("->"); //varNameValue is the last one with '\n' int pose = varNameValue.IndexOf('\n'); if (pose == -1) { pose = varNameValue.Length; } size = pose - posb - 2; string varName = varNameValue.Substring(0, posb); string varValue = varNameValue.Substring(posb + 2, size); // If pAgent.name is "null", pAgent != null will return false. if (pAgent != null && !System.Object.ReferenceEquals(pAgent, null)) { pAgent.SetVariableFromString(varName, varValue); }//end of if (pAgent) } #endif } private int m_frame = 0; protected void LogFrames() { #if !BEHAVIAC_RELEASE if (Config.IsLoggingOrSocketing) { LogManager.Instance.Log("[frame]{0}\n", (this.FrameSinceStartup >= 0) ? this.FrameSinceStartup : (this.m_frame++)); } #endif } protected void WaitforContinue() { #if !BEHAVIAC_RELEASE while (!HandleRequests()) { System.Threading.Thread.Sleep(200); } #endif//BEHAVIAC_RELEASE } protected bool HandleRequests() { bool bContinue = false; #if !BEHAVIAC_RELEASE if (Config.IsSocketing) { string command = ""; if (SocketUtils.ReadText(ref command)) { const string kBreakpoint = "[breakpoint]"; const string kProperty = "[property]"; const string kProfiling = "[profiling]"; const string kStart = "[start]"; const string kAppLogFilter = "[applogfilter]"; const string kContinue = "[continue]"; const string kCloseConnection = "[closeconnection]"; string[] cs = command.Split('\n'); foreach (string c in cs) { if (string.IsNullOrEmpty(c)) { continue; } string[] tokens = c.Split(' '); if (tokens[0] == kBreakpoint) { ParseBreakpoint(tokens); } else if (tokens[0] == kProperty) { ParseProperty(tokens); } else if (tokens[0] == kProfiling) { ParseProfiling(tokens); } else if (tokens[0] == kStart) { m_breakpoints.Clear(); bContinue = true; } else if (tokens[0] == kAppLogFilter) { ParseAppLogFilter(tokens); } else if (tokens[0] == kContinue) { bContinue = true; } else if (tokens[0] == kCloseConnection) { m_breakpoints.Clear(); bContinue = true; } else { Debug.Check(false); } }//end of for }//end of if (Socket::ReadText(command)) else { if (!SocketUtils.IsConnected()) { //connection has something wrong bContinue = true; } } } else { bContinue = true; } #endif return bContinue; } private bool m_bExecAgents = false; public bool IsExecAgents { get { return this.m_bExecAgents; } set { this.m_bExecAgents = value; } } public void DebugUpdate() { this.LogFrames(); this.HandleRequests(); if (behaviac.Config.IsHotReload) { this.HotReload(); } } public void Update() { this.DebugUpdate(); if (this.m_bExecAgents) { int contextId = -1; Context.execAgents(contextId); } } public void LogCurrentStates() { int contextId = -1; Context.LogCurrentStates(contextId); } public bool CheckBreakpoint(Agent pAgent, BehaviorNode b, string action, EActionResult actionResult) { #if !BEHAVIAC_RELEASE if (Config.IsSocketing) { string bpStr = BehaviorTask.GetTickInfo(pAgent, b, action); uint bpid = Utils.MakeVariableId(bpStr); if (m_breakpoints.ContainsKey(bpid)) { BreakpointInfo_t bp = m_breakpoints[bpid]; if ((bp.action_result & actionResult) != 0) { int count = GetActionCount(bpStr); Debug.Check(count > 0); if (bp.hit_config == 0 || bp.hit_config == count) { return true; } } } } #endif return false; } public bool CheckAppLogFilter(string filter) { #if !BEHAVIAC_RELEASE if (Config.IsSocketing) { //m_applogFilter is UPPER if (!string.IsNullOrEmpty(m_applogFilter)) { if (m_applogFilter == "ALL") { return true; } else { string f = filter.ToUpper(); if (m_applogFilter == f) { return true; } } } } #endif return false; } public int UpdateActionCount(string actionString) { lock (m_actions_count) { int count = 1; CStringID actionId = new CStringID(actionString); if (!m_actions_count.ContainsKey(actionId)) { m_actions_count[actionId] = count; } else { count = m_actions_count[actionId]; count++; m_actions_count[actionId] = count; } return count; } } public int GetActionCount(string actionString) { lock (m_actions_count) { int count = 0; CStringID actionId = new CStringID(actionString); if (m_actions_count.ContainsKey(actionId)) { count = m_actions_count[actionId]; } return count; } } #endregion Development #region Load private Dictionary<string, BehaviorTree> m_behaviortrees; private Dictionary<string, BehaviorTree> BehaviorTrees { get { if (m_behaviortrees == null) { m_behaviortrees = new Dictionary<string, BehaviorTree>(); } return m_behaviortrees; } } private Dictionary<string, MethodInfo> m_btCreators; private Dictionary<string, MethodInfo> BTCreators { get { if (m_btCreators == null) { m_btCreators = new Dictionary<string, MethodInfo>(); } return m_btCreators; } } public void RecordBTAgentMapping(string relativePath, Agent agent) { if (m_allBehaviorTreeTasks == null) { m_allBehaviorTreeTasks = new Dictionary<string, BTItem_t>(); } if (!m_allBehaviorTreeTasks.ContainsKey(relativePath)) { m_allBehaviorTreeTasks[relativePath] = new BTItem_t(); } BTItem_t btItems = m_allBehaviorTreeTasks[relativePath]; //bool bFound = false; if (btItems.agents.IndexOf(agent) == -1) { btItems.agents.Add(agent); } } public void UnLoad(string relativePath) { Debug.Check(string.IsNullOrEmpty(StringUtils.FindExtension(relativePath)), "no extention to specify"); Debug.Check(this.IsValidPath(relativePath)); if (BehaviorTrees.ContainsKey(relativePath)) { BehaviorTrees.Remove(relativePath); } } public void UnLoadAll() { m_allBehaviorTreeTasks.Clear(); BehaviorTrees.Clear(); BTCreators.Clear(); } public byte[] ReadFileToBuffer(string file, string ext) { byte[] pBuffer = FileManager.Instance.FileOpen(file, ext); return pBuffer; } public void PopFileFromBuffer(string file, string ext, byte[] pBuffer) { FileManager.Instance.FileClose(file, ext, pBuffer); } private string getValidFilename(string filename) { filename = filename.Replace("/", "_"); filename = filename.Replace("-", "_"); return filename; } /** Load the specified behavior tree the workspace export path is provided by Workspace.FilePath the file format(xml/bson) is provided by Workspace.FileFormat generally, you need to derive Workspace and override FilePath and FileFormat, then, instantiate your derived Workspace at the very beginning @param relativePath a path relateve to the workspace exported path. relativePath should not include extension. @param bForce force to load, otherwise it just uses the one in the cache */ public bool Load(string relativePath, bool bForce) { Debug.Check(string.IsNullOrEmpty(StringUtils.FindExtension(relativePath)), "no extention to specify"); Debug.Check(this.IsValidPath(relativePath)); TryInit(); BehaviorTree pBT = null; if (BehaviorTrees.ContainsKey(relativePath)) { if (!bForce) { return true; } pBT = BehaviorTrees[relativePath]; } string fullPath = Path.Combine(this.FilePath, relativePath); fullPath = fullPath.Replace('\\', '/'); string ext = ""; EFileFormat f = this.FileFormat; this.HandleFileFormat(fullPath, ref ext, ref f); bool bLoadResult = false; bool bCleared = false; bool bNewly = false; if (pBT == null) { bNewly = true; pBT = new BehaviorTree(); //in case of circular referencebehavior BehaviorTrees[relativePath] = pBT; } Debug.Check(pBT != null); if (f == EFileFormat.EFF_xml || f == EFileFormat.EFF_bson) { byte[] pBuffer = ReadFileToBuffer(fullPath, ext); if (pBuffer != null) { //if forced to reload if (!bNewly) { bCleared = true; pBT.Clear(); } if (f == EFileFormat.EFF_xml) { bLoadResult = pBT.load_xml(pBuffer); } else { bLoadResult = pBT.load_bson(pBuffer); } PopFileFromBuffer(fullPath, ext, pBuffer); } else { Debug.LogError(string.Format("'{0}' doesn't exist!, Please set Workspace.FilePath", fullPath)); Debug.Check(false); } } else if (f == EFileFormat.EFF_cs) { if (!bNewly) { bCleared = true; pBT.Clear(); } try { MethodInfo m = null; if (BTCreators.ContainsKey(relativePath)) { m = BTCreators[relativePath]; } else { string clsName = "behaviac.bt_" + getValidFilename(relativePath); Type type = Utils.GetType(clsName); if (type != null) { m = type.GetMethod("build_behavior_tree", BindingFlags.Public | BindingFlags.Static); Debug.Check(m != null); if (m != null) { BTCreators[relativePath] = m; } } } if (m != null) { object[] args = { pBT }; bLoadResult = (bool)m.Invoke(null, args); } else { Debug.Check(false); Debug.LogError("The generated_behaviors.cs file should be added into the app."); } } catch (Exception e) { string errorInfo = string.Format("The behavior {0} failed to be loaded : {1}", relativePath, e.Message); Debug.LogError(errorInfo); } } else { Debug.Check(false); } if (bLoadResult) { Debug.Check(pBT.GetName() == relativePath); if (!bNewly) { Debug.Check(BehaviorTrees[pBT.GetName()] == pBT); } } else { if (bNewly) { bool removed = BehaviorTrees.Remove(relativePath); Debug.Check(removed); } else if (bCleared) { //it has been cleared but failed to load, to remove it BehaviorTrees.Remove(relativePath); } behaviac.Debug.LogError(string.Format("{0} is not loaded!", fullPath)); } return bLoadResult; } public void HandleFileFormat(string fullPath, ref string ext, ref EFileFormat f) { if (f == EFileFormat.EFF_default) { // try to load the behavior in xml ext = ".xml"; if (FileManager.Instance.FileExist(fullPath, ext)) { f = EFileFormat.EFF_xml; } else { // try to load the behavior in bson ext = ".bson"; if (FileManager.Instance.FileExist(fullPath, ext)) { f = EFileFormat.EFF_bson; } else { // try to load the behavior in cs f = EFileFormat.EFF_cs; } } } else if (f == EFileFormat.EFF_xml || f == EFileFormat.EFF_cs) { ext = ".xml"; } else if (f == EFileFormat.EFF_bson) { ext = ".bson"; } //else if (f == EFileFormat.EFF_cs) //{ //} } public bool Load(string relativePath) { return this.Load(relativePath, false); } public BehaviorTree LoadBehaviorTree(string relativePath) { if (BehaviorTrees.ContainsKey(relativePath)) { return BehaviorTrees[relativePath]; } else { bool bOk = this.Load(relativePath, true); if (bOk) { return BehaviorTrees[relativePath]; } } return null; } public bool IsValidPath(string relativePath) { Debug.Check(!string.IsNullOrEmpty(relativePath)); if (relativePath[0] == '.' && (relativePath[1] == '/' || relativePath[1] == '\\')) { // ./dummy_bt return false; } else if (relativePath[0] == '/' || relativePath[0] == '\\') { // /dummy_bt return false; } return true; } private class BTItem_t { public List<BehaviorTreeTask> bts = new List<BehaviorTreeTask>(); public List<Agent> agents = new List<Agent>(); }; private Dictionary<string, BTItem_t> m_allBehaviorTreeTasks = new Dictionary<string, BTItem_t>(); /** uses the behavior tree in the cache, if not loaded yet, it loads the behavior tree first */ public BehaviorTreeTask CreateBehaviorTreeTask(string relativePath) { Debug.Check(string.IsNullOrEmpty(Path.GetExtension(relativePath)), "no extention to specify"); Debug.Check(this.IsValidPath(relativePath)); BehaviorTree bt = null; if (BehaviorTrees.ContainsKey(relativePath)) { bt = BehaviorTrees[relativePath]; } else { bool bOk = this.Load(relativePath); if (bOk) { bt = BehaviorTrees[relativePath]; } } if (bt != null) { BehaviorTask task = bt.CreateAndInitTask(); Debug.Check(task is BehaviorTreeTask); BehaviorTreeTask behaviorTreeTask = task as BehaviorTreeTask; if (!m_allBehaviorTreeTasks.ContainsKey(relativePath)) { m_allBehaviorTreeTasks[relativePath] = new BTItem_t(); } BTItem_t btItem = m_allBehaviorTreeTasks[relativePath]; if (!btItem.bts.Contains(behaviorTreeTask)) { btItem.bts.Add(behaviorTreeTask); } return behaviorTreeTask; } return null; } public void DestroyBehaviorTreeTask(BehaviorTreeTask behaviorTreeTask, Agent agent) { if (behaviorTreeTask != null) { if (m_allBehaviorTreeTasks.ContainsKey(behaviorTreeTask.GetName())) { BTItem_t btItem = m_allBehaviorTreeTasks[behaviorTreeTask.GetName()]; btItem.bts.Remove(behaviorTreeTask); if (!System.Object.ReferenceEquals(agent, null)) { btItem.agents.Remove(agent); } } BehaviorTask.DestroyTask(behaviorTreeTask); } } public Dictionary<string, BehaviorTree> GetBehaviorTrees() { return m_behaviortrees; } #endregion Load private Dictionary<string, Type> m_behaviorNodeTypes = new Dictionary<string, Type>(); private void UnRegisterBehaviorNode() { Debug.Check(m_behaviorNodeTypes != null); m_behaviorNodeTypes.Clear(); } public BehaviorNode CreateBehaviorNode(string className) { Type type = null; if (m_behaviorNodeTypes.ContainsKey(className)) { type = m_behaviorNodeTypes[className]; } else { string fullClassName = "behaviac." + className.Replace("::", "."); type = this.CallingAssembly.GetType(fullClassName, false); Debug.Check(type != null); if (type == null) { type = this.CallingAssembly.GetType(className, false); } if (type != null) { m_behaviorNodeTypes[className] = type; } } if (type != null) { object p = Activator.CreateInstance(type); return p as BehaviorNode; } return null; } private Assembly m_callingAssembly = null; private Assembly CallingAssembly { get { if (m_callingAssembly == null) { m_callingAssembly = Assembly.GetCallingAssembly(); } return m_callingAssembly; } } public bool ExportMetas(string xmlMetaFilePath, bool onlyExportPublicMembers) { Debug.LogWarning("deprecated, please remove calling of ExportMetas"); return false; } public bool ExportMetas(string exportPathRelativeToWorkspace) { return ExportMetas(exportPathRelativeToWorkspace, false); } } }
using System; using System.Net.Sockets; using System.Net; using System.IO; using System.Text.RegularExpressions; using System.Diagnostics; namespace RTMPDownloader { public class NetworkServer { TcpListener listener; public NetworkServer (){} public bool Abre(int puerto){ try{ Console.WriteLine ("Abriendo servidor en \"127.0.0.1:" + puerto + "\"..."); listener = new TcpListener (IPAddress.Loopback, puerto); listener.Start (); Console.WriteLine ("Servidor abierto."); return true; } catch(Exception e){ Console.WriteLine ("h0"); Console.WriteLine (e); Debug.WriteLine(Utilidades.WL("h0")); Debug.WriteLine(Utilidades.WL(e.ToString())); return false; } } private string streamReadLine(Stream inputStream) { int next_char; string data = ""; while (true) { next_char = inputStream.ReadByte(); if (next_char == '\n') { break; } if (next_char == '\r') { continue; } //if (next_char == -1) { System.Threading.Thread.Sleep(1); continue; } if (next_char == -1) { break; } data += Convert.ToChar(next_char); } return data; } private static byte[] GetBytes(string str) { byte[] bytes = new byte[str.Length * sizeof(char)]; System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length); return bytes; } private void streamWrite(Stream inputStream, string text) { inputStream.Flush (); byte[] bytes = System.Text.Encoding.UTF8.GetBytes (text); inputStream.Write (bytes, 0, bytes.Length); } /* public bool puedeEscuchar (){ return listener.Pending; } */ public RespuestaServer Escucha () { try{ /*if(client != null) return new RespuestaServer(new RespuestaHTTP(false), null, null);*/ TcpClient client = listener.AcceptTcpClient (); //Console.WriteLine ("Conexion establecida"); Stream stream = new BufferedStream(client.GetStream ()); //stream = client.GetStream (); string GETurl = streamReadLine(stream); if(GETurl != null){ string pattern = " (.*?) HTTP"; MatchCollection matches = Regex.Matches (GETurl, pattern); string url=""; if (matches.Count > 0) { GroupCollection gc = matches[0].Groups; CaptureCollection cc = gc[1].Captures; url = cc[0].Value; } //Console.WriteLine (url); pattern = "\\?(&?([^=^&]+?)=([^&]*))*"; matches = Regex.Matches (url, pattern); //Utilidades.print_r_regex(matches); if (matches.Count > 0) { GroupCollection gc = matches[0].Groups; CaptureCollection variables = gc[2].Captures; CaptureCollection valores = gc[3].Captures; ParametroGet[] parametros = new ParametroGet[variables.Count]; for(int i = 0; i < variables.Count; i++){ parametros[i] = new ParametroGet( Uri.UnescapeDataString(variables[i].Value).Replace("+", " "), Uri.UnescapeDataString(valores[i].Value).Replace("+", " ")); } return new RespuestaServer(new RespuestaHTTP(url, parametros), client, stream); } return new RespuestaServer(new RespuestaHTTP(url), client, stream); } return new RespuestaServer(new RespuestaHTTP(false), client, stream); } catch(Exception e){ Console.WriteLine ("h1"); Console.WriteLine (e); Debug.WriteLine(Utilidades.WL("h1")); Debug.WriteLine(Utilidades.WL(e.ToString())); //CierraCliente (); return new RespuestaServer(new RespuestaHTTP(false), null, null); } } public bool Envia (RespuestaServer respuestaServer, string que) { try { streamWrite(respuestaServer.stream, "HTTP/1.1 200 OK\r\n"+ "Connection: Close\r\n"+ "Content-Type: text/html; charset=utf-8\r\n"+ "Connection: Close\r\n"+ "\r\n"+que); CierraCliente (respuestaServer); return true; } catch (Exception e) { Console.WriteLine ("h2"); Console.WriteLine (e); Debug.WriteLine(Utilidades.WL("h2")); Debug.WriteLine(Utilidades.WL(e.ToString())); return false; } } public bool EnviaRaw(RespuestaServer respuestaServer, String contentType, byte[] contenido){ try { streamWrite(respuestaServer.stream, "HTTP/1.1 200 OK\r\n"+ "Connection: Close\r\n"+ "Content-Type: "+contentType+"\r\n"+ "Connection: Close\r\n"+ "\r\n"); respuestaServer.stream.Write(contenido, 0, contenido.Length); CierraCliente (respuestaServer); return true; } catch (Exception e) { Console.WriteLine ("h10"); Console.WriteLine (e); Debug.WriteLine(Utilidades.WL("h10")); Debug.WriteLine(Utilidades.WL(e.ToString())); return false; } } public bool EnviaLocation (RespuestaServer respuestaServer, String que) { try { streamWrite(respuestaServer.stream, "HTTP/1.1 301 OK\r\n"); streamWrite(respuestaServer.stream, "Location: " + que+"\r\n"); streamWrite(respuestaServer.stream, "Content-Length: 0\r\n"); streamWrite(respuestaServer.stream, "Connection: Close\r\n"); streamWrite(respuestaServer.stream, "\r\n"); CierraCliente (respuestaServer); return true; } catch (Exception e) { Console.WriteLine("h3"); Console.WriteLine (e); Debug.WriteLine(Utilidades.WL("h3")); Debug.WriteLine(Utilidades.WL(e.ToString())); return false; } } public void CierraCliente (RespuestaServer respuestaServer) { try{ respuestaServer.stream.Dispose(); respuestaServer.stream.Close (); respuestaServer.stream = null; //Console.WriteLine("Cliente cerrado."); respuestaServer.client.Close(); respuestaServer.client = null; } catch(Exception e){ Console.WriteLine("h4"); Console.WriteLine (e); Debug.WriteLine(Utilidades.WL("h4")); Debug.WriteLine(Utilidades.WL(e.ToString())); } } public void Cierra () { try{ //CierraCliente(); this.listener.Stop (); Console.WriteLine("Servidor cerrado."); } catch(Exception e){ Console.WriteLine("h5"); Console.WriteLine (e); Debug.WriteLine(Utilidades.WL("h5")); Debug.WriteLine(Utilidades.WL(e.ToString())); } } } public class RespuestaHTTP { public String url; public String path; public ParametroGet[] parametros; bool _correcto; public bool correcto{ get{ return _correcto; } set{ } } public RespuestaHTTP (String url) { this._correcto = true; this.setURL(url); } public RespuestaHTTP (bool correcto) { this.correcto = correcto; } public RespuestaHTTP (String url, ParametroGet[] parametros) { this.setURL(url); this.parametros = parametros; this._correcto = true; } void setURL(String url){ this.url = url; String pattern = "[^\\?]*"; MatchCollection matches = Regex.Matches (url, pattern); //Utilidades.print_r_regex(matches); this.path = matches[0].Groups[0].Captures[0].Value; } public bool tieneParametros(){ return parametros != null; } public bool existeParametro(String variable){ if (!tieneParametros()) return false; for(int i = 0; i < parametros.Length; i++){ if (parametros[i].variable == variable) return true; } return false; } public String getParametro(String variable){ if (!tieneParametros()) return ""; for (int i = 0; i < parametros.Length; i++) { if (parametros [i].variable == variable) return parametros [i].valor; } return ""; } } public class ParametroGet{ String _variable; String _valor; public String variable{ get{ return _variable; } set{ } } public String valor{ get{ return _valor; } set{ } } public ParametroGet (String variable, String valor) { this._variable = variable; this._valor = valor; } } public class RespuestaServer{ RespuestaHTTP _respuestaHTTP; TcpClient _client; Stream _stream; public RespuestaHTTP respuestaHTTP{ get{ return _respuestaHTTP; } set{ } } public TcpClient client{ get{ return _client; } set{ } } public Stream stream{ get{ return _stream; } set{ } } public RespuestaServer (RespuestaHTTP respuestaHTTP, TcpClient client, Stream stream) { this._respuestaHTTP = respuestaHTTP; this._client = client; this._stream = stream; } } }
// 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. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // // // A pair of schedulers that together support concurrent (reader) / exclusive (writer) // task scheduling. Using just the exclusive scheduler can be used to simulate a serial // processing queue, and using just the concurrent scheduler with a specified // MaximumConcurrentlyLevel can be used to achieve a MaxDegreeOfParallelism across // a bunch of tasks, parallel loops, dataflow blocks, etc. // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; using System.Security; using System.Security.Permissions; namespace System.Threading.Tasks { /// <summary> /// Provides concurrent and exclusive task schedulers that coordinate to execute /// tasks while ensuring that concurrent tasks may run concurrently and exclusive tasks never do. /// </summary> [DebuggerDisplay("Concurrent={ConcurrentTaskCountForDebugger}, Exclusive={ExclusiveTaskCountForDebugger}, Mode={ModeForDebugger}")] [DebuggerTypeProxy(typeof(ConcurrentExclusiveSchedulerPair.DebugView))] public class ConcurrentExclusiveSchedulerPair { /// <summary>A dictionary mapping thread ID to a processing mode to denote what kinds of tasks are currently being processed on this thread.</summary> private readonly ConcurrentDictionary<int, ProcessingMode> m_threadProcessingMapping = new ConcurrentDictionary<int, ProcessingMode>(); /// <summary>The scheduler used to queue and execute "concurrent" tasks that may run concurrently with other concurrent tasks.</summary> private readonly ConcurrentExclusiveTaskScheduler m_concurrentTaskScheduler; /// <summary>The scheduler used to queue and execute "exclusive" tasks that must run exclusively while no other tasks for this pair are running.</summary> private readonly ConcurrentExclusiveTaskScheduler m_exclusiveTaskScheduler; /// <summary>The underlying task scheduler to which all work should be scheduled.</summary> private readonly TaskScheduler m_underlyingTaskScheduler; /// <summary> /// The maximum number of tasks allowed to run concurrently. This only applies to concurrent tasks, /// since exlusive tasks are inherently limited to 1. /// </summary> private readonly int m_maxConcurrencyLevel; /// <summary>The maximum number of tasks we can process before recyling our runner tasks.</summary> private readonly int m_maxItemsPerTask; /// <summary> /// If positive, it represents the number of concurrently running concurrent tasks. /// If negative, it means an exclusive task has been scheduled. /// If 0, nothing has been scheduled. /// </summary> private int m_processingCount; /// <summary>Completion state for a task representing the completion of this pair.</summary> /// <remarks>Lazily-initialized only if the scheduler pair is shutting down or if the Completion is requested.</remarks> private CompletionState m_completionState; /// <summary>A constant value used to signal unlimited processing.</summary> private const int UNLIMITED_PROCESSING = -1; /// <summary>Constant used for m_processingCount to indicate that an exclusive task is being processed.</summary> private const int EXCLUSIVE_PROCESSING_SENTINEL = -1; /// <summary>Default MaxItemsPerTask to use for processing if none is specified.</summary> private const int DEFAULT_MAXITEMSPERTASK = UNLIMITED_PROCESSING; /// <summary>Default MaxConcurrencyLevel is the processor count if not otherwise specified.</summary> private static Int32 DefaultMaxConcurrencyLevel { get { return Environment.ProcessorCount; } } /// <summary>Gets the sync obj used to protect all state on this instance.</summary> private object ValueLock { get { return m_threadProcessingMapping; } } /// <summary> /// Initializes the ConcurrentExclusiveSchedulerPair. /// </summary> public ConcurrentExclusiveSchedulerPair() : this(TaskScheduler.Default, DefaultMaxConcurrencyLevel, DEFAULT_MAXITEMSPERTASK) { } /// <summary> /// Initializes the ConcurrentExclusiveSchedulerPair to target the specified scheduler. /// </summary> /// <param name="taskScheduler">The target scheduler on which this pair should execute.</param> public ConcurrentExclusiveSchedulerPair(TaskScheduler taskScheduler) : this(taskScheduler, DefaultMaxConcurrencyLevel, DEFAULT_MAXITEMSPERTASK) { } /// <summary> /// Initializes the ConcurrentExclusiveSchedulerPair to target the specified scheduler with a maximum concurrency level. /// </summary> /// <param name="taskScheduler">The target scheduler on which this pair should execute.</param> /// <param name="maxConcurrencyLevel">The maximum number of tasks to run concurrently.</param> public ConcurrentExclusiveSchedulerPair(TaskScheduler taskScheduler, int maxConcurrencyLevel) : this(taskScheduler, maxConcurrencyLevel, DEFAULT_MAXITEMSPERTASK) { } /// <summary> /// Initializes the ConcurrentExclusiveSchedulerPair to target the specified scheduler with a maximum /// concurrency level and a maximum number of scheduled tasks that may be processed as a unit. /// </summary> /// <param name="taskScheduler">The target scheduler on which this pair should execute.</param> /// <param name="maxConcurrencyLevel">The maximum number of tasks to run concurrently.</param> /// <param name="maxItemsPerTask">The maximum number of tasks to process for each underlying scheduled task used by the pair.</param> public ConcurrentExclusiveSchedulerPair(TaskScheduler taskScheduler, int maxConcurrencyLevel, int maxItemsPerTask) { // Validate arguments if (taskScheduler == null) throw new ArgumentNullException(nameof(taskScheduler)); if (maxConcurrencyLevel == 0 || maxConcurrencyLevel < -1) throw new ArgumentOutOfRangeException(nameof(maxConcurrencyLevel)); if (maxItemsPerTask == 0 || maxItemsPerTask < -1) throw new ArgumentOutOfRangeException(nameof(maxItemsPerTask)); Contract.EndContractBlock(); // Store configuration m_underlyingTaskScheduler = taskScheduler; m_maxConcurrencyLevel = maxConcurrencyLevel; m_maxItemsPerTask = maxItemsPerTask; // Downgrade to the underlying scheduler's max degree of parallelism if it's lower than the user-supplied level int mcl = taskScheduler.MaximumConcurrencyLevel; if (mcl > 0 && mcl < m_maxConcurrencyLevel) m_maxConcurrencyLevel = mcl; // Treat UNLIMITED_PROCESSING/-1 for both MCL and MIPT as the biggest possible value so that we don't // have to special case UNLIMITED_PROCESSING later on in processing. if (m_maxConcurrencyLevel == UNLIMITED_PROCESSING) m_maxConcurrencyLevel = Int32.MaxValue; if (m_maxItemsPerTask == UNLIMITED_PROCESSING) m_maxItemsPerTask = Int32.MaxValue; // Create the concurrent/exclusive schedulers for this pair m_exclusiveTaskScheduler = new ConcurrentExclusiveTaskScheduler(this, 1, ProcessingMode.ProcessingExclusiveTask); m_concurrentTaskScheduler = new ConcurrentExclusiveTaskScheduler(this, m_maxConcurrencyLevel, ProcessingMode.ProcessingConcurrentTasks); } /// <summary>Informs the scheduler pair that it should not accept any more tasks.</summary> /// <remarks> /// Calling <see cref="Complete"/> is optional, and it's only necessary if the <see cref="Completion"/> /// will be relied on for notification of all processing being completed. /// </remarks> public void Complete() { lock (ValueLock) { if (!CompletionRequested) { RequestCompletion(); CleanupStateIfCompletingAndQuiesced(); } } } /// <summary>Gets a <see cref="System.Threading.Tasks.Task"/> that will complete when the scheduler has completed processing.</summary> public Task Completion { // ValueLock not needed, but it's ok if it's held get { return EnsureCompletionStateInitialized().Task; } } /// <summary>Gets the lazily-initialized completion state.</summary> private CompletionState EnsureCompletionStateInitialized() { // ValueLock not needed, but it's ok if it's held return LazyInitializer.EnsureInitialized(ref m_completionState, () => new CompletionState()); } /// <summary>Gets whether completion has been requested.</summary> private bool CompletionRequested { // ValueLock not needed, but it's ok if it's held get { return m_completionState != null && Volatile.Read(ref m_completionState.m_completionRequested); } } /// <summary>Sets that completion has been requested.</summary> private void RequestCompletion() { ContractAssertMonitorStatus(ValueLock, held: true); EnsureCompletionStateInitialized().m_completionRequested = true; } /// <summary> /// Cleans up state if and only if there's no processing currently happening /// and no more to be done later. /// </summary> private void CleanupStateIfCompletingAndQuiesced() { ContractAssertMonitorStatus(ValueLock, held: true); if (ReadyToComplete) CompleteTaskAsync(); } /// <summary>Gets whether the pair is ready to complete.</summary> private bool ReadyToComplete { get { ContractAssertMonitorStatus(ValueLock, held: true); // We can only complete if completion has been requested and no processing is currently happening. if (!CompletionRequested || m_processingCount != 0) return false; // Now, only allow shutdown if an exception occurred or if there are no more tasks to process. var cs = EnsureCompletionStateInitialized(); return (cs.m_exceptions != null && cs.m_exceptions.Count > 0) || (m_concurrentTaskScheduler.m_tasks.IsEmpty && m_exclusiveTaskScheduler.m_tasks.IsEmpty); } } /// <summary>Completes the completion task asynchronously.</summary> private void CompleteTaskAsync() { Contract.Requires(ReadyToComplete, "The block must be ready to complete to be here."); ContractAssertMonitorStatus(ValueLock, held: true); // Ensure we only try to complete once, then schedule completion // in order to escape held locks and the caller's context var cs = EnsureCompletionStateInitialized(); if (!cs.m_completionQueued) { cs.m_completionQueued = true; ThreadPool.QueueUserWorkItem(state => { var localCs = (CompletionState)state; // don't use 'cs', as it'll force a closure Debug.Assert(!localCs.Task.IsCompleted, "Completion should only happen once."); var exceptions = localCs.m_exceptions; bool success = (exceptions != null && exceptions.Count > 0) ? localCs.TrySetException(exceptions) : localCs.TrySetResult(default(VoidTaskResult)); Debug.Assert(success, "Expected to complete completion task."); }, cs); } } /// <summary>Initiatites scheduler shutdown due to a worker task faulting..</summary> /// <param name="faultedTask">The faulted worker task that's initiating the shutdown.</param> private void FaultWithTask(Task faultedTask) { Contract.Requires(faultedTask != null && faultedTask.IsFaulted && faultedTask.Exception.InnerExceptions.Count > 0, "Needs a task in the faulted state and thus with exceptions."); ContractAssertMonitorStatus(ValueLock, held: true); // Store the faulted task's exceptions var cs = EnsureCompletionStateInitialized(); if (cs.m_exceptions == null) cs.m_exceptions = new List<Exception>(); cs.m_exceptions.AddRange(faultedTask.Exception.InnerExceptions); // Now that we're doomed, request completion RequestCompletion(); } /// <summary> /// Gets a TaskScheduler that can be used to schedule tasks to this pair /// that may run concurrently with other tasks on this pair. /// </summary> public TaskScheduler ConcurrentScheduler { get { return m_concurrentTaskScheduler; } } /// <summary> /// Gets a TaskScheduler that can be used to schedule tasks to this pair /// that must run exclusively with regards to other tasks on this pair. /// </summary> public TaskScheduler ExclusiveScheduler { get { return m_exclusiveTaskScheduler; } } /// <summary>Gets the number of tasks waiting to run concurrently.</summary> /// <remarks>This does not take the necessary lock, as it's only called from under the debugger.</remarks> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] private int ConcurrentTaskCountForDebugger { get { return m_concurrentTaskScheduler.m_tasks.Count; } } /// <summary>Gets the number of tasks waiting to run exclusively.</summary> /// <remarks>This does not take the necessary lock, as it's only called from under the debugger.</remarks> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] private int ExclusiveTaskCountForDebugger { get { return m_exclusiveTaskScheduler.m_tasks.Count; } } /// <summary>Notifies the pair that new work has arrived to be processed.</summary> /// <param name="fairly">Whether tasks should be scheduled fairly with regards to other tasks.</param> /// <remarks>Must only be called while holding the lock.</remarks> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] [SuppressMessage("Microsoft.Performance", "CA1804:RemoveUnusedLocals")] [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] private void ProcessAsyncIfNecessary(bool fairly = false) { ContractAssertMonitorStatus(ValueLock, held: true); // If the current processing count is >= 0, we can potentially launch further processing. if (m_processingCount >= 0) { // We snap whether there are any exclusive tasks or concurrent tasks waiting. // (We grab the concurrent count below only once we know we need it.) // With processing happening concurrent to this operation, this data may // immediately be out of date, but it can only go from non-empty // to empty and not the other way around. As such, this is safe, // as worst case is we'll schedule an extra task when we didn't // otherwise need to, and we'll just eat its overhead. bool exclusiveTasksAreWaiting = !m_exclusiveTaskScheduler.m_tasks.IsEmpty; // If there's no processing currently happening but there are waiting exclusive tasks, // let's start processing those exclusive tasks. Task processingTask = null; if (m_processingCount == 0 && exclusiveTasksAreWaiting) { // Launch exclusive task processing m_processingCount = EXCLUSIVE_PROCESSING_SENTINEL; // -1 try { processingTask = new Task(thisPair => ((ConcurrentExclusiveSchedulerPair)thisPair).ProcessExclusiveTasks(), this, default(CancellationToken), GetCreationOptionsForTask(fairly)); processingTask.Start(m_underlyingTaskScheduler); // When we call Start, if the underlying scheduler throws in QueueTask, TPL will fault the task and rethrow // the exception. To deal with that, we need a reference to the task object, so that we can observe its exception. // Hence, we separate creation and starting, so that we can store a reference to the task before we attempt QueueTask. } catch { m_processingCount = 0; FaultWithTask(processingTask); } } // If there are no waiting exclusive tasks, there are concurrent tasks, and we haven't reached our maximum // concurrency level for processing, let's start processing more concurrent tasks. else { int concurrentTasksWaitingCount = m_concurrentTaskScheduler.m_tasks.Count; if (concurrentTasksWaitingCount > 0 && !exclusiveTasksAreWaiting && m_processingCount < m_maxConcurrencyLevel) { // Launch concurrent task processing, up to the allowed limit for (int i = 0; i < concurrentTasksWaitingCount && m_processingCount < m_maxConcurrencyLevel; ++i) { ++m_processingCount; try { processingTask = new Task(thisPair => ((ConcurrentExclusiveSchedulerPair)thisPair).ProcessConcurrentTasks(), this, default(CancellationToken), GetCreationOptionsForTask(fairly)); processingTask.Start(m_underlyingTaskScheduler); // See above logic for why we use new + Start rather than StartNew } catch { --m_processingCount; FaultWithTask(processingTask); } } } } // Check to see if all tasks have completed and if completion has been requested. CleanupStateIfCompletingAndQuiesced(); } else Debug.Assert(m_processingCount == EXCLUSIVE_PROCESSING_SENTINEL, "The processing count must be the sentinel if it's not >= 0."); } /// <summary> /// Processes exclusive tasks serially until either there are no more to process /// or we've reached our user-specified maximum limit. /// </summary> private void ProcessExclusiveTasks() { Contract.Requires(m_processingCount == EXCLUSIVE_PROCESSING_SENTINEL, "Processing exclusive tasks requires being in exclusive mode."); Contract.Requires(!m_exclusiveTaskScheduler.m_tasks.IsEmpty, "Processing exclusive tasks requires tasks to be processed."); ContractAssertMonitorStatus(ValueLock, held: false); try { // Note that we're processing exclusive tasks on the current thread Debug.Assert(!m_threadProcessingMapping.ContainsKey(Thread.CurrentThread.ManagedThreadId), "This thread should not yet be involved in this pair's processing."); m_threadProcessingMapping[Thread.CurrentThread.ManagedThreadId] = ProcessingMode.ProcessingExclusiveTask; // Process up to the maximum number of items per task allowed for (int i = 0; i < m_maxItemsPerTask; i++) { // Get the next available exclusive task. If we can't find one, bail. Task exclusiveTask; if (!m_exclusiveTaskScheduler.m_tasks.TryDequeue(out exclusiveTask)) break; // Execute the task. If the scheduler was previously faulted, // this task could have been faulted when it was queued; ignore such tasks. if (!exclusiveTask.IsFaulted) m_exclusiveTaskScheduler.ExecuteTask(exclusiveTask); } } finally { // We're no longer processing exclusive tasks on the current thread ProcessingMode currentMode; m_threadProcessingMapping.TryRemove(Thread.CurrentThread.ManagedThreadId, out currentMode); Debug.Assert(currentMode == ProcessingMode.ProcessingExclusiveTask, "Somehow we ended up escaping exclusive mode."); lock (ValueLock) { // When this task was launched, we tracked it by setting m_processingCount to WRITER_IN_PROGRESS. // now reset it to 0. Then check to see whether there's more processing to be done. // There might be more concurrent tasks available, for example, if concurrent tasks arrived // after we exited the loop, or if we exited the loop while concurrent tasks were still // available but we hit our maxItemsPerTask limit. Debug.Assert(m_processingCount == EXCLUSIVE_PROCESSING_SENTINEL, "The processing mode should not have deviated from exclusive."); m_processingCount = 0; ProcessAsyncIfNecessary(true); } } } /// <summary> /// Processes concurrent tasks serially until either there are no more to process, /// we've reached our user-specified maximum limit, or exclusive tasks have arrived. /// </summary> private void ProcessConcurrentTasks() { Contract.Requires(m_processingCount > 0, "Processing concurrent tasks requires us to be in concurrent mode."); ContractAssertMonitorStatus(ValueLock, held: false); try { // Note that we're processing concurrent tasks on the current thread Debug.Assert(!m_threadProcessingMapping.ContainsKey(Thread.CurrentThread.ManagedThreadId), "This thread should not yet be involved in this pair's processing."); m_threadProcessingMapping[Thread.CurrentThread.ManagedThreadId] = ProcessingMode.ProcessingConcurrentTasks; // Process up to the maximum number of items per task allowed for (int i = 0; i < m_maxItemsPerTask; i++) { // Get the next available concurrent task. If we can't find one, bail. Task concurrentTask; if (!m_concurrentTaskScheduler.m_tasks.TryDequeue(out concurrentTask)) break; // Execute the task. If the scheduler was previously faulted, // this task could have been faulted when it was queued; ignore such tasks. if (!concurrentTask.IsFaulted) m_concurrentTaskScheduler.ExecuteTask(concurrentTask); // Now check to see if exclusive tasks have arrived; if any have, they take priority // so we'll bail out here. Note that we could have checked this condition // in the for loop's condition, but that could lead to extra overhead // in the case where a concurrent task arrives, this task is launched, and then // before entering the loop an exclusive task arrives. If we didn't execute at // least one task, we would have spent all of the overhead to launch a // task but with none of the benefit. There's of course also an inherent // race condition here with regards to exclusive tasks arriving, and we're ok with // executing one more concurrent task than we should before giving priority to exclusive tasks. if (!m_exclusiveTaskScheduler.m_tasks.IsEmpty) break; } } finally { // We're no longer processing concurrent tasks on the current thread ProcessingMode currentMode; m_threadProcessingMapping.TryRemove(Thread.CurrentThread.ManagedThreadId, out currentMode); Debug.Assert(currentMode == ProcessingMode.ProcessingConcurrentTasks, "Somehow we ended up escaping concurrent mode."); lock (ValueLock) { // When this task was launched, we tracked it with a positive processing count; // decrement that count. Then check to see whether there's more processing to be done. // There might be more concurrent tasks available, for example, if concurrent tasks arrived // after we exited the loop, or if we exited the loop while concurrent tasks were still // available but we hit our maxItemsPerTask limit. Debug.Assert(m_processingCount > 0, "The procesing mode should not have deviated from concurrent."); if (m_processingCount > 0) --m_processingCount; ProcessAsyncIfNecessary(true); } } } #if PRENET45 /// <summary> /// Type used with TaskCompletionSource(Of TResult) as the TResult /// to ensure that the resulting task can't be upcast to something /// that in the future could lead to compat problems. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses")] [DebuggerNonUserCode] private struct VoidTaskResult { } #endif /// <summary> /// Holder for lazily-initialized state about the completion of a scheduler pair. /// Completion is only triggered either by rare exceptional conditions or by /// the user calling Complete, and as such we only lazily initialize this /// state in one of those conditions or if the user explicitly asks for /// the Completion. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses")] private sealed class CompletionState : TaskCompletionSource<VoidTaskResult> { /// <summary>Whether the scheduler has had completion requested.</summary> /// <remarks>This variable is not volatile, so to gurantee safe reading reads, Volatile.Read is used in TryExecuteTaskInline.</remarks> internal bool m_completionRequested; /// <summary>Whether completion processing has been queued.</summary> internal bool m_completionQueued; /// <summary>Unrecoverable exceptions incurred while processing.</summary> internal List<Exception> m_exceptions; } /// <summary> /// A scheduler shim used to queue tasks to the pair and execute those tasks on request of the pair. /// </summary> [DebuggerDisplay("Count={CountForDebugger}, MaxConcurrencyLevel={m_maxConcurrencyLevel}, Id={Id}")] [DebuggerTypeProxy(typeof(ConcurrentExclusiveTaskScheduler.DebugView))] private sealed class ConcurrentExclusiveTaskScheduler : TaskScheduler { /// <summary>Cached delegate for invoking TryExecuteTaskShim.</summary> private static readonly Func<object, bool> s_tryExecuteTaskShim = new Func<object, bool>(TryExecuteTaskShim); /// <summary>The parent pair.</summary> private readonly ConcurrentExclusiveSchedulerPair m_pair; /// <summary>The maximum concurrency level for the scheduler.</summary> private readonly int m_maxConcurrencyLevel; /// <summary>The processing mode of this scheduler, exclusive or concurrent.</summary> private readonly ProcessingMode m_processingMode; /// <summary>Gets the queue of tasks for this scheduler.</summary> internal readonly IProducerConsumerQueue<Task> m_tasks; /// <summary>Initializes the scheduler.</summary> /// <param name="pair">The parent pair.</param> /// <param name="maxConcurrencyLevel">The maximum degree of concurrency this scheduler may use.</param> /// <param name="processingMode">The processing mode of this scheduler.</param> internal ConcurrentExclusiveTaskScheduler(ConcurrentExclusiveSchedulerPair pair, int maxConcurrencyLevel, ProcessingMode processingMode) { Contract.Requires(pair != null, "Scheduler must be associated with a valid pair."); Contract.Requires(processingMode == ProcessingMode.ProcessingConcurrentTasks || processingMode == ProcessingMode.ProcessingExclusiveTask, "Scheduler must be for concurrent or exclusive processing."); Contract.Requires( (processingMode == ProcessingMode.ProcessingConcurrentTasks && (maxConcurrencyLevel >= 1 || maxConcurrencyLevel == UNLIMITED_PROCESSING)) || (processingMode == ProcessingMode.ProcessingExclusiveTask && maxConcurrencyLevel == 1), "If we're in concurrent mode, our concurrency level should be positive or unlimited. If exclusive, it should be 1."); m_pair = pair; m_maxConcurrencyLevel = maxConcurrencyLevel; m_processingMode = processingMode; m_tasks = (processingMode == ProcessingMode.ProcessingExclusiveTask) ? (IProducerConsumerQueue<Task>)new SingleProducerSingleConsumerQueue<Task>() : (IProducerConsumerQueue<Task>)new MultiProducerMultiConsumerQueue<Task>(); } /// <summary>Gets the maximum concurrency level this scheduler is able to support.</summary> public override int MaximumConcurrencyLevel { get { return m_maxConcurrencyLevel; } } /// <summary>Queues a task to the scheduler.</summary> /// <param name="task">The task to be queued.</param> protected internal override void QueueTask(Task task) { Debug.Assert(task != null, "Infrastructure should have provided a non-null task."); lock (m_pair.ValueLock) { // If the scheduler has already had completion requested, no new work is allowed to be scheduled if (m_pair.CompletionRequested) throw new InvalidOperationException(GetType().Name); // Queue the task, and then let the pair know that more work is now available to be scheduled m_tasks.Enqueue(task); m_pair.ProcessAsyncIfNecessary(); } } /// <summary>Executes a task on this scheduler.</summary> /// <param name="task">The task to be executed.</param> internal void ExecuteTask(Task task) { Debug.Assert(task != null, "Infrastructure should have provided a non-null task."); base.TryExecuteTask(task); } /// <summary>Tries to execute the task synchronously on this scheduler.</summary> /// <param name="task">The task to execute.</param> /// <param name="taskWasPreviouslyQueued">Whether the task was previously queued to the scheduler.</param> /// <returns>true if the task could be executed; otherwise, false.</returns> protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued) { Debug.Assert(task != null, "Infrastructure should have provided a non-null task."); // If the scheduler has had completion requested, no new work is allowed to be scheduled. // A non-locked read on m_completionRequested (in CompletionRequested) is acceptable here because: // a) we don't need to be exact... a Complete call could come in later in the function anyway // b) this is only a fast path escape hatch. To actually inline the task, // we need to be inside of an already executing task, and in such a case, // while completion may have been requested, we can't have shutdown yet. if (!taskWasPreviouslyQueued && m_pair.CompletionRequested) return false; // We know the implementation of the default scheduler and how it will behave. // As it's the most common underlying scheduler, we optimize for it. bool isDefaultScheduler = m_pair.m_underlyingTaskScheduler == TaskScheduler.Default; // If we're targeting the default scheduler and taskWasPreviouslyQueued is true, // we know that the default scheduler will only allow it to be inlined // if we're on a thread pool thread (but it won't always allow it in that case, // since it'll only allow inlining if it can find the task in the local queue). // As such, if we're not on a thread pool thread, we know for sure the // task won't be inlined, so let's not even try. if (isDefaultScheduler && taskWasPreviouslyQueued && !Thread.CurrentThread.IsThreadPoolThread) { return false; } else { // If a task is already running on this thread, allow inline execution to proceed. // If there's already a task from this scheduler running on the current thread, we know it's safe // to run this task, in effect temporarily taking that task's count allocation. ProcessingMode currentThreadMode; if (m_pair.m_threadProcessingMapping.TryGetValue(Thread.CurrentThread.ManagedThreadId, out currentThreadMode) && currentThreadMode == m_processingMode) { // If we're targeting the default scheduler and taskWasPreviouslyQueued is false, // we know the default scheduler will allow it, so we can just execute it here. // Otherwise, delegate to the target scheduler's inlining. return (isDefaultScheduler && !taskWasPreviouslyQueued) ? TryExecuteTask(task) : TryExecuteTaskInlineOnTargetScheduler(task); } } // We're not in the context of a task already executing on this scheduler. Bail. return false; } /// <summary> /// Implements a reasonable approximation for TryExecuteTaskInline on the underlying scheduler, /// which we can't call directly on the underlying scheduler. /// </summary> /// <param name="task">The task to execute inline if possible.</param> /// <returns>true if the task was inlined successfully; otherwise, false.</returns> [SuppressMessage("Microsoft.Performance", "CA1804:RemoveUnusedLocals", MessageId = "ignored")] private bool TryExecuteTaskInlineOnTargetScheduler(Task task) { // We'd like to simply call TryExecuteTaskInline here, but we can't. // As there's no built-in API for this, a workaround is to create a new task that, // when executed, will simply call TryExecuteTask to run the real task, and then // we run our new shim task synchronously on the target scheduler. If all goes well, // our synchronous invocation will succeed in running the shim task on the current thread, // which will in turn run the real task on the current thread. If the scheduler // doesn't allow that execution, RunSynchronously will block until the underlying scheduler // is able to invoke the task, which might account for an additional but unavoidable delay. // Once it's done, we can return whether the task executed by returning the // shim task's Result, which is in turn the result of TryExecuteTask. var t = new Task<bool>(s_tryExecuteTaskShim, Tuple.Create(this, task)); try { t.RunSynchronously(m_pair.m_underlyingTaskScheduler); return t.Result; } catch { Debug.Assert(t.IsFaulted, "Task should be faulted due to the scheduler faulting it and throwing the exception."); var ignored = t.Exception; throw; } finally { t.Dispose(); } } /// <summary>Shim used to invoke this.TryExecuteTask(task).</summary> /// <param name="state">A tuple of the ConcurrentExclusiveTaskScheduler and the task to execute.</param> /// <returns>true if the task was successfully inlined; otherwise, false.</returns> /// <remarks> /// This method is separated out not because of performance reasons but so that /// the SecuritySafeCritical attribute may be employed. /// </remarks> private static bool TryExecuteTaskShim(object state) { var tuple = (Tuple<ConcurrentExclusiveTaskScheduler, Task>)state; return tuple.Item1.TryExecuteTask(tuple.Item2); } /// <summary>Gets for debugging purposes the tasks scheduled to this scheduler.</summary> /// <returns>An enumerable of the tasks queued.</returns> protected override IEnumerable<Task> GetScheduledTasks() { return m_tasks; } /// <summary>Gets the number of tasks queued to this scheduler.</summary> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] private int CountForDebugger { get { return m_tasks.Count; } } /// <summary>Provides a debug view for ConcurrentExclusiveTaskScheduler.</summary> private sealed class DebugView { /// <summary>The scheduler being debugged.</summary> private readonly ConcurrentExclusiveTaskScheduler m_taskScheduler; /// <summary>Initializes the debug view.</summary> /// <param name="scheduler">The scheduler being debugged.</param> public DebugView(ConcurrentExclusiveTaskScheduler scheduler) { Contract.Requires(scheduler != null, "Need a scheduler with which to construct the debug view."); m_taskScheduler = scheduler; } /// <summary>Gets this pair's maximum allowed concurrency level.</summary> public int MaximumConcurrencyLevel { get { return m_taskScheduler.m_maxConcurrencyLevel; } } /// <summary>Gets the tasks scheduled to this scheduler.</summary> public IEnumerable<Task> ScheduledTasks { get { return m_taskScheduler.m_tasks; } } /// <summary>Gets the scheduler pair with which this scheduler is associated.</summary> public ConcurrentExclusiveSchedulerPair SchedulerPair { get { return m_taskScheduler.m_pair; } } } } /// <summary>Provides a debug view for ConcurrentExclusiveSchedulerPair.</summary> private sealed class DebugView { /// <summary>The pair being debugged.</summary> private readonly ConcurrentExclusiveSchedulerPair m_pair; /// <summary>Initializes the debug view.</summary> /// <param name="pair">The pair being debugged.</param> public DebugView(ConcurrentExclusiveSchedulerPair pair) { Contract.Requires(pair != null, "Need a pair with which to construct the debug view."); m_pair = pair; } /// <summary>Gets a representation of the execution state of the pair.</summary> public ProcessingMode Mode { get { return m_pair.ModeForDebugger; } } /// <summary>Gets the number of tasks waiting to run exclusively.</summary> public IEnumerable<Task> ScheduledExclusive { get { return m_pair.m_exclusiveTaskScheduler.m_tasks; } } /// <summary>Gets the number of tasks waiting to run concurrently.</summary> public IEnumerable<Task> ScheduledConcurrent { get { return m_pair.m_concurrentTaskScheduler.m_tasks; } } /// <summary>Gets the number of tasks currently being executed.</summary> public int CurrentlyExecutingTaskCount { get { return (m_pair.m_processingCount == EXCLUSIVE_PROCESSING_SENTINEL) ? 1 : m_pair.m_processingCount; } } /// <summary>Gets the underlying task scheduler that actually executes the tasks.</summary> public TaskScheduler TargetScheduler { get { return m_pair.m_underlyingTaskScheduler; } } } /// <summary>Gets an enumeration for debugging that represents the current state of the scheduler pair.</summary> /// <remarks>This is only for debugging. It does not take the necessary locks to be useful for runtime usage.</remarks> private ProcessingMode ModeForDebugger { get { // If our completion task is done, so are we. if (m_completionState != null && m_completionState.Task.IsCompleted) return ProcessingMode.Completed; // Otherwise, summarize our current state. var mode = ProcessingMode.NotCurrentlyProcessing; if (m_processingCount == EXCLUSIVE_PROCESSING_SENTINEL) mode |= ProcessingMode.ProcessingExclusiveTask; if (m_processingCount >= 1) mode |= ProcessingMode.ProcessingConcurrentTasks; if (CompletionRequested) mode |= ProcessingMode.Completing; return mode; } } /// <summary>Asserts that a given synchronization object is either held or not held.</summary> /// <param name="syncObj">The monitor to check.</param> /// <param name="held">Whether we want to assert that it's currently held or not held.</param> [Conditional("DEBUG")] internal static void ContractAssertMonitorStatus(object syncObj, bool held) { Contract.Requires(syncObj != null, "The monitor object to check must be provided."); #if PRENET45 #if DEBUG // This check is expensive, // which is why it's protected by ShouldCheckMonitorStatus and controlled by an environment variable DEBUGSYNC. if (ShouldCheckMonitorStatus) { bool exceptionThrown; try { Monitor.Pulse(syncObj); // throws a SynchronizationLockException if the monitor isn't held by this thread exceptionThrown = false; } catch (SynchronizationLockException) { exceptionThrown = true; } Debug.Assert(held == !exceptionThrown, "The locking scheme was not correctly followed."); } #endif #else Debug.Assert(Monitor.IsEntered(syncObj) == held, "The locking scheme was not correctly followed."); #endif } /// <summary>Gets the options to use for tasks.</summary> /// <param name="isReplacementReplica">If this task is being created to replace another.</param> /// <remarks> /// These options should be used for all tasks that have the potential to run user code or /// that are repeatedly spawned and thus need a modicum of fair treatment. /// </remarks> /// <returns>The options to use.</returns> internal static TaskCreationOptions GetCreationOptionsForTask(bool isReplacementReplica = false) { TaskCreationOptions options = #if PRENET45 TaskCreationOptions.None; #else TaskCreationOptions.DenyChildAttach; #endif if (isReplacementReplica) options |= TaskCreationOptions.PreferFairness; return options; } /// <summary>Provides an enumeration that represents the current state of the scheduler pair.</summary> [Flags] private enum ProcessingMode : byte { /// <summary>The scheduler pair is currently dormant, with no work scheduled.</summary> NotCurrentlyProcessing = 0x0, /// <summary>The scheduler pair has queued processing for exclusive tasks.</summary> ProcessingExclusiveTask = 0x1, /// <summary>The scheduler pair has queued processing for concurrent tasks.</summary> ProcessingConcurrentTasks = 0x2, /// <summary>Completion has been requested.</summary> Completing = 0x4, /// <summary>The scheduler pair is finished processing.</summary> Completed = 0x8 } } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gaxgrpc = Google.Api.Gax.Grpc; using gagr = Google.Api.Gax.ResourceNames; using lro = Google.LongRunning; using wkt = Google.Protobuf.WellKnownTypes; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using xunit = Xunit; namespace Google.Cloud.Dialogflow.Cx.V3.Tests { /// <summary>Generated unit tests.</summary> public sealed class GeneratedAgentsClientTest { [xunit::FactAttribute] public void GetAgentRequestObject() { moq::Mock<Agents.AgentsClient> mockGrpcClient = new moq::Mock<Agents.AgentsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetAgentRequest request = new GetAgentRequest { AgentName = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"), }; Agent expectedResponse = new Agent { AgentName = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"), DisplayName = "display_name137f65c2", DefaultLanguageCode = "default_language_codee612e130", SupportedLanguageCodes = { "supported_language_codesbcd806b9", }, TimeZone = "time_zone73f23b20", Description = "description2cf9da67", AvatarUri = "avatar_urie1767db7", SpeechToTextSettings = new SpeechToTextSettings(), StartFlowAsFlowName = FlowName.FromProjectLocationAgentFlow("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]"), SecuritySettingsAsSecuritySettingsName = SecuritySettingsName.FromProjectLocationSecuritySettings("[PROJECT]", "[LOCATION]", "[SECURITY_SETTINGS]"), #pragma warning disable CS0612 EnableStackdriverLogging = false, #pragma warning restore CS0612 EnableSpellCorrection = true, AdvancedSettings = new AdvancedSettings(), }; mockGrpcClient.Setup(x => x.GetAgent(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); AgentsClient client = new AgentsClientImpl(mockGrpcClient.Object, null); Agent response = client.GetAgent(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetAgentRequestObjectAsync() { moq::Mock<Agents.AgentsClient> mockGrpcClient = new moq::Mock<Agents.AgentsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetAgentRequest request = new GetAgentRequest { AgentName = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"), }; Agent expectedResponse = new Agent { AgentName = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"), DisplayName = "display_name137f65c2", DefaultLanguageCode = "default_language_codee612e130", SupportedLanguageCodes = { "supported_language_codesbcd806b9", }, TimeZone = "time_zone73f23b20", Description = "description2cf9da67", AvatarUri = "avatar_urie1767db7", SpeechToTextSettings = new SpeechToTextSettings(), StartFlowAsFlowName = FlowName.FromProjectLocationAgentFlow("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]"), SecuritySettingsAsSecuritySettingsName = SecuritySettingsName.FromProjectLocationSecuritySettings("[PROJECT]", "[LOCATION]", "[SECURITY_SETTINGS]"), #pragma warning disable CS0612 EnableStackdriverLogging = false, #pragma warning restore CS0612 EnableSpellCorrection = true, AdvancedSettings = new AdvancedSettings(), }; mockGrpcClient.Setup(x => x.GetAgentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Agent>(stt::Task.FromResult(expectedResponse), null, null, null, null)); AgentsClient client = new AgentsClientImpl(mockGrpcClient.Object, null); Agent responseCallSettings = await client.GetAgentAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Agent responseCancellationToken = await client.GetAgentAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetAgent() { moq::Mock<Agents.AgentsClient> mockGrpcClient = new moq::Mock<Agents.AgentsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetAgentRequest request = new GetAgentRequest { AgentName = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"), }; Agent expectedResponse = new Agent { AgentName = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"), DisplayName = "display_name137f65c2", DefaultLanguageCode = "default_language_codee612e130", SupportedLanguageCodes = { "supported_language_codesbcd806b9", }, TimeZone = "time_zone73f23b20", Description = "description2cf9da67", AvatarUri = "avatar_urie1767db7", SpeechToTextSettings = new SpeechToTextSettings(), StartFlowAsFlowName = FlowName.FromProjectLocationAgentFlow("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]"), SecuritySettingsAsSecuritySettingsName = SecuritySettingsName.FromProjectLocationSecuritySettings("[PROJECT]", "[LOCATION]", "[SECURITY_SETTINGS]"), #pragma warning disable CS0612 EnableStackdriverLogging = false, #pragma warning restore CS0612 EnableSpellCorrection = true, AdvancedSettings = new AdvancedSettings(), }; mockGrpcClient.Setup(x => x.GetAgent(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); AgentsClient client = new AgentsClientImpl(mockGrpcClient.Object, null); Agent response = client.GetAgent(request.Name); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetAgentAsync() { moq::Mock<Agents.AgentsClient> mockGrpcClient = new moq::Mock<Agents.AgentsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetAgentRequest request = new GetAgentRequest { AgentName = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"), }; Agent expectedResponse = new Agent { AgentName = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"), DisplayName = "display_name137f65c2", DefaultLanguageCode = "default_language_codee612e130", SupportedLanguageCodes = { "supported_language_codesbcd806b9", }, TimeZone = "time_zone73f23b20", Description = "description2cf9da67", AvatarUri = "avatar_urie1767db7", SpeechToTextSettings = new SpeechToTextSettings(), StartFlowAsFlowName = FlowName.FromProjectLocationAgentFlow("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]"), SecuritySettingsAsSecuritySettingsName = SecuritySettingsName.FromProjectLocationSecuritySettings("[PROJECT]", "[LOCATION]", "[SECURITY_SETTINGS]"), #pragma warning disable CS0612 EnableStackdriverLogging = false, #pragma warning restore CS0612 EnableSpellCorrection = true, AdvancedSettings = new AdvancedSettings(), }; mockGrpcClient.Setup(x => x.GetAgentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Agent>(stt::Task.FromResult(expectedResponse), null, null, null, null)); AgentsClient client = new AgentsClientImpl(mockGrpcClient.Object, null); Agent responseCallSettings = await client.GetAgentAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Agent responseCancellationToken = await client.GetAgentAsync(request.Name, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetAgentResourceNames() { moq::Mock<Agents.AgentsClient> mockGrpcClient = new moq::Mock<Agents.AgentsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetAgentRequest request = new GetAgentRequest { AgentName = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"), }; Agent expectedResponse = new Agent { AgentName = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"), DisplayName = "display_name137f65c2", DefaultLanguageCode = "default_language_codee612e130", SupportedLanguageCodes = { "supported_language_codesbcd806b9", }, TimeZone = "time_zone73f23b20", Description = "description2cf9da67", AvatarUri = "avatar_urie1767db7", SpeechToTextSettings = new SpeechToTextSettings(), StartFlowAsFlowName = FlowName.FromProjectLocationAgentFlow("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]"), SecuritySettingsAsSecuritySettingsName = SecuritySettingsName.FromProjectLocationSecuritySettings("[PROJECT]", "[LOCATION]", "[SECURITY_SETTINGS]"), #pragma warning disable CS0612 EnableStackdriverLogging = false, #pragma warning restore CS0612 EnableSpellCorrection = true, AdvancedSettings = new AdvancedSettings(), }; mockGrpcClient.Setup(x => x.GetAgent(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); AgentsClient client = new AgentsClientImpl(mockGrpcClient.Object, null); Agent response = client.GetAgent(request.AgentName); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetAgentResourceNamesAsync() { moq::Mock<Agents.AgentsClient> mockGrpcClient = new moq::Mock<Agents.AgentsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetAgentRequest request = new GetAgentRequest { AgentName = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"), }; Agent expectedResponse = new Agent { AgentName = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"), DisplayName = "display_name137f65c2", DefaultLanguageCode = "default_language_codee612e130", SupportedLanguageCodes = { "supported_language_codesbcd806b9", }, TimeZone = "time_zone73f23b20", Description = "description2cf9da67", AvatarUri = "avatar_urie1767db7", SpeechToTextSettings = new SpeechToTextSettings(), StartFlowAsFlowName = FlowName.FromProjectLocationAgentFlow("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]"), SecuritySettingsAsSecuritySettingsName = SecuritySettingsName.FromProjectLocationSecuritySettings("[PROJECT]", "[LOCATION]", "[SECURITY_SETTINGS]"), #pragma warning disable CS0612 EnableStackdriverLogging = false, #pragma warning restore CS0612 EnableSpellCorrection = true, AdvancedSettings = new AdvancedSettings(), }; mockGrpcClient.Setup(x => x.GetAgentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Agent>(stt::Task.FromResult(expectedResponse), null, null, null, null)); AgentsClient client = new AgentsClientImpl(mockGrpcClient.Object, null); Agent responseCallSettings = await client.GetAgentAsync(request.AgentName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Agent responseCancellationToken = await client.GetAgentAsync(request.AgentName, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void CreateAgentRequestObject() { moq::Mock<Agents.AgentsClient> mockGrpcClient = new moq::Mock<Agents.AgentsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); CreateAgentRequest request = new CreateAgentRequest { ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), Agent = new Agent(), }; Agent expectedResponse = new Agent { AgentName = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"), DisplayName = "display_name137f65c2", DefaultLanguageCode = "default_language_codee612e130", SupportedLanguageCodes = { "supported_language_codesbcd806b9", }, TimeZone = "time_zone73f23b20", Description = "description2cf9da67", AvatarUri = "avatar_urie1767db7", SpeechToTextSettings = new SpeechToTextSettings(), StartFlowAsFlowName = FlowName.FromProjectLocationAgentFlow("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]"), SecuritySettingsAsSecuritySettingsName = SecuritySettingsName.FromProjectLocationSecuritySettings("[PROJECT]", "[LOCATION]", "[SECURITY_SETTINGS]"), #pragma warning disable CS0612 EnableStackdriverLogging = false, #pragma warning restore CS0612 EnableSpellCorrection = true, AdvancedSettings = new AdvancedSettings(), }; mockGrpcClient.Setup(x => x.CreateAgent(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); AgentsClient client = new AgentsClientImpl(mockGrpcClient.Object, null); Agent response = client.CreateAgent(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task CreateAgentRequestObjectAsync() { moq::Mock<Agents.AgentsClient> mockGrpcClient = new moq::Mock<Agents.AgentsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); CreateAgentRequest request = new CreateAgentRequest { ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), Agent = new Agent(), }; Agent expectedResponse = new Agent { AgentName = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"), DisplayName = "display_name137f65c2", DefaultLanguageCode = "default_language_codee612e130", SupportedLanguageCodes = { "supported_language_codesbcd806b9", }, TimeZone = "time_zone73f23b20", Description = "description2cf9da67", AvatarUri = "avatar_urie1767db7", SpeechToTextSettings = new SpeechToTextSettings(), StartFlowAsFlowName = FlowName.FromProjectLocationAgentFlow("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]"), SecuritySettingsAsSecuritySettingsName = SecuritySettingsName.FromProjectLocationSecuritySettings("[PROJECT]", "[LOCATION]", "[SECURITY_SETTINGS]"), #pragma warning disable CS0612 EnableStackdriverLogging = false, #pragma warning restore CS0612 EnableSpellCorrection = true, AdvancedSettings = new AdvancedSettings(), }; mockGrpcClient.Setup(x => x.CreateAgentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Agent>(stt::Task.FromResult(expectedResponse), null, null, null, null)); AgentsClient client = new AgentsClientImpl(mockGrpcClient.Object, null); Agent responseCallSettings = await client.CreateAgentAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Agent responseCancellationToken = await client.CreateAgentAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void CreateAgent() { moq::Mock<Agents.AgentsClient> mockGrpcClient = new moq::Mock<Agents.AgentsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); CreateAgentRequest request = new CreateAgentRequest { ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), Agent = new Agent(), }; Agent expectedResponse = new Agent { AgentName = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"), DisplayName = "display_name137f65c2", DefaultLanguageCode = "default_language_codee612e130", SupportedLanguageCodes = { "supported_language_codesbcd806b9", }, TimeZone = "time_zone73f23b20", Description = "description2cf9da67", AvatarUri = "avatar_urie1767db7", SpeechToTextSettings = new SpeechToTextSettings(), StartFlowAsFlowName = FlowName.FromProjectLocationAgentFlow("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]"), SecuritySettingsAsSecuritySettingsName = SecuritySettingsName.FromProjectLocationSecuritySettings("[PROJECT]", "[LOCATION]", "[SECURITY_SETTINGS]"), #pragma warning disable CS0612 EnableStackdriverLogging = false, #pragma warning restore CS0612 EnableSpellCorrection = true, AdvancedSettings = new AdvancedSettings(), }; mockGrpcClient.Setup(x => x.CreateAgent(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); AgentsClient client = new AgentsClientImpl(mockGrpcClient.Object, null); Agent response = client.CreateAgent(request.Parent, request.Agent); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task CreateAgentAsync() { moq::Mock<Agents.AgentsClient> mockGrpcClient = new moq::Mock<Agents.AgentsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); CreateAgentRequest request = new CreateAgentRequest { ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), Agent = new Agent(), }; Agent expectedResponse = new Agent { AgentName = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"), DisplayName = "display_name137f65c2", DefaultLanguageCode = "default_language_codee612e130", SupportedLanguageCodes = { "supported_language_codesbcd806b9", }, TimeZone = "time_zone73f23b20", Description = "description2cf9da67", AvatarUri = "avatar_urie1767db7", SpeechToTextSettings = new SpeechToTextSettings(), StartFlowAsFlowName = FlowName.FromProjectLocationAgentFlow("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]"), SecuritySettingsAsSecuritySettingsName = SecuritySettingsName.FromProjectLocationSecuritySettings("[PROJECT]", "[LOCATION]", "[SECURITY_SETTINGS]"), #pragma warning disable CS0612 EnableStackdriverLogging = false, #pragma warning restore CS0612 EnableSpellCorrection = true, AdvancedSettings = new AdvancedSettings(), }; mockGrpcClient.Setup(x => x.CreateAgentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Agent>(stt::Task.FromResult(expectedResponse), null, null, null, null)); AgentsClient client = new AgentsClientImpl(mockGrpcClient.Object, null); Agent responseCallSettings = await client.CreateAgentAsync(request.Parent, request.Agent, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Agent responseCancellationToken = await client.CreateAgentAsync(request.Parent, request.Agent, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void CreateAgentResourceNames() { moq::Mock<Agents.AgentsClient> mockGrpcClient = new moq::Mock<Agents.AgentsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); CreateAgentRequest request = new CreateAgentRequest { ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), Agent = new Agent(), }; Agent expectedResponse = new Agent { AgentName = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"), DisplayName = "display_name137f65c2", DefaultLanguageCode = "default_language_codee612e130", SupportedLanguageCodes = { "supported_language_codesbcd806b9", }, TimeZone = "time_zone73f23b20", Description = "description2cf9da67", AvatarUri = "avatar_urie1767db7", SpeechToTextSettings = new SpeechToTextSettings(), StartFlowAsFlowName = FlowName.FromProjectLocationAgentFlow("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]"), SecuritySettingsAsSecuritySettingsName = SecuritySettingsName.FromProjectLocationSecuritySettings("[PROJECT]", "[LOCATION]", "[SECURITY_SETTINGS]"), #pragma warning disable CS0612 EnableStackdriverLogging = false, #pragma warning restore CS0612 EnableSpellCorrection = true, AdvancedSettings = new AdvancedSettings(), }; mockGrpcClient.Setup(x => x.CreateAgent(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); AgentsClient client = new AgentsClientImpl(mockGrpcClient.Object, null); Agent response = client.CreateAgent(request.ParentAsLocationName, request.Agent); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task CreateAgentResourceNamesAsync() { moq::Mock<Agents.AgentsClient> mockGrpcClient = new moq::Mock<Agents.AgentsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); CreateAgentRequest request = new CreateAgentRequest { ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), Agent = new Agent(), }; Agent expectedResponse = new Agent { AgentName = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"), DisplayName = "display_name137f65c2", DefaultLanguageCode = "default_language_codee612e130", SupportedLanguageCodes = { "supported_language_codesbcd806b9", }, TimeZone = "time_zone73f23b20", Description = "description2cf9da67", AvatarUri = "avatar_urie1767db7", SpeechToTextSettings = new SpeechToTextSettings(), StartFlowAsFlowName = FlowName.FromProjectLocationAgentFlow("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]"), SecuritySettingsAsSecuritySettingsName = SecuritySettingsName.FromProjectLocationSecuritySettings("[PROJECT]", "[LOCATION]", "[SECURITY_SETTINGS]"), #pragma warning disable CS0612 EnableStackdriverLogging = false, #pragma warning restore CS0612 EnableSpellCorrection = true, AdvancedSettings = new AdvancedSettings(), }; mockGrpcClient.Setup(x => x.CreateAgentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Agent>(stt::Task.FromResult(expectedResponse), null, null, null, null)); AgentsClient client = new AgentsClientImpl(mockGrpcClient.Object, null); Agent responseCallSettings = await client.CreateAgentAsync(request.ParentAsLocationName, request.Agent, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Agent responseCancellationToken = await client.CreateAgentAsync(request.ParentAsLocationName, request.Agent, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void UpdateAgentRequestObject() { moq::Mock<Agents.AgentsClient> mockGrpcClient = new moq::Mock<Agents.AgentsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); UpdateAgentRequest request = new UpdateAgentRequest { Agent = new Agent(), UpdateMask = new wkt::FieldMask(), }; Agent expectedResponse = new Agent { AgentName = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"), DisplayName = "display_name137f65c2", DefaultLanguageCode = "default_language_codee612e130", SupportedLanguageCodes = { "supported_language_codesbcd806b9", }, TimeZone = "time_zone73f23b20", Description = "description2cf9da67", AvatarUri = "avatar_urie1767db7", SpeechToTextSettings = new SpeechToTextSettings(), StartFlowAsFlowName = FlowName.FromProjectLocationAgentFlow("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]"), SecuritySettingsAsSecuritySettingsName = SecuritySettingsName.FromProjectLocationSecuritySettings("[PROJECT]", "[LOCATION]", "[SECURITY_SETTINGS]"), #pragma warning disable CS0612 EnableStackdriverLogging = false, #pragma warning restore CS0612 EnableSpellCorrection = true, AdvancedSettings = new AdvancedSettings(), }; mockGrpcClient.Setup(x => x.UpdateAgent(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); AgentsClient client = new AgentsClientImpl(mockGrpcClient.Object, null); Agent response = client.UpdateAgent(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task UpdateAgentRequestObjectAsync() { moq::Mock<Agents.AgentsClient> mockGrpcClient = new moq::Mock<Agents.AgentsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); UpdateAgentRequest request = new UpdateAgentRequest { Agent = new Agent(), UpdateMask = new wkt::FieldMask(), }; Agent expectedResponse = new Agent { AgentName = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"), DisplayName = "display_name137f65c2", DefaultLanguageCode = "default_language_codee612e130", SupportedLanguageCodes = { "supported_language_codesbcd806b9", }, TimeZone = "time_zone73f23b20", Description = "description2cf9da67", AvatarUri = "avatar_urie1767db7", SpeechToTextSettings = new SpeechToTextSettings(), StartFlowAsFlowName = FlowName.FromProjectLocationAgentFlow("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]"), SecuritySettingsAsSecuritySettingsName = SecuritySettingsName.FromProjectLocationSecuritySettings("[PROJECT]", "[LOCATION]", "[SECURITY_SETTINGS]"), #pragma warning disable CS0612 EnableStackdriverLogging = false, #pragma warning restore CS0612 EnableSpellCorrection = true, AdvancedSettings = new AdvancedSettings(), }; mockGrpcClient.Setup(x => x.UpdateAgentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Agent>(stt::Task.FromResult(expectedResponse), null, null, null, null)); AgentsClient client = new AgentsClientImpl(mockGrpcClient.Object, null); Agent responseCallSettings = await client.UpdateAgentAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Agent responseCancellationToken = await client.UpdateAgentAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void UpdateAgent() { moq::Mock<Agents.AgentsClient> mockGrpcClient = new moq::Mock<Agents.AgentsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); UpdateAgentRequest request = new UpdateAgentRequest { Agent = new Agent(), UpdateMask = new wkt::FieldMask(), }; Agent expectedResponse = new Agent { AgentName = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"), DisplayName = "display_name137f65c2", DefaultLanguageCode = "default_language_codee612e130", SupportedLanguageCodes = { "supported_language_codesbcd806b9", }, TimeZone = "time_zone73f23b20", Description = "description2cf9da67", AvatarUri = "avatar_urie1767db7", SpeechToTextSettings = new SpeechToTextSettings(), StartFlowAsFlowName = FlowName.FromProjectLocationAgentFlow("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]"), SecuritySettingsAsSecuritySettingsName = SecuritySettingsName.FromProjectLocationSecuritySettings("[PROJECT]", "[LOCATION]", "[SECURITY_SETTINGS]"), #pragma warning disable CS0612 EnableStackdriverLogging = false, #pragma warning restore CS0612 EnableSpellCorrection = true, AdvancedSettings = new AdvancedSettings(), }; mockGrpcClient.Setup(x => x.UpdateAgent(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); AgentsClient client = new AgentsClientImpl(mockGrpcClient.Object, null); Agent response = client.UpdateAgent(request.Agent, request.UpdateMask); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task UpdateAgentAsync() { moq::Mock<Agents.AgentsClient> mockGrpcClient = new moq::Mock<Agents.AgentsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); UpdateAgentRequest request = new UpdateAgentRequest { Agent = new Agent(), UpdateMask = new wkt::FieldMask(), }; Agent expectedResponse = new Agent { AgentName = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"), DisplayName = "display_name137f65c2", DefaultLanguageCode = "default_language_codee612e130", SupportedLanguageCodes = { "supported_language_codesbcd806b9", }, TimeZone = "time_zone73f23b20", Description = "description2cf9da67", AvatarUri = "avatar_urie1767db7", SpeechToTextSettings = new SpeechToTextSettings(), StartFlowAsFlowName = FlowName.FromProjectLocationAgentFlow("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]"), SecuritySettingsAsSecuritySettingsName = SecuritySettingsName.FromProjectLocationSecuritySettings("[PROJECT]", "[LOCATION]", "[SECURITY_SETTINGS]"), #pragma warning disable CS0612 EnableStackdriverLogging = false, #pragma warning restore CS0612 EnableSpellCorrection = true, AdvancedSettings = new AdvancedSettings(), }; mockGrpcClient.Setup(x => x.UpdateAgentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Agent>(stt::Task.FromResult(expectedResponse), null, null, null, null)); AgentsClient client = new AgentsClientImpl(mockGrpcClient.Object, null); Agent responseCallSettings = await client.UpdateAgentAsync(request.Agent, request.UpdateMask, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Agent responseCancellationToken = await client.UpdateAgentAsync(request.Agent, request.UpdateMask, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void DeleteAgentRequestObject() { moq::Mock<Agents.AgentsClient> mockGrpcClient = new moq::Mock<Agents.AgentsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); DeleteAgentRequest request = new DeleteAgentRequest { AgentName = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteAgent(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); AgentsClient client = new AgentsClientImpl(mockGrpcClient.Object, null); client.DeleteAgent(request); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task DeleteAgentRequestObjectAsync() { moq::Mock<Agents.AgentsClient> mockGrpcClient = new moq::Mock<Agents.AgentsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); DeleteAgentRequest request = new DeleteAgentRequest { AgentName = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteAgentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); AgentsClient client = new AgentsClientImpl(mockGrpcClient.Object, null); await client.DeleteAgentAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.DeleteAgentAsync(request, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void DeleteAgent() { moq::Mock<Agents.AgentsClient> mockGrpcClient = new moq::Mock<Agents.AgentsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); DeleteAgentRequest request = new DeleteAgentRequest { AgentName = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteAgent(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); AgentsClient client = new AgentsClientImpl(mockGrpcClient.Object, null); client.DeleteAgent(request.Name); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task DeleteAgentAsync() { moq::Mock<Agents.AgentsClient> mockGrpcClient = new moq::Mock<Agents.AgentsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); DeleteAgentRequest request = new DeleteAgentRequest { AgentName = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteAgentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); AgentsClient client = new AgentsClientImpl(mockGrpcClient.Object, null); await client.DeleteAgentAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.DeleteAgentAsync(request.Name, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void DeleteAgentResourceNames() { moq::Mock<Agents.AgentsClient> mockGrpcClient = new moq::Mock<Agents.AgentsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); DeleteAgentRequest request = new DeleteAgentRequest { AgentName = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteAgent(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); AgentsClient client = new AgentsClientImpl(mockGrpcClient.Object, null); client.DeleteAgent(request.AgentName); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task DeleteAgentResourceNamesAsync() { moq::Mock<Agents.AgentsClient> mockGrpcClient = new moq::Mock<Agents.AgentsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); DeleteAgentRequest request = new DeleteAgentRequest { AgentName = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteAgentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); AgentsClient client = new AgentsClientImpl(mockGrpcClient.Object, null); await client.DeleteAgentAsync(request.AgentName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.DeleteAgentAsync(request.AgentName, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void ValidateAgentRequestObject() { moq::Mock<Agents.AgentsClient> mockGrpcClient = new moq::Mock<Agents.AgentsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); ValidateAgentRequest request = new ValidateAgentRequest { AgentName = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"), LanguageCode = "language_code2f6c7160", }; AgentValidationResult expectedResponse = new AgentValidationResult { AgentValidationResultName = AgentValidationResultName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"), FlowValidationResults = { new FlowValidationResult(), }, }; mockGrpcClient.Setup(x => x.ValidateAgent(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); AgentsClient client = new AgentsClientImpl(mockGrpcClient.Object, null); AgentValidationResult response = client.ValidateAgent(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task ValidateAgentRequestObjectAsync() { moq::Mock<Agents.AgentsClient> mockGrpcClient = new moq::Mock<Agents.AgentsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); ValidateAgentRequest request = new ValidateAgentRequest { AgentName = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"), LanguageCode = "language_code2f6c7160", }; AgentValidationResult expectedResponse = new AgentValidationResult { AgentValidationResultName = AgentValidationResultName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"), FlowValidationResults = { new FlowValidationResult(), }, }; mockGrpcClient.Setup(x => x.ValidateAgentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<AgentValidationResult>(stt::Task.FromResult(expectedResponse), null, null, null, null)); AgentsClient client = new AgentsClientImpl(mockGrpcClient.Object, null); AgentValidationResult responseCallSettings = await client.ValidateAgentAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); AgentValidationResult responseCancellationToken = await client.ValidateAgentAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetAgentValidationResultRequestObject() { moq::Mock<Agents.AgentsClient> mockGrpcClient = new moq::Mock<Agents.AgentsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetAgentValidationResultRequest request = new GetAgentValidationResultRequest { AgentValidationResultName = AgentValidationResultName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"), LanguageCode = "language_code2f6c7160", }; AgentValidationResult expectedResponse = new AgentValidationResult { AgentValidationResultName = AgentValidationResultName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"), FlowValidationResults = { new FlowValidationResult(), }, }; mockGrpcClient.Setup(x => x.GetAgentValidationResult(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); AgentsClient client = new AgentsClientImpl(mockGrpcClient.Object, null); AgentValidationResult response = client.GetAgentValidationResult(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetAgentValidationResultRequestObjectAsync() { moq::Mock<Agents.AgentsClient> mockGrpcClient = new moq::Mock<Agents.AgentsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetAgentValidationResultRequest request = new GetAgentValidationResultRequest { AgentValidationResultName = AgentValidationResultName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"), LanguageCode = "language_code2f6c7160", }; AgentValidationResult expectedResponse = new AgentValidationResult { AgentValidationResultName = AgentValidationResultName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"), FlowValidationResults = { new FlowValidationResult(), }, }; mockGrpcClient.Setup(x => x.GetAgentValidationResultAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<AgentValidationResult>(stt::Task.FromResult(expectedResponse), null, null, null, null)); AgentsClient client = new AgentsClientImpl(mockGrpcClient.Object, null); AgentValidationResult responseCallSettings = await client.GetAgentValidationResultAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); AgentValidationResult responseCancellationToken = await client.GetAgentValidationResultAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetAgentValidationResult() { moq::Mock<Agents.AgentsClient> mockGrpcClient = new moq::Mock<Agents.AgentsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetAgentValidationResultRequest request = new GetAgentValidationResultRequest { AgentValidationResultName = AgentValidationResultName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"), }; AgentValidationResult expectedResponse = new AgentValidationResult { AgentValidationResultName = AgentValidationResultName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"), FlowValidationResults = { new FlowValidationResult(), }, }; mockGrpcClient.Setup(x => x.GetAgentValidationResult(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); AgentsClient client = new AgentsClientImpl(mockGrpcClient.Object, null); AgentValidationResult response = client.GetAgentValidationResult(request.Name); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetAgentValidationResultAsync() { moq::Mock<Agents.AgentsClient> mockGrpcClient = new moq::Mock<Agents.AgentsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetAgentValidationResultRequest request = new GetAgentValidationResultRequest { AgentValidationResultName = AgentValidationResultName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"), }; AgentValidationResult expectedResponse = new AgentValidationResult { AgentValidationResultName = AgentValidationResultName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"), FlowValidationResults = { new FlowValidationResult(), }, }; mockGrpcClient.Setup(x => x.GetAgentValidationResultAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<AgentValidationResult>(stt::Task.FromResult(expectedResponse), null, null, null, null)); AgentsClient client = new AgentsClientImpl(mockGrpcClient.Object, null); AgentValidationResult responseCallSettings = await client.GetAgentValidationResultAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); AgentValidationResult responseCancellationToken = await client.GetAgentValidationResultAsync(request.Name, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetAgentValidationResultResourceNames() { moq::Mock<Agents.AgentsClient> mockGrpcClient = new moq::Mock<Agents.AgentsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetAgentValidationResultRequest request = new GetAgentValidationResultRequest { AgentValidationResultName = AgentValidationResultName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"), }; AgentValidationResult expectedResponse = new AgentValidationResult { AgentValidationResultName = AgentValidationResultName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"), FlowValidationResults = { new FlowValidationResult(), }, }; mockGrpcClient.Setup(x => x.GetAgentValidationResult(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); AgentsClient client = new AgentsClientImpl(mockGrpcClient.Object, null); AgentValidationResult response = client.GetAgentValidationResult(request.AgentValidationResultName); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetAgentValidationResultResourceNamesAsync() { moq::Mock<Agents.AgentsClient> mockGrpcClient = new moq::Mock<Agents.AgentsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetAgentValidationResultRequest request = new GetAgentValidationResultRequest { AgentValidationResultName = AgentValidationResultName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"), }; AgentValidationResult expectedResponse = new AgentValidationResult { AgentValidationResultName = AgentValidationResultName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"), FlowValidationResults = { new FlowValidationResult(), }, }; mockGrpcClient.Setup(x => x.GetAgentValidationResultAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<AgentValidationResult>(stt::Task.FromResult(expectedResponse), null, null, null, null)); AgentsClient client = new AgentsClientImpl(mockGrpcClient.Object, null); AgentValidationResult responseCallSettings = await client.GetAgentValidationResultAsync(request.AgentValidationResultName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); AgentValidationResult responseCancellationToken = await client.GetAgentValidationResultAsync(request.AgentValidationResultName, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } } }
// 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. using Google.Cloud.EntityFrameworkCore.Spanner.IntegrationTests.Model; using Google.Cloud.EntityFrameworkCore.Spanner.Storage; using Google.Cloud.Spanner.Data; using Google.Cloud.Spanner.V1; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.Json; using System.Text.RegularExpressions; using System.Threading.Tasks; using Xunit; namespace Google.Cloud.EntityFrameworkCore.Spanner.IntegrationTests { public class QueryTests : IClassFixture<SpannerSampleFixture> { private readonly SpannerSampleFixture _fixture; public QueryTests(SpannerSampleFixture fixture) => _fixture = fixture; [Fact] public async Task CanFilterOnProperty() { using var db = new TestSpannerSampleDbContext(_fixture.DatabaseName); var singerId = _fixture.RandomLong(); db.Singers.Add(new Singers { SingerId = singerId, FirstName = "Pete", LastName = "Peterson" }); await db.SaveChangesAsync(); var singer = await db.Singers .Where(s => s.FullName == "Pete Peterson" && s.SingerId == singerId) .FirstOrDefaultAsync(); Assert.NotNull(singer); Assert.Equal("Pete Peterson", singer.FullName); } [Fact] public async Task CanOrderByProperty() { using var db = new TestSpannerSampleDbContext(_fixture.DatabaseName); var singerId1 = _fixture.RandomLong(); var singerId2 = _fixture.RandomLong(); db.Singers.AddRange( new Singers { SingerId = singerId1, FirstName = "Pete", LastName = "Peterson" }, new Singers { SingerId = singerId2, FirstName = "Zeke", LastName = "Allison" } ); await db.SaveChangesAsync(); var singers = await db.Singers .Where(s => s.SingerId == singerId1 || s.SingerId == singerId2) .OrderBy(s => s.LastName) .ToListAsync(); Assert.Collection(singers, s => Assert.Equal("Zeke Allison", s.FullName), s => Assert.Equal("Pete Peterson", s.FullName) ); } [Fact] public async Task CanIncludeProperty() { using var db = new TestSpannerSampleDbContext(_fixture.DatabaseName); var singerId1 = _fixture.RandomLong(); var singerId2 = _fixture.RandomLong(); db.Singers.AddRange( new Singers { SingerId = singerId1, FirstName = "Pete", LastName = "Peterson" }, new Singers { SingerId = singerId2, FirstName = "Zeke", LastName = "Allison" } ); db.Albums.AddRange( new Albums { AlbumId = _fixture.RandomLong(), Title = "Album 1", SingerId = singerId1 }, new Albums { AlbumId = _fixture.RandomLong(), Title = "Album 2", SingerId = singerId1 }, new Albums { AlbumId = _fixture.RandomLong(), Title = "Album 3", SingerId = singerId2 }, new Albums { AlbumId = _fixture.RandomLong(), Title = "Album 4", SingerId = singerId2 }, new Albums { AlbumId = _fixture.RandomLong(), Title = "Album 5", SingerId = singerId2 } ); await db.SaveChangesAsync(); var albums = await db.Albums .Include(a => a.Singer) .Where(a => a.Singer.LastName == "Allison" && new long[] { singerId1, singerId2 }.Contains(a.SingerId)) .OrderBy(a => a.Title) .ToListAsync(); Assert.Collection(albums, a => Assert.Equal("Album 3", a.Title), a => Assert.Equal("Album 4", a.Title), a => Assert.Equal("Album 5", a.Title) ); } [Fact] public async Task CanUseLimitWithoutOffset() { using var db = new TestSpannerSampleDbContext(_fixture.DatabaseName); var singerId1 = _fixture.RandomLong(); var singerId2 = _fixture.RandomLong(); db.Singers.AddRange( new Singers { SingerId = singerId1, FirstName = "Pete", LastName = "Peterson" }, new Singers { SingerId = singerId2, FirstName = "Zeke", LastName = "Allison" } ); await db.SaveChangesAsync(); var singers = await db.Singers .Where(s => new long[] { singerId1, singerId2 }.Contains(s.SingerId)) .OrderBy(s => s.LastName) .Take(1) .ToListAsync(); Assert.Collection(singers, s => Assert.Equal("Allison", s.LastName)); } [Fact] public async Task CanUseLimitWithOffset() { using var db = new TestSpannerSampleDbContext(_fixture.DatabaseName); var singerId1 = _fixture.RandomLong(); var singerId2 = _fixture.RandomLong(); var singerId3 = _fixture.RandomLong(); db.Singers.AddRange( new Singers { SingerId = singerId1, FirstName = "Pete", LastName = "Peterson" }, new Singers { SingerId = singerId2, FirstName = "Zeke", LastName = "Allison" }, new Singers { SingerId = singerId3, FirstName = "Sandra", LastName = "Ericson" } ); await db.SaveChangesAsync(); var singers = await db.Singers .Where(s => new long[] { singerId1, singerId2, singerId3 }.Contains(s.SingerId)) .OrderBy(s => s.LastName) .Skip(1) .Take(1) .ToListAsync(); Assert.Collection(singers, s => Assert.Equal("Ericson", s.LastName) ); } [Fact] public async Task CanUseOffsetWithoutLimit() { using var db = new TestSpannerSampleDbContext(_fixture.DatabaseName); var singerId1 = _fixture.RandomLong(); var singerId2 = _fixture.RandomLong(); db.Singers.AddRange( new Singers { SingerId = singerId1, FirstName = "Pete", LastName = "Peterson" }, new Singers { SingerId = singerId2, FirstName = "Zeke", LastName = "Allison" } ); await db.SaveChangesAsync(); var singers = await db.Singers .Where(s => new long[] { singerId1, singerId2 }.Contains(s.SingerId)) .OrderBy(s => s.LastName) .Skip(1) .ToListAsync(); Assert.Collection(singers, s => Assert.Equal("Peterson", s.LastName)); } [Fact] public async Task CanUseInnerJoin() { using var db = new TestSpannerSampleDbContext(_fixture.DatabaseName); var singerId1 = _fixture.RandomLong(); var singerId2 = _fixture.RandomLong(); db.Singers.AddRange( new Singers { SingerId = singerId1, FirstName = "Pete", LastName = "Peterson" }, new Singers { SingerId = singerId2, FirstName = "Zeke", LastName = "Allison" } ); db.Albums.Add(new Albums { AlbumId = _fixture.RandomLong(), Title = "Some Title", SingerId = singerId1 }); await db.SaveChangesAsync(); var singers = await db.Singers .Join(db.Albums, a => a.SingerId, s => s.SingerId, (s, a) => new { Singer = s, Album = a }) .Where(s => new long[] { singerId1, singerId2 }.Contains(s.Singer.SingerId)) .ToListAsync(); Assert.Collection(singers, s => { Assert.Equal("Peterson", s.Singer.LastName); Assert.Equal("Some Title", s.Album.Title); } ); } [Fact] public async Task CanUseOuterJoin() { using var db = new TestSpannerSampleDbContext(_fixture.DatabaseName); var singerId1 = _fixture.RandomLong(); var singerId2 = _fixture.RandomLong(); db.Singers.AddRange( new Singers { SingerId = singerId1, FirstName = "Pete", LastName = "Peterson" }, new Singers { SingerId = singerId2, FirstName = "Zeke", LastName = "Allison" } ); db.Albums.Add(new Albums { AlbumId = _fixture.RandomLong(), Title = "Some Title", SingerId = singerId1 }); await db.SaveChangesAsync(); var singers = await db.Singers .GroupJoin(db.Albums, s => s.SingerId, a => a.SingerId, (s, a) => new { Singer = s, Albums = a }) .SelectMany( s => s.Albums.DefaultIfEmpty(), (s, a) => new { s.Singer, Album = a }) .Where(s => new long[] { singerId1, singerId2 }.Contains(s.Singer.SingerId)) .OrderBy(s => s.Singer.LastName) .ToListAsync(); Assert.Collection(singers, s => { Assert.Equal("Allison", s.Singer.LastName); Assert.Null(s.Album); }, s => { Assert.Equal("Peterson", s.Singer.LastName); Assert.Equal("Some Title", s.Album.Title); } ); } [Fact] public async Task CanUseStringContains() { using var db = new TestSpannerSampleDbContext(_fixture.DatabaseName); var singerId1 = _fixture.RandomLong(); var singerId2 = _fixture.RandomLong(); db.Singers.AddRange( new Singers { SingerId = singerId1, FirstName = "Pete", LastName = "Peterson" }, new Singers { SingerId = singerId2, FirstName = "Zeke", LastName = "Allison" } ); await db.SaveChangesAsync(); var fullName = "Alli"; var singers = await db.Singers .Where(s => s.FullName.Contains(fullName)) .Where(s => new long[] { singerId1, singerId2 }.Contains(s.SingerId)) .ToListAsync(); Assert.Collection(singers, s => Assert.Equal("Zeke Allison", s.FullName)); } [Fact] public async Task CanUseStringStartsWith() { using var db = new TestSpannerSampleDbContext(_fixture.DatabaseName); var singerId1 = _fixture.RandomLong(); var singerId2 = _fixture.RandomLong(); db.Singers.AddRange( new Singers { SingerId = singerId1, FirstName = "Pete", LastName = "Peterson" }, new Singers { SingerId = singerId2, FirstName = "Zeke", LastName = "Allison" } ); await db.SaveChangesAsync(); var fullName = "Zeke"; var singers = await db.Singers .Where(s => s.FullName.StartsWith(fullName)) .Where(s => new long[] { singerId1, singerId2 }.Contains(s.SingerId)) .ToListAsync(); Assert.Collection(singers, s => Assert.Equal("Zeke Allison", s.FullName)); } [Fact] public async Task CanUseStringEndsWith() { using var db = new TestSpannerSampleDbContext(_fixture.DatabaseName); var singerId1 = _fixture.RandomLong(); var singerId2 = _fixture.RandomLong(); db.Singers.AddRange( new Singers { SingerId = singerId1, FirstName = "Pete", LastName = "Peterson" }, new Singers { SingerId = singerId2, FirstName = "Zeke", LastName = "Allison" } ); await db.SaveChangesAsync(); var fullName = "Peterson"; var singers = await db.Singers .Where(s => s.FullName.EndsWith(fullName)) .Where(s => new long[] { singerId1, singerId2 }.Contains(s.SingerId)) .ToListAsync(); Assert.Collection(singers, s => Assert.Equal("Pete Peterson", s.FullName)); } [Fact] public async Task CanUseStringLength() { using var db = new TestSpannerSampleDbContext(_fixture.DatabaseName); var singerId1 = _fixture.RandomLong(); var singerId2 = _fixture.RandomLong(); db.Singers.AddRange( new Singers { SingerId = singerId1, FirstName = "Pete", LastName = "Peterson" }, new Singers { SingerId = singerId2, FirstName = "Alice", LastName = "Morrison" } ); await db.SaveChangesAsync(); var minLength = 4; var singers = await db.Singers .Where(s => s.FirstName.Length > minLength) .Where(s => new long[] { singerId1, singerId2 }.Contains(s.SingerId)) .ToListAsync(); Assert.Collection(singers, s => Assert.Equal("Alice Morrison", s.FullName)); } [Fact] public async Task CanUseStringIndexOf() { using var db = new TestSpannerSampleDbContext(_fixture.DatabaseName); var singerId1 = _fixture.RandomLong(); var singerId2 = _fixture.RandomLong(); db.Singers.AddRange( new Singers { SingerId = singerId1, FirstName = "Pete", LastName = "Peterson" }, new Singers { SingerId = singerId2, FirstName = "Alice", LastName = "Morrison" } ); await db.SaveChangesAsync(); var name = "Morrison"; var minIndex = -1; var singers = await db.Singers .Where(s => s.FullName.IndexOf(name) > minIndex) .Where(s => new long[] { singerId1, singerId2 }.Contains(s.SingerId)) .ToListAsync(); Assert.Collection(singers, s => Assert.Equal("Alice Morrison", s.FullName)); } [Fact] public async Task CanUseStringReplace() { using var db = new TestSpannerSampleDbContext(_fixture.DatabaseName); var singerId1 = _fixture.RandomLong(); var singerId2 = _fixture.RandomLong(); db.Singers.AddRange( new Singers { SingerId = singerId1, FirstName = "Pete", LastName = "Peterson" }, new Singers { SingerId = singerId2, FirstName = "Alice", LastName = "Morrison" } ); await db.SaveChangesAsync(); var from = "Pete"; var to = "Peter"; var name = "Peter Peterrson"; var singers = await db.Singers .Where(s => s.FullName.Replace(from, to) == name) .Where(s => new long[] { singerId1, singerId2 }.Contains(s.SingerId)) .ToListAsync(); Assert.Collection(singers, s => Assert.Equal("Pete Peterson", s.FullName)); } [Fact] public async Task CanUseStringToLower() { using var db = new TestSpannerSampleDbContext(_fixture.DatabaseName); var singerId = _fixture.RandomLong(); db.Singers.AddRange( new Singers { SingerId = singerId, FirstName = "Alice", LastName = "Morrison" } ); await db.SaveChangesAsync(); var fullNameLowerCase = await db.Singers .Where(s => new long[] { singerId }.Contains(s.SingerId)) .Select(s => s.FullName.ToLower()) .FirstOrDefaultAsync(); Assert.Equal("alice morrison", fullNameLowerCase); } [Fact] public async Task CanUseStringToUpper() { using var db = new TestSpannerSampleDbContext(_fixture.DatabaseName); var singerId = _fixture.RandomLong(); db.Singers.AddRange( new Singers { SingerId = singerId, FirstName = "Alice", LastName = "Morrison" } ); await db.SaveChangesAsync(); var fullNameLowerCase = await db.Singers .Where(s => new long[] { singerId }.Contains(s.SingerId)) .Select(s => s.FullName.ToUpper()) .FirstOrDefaultAsync(); Assert.Equal("ALICE MORRISON", fullNameLowerCase); } [Fact] public async Task CanUseStringSubstring() { using var db = new TestSpannerSampleDbContext(_fixture.DatabaseName); var singerId = _fixture.RandomLong(); db.Singers.AddRange( new Singers { SingerId = singerId, FirstName = "Alice", LastName = "Morrison" } ); await db.SaveChangesAsync(); var lastNameFromFullName = await db.Singers .Where(s => new long[] { singerId }.Contains(s.SingerId)) .Select(s => s.FullName.Substring(6)) .FirstOrDefaultAsync(); Assert.Equal("Morrison", lastNameFromFullName); } [Fact] public async Task CanUseStringSubstringWithLength() { using var db = new TestSpannerSampleDbContext(_fixture.DatabaseName); var singerId = _fixture.RandomLong(); db.Singers.AddRange( new Singers { SingerId = singerId, FirstName = "Alice", LastName = "Morrison" } ); await db.SaveChangesAsync(); var lastNameFromFullName = await db.Singers .Where(s => new long[] { singerId }.Contains(s.SingerId)) .Select(s => s.FullName.Substring(6, 3)) .FirstOrDefaultAsync(); Assert.Equal("Mor", lastNameFromFullName); } [Fact] public async Task CanUseStringTrimStart() { using var db = new TestSpannerSampleDbContext(_fixture.DatabaseName); var singerId = _fixture.RandomLong(); db.Singers.AddRange( new Singers { SingerId = singerId, FirstName = " Alice", LastName = "Morrison" } ); await db.SaveChangesAsync(); var trimmedName = await db.Singers .Where(s => new long[] { singerId }.Contains(s.SingerId)) .Select(s => s.FullName.TrimStart()) .FirstOrDefaultAsync(); Assert.Equal("Alice Morrison", trimmedName); } [Fact] public async Task CanUseStringTrimStartWithArgument() { using var db = new TestSpannerSampleDbContext(_fixture.DatabaseName); var singerId = _fixture.RandomLong(); db.Singers.AddRange( new Singers { SingerId = singerId, FirstName = "\t\t\tAlice", LastName = "Morrison" } ); await db.SaveChangesAsync(); var trimmedName = await db.Singers .Where(s => new long[] { singerId }.Contains(s.SingerId)) .Select(s => s.FullName.TrimStart('\t')) .FirstOrDefaultAsync(); Assert.Equal("Alice Morrison", trimmedName); } [Fact] public async Task CanUseStringTrimEnd() { using var db = new TestSpannerSampleDbContext(_fixture.DatabaseName); var singerId = _fixture.RandomLong(); db.Singers.AddRange( new Singers { SingerId = singerId, FirstName = "Alice", LastName = "Morrison " } ); await db.SaveChangesAsync(); var trimmedName = await db.Singers .Where(s => new long[] { singerId }.Contains(s.SingerId)) .Select(s => s.FullName.TrimEnd()) .FirstOrDefaultAsync(); Assert.Equal("Alice Morrison", trimmedName); } [Fact] public async Task CanUseStringTrimEndWithArgument() { using var db = new TestSpannerSampleDbContext(_fixture.DatabaseName); var singerId = _fixture.RandomLong(); db.Singers.AddRange( new Singers { SingerId = singerId, FirstName = "Alice", LastName = "Morrison\t\t\t" } ); await db.SaveChangesAsync(); var trimmedName = await db.Singers .Where(s => new long[] { singerId }.Contains(s.SingerId)) .Select(s => s.FullName.TrimEnd('\t')) .FirstOrDefaultAsync(); Assert.Equal("Alice Morrison", trimmedName); } [Fact] public async Task CanUseStringTrim() { using var db = new TestSpannerSampleDbContext(_fixture.DatabaseName); var singerId = _fixture.RandomLong(); db.Singers.AddRange( new Singers { SingerId = singerId, FirstName = " Alice", LastName = "Morrison " } ); await db.SaveChangesAsync(); var trimmedName = await db.Singers .Where(s => new long[] { singerId }.Contains(s.SingerId)) .Select(s => s.FullName.Trim()) .FirstOrDefaultAsync(); Assert.Equal("Alice Morrison", trimmedName); } [Fact] public async Task CanUseStringTrimWithArgument() { using var db = new TestSpannerSampleDbContext(_fixture.DatabaseName); var singerId = _fixture.RandomLong(); db.Singers.AddRange( new Singers { SingerId = singerId, FirstName = "\t\t\tAlice", LastName = "Morrison\t\t\t" } ); await db.SaveChangesAsync(); var trimmedName = await db.Singers .Where(s => new long[] { singerId }.Contains(s.SingerId)) .Select(s => s.FullName.Trim('\t')) .FirstOrDefaultAsync(); Assert.Equal("Alice Morrison", trimmedName); } [Fact] public async Task CanUseStringConcat() { using var db = new TestSpannerSampleDbContext(_fixture.DatabaseName); var singerId = _fixture.RandomLong(); db.Singers.AddRange( new Singers { SingerId = singerId, FirstName = "Alice", LastName = "Morrison" } ); await db.SaveChangesAsync(); var calculatedFullName = await db.Singers .Where(s => new long[] { singerId }.Contains(s.SingerId)) .Select(s => s.FirstName + " " + s.LastName) .FirstOrDefaultAsync(); Assert.Equal("Alice Morrison", calculatedFullName); } [Fact] public async Task CanUseStringPadLeft() { using var db = new TestSpannerSampleDbContext(_fixture.DatabaseName); var singerId = _fixture.RandomLong(); db.Singers.AddRange( new Singers { SingerId = singerId, FirstName = "Alice", LastName = "Morrison" } ); await db.SaveChangesAsync(); var paddedName = await db.Singers .Where(s => new long[] { singerId }.Contains(s.SingerId)) .Select(s => s.FullName.PadLeft(20)) .FirstOrDefaultAsync(); Assert.Equal(" Alice Morrison", paddedName); } [Fact] public async Task CanUseStringPadLeftWithChar() { using var db = new TestSpannerSampleDbContext(_fixture.DatabaseName); var singerId = _fixture.RandomLong(); db.Singers.AddRange( new Singers { SingerId = singerId, FirstName = "Alice", LastName = "Morrison" } ); await db.SaveChangesAsync(); var paddedName = await db.Singers .Where(s => new long[] { singerId }.Contains(s.SingerId)) .Select(s => s.FullName.PadLeft(20, '$')) .FirstOrDefaultAsync(); Assert.Equal("$$$$$$Alice Morrison", paddedName); } [Fact] public async Task CanUseStringPadRight() { using var db = new TestSpannerSampleDbContext(_fixture.DatabaseName); var singerId = _fixture.RandomLong(); db.Singers.AddRange( new Singers { SingerId = singerId, FirstName = "Alice", LastName = "Morrison" } ); await db.SaveChangesAsync(); var paddedName = await db.Singers .Where(s => new long[] { singerId }.Contains(s.SingerId)) .Select(s => s.FullName.PadRight(20)) .FirstOrDefaultAsync(); Assert.Equal("Alice Morrison ", paddedName); } [Fact] public async Task CanUseStringPadRightWithChar() { using var db = new TestSpannerSampleDbContext(_fixture.DatabaseName); var singerId = _fixture.RandomLong(); db.Singers.AddRange( new Singers { SingerId = singerId, FirstName = "Alice", LastName = "Morrison" } ); await db.SaveChangesAsync(); var paddedName = await db.Singers .Where(s => new long[] { singerId }.Contains(s.SingerId)) .Select(s => s.FullName.PadRight(20, '$')) .FirstOrDefaultAsync(); Assert.Equal("Alice Morrison$$$$$$", paddedName); } [Fact] public async Task CanUseStringFormat() { using var db = new TestSpannerSampleDbContext(_fixture.DatabaseName); var singerId = _fixture.RandomLong(); db.Singers.AddRange( new Singers { SingerId = singerId, FirstName = "Alice", LastName = "Morrison", BirthDate = new SpannerDate(1973, 10, 9) } ); await db.SaveChangesAsync(); var formattedName = await db.Singers .Where(s => new long[] { singerId }.Contains(s.SingerId)) .Select(s => string.Format("String without formatting")) .FirstOrDefaultAsync(); Assert.Equal("String without formatting", formattedName); formattedName = await db.Singers .Where(s => new long[] { singerId }.Contains(s.SingerId)) .Select(s => string.Format("%s", s.FullName)) .FirstOrDefaultAsync(); Assert.Equal("Alice Morrison", formattedName); formattedName = await db.Singers .Where(s => new long[] { singerId }.Contains(s.SingerId)) .Select(s => string.Format("%025d: %s", s.SingerId, s.FullName)) .FirstOrDefaultAsync(); Assert.Equal($"{singerId.ToString().PadLeft(25, '0')}: Alice Morrison", formattedName); formattedName = await db.Singers .Where(s => new long[] { singerId }.Contains(s.SingerId)) .Select(s => string.Format("%025d: %s, born on %t", s.SingerId, s.FullName, s.BirthDate)) .FirstOrDefaultAsync(); Assert.Equal($"{singerId.ToString().PadLeft(25, '0')}: Alice Morrison, born on {new SpannerDate(1973, 10, 9)}", formattedName); } [Fact] public async Task CanUseStringJoin() { using var db = new TestSpannerSampleDbContext(_fixture.DatabaseName); var singerId = _fixture.RandomLong(); var albumId = _fixture.RandomLong(); var id1 = _fixture.RandomLong(); var id2 = _fixture.RandomLong(); db.AddRange( new Singers { SingerId = singerId, LastName = "Allison" }, new Albums { AlbumId = albumId, SingerId = singerId, Title = "Test Title" }, new Tracks { AlbumId = albumId, TrackId = id1, Title = "Track 1", Lyrics = new List<string> { "Test 1", null, "Test 2" }, LyricsLanguages = new List<string> { "en", "en", "en" } }, new Tracks { AlbumId = albumId, TrackId = id2, Title = "Track 2", Lyrics = new List<string> { null, "Test 3", null, "Test 4" }, LyricsLanguages = new List<string> { "en", "en", "en", "en" } } ); await db.SaveChangesAsync(); var rows = await db.Tracks .Where(row => new long[] { id1, id2 }.Contains(row.TrackId) && string.Join(", ", row.Lyrics) == ", Test 3, , Test 4") .ToListAsync(); Assert.Collection(rows, row => Assert.Equal(id2, row.TrackId)); } [Fact] public async Task CanUseRegexIsMatch() { using var db = new TestSpannerSampleDbContext(_fixture.DatabaseName); var singerId1 = _fixture.RandomLong(); var singerId2 = _fixture.RandomLong(); db.Singers.AddRange( new Singers { SingerId = singerId1, FirstName = "Pete", LastName = "Peterson" }, new Singers { SingerId = singerId2, FirstName = "Alice", LastName = "Morrison" } ); await db.SaveChangesAsync(); var pattern = ".*Peterson"; var regex = new Regex(pattern); var singers = await db.Singers .Where(s => regex.IsMatch(s.FullName)) .Where(s => new long[] { singerId1, singerId2 }.Contains(s.SingerId)) .ToListAsync(); Assert.Collection(singers, s => Assert.Equal("Pete Peterson", s.FullName)); singers = await db.Singers .Where(s => Regex.IsMatch(s.FullName, pattern)) .Where(s => new long[] { singerId1, singerId2 }.Contains(s.SingerId)) .ToListAsync(); Assert.Collection(singers, s => Assert.Equal("Pete Peterson", s.FullName)); } [Fact] public async Task CanUseRegexReplace() { using var db = new TestSpannerSampleDbContext(_fixture.DatabaseName); var singerId1 = _fixture.RandomLong(); var singerId2 = _fixture.RandomLong(); db.Singers.AddRange( new Singers { SingerId = singerId1, FirstName = "Pete", LastName = "Peterson" }, new Singers { SingerId = singerId2, FirstName = "Alice", LastName = "Morrison" } ); await db.SaveChangesAsync(); var replacement = "Allison"; var pattern = "Al.*"; var regex = new Regex(pattern); var firstNames = await db.Singers .Where(s => new long[] { singerId1, singerId2 }.Contains(s.SingerId)) .OrderBy(s => s.LastName) .Select(s => regex.Replace(s.FirstName, replacement)) .ToListAsync(); Assert.Collection(firstNames, s => Assert.Equal("Allison", s), s => Assert.Equal("Pete", s) ); firstNames = await db.Singers .Where(s => new long[] { singerId1, singerId2 }.Contains(s.SingerId)) .OrderBy(s => s.LastName) .Select(s => Regex.Replace(s.FirstName, pattern, replacement)) .ToListAsync(); Assert.Collection(firstNames, s => Assert.Equal("Allison", s), s => Assert.Equal("Pete", s) ); } [Fact] public async Task CanUseSpannerDateAddYears() { using var db = new TestSpannerSampleDbContext(_fixture.DatabaseName); var singerId = _fixture.RandomLong(); db.Singers.Add( new Singers { SingerId = singerId, FirstName = "Pete", LastName = "Peterson", BirthDate = new SpannerDate(2001, 12, 13) } ); await db.SaveChangesAsync(); var tenthBirthDate = await db.Singers .Where(s => s.SingerId == singerId) .Select(s => ((SpannerDate)s.BirthDate).AddYears(10)) .FirstOrDefaultAsync(); Assert.Equal(new SpannerDate(2011, 12, 13), tenthBirthDate); } [Fact] public async Task CanUseSpannerDateAddMonths() { using var db = new TestSpannerSampleDbContext(_fixture.DatabaseName); var singerId = _fixture.RandomLong(); db.Singers.Add( new Singers { SingerId = singerId, FirstName = "Pete", LastName = "Peterson", BirthDate = new SpannerDate(2001, 12, 13) } ); await db.SaveChangesAsync(); var date = await db.Singers .Where(s => s.SingerId == singerId) .Select(s => ((SpannerDate)s.BirthDate).AddMonths(23)) .FirstOrDefaultAsync(); Assert.Equal(new SpannerDate(2003, 11, 13), date); } [Fact] public async Task CanUseSpannerDateAddDays() { using var db = new TestSpannerSampleDbContext(_fixture.DatabaseName); var singerId = _fixture.RandomLong(); db.Singers.Add( new Singers { SingerId = singerId, FirstName = "Pete", LastName = "Peterson", BirthDate = new SpannerDate(2001, 12, 13) } ); await db.SaveChangesAsync(); var date = await db.Singers .Where(s => s.SingerId == singerId) .Select(s => ((SpannerDate)s.BirthDate).AddDays(23)) .FirstOrDefaultAsync(); Assert.Equal(new SpannerDate(2002, 1, 5), date); } [Fact] public async Task CanUseDateTimeAddDays() { using var db = new TestSpannerSampleDbContext(_fixture.DatabaseName); var id = _fixture.RandomLong(); var timestamp = new DateTime(2021, 1, 21, 11, 40, 10, DateTimeKind.Utc); db.TableWithAllColumnTypes.Add( new TableWithAllColumnTypes { ColInt64 = id, ColTimestamp = timestamp } ); await db.SaveChangesAsync(); var date = await db.TableWithAllColumnTypes .Where(s => s.ColInt64 == id) .Select(s => new { D1 = ((DateTime)s.ColTimestamp).AddDays(23), D2 = ((DateTime)s.ColTimestamp).AddDays(100) }) .FirstOrDefaultAsync(); Assert.Equal(timestamp.AddDays(23), date.D1); Assert.Equal(timestamp.AddDays(100), date.D2); } [Fact] public async Task CanUseDateTimeAddHours() { using var db = new TestSpannerSampleDbContext(_fixture.DatabaseName); var id = _fixture.RandomLong(); db.TableWithAllColumnTypes.Add( new TableWithAllColumnTypes { ColInt64 = id, ColTimestamp = new DateTime(2021, 1, 21, 11, 40, 10, DateTimeKind.Utc) } ); await db.SaveChangesAsync(); var date = await db.TableWithAllColumnTypes .Where(s => s.ColInt64 == id) .Select(s => ((DateTime)s.ColTimestamp).AddHours(47)) .FirstOrDefaultAsync(); Assert.Equal(new DateTime(2021, 1, 23, 10, 40, 10, DateTimeKind.Utc), date); } [Fact] public async Task CanUseDateTimeAddTicks() { using var db = new TestSpannerSampleDbContext(_fixture.DatabaseName); var id = _fixture.RandomLong(); db.TableWithAllColumnTypes.Add( new TableWithAllColumnTypes { ColInt64 = id, ColTimestamp = new DateTime(2021, 1, 21, 11, 40, 10, DateTimeKind.Utc) } ); await db.SaveChangesAsync(); var date = await db.TableWithAllColumnTypes .Where(s => s.ColInt64 == id) .Select(s => ((DateTime)s.ColTimestamp).AddTicks(20)) .FirstOrDefaultAsync(); Assert.Equal(new DateTime(2021, 1, 21, 11, 40, 10, DateTimeKind.Utc).AddTicks(20), date); } [Fact] public async Task CanUseNumericValueOrDefaultAsDecimal_ThenRoundWithDigits() { using var db = new TestSpannerSampleDbContext(_fixture.DatabaseName); var id = _fixture.RandomLong(); db.TableWithAllColumnTypes.Add( new TableWithAllColumnTypes { ColInt64 = id, ColNumeric = SpannerNumeric.FromDecimal(3.14m, LossOfPrecisionHandling.Throw) } ); await db.SaveChangesAsync(); var expectedValue = 3.1m; var dbValue = await db.TableWithAllColumnTypes // Only rounding with the option AwayFromZero can be handled server side, as that is the only option offered by // Cloud Spanner. If the user does not specify this rounding mode, this query would fail as it cannot be constructed. .Where(s => s.ColInt64 == id && Math.Round(s.ColNumeric.GetValueOrDefault().ToDecimal(LossOfPrecisionHandling.Throw), 1, MidpointRounding.AwayFromZero) == expectedValue) .Select(s => Math.Round(s.ColNumeric.GetValueOrDefault().ToDecimal(LossOfPrecisionHandling.Throw), 1, MidpointRounding.AwayFromZero)) .FirstOrDefaultAsync(); Assert.Equal(expectedValue, dbValue); } [Fact] public async Task CanUseLongMax() { using var db = new TestSpannerSampleDbContext(_fixture.DatabaseName); var id = _fixture.RandomLong(); var randomLong = _fixture.RandomLong(); db.TableWithAllColumnTypes.Add( new TableWithAllColumnTypes { ColInt64 = id } ); await db.SaveChangesAsync(); var expectedValue = Math.Max(id, randomLong); var dbValue = await db.TableWithAllColumnTypes .Where(s => s.ColInt64 == id && Math.Max(s.ColInt64, randomLong) == expectedValue) .Select(s => Math.Max(s.ColInt64, randomLong)) .FirstOrDefaultAsync(); Assert.Equal(expectedValue, dbValue); } [Fact] public async Task CanUseDateTimeProperties() { using var db = new TestSpannerSampleDbContext(_fixture.DatabaseName); var id = _fixture.RandomLong(); var randomLong = _fixture.RandomLong(); var timestamp = new DateTime(2021, 1, 25, 14, 29, 15, 182, DateTimeKind.Utc); db.TableWithAllColumnTypes.Add( new TableWithAllColumnTypes { ColInt64 = id, ColTimestamp = timestamp } ); await db.SaveChangesAsync(); var extracted = await db.TableWithAllColumnTypes .Where(t => t.ColInt64 == id) .Select(t => new { t.ColTimestamp.GetValueOrDefault().Year, t.ColTimestamp.GetValueOrDefault().Month, t.ColTimestamp.GetValueOrDefault().Day, t.ColTimestamp.GetValueOrDefault().DayOfYear, t.ColTimestamp.GetValueOrDefault().DayOfWeek, t.ColTimestamp.GetValueOrDefault().Hour, t.ColTimestamp.GetValueOrDefault().Minute, t.ColTimestamp.GetValueOrDefault().Second, t.ColTimestamp.GetValueOrDefault().Millisecond, t.ColTimestamp.GetValueOrDefault().Date, }) .FirstOrDefaultAsync(); Assert.Equal(timestamp.Year, extracted.Year); Assert.Equal(timestamp.Month, extracted.Month); Assert.Equal(timestamp.Day, extracted.Day); Assert.Equal(timestamp.DayOfYear, extracted.DayOfYear); Assert.Equal(timestamp.DayOfWeek, extracted.DayOfWeek); Assert.Equal(timestamp.Hour, extracted.Hour); Assert.Equal(timestamp.Minute, extracted.Minute); Assert.Equal(timestamp.Second, extracted.Second); Assert.Equal(timestamp.Millisecond, extracted.Millisecond); Assert.Equal(timestamp.Date, extracted.Date); } [Fact] public async Task CanUseSpannerDateProperties() { using var db = new TestSpannerSampleDbContext(_fixture.DatabaseName); var id = _fixture.RandomLong(); var randomLong = _fixture.RandomLong(); var date = new SpannerDate(2021, 1, 25); db.TableWithAllColumnTypes.Add( new TableWithAllColumnTypes { ColInt64 = id, ColDate = date } ); await db.SaveChangesAsync(); var extracted = await db.TableWithAllColumnTypes .Where(t => t.ColInt64 == id) .Select(t => new { t.ColDate.GetValueOrDefault().Year, t.ColDate.GetValueOrDefault().Month, t.ColDate.GetValueOrDefault().Day, t.ColDate.GetValueOrDefault().DayOfYear, t.ColDate.GetValueOrDefault().DayOfWeek, }) .FirstOrDefaultAsync(); Assert.Equal(date.Year, extracted.Year); Assert.Equal(date.Month, extracted.Month); Assert.Equal(date.Day, extracted.Day); Assert.Equal(date.DayOfYear, extracted.DayOfYear); Assert.Equal(date.DayOfWeek, extracted.DayOfWeek); } [Fact] public async Task CanUseBoolToString() { using var db = new TestSpannerSampleDbContext(_fixture.DatabaseName); var id = _fixture.RandomLong(); db.TableWithAllColumnTypes.Add( new TableWithAllColumnTypes { ColInt64 = id, ColBool = true } ); await db.SaveChangesAsync(); var converted = await db.TableWithAllColumnTypes .Where(t => t.ColInt64 == id) .Select(t => t.ColBool.GetValueOrDefault().ToString()) .FirstOrDefaultAsync(); Assert.Equal("true", converted); } [Fact] public async Task CanUseBytesToString() { using var db = new TestSpannerSampleDbContext(_fixture.DatabaseName); var id = _fixture.RandomLong(); db.TableWithAllColumnTypes.Add( new TableWithAllColumnTypes { ColInt64 = id, ColBytes = Encoding.UTF8.GetBytes("test") } ); await db.SaveChangesAsync(); var converted = await db.TableWithAllColumnTypes .Where(t => t.ColInt64 == id) .Select(t => t.ColBytes.ToString()) .FirstOrDefaultAsync(); Assert.Equal("test", converted); } [Fact] public async Task CanUseLongToString() { using var db = new TestSpannerSampleDbContext(_fixture.DatabaseName); var id = _fixture.RandomLong(); db.TableWithAllColumnTypes.Add( new TableWithAllColumnTypes { ColInt64 = id } ); await db.SaveChangesAsync(); var converted = await db.TableWithAllColumnTypes .Where(t => t.ColInt64 == id) .Select(t => t.ColInt64.ToString()) .FirstOrDefaultAsync(); Assert.Equal($"{id}", converted); } [Fact] public async Task CanUseSpannerNumericToString() { using var db = new TestSpannerSampleDbContext(_fixture.DatabaseName); var id = _fixture.RandomLong(); db.TableWithAllColumnTypes.Add( new TableWithAllColumnTypes { ColInt64 = id, ColNumeric = SpannerNumeric.Parse("3.14") } ); await db.SaveChangesAsync(); var converted = await db.TableWithAllColumnTypes .Where(t => t.ColInt64 == id) .Select(t => t.ColNumeric.GetValueOrDefault().ToString()) .FirstOrDefaultAsync(); // The emulator and real Spanner have a slight difference in casting this FLOAT64 to STRING. // Real Spanner returns '3.14' and the emulator returns '3.1400000000000001'. Assert.StartsWith("3.14", converted); } [Fact] public async Task CanUseDoubleToString() { using var db = new TestSpannerSampleDbContext(_fixture.DatabaseName); var id = _fixture.RandomLong(); db.TableWithAllColumnTypes.Add( new TableWithAllColumnTypes { ColInt64 = id, ColFloat64 = 3.14d } ); await db.SaveChangesAsync(); var converted = await db.TableWithAllColumnTypes .Where(t => t.ColInt64 == id) .Select(t => t.ColFloat64.GetValueOrDefault().ToString()) .FirstOrDefaultAsync(); // The emulator and real Spanner have a slight difference in casting this FLOAT64 to STRING. // Real Spanner returns '3.14' and the emulator returns '3.1400000000000001'. Assert.StartsWith("3.14", converted); } [Fact] public async Task CanUseSpannerDateToString() { using var db = new TestSpannerSampleDbContext(_fixture.DatabaseName); var id = _fixture.RandomLong(); db.TableWithAllColumnTypes.Add( new TableWithAllColumnTypes { ColInt64 = id, ColDate = new SpannerDate(2021, 1, 25) } ); await db.SaveChangesAsync(); var converted = await db.TableWithAllColumnTypes .Where(t => t.ColInt64 == id) .Select(t => t.ColDate.GetValueOrDefault().ToString()) .FirstOrDefaultAsync(); Assert.Equal("2021-01-25", converted); } [Fact] public async Task CanUseDateTimeToString() { using var db = new TestSpannerSampleDbContext(_fixture.DatabaseName); var id = _fixture.RandomLong(); db.TableWithAllColumnTypes.Add( new TableWithAllColumnTypes { ColInt64 = id, ColTimestamp = new DateTime(2021, 1, 25, 12, 46, 1, 982, DateTimeKind.Utc) } ); await db.SaveChangesAsync(); var converted = await db.TableWithAllColumnTypes .Where(t => t.ColInt64 == id) .Select(t => t.ColTimestamp.GetValueOrDefault().ToString()) .FirstOrDefaultAsync(); Assert.Equal("2021-01-25T12:46:01.982Z", converted); } [Fact] public async Task CanFilterOnArrayLength() { using var db = new TestSpannerSampleDbContext(_fixture.DatabaseName); var id = _fixture.RandomLong(); db.TableWithAllColumnTypes.Add( new TableWithAllColumnTypes { ColInt64 = id, ColStringArray = new List<string> { "1", "2" } } ); await db.SaveChangesAsync(); var selectedId = await db.TableWithAllColumnTypes .Where(t => t.ColInt64 == id && t.ColStringArray.Count == 2) .Select(t => t.ColInt64) .FirstOrDefaultAsync(); Assert.Equal(id, selectedId); } [Fact] public async Task CanQueryRawSqlWithParameters() { using var db = new TestSpannerSampleDbContext(_fixture.DatabaseName); var singerId1 = _fixture.RandomLong(); var singerId2 = _fixture.RandomLong(); db.Singers.AddRange( new Singers { SingerId = singerId1, FirstName = "Pete", LastName = "Peterson" }, new Singers { SingerId = singerId2, FirstName = "Zeke", LastName = "Allison" } ); await db.SaveChangesAsync(); var singers = await db.Singers .FromSqlRaw("SELECT * FROM Singers WHERE SingerId IN UNNEST(@id)", new SpannerParameter("id", SpannerDbType.ArrayOf(SpannerDbType.Int64), new List<long> { singerId1, singerId2 })) .OrderBy(s => s.LastName) .ToListAsync(); Assert.Collection(singers, s => Assert.Equal("Allison", s.LastName), s => Assert.Equal("Peterson", s.LastName) ); } [Fact] public async Task CanInsertSingerUsingRawSql() { using var db = new TestSpannerSampleDbContext(_fixture.DatabaseName); var singerId1 = _fixture.RandomLong(); var firstName1 = "Pete"; var lastName1 = "Peterson"; var updateCount1 = await db.Database.ExecuteSqlRawAsync( "INSERT INTO Singers (SingerId, FirstName, LastName) VALUES (@id, @firstName, @lastName)", new SpannerParameter("id", SpannerDbType.Int64, singerId1), new SpannerParameter("firstName", SpannerDbType.String, firstName1), new SpannerParameter("lastName", SpannerDbType.String, lastName1) ); var singerId2 = _fixture.RandomLong(); var firstName2 = "Zeke"; var lastName2 = "Allison"; var updateCount2 = await db.Database.ExecuteSqlInterpolatedAsync( $"INSERT INTO Singers (SingerId, FirstName, LastName) VALUES ({singerId2}, {firstName2}, {lastName2})" ); var singerId3 = _fixture.RandomLong(); var firstName3 = "Luke"; var lastName3 = "Harrison"; var updateCount3 = await db.Database.ExecuteSqlRawAsync( "INSERT INTO Singers (SingerId, FirstName, LastName) VALUES ({0}, {1}, {2})", singerId3, firstName3, lastName3 ); Assert.Equal(1, updateCount1); Assert.Equal(1, updateCount2); Assert.Equal(1, updateCount3); var singers = await db.Singers .FromSqlRaw("SELECT * FROM Singers WHERE SingerId IN UNNEST(@id)", new SpannerParameter("id", SpannerDbType.ArrayOf(SpannerDbType.Int64), new List<long> { singerId1, singerId2, singerId3 })) .OrderBy(s => s.LastName) .ToListAsync(); Assert.Collection(singers, s => Assert.Equal("Allison", s.LastName), s => Assert.Equal("Harrison", s.LastName), s => Assert.Equal("Peterson", s.LastName) ); } [Fact] public async Task CanInsertRowWithAllColumnTypesUsingRawSql() { using var db = new TestSpannerSampleDbContext(_fixture.DatabaseName); var id1 = _fixture.RandomLong(); var today = SpannerDate.FromDateTime(DateTime.SpecifyKind(DateTime.Today, DateTimeKind.Unspecified)); var now = DateTime.UtcNow; var row = new TableWithAllColumnTypes { ColBool = true, ColBoolArray = new List<bool?> { true, false, true }, ColBytes = new byte[] { 1, 2, 3 }, ColBytesMax = Encoding.UTF8.GetBytes("This is a long string"), ColBytesArray = new List<byte[]> { new byte[] { 3, 2, 1 }, new byte[] { }, new byte[] { 4, 5, 6 } }, ColBytesMaxArray = new List<byte[]> { Encoding.UTF8.GetBytes("string 1"), Encoding.UTF8.GetBytes("string 2"), Encoding.UTF8.GetBytes("string 3") }, ColDate = new SpannerDate(2020, 12, 28), ColDateArray = new List<SpannerDate?> { new SpannerDate(2020, 12, 28), new SpannerDate(2010, 1, 1), today }, ColFloat64 = 3.14D, ColFloat64Array = new List<double?> { 3.14D, 6.626D }, ColInt64 = id1, ColInt64Array = new List<long?> { 1L, 2L, 4L, 8L }, ColJson = JsonDocument.Parse("{\"key\": \"value\"}"), ColJsonArray = new List<JsonDocument>{JsonDocument.Parse("{\"key1\": \"value1\"}"), null, JsonDocument.Parse("{\"key2\": \"value2\"}")}, ColNumeric = (SpannerNumeric?)3.14m, ColNumericArray = new List<SpannerNumeric?> { (SpannerNumeric)3.14m, (SpannerNumeric)6.626m }, ColString = "some string", ColStringArray = new List<string> { "string1", "string2", "string3" }, ColStringMax = "some longer string", ColStringMaxArray = new List<string> { "longer string1", "longer string2", "longer string3" }, ColTimestamp = new DateTime(2020, 12, 28, 15, 16, 28, 148).AddTicks(1839288), ColTimestampArray = new List<DateTime?> { new DateTime(2020, 12, 28, 15, 16, 28, 148).AddTicks(1839288), now }, }; var updateCount1 = await db.Database.ExecuteSqlRawAsync(@"INSERT INTO TableWithAllColumnTypes (ColBool, ColBoolArray, ColBytes, ColBytesMax, ColBytesArray, ColBytesMaxArray, ColDate, ColDateArray, ColFloat64, ColFloat64Array, ColInt64, ColInt64Array, ColJson, ColJsonArray, ColNumeric, ColNumericArray, ColString, ColStringArray, ColStringMax, ColStringMaxArray, ColTimestamp, ColTimestampArray) VALUES (@ColBool, @ColBoolArray, @ColBytes, @ColBytesMax, @ColBytesArray, @ColBytesMaxArray, @ColDate, @ColDateArray, @ColFloat64, @ColFloat64Array, @ColInt64, @ColInt64Array, @ColJson, @ColJsonArray, @ColNumeric, @ColNumericArray, @ColString, @ColStringArray, @ColStringMax, @ColStringMaxArray, @ColTimestamp, @ColTimestampArray)", new SpannerParameter("ColBool", SpannerDbType.Bool, row.ColBool), new SpannerParameter("ColBoolArray", SpannerDbType.ArrayOf(SpannerDbType.Bool), row.ColBoolArray), new SpannerParameter("ColBytes", SpannerDbType.Bytes, row.ColBytes), new SpannerParameter("ColBytesMax", SpannerDbType.Bytes, row.ColBytesMax), new SpannerParameter("ColBytesArray", SpannerDbType.ArrayOf(SpannerDbType.Bytes), row.ColBytesArray), new SpannerParameter("ColBytesMaxArray", SpannerDbType.ArrayOf(SpannerDbType.Bytes), row.ColBytesMaxArray), new SpannerParameter("ColDate", SpannerDbType.Date, row.ColDate), new SpannerParameter("ColDateArray", SpannerDbType.ArrayOf(SpannerDbType.Date), row.ColDateArray), new SpannerParameter("ColFloat64", SpannerDbType.Float64, row.ColFloat64), new SpannerParameter("ColFloat64Array", SpannerDbType.ArrayOf(SpannerDbType.Float64), row.ColFloat64Array), new SpannerParameter("ColInt64", SpannerDbType.Int64, row.ColInt64), new SpannerParameter("ColInt64Array", SpannerDbType.ArrayOf(SpannerDbType.Int64), row.ColInt64Array), new SpannerParameter("ColJson", SpannerDbType.Json, row.ColJson.RootElement.ToString()), new SpannerParameter("ColJsonArray", SpannerDbType.ArrayOf(SpannerDbType.Json), row.ColJsonArray.Select(v => v?.RootElement.ToString())), new SpannerParameter("ColNumeric", SpannerDbType.Numeric, row.ColNumeric), new SpannerParameter("ColNumericArray", SpannerDbType.ArrayOf(SpannerDbType.Numeric), row.ColNumericArray), new SpannerParameter("ColString", SpannerDbType.String, row.ColString), new SpannerParameter("ColStringArray", SpannerDbType.ArrayOf(SpannerDbType.String), row.ColStringArray), new SpannerParameter("ColStringMax", SpannerDbType.String, row.ColStringMax), new SpannerParameter("ColStringMaxArray", SpannerDbType.ArrayOf(SpannerDbType.String), row.ColStringMaxArray), new SpannerParameter("ColTimestamp", SpannerDbType.Timestamp, row.ColTimestamp), new SpannerParameter("ColTimestampArray", SpannerDbType.ArrayOf(SpannerDbType.Timestamp), row.ColTimestampArray) ); Assert.Equal(1, updateCount1); var id2 = _fixture.RandomLong(); row.ColInt64 = id2; var updateCount2 = await db.Database.ExecuteSqlInterpolatedAsync( @$"INSERT INTO TableWithAllColumnTypes (ColBool, ColBoolArray, ColBytes, ColBytesMax, ColBytesArray, ColBytesMaxArray, ColDate, ColDateArray, ColFloat64, ColFloat64Array, ColInt64, ColInt64Array, ColJson, ColJsonArray, ColNumeric, ColNumericArray, ColString, ColStringArray, ColStringMax, ColStringMaxArray, ColTimestamp, ColTimestampArray) VALUES ({ row.ColBool}, { row.ColBoolArray}, { row.ColBytes}, { row.ColBytesMax}, { row.ColBytesArray}, { row.ColBytesMaxArray}, { row.ColDate}, { row.ColDateArray}, { row.ColFloat64}, { row.ColFloat64Array}, { row.ColInt64}, { row.ColInt64Array}, { row.ColJson}, { row.ColJsonArray}, { row.ColNumeric}, { row.ColNumericArray}, { row.ColString}, { row.ColStringArray}, { row.ColStringMax}, { row.ColStringMaxArray}, { row.ColTimestamp}, { row.ColTimestampArray})" ); Assert.Equal(1, updateCount2); var id3 = _fixture.RandomLong(); row.ColInt64 = id3; var updateCount3 = await db.Database.ExecuteSqlRawAsync( @"INSERT INTO TableWithAllColumnTypes (ColBool, ColBoolArray, ColBytes, ColBytesMax, ColBytesArray, ColBytesMaxArray, ColDate, ColDateArray, ColFloat64, ColFloat64Array, ColInt64, ColInt64Array, ColJson, ColJsonArray, ColNumeric, ColNumericArray, ColString, ColStringArray, ColStringMax, ColStringMaxArray, ColTimestamp, ColTimestampArray) VALUES ({0}, {1}, {2}, {3}, {4}, {5}, {6}, {7}, {8}, {9}, {10}, {11}, {12}, {13}, {14}, {15}, {16}, {17}, {18}, {19}, {20}, {21})", row.ColBool, row.ColBoolArray, row.ColBytes, row.ColBytesMax, row.ColBytesArray, row.ColBytesMaxArray, row.ColDate, row.ColDateArray, row.ColFloat64, row.ColFloat64Array, row.ColInt64, row.ColInt64Array, row.ColJson, row.ColJsonArray, row.ColNumeric, row.ColNumericArray, row.ColString, row.ColStringArray, row.ColStringMax, row.ColStringMaxArray, row.ColTimestamp, row.ColTimestampArray ); Assert.Equal(1, updateCount3); var rows = await db.TableWithAllColumnTypes .FromSqlRaw("SELECT * FROM TableWithAllColumnTypes WHERE ColInt64 IN UNNEST(@id)", new SpannerParameter("id", SpannerDbType.ArrayOf(SpannerDbType.Int64), new List<long> { id1, id2, id3 })) .OrderBy(s => s.ColString) .ToListAsync(); Assert.Collection(rows, row => Assert.NotNull(row.ColDateArray), row => Assert.NotNull(row.ColDateArray), row => Assert.NotNull(row.ColDateArray) ); } [Fact] public async Task CanQueryOnReservedKeywords() { using var db = new TestSpannerSampleDbContext(_fixture.DatabaseName); var id1 = _fixture.RandomLong(); var id2 = _fixture.RandomLong(); db.TableWithAllColumnTypes.Add( new TableWithAllColumnTypes { ColInt64 = id1, ASC = "This is reserved keyword" }); await db.SaveChangesAsync(); db.TableWithAllColumnTypes.Add(new TableWithAllColumnTypes { ColInt64 = id2, ASC = "string1" }); await db.SaveChangesAsync(); // Select query var result = db.TableWithAllColumnTypes .Where(s => new long[] { id1, id2 }.Contains(s.ColInt64)) .OrderBy(s => s.ASC) .Select(c => c.ASC).ToList(); Assert.Collection(result, s => Assert.Equal("This is reserved keyword", s), s => Assert.Equal("string1", s)); // Where clause var result1 = db.TableWithAllColumnTypes .Where(s => new long[] { id1, id2 }.Contains(s.ColInt64)) .Where(s => s.ASC == "string1") .Select(c => c.ASC).ToList(); Assert.Collection(result1, s => Assert.Equal("string1", s)); // Start with query var result2 = db.TableWithAllColumnTypes .Where(s => new long[] { id1, id2 }.Contains(s.ColInt64)) .Where(s => s.ASC.StartsWith("This")) .Select(c => c.ASC).ToList(); Assert.Collection(result2, s => Assert.Equal("This is reserved keyword", s)); // Contain query var result3 = db.TableWithAllColumnTypes .Where(s => new long[] { id1, id2 }.Contains(s.ColInt64)) .Where(s => s.ASC.Contains("1")) .Select(c => c.ASC).ToList(); Assert.Collection(result3, s => Assert.Equal("string1", s)); // Like function var result4 = db.TableWithAllColumnTypes .Where(s => new long[] { id1, id2 }.Contains(s.ColInt64)) .Where(s => EF.Functions.Like(s.ASC, "%1")) .Select(c => c.ASC).ToList(); Assert.Collection(result4, s => Assert.Equal("string1", s)); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information. using System.Threading.Tasks; using Microsoft.CodeAnalysis.Testing; using Test.Utilities; using Xunit; using VerifyCS = Test.Utilities.CSharpCodeFixVerifier< Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.StaticHolderTypesAnalyzer, Microsoft.CodeQuality.CSharp.Analyzers.ApiDesignGuidelines.CSharpStaticHolderTypesFixer>; using VerifyVB = Test.Utilities.VisualBasicCodeFixVerifier< Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.StaticHolderTypesAnalyzer, Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>; namespace Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.UnitTests { public class StaticHolderTypeTests { #region Verifiers private static DiagnosticResult CSharpResult(int line, int column, string objectName) #pragma warning disable RS0030 // Do not used banned APIs => VerifyCS.Diagnostic() .WithLocation(line, column) #pragma warning restore RS0030 // Do not used banned APIs .WithArguments(objectName); private static DiagnosticResult BasicResult(int line, int column, string objectName) #pragma warning disable RS0030 // Do not used banned APIs => VerifyVB.Diagnostic() .WithLocation(line, column) #pragma warning restore RS0030 // Do not used banned APIs .WithArguments(objectName); #endregion [Fact] public async Task CA1052NoDiagnosticForEmptyNonStaticClassCSharpAsync() { await VerifyCS.VerifyAnalyzerAsync(@" public class C1 { } "); } [Fact] public async Task CA1052NoDiagnosticForEmptyInheritableClassBasicAsync() { await VerifyVB.VerifyAnalyzerAsync(@" Public Class B1 End Class "); } [Fact] public async Task CA1052NoDiagnosticForStaticClassWithOnlyStaticDeclaredMembersCSharpAsync() { await VerifyCS.VerifyAnalyzerAsync(@" public static class C2 { public static void DoSomething() { } } "); } [Fact, WorkItem(1320, "https://github.com/dotnet/roslyn-analyzers/issues/1320")] public async Task CA1052NoDiagnosticForSealedClassWithOnlyStaticDeclaredMembersCSharpAsync() { await VerifyCS.VerifyAnalyzerAsync(@" public sealed class C3 { public static void DoSomething() { } } "); } [Fact, WorkItem(1320, "https://github.com/dotnet/roslyn-analyzers/issues/1320")] public async Task CA1052NoDiagnosticForNonInheritableClassWithOnlySharedDeclaredMembersBasicAsync() { await VerifyVB.VerifyAnalyzerAsync(@" Public NotInheritable Class B3 Public Shared Sub DoSomething() End Sub End Class "); } [Fact, WorkItem(1292, "https://github.com/dotnet/roslyn-analyzers/issues/1292")] public async Task CA1052NoDiagnosticForSealedClassWithPublicConstructorAndStaticMembersAsync() { await VerifyCS.VerifyAnalyzerAsync(@" using System.Threading; public sealed class ConcurrentCreationDummy { private static int creationAttempts; public ConcurrentCreationDummy() { if (IsCreatingFirstInstance()) { CreatingFirstInstance.Set(); CreatedSecondInstance.Wait(); } } public static ManualResetEventSlim CreatingFirstInstance { get; } = new ManualResetEventSlim(); public static ManualResetEventSlim CreatedSecondInstance { get; } = new ManualResetEventSlim(); private static bool IsCreatingFirstInstance() { return Interlocked.Increment(ref creationAttempts) == 1; } }"); } [Fact] public async Task CA1052DiagnosticForNonStaticClassWithOnlyStaticDeclaredMembersCSharpAsync() { await VerifyCS.VerifyAnalyzerAsync(@" public class C4 { public static void DoSomething() { } } ", CSharpResult(2, 14, "C4")); } [Fact] public async Task CA1052DiagnosticForNonStaticClassWithOnlySharedDeclaredMembersBasicAsync() { await VerifyVB.VerifyAnalyzerAsync(@" Public Class B4 Public Shared Sub DoSomething() End Sub End Class ", BasicResult(2, 14, "B4")); } [Fact] public async Task CA1052NoDiagnosticForNonStaticClassWithBothStaticAndInstanceDeclaredMembersCSharpAsync() { await VerifyCS.VerifyAnalyzerAsync(@" public class C5 { public void Moo() { } public static void DoSomething() { } } "); } [Fact] public async Task CA1052NoDiagnosticForNonStaticClassWithBothSharedAndInstanceDeclaredMembersBasicAsync() { await VerifyVB.VerifyAnalyzerAsync(@" Public Class B5 Public Sub Moo() End Sub Public Shared Sub DoSomething() End Sub End Class "); } [Fact] public async Task CA1052NoDiagnosticForInternalClassWithOnlyStaticDeclaredMembersCSharpAsync() { await VerifyCS.VerifyAnalyzerAsync(@" internal class C6 { public static void DoSomething() { } } "); } [Fact, WorkItem(1432, "https://github.com/dotnet/roslyn-analyzers/issues/1432")] public async Task CA1052NoDiagnosticForEffectivelyInternalClassWithOnlyStaticDeclaredMembersCSharpAsync() { await VerifyCS.VerifyAnalyzerAsync(@" internal class C6 { public class Inner { public static void DoSomething() { } } } "); } [Fact] public async Task CA1052NoDiagnosticForFriendClassWithOnlySharedDeclaredMembersBasicAsync() { await VerifyVB.VerifyAnalyzerAsync(@" Friend Class B6 Public Shared Sub DoSomething() End Sub End Class "); } [Fact, WorkItem(1432, "https://github.com/dotnet/roslyn-analyzers/issues/1432")] public async Task CA1052NoDiagnosticForEffectivelyFriendClassWithOnlySharedDeclaredMembersBasicAsync() { await VerifyVB.VerifyAnalyzerAsync(@" Friend Class B6 Public Class InnerClass Public Shared Sub DoSomething() End Sub End Class End Class "); } [Fact] public async Task CA1052NoDiagnosticForNonStaticClassWithUserDefinedOperatorCSharpAsync() { await VerifyCS.VerifyAnalyzerAsync(@" public class C7 { public static int operator +(C7 a, C7 b) { return 0; } } "); } [Fact] public async Task CA1052NoDiagnosticForNonStaticClassWithUserDefinedOperatorBasicAsync() { await VerifyVB.VerifyAnalyzerAsync(@" Public Class B7 Public Shared Operator +(a As B7, b As B7) As Integer Return 0 End Operator End Class "); } [Fact] public async Task CA1052NoDiagnosticForNonStaticClassWithStaticMethodAndUserDefinedOperatorCSharpAsync() { await VerifyCS.VerifyAnalyzerAsync(@" public class C8 { public static void DoSomething() { } public static int operator +(C8 a, C8 b) { return 0; } } "); } [Fact] public async Task CA1052NoDiagnosticForNonStaticClassWithSharedMethodAndUserDefinedOperatorBasicAsync() { await VerifyVB.VerifyAnalyzerAsync(@" Public Class B8 Public Shared Sub DoSomething() End Sub Public Shared Operator +(a As B8, b As B8) As Integer Return 0 End Operator End Class "); } [Fact] public async Task CA1052DiagnosticForNonStaticClassWithPublicDefaultConstructorAndStaticMethodCSharpAsync() { await VerifyCS.VerifyAnalyzerAsync(@" public class C9 { public C9() { } public static void DoSomething() { } } ", CSharpResult(2, 14, "C9")); } [Fact] public async Task CA1052DiagnosticForNonStaticClassWithPublicDefaultConstructorAndSharedMethodBasicAsync() { await VerifyVB.VerifyAnalyzerAsync(@" Public Class B9 Public Sub New() End Sub Public Shared Sub DoSomething() End Sub End Class ", BasicResult(2, 14, "B9")); } [Fact] public async Task CA1052DiagnosticForNonStaticClassWithProtectedDefaultConstructorAndStaticMethodCSharpAsync() { await VerifyCS.VerifyAnalyzerAsync(@" public class C10 { protected C10() { } public static void DoSomething() { } } ", CSharpResult(2, 14, "C10")); } [Fact] public async Task CA1052DiagnosticForNonStaticClassWithProtectedDefaultConstructorAndSharedMethodBasicAsync() { await VerifyVB.VerifyAnalyzerAsync(@" Public Class B10 Protected Sub New() End Sub Public Shared Sub DoSomething() End Sub End Class ", BasicResult(2, 14, "B10")); } [Fact] public async Task CA1052DiagnosticForNonStaticClassWithPrivateDefaultConstructorAndStaticMethodCSharpAsync() { await VerifyCS.VerifyAnalyzerAsync(@" public class C11 { private C11() { } public static void DoSomething() { } } ", CSharpResult(2, 14, "C11")); } [Fact] public async Task CA1052DiagnosticForNonStaticClassWithPrivateDefaultConstructorAndSharedMethodBasicAsync() { await VerifyVB.VerifyAnalyzerAsync(@" Public Class B11 Private Sub New() End Sub Public Shared Sub DoSomething() End Sub End Class ", BasicResult(2, 14, "B11")); } [Fact] public async Task CA1052NoDiagnosticForNonStaticClassWithPublicNonDefaultConstructorAndStaticMethodCSharpAsync() { await VerifyCS.VerifyAnalyzerAsync(@" public class C12 { public C12(int i) { } public static void DoSomething() { } } "); } [Fact] public async Task CA1052NoDiagnosticForNonStaticClassWithPublicNonDefaultConstructorAndSharedMethodBasicAsync() { await VerifyVB.VerifyAnalyzerAsync(@" Public Class B12 Public Sub New(i as Integer) End Sub Public Shared Sub DoSomething() End Sub End Class "); } [Fact] public async Task CA1052NoDiagnosticForNonStaticClassWithPublicNonDefaultConstructorWithDefaultedParametersAndStaticMethodCSharpAsync() { await VerifyCS.VerifyAnalyzerAsync(@" public class C13 { public C13(int i = 0, string s = """") { } public static void DoSomething() { } } "); } [Fact] public async Task CA1052NoDiagnosticForNonStaticClassWithPublicNonDefaultConstructorWithOptionalParametersAndSharedMethodBasicAsync() { await VerifyVB.VerifyAnalyzerAsync(@" Public Class B13 Public Sub New(Optional i as Integer = 0, Optional s as String = """") End Sub Public Shared Sub DoSomething() End Sub End Class "); } [Fact] public async Task CA1052DiagnosticForNestedPublicNonStaticClassWithPublicDefaultConstructorAndStaticMethodCSharpAsync() { await VerifyCS.VerifyAnalyzerAsync(@" public class C14 { public void Moo() { } public class C14Inner { public C14Inner() { } public static void DoSomething() { } } } ", CSharpResult(6, 18, "C14Inner")); } [Fact] public async Task CA1052DiagnosticForNestedPublicNonStaticClassWithPublicDefaultConstructorAndSharedMethodBasicAsync() { await VerifyVB.VerifyAnalyzerAsync(@" Public Class B14 Public Sub Moo() End Sub Public Class B14Inner Public Sub New() End Sub Public Shared Sub DoSomething() End Sub End Class End Class ", BasicResult(6, 18, "B14Inner")); } [Fact] public async Task CA1052NoDiagnosticForEmptyStaticClassCSharpAsync() { await VerifyCS.VerifyAnalyzerAsync(@" public static class C15 { } "); } [Fact] public async Task CA1052NoDiagnosticForNonStaticClassWithStaticConstructorCSharpAsync() { await VerifyCS.VerifyAnalyzerAsync(@" public class C16 { static C16() { } } "); } [Fact] public async Task CA1052NoDiagnosticForNonStaticClassWithStaticConstructorBasicAsync() { await VerifyVB.VerifyAnalyzerAsync(@" Public Class B16 Shared Sub New() End Sub End Class "); } [Fact] public async Task CA1052NoDiagnosticForStaticClassWithStaticConstructorCSharpAsync() { await VerifyCS.VerifyAnalyzerAsync(@" public static class C17 { static C17() { } } "); } [Fact] public async Task CA1052NoDiagnosticForNonStaticClassWithStaticConstructorAndInstanceConstructorCSharpAsync() { await VerifyCS.VerifyAnalyzerAsync(@" public class C18 { public C18() { } static C18() { } } "); } [Fact] public async Task CA1052NoDiagnosticForNonStaticClassWithStaticConstructorAndInstanceConstructorBasicAsync() { await VerifyVB.VerifyAnalyzerAsync(@" Public Class B18 Sub New() End Sub Shared Sub New() End Sub End Class "); } [Fact] public async Task CA1052DiagnosticForNestedPublicClassInOtherwiseEmptyNonStaticClassCSharpAsync() { await VerifyCS.VerifyAnalyzerAsync(@" public class C19 { public class C19Inner { } } ", CSharpResult(2, 14, "C19")); } [Fact] public async Task CA1052DiagnosticForNestedPublicClassInOtherwiseEmptyNonStaticClassBasicAsync() { await VerifyVB.VerifyAnalyzerAsync(@" Public Class B19 Public Class B19Inner End Class End Class ", BasicResult(2, 14, "B19")); } [Fact] public async Task CA1052NoDiagnosticAnEnumCSharpAsync() { await VerifyCS.VerifyAnalyzerAsync(@" public enum E20 { Unknown = 0 } "); } [Fact] public async Task CA1052NoDiagnosticAnEnumBasicAsync() { await VerifyVB.VerifyAnalyzerAsync(@" Public Enum EB20 Unknown = 0 End Enum "); } [Fact] public async Task CA1052NoDiagnosticOnClassWithOnlyDefaultConstructorCSharpAsync() { await VerifyCS.VerifyAnalyzerAsync(@" public class C21 { public C21() { } } "); } [Fact] public async Task CA1052NoDiagnosticOnClassWithOnlyDefaultConstructorBasicAsync() { await VerifyVB.VerifyAnalyzerAsync(@" Public Class B21 Public Sub New() End Sub End Class "); } [Fact] public async Task CA1052NoDiagnosticForNestedPrivateNonStaticClassWithPublicDefaultConstructorAndStaticMethodCSharpAsync() { await VerifyCS.VerifyAnalyzerAsync(@" public class C22 { public void Moo() { } private class C22Inner { public C22Inner() { } public static void DoSomething() { } } } "); } [Fact] public async Task CA1052NoDiagnosticForNestedPrivateNonStaticClassWithPublicDefaultConstructorAndSharedMethodBasicAsync() { await VerifyVB.VerifyAnalyzerAsync(@" Public Class B22 Public Sub Moo() End Sub Private Class B22Inner Public Sub New() End Sub Public Shared Sub DoSomething() End Sub End Class End Class "); } [Fact] public async Task CA1052NoDiagnosticForNonStaticClassWithOnlyStaticDeclaredMembersAndBaseClassCSharpAsync() { await VerifyCS.VerifyAnalyzerAsync(@" public class C23Base { } public class C23 : C23Base { public static void DoSomething() { } } "); } [Fact] public async Task CA1052NoDiagnosticForNonStaticClassWithOnlyStaticDeclaredMembersAndBaseClassBasicAsync() { await VerifyVB.VerifyAnalyzerAsync(@" Public Class B23Base End Class Public Class B23 Inherits B23Base Public Shared Sub DoSomething() End Sub End Class "); } [Fact] public async Task CA1052NoDiagnosticForNonStaticClassWithOnlyStaticDeclaredMembersAndEmptyBaseInterfaceCSharpAsync() { await VerifyCS.VerifyAnalyzerAsync(@" public interface IC24Base { } public class C24 : IC24Base { public static void DoSomething() { } } "); } [Fact] public async Task CA1052NoDiagnosticForNonStaticClassWithOnlyStaticDeclaredMembersAndEmptyBaseInterfaceBasicAsync() { await VerifyVB.VerifyAnalyzerAsync(@" Public Interface IB24Base End Interface Public Class B24 Implements IB24Base Public Shared Sub DoSomething() End Sub End Class "); } [Fact] public async Task CA1052NoDiagnosticForNonStaticClassWithOnlyStaticDeclaredMembersAndNotEmptyBaseInterfaceCSharpAsync() { await VerifyCS.VerifyAnalyzerAsync(@" public interface IC25Base { void Moo(); } public class C25 : IC25Base { public static void DoSomething() { } void IC25Base.Moo() { } } "); } [Fact] public async Task CA1052NoDiagnosticForNonStaticClassWithOnlyStaticDeclaredMembersAndNotEmptyBaseInterfaceBasicAsync() { await VerifyVB.VerifyAnalyzerAsync(@" Public Interface IB25Base Sub Moo() End Interface Public Class B25 Implements IB25Base Public Shared Sub DoSomething() End Sub Private Sub B25Base_Moo() Implements IB25Base.Moo End Sub End Class "); } [Fact] public async Task CA1052NoDiagnosticForNonStaticClassWithOnlyStaticDeclaredMembersAndIncompleteBaseClassDefinitionCSharpAsync() { await VerifyCS.VerifyAnalyzerAsync(@" public class C26 :{|CS1031:|} { public static void DoSomething() { } } "); } [Fact] public async Task CA1052NoDiagnosticForNonStaticClassWithOnlyStaticDeclaredMembersAndIncompleteBaseClassDefinitionBasicAsync() { await VerifyVB.VerifyAnalyzerAsync(@" Public Class B26 Inherits{|BC30182:|} Public Shared Sub DoSomething() End Sub End Class "); } [Fact] public async Task CA1052NoDiagnosticForEmptyNonStaticClassWithIncompleteBaseClassDefinitionCSharpAsync() { await VerifyCS.VerifyAnalyzerAsync(@" public class C27 :{|CS1031:|} { } "); } [Fact] public async Task CA1052NoDiagnosticForEmptyNonStaticClassWithIncompleteBaseClassDefinitionBasicAsync() { await VerifyVB.VerifyAnalyzerAsync(@" Public Class B27 Inherits{|BC30182:|} End Class "); } [Fact] public async Task CA1052NoDiagnosticForNonStaticClassWithOnlyPrivateAndProtectedStaticMethodsCSharpAsync() { await VerifyCS.VerifyAnalyzerAsync(@" public class C28 { private static void SomeMethod() {} protected static void SomeOtherMethod() {} } "); } [Fact] public async Task CA1052NoDiagnosticForNonStaticClassWithOnlyPrivateAndProtectedStaticMethodsBasicAsync() { await VerifyVB.VerifyAnalyzerAsync(@" Public Class B28 Private Shared Sub SomeMethod() End Sub Protected Shared Sub SomeOtherMethod() End Sub End Class "); } [Fact] public async Task CA1052NoDiagnosticForNonStaticClassWithOnlyExplicitConversionOperatorsCSharpAsync() { await VerifyCS.VerifyAnalyzerAsync(@" public class C29 { public static explicit operator C29(int p) => new C29(); } "); } [Fact] public async Task CA1052NoDiagnosticForNonStaticClassWithOnlyImplicitConversionOperatorsCSharpAsync() { await VerifyCS.VerifyAnalyzerAsync(@" public class C29 { public static implicit operator C29(int p) => new C29(); } "); } [Fact] public async Task CA1052NoDiagnosticForNonStaticClassWithOnlyExplicitConversionOperatorsBasicAsync() { await VerifyVB.VerifyAnalyzerAsync(@" Public Class B29 Public Shared Widening Operator CType(ByVal p As Integer) As B29 Return New B29() End Operator End Class "); } [Fact] public async Task CA1052NoDiagnosticForAbstractNonStaticClassCSharpAsync() { await VerifyCS.VerifyAnalyzerAsync(@" public abstract class C1 { internal class C2 : C1 { } } "); } [Fact] public async Task CA1052NoDiagnosticRecordsAsync() { await new VerifyCS.Test { LanguageVersion = Microsoft.CodeAnalysis.CSharp.LanguageVersion.CSharp9, TestCode = @" public record C { public static void M() { } } " }.RunAsync(); } } }
// 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: An array implementation of a generic stack. ** ** =============================================================================*/ using System.Diagnostics; using System.Diagnostics.CodeAnalysis; namespace System.Collections.Generic { // A simple stack of objects. Internally it is implemented as an array, // so Push can be O(n). Pop is O(1). [DebuggerTypeProxy(typeof(StackDebugView<>))] [DebuggerDisplay("Count = {Count}")] public class Stack<T> : IEnumerable<T>, System.Collections.ICollection, IReadOnlyCollection<T> { private T[] _array; // Storage for stack elements private int _size; // Number of items in the stack. private int _version; // Used to keep enumerator in sync w/ collection. private object _syncRoot; private const int DefaultCapacity = 4; /// <include file='doc\Stack.uex' path='docs/doc[@for="Stack.Stack"]/*' /> public Stack() { _array = Array.Empty<T>(); } // Create a stack with a specific initial capacity. The initial capacity // must be a non-negative number. /// <include file='doc\Stack.uex' path='docs/doc[@for="Stack.Stack1"]/*' /> public Stack(int capacity) { if (capacity < 0) throw new ArgumentOutOfRangeException(nameof(capacity), capacity, SR.ArgumentOutOfRange_NeedNonNegNum); _array = new T[capacity]; } // Fills a Stack with the contents of a particular collection. The items are // pushed onto the stack in the same order they are read by the enumerator. // /// <include file='doc\Stack.uex' path='docs/doc[@for="Stack.Stack2"]/*' /> public Stack(IEnumerable<T> collection) { if (collection == null) throw new ArgumentNullException(nameof(collection)); _array = EnumerableHelpers.ToArray(collection, out _size); } /// <include file='doc\Stack.uex' path='docs/doc[@for="Stack.Count"]/*' /> public int Count { get { return _size; } } /// <include file='doc\Stack.uex' path='docs/doc[@for="Stack.IsSynchronized"]/*' /> bool ICollection.IsSynchronized { get { return false; } } /// <include file='doc\Stack.uex' path='docs/doc[@for="Stack.SyncRoot"]/*' /> object ICollection.SyncRoot { get { if (_syncRoot == null) { Threading.Interlocked.CompareExchange<object>(ref _syncRoot, new object(), null); } return _syncRoot; } } // Removes all Objects from the Stack. /// <include file='doc\Stack.uex' path='docs/doc[@for="Stack.Clear"]/*' /> public void Clear() { Array.Clear(_array, 0, _size); // Don't need to doc this but we clear the elements so that the gc can reclaim the references. _size = 0; _version++; } /// <include file='doc\Stack.uex' path='docs/doc[@for="Stack.Contains"]/*' /> public bool Contains(T item) { int count = _size; EqualityComparer<T> c = EqualityComparer<T>.Default; while (count-- > 0) { if (c.Equals(_array[count], item)) { return true; } } return false; } // Copies the stack into an array. /// <include file='doc\Stack.uex' path='docs/doc[@for="Stack.CopyTo"]/*' /> public void CopyTo(T[] array, int arrayIndex) { if (array == null) { throw new ArgumentNullException(nameof(array)); } if (arrayIndex < 0 || arrayIndex > array.Length) { throw new ArgumentOutOfRangeException(nameof(arrayIndex), arrayIndex, SR.ArgumentOutOfRange_Index); } if (array.Length - arrayIndex < _size) { throw new ArgumentException(SR.Argument_InvalidOffLen); } Debug.Assert(array != _array); int srcIndex = 0; int dstIndex = arrayIndex + _size; for (int i = 0; i < _size; i++) array[--dstIndex] = _array[srcIndex++]; } void ICollection.CopyTo(Array array, int arrayIndex) { if (array == null) { throw new ArgumentNullException(nameof(array)); } if (array.Rank != 1) { throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array)); } if (array.GetLowerBound(0) != 0) { throw new ArgumentException(SR.Arg_NonZeroLowerBound, nameof(array)); } if (arrayIndex < 0 || arrayIndex > array.Length) { throw new ArgumentOutOfRangeException(nameof(arrayIndex), arrayIndex, SR.ArgumentOutOfRange_Index); } if (array.Length - arrayIndex < _size) { throw new ArgumentException(SR.Argument_InvalidOffLen); } try { Array.Copy(_array, 0, array, arrayIndex, _size); Array.Reverse(array, arrayIndex, _size); } catch (ArrayTypeMismatchException) { throw new ArgumentException(SR.Argument_InvalidArrayType, nameof(array)); } } // Returns an IEnumerator for this Stack. /// <include file='doc\Stack.uex' path='docs/doc[@for="Stack.GetEnumerator"]/*' /> public Enumerator GetEnumerator() { return new Enumerator(this); } /// <include file='doc\Stack.uex' path='docs/doc[@for="Stack.IEnumerable.GetEnumerator"]/*' /> /// <internalonly/> IEnumerator<T> IEnumerable<T>.GetEnumerator() { return new Enumerator(this); } IEnumerator IEnumerable.GetEnumerator() { return new Enumerator(this); } public void TrimExcess() { int threshold = (int)(((double)_array.Length) * 0.9); if (_size < threshold) { Array.Resize(ref _array, _size); _version++; } } // Returns the top object on the stack without removing it. If the stack // is empty, Peek throws an InvalidOperationException. /// <include file='doc\Stack.uex' path='docs/doc[@for="Stack.Peek"]/*' /> public T Peek() { if (_size == 0) throw new InvalidOperationException(SR.InvalidOperation_EmptyStack); return _array[_size - 1]; } // Pops an item from the top of the stack. If the stack is empty, Pop // throws an InvalidOperationException. /// <include file='doc\Stack.uex' path='docs/doc[@for="Stack.Pop"]/*' /> public T Pop() { if (_size == 0) throw new InvalidOperationException(SR.InvalidOperation_EmptyStack); _version++; T item = _array[--_size]; _array[_size] = default(T); // Free memory quicker. return item; } // Pushes an item to the top of the stack. // /// <include file='doc\Stack.uex' path='docs/doc[@for="Stack.Push"]/*' /> public void Push(T item) { if (_size == _array.Length) { Array.Resize(ref _array, (_array.Length == 0) ? DefaultCapacity : 2 * _array.Length); } _array[_size++] = item; _version++; } // Copies the Stack to an array, in the same order Pop would return the items. public T[] ToArray() { if (_size == 0) return Array.Empty<T>(); T[] objArray = new T[_size]; int i = 0; while (i < _size) { objArray[i] = _array[_size - i - 1]; i++; } return objArray; } /// <include file='doc\Stack.uex' path='docs/doc[@for="StackEnumerator"]/*' /> [SuppressMessage("Microsoft.Performance", "CA1815:OverrideEqualsAndOperatorEqualsOnValueTypes", Justification = "not an expected scenario")] public struct Enumerator : IEnumerator<T>, System.Collections.IEnumerator { private readonly Stack<T> _stack; private readonly int _version; private int _index; private T _currentElement; internal Enumerator(Stack<T> stack) { _stack = stack; _version = stack._version; _index = -2; _currentElement = default(T); } /// <include file='doc\Stack.uex' path='docs/doc[@for="StackEnumerator.Dispose"]/*' /> public void Dispose() { _index = -1; } /// <include file='doc\Stack.uex' path='docs/doc[@for="StackEnumerator.MoveNext"]/*' /> public bool MoveNext() { bool retval; if (_version != _stack._version) throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion); if (_index == -2) { // First call to enumerator. _index = _stack._size - 1; retval = (_index >= 0); if (retval) _currentElement = _stack._array[_index]; return retval; } if (_index == -1) { // End of enumeration. return false; } retval = (--_index >= 0); if (retval) _currentElement = _stack._array[_index]; else _currentElement = default(T); return retval; } /// <include file='doc\Stack.uex' path='docs/doc[@for="StackEnumerator.Current"]/*' /> public T Current { get { if (_index < 0) ThrowEnumerationNotStartedOrEnded(); return _currentElement; } } private void ThrowEnumerationNotStartedOrEnded() { Debug.Assert(_index == -1 || _index == -2); throw new InvalidOperationException(_index == -2 ? SR.InvalidOperation_EnumNotStarted : SR.InvalidOperation_EnumEnded); } object System.Collections.IEnumerator.Current { get { return Current; } } void IEnumerator.Reset() { if (_version != _stack._version) throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion); _index = -2; _currentElement = default(T); } } } }
using System; using System.Collections.Generic; using System.IO; using System.Text; /* * An instance of SSLTestResult contains the data obtained from a * test connection. */ class SSLTestResult { /* * Protocol version selected by the server (in the ServerHello). */ internal int Version { get { return version; } } /* * Protocol version used by the server for record headers. */ internal int RecordVersion { get { return recordVersion; } } /* * Server time, from the server random. * (Expressed in milliseconds since Jan 1st, 1970, 00:00:00 UTC, * skipping leap seconds.) */ internal long TimeMillis { get { return timeMillis; } } /* * Session ID sent by the server. */ internal byte[] SessionID { get { return sessionID; } } /* * Cipher suite selected by the server. */ internal int SelectedCipherSuite { get { return selectedCipherSuite; } } /* * This flag is set to true if the cipher suite selected by * the server was among the suites sent by the client. Some * flawed servers try to use cipher suites not advertised by * the client. */ internal bool CipherSuiteInClientList { get { return cipherSuiteInClientList; } set { cipherSuiteInClientList = value; } } /* * True if the server selected deflate compression. */ internal bool DeflateCompress { get { return deflateCompress; } } /* * Secure renegotiation information sent by the server (null if * no such extension was sent). */ internal byte[] RenegotiationInfo { get { return renegInfo; } } /* * True if the server sends the Encrypt-then-MAC extension * (RFC 7366). */ internal bool DoesEtM { get { return doesEtM; } } /* * Set to true if the server sent a ServerKeyExchange that we * could not understand. */ internal bool UnknownSKE { get { return unknownSKE; } } /* * True if the server sent a ServerHello but then failed to * complete the handshake (some flawed servers do that, usually * because of a misconfiguration that pretends that a particular * cipher suite is supported, but some needed piece is missing * on the server). */ internal bool FailedAfterHello { get { return failedAfterHello; } } /* * The server certificate. May be null if the server sent an * empty chain, or for cipher suites which do not use * certificates. */ internal byte[] Certificate { get { return certificate; } } /* * Get certificate chain in the order returned by the server * (nominally reverse order). This is null if the server did * not send any Certificate message. */ internal byte[][] CertificateChain { get { return certificateChain; } } /* * Get the size used for a classic DHE key exchange (also applies to * DH_anon and SRP). If there was no such key exchange, then 0 * is returned. */ internal int DHSize { get { return dhSize; } } /* * Get the size used for an ECDHE key exchange (also applies to * ECDH_anon). If there was no such key exchange, then 0 is * returned. */ internal int ECSize { get { return ecSize; } } /* * Get the SHA-1 hash of the key exchange parameters sent by the * server (DHE or ECDHE, excluding any signature by the server; * also applies to DH_anon and ECDH_anon). The hash value is * converted to lowercase hexadecimal. This is null if the * server did not send such parameters. */ internal string KXHash { get { return kxHash; } } /* * Get the curve used for an ECDHE key exchange (also applies to * ECDH_anon). This is set only if a named curved was used, and * the curve was recognized; otherwise, this property returns * null. */ internal SSLCurve Curve { get { return curve; } } /* * Set to true if the server sent an "explicit prime" curve. */ internal bool CurveExplicitPrime { get { return curveExplicitPrime; } } /* * Set to true if the server sent an "explicit char2" curve. */ internal bool CurveExplicitChar2 { get { return curveExplicitChar2; } } int version; int recordVersion; long timeMillis; byte[] sessionID; int selectedCipherSuite; bool cipherSuiteInClientList; bool deflateCompress; byte[] renegInfo; bool doesEtM; bool unknownSKE; bool failedAfterHello; byte[] certificate; byte[][] certificateChain; int dhSize; int ecSize; string kxHash; bool curveExplicitPrime; bool curveExplicitChar2; SSLCurve curve; /* * A new empty instance. */ internal SSLTestResult() { } /* * Parse messages from the server: from ServerHello to * ServerHelloDone. */ internal void Parse(SSLRecord rec) { rec.SetExpectedType(M.HANDSHAKE); /* * First parse a ServerHello. */ HMParser sh = new HMParser(rec); if (sh.MessageType != M.SERVER_HELLO) { throw new Exception("Not a ServerHello"); } version = sh.Read2(); byte[] serverRandom = sh.ReadBlobFixed(32); timeMillis = 1000 * (long)M.Dec32be(serverRandom, 0); sessionID = sh.ReadBlobVar(1); if (sessionID.Length > 32) { throw new Exception("Oversized session ID"); } selectedCipherSuite = sh.Read2(); int cm = sh.Read1(); if (cm == 0) { deflateCompress = false; } else if (cm == 1) { deflateCompress = true; } else { throw new Exception( "Unknown compression method: " + cm); } if (!sh.EndOfStruct) { sh.OpenVar(2); Dictionary<int, bool> d = new Dictionary<int, bool>(); while (!sh.EndOfStruct) { int extType = sh.Read2(); if (d.ContainsKey(extType)) { throw new Exception( "Duplicate extension: " + extType); } d[extType] = true; sh.OpenVar(2); switch (extType) { case M.EXT_SERVER_NAME: ParseEmptyServerName(sh); break; case M.EXT_RENEGOTIATION_INFO: ParseRenegInfo(sh); break; case M.EXT_ENCRYPT_THEN_MAC: ParseEtM(sh); break; case M.EXT_SUPPORTED_CURVES: ParseSupportedCurves(sh); break; case M.EXT_SUPPORTED_EC_POINTS: ParseSupportedECPoints(sh); break; default: throw new Exception( "Unknown extension: " + extType); } sh.Close(); } sh.Close(); } sh.Close(); /* * Read other messages, up to the ServerHelloDone. */ try { bool seenSHD = false; while (!seenSHD) { HMParser hm = new HMParser(rec); switch (hm.MessageType) { case M.CERTIFICATE: ParseCertificate(hm); break; case M.SERVER_KEY_EXCHANGE: ParseServerKeyExchange(hm); break; case M.CERTIFICATE_REQUEST: ParseCertificateRequest(hm); break; case M.SERVER_HELLO_DONE: hm.Close(); seenSHD = true; break; default: hm.Close(true); break; } } } catch { failedAfterHello = true; } recordVersion = rec.GetInVersion(); } void ParseEmptyServerName(HMParser sh) { /* * The SNI extension from the server is supposed to have * empty contents. */ } void ParseRenegInfo(HMParser sh) { renegInfo = sh.ReadBlobVar(1); } void ParseEtM(HMParser sh) { /* * The Encrypt-then-MAC extension is supposed to be empty. */ doesEtM = true; } void ParseSupportedCurves(HMParser sh) { /* * TODO: see if we should parse this information. The * server sends that extension after seeing the client's * ClientHello, so it may "lie" about its actual abilities. */ sh.SkipRemainder(); } void ParseSupportedECPoints(HMParser sh) { /* * TODO: see if we should parse this information. The * server sends that extension after seeing the client's * ClientHello, so it may "lie" about its actual abilities. */ sh.SkipRemainder(); } void ParseCertificate(HMParser hm) { if (certificateChain != null) { throw new Exception("Duplicate Certificate message"); } List<byte[]> chain = new List<byte[]>(); hm.OpenVar(3); while (!hm.EndOfStruct) { chain.Add(hm.ReadBlobVar(3)); } hm.Close(); hm.Close(); certificateChain = chain.ToArray(); certificate = (chain.Count > 0) ? chain[0] : null; } void ParseServerKeyExchange(HMParser hm) { try { ParseServerKeyExchangeInner(hm); } catch (Exception e) { throw e; } } void ParseServerKeyExchangeInner(HMParser hm) { CipherSuite cs; if (!CipherSuite.ALL.TryGetValue(selectedCipherSuite, out cs)) { unknownSKE = true; hm.Close(true); return; } if (cs.IsDHE) { /* * If this is DHE_PSK, then there is first a * "key hint" to skip. */ if (cs.IsPSK) { hm.ReadBlobVar(2); } /* * DH parameters: p, g, y. We are only interested * in p. */ byte[] p = hm.ReadBlobVar(2); dhSize = M.BitLength(p); byte[] g = hm.ReadBlobVar(2); byte[] y = hm.ReadBlobVar(2); if (cs.ServerKeyType != "none") { if (version >= M.TLSv12) { /* * Hash-and-sign identifiers. */ hm.Read2(); } hm.ReadBlobVar(2); } kxHash = M.DoSHA1Values(0, p, g, y); } else if (cs.IsECDHE) { /* * If this is ECDHE_PSK, then there is first a * "key hint" to skip. */ if (cs.IsPSK) { hm.ReadBlobVar(2); } /* * Curve elements. */ int id = 0; byte[] p = null; byte[] bf1 = null; byte[] bf2 = null; byte[] bf3 = null; byte[] a = null; byte[] b = null; byte[] G = null; byte[] order = null; byte[] cofactor = null; /* * Read curve type: one byte. */ int ptype = hm.Read1(); switch (ptype) { case 1: /* * explicit_prime: p, a, b, G, * order, cofactor. */ p = hm.ReadBlobVar(1); a = hm.ReadBlobVar(1); b = hm.ReadBlobVar(1); G = hm.ReadBlobVar(1); order = hm.ReadBlobVar(1); ecSize = M.AdjustedBitLength(order); cofactor = hm.ReadBlobVar(1); curveExplicitPrime = true; break; case 2: /* explicit_char2 */ hm.Read2(); switch (hm.Read1()) { case 1: /* trinomial */ bf1 = hm.ReadBlobVar(1); break; case 2: /* pentanomial */ bf1 = hm.ReadBlobVar(1); bf2 = hm.ReadBlobVar(1); bf3 = hm.ReadBlobVar(1); break; default: hm.Close(true); unknownSKE = true; return; } a = hm.ReadBlobVar(1); b = hm.ReadBlobVar(1); G = hm.ReadBlobVar(1); order = hm.ReadBlobVar(1); ecSize = M.AdjustedBitLength(order); cofactor = hm.ReadBlobVar(1); curveExplicitChar2 = true; break; case 3: /* * named_curve. */ id = hm.Read2(); if (SSLCurve.ALL.TryGetValue(id, out curve)) { ecSize = curve.Size; } else { curve = null; hm.Close(true); unknownSKE = true; return; } break; default: hm.Close(true); unknownSKE = true; return; } /* * Read public key: one curve point. */ byte[] Q = hm.ReadBlobVar(1); if (cs.ServerKeyType != "none") { if (version >= M.TLSv12) { /* * Hash-and-sign identifiers. */ hm.Read2(); } hm.ReadBlobVar(2); } kxHash = M.DoSHA1Values(1, ptype, id, p, bf1, bf2, bf3, a, b, G, order, cofactor, Q); } else if (cs.IsRSAExport) { /* * If cipher suite uses RSA key exchange and is * flagged "export" then it may send an ephemeral * RSA key pair, which will be weak and probably * not very ephemeral, since RSA key pair generation * is kinda expensive. * * Format: modulus, public exponent, signature. */ byte[] modulus = hm.ReadBlobVar(2); byte[] exponent = hm.ReadBlobVar(2); if (version >= M.TLSv12) { /* * Hash-and-sign identifiers. */ hm.Read2(); } hm.ReadBlobVar(2); kxHash = M.DoSHA1Values(2, modulus, exponent); } else if (cs.IsSRP) { /* * SRP parameters are: N, g, s, B. N is the * modulus. */ byte[] N = hm.ReadBlobVar(2); dhSize = M.BitLength(N); byte[] g = hm.ReadBlobVar(2); byte[] s = hm.ReadBlobVar(1); byte[] B = hm.ReadBlobVar(2); kxHash = M.DoSHA1Values(3, N, g, s, B); /* * RFC 5054 says that there is a signature, * except if the server sent no certificate. What * happens at the encoding level is unclear, so * we skip the remaining bytes. */ hm.SkipRemainder(); } else if (cs.IsPSK) { /* * Key hint from the server. */ hm.ReadBlobVar(2); } else { throw new IOException("Unexpected ServerKeyExchange"); } hm.Close(); } void ParseCertificateRequest(HMParser hm) { // TODO: extract CA names. hm.Close(true); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*============================================================================= ** ** ** ** ** Purpose: An array implementation of a stack. ** ** =============================================================================*/ namespace System.Collections { using System; using System.Security.Permissions; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; // A simple stack of objects. Internally it is implemented as an array, // so Push can be O(n). Pop is O(1). [DebuggerTypeProxy(typeof(System.Collections.Stack.StackDebugView))] [DebuggerDisplay("Count = {Count}")] [System.Runtime.InteropServices.ComVisible(true)] [Serializable] public class Stack : ICollection, ICloneable { private Object[] _array; // Storage for stack elements [ContractPublicPropertyName("Count")] private int _size; // Number of items in the stack. private int _version; // Used to keep enumerator in sync w/ collection. [NonSerialized] private Object _syncRoot; private const int _defaultCapacity = 10; public Stack() { _array = new Object[_defaultCapacity]; _size = 0; _version = 0; } // Create a stack with a specific initial capacity. The initial capacity // must be a non-negative number. public Stack(int initialCapacity) { if (initialCapacity < 0) throw new ArgumentOutOfRangeException(nameof(initialCapacity), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); Contract.EndContractBlock(); if (initialCapacity < _defaultCapacity) initialCapacity = _defaultCapacity; // Simplify doubling logic in Push. _array = new Object[initialCapacity]; _size = 0; _version = 0; } // Fills a Stack with the contents of a particular collection. The items are // pushed onto the stack in the same order they are read by the enumerator. // public Stack(ICollection col) : this((col==null ? 32 : col.Count)) { if (col==null) throw new ArgumentNullException(nameof(col)); Contract.EndContractBlock(); IEnumerator en = col.GetEnumerator(); while(en.MoveNext()) Push(en.Current); } public virtual int Count { get { Contract.Ensures(Contract.Result<int>() >= 0); return _size; } } public virtual bool IsSynchronized { get { return false; } } public virtual Object SyncRoot { get { if( _syncRoot == null) { System.Threading.Interlocked.CompareExchange<Object>(ref _syncRoot, new Object(), null); } return _syncRoot; } } // Removes all Objects from the Stack. public virtual void Clear() { Array.Clear(_array, 0, _size); // Don't need to doc this but we clear the elements so that the gc can reclaim the references. _size = 0; _version++; } public virtual Object Clone() { Contract.Ensures(Contract.Result<Object>() != null); Stack s = new Stack(_size); s._size = _size; Array.Copy(_array, 0, s._array, 0, _size); s._version = _version; return s; } public virtual bool Contains(Object obj) { int count = _size; while (count-- > 0) { if (obj == null) { if (_array[count] == null) return true; } else if (_array[count] != null && _array[count].Equals(obj)) { return true; } } return false; } // Copies the stack into an array. public virtual void CopyTo(Array array, int index) { if (array==null) throw new ArgumentNullException(nameof(array)); if (array.Rank != 1) throw new ArgumentException(Environment.GetResourceString("Arg_RankMultiDimNotSupported")); if (index < 0) throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (array.Length - index < _size) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen")); Contract.EndContractBlock(); int i = 0; if (array is Object[]) { Object[] objArray = (Object[]) array; while(i < _size) { objArray[i+index] = _array[_size-i-1]; i++; } } else { while(i < _size) { array.SetValue(_array[_size-i-1], i+index); i++; } } } // Returns an IEnumerator for this Stack. public virtual IEnumerator GetEnumerator() { Contract.Ensures(Contract.Result<IEnumerator>() != null); return new StackEnumerator(this); } // Returns the top object on the stack without removing it. If the stack // is empty, Peek throws an InvalidOperationException. public virtual Object Peek() { if (_size==0) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EmptyStack")); Contract.EndContractBlock(); return _array[_size-1]; } // Pops an item from the top of the stack. If the stack is empty, Pop // throws an InvalidOperationException. public virtual Object Pop() { if (_size == 0) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EmptyStack")); //Contract.Ensures(Count == Contract.OldValue(Count) - 1); Contract.EndContractBlock(); _version++; Object obj = _array[--_size]; _array[_size] = null; // Free memory quicker. return obj; } // Pushes an item to the top of the stack. // public virtual void Push(Object obj) { //Contract.Ensures(Count == Contract.OldValue(Count) + 1); if (_size == _array.Length) { Object[] newArray = new Object[2*_array.Length]; Array.Copy(_array, 0, newArray, 0, _size); _array = newArray; } _array[_size++] = obj; _version++; } // Returns a synchronized Stack. // [HostProtection(Synchronization=true)] public static Stack Synchronized(Stack stack) { if (stack==null) throw new ArgumentNullException(nameof(stack)); Contract.Ensures(Contract.Result<Stack>() != null); Contract.EndContractBlock(); return new SyncStack(stack); } // Copies the Stack to an array, in the same order Pop would return the items. public virtual Object[] ToArray() { Contract.Ensures(Contract.Result<Object[]>() != null); Object[] objArray = new Object[_size]; int i = 0; while(i < _size) { objArray[i] = _array[_size-i-1]; i++; } return objArray; } [Serializable] private class SyncStack : Stack { private Stack _s; private Object _root; internal SyncStack(Stack stack) { _s = stack; _root = stack.SyncRoot; } public override bool IsSynchronized { get { return true; } } public override Object SyncRoot { get { return _root; } } public override int Count { get { lock (_root) { return _s.Count; } } } public override bool Contains(Object obj) { lock (_root) { return _s.Contains(obj); } } public override Object Clone() { lock (_root) { return new SyncStack((Stack)_s.Clone()); } } public override void Clear() { lock (_root) { _s.Clear(); } } public override void CopyTo(Array array, int arrayIndex) { lock (_root) { _s.CopyTo(array, arrayIndex); } } public override void Push(Object value) { lock (_root) { _s.Push(value); } } [SuppressMessage("Microsoft.Contracts", "CC1055")] // Thread safety problems with precondition - can't express the precondition as of Dev10. public override Object Pop() { lock (_root) { return _s.Pop(); } } public override IEnumerator GetEnumerator() { lock (_root) { return _s.GetEnumerator(); } } [SuppressMessage("Microsoft.Contracts", "CC1055")] // Thread safety problems with precondition - can't express the precondition as of Dev10. public override Object Peek() { lock (_root) { return _s.Peek(); } } public override Object[] ToArray() { lock (_root) { return _s.ToArray(); } } } [Serializable] private class StackEnumerator : IEnumerator, ICloneable { private Stack _stack; private int _index; private int _version; private Object currentElement; internal StackEnumerator(Stack stack) { _stack = stack; _version = _stack._version; _index = -2; currentElement = null; } public Object Clone() { return MemberwiseClone(); } public virtual bool MoveNext() { bool retval; if (_version != _stack._version) throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumFailedVersion)); if (_index == -2) { // First call to enumerator. _index = _stack._size-1; retval = ( _index >= 0); if (retval) currentElement = _stack._array[_index]; return retval; } if (_index == -1) { // End of enumeration. return false; } retval = (--_index >= 0); if (retval) currentElement = _stack._array[_index]; else currentElement = null; return retval; } public virtual Object Current { get { if (_index == -2) throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumNotStarted)); if (_index == -1) throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumEnded)); return currentElement; } } public virtual void Reset() { if (_version != _stack._version) throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumFailedVersion)); _index = -2; currentElement = null; } } internal class StackDebugView { private Stack stack; public StackDebugView( Stack stack) { if( stack == null) throw new ArgumentNullException(nameof(stack)); Contract.EndContractBlock(); this.stack = stack; } [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] public Object[] Items { get { return stack.ToArray(); } } } } }
// *********************************************************************** // Copyright (c) 2011 Charlie Poole, Rob Prouse // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** #if !NETSTANDARD1_3 && !NETCOREAPP1_0 using System; using System.IO; using System.Text; using System.Xml; using NUnit.Framework; using NUnit.Framework.Interfaces; using NUnit.Tests.Assemblies; namespace NUnitLite.Tests { public class NUnit2XmlOutputWriterTests { private XmlDocument doc; private XmlNode topNode; private XmlNode envNode; private XmlNode cultureNode; private XmlNode suiteNode; [OneTimeSetUp] public void RunMockAssemblyTests() { ITestResult result = NUnit.TestUtilities.TestBuilder.RunTestFixture(typeof(MockTestFixture)); Assert.NotNull(result); StringBuilder sb = new StringBuilder(); StringWriter writer = new StringWriter(sb); new NUnit2XmlOutputWriter().WriteResultFile(result, writer, null, null); writer.Close(); #if DEBUG StreamWriter sw = new StreamWriter("MockAssemblyResult.xml"); sw.WriteLine(sb.ToString()); sw.Close(); #endif doc = new XmlDocument(); doc.LoadXml(sb.ToString()); topNode = doc.SelectSingleNode("/test-results"); if (topNode != null) { envNode = topNode.SelectSingleNode("environment"); cultureNode = topNode.SelectSingleNode("culture-info"); suiteNode = topNode.SelectSingleNode("test-suite"); } } [Test] public void Document_HasThreeChildren() { Assert.That(doc.ChildNodes.Count, Is.EqualTo(3)); } [Test] public void Document_FirstChildIsXmlDeclaration() { Assume.That(doc.FirstChild != null); Assert.That(doc.FirstChild.NodeType, Is.EqualTo(XmlNodeType.XmlDeclaration)); Assert.That(doc.FirstChild.Name, Is.EqualTo("xml")); } [Test] public void Document_SecondChildIsComment() { Assume.That(doc.ChildNodes.Count >= 2); Assert.That(doc.ChildNodes[1].Name, Is.EqualTo("#comment")); } [Test] public void Document_ThirdChildIsTestResults() { Assume.That(doc.ChildNodes.Count >= 3); Assert.That(doc.ChildNodes[2].Name, Is.EqualTo("test-results")); } [Test] public void Document_HasTestResults() { Assert.That(topNode, Is.Not.Null); Assert.That(topNode.Name, Is.EqualTo("test-results")); } [Test] public void TestResults_AssemblyPathIsCorrect() { Assert.That(RequiredAttribute(topNode, "name"), Is.EqualTo("NUnit.Tests.Assemblies.MockTestFixture")); } [TestCase("total", MockTestFixture.Tests)] [TestCase("errors", MockTestFixture.Failed_Error)] [TestCase("failures", MockTestFixture.Failed_Other)] [TestCase("inconclusive", MockTestFixture.Inconclusive)] [TestCase("not-run", MockTestFixture.Skipped+MockTestFixture.Failed_NotRunnable-MockTestFixture.Skipped_Explicit)] [TestCase("ignored", MockTestFixture.Skipped_Ignored)] [TestCase("skipped", MockTestFixture.Skipped-MockTestFixture.Skipped_Ignored-MockTestFixture.Skipped_Explicit)] [TestCase("invalid", MockTestFixture.Failed_NotRunnable)] public void TestResults_CounterIsCorrect(string name, int count) { Assert.That(RequiredAttribute(topNode, name), Is.EqualTo(count.ToString())); } [Test] public void TestResults_HasValidDateAttribute() { string dateString = RequiredAttribute(topNode, "date"); DateTime date; Assert.That(DateTime.TryParse(dateString, out date), "Invalid date attribute: {0}", dateString); } [Test] public void TestResults_HasValidTimeAttribute() { string timeString = RequiredAttribute(topNode, "time"); DateTime time; Assert.That(DateTime.TryParse(timeString, out time), "Invalid time attribute: {0}", timeString); } [Test] public void Environment_HasEnvironmentElement() { Assert.That(envNode, Is.Not.Null, "Missing environment element"); } [TestCase("nunit-version")] [TestCase("clr-version")] [TestCase("os-version")] [TestCase("platform")] [TestCase("cwd")] [TestCase("machine-name")] [TestCase("user")] [TestCase("user-domain")] public void Environment_HasRequiredAttribute(string name) { RequiredAttribute(envNode, name); } [Test] public void CultureInfo_HasCultureInfoElement() { Assert.That(cultureNode, Is.Not.Null, "Missing culture-info element"); } [TestCase("current-culture")] [TestCase("current-uiculture")] public void CultureInfo_HasRequiredAttribute(string name) { string cultureName = RequiredAttribute(cultureNode, name); System.Globalization.CultureInfo culture = null; try { culture = System.Globalization.CultureInfo.CreateSpecificCulture(cultureName); } catch(ArgumentException) { // Do nothing - culture will be null } Assert.That(culture, Is.Not.Null, "Invalid value for {0}: {1}", name, cultureName); } [Test] public void TestSuite_HasTestSuiteElement() { Assert.That(suiteNode, Is.Not.Null, "Missing test-suite element"); } [TestCase("type", "TestFixture")] [TestCase("name", "MockTestFixture")] [TestCase("description", "Fake Test Fixture")] [TestCase("executed", "True")] [TestCase("result", "Failure")] [TestCase("success", "False")] [TestCase("asserts", "0")] public void TestSuite_ExpectedAttribute(string name, string value) { Assert.That(RequiredAttribute(suiteNode, name), Is.EqualTo(value)); } [Test] public void TestSuite_HasValidTimeAttribute() { double time; var timeString = RequiredAttribute(suiteNode, "time"); // NOTE: We use the TryParse overload with 4 args because it's supported in .NET 1.1 var success = double.TryParse(timeString,System.Globalization.NumberStyles.Float,System.Globalization.NumberFormatInfo.InvariantInfo, out time); Assert.That(success, "{0} is an invalid value for time", timeString); } [Test] public void TestSuite_ResultIsFailure() { } #region Helper Methods private string RequiredAttribute(XmlNode node, string name) { XmlAttribute attr = node.Attributes[name]; Assert.That(attr, Is.Not.Null, "Missing attribute {0} on element {1}", name, node.Name); return attr.Value; } #endregion } } #endif
namespace Ioke.Lang { using System.Collections; using System.Collections.Generic; using Ioke.Lang.Util; public class DefaultSyntax : IokeData, Named, Inspectable, AssociatedCode { string name; IokeObject context; IokeObject code; public DefaultSyntax(string name) : base(IokeData.TYPE_DEFAULT_SYNTAX) { this.name = name; } public DefaultSyntax(IokeObject context, IokeObject code) : this((string)null) { this.context = context; this.code = code; } public override void Init(IokeObject obj) { obj.Kind = "DefaultSyntax"; obj.SetActivatable(true); obj.RegisterMethod(obj.runtime.NewNativeMethod("returns the name of the syntax", new TypeCheckingNativeMethod.WithNoArguments("name", obj, (method, on, args, keywords, _context, message) => { return _context.runtime.NewText(((DefaultSyntax)IokeObject.dataOf(on)).name); }))); obj.RegisterMethod(obj.runtime.NewNativeMethod("activates this syntax with the arguments given to call", new NativeMethod("call", DefaultArgumentsDefinition.builder() .WithRestUnevaluated("arguments") .Arguments, (method, _context, message, on, outer) => { return Interpreter.Activate(IokeObject.As(on, _context), _context, message, _context.RealContext); }))); obj.RegisterMethod(obj.runtime.NewNativeMethod("returns the result of activating this syntax without actually doing the replacement or execution part.", new NativeMethod("expand", DefaultArgumentsDefinition.builder() .WithRestUnevaluated("arguments") .Arguments, (method, _context, message, on, outer) => { object onAsSyntax = _context.runtime.DefaultSyntax.ConvertToThis(on, message, _context); return ((DefaultSyntax)IokeObject.dataOf(onAsSyntax)).Expand(IokeObject.As(onAsSyntax, context), context, message, context.RealContext, null); }))); obj.RegisterMethod(obj.runtime.NewNativeMethod("returns the message chain for this syntax", new TypeCheckingNativeMethod.WithNoArguments("message", obj, (method, on, args, keywords, _context, message) => { return ((AssociatedCode)IokeObject.dataOf(on)).Code; }))); obj.RegisterMethod(obj.runtime.NewNativeMethod("returns the code for the argument definition", new TypeCheckingNativeMethod.WithNoArguments("argumentsCode", obj, (method, on, args, keywords, _context, message) => { return _context.runtime.NewText(((AssociatedCode)IokeObject.dataOf(on)).ArgumentsCode); }))); obj.RegisterMethod(obj.runtime.NewNativeMethod("Returns a text inspection of the object", new TypeCheckingNativeMethod.WithNoArguments("inspect", obj, (method, on, args, keywords, _context, message) => { return _context.runtime.NewText(DefaultSyntax.GetInspect(on)); }))); obj.RegisterMethod(obj.runtime.NewNativeMethod("Returns a brief text inspection of the object", new TypeCheckingNativeMethod.WithNoArguments("notice", obj, (method, on, args, keywords, _context, message) => { return _context.runtime.NewText(DefaultSyntax.GetNotice(on)); }))); obj.RegisterMethod(obj.runtime.NewNativeMethod("returns the full code of this syntax, as a Text", new TypeCheckingNativeMethod.WithNoArguments("code", obj, (method, on, args, keywords, _context, message) => { IokeData data = IokeObject.dataOf(on); if(data is DefaultSyntax) { return _context.runtime.NewText(((DefaultSyntax)data).CodeString); } else { return _context.runtime.NewText(((AliasMethod)data).CodeString); } }))); obj.RegisterMethod(obj.runtime.NewNativeMethod("returns idiomatically formatted code for this syntax", new TypeCheckingNativeMethod.WithNoArguments("formattedCode", obj, (method, on, args, keywords, _context, message) => { return _context.runtime.NewText(((AssociatedCode)IokeObject.dataOf(on)).FormattedCode(method)); }))); } public string Name { get { return this.name; } set { this.name = value; } } public static string GetInspect(object on) { return ((Inspectable)(IokeObject.dataOf(on))).Inspect(on); } public static string GetNotice(object on) { return ((Inspectable)(IokeObject.dataOf(on))).Notice(on); } public string Inspect(object self) { if(name == null) { return "syntax(" + Message.Code(code) + ")"; } else { return name + ":syntax(" + Message.Code(code) + ")"; } } public string Notice(object self) { if(name == null) { return "syntax(...)"; } else { return name + ":syntax(...)"; } } public string ArgumentsCode { get { return "..."; } } public IokeObject Code { get { return code; } } public string CodeString { get { return "syntax(" + Message.Code(code) + ")"; } } public string FormattedCode(object self) { return "syntax(\n " + Message.FormattedCode(code, 2, (IokeObject)self) + ")"; } private object Expand(IokeObject self, IokeObject context, IokeObject message, object on, IDictionary<string, object> data) { if(code == null) { IokeObject condition = IokeObject.As(IokeObject.GetCellChain(context.runtime.Condition, message, context, "Error", "Invocation", "NotActivatable"), context).Mimic(message, context); condition.SetCell("message", message); condition.SetCell("context", context); condition.SetCell("receiver", on); condition.SetCell("method", self); condition.SetCell("report", context.runtime.NewText("You tried to activate a method without any code - did you by any chance activate the DefaultSyntax kind by referring to it without wrapping it inside a call to cell?")); context.runtime.ErrorCondition(condition); return null; } IokeObject c = context.runtime.Locals.Mimic(message, context); c.SetCell("self", on); c.SetCell("@", on); c.RegisterMethod(c.runtime.NewNativeMethod("will return the currently executing syntax receiver", new NativeMethod.WithNoArguments("@@", (method, _context, _message, _on, outer) => { outer.ArgumentsDefinition.GetEvaluatedArguments(_context, _message, _on, new SaneArrayList(), new SaneDictionary<string, object>()); return self; }))); c.SetCell("currentMessage", message); c.SetCell("surroundingContext", context); c.SetCell("call", context.runtime.NewCallFrom(c, message, context, IokeObject.As(on, context))); if(data != null) { foreach(var d in data) { string s = d.Key; c.SetCell(s.Substring(0, s.Length-1), d.Value); } } object result = null; try { result = context.runtime.interpreter.Evaluate(code, c, on, c); } catch(ControlFlow.Return e) { if(e.context == c) { result = e.Value; } else { throw e; } } return result; } private object ExpandWithCall(IokeObject self, IokeObject context, IokeObject message, object on, object call, IDictionary<string, object> data) { if(code == null) { IokeObject condition = IokeObject.As(IokeObject.GetCellChain(context.runtime.Condition, message, context, "Error", "Invocation", "NotActivatable"), context).Mimic(message, context); condition.SetCell("message", message); condition.SetCell("context", context); condition.SetCell("receiver", on); condition.SetCell("method", self); condition.SetCell("report", context.runtime.NewText("You tried to activate a method without any code - did you by any chance activate the DefaultSyntax kind by referring to it without wrapping it inside a call to cell?")); context.runtime.ErrorCondition(condition); return null; } IokeObject c = context.runtime.Locals.Mimic(message, context); c.SetCell("self", on); c.SetCell("@", on); c.RegisterMethod(c.runtime.NewNativeMethod("will return the currently executing syntax receiver", new NativeMethod.WithNoArguments("@@", (method, _context, _message, _on, outer) => { outer.ArgumentsDefinition.GetEvaluatedArguments(_context, _message, _on, new SaneArrayList(), new SaneDictionary<string, object>()); return self; }))); c.SetCell("currentMessage", message); c.SetCell("surroundingContext", context); c.SetCell("call", call); if(data != null) { foreach(var d in data) { string s = d.Key; c.SetCell(s.Substring(0, s.Length-1), d.Value); } } object result = null; try { result = context.runtime.interpreter.Evaluate(code, c, on, c); } catch(ControlFlow.Return e) { if(e.context == c) { result = e.Value; } else { throw e; } } return result; } public static object ActivateWithCallAndDataFixed(IokeObject self, IokeObject context, IokeObject message, object on, object call, IDictionary<string, object> data) { DefaultSyntax dm = (DefaultSyntax)self.data; object result = dm.ExpandWithCall(self, context, message, on, call, data); if(result == context.runtime.nil) { // Remove chain completely IokeObject prev = Message.GetPrev(message); IokeObject next = Message.GetNext(message); if(prev != null) { Message.SetNext(prev, next); if(next != null) { Message.SetPrev(next, prev); } } else { message.Become(next, message, context); Message.SetPrev(next, null); } return null; } else { // Insert resulting value into chain, wrapping it if it's not a message IokeObject newObj = null; if(IokeObject.dataOf(result) is Message) { newObj = IokeObject.As(result, context); } else { newObj = context.runtime.CreateMessage(Message.Wrap(IokeObject.As(result, context))); } IokeObject prev = Message.GetPrev(message); IokeObject next = Message.GetNext(message); message.Become(newObj, message, context); IokeObject last = newObj; while(Message.GetNext(last) != null) { last = Message.GetNext(last); } Message.SetNext(last, next); if(next != null) { Message.SetPrev(next, last); } Message.SetPrev(newObj, prev); // We need to distinguish explicit calls to self, and calls through a local context. object receiver = (prev == null || Message.IsTerminator(prev)) ? context : on; return Interpreter.Send(message, context, receiver); } } public new static object ActivateFixed(IokeObject self, IokeObject context, IokeObject message, object on) { return ActivateWithDataFixed(self, context, message, on, null); } public static object ActivateWithDataFixed(IokeObject self, IokeObject context, IokeObject message, object on, IDictionary<string, object> data) { DefaultSyntax dm = (DefaultSyntax)self.data; object result = dm.Expand(self, context, message, on, data); if(result == context.runtime.nil) { // Remove chain completely IokeObject prev = Message.GetPrev(message); IokeObject next = Message.GetNext(message); if(prev != null) { Message.SetNext(prev, next); if(next != null) { Message.SetPrev(next, prev); } } else { message.Become(next, message, context); Message.SetPrev(next, null); } return null; } else { // Insert resulting value into chain, wrapping it if it's not a message IokeObject newObj = null; if(IokeObject.dataOf(result) is Message) { newObj = IokeObject.As(result, context); } else { newObj = context.runtime.CreateMessage(Message.Wrap(IokeObject.As(result, context))); } IokeObject prev = Message.GetPrev(message); IokeObject next = Message.GetNext(message); message.Become(newObj, message, context); IokeObject last = newObj; while(Message.GetNext(last) != null) { last = Message.GetNext(last); } Message.SetNext(last, next); if(next != null) { Message.SetPrev(next, last); } Message.SetPrev(newObj, prev); // We need to distinguish explicit calls to self, and calls through a local context. object receiver = (prev == null || Message.IsTerminator(prev)) ? context : on; return Interpreter.Send(message, context, receiver); } } } }
using System; using System.Diagnostics.CodeAnalysis; using Content.Server.GameTicking.Presets; using Content.Server.GameTicking.Rules; using Content.Server.Ghost.Components; using Content.Shared.CCVar; using Content.Shared.Damage; using Content.Shared.Damage.Prototypes; using Content.Shared.MobState.Components; using Robust.Server.Player; using Robust.Shared.GameObjects; using Robust.Shared.IoC; namespace Content.Server.GameTicking { public sealed partial class GameTicker { public const float PresetFailedCooldownIncrease = 30f; private GamePresetPrototype? _preset; private bool StartPreset(IPlayerSession[] origReadyPlayers, bool force) { var startAttempt = new RoundStartAttemptEvent(origReadyPlayers, force); RaiseLocalEvent(startAttempt); if (!startAttempt.Cancelled) return true; var presetTitle = _preset != null ? Loc.GetString(_preset.ModeTitle) : string.Empty; void FailedPresetRestart() { SendServerMessage(Loc.GetString("game-ticker-start-round-cannot-start-game-mode-restart", ("failedGameMode", presetTitle))); RestartRound(); DelayStart(TimeSpan.FromSeconds(PresetFailedCooldownIncrease)); } if (_configurationManager.GetCVar(CCVars.GameLobbyFallbackEnabled)) { var oldPreset = _preset; ClearGameRules(); SetGamePreset(_configurationManager.GetCVar(CCVars.GameLobbyFallbackPreset)); AddGamePresetRules(); StartGamePresetRules(); startAttempt.Uncancel(); RaiseLocalEvent(startAttempt); _chatManager.DispatchServerAnnouncement( Loc.GetString("game-ticker-start-round-cannot-start-game-mode-fallback", ("failedGameMode", presetTitle), ("fallbackMode", Loc.GetString(_preset!.ModeTitle)))); if (startAttempt.Cancelled) { FailedPresetRestart(); return false; } RefreshLateJoinAllowed(); } else { FailedPresetRestart(); return false; } return true; } private void InitializeGamePreset() { SetGamePreset(_configurationManager.GetCVar(CCVars.GameLobbyDefaultPreset)); } public void SetGamePreset(GamePresetPrototype preset, bool force = false) { // Do nothing if this game ticker is a dummy! if (DummyTicker) return; _preset = preset; UpdateInfoText(); if (force) { StartRound(true); } } public void SetGamePreset(string preset, bool force = false) { var proto = FindGamePreset(preset); if(proto != null) SetGamePreset(proto, force); } public GamePresetPrototype? FindGamePreset(string preset) { if (_prototypeManager.TryIndex(preset, out GamePresetPrototype? presetProto)) return presetProto; foreach (var proto in _prototypeManager.EnumeratePrototypes<GamePresetPrototype>()) { foreach (var alias in proto.Alias) { if (preset.Equals(alias, StringComparison.InvariantCultureIgnoreCase)) return proto; } } return null; } public bool TryFindGamePreset(string preset, [NotNullWhen(true)] out GamePresetPrototype? prototype) { prototype = FindGamePreset(preset); return prototype != null; } private bool AddGamePresetRules() { if (DummyTicker || _preset == null) return false; foreach (var rule in _preset.Rules) { if (!_prototypeManager.TryIndex(rule, out GameRulePrototype? ruleProto)) continue; AddGameRule(ruleProto); } return true; } private void StartGamePresetRules() { foreach (var rule in _addedGameRules) { StartGameRule(rule); } } public bool OnGhostAttempt(Mind.Mind mind, bool canReturnGlobal) { var handleEv = new GhostAttemptHandleEvent(mind, canReturnGlobal); RaiseLocalEvent(handleEv); // Something else has handled the ghost attempt for us! We return its result. if (handleEv.Handled) return handleEv.Result; var playerEntity = mind.OwnedEntity; var entities = IoCManager.Resolve<IEntityManager>(); if (entities.HasComponent<GhostComponent>(playerEntity)) return false; if (mind.VisitingEntity != default) { mind.UnVisit(); } var position = playerEntity is {Valid: true} ? Transform(playerEntity.Value).Coordinates : GetObserverSpawnPoint(); // Ok, so, this is the master place for the logic for if ghosting is "too cheaty" to allow returning. // There's no reason at this time to move it to any other place, especially given that the 'side effects required' situations would also have to be moved. // + If CharacterDeadPhysically applies, we're physically dead. Therefore, ghosting OK, and we can return (this is critical for gibbing) // Note that we could theoretically be ICly dead and still physically alive and vice versa. // (For example, a zombie could be dead ICly, but may retain memories and is definitely physically active) // + If we're in a mob that is critical, and we're supposed to be able to return if possible, // we're succumbing - the mob is killed. Therefore, character is dead. Ghosting OK. // (If the mob survives, that's a bug. Ghosting is kept regardless.) var canReturn = canReturnGlobal && mind.CharacterDeadPhysically; if (canReturnGlobal && TryComp(playerEntity, out MobStateComponent? mobState)) { if (mobState.IsCritical()) { canReturn = true; //todo: what if they dont breathe lol //cry deeply DamageSpecifier damage = new(_prototypeManager.Index<DamageTypePrototype>("Asphyxiation"), 200); _damageable.TryChangeDamage(playerEntity, damage, true); } } var ghost = Spawn("MobObserver", position.ToMap(entities)); // Try setting the ghost entity name to either the character name or the player name. // If all else fails, it'll default to the default entity prototype name, "observer". // However, that should rarely happen. var meta = MetaData(ghost); if(!string.IsNullOrWhiteSpace(mind.CharacterName)) meta.EntityName = mind.CharacterName; else if (!string.IsNullOrWhiteSpace(mind.Session?.Name)) meta.EntityName = mind.Session.Name; var ghostComponent = Comp<GhostComponent>(ghost); if (mind.TimeOfDeath.HasValue) { ghostComponent.TimeOfDeath = mind.TimeOfDeath!.Value; } _ghosts.SetCanReturnToBody(ghostComponent, canReturn); if (canReturn) mind.Visit(ghost); else mind.TransferTo(ghost); return true; } } public sealed class GhostAttemptHandleEvent : HandledEntityEventArgs { public Mind.Mind Mind { get; } public bool CanReturnGlobal { get; } public bool Result { get; set; } public GhostAttemptHandleEvent(Mind.Mind mind, bool canReturnGlobal) { Mind = mind; CanReturnGlobal = canReturnGlobal; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Network { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// NetworkInterfaceIPConfigurationsOperations operations. /// </summary> internal partial class NetworkInterfaceIPConfigurationsOperations : IServiceOperations<NetworkManagementClient>, INetworkInterfaceIPConfigurationsOperations { /// <summary> /// Initializes a new instance of the NetworkInterfaceIPConfigurationsOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal NetworkInterfaceIPConfigurationsOperations(NetworkManagementClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the NetworkManagementClient /// </summary> public NetworkManagementClient Client { get; private set; } /// <summary> /// Get all ip configurations in a network interface /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkInterfaceName'> /// The name of the network interface. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<NetworkInterfaceIPConfiguration>>> ListWithHttpMessagesAsync(string resourceGroupName, string networkInterfaceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (networkInterfaceName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "networkInterfaceName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2017-09-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("networkInterfaceName", networkInterfaceName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkInterfaces/{networkInterfaceName}/ipConfigurations").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{networkInterfaceName}", System.Uri.EscapeDataString(networkInterfaceName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<NetworkInterfaceIPConfiguration>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<NetworkInterfaceIPConfiguration>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets the specified network interface ip configuration. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkInterfaceName'> /// The name of the network interface. /// </param> /// <param name='ipConfigurationName'> /// The name of the ip configuration name. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<NetworkInterfaceIPConfiguration>> GetWithHttpMessagesAsync(string resourceGroupName, string networkInterfaceName, string ipConfigurationName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (networkInterfaceName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "networkInterfaceName"); } if (ipConfigurationName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "ipConfigurationName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2017-09-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("networkInterfaceName", networkInterfaceName); tracingParameters.Add("ipConfigurationName", ipConfigurationName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkInterfaces/{networkInterfaceName}/ipConfigurations/{ipConfigurationName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{networkInterfaceName}", System.Uri.EscapeDataString(networkInterfaceName)); _url = _url.Replace("{ipConfigurationName}", System.Uri.EscapeDataString(ipConfigurationName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<NetworkInterfaceIPConfiguration>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<NetworkInterfaceIPConfiguration>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get all ip configurations in a network interface /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<NetworkInterfaceIPConfiguration>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<NetworkInterfaceIPConfiguration>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<NetworkInterfaceIPConfiguration>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
namespace Nancy { using System; using System.Collections.Generic; using System.Linq; using Nancy.Cookies; using Nancy.Responses; /// <summary> /// Containing extensions for the <see cref="Response"/> object. /// </summary> public static class ResponseExtensions { /// <summary> /// Force the response to be downloaded as an attachment /// </summary> /// <param name="response">Response object</param> /// <param name="fileName">Filename for the download</param> /// <param name="contentType">Optional content type</param> /// <returns>Modified Response object</returns> public static Response AsAttachment(this Response response, string fileName = null, string contentType = null) { var actualFilename = fileName; if (actualFilename == null && response is GenericFileResponse) { actualFilename = ((GenericFileResponse)response).Filename; } if (string.IsNullOrEmpty(actualFilename)) { throw new ArgumentException("fileName cannot be null or empty"); } if (contentType != null) { response.ContentType = contentType; } return response.WithHeader("Content-Disposition", "attachment; filename=" + actualFilename); } /// <summary> /// Adds a <see cref="INancyCookie"/> to the response. /// </summary> /// <param name="response">Response object</param> /// <param name="name">The name of the cookie.</param> /// <param name="value">The value of the cookie.</param> /// <returns>The <see cref="Response"/> instance.</returns> public static Response WithCookie(this Response response, string name, string value) { return WithCookie(response, name, value, null, null, null); } /// <summary> /// Adds a <see cref="INancyCookie"/> to the response. /// </summary> /// <param name="response">Response object</param> /// <param name="name">The name of the cookie.</param> /// <param name="value">The value of the cookie.</param> /// <param name="expires">The expiration date of the cookie. Can be <see langword="null" /> if it should expire at the end of the session.</param> /// <returns>The <see cref="Response"/> instance.</returns> public static Response WithCookie(this Response response, string name, string value, DateTime? expires) { return WithCookie(response, name, value, expires, null, null); } /// <summary> /// Adds a <see cref="INancyCookie"/> to the response. /// </summary> /// <param name="response">Response object</param> /// <param name="name">The name of the cookie.</param> /// <param name="value">The value of the cookie.</param> /// <param name="expires">The expiration date of the cookie. Can be <see langword="null" /> if it should expire at the end of the session.</param> /// <param name="domain">The domain of the cookie.</param> /// <param name="path">The path of the cookie.</param> /// <returns>The <see cref="Response"/> instance.</returns> public static Response WithCookie(this Response response, string name, string value, DateTime? expires, string domain, string path) { return WithCookie(response, new NancyCookie(name, value) { Expires = expires, Domain = domain, Path = path }); } /// <summary> /// Adds a <see cref="INancyCookie"/> to the response. /// </summary> /// <param name="response">Response object</param> /// <param name="nancyCookie">A <see cref="INancyCookie"/> instance.</param> /// <returns></returns> public static Response WithCookie(this Response response, INancyCookie nancyCookie) { response.Cookies.Add(nancyCookie); return response; } /// <summary> /// Add a header to the response /// </summary> /// <param name="response">Response object</param> /// <param name="header">Header name</param> /// <param name="value">Header value</param> /// <returns>Modified response</returns> public static Response WithHeader(this Response response, string header, string value) { return response.WithHeaders(new { Header = header, Value = value }); } /// <summary> /// Adds headers to the response using anonymous types /// </summary> /// <param name="response">Response object</param> /// <param name="headers"> /// Array of headers - each header should be an anonymous type with two string properties /// 'Header' and 'Value' to represent the header name and its value. /// </param> /// <returns>Modified response</returns> public static Response WithHeaders(this Response response, params object[] headers) { return response.WithHeaders(headers.Select(GetTuple).ToArray()); } /// <summary> /// Adds headers to the response using anonymous types /// </summary> /// <param name="response">Response object</param> /// <param name="headers"> /// Array of headers - each header should be a Tuple with two string elements /// for header name and header value /// </param> /// <returns>Modified response</returns> public static Response WithHeaders(this Response response, params Tuple<string, string>[] headers) { if (response.Headers == null) { response.Headers = new Dictionary<string, string>(); } foreach (var keyValuePair in headers) { response.Headers[keyValuePair.Item1] = keyValuePair.Item2; } return response; } /// <summary> /// Sets the content type of the response /// </summary> /// <param name="response">Response object</param> /// <param name="contentType">The type of the content</param> /// <returns>Modified response</returns> public static Response WithContentType(this Response response, string contentType) { response.ContentType = contentType; return response; } /// <summary> /// Sets the status code of the response /// </summary> /// <param name="response">Response object</param> /// <param name="statusCode">The http status code</param> /// <returns>Modified response</returns> public static Response WithStatusCode(this Response response, HttpStatusCode statusCode) { response.StatusCode = statusCode; return response; } /// <summary> /// Sets the status code of the response /// </summary> /// <param name="response">Response object</param> /// <param name="statusCode">The http status code</param> /// <returns>Modified response</returns> public static Response WithStatusCode(this Response response, int statusCode) { response.StatusCode = (HttpStatusCode) statusCode; return response; } private static Tuple<string, string> GetTuple(object header) { var properties = header.GetType() .GetProperties() .Where(prop => prop.CanRead && prop.PropertyType == typeof(string)) .ToArray(); var headerProperty = properties .Where(p => string.Equals(p.Name, "Header", StringComparison.InvariantCultureIgnoreCase)) .FirstOrDefault(); var valueProperty = properties .Where(p => string.Equals(p.Name, "Value", StringComparison.InvariantCultureIgnoreCase)) .FirstOrDefault(); if (headerProperty == null || valueProperty == null) { throw new ArgumentException("Unable to extract 'Header' or 'Value' properties from anonymous type."); } return Tuple.Create( (string)headerProperty.GetValue(header, null), (string)valueProperty.GetValue(header, null)); } } }
/* VRCustomEditor * MiddleVR * (c) MiddleVR */ // In versions prior Unity 4.6 the fullscreen mode parameter does not exist. // In the Unity 4.6 the full screen mode for DirectX 9 was added and the support // for full screen mode in DirectX 11 was added in Unity 5.0. #if !UNITY_4_2 && !UNITY_4_3 && !UNITY_4_5 #define UNITY_D3D9_FULLSCREEN_MODE #if !UNITY_4_6 #define UNITY_D3D11_FULLSCREEN_MODE #endif #endif using UnityEngine; using UnityEditor; using System.Collections; using System.IO; using MiddleVR_Unity3D; using UnityEditor.Callbacks; [CustomEditor(typeof(VRManagerScript))] public class VRCustomEditor : Editor { //This will just be a shortcut to the target, ex: the object you clicked on. private VRManagerScript mgr; static private bool m_SettingsApplied = false; void Awake() { mgr = (VRManagerScript)target; if( !m_SettingsApplied ) { ApplyVRSettings(); m_SettingsApplied = true; } } void Start() { Debug.Log("MT: " + PlayerSettings.MTRendering); } public void ApplyVRSettings() { PlayerSettings.defaultIsFullScreen = false; PlayerSettings.displayResolutionDialog = ResolutionDialogSetting.Disabled; PlayerSettings.runInBackground = true; PlayerSettings.captureSingleScreen = false; PlayerSettings.MTRendering = false; //PlayerSettings.usePlayerLog = false; //PlayerSettings.useDirect3D11 = false; #if UNITY_D3D9_FULLSCREEN_MODE PlayerSettings.d3d9FullscreenMode = D3D9FullscreenMode.ExclusiveMode; #endif #if UNITY_D3D11_FULLSCREEN_MODE PlayerSettings.d3d11FullscreenMode = D3D11FullscreenMode.ExclusiveMode; #endif MVRTools.Log("VR Player settings changed:"); MVRTools.Log("- DefaultIsFullScreen = false"); MVRTools.Log("- DisplayResolutionDialog = Disabled"); MVRTools.Log("- RunInBackground = true"); MVRTools.Log("- CaptureSingleScreen = false"); //MVRTools.Log("- UsePlayerLog = false"); string[] names = QualitySettings.names; int qualityLevel = QualitySettings.GetQualityLevel(); // Disable VSync on all quality levels for( int i=0 ; i<names.Length ; ++i ) { QualitySettings.SetQualityLevel( i ); QualitySettings.vSyncCount = 0; } QualitySettings.SetQualityLevel( qualityLevel ); MVRTools.Log("Quality settings changed for all quality levels:"); MVRTools.Log("- VSyncCount = 0"); } public override void OnInspectorGUI() { GUILayout.BeginVertical(); if (GUILayout.Button("Re-apply VR player settings")) { ApplyVRSettings(); } if (GUILayout.Button("Pick configuration file")) { string path = EditorUtility.OpenFilePanel("Please choose MiddleVR configuration file", "C:/Program Files (x86)/MiddleVR/data/Config", "vrx"); MVRTools.Log("[+] Picked " + path ); mgr.ConfigFile = path; EditorUtility.SetDirty(mgr); } DrawDefaultInspector(); GUILayout.EndVertical(); } private static void CopyFolderIfExists(string iFolderName, string iSrcBasePath, string iDstBasePath) { string sourcePath = Path.Combine(iSrcBasePath, iFolderName); if (Directory.Exists(sourcePath)) { // The player executable file and the data folder share the same base name string destinationPath = Path.Combine(iDstBasePath, iFolderName); FileSystemTools.DirectoryCopy(sourcePath, destinationPath, true, true); } } [PostProcessBuild] public static void OnPostprocessBuild(BuildTarget target, string pathToBuiltProject) { string pathToSourceData = Application.dataPath; string pathToPlayerData = Path.Combine(Path.GetDirectoryName(pathToBuiltProject), Path.GetFileNameWithoutExtension(pathToBuiltProject) + "_Data"); CopyFolderIfExists("WebAssets", pathToSourceData, pathToPlayerData); // Copy web assets CopyFolderIfExists(".WebAssets", pathToSourceData, pathToPlayerData); // Copy web assets in hidden directory string pathToSourceDataMiddleVR = Path.Combine(pathToSourceData, "MiddleVR"); string pathToPlayerDataMiddleVR = Path.Combine(pathToPlayerData, "MiddleVR"); CopyFolderIfExists("WebAssets", pathToSourceDataMiddleVR, pathToPlayerDataMiddleVR); // Copy web assets CopyFolderIfExists(".WebAssets", pathToSourceDataMiddleVR, pathToPlayerDataMiddleVR); // Copy web assets in hidden directory // Sign Application MVRTools.SignApplication( pathToBuiltProject ); } } // InitializeOnLoad will run the static contructor of this class when // starting the editor and after every re-compilation of this script [InitializeOnLoad] public class MiddleVRDeprecatedAssetsCleaner { static MiddleVRDeprecatedAssetsCleaner() { Run(); } internal static void Run() { EditorApplication.update += CleanAssets; } private static void CleanAssets() { // Ensure this is called only once EditorApplication.update -= CleanAssets; if (!File.Exists(Path.Combine(Application.dataPath, "MiddleVR_Source_Project.txt"))) { // Clean old deprecated assets from previous MiddleVR versions string[] assetsToDelete = { "Assets/Editor/VRCustomEditor.cs", "Assets/MiddleVR/Resources/OVRLensCorrectionMat.mat", "Assets/MiddleVR/Scripts/Internal/VRCameraCB.cs", "Assets/MiddleVR/Assets/Materials/WandRayMaterial.mat", "Assets/Plugins/MiddleVR_UnityRendering.dll", "Assets/Plugins/MiddleVR_UnityRendering_x64.dll" }; int filesDeleted = 0; foreach (string assetToDelete in assetsToDelete) { if (AssetDatabase.DeleteAsset(assetToDelete)) { filesDeleted++; MVRTools.Log(3, "[ ] Deleting deprecated MiddleVR asset '" + assetToDelete + "'."); } } if (filesDeleted > 0) { MVRTools.Log(3, "[ ] Deleted " + filesDeleted.ToString() + " deprecated MiddleVR asset(s)."); AssetDatabase.Refresh(); } } } } public class AdditionnalImports : AssetPostprocessor { public static void OnPostprocessAllAssets(string[] iImportedAssets, string[] iDeletedAssets, string[] iMovedAssets, string[] iMovedFromAssetPaths) { MiddleVRDeprecatedAssetsCleaner.Run(); } } public class FileSystemTools { public static void DirectoryCopy(string sourceDirName, string destDirName, bool copySubDirs, bool overwrite) { // Get the subdirectories for the specified directory DirectoryInfo dir = new DirectoryInfo(sourceDirName); DirectoryInfo[] dirs = dir.GetDirectories(); if (!dir.Exists) { throw new DirectoryNotFoundException( "Source directory does not exist or could not be found: '" + sourceDirName + "'."); } // If the destination directory doesn't exist, create it if (!Directory.Exists(destDirName)) { Directory.CreateDirectory(destDirName); } // Get the files in the directory and copy them to the new location FileInfo[] files = dir.GetFiles(); foreach (FileInfo file in files) { if (!file.Name.ToLower().EndsWith(".meta")) { string temppath = Path.Combine(destDirName, file.Name); file.CopyTo(temppath, overwrite); } } // If copying subdirectories, copy them and their contents to new location if (copySubDirs) { foreach (DirectoryInfo subdir in dirs) { string temppath = Path.Combine(destDirName, subdir.Name); DirectoryCopy(subdir.FullName, temppath, copySubDirs, overwrite); } } } }
/** * 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.Text; using Lucene.Net.Analysis; using Lucene.Net.Analysis.Tokenattributes; using Lucene.Net.Search; using Lucene.Net.Documents; using Lucene.Net.QueryParsers; using Lucene.Net.Store; using Lucene.Net.Index; using Lucene.Net.Util; using NUnit.Framework; namespace Lucene.Net.Search.Vectorhighlight { public abstract class AbstractTestCase { protected String F = "f"; protected String F1 = "f1"; protected String F2 = "f2"; protected Directory dir; protected Analyzer analyzerW; protected Analyzer analyzerB; protected Analyzer analyzerK; protected IndexReader reader; protected QueryParser paW; protected QueryParser paB; protected static String[] shortMVValues = { "a b c", "", // empty data in multi valued field "d e" }; protected static String[] longMVValues = { "Followings are the examples of customizable parameters and actual examples of customization:", "The most search engines use only one of these methods. Even the search engines that says they can use the both methods basically" }; // test data for LUCENE-1448 bug protected static String[] biMVValues = { "\nLucene/Solr does not require such additional hardware.", "\nWhen you talk about processing speed, the" }; protected static String[] strMVValues = { "abc", "defg", "hijkl" }; [SetUp] public void SetUp() { analyzerW = new WhitespaceAnalyzer(); analyzerB = new BigramAnalyzer(); analyzerK = new KeywordAnalyzer(); paW = new QueryParser(F, analyzerW); paB = new QueryParser(F, analyzerB); dir = new RAMDirectory(); } [TearDown] public void TearDown() { if (reader != null) { reader.Close(); reader = null; } } protected Query Tq(String text) { return Tq(1F, text); } protected Query Tq(float boost, String text) { return Tq(boost, F, text); } protected Query Tq(String field, String text) { return Tq(1F, field, text); } protected Query Tq(float boost, String field, String text) { Query query = new TermQuery(new Term(field, text)); query.SetBoost(boost); return query; } protected Query PqF(params String[] texts) { return PqF(1F, texts); } //protected Query pqF(String[] texts) //{ // return pqF(1F, texts); //} protected Query PqF(float boost, params String[] texts) { return pqF(boost, 0, texts); } protected Query pqF(float boost, int slop, params String[] texts) { return Pq(boost, slop, F, texts); } protected Query Pq(String field, params String[] texts) { return Pq(1F, 0, field, texts); } protected Query Pq(float boost, String field, params String[] texts) { return Pq(boost, 0, field, texts); } protected Query Pq(float boost, int slop, String field, params String[] texts) { PhraseQuery query = new PhraseQuery(); foreach (String text in texts) { query.Add(new Term(field, text)); } query.SetBoost(boost); query.SetSlop(slop); return query; } protected Query Dmq(params Query[] queries) { return Dmq(0.0F, queries); } protected Query Dmq(float tieBreakerMultiplier, params Query[] queries) { DisjunctionMaxQuery query = new DisjunctionMaxQuery(tieBreakerMultiplier); foreach (Query q in queries) { query.Add(q); } return query; } protected void AssertCollectionQueries(Dictionary<Query, Query> actual, params Query[] expected) { Assert.AreEqual(expected.Length, actual.Count); foreach (Query query in expected) { Assert.IsTrue(actual.ContainsKey(query)); } } class BigramAnalyzer : Analyzer { public override TokenStream TokenStream(String fieldName, System.IO.TextReader reader) { return new BasicNGramTokenizer(reader); } } class BasicNGramTokenizer : Tokenizer { public static int DEFAULT_N_SIZE = 2; public static String DEFAULT_DELIMITERS = " \t\n.,"; private int n; private String delimiters; private int startTerm; private int lenTerm; private int startOffset; private int nextStartOffset; private int ch; private String snippet; private StringBuilder snippetBuffer; private static int BUFFER_SIZE = 4096; private char[] charBuffer; private int charBufferIndex; private int charBufferLen; public BasicNGramTokenizer(System.IO.TextReader inReader): this(inReader, DEFAULT_N_SIZE) { } public BasicNGramTokenizer(System.IO.TextReader inReader, int n): this(inReader, n, DEFAULT_DELIMITERS) { } public BasicNGramTokenizer(System.IO.TextReader inReader, String delimiters) : this(inReader, DEFAULT_N_SIZE, delimiters) { } public BasicNGramTokenizer(System.IO.TextReader inReader, int n, String delimiters) : base(inReader) { this.n = n; this.delimiters = delimiters; startTerm = 0; nextStartOffset = 0; snippet = null; snippetBuffer = new StringBuilder(); charBuffer = new char[BUFFER_SIZE]; charBufferIndex = BUFFER_SIZE; charBufferLen = 0; ch = 0; Init(); } void Init() { termAtt = (TermAttribute)AddAttribute(typeof(TermAttribute)); offsetAtt = (OffsetAttribute)AddAttribute(typeof(OffsetAttribute)); } TermAttribute termAtt = null; OffsetAttribute offsetAtt = null; public override bool IncrementToken() { if (!GetNextPartialSnippet()) return false; ClearAttributes(); termAtt.SetTermBuffer(snippet, startTerm, lenTerm); offsetAtt.SetOffset(CorrectOffset(startOffset), CorrectOffset(startOffset + lenTerm)); return true; } private int GetFinalOffset() { return nextStartOffset; } public override void End() { offsetAtt.SetOffset(GetFinalOffset(), GetFinalOffset()); } protected bool GetNextPartialSnippet() { if (snippet != null && snippet.Length >= startTerm + 1 + n) { startTerm++; startOffset++; lenTerm = n; return true; } return GetNextSnippet(); } protected bool GetNextSnippet() { startTerm = 0; startOffset = nextStartOffset; snippetBuffer.Remove(0, snippetBuffer.Length); while (true) { if (ch != -1) ch = ReadCharFromBuffer(); if (ch == -1) break; else if (!IsDelimiter(ch)) snippetBuffer.Append((char)ch); else if (snippetBuffer.Length > 0) break; else startOffset++; } if (snippetBuffer.Length == 0) return false; snippet = snippetBuffer.ToString(); lenTerm = snippet.Length >= n ? n : snippet.Length; return true; } protected int ReadCharFromBuffer() { if (charBufferIndex >= charBufferLen) { charBufferLen = input.Read(charBuffer,0,charBuffer.Length); if (charBufferLen <= 0) { return -1; } charBufferIndex = 0; } int c = (int)charBuffer[charBufferIndex++]; nextStartOffset++; return c; } protected bool IsDelimiter(int c) { return delimiters.IndexOf(Convert.ToChar(c) ) >= 0; } } protected void Make1d1fIndex(String value) { Make1dmfIndex( value ); } protected void Make1d1fIndexB(String value) { Make1dmfIndexB( value ); } protected void Make1dmfIndex(params String[] values) { Make1dmfIndex(analyzerW, values); } protected void Make1dmfIndexB(params String[] values) { Make1dmfIndex(analyzerB, values); } // make 1 doc with multi valued field protected void Make1dmfIndex(Analyzer analyzer, params String[] values) { IndexWriter writer = new IndexWriter(dir, analyzer, true, IndexWriter.MaxFieldLength.LIMITED); Document doc = new Document(); foreach (String value in values) doc.Add(new Field(F, value, Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.WITH_POSITIONS_OFFSETS)); writer.AddDocument(doc); writer.Close(); reader = IndexReader.Open(dir,true); } // make 1 doc with multi valued & not analyzed field protected void Make1dmfIndexNA(String[] values) { IndexWriter writer = new IndexWriter(dir, analyzerK, true, IndexWriter.MaxFieldLength.LIMITED); Document doc = new Document(); foreach (String value in values) doc.Add(new Field(F, value, Field.Store.YES, Field.Index.NOT_ANALYZED, Field.TermVector.WITH_POSITIONS_OFFSETS)); writer.AddDocument(doc); writer.Close(); reader = IndexReader.Open(dir, true); } protected void MakeIndexShortMV() { // 012345 // "a b c" // 0 1 2 // "" // 6789 // "d e" // 3 4 Make1dmfIndex(shortMVValues); } protected void MakeIndexLongMV() { // 11111111112222222222333333333344444444445555555555666666666677777777778888888888999 // 012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012 // Followings are the examples of customizable parameters and actual examples of customization: // 0 1 2 3 4 5 6 7 8 9 10 11 // 1 2 // 999999900000000001111111111222222222233333333334444444444555555555566666666667777777777888888888899999999990000000000111111111122 // 345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901 // The most search engines use only one of these methods. Even the search engines that says they can use the both methods basically // 12 13 (14) (15) 16 17 18 19 20 21 22 23 (24) (25) 26 27 28 29 30 31 32 33 34 Make1dmfIndex(longMVValues); } protected void MakeIndexLongMVB() { // "*" [] LF // 1111111111222222222233333333334444444444555555 // 01234567890123456789012345678901234567890123456789012345 // *Lucene/Solr does not require such additional hardware. // Lu 0 do 10 re 15 su 21 na 31 // uc 1 oe 11 eq 16 uc 22 al 32 // ce 2 es 12 qu 17 ch 23 ha 33 // en 3 no 13 ui 18 ad 24 ar 34 // ne 4 ot 14 ir 19 dd 25 rd 35 // e/ 5 re 20 di 26 dw 36 // /S 6 it 27 wa 37 // So 7 ti 28 ar 38 // ol 8 io 29 re 39 // lr 9 on 30 // 5555666666666677777777778888888888999999999 // 6789012345678901234567890123456789012345678 // *When you talk about processing speed, the // Wh 40 ab 48 es 56 th 65 // he 41 bo 49 ss 57 he 66 // en 42 ou 50 si 58 // yo 43 ut 51 in 59 // ou 44 pr 52 ng 60 // ta 45 ro 53 sp 61 // al 46 oc 54 pe 62 // lk 47 ce 55 ee 63 // ed 64 Make1dmfIndexB(biMVValues); } protected void MakeIndexStrMV() { // 0123 // "abc" // 34567 // "defg" // 111 // 789012 // "hijkl" Make1dmfIndexNA(strMVValues); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Xunit; using System; using System.Collections.Generic; using System.Linq; namespace Test { public class ExceptConcatReverseTests { // // Except // [Fact] public static void RunExceptTest1() { RunExceptTest1Core(0, 0); RunExceptTest1Core(1, 0); RunExceptTest1Core(0, 1); RunExceptTest1Core(4, 4); RunExceptTest1Core(1024, 4); RunExceptTest1Core(4, 1024); RunExceptTest1Core(1024, 1024); RunExceptTest1Core(1024 * 4, 1024); RunExceptTest1Core(1024, 1024 * 4); RunExceptTest1Core(1024 * 1024, 1024 * 1024); } private static void RunExceptTest1Core(int leftDataSize, int rightDataSize) { string[] names1 = new string[] { "balmer", "duffy", "gates", "jobs", "silva", "brumme", "gray", "grover", "yedlin" }; string[] names2 = new string[] { "balmer", "duffy", "gates", "essey", "crocker", "smith", "callahan", "jimbob", "beebop" }; string method = string.Format("RunExceptTest1(leftSize={0}, rightSize={1}) - except of names", leftDataSize, rightDataSize); //Random r = new Random(33); // use constant seed for predictable test runs. string[] leftData = new string[leftDataSize]; for (int i = 0; i < leftDataSize; i++) { int index = i % names1.Length; leftData[i] = names1[index]; } string[] rightData = new string[rightDataSize]; for (int i = 0; i < rightDataSize; i++) { int index = i % names2.Length; rightData[i] = names2[index]; } // Just get the exception of thw two sets. ParallelQuery<string> q = leftData.AsParallel().Except<string>(rightData.AsParallel()); // Build a list of seen names, ensuring we don't see dups. List<string> seen = new List<string>(); foreach (string n in q) { // Ensure we haven't seen this name before. if (seen.Contains(n)) { Assert.True(false, string.Format(method + " ** FAILED. NotUnique: {0} is not unique, already seen (failure)", n)); } // Ensure the data DOES NOT exist in the right source. if (Array.IndexOf(rightData, n) != -1) { Assert.True(false, string.Format(method + " ** FAILED. FoundInRight: {0} found in the right data source, error", n)); } seen.Add(n); } } [Fact] public static void RunOrderedExceptTest1() { for (int len = 1; len <= 300; len += 3) { var data = Enumerable.Repeat(0, len) .Concat(new int[] { 1 }) .Concat(Enumerable.Repeat(0, len)) .Concat(new int[] { 2 }) .Concat(Enumerable.Repeat(0, len)) .Concat(new int[] { 1 }) .Concat(Enumerable.Repeat(0, len)) .Concat(new int[] { 2 }) .Concat(Enumerable.Repeat(0, len)) .Concat(new int[] { 3 }) .Concat(Enumerable.Repeat(0, len)); var output = data.AsParallel().AsOrdered().Except(Enumerable.Empty<int>().AsParallel()).ToArray(); if (!Enumerable.Range(0, 4).SequenceEqual(output)) { Assert.True(false, string.Format("RunOrderedExceptTest1: FAILED. ** Incorrect output")); } } } // // Concat // [Fact] public static void RunConcatTest() { bool[] booleanValues = new[] { true, false }; foreach (bool usePipelining in booleanValues) { foreach (bool useParallelRange in booleanValues) { RunConcatTestCore(usePipelining, useParallelRange, 0, 0); RunConcatTestCore(usePipelining, useParallelRange, 0, 1); RunConcatTestCore(usePipelining, useParallelRange, 1, 0); RunConcatTestCore(usePipelining, useParallelRange, 1, 1); RunConcatTestCore(usePipelining, useParallelRange, 4, 4); RunConcatTestCore(usePipelining, useParallelRange, 1024, 1024); RunConcatTestCore(usePipelining, useParallelRange, 0, 1024); RunConcatTestCore(usePipelining, useParallelRange, 1024, 0); RunConcatTestCore(usePipelining, useParallelRange, 1023 * 1024, 1023 * 1024); } } } private static void RunConcatTestCore(bool usePipelining, bool useParallelRange, int leftSize, int rightSize) { string method = string.Format("RunConcatTest1(usePipelining={0}, useParallelRange={1}, leftSize={2}, rightSize={3})", usePipelining, useParallelRange, leftSize, rightSize); int[] leftData = new int[leftSize]; for (int i = 0; i < leftSize; i++) leftData[i] = i; int[] rightData = new int[rightSize]; for (int i = 0; i < rightSize; i++) rightData[i] = i; ParallelQuery<int> q = useParallelRange ? ParallelEnumerable.Range(0, leftSize) : leftData.AsParallel(); IEnumerable<int> r = usePipelining ? (IEnumerable<int>)q.AsOrdered().Concat(rightData.AsParallel()) : (IEnumerable<int>)q.AsOrdered().Concat(rightData.AsParallel()).ToList(); int cnt = 0; foreach (int x in r) { if (cnt < leftSize) { if (x != leftData[cnt]) { Assert.True(false, string.Format(method + " > FAILED. Expected element {0} to == {1} (from left)); got {2} instead", cnt, leftData[cnt], x)); } } else { if (x != rightData[cnt - leftSize]) { Assert.True(false, string.Format(method + " > FAILED. Expected element {0} to == {1} (from right)); got {2} instead", cnt, rightData[cnt - leftSize], x)); } } cnt++; } if (!(cnt == leftSize + rightSize)) { Assert.True(false, string.Format(method + " > FAILED. Expect: {0}, real: {1}", leftSize + rightSize, cnt)); } } // // Reverse // [Fact] public static void RunReverseTest1() { RunReverseTest1Core(0); RunReverseTest1Core(33); RunReverseTest1Core(1024); RunReverseTest1Core(1024 * 1024); } [Fact] public static void RunReverseTest2_Range() { RunReverseTest2_RangeCore(0, 0); RunReverseTest2_RangeCore(0, 33); RunReverseTest2_RangeCore(33, 33); RunReverseTest2_RangeCore(33, 66); } [Fact] [OuterLoop] public static void RunReverseTest2_Range_LongRunning() { RunReverseTest2_RangeCore(0, 1024 * 3); RunReverseTest2_RangeCore(1024, 1024 * 1024 * 3); } private static void RunReverseTest1Core(int size) { string method = string.Format("RunReverseTest1(size={0})", size); int[] ints = new int[size]; for (int i = 0; i < size; i++) ints[i] = i; ParallelQuery<int> q = ints.AsParallel().AsOrdered().Reverse(); int cnt = 0; int last = size; foreach (int x in q) { if (x != last - 1) { Assert.True(false, string.Format(method + " > FAILED. Elems not in decreasing order: this={0}, last={1}", x, last)); } last = x; cnt++; } if (cnt != size) { Assert.True(false, string.Format(method + " > Expect: {0}, real: {1}", size, cnt)); } } private static void RunReverseTest2_RangeCore(int start, int count) { string method = string.Format("RunReverseTest2_Range(start={0}, count={1})", start, count); ParallelQuery<int> q = ParallelEnumerable.Range(start, count).AsOrdered().Reverse(); int seen = 0; int last = (start + count); foreach (int x in q) { if (x != last - 1) { Assert.True(false, string.Format(method + " > FAILED. Elems not in decreasing order: this={0}, last={1}", x, last)); } last = x; seen++; } if (seen != count) { Assert.True(false, string.Format(method + " > FAILED. Expect: {0}, real: {1}", count, seen)); } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Xml; using System.Xml.Schema; using System.Xml.Serialization; namespace MongoDB { /// <summary> /// </summary> [Serializable] public sealed class Binary : IEquatable<Binary>, ICloneable, IEnumerable<byte>, IXmlSerializable { /// <summary> /// Initializes a new instance of the <see cref = "Binary" /> class. /// </summary> public Binary() { } /// <summary> /// Initializes a new instance of the <see cref = "Binary" /> class. /// </summary> /// <param name = "bytes">The value.</param> public Binary(byte[] bytes) { Bytes = bytes; Subtype = BinarySubtype.General; } /// <summary> /// Initializes a new instance of the <see cref = "Binary" /> class. /// </summary> /// <param name = "bytes">The bytes.</param> /// <param name = "subtype">The subtype.</param> public Binary(byte[] bytes, BinarySubtype subtype) { Bytes = bytes; Subtype = subtype; } /// <summary> /// Gets or sets the bytes. /// </summary> /// <value>The bytes.</value> public byte[] Bytes { get; set; } /// <summary> /// Gets or sets the subtype. /// </summary> /// <value>The subtype.</value> public BinarySubtype Subtype { get; set; } /// <summary> /// Creates a new object that is a copy of the current instance. /// </summary> /// <returns> /// A new object that is a copy of this instance. /// </returns> public object Clone() { return new Binary(Bytes) {Subtype = Subtype}; } /// <summary> /// Returns an enumerator that iterates through a collection. /// </summary> /// <returns> /// An <see cref = "T:System.Collections.IEnumerator" /> object that can be used to iterate through the collection. /// </returns> IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns> /// A <see cref = "T:System.Collections.Generic.IEnumerator`1" /> that can be used to iterate through the collection. /// </returns> public IEnumerator<byte> GetEnumerator() { if(Bytes == null) yield break; foreach(var b in Bytes) yield return b; } /// <summary> /// Performs an implicit conversion from <see cref="MongoDB.Binary"/> to <see cref="System.Byte"/>. /// </summary> /// <param name="binary">The binary.</param> /// <returns>The result of the conversion.</returns> public static implicit operator byte[](Binary binary) { if(binary == null) throw new ArgumentNullException("binary"); return binary.Bytes; } /// <summary> /// Performs an implicit conversion from <see cref = "System.Byte" /> to <see cref = "MongoDB.Binary" />. /// </summary> /// <param name = "bytes">The bytes.</param> /// <returns>The result of the conversion.</returns> public static implicit operator Binary(byte[] bytes) { if(bytes == null) throw new ArgumentNullException("bytes"); return new Binary(bytes); } /// <summary> /// Implements the operator ==. /// </summary> /// <param name = "left">The left.</param> /// <param name = "right">The right.</param> /// <returns>The result of the operator.</returns> public static bool operator ==(Binary left, Binary right) { return Equals(left, right); } /// <summary> /// Implements the operator !=. /// </summary> /// <param name = "left">The left.</param> /// <param name = "right">The right.</param> /// <returns>The result of the operator.</returns> public static bool operator !=(Binary left, Binary right) { return !Equals(left, right); } /// <summary> /// Indicates whether the current object is equal to another object of the same type. /// </summary> /// <param name="other">An object to compare with this object.</param> /// <returns> /// true if the current object is equal to the <paramref name="other"/> parameter; otherwise, false. /// </returns> public bool Equals(Binary other) { if(ReferenceEquals(null, other)) return false; if(ReferenceEquals(this, other)) return true; if(!Equals(other.Subtype, Subtype)) return false; if(Bytes != null && other.Bytes != null) return Bytes.SequenceEqual(other.Bytes); return Equals(Bytes, other.Bytes); } /// <summary> /// Determines whether the specified <see cref="System.Object"/> is equal to this instance. /// </summary> /// <param name="obj">The <see cref="System.Object"/> to compare with this instance.</param> /// <returns> /// <c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>. /// </returns> /// <exception cref="T:System.NullReferenceException"> /// The <paramref name="obj"/> parameter is null. /// </exception> public override bool Equals(object obj) { if(ReferenceEquals(null, obj)) return false; if(ReferenceEquals(this, obj)) return true; return obj.GetType() == typeof(Binary) && Equals((Binary)obj); } /// <summary> /// Returns a hash code for this instance. /// </summary> /// <returns> /// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table. /// </returns> public override int GetHashCode() { unchecked { return ((Bytes != null ? Bytes.GetHashCode() : 0)*397) ^ Subtype.GetHashCode(); } } /// <summary> /// Returns a <see cref = "System.String" /> that represents this instance. /// </summary> /// <returns> /// A <see cref = "System.String" /> that represents this instance. /// </returns> public override string ToString() { return String.Format(@"{{ ""$binary"": ""{0}"", ""$type"" : {1} }}", Convert.ToBase64String(Bytes??new byte[0]), (int)Subtype); } /// <summary> /// This method is reserved and should not be used. When implementing the IXmlSerializable interface, you should return null (Nothing in Visual Basic) from this method, and instead, if specifying a custom schema is required, apply the <see cref="T:System.Xml.Serialization.XmlSchemaProviderAttribute"/> to the class. /// </summary> /// <returns> /// An <see cref="T:System.Xml.Schema.XmlSchema"/> that describes the XML representation of the object that is produced by the <see cref="M:System.Xml.Serialization.IXmlSerializable.WriteXml(System.Xml.XmlWriter)"/> method and consumed by the <see cref="M:System.Xml.Serialization.IXmlSerializable.ReadXml(System.Xml.XmlReader)"/> method. /// </returns> XmlSchema IXmlSerializable.GetSchema() { return null; } /// <summary> /// Generates an object from its XML representation. /// </summary> /// <param name="reader">The <see cref="T:System.Xml.XmlReader"/> stream from which the object is deserialized.</param> void IXmlSerializable.ReadXml(XmlReader reader) { reader.MoveToAttribute("subtype"); Subtype = (BinarySubtype)Enum.Parse(typeof(BinarySubtype), reader.Value); reader.MoveToElement(); if(reader.IsEmptyElement) return; var content = reader.ReadElementContentAsString(); if(content != null) Bytes = Convert.FromBase64String(content); } /// <summary> /// Converts an object into its XML representation. /// </summary> /// <param name="writer">The <see cref="T:System.Xml.XmlWriter"/> stream to which the object is serialized.</param> void IXmlSerializable.WriteXml(XmlWriter writer) { writer.WriteAttributeString("subtype",Subtype.ToString()); if(Bytes!=null) writer.WriteBase64(Bytes,0,Bytes.Length); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using Android.App; using Android.Content; using Android.Content.PM; using Android.OS; using Android.Support.V4.App; using Android.Support.V4.Widget; using Android.Text.Format; using Android.Views; using Android.Widget; using Toggl.Joey.UI.Adapters; using Toggl.Joey.UI.Components; using Toggl.Joey.UI.Fragments; using Toggl.Joey.UI.Views; using Toggl.Phoebe; using Toggl.Phoebe.Data; using Toggl.Phoebe.Net; using XPlatUtils; using ActionBarDrawerToggle = Android.Support.V7.App.ActionBarDrawerToggle; using Fragment = Android.Support.V4.App.Fragment; using Toolbar = Android.Support.V7.Widget.Toolbar; using FragmentManager = Android.Support.V4.App.FragmentManager; using DialogFragment = Android.Support.V4.App.DialogFragment; namespace Toggl.Joey.UI.Activities { [Activity ( ScreenOrientation = ScreenOrientation.Portrait, Name = "toggl.joey.ui.activities.MainDrawerActivity", Label = "@string/EntryName", Exported = true, #if DEBUG // The actual entry-point is defined in manifest via activity-alias, this here is just to // make adb launch the activity automatically when developing. #endif Theme = "@style/Theme.Toggl.Main")] public class MainDrawerActivity : BaseActivity { private const string PageStackExtra = "com.toggl.timer.page_stack"; private const string LastSyncArgument = "com.toggl.timer.last_sync"; private const string LastSyncResultArgument = "com.toggl.timer.last_sync_result"; private readonly TimerComponent barTimer = new TimerComponent (); private readonly Lazy<LogTimeEntriesListFragment> trackingFragment = new Lazy<LogTimeEntriesListFragment> (); private readonly Lazy<SettingsListFragment> settingsFragment = new Lazy<SettingsListFragment> (); private readonly Lazy<ReportsPagerFragment> reportFragment = new Lazy<ReportsPagerFragment> (); private readonly Lazy<FeedbackFragment> feedbackFragment = new Lazy<FeedbackFragment> (); private readonly Lazy<RegisterUserFragment> registerUserFragment = new Lazy<RegisterUserFragment> (); private readonly List<int> pageStack = new List<int> (); private AuthManager authManager; private DrawerListAdapter drawerAdapter; private ToolbarModes toolbarMode; private bool OpenInSignup = false; private ListView DrawerListView { get; set; } private TextView DrawerUserName { get; set; } private TextView DrawerEmail { get; set; } private ProfileImageView DrawerImage { get; set; } private View DrawerUserView { get; set; } private DrawerLayout DrawerLayout { get; set; } protected ActionBarDrawerToggle DrawerToggle { get; private set; } private FrameLayout DrawerSyncView { get; set; } public Toolbar MainToolbar { get; set; } // Explanation of native constructor // http://stackoverflow.com/questions/10593022/monodroid-error-when-calling-constructor-of-custom-view-twodscrollview/10603714#10603714 public MainDrawerActivity (IntPtr a, Android.Runtime.JniHandleOwnership b) : base (a, b) { } public MainDrawerActivity () { } protected override void OnCreateActivity (Bundle state) { base.OnCreateActivity (state); SetContentView (Resource.Layout.MainDrawerActivity); MainToolbar = FindViewById<Toolbar> (Resource.Id.MainToolbar); DrawerListView = FindViewById<ListView> (Resource.Id.DrawerListView); DrawerUserView = LayoutInflater.Inflate (Resource.Layout.MainDrawerListHeader, null); DrawerUserName = DrawerUserView.FindViewById<TextView> (Resource.Id.TitleTextView); DrawerEmail = DrawerUserView.FindViewById<TextView> (Resource.Id.EmailTextView); DrawerImage = DrawerUserView.FindViewById<ProfileImageView> (Resource.Id.IconProfileImageView); if (!ServiceContainer.Resolve<AuthManager>().OfflineMode) { DrawerListView.AddHeaderView (DrawerUserView); } DrawerListView.Adapter = drawerAdapter = new DrawerListAdapter (); DrawerListView.ItemClick += OnDrawerListViewItemClick; authManager = ServiceContainer.Resolve<AuthManager> (); authManager.PropertyChanged += OnUserChangedEvent; DrawerLayout = FindViewById<DrawerLayout> (Resource.Id.DrawerLayout); DrawerToggle = new ActionBarDrawerToggle (this, DrawerLayout, MainToolbar, Resource.String.EntryName, Resource.String.EntryName); DrawerLayout.SetDrawerShadow (Resource.Drawable.drawershadow, (int)GravityFlags.Start); DrawerLayout.SetDrawerListener (DrawerToggle); var drawerFrameLayout = FindViewById<FrameLayout> (Resource.Id.DrawerFrameLayout); drawerFrameLayout.Touch += (sender, e) => { // Do nothing, just absorb the event // TODO: Improve this dirty solution? }; Timer.OnCreate (this); var lp = new Android.Support.V7.App.ActionBar.LayoutParams (ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent, (int)GravityFlags.Right); MainToolbar.SetNavigationIcon (Resource.Drawable.ic_menu_black_24dp); SetSupportActionBar (MainToolbar); SupportActionBar.SetTitle (Resource.String.MainDrawerTimer); SupportActionBar.SetCustomView (Timer.Root, lp); SupportActionBar.SetDisplayShowCustomEnabled (true); if (state == null) { OpenPage (DrawerListAdapter.TimerPageId); } else { // Restore page stack pageStack.Clear (); var arr = state.GetIntArray (PageStackExtra); if (arr != null) { pageStack.AddRange (arr); } } // Make sure that the user will see newest data when they start the activity ServiceContainer.Resolve<ISyncManager> ().Run (); } public ToolbarModes ToolbarMode { get { return toolbarMode; } set { toolbarMode = value; AdjustToolbar(); } } private void AdjustToolbar() { switch (toolbarMode) { case MainDrawerActivity.ToolbarModes.Timer: SupportActionBar.SetDisplayShowTitleEnabled (false); Timer.Hide = false; break; case MainDrawerActivity.ToolbarModes.Normal: Timer.Hide = true; SupportActionBar.SetDisplayShowTitleEnabled (true); break; } } private void OnUserChangedEvent (object sender, PropertyChangedEventArgs args) { var userData = ServiceContainer.Resolve<AuthManager> ().User; if (userData == null) { return; } DrawerUserName.Text = userData.Name; DrawerEmail.Text = userData.Email; DrawerImage.ImageUrl = userData.ImageUrl; } protected override void OnSaveInstanceState (Bundle outState) { outState.PutIntArray (PageStackExtra, pageStack.ToArray ()); base.OnSaveInstanceState (outState); } public override void OnConfigurationChanged (Android.Content.Res.Configuration newConfig) { base.OnConfigurationChanged (newConfig); DrawerToggle.OnConfigurationChanged (newConfig); } public override bool OnOptionsItemSelected (IMenuItem item) { return DrawerToggle.OnOptionsItemSelected (item) || base.OnOptionsItemSelected (item); } public override void OnBackPressed () { if (pageStack.Count > 0) { pageStack.RemoveAt (pageStack.Count - 1); var pageId = pageStack.Count > 0 ? pageStack [pageStack.Count - 1] : DrawerListAdapter.TimerPageId; OpenPage (pageId); } else { base.OnBackPressed (); } } private void SetMenuSelection (int pos) { DrawerListView.ClearChoices (); DrawerListView.ChoiceMode = (ChoiceMode)ListView.ChoiceModeSingle; DrawerListView.SetItemChecked (pos, true); } public void OpenPage (int id) { if (id == DrawerListAdapter.SettingsPageId) { OpenFragment (settingsFragment.Value); SupportActionBar.SetTitle (Resource.String.MainDrawerSettings); } else if (id == DrawerListAdapter.ReportsPageId) { if (reportFragment.Value.ZoomLevel == ZoomLevel.Week) { SupportActionBar.SetTitle (Resource.String.MainDrawerReportsWeek); } else if (reportFragment.Value.ZoomLevel == ZoomLevel.Month) { SupportActionBar.SetTitle (Resource.String.MainDrawerReportsMonth); } else { SupportActionBar.SetTitle (Resource.String.MainDrawerReportsYear); } OpenFragment (reportFragment.Value); } else if (id == DrawerListAdapter.FeedbackPageId) { SupportActionBar.SetTitle (Resource.String.MainDrawerFeedback); OpenFragment (feedbackFragment.Value); } else if (id == DrawerListAdapter.RegisterUserPageId) { SupportActionBar.SetTitle (Resource.String.MainDrawerSignup); OpenFragment (registerUserFragment.Value); } else { SupportActionBar.SetTitle (Resource.String.MainDrawerTimer); OpenFragment (trackingFragment.Value); } SetMenuSelection (drawerAdapter.GetItemPosition (id)); pageStack.Remove (id); pageStack.Add (id); // Make sure we don't store the timer page as the first page (this is implied) if (pageStack.Count == 1 && id == DrawerListAdapter.TimerPageId) { pageStack.Clear (); } } public void ForgetCurrentUser () { authManager.Forget (); StartAuthActivity (); } public void OpenLogin () { var intent = new Intent (this, typeof (LoginActivity)); StartActivityForResult (intent, LoginActivity.LoginRequestCode); } protected override void OnActivityResult (int requestCode, Result resultCode, Intent data) { if (requestCode == LoginActivity.LoginRequestCode && resultCode == Result.Ok) { OpenInSignup = true; } } protected override void OnResumeActivity () { if (OpenInSignup) { OpenPage (DrawerListAdapter.RegisterUserPageId); OpenInSignup = false; } base.OnResumeActivity (); } private void OpenFragment (Fragment fragment) { var old = FragmentManager.FindFragmentById (Resource.Id.ContentFrameLayout); if (old == null) { FragmentManager.BeginTransaction () .Add (Resource.Id.ContentFrameLayout, fragment) .Commit (); } else if (old != fragment) { // The detach/attach is a workaround for https://code.google.com/p/android/issues/detail?id=42601 FragmentManager.BeginTransaction () .Detach (old) .Replace (Resource.Id.ContentFrameLayout, fragment) .Attach (fragment) .Commit (); } } private void OnDrawerListViewItemClick (object sender, ListView.ItemClickEventArgs e) { // If tap outside options just close drawer if (e.Id == -1) { DrawerLayout.CloseDrawers (); return; } // Configure timer component for selected page: if (e.Id != DrawerListAdapter.TimerPageId) { ToolbarMode = MainDrawerActivity.ToolbarModes.Normal; } else { ToolbarMode = MainDrawerActivity.ToolbarModes.Timer; } if (e.Id == DrawerListAdapter.TimerPageId) { OpenPage (DrawerListAdapter.TimerPageId); } else if (e.Id == DrawerListAdapter.LogoutPageId) { ForgetCurrentUser (); } else if (e.Id == DrawerListAdapter.ReportsPageId) { OpenPage (DrawerListAdapter.ReportsPageId); } else if (e.Id == DrawerListAdapter.SettingsPageId) { OpenPage (DrawerListAdapter.SettingsPageId); } else if (e.Id == DrawerListAdapter.FeedbackPageId) { OpenPage (DrawerListAdapter.FeedbackPageId); } else if (e.Id == DrawerListAdapter.LoginPageId) { OpenLogin (); } DrawerLayout.CloseDrawers (); } public TimerComponent Timer { get { return barTimer; } } public enum ToolbarModes { Normal, Timer } } }
#region Header // -------------------------------------------------------------------------- // Tethys.Silverlight // ========================================================================== // // This library contains common code for WPF, Silverlight, Windows Phone and // Windows 8 projects. // // =========================================================================== // // <copyright file="ExceptionInformation.cs" company="Tethys"> // Copyright 2010-2015 by Thomas Graf // All rights reserved. // Licensed under the Apache License, Version 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. // </copyright> // // System ... Microsoft .Net Framework 4.5 // Tools .... Microsoft Visual Studio 2013 // // --------------------------------------------------------------------------- #endregion namespace Tethys.Silverlight.Diagnostics { using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Reflection; using System.Security.Principal; using System.Text.RegularExpressions; using System.Threading; /// <summary> /// Provides some information about an exception. /// </summary> [Serializable] public class ExceptionInformation { #region PUBLIC PROPERTIES /// <summary> /// Gets or sets the thread that has thrown the exception. /// </summary> public Thread Thread { get; set; } /// <summary> /// Gets or sets the exception for which the information shall get determined. /// </summary> public Exception Exception { get; set; } /// <summary> /// Gets the name of the application domain of the exception. /// </summary> public string AppDomainName { get; private set; } /// <summary> /// Gets the name of the assembly of the exception. /// </summary> public string AssemblyName { get; private set; } /// <summary> /// Gets the thread identifier of the exception. /// </summary> public int ThreadId { get; private set; } /// <summary> /// Gets the thread user of the exception. /// </summary> public string ThreadUser { get; private set; } /// <summary> /// Gets the name of the product of the exception. /// </summary> public string ProductName { get; private set; } /// <summary> /// Gets the product version of the exception. /// </summary> public string ProductVersion { get; private set; } /// <summary> /// Gets the executable path of the exception. /// </summary> public string ExecutablePath { get; private set; } /// <summary> /// Gets the name of the company of the exception. /// </summary> public string CompanyName { get; private set; } /// <summary> /// Gets the installed operating system of the exception. /// </summary> public OperatingSystem OperatingSystem { get; private set; } /// <summary> /// Gets version information of the installed .NET-Framework. /// </summary> public Version FrameworkVersion { get; private set; } /// <summary> /// Gets the physical memory of the active process. /// </summary> public long WorkingSet { get; private set; } #endregion // PUBLIC PROPERTIES //// ---------------------------------------------------------------------- #region CONSTRUCTION /// <summary> /// Initializes a new instance of the <see cref="ExceptionInformation"/> /// class. /// </summary> public ExceptionInformation() { this.Thread = Thread.CurrentThread; } // ExceptionInformation() /// <summary> /// Initializes a new instance of the <see cref="ExceptionInformation"/> /// class. /// </summary> /// <param name="ex">The exception.</param> public ExceptionInformation(Exception ex) : this(ex, null) { } // ExceptionInformation() /// <summary> /// Initializes a new instance of the <see cref="ExceptionInformation"/> /// class. /// </summary> /// <param name="ex">The exception.</param> /// <param name="threadObject">The thread that has thrown the exception. /// </param> public ExceptionInformation(Exception ex, Thread threadObject) : this() { if (ex == null) { throw new ArgumentNullException("ex"); } // if this.Exception = ex; if (threadObject != null) { this.Thread = threadObject; } // if this.Initialize(); } // ExceptionInformation() #endregion // CONSTRUCTION //// ---------------------------------------------------------------------- #region OVERRIDES /// <summary> /// Returns a <see cref="System.String"/> that represents this instance. /// </summary> /// <returns> /// A <see cref="System.String"/> that represents this instance. /// </returns> public new string ToString() { return string.Format("{0}\r\n" + "AppDomain: {1}\r\n" + "ThreadId {2}\r\n" + "ThreadUser: {3}\r\n" + "Productname: {4}\r\n" + "Productversion: {5}\r\n" + "Dateipfad: {6}\r\n" + "Betriebssystem: {7}\r\n" + ".NET-Framework-Version: {8}\r\n", this.Exception, this.AppDomainName, this.ThreadId, this.ThreadUser, this.ProductName, this.ProductVersion, this.ExecutablePath, this.OperatingSystem, this.FrameworkVersion); } // ToString() #endregion // OVERRIDES //// ---------------------------------------------------------------------- #region PUBLIC METHODS /// <summary> /// Gets the name of the method. /// </summary> /// <param name="ex">The exception.</param> /// <returns> /// The method name. /// </returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Ok here.")] public static string GetMethodName(Exception ex) { string methodName; try { // Erstes StackFrame aus StackTrace ermitteln var frame = GetFirstStackFrame(ex); // Klassen- und Funktionsnamen aus StackFrame ermitteln if (frame != null) { var method = frame.GetMethod(); methodName = method.Name + "("; // Methoden-Parameter ermitteln var paramInfos = method.GetParameters(); var methodParams = string.Empty; foreach (var paramInfo in paramInfos) { methodParams += ", " + paramInfo.ParameterType.Name + " " + paramInfo.Name; } // foreach if (methodParams.Length > 2) { methodName += methodParams.Substring(2); } // if methodName += ")"; } else { methodName = GetMethodNameFromStack(ex.StackTrace); } // if } catch { methodName = string.Empty; } // catch return methodName; } // GetMethodName() /// <summary> /// Gets the name of the class. /// </summary> /// <param name="ex">The exception.</param> /// <returns> /// The class name. /// </returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Ok here.")] public static string GetClassName(Exception ex) { var className = string.Empty; try { // Erstes StackFrame aus StackTrace ermitteln var frame = GetFirstStackFrame(ex); // Klassennamen aus StackFrame ermitteln if (frame != null) { var method = frame.GetMethod(); if (method.DeclaringType != null) { className = method.DeclaringType.ToString(); } // if } else { className = GetClassNameFromStack(ex.StackTrace); } // if } catch { className = string.Empty; } // catch return className; } // GetClassName() /// <summary> /// Gets the name of the file. /// </summary> /// <param name="ex">The exception.</param> /// <returns> /// The filename. /// </returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Ok here.")] public static string GetFileName(Exception ex) { string fileName; try { // Erstes StackFrame aus StackTrace ermitteln var frame = GetFirstStackFrame(ex); // Dateinamen aus StackFrame ermitteln if (frame != null) { fileName = frame.GetFileName(); fileName = fileName.Substring(fileName.LastIndexOf("\\", StringComparison.CurrentCulture) + 1); } else { fileName = GetFileNameFromStack(ex.StackTrace); } // if } catch { fileName = string.Empty; } // catch return fileName; } // GetFileName() /// <summary> /// Gets the file column number. /// </summary> /// <param name="ex">The exception.</param> /// <returns> /// The column number. /// </returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Ok here.")] public static int GetFileColumnNumber(Exception ex) { int column; try { // Erstes StackFrame aus StackTrace ermitteln var frame = GetFirstStackFrame(ex); // Dateinamen aus StackFrame ermitteln column = frame.GetFileColumnNumber(); } catch { column = 0; } // catch return column; } // GetFileColumnNumber() /// <summary> /// Gets the file line number. /// </summary> /// <param name="ex">The exception.</param> /// <returns> /// The line number. /// </returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Ok here.")] public static int GetFileLineNumber(Exception ex) { int line; try { // Erstes StackFrame aus StackTrace ermitteln var frame = GetFirstStackFrame(ex); // Dateinamen aus StackFrame ermitteln if (frame != null) { line = frame.GetFileLineNumber(); } else { line = Convert.ToInt32(GetLineNumberFromStack(ex.StackTrace), CultureInfo.CurrentCulture); } // if } catch { line = 0; } // catch return line; } // GetFileLineNumber() /// <summary> /// Gets the IL offset. /// </summary> /// <param name="ex">The exception.</param> /// <returns> /// The offset. /// </returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Ok here.")] public static int GetIlOffset(Exception ex) { int ilOffset; try { // Erstes StackFrame aus StackTrace ermitteln var frame = GetFirstStackFrame(ex); // Dateinamen aus StackFrame ermitteln ilOffset = frame.GetILOffset(); } catch { ilOffset = 0; } // catch return ilOffset; } // GetIlOffset() /// <summary> /// Gets the native offset. /// </summary> /// <param name="ex">The exception.</param> /// <returns>The native offset.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Ok here.")] public static int GetNativeOffset(Exception ex) { int nativeOffset; try { // Erstes StackFrame aus StackTrace ermitteln var frame = GetFirstStackFrame(ex); // Dateinamen aus StackFrame ermitteln nativeOffset = frame.GetNativeOffset(); } catch { nativeOffset = 0; } // catch return nativeOffset; } // GetNativeOffset() /// <summary> /// Gets the stack trace for the specified exception. /// </summary> /// <param name="ex">The exception.</param> /// <returns>The stack trace as string.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Ok here.")] public static string GetStackTrace(Exception ex) { string stackTrace; try { stackTrace = ex.StackTrace ?? string.Empty; } catch { stackTrace = string.Empty; } return stackTrace; } // GetStackTrace() /// <summary> /// Gets the class name from stack. /// </summary> /// <param name="stackTrace">The stack trace.</param> /// <returns>The class name from stack.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Ok here.")] public static string GetClassNameFromStack(string stackTrace) { var className = string.Empty; try { var regClass = new Regex(@" at ([_a-zA-Z0-9\.]+\({1})"); var matchClass = regClass.Match(stackTrace); if (matchClass != null) { className = matchClass.Value.Replace(" at ", string.Empty); className = className.Substring(0, className.LastIndexOf(".")).Trim(); } // if } // ReSharper disable EmptyGeneralCatchClause catch // ReSharper restore EmptyGeneralCatchClause { // ignore } // catch return className; } // GetClassNameFromStack() /// <summary> /// Gets the method name from stack. /// </summary> /// <param name="stackTrace">The stack trace.</param> /// <returns>The method name from stack.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Ok here.")] public static string GetMethodNameFromStack(string stackTrace) { var methodName = string.Empty; try { var regMethod = new Regex(@"\.[_a-zA-Z0-9\, ]+\({1}[_a-zA-Z0-9\, ]+\)"); var matchMethod = regMethod.Match(stackTrace); if (matchMethod != null) { methodName = matchMethod.Value.Replace(".", string.Empty).Trim(); } } // ReSharper disable EmptyGeneralCatchClause catch // ReSharper restore EmptyGeneralCatchClause { // ignore } // catch return methodName; } // GetMethodNameFromStack() /// <summary> /// Gets the file name from stack. /// </summary> /// <param name="stackTrace">The stack trace.</param> /// <returns>The file name from stack.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Ok here.")] public static string GetFileNameFromStack(string stackTrace) { var fileName = string.Empty; try { var regFile = new Regex(@"(\\{1}[_a-zA-Z0-9\.]+\:)"); var matchFile = regFile.Match(stackTrace); if (matchFile != null) { fileName = matchFile.Value.Trim().Replace("\\", string.Empty) .Replace(":", string.Empty); } } // ReSharper disable EmptyGeneralCatchClause catch // ReSharper restore EmptyGeneralCatchClause { // ignore } // catch return fileName; } // GetFileNameFromStack() /// <summary> /// Gets the line number from stack. /// </summary> /// <param name="stackTrace">The stack trace.</param> /// <returns>The line number from stack.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Ok here.")] public static string GetLineNumberFromStack(string stackTrace) { var lineNumber = string.Empty; try { var regLine = new Regex(@"(\:{1}line [1-9]+)"); var matchLine = regLine.Match(stackTrace); if (matchLine != null) { lineNumber = matchLine.Value.Replace(":line", string.Empty).Trim(); } // if } // ReSharper disable EmptyGeneralCatchClause catch // ReSharper restore EmptyGeneralCatchClause { // ignore } // catch return lineNumber; } // GetLineNumberFromStack() #endregion //// ---------------------------------------------------------------------- #region Private Functions /// <summary> /// Gets the first stack frame. /// </summary> /// <param name="ex">The exception.</param> /// <returns>The <see cref="StackFrame"/>.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Ok here.")] private static StackFrame GetFirstStackFrame(Exception ex) { try { // StackTrace aus Exception erstellen var trace = new StackTrace(ex, true); // StackFrame aus StackTrace ermitteln var frame = trace.GetFrame(0); return frame; } catch { return null; } } /// <summary> /// Initializes this instance. /// </summary> private void Initialize() { if (this.Exception != null) { this.AppDomainName = AppDomain.CurrentDomain.FriendlyName; this.AssemblyName = GetAssemblyName(); this.ThreadId = Thread.CurrentThread.ManagedThreadId; this.ThreadUser = GetThreadUser(); this.ProductName = AssemblyInformation.Product; this.ProductVersion = AssemblyInformation.Version; this.ExecutablePath = System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); this.CompanyName = AssemblyInformation.Company; this.OperatingSystem = Environment.OSVersion; this.FrameworkVersion = Environment.Version; this.WorkingSet = Environment.WorkingSet; } // if } // Initialize() /// <summary> /// Gets the thread user. /// </summary> /// <returns>The thread user.</returns> private static string GetThreadUser() { var id = WindowsIdentity.GetCurrent(); if (id != null) { return id.Name; } // if return string.Empty; } // GetThreadUser() /// <summary> /// Gets the name of the assembly. /// </summary> /// <returns>The name of the assembly.</returns> private static string GetAssemblyName() { return Assembly.GetEntryAssembly().GetName(true).Name; } // GetAssemblyName() #endregion } // ExceptionInformation } // Tethys.Silverlight.Diagnostics
// 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.Globalization { /// <remarks> /// Calendar support range: /// Calendar Minimum Maximum /// ========== ========== ========== /// Gregorian 1912/02/18 2051/02/10 /// TaiwanLunisolar 1912/01/01 2050/13/29 /// </remarks> public class TaiwanLunisolarCalendar : EastAsianLunisolarCalendar { // Since // Gregorian Year = Era Year + yearOffset // When Gregorian Year 1912 is year 1, so that // 1912 = 1 + yearOffset // So yearOffset = 1911 private static readonly EraInfo[] s_taiwanLunisolarEraInfo = new EraInfo[] { new EraInfo(1, 1912, 1, 1, 1911, 1, GregorianCalendar.MaxYear - 1911) // era #, start year/month/day, yearOffset, minEraYear }; private readonly GregorianCalendarHelper _helper; private const int MinLunisolarYear = 1912; private const int MaxLunisolarYear = 2050; private static readonly DateTime s_minDate = new DateTime(1912, 2, 18); private static readonly DateTime s_maxDate = new DateTime((new DateTime(2051, 2, 10, 23, 59, 59, 999)).Ticks + 9999); public override DateTime MinSupportedDateTime => s_minDate; public override DateTime MaxSupportedDateTime => s_maxDate; protected override int DaysInYearBeforeMinSupportedYear => // 1911 from ChineseLunisolarCalendar 384; private static readonly int[,] s_yinfo = { /*Y LM Lmon Lday DaysPerMonth D1 D2 D3 D4 D5 D6 D7 D8 D9 D10 D11 D12 D13 #Days 1912 */ { 0, 2, 18, 42192 }, /* 30 29 30 29 29 30 29 29 30 30 29 30 0 354 1913 */ { 0, 2, 6, 53840 }, /* 30 30 29 30 29 29 30 29 29 30 29 30 0 354 1914 */ { 5, 1, 26, 54568 }, /* 30 30 29 30 29 30 29 30 29 29 30 29 30 384 1915 */ { 0, 2, 14, 46400 }, /* 30 29 30 30 29 30 29 30 29 30 29 29 0 354 1916 */ { 0, 2, 3, 54944 }, /* 30 30 29 30 29 30 30 29 30 29 30 29 0 355 1917 */ { 2, 1, 23, 38608 }, /* 30 29 29 30 29 30 30 29 30 30 29 30 29 384 1918 */ { 0, 2, 11, 38320 }, /* 30 29 29 30 29 30 29 30 30 29 30 30 0 355 1919 */ { 7, 2, 1, 18872 }, /* 29 30 29 29 30 29 29 30 30 29 30 30 30 384 1920 */ { 0, 2, 20, 18800 }, /* 29 30 29 29 30 29 29 30 29 30 30 30 0 354 1921 */ { 0, 2, 8, 42160 }, /* 30 29 30 29 29 30 29 29 30 29 30 30 0 354 1922 */ { 5, 1, 28, 45656 }, /* 30 29 30 30 29 29 30 29 29 30 29 30 30 384 1923 */ { 0, 2, 16, 27216 }, /* 29 30 30 29 30 29 30 29 29 30 29 30 0 354 1924 */ { 0, 2, 5, 27968 }, /* 29 30 30 29 30 30 29 30 29 30 29 29 0 354 1925 */ { 4, 1, 24, 44456 }, /* 30 29 30 29 30 30 29 30 30 29 30 29 30 385 1926 */ { 0, 2, 13, 11104 }, /* 29 29 30 29 30 29 30 30 29 30 30 29 0 354 1927 */ { 0, 2, 2, 38256 }, /* 30 29 29 30 29 30 29 30 29 30 30 30 0 355 1928 */ { 2, 1, 23, 18808 }, /* 29 30 29 29 30 29 29 30 29 30 30 30 30 384 1929 */ { 0, 2, 10, 18800 }, /* 29 30 29 29 30 29 29 30 29 30 30 30 0 354 1930 */ { 6, 1, 30, 25776 }, /* 29 30 30 29 29 30 29 29 30 29 30 30 29 383 1931 */ { 0, 2, 17, 54432 }, /* 30 30 29 30 29 30 29 29 30 29 30 29 0 354 1932 */ { 0, 2, 6, 59984 }, /* 30 30 30 29 30 29 30 29 29 30 29 30 0 355 1933 */ { 5, 1, 26, 27976 }, /* 29 30 30 29 30 30 29 30 29 30 29 29 30 384 1934 */ { 0, 2, 14, 23248 }, /* 29 30 29 30 30 29 30 29 30 30 29 30 0 355 1935 */ { 0, 2, 4, 11104 }, /* 29 29 30 29 30 29 30 30 29 30 30 29 0 354 1936 */ { 3, 1, 24, 37744 }, /* 30 29 29 30 29 29 30 30 29 30 30 30 29 384 1937 */ { 0, 2, 11, 37600 }, /* 30 29 29 30 29 29 30 29 30 30 30 29 0 354 1938 */ { 7, 1, 31, 51560 }, /* 30 30 29 29 30 29 29 30 29 30 30 29 30 384 1939 */ { 0, 2, 19, 51536 }, /* 30 30 29 29 30 29 29 30 29 30 29 30 0 354 1940 */ { 0, 2, 8, 54432 }, /* 30 30 29 30 29 30 29 29 30 29 30 29 0 354 1941 */ { 6, 1, 27, 55888 }, /* 30 30 29 30 30 29 30 29 29 30 29 30 29 384 1942 */ { 0, 2, 15, 46416 }, /* 30 29 30 30 29 30 29 30 29 30 29 30 0 355 1943 */ { 0, 2, 5, 22176 }, /* 29 30 29 30 29 30 30 29 30 29 30 29 0 354 1944 */ { 4, 1, 25, 43736 }, /* 30 29 30 29 30 29 30 29 30 30 29 30 30 385 1945 */ { 0, 2, 13, 9680 }, /* 29 29 30 29 29 30 29 30 30 30 29 30 0 354 1946 */ { 0, 2, 2, 37584 }, /* 30 29 29 30 29 29 30 29 30 30 29 30 0 354 1947 */ { 2, 1, 22, 51544 }, /* 30 30 29 29 30 29 29 30 29 30 29 30 30 384 1948 */ { 0, 2, 10, 43344 }, /* 30 29 30 29 30 29 29 30 29 30 29 30 0 354 1949 */ { 7, 1, 29, 46248 }, /* 30 29 30 30 29 30 29 29 30 29 30 29 30 384 1950 */ { 0, 2, 17, 27808 }, /* 29 30 30 29 30 30 29 29 30 29 30 29 0 354 1951 */ { 0, 2, 6, 46416 }, /* 30 29 30 30 29 30 29 30 29 30 29 30 0 355 1952 */ { 5, 1, 27, 21928 }, /* 29 30 29 30 29 30 29 30 30 29 30 29 30 384 1953 */ { 0, 2, 14, 19872 }, /* 29 30 29 29 30 30 29 30 30 29 30 29 0 354 1954 */ { 0, 2, 3, 42416 }, /* 30 29 30 29 29 30 29 30 30 29 30 30 0 355 1955 */ { 3, 1, 24, 21176 }, /* 29 30 29 30 29 29 30 29 30 29 30 30 30 384 1956 */ { 0, 2, 12, 21168 }, /* 29 30 29 30 29 29 30 29 30 29 30 30 0 354 1957 */ { 8, 1, 31, 43344 }, /* 30 29 30 29 30 29 29 30 29 30 29 30 29 383 1958 */ { 0, 2, 18, 59728 }, /* 30 30 30 29 30 29 29 30 29 30 29 30 0 355 1959 */ { 0, 2, 8, 27296 }, /* 29 30 30 29 30 29 30 29 30 29 30 29 0 354 1960 */ { 6, 1, 28, 44368 }, /* 30 29 30 29 30 30 29 30 29 30 29 30 29 384 1961 */ { 0, 2, 15, 43856 }, /* 30 29 30 29 30 29 30 30 29 30 29 30 0 355 1962 */ { 0, 2, 5, 19296 }, /* 29 30 29 29 30 29 30 30 29 30 30 29 0 354 1963 */ { 4, 1, 25, 42352 }, /* 30 29 30 29 29 30 29 30 29 30 30 30 29 384 1964 */ { 0, 2, 13, 42352 }, /* 30 29 30 29 29 30 29 30 29 30 30 30 0 355 1965 */ { 0, 2, 2, 21088 }, /* 29 30 29 30 29 29 30 29 29 30 30 29 0 353 1966 */ { 3, 1, 21, 59696 }, /* 30 30 30 29 30 29 29 30 29 29 30 30 29 384 1967 */ { 0, 2, 9, 55632 }, /* 30 30 29 30 30 29 29 30 29 30 29 30 0 355 1968 */ { 7, 1, 30, 23208 }, /* 29 30 29 30 30 29 30 29 30 29 30 29 30 384 1969 */ { 0, 2, 17, 22176 }, /* 29 30 29 30 29 30 30 29 30 29 30 29 0 354 1970 */ { 0, 2, 6, 38608 }, /* 30 29 29 30 29 30 30 29 30 30 29 30 0 355 1971 */ { 5, 1, 27, 19176 }, /* 29 30 29 29 30 29 30 29 30 30 30 29 30 384 1972 */ { 0, 2, 15, 19152 }, /* 29 30 29 29 30 29 30 29 30 30 29 30 0 354 1973 */ { 0, 2, 3, 42192 }, /* 30 29 30 29 29 30 29 29 30 30 29 30 0 354 1974 */ { 4, 1, 23, 53864 }, /* 30 30 29 30 29 29 30 29 29 30 30 29 30 384 1975 */ { 0, 2, 11, 53840 }, /* 30 30 29 30 29 29 30 29 29 30 29 30 0 354 1976 */ { 8, 1, 31, 54568 }, /* 30 30 29 30 29 30 29 30 29 29 30 29 30 384 1977 */ { 0, 2, 18, 46400 }, /* 30 29 30 30 29 30 29 30 29 30 29 29 0 354 1978 */ { 0, 2, 7, 46752 }, /* 30 29 30 30 29 30 30 29 30 29 30 29 0 355 1979 */ { 6, 1, 28, 38608 }, /* 30 29 29 30 29 30 30 29 30 30 29 30 29 384 1980 */ { 0, 2, 16, 38320 }, /* 30 29 29 30 29 30 29 30 30 29 30 30 0 355 1981 */ { 0, 2, 5, 18864 }, /* 29 30 29 29 30 29 29 30 30 29 30 30 0 354 1982 */ { 4, 1, 25, 42168 }, /* 30 29 30 29 29 30 29 29 30 29 30 30 30 384 1983 */ { 0, 2, 13, 42160 }, /* 30 29 30 29 29 30 29 29 30 29 30 30 0 354 1984 */ { 10, 2, 2, 45656 }, /* 30 29 30 30 29 29 30 29 29 30 29 30 30 384 1985 */ { 0, 2, 20, 27216 }, /* 29 30 30 29 30 29 30 29 29 30 29 30 0 354 1986 */ { 0, 2, 9, 27968 }, /* 29 30 30 29 30 30 29 30 29 30 29 29 0 354 1987 */ { 6, 1, 29, 44448 }, /* 30 29 30 29 30 30 29 30 30 29 30 29 29 384 1988 */ { 0, 2, 17, 43872 }, /* 30 29 30 29 30 29 30 30 29 30 30 29 0 355 1989 */ { 0, 2, 6, 38256 }, /* 30 29 29 30 29 30 29 30 29 30 30 30 0 355 1990 */ { 5, 1, 27, 18808 }, /* 29 30 29 29 30 29 29 30 29 30 30 30 30 384 1991 */ { 0, 2, 15, 18800 }, /* 29 30 29 29 30 29 29 30 29 30 30 30 0 354 1992 */ { 0, 2, 4, 25776 }, /* 29 30 30 29 29 30 29 29 30 29 30 30 0 354 1993 */ { 3, 1, 23, 27216 }, /* 29 30 30 29 30 29 30 29 29 30 29 30 29 383 1994 */ { 0, 2, 10, 59984 }, /* 30 30 30 29 30 29 30 29 29 30 29 30 0 355 1995 */ { 8, 1, 31, 27432 }, /* 29 30 30 29 30 29 30 30 29 29 30 29 30 384 1996 */ { 0, 2, 19, 23232 }, /* 29 30 29 30 30 29 30 29 30 30 29 29 0 354 1997 */ { 0, 2, 7, 43872 }, /* 30 29 30 29 30 29 30 30 29 30 30 29 0 355 1998 */ { 5, 1, 28, 37736 }, /* 30 29 29 30 29 29 30 30 29 30 30 29 30 384 1999 */ { 0, 2, 16, 37600 }, /* 30 29 29 30 29 29 30 29 30 30 30 29 0 354 2000 */ { 0, 2, 5, 51552 }, /* 30 30 29 29 30 29 29 30 29 30 30 29 0 354 2001 */ { 4, 1, 24, 54440 }, /* 30 30 29 30 29 30 29 29 30 29 30 29 30 384 2002 */ { 0, 2, 12, 54432 }, /* 30 30 29 30 29 30 29 29 30 29 30 29 0 354 2003 */ { 0, 2, 1, 55888 }, /* 30 30 29 30 30 29 30 29 29 30 29 30 0 355 2004 */ { 2, 1, 22, 23208 }, /* 29 30 29 30 30 29 30 29 30 29 30 29 30 384 2005 */ { 0, 2, 9, 22176 }, /* 29 30 29 30 29 30 30 29 30 29 30 29 0 354 2006 */ { 7, 1, 29, 43736 }, /* 30 29 30 29 30 29 30 29 30 30 29 30 30 385 2007 */ { 0, 2, 18, 9680 }, /* 29 29 30 29 29 30 29 30 30 30 29 30 0 354 2008 */ { 0, 2, 7, 37584 }, /* 30 29 29 30 29 29 30 29 30 30 29 30 0 354 2009 */ { 5, 1, 26, 51544 }, /* 30 30 29 29 30 29 29 30 29 30 29 30 30 384 2010 */ { 0, 2, 14, 43344 }, /* 30 29 30 29 30 29 29 30 29 30 29 30 0 354 2011 */ { 0, 2, 3, 46240 }, /* 30 29 30 30 29 30 29 29 30 29 30 29 0 354 2012 */ { 4, 1, 23, 46416 }, /* 30 29 30 30 29 30 29 30 29 30 29 30 29 384 2013 */ { 0, 2, 10, 44368 }, /* 30 29 30 29 30 30 29 30 29 30 29 30 0 355 2014 */ { 9, 1, 31, 21928 }, /* 29 30 29 30 29 30 29 30 30 29 30 29 30 384 2015 */ { 0, 2, 19, 19360 }, /* 29 30 29 29 30 29 30 30 30 29 30 29 0 354 2016 */ { 0, 2, 8, 42416 }, /* 30 29 30 29 29 30 29 30 30 29 30 30 0 355 2017 */ { 6, 1, 28, 21176 }, /* 29 30 29 30 29 29 30 29 30 29 30 30 30 384 2018 */ { 0, 2, 16, 21168 }, /* 29 30 29 30 29 29 30 29 30 29 30 30 0 354 2019 */ { 0, 2, 5, 43312 }, /* 30 29 30 29 30 29 29 30 29 29 30 30 0 354 2020 */ { 4, 1, 25, 29864 }, /* 29 30 30 30 29 30 29 29 30 29 30 29 30 384 2021 */ { 0, 2, 12, 27296 }, /* 29 30 30 29 30 29 30 29 30 29 30 29 0 354 2022 */ { 0, 2, 1, 44368 }, /* 30 29 30 29 30 30 29 30 29 30 29 30 0 355 2023 */ { 2, 1, 22, 19880 }, /* 29 30 29 29 30 30 29 30 30 29 30 29 30 384 2024 */ { 0, 2, 10, 19296 }, /* 29 30 29 29 30 29 30 30 29 30 30 29 0 354 2025 */ { 6, 1, 29, 42352 }, /* 30 29 30 29 29 30 29 30 29 30 30 30 29 384 2026 */ { 0, 2, 17, 42208 }, /* 30 29 30 29 29 30 29 29 30 30 30 29 0 354 2027 */ { 0, 2, 6, 53856 }, /* 30 30 29 30 29 29 30 29 29 30 30 29 0 354 2028 */ { 5, 1, 26, 59696 }, /* 30 30 30 29 30 29 29 30 29 29 30 30 29 384 2029 */ { 0, 2, 13, 54576 }, /* 30 30 29 30 29 30 29 30 29 29 30 30 0 355 2030 */ { 0, 2, 3, 23200 }, /* 29 30 29 30 30 29 30 29 30 29 30 29 0 354 2031 */ { 3, 1, 23, 27472 }, /* 29 30 30 29 30 29 30 30 29 30 29 30 29 384 2032 */ { 0, 2, 11, 38608 }, /* 30 29 29 30 29 30 30 29 30 30 29 30 0 355 2033 */ { 11, 1, 31, 19176 }, /* 29 30 29 29 30 29 30 29 30 30 30 29 30 384 2034 */ { 0, 2, 19, 19152 }, /* 29 30 29 29 30 29 30 29 30 30 29 30 0 354 2035 */ { 0, 2, 8, 42192 }, /* 30 29 30 29 29 30 29 29 30 30 29 30 0 354 2036 */ { 6, 1, 28, 53848 }, /* 30 30 29 30 29 29 30 29 29 30 29 30 30 384 2037 */ { 0, 2, 15, 53840 }, /* 30 30 29 30 29 29 30 29 29 30 29 30 0 354 2038 */ { 0, 2, 4, 54560 }, /* 30 30 29 30 29 30 29 30 29 29 30 29 0 354 2039 */ { 5, 1, 24, 55968 }, /* 30 30 29 30 30 29 30 29 30 29 30 29 29 384 2040 */ { 0, 2, 12, 46496 }, /* 30 29 30 30 29 30 29 30 30 29 30 29 0 355 2041 */ { 0, 2, 1, 22224 }, /* 29 30 29 30 29 30 30 29 30 30 29 30 0 355 2042 */ { 2, 1, 22, 19160 }, /* 29 30 29 29 30 29 30 29 30 30 29 30 30 384 2043 */ { 0, 2, 10, 18864 }, /* 29 30 29 29 30 29 29 30 30 29 30 30 0 354 2044 */ { 7, 1, 30, 42168 }, /* 30 29 30 29 29 30 29 29 30 29 30 30 30 384 2045 */ { 0, 2, 17, 42160 }, /* 30 29 30 29 29 30 29 29 30 29 30 30 0 354 2046 */ { 0, 2, 6, 43600 }, /* 30 29 30 29 30 29 30 29 29 30 29 30 0 354 2047 */ { 5, 1, 26, 46376 }, /* 30 29 30 30 29 30 29 30 29 29 30 29 30 384 2048 */ { 0, 2, 14, 27936 }, /* 29 30 30 29 30 30 29 30 29 29 30 29 0 354 2049 */ { 0, 2, 2, 44448 }, /* 30 29 30 29 30 30 29 30 30 29 30 29 0 355 2050 */ { 3, 1, 23, 21936 }, /* 29 30 29 30 29 30 29 30 30 29 30 30 29 384 */ }; internal override int MinCalendarYear => MinLunisolarYear; internal override int MaxCalendarYear => MaxLunisolarYear; internal override DateTime MinDate => s_minDate; internal override DateTime MaxDate => s_maxDate; internal override EraInfo[]? CalEraInfo => s_taiwanLunisolarEraInfo; internal override int GetYearInfo(int lunarYear, int index) { if ((lunarYear < MinLunisolarYear) || (lunarYear > MaxLunisolarYear)) { throw new ArgumentOutOfRangeException( "year", lunarYear, SR.Format(SR.ArgumentOutOfRange_Range, MinLunisolarYear, MaxLunisolarYear)); } return s_yinfo[lunarYear - MinLunisolarYear, index]; } internal override int GetYear(int year, DateTime time) { return _helper.GetYear(year, time); } internal override int GetGregorianYear(int year, int era) { return _helper.GetGregorianYear(year, era); } public TaiwanLunisolarCalendar() { _helper = new GregorianCalendarHelper(this, s_taiwanLunisolarEraInfo); } public override int GetEra(DateTime time) => _helper.GetEra(time); internal override CalendarId BaseCalendarID => CalendarId.TAIWAN; internal override CalendarId ID => CalendarId.TAIWANLUNISOLAR; public override int[] Eras => _helper.Eras; } }
//+----------------------------------------------------------------------- // // Microsoft Windows Client Platform // Copyright (C) Microsoft Corporation, 2002 // // File: FontFamilyConverter.cs // // Contents: FontFamilyConverter implementation // // Spec: http://team/sites/Avalon/Specs/Fonts.htm // // Created: 2-1-2005 Niklas Borson (niklasb) // //------------------------------------------------------------------------ using System; using System.ComponentModel; using System.ComponentModel.Design.Serialization; using System.Diagnostics; using System.Globalization; using System.Windows.Navigation; using System.Windows.Markup; using SR=MS.Internal.PresentationCore.SR; using SRID=MS.Internal.PresentationCore.SRID; // Allow suppression of presharp warnings #pragma warning disable 1634, 1691 namespace System.Windows.Media { /// <summary> /// FontFamilyConverter - converter class for converting between the FontFamily /// and String types. /// </summary> public class FontFamilyConverter : TypeConverter { /// <summary> /// CanConvertFrom - Returns whether or not the given type can be converted to a /// FontFamily. /// </summary> public override bool CanConvertFrom(ITypeDescriptorContext td, Type t) { return t == typeof(string); } /// <summary> /// CanConvertTo - Returns whether or not this class can convert to the specified type. /// Conversion is possible only if the source and destination types are FontFamily and /// string, respectively, and the font family is not anonymous (i.e., the Source propery /// is not null). /// </summary> /// <param name="context">ITypeDescriptorContext</param> /// <param name="destinationType">Type to convert to</param> /// <returns>true if conversion is possible</returns> public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { if (destinationType == typeof(string)) { if (context != null) { // When serializing to XAML we want to write the FontFamily as an attribute if and // only if it's a named font family. FontFamily fontFamily = context.Instance as FontFamily; // Suppress PRESharp warning that fontFamily can be null; apparently PRESharp // doesn't understand short circuit evaluation of operator &&. #pragma warning suppress 56506 return fontFamily != null && fontFamily.Source != null && fontFamily.Source.Length != 0; } else { // Some clients call typeConverter.CanConvertTo(typeof(string)), in which case we // don't have the FontFamily instance to convert. Most font families are named, and // we can always give some kind of name, so return true. return true; } } else if (destinationType == typeof(FontFamily)) { return true; } return base.CanConvertTo(context, destinationType); } /// <summary> /// ConvertFrom - Converts the specified object to a FontFamily. /// </summary> public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo cultureInfo, object o) { if ((o != null) && (o.GetType() == typeof(string))) { string s = o as string; if (s == null || s.Length == 0) { throw GetConvertFromException(s); } // Logic below is similar to TypeConverterHelper.GetUriFromUriContext, // except that we cannot treat font family string as a Uri, // and that we handle cases when context is null. Uri baseUri = null; if (context != null) { IUriContext iuc = (IUriContext)context.GetService(typeof(IUriContext)); if (iuc != null) { if (iuc.BaseUri != null) { baseUri = iuc.BaseUri; if (!baseUri.IsAbsoluteUri) { baseUri = new Uri(BaseUriHelper.BaseUri, baseUri); } } else { // If we reach here, the base uri we got from IUriContext is "". // Here we resolve it to application's base baseUri = BaseUriHelper.BaseUri; } } } return new FontFamily(baseUri, s); } return base.ConvertFrom(context, cultureInfo, o); ; } /// <summary> /// ConvertTo - Converts the specified object to an instance of the specified type. /// </summary> public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { if (null == value) { throw new ArgumentNullException("value"); } FontFamily fontFamily = value as FontFamily; if (fontFamily == null) { throw new ArgumentException(SR.Get(SRID.General_Expected_Type, "FontFamily"), "value"); } if (null == destinationType) { throw new ArgumentNullException("destinationType"); } if (destinationType == typeof(string)) { if (fontFamily.Source != null) { // Usual case: it's a named font family. return fontFamily.Source; } else { // If client calls typeConverter.CanConvertTo(typeof(string)) then we'll return // true always, even though we don't have access to the FontFamily instance; so // we need to be able to return some kind of family name even if Source==null. string name = null; CultureInfo parentCulture = null; if (culture != null) { if (culture.Equals(CultureInfo.InvariantCulture)) { culture = null; } else { parentCulture = culture.Parent; if (parentCulture != null && (parentCulture.Equals(CultureInfo.InvariantCulture) || parentCulture == culture)) { parentCulture = null; } } } // Try looking up the name in the FamilyNames dictionary. LanguageSpecificStringDictionary names = fontFamily.FamilyNames; if (culture != null && names.TryGetValue(XmlLanguage.GetLanguage(culture.IetfLanguageTag), out name)) { // LanguageSpecificStringDictionary does not allow null string to be added. Debug.Assert(name != null); } else if (parentCulture != null && names.TryGetValue(XmlLanguage.GetLanguage(parentCulture.IetfLanguageTag), out name)) { // LanguageSpecificStringDictionary does not allow null string to be added. Debug.Assert(name != null); } else if (names.TryGetValue(XmlLanguage.Empty, out name)) { // LanguageSpecificStringDictionary does not allow null string to be added. Debug.Assert(name != null); } else { // Try the first target font compatible with the culture. foreach (FontFamilyMap familyMap in fontFamily.FamilyMaps) { if (FontFamilyMap.MatchCulture(familyMap.Language, culture)) { name = familyMap.Target; break; } } // Use global ui as a last resort. if (name == null) name = FontFamily.GlobalUI; } return name; } } return base.ConvertTo(context, culture, value, destinationType); } } }
using System; using System.Collections.Generic; using NiL.JS.Core; using NiL.JS.Statements; using NiL.JS.Core.Interop; namespace NiL.JS { [Flags] public enum Options { None = 0, SuppressUselessExpressionsElimination = 1, SuppressUselessStatementsElimination = 2, SuppressConstantPropogation = 4, } public enum ModuleEvaluationState { Default = 0, Evaluating, Evaluated, Fail, } /// <summary> /// Represents and manages JavaScript module /// </summary> public class Module { private static readonly char[] _pathSplitChars = new[] { '\\', '/' }; public ExportTable Exports { get; } = new ExportTable(); public List<IModuleResolver> ModuleResolversChain { get; } = new List<IModuleResolver>(); public ModuleEvaluationState EvaluationState { get; private set; } /// <summary> /// Root node of AST /// </summary> [Obsolete] public CodeBlock Root => Script.Root; /// <summary> /// JavaScript code, used for initialization /// </summary> [Obsolete] public string Code => Script.Code; /// <summary> /// The script of the module /// </summary> public Script Script { get; private set; } /// <summary> /// Root context of module /// </summary> public Context Context { get; private set; } /// <summary> /// Path to file with script /// </summary> public string FilePath { get; private set; } /// <summary> /// Initializes a new Module with specified code. /// </summary> /// <param name="code">JavaScript code.</param> public Module(string code) : this(code, null, Options.None) { } /// <summary> /// Initializes a new Module with specified code. /// </summary> /// <param name="path">Path to file with script. Used for resolving paths to other modules for importing via import directive. Can be null or empty</param> /// <param name="code">JavaScript code.</param> /// <param name="globalContext">Global context</param> public Module(string path, string code, GlobalContext globalContext) : this(path, code, null, Options.None, globalContext) { } /// <summary> /// Initializes a new Module with specified code. /// </summary> /// <param name="path">Path to file with script. Used for resolving paths to other modules for importing via import directive. Can be null or empty</param> /// <param name="code">JavaScript code.</param> public Module(string path, string code) : this(path, code, null, Options.None) { } /// <summary> /// Initializes a new Module with specified code and callback for output compiler messages. /// </summary> /// <param name="code">JavaScript code.</param> /// <param name="messageCallback">Callback used to output compiler messages</param> public Module(string code, CompilerMessageCallback messageCallback) : this(code, messageCallback, Options.None) { } /// <summary> /// Initializes a new Module with specified code and callback for output compiler messages. /// </summary> /// <param name="virtualPath">Path to file with script. Used for resolving paths to other modules for importing via import directive. Can be null or empty</param> /// <param name="code">JavaScript code.</param> /// <param name="messageCallback">Callback used to output compiler messages</param> public Module(string virtualPath, string code, CompilerMessageCallback messageCallback) : this(virtualPath, code, messageCallback, Options.None) { } /// <summary> /// Initializes a new Module with specified code, callback for output compiler messages and compiler options. /// </summary> /// <param name="code">JavaScript code.</param> /// <param name="messageCallback">Callback used to output compiler messages or null</param> /// <param name="options">Compiler options</param> public Module(string code, CompilerMessageCallback messageCallback, Options options) : this(null, code, messageCallback, options) { } /// <summary> /// Initializes a new Module with specified code, callback for output compiler messages and compiler options. /// </summary> /// <param name="code">JavaScript code.</param> /// <param name="messageCallback">Callback used to output compiler messages or null</param> /// <param name="options">Compiler options</param> /// <param name="globalContext">Global context</param> public Module(string code, CompilerMessageCallback messageCallback, Options options, GlobalContext globalContext) : this(null, code, messageCallback, options, globalContext) { } /// <summary> /// Initializes a new Module with specified code, callback for output compiler messages and compiler options. /// </summary> /// <param name="virtualPath">Path to file with script. Used for resolving paths to other modules for importing via import directive. Can be null or empty</param> /// <param name="code">JavaScript code.</param> /// <param name="messageCallback">Callback used to output compiler messages or null</param> /// <param name="options">Compiler options</param> public Module(string virtualPath, string code, CompilerMessageCallback messageCallback = null, Options options = Options.None, GlobalContext globalContext = null) : this(virtualPath, Script.Parse(code, messageCallback, options), globalContext) { } /// <summary> /// Initializes a new Module with a script. /// </summary> /// <param name="virtualPath">Path to file with script. Used for resolving paths to other modules for importing via import directive. Can be null or empty</param> /// <param name="script">The module script</param> /// <param name="globalContext">Global context</param> public Module(string virtualPath, Script script, GlobalContext globalContext = null) { if (script == null) throw new ArgumentNullException(); FilePath = virtualPath; Context = new Context(globalContext ?? Context.CurrentGlobalContext, true, null); Context._module = this; Context._thisBind = new GlobalObject(Context); Script = script; Context._strict = Script.Root._strict; } public Module() : this("") { } /// <summary> /// Run the script /// </summary> public void Run() { EvaluationState = ModuleEvaluationState.Evaluating; Script.Evaluate(Context); EvaluationState = ModuleEvaluationState.Evaluated; } /// <summary> /// Run the script with time limit /// </summary> /// <param name="timeLimitInMilliseconds">Time limit</param> public void Run(int timeLimitInMilliseconds) { var start = Environment.TickCount; var oldDebugValue = Context.Debugging; Context.Debugging = true; DebuggerCallback callback = (context, e) => { if (Environment.TickCount - start >= timeLimitInMilliseconds) throw new TimeoutException(); }; Context.DebuggerCallback += callback; try { Run(); } catch { EvaluationState = ModuleEvaluationState.Fail; throw; } finally { Context.Debugging = oldDebugValue; Context.DebuggerCallback -= callback; } } internal Module Import(string importArg) { var request = new ModuleRequest(this, importArg, makeAbsolutePath(this, importArg)); Module module = null; for (var i = 0; i < ModuleResolversChain.Count; i++) { if (ModuleResolversChain[i].TryGetModule(request, out module)) break; module = null; } if (module == null) throw new InvalidOperationException("Unable to load module \"" + request.CmdArgument + "\""); if (module.FilePath == null) module.FilePath = request.AbsolutePath; if (module.EvaluationState == ModuleEvaluationState.Default) { module.ModuleResolversChain.AddRange(ModuleResolversChain); module.Run(); } return module; } private static string makeAbsolutePath(Module initiator, string path) { var thisName = initiator.FilePath.Split(_pathSplitChars); var requestedName = path.Split(_pathSplitChars); var pathTokens = new LinkedList<string>(thisName); if (requestedName.Length > 0 && requestedName[0] == "" || requestedName[0].EndsWith(":")) pathTokens.Clear(); else pathTokens.RemoveLast(); for (var i = 0; i < requestedName.Length; i++) pathTokens.AddLast(requestedName[i]); for (var node = pathTokens.First; node != null;) { if (node.Value == "." || (node.Value == "" && node.Previous != pathTokens.First)) { node = node.Next; pathTokens.Remove(node.Previous); } else if (node.Value == ".." && node.Previous != null) { node = node.Next; pathTokens.Remove(node.Previous); pathTokens.Remove(node.Previous); } else node = node.Next; } if (pathTokens.Last.Value.IndexOf('.') == -1) pathTokens.Last.Value = pathTokens.Last.Value + ".js"; if (pathTokens.Count == 0 || !pathTokens.First.Value.EndsWith(":")) pathTokens.AddFirst(""); return string.Join("/", pathTokens); } #if !NETCORE /// <summary> /// Returns module, which provides access to clr-namespace /// </summary> /// <param name="namespace">Namespace</param> /// <returns></returns> public static Module ClrNamespace(string @namespace) { var result = new Module(); foreach (var type in NamespaceProvider.GetTypesByPrefix(@namespace)) { try { if (type.Namespace == @namespace) { result.Exports[type.Name] = Context.CurrentGlobalContext.GetConstructor(type); } else if (type.Namespace.StartsWith(@namespace) && type.Namespace[@namespace.Length] == '.') { var nextSegment = type.Namespace.Substring(@namespace.Length).Split('.')[1]; result.Exports[nextSegment] = new NamespaceProvider($"{@namespace}.{nextSegment}"); } } catch { } } return result; } #endif } }
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the codedeploy-2014-10-06.normal.json service model. */ using System; using Amazon.Runtime; namespace Amazon.CodeDeploy { /// <summary> /// Constants used for properties of type ApplicationRevisionSortBy. /// </summary> public class ApplicationRevisionSortBy : ConstantClass { /// <summary> /// Constant FirstUsedTime for ApplicationRevisionSortBy /// </summary> public static readonly ApplicationRevisionSortBy FirstUsedTime = new ApplicationRevisionSortBy("firstUsedTime"); /// <summary> /// Constant LastUsedTime for ApplicationRevisionSortBy /// </summary> public static readonly ApplicationRevisionSortBy LastUsedTime = new ApplicationRevisionSortBy("lastUsedTime"); /// <summary> /// Constant RegisterTime for ApplicationRevisionSortBy /// </summary> public static readonly ApplicationRevisionSortBy RegisterTime = new ApplicationRevisionSortBy("registerTime"); /// <summary> /// Default Constructor /// </summary> public ApplicationRevisionSortBy(string value) : base(value) { } /// <summary> /// Finds the constant for the unique value. /// </summary> /// <param name="value">The unique value for the constant</param> /// <returns>The constant for the unique value</returns> public static ApplicationRevisionSortBy FindValue(string value) { return FindValue<ApplicationRevisionSortBy>(value); } /// <summary> /// Utility method to convert strings to the constant class. /// </summary> /// <param name="value">The string value to convert to the constant class.</param> /// <returns></returns> public static implicit operator ApplicationRevisionSortBy(string value) { return FindValue(value); } } /// <summary> /// Constants used for properties of type BundleType. /// </summary> public class BundleType : ConstantClass { /// <summary> /// Constant Tar for BundleType /// </summary> public static readonly BundleType Tar = new BundleType("tar"); /// <summary> /// Constant Tgz for BundleType /// </summary> public static readonly BundleType Tgz = new BundleType("tgz"); /// <summary> /// Constant Zip for BundleType /// </summary> public static readonly BundleType Zip = new BundleType("zip"); /// <summary> /// Default Constructor /// </summary> public BundleType(string value) : base(value) { } /// <summary> /// Finds the constant for the unique value. /// </summary> /// <param name="value">The unique value for the constant</param> /// <returns>The constant for the unique value</returns> public static BundleType FindValue(string value) { return FindValue<BundleType>(value); } /// <summary> /// Utility method to convert strings to the constant class. /// </summary> /// <param name="value">The string value to convert to the constant class.</param> /// <returns></returns> public static implicit operator BundleType(string value) { return FindValue(value); } } /// <summary> /// Constants used for properties of type DeploymentCreator. /// </summary> public class DeploymentCreator : ConstantClass { /// <summary> /// Constant Autoscaling for DeploymentCreator /// </summary> public static readonly DeploymentCreator Autoscaling = new DeploymentCreator("autoscaling"); /// <summary> /// Constant User for DeploymentCreator /// </summary> public static readonly DeploymentCreator User = new DeploymentCreator("user"); /// <summary> /// Default Constructor /// </summary> public DeploymentCreator(string value) : base(value) { } /// <summary> /// Finds the constant for the unique value. /// </summary> /// <param name="value">The unique value for the constant</param> /// <returns>The constant for the unique value</returns> public static DeploymentCreator FindValue(string value) { return FindValue<DeploymentCreator>(value); } /// <summary> /// Utility method to convert strings to the constant class. /// </summary> /// <param name="value">The string value to convert to the constant class.</param> /// <returns></returns> public static implicit operator DeploymentCreator(string value) { return FindValue(value); } } /// <summary> /// Constants used for properties of type DeploymentStatus. /// </summary> public class DeploymentStatus : ConstantClass { /// <summary> /// Constant Created for DeploymentStatus /// </summary> public static readonly DeploymentStatus Created = new DeploymentStatus("Created"); /// <summary> /// Constant Failed for DeploymentStatus /// </summary> public static readonly DeploymentStatus Failed = new DeploymentStatus("Failed"); /// <summary> /// Constant InProgress for DeploymentStatus /// </summary> public static readonly DeploymentStatus InProgress = new DeploymentStatus("InProgress"); /// <summary> /// Constant Queued for DeploymentStatus /// </summary> public static readonly DeploymentStatus Queued = new DeploymentStatus("Queued"); /// <summary> /// Constant Stopped for DeploymentStatus /// </summary> public static readonly DeploymentStatus Stopped = new DeploymentStatus("Stopped"); /// <summary> /// Constant Succeeded for DeploymentStatus /// </summary> public static readonly DeploymentStatus Succeeded = new DeploymentStatus("Succeeded"); /// <summary> /// Default Constructor /// </summary> public DeploymentStatus(string value) : base(value) { } /// <summary> /// Finds the constant for the unique value. /// </summary> /// <param name="value">The unique value for the constant</param> /// <returns>The constant for the unique value</returns> public static DeploymentStatus FindValue(string value) { return FindValue<DeploymentStatus>(value); } /// <summary> /// Utility method to convert strings to the constant class. /// </summary> /// <param name="value">The string value to convert to the constant class.</param> /// <returns></returns> public static implicit operator DeploymentStatus(string value) { return FindValue(value); } } /// <summary> /// Constants used for properties of type EC2TagFilterType. /// </summary> public class EC2TagFilterType : ConstantClass { /// <summary> /// Constant KEY_AND_VALUE for EC2TagFilterType /// </summary> public static readonly EC2TagFilterType KEY_AND_VALUE = new EC2TagFilterType("KEY_AND_VALUE"); /// <summary> /// Constant KEY_ONLY for EC2TagFilterType /// </summary> public static readonly EC2TagFilterType KEY_ONLY = new EC2TagFilterType("KEY_ONLY"); /// <summary> /// Constant VALUE_ONLY for EC2TagFilterType /// </summary> public static readonly EC2TagFilterType VALUE_ONLY = new EC2TagFilterType("VALUE_ONLY"); /// <summary> /// Default Constructor /// </summary> public EC2TagFilterType(string value) : base(value) { } /// <summary> /// Finds the constant for the unique value. /// </summary> /// <param name="value">The unique value for the constant</param> /// <returns>The constant for the unique value</returns> public static EC2TagFilterType FindValue(string value) { return FindValue<EC2TagFilterType>(value); } /// <summary> /// Utility method to convert strings to the constant class. /// </summary> /// <param name="value">The string value to convert to the constant class.</param> /// <returns></returns> public static implicit operator EC2TagFilterType(string value) { return FindValue(value); } } /// <summary> /// Constants used for properties of type ErrorCode. /// </summary> public class ErrorCode : ConstantClass { /// <summary> /// Constant APPLICATION_MISSING for ErrorCode /// </summary> public static readonly ErrorCode APPLICATION_MISSING = new ErrorCode("APPLICATION_MISSING"); /// <summary> /// Constant DEPLOYMENT_GROUP_MISSING for ErrorCode /// </summary> public static readonly ErrorCode DEPLOYMENT_GROUP_MISSING = new ErrorCode("DEPLOYMENT_GROUP_MISSING"); /// <summary> /// Constant HEALTH_CONSTRAINTS for ErrorCode /// </summary> public static readonly ErrorCode HEALTH_CONSTRAINTS = new ErrorCode("HEALTH_CONSTRAINTS"); /// <summary> /// Constant HEALTH_CONSTRAINTS_INVALID for ErrorCode /// </summary> public static readonly ErrorCode HEALTH_CONSTRAINTS_INVALID = new ErrorCode("HEALTH_CONSTRAINTS_INVALID"); /// <summary> /// Constant IAM_ROLE_MISSING for ErrorCode /// </summary> public static readonly ErrorCode IAM_ROLE_MISSING = new ErrorCode("IAM_ROLE_MISSING"); /// <summary> /// Constant IAM_ROLE_PERMISSIONS for ErrorCode /// </summary> public static readonly ErrorCode IAM_ROLE_PERMISSIONS = new ErrorCode("IAM_ROLE_PERMISSIONS"); /// <summary> /// Constant INTERNAL_ERROR for ErrorCode /// </summary> public static readonly ErrorCode INTERNAL_ERROR = new ErrorCode("INTERNAL_ERROR"); /// <summary> /// Constant NO_EC2_SUBSCRIPTION for ErrorCode /// </summary> public static readonly ErrorCode NO_EC2_SUBSCRIPTION = new ErrorCode("NO_EC2_SUBSCRIPTION"); /// <summary> /// Constant NO_INSTANCES for ErrorCode /// </summary> public static readonly ErrorCode NO_INSTANCES = new ErrorCode("NO_INSTANCES"); /// <summary> /// Constant OVER_MAX_INSTANCES for ErrorCode /// </summary> public static readonly ErrorCode OVER_MAX_INSTANCES = new ErrorCode("OVER_MAX_INSTANCES"); /// <summary> /// Constant REVISION_MISSING for ErrorCode /// </summary> public static readonly ErrorCode REVISION_MISSING = new ErrorCode("REVISION_MISSING"); /// <summary> /// Constant THROTTLED for ErrorCode /// </summary> public static readonly ErrorCode THROTTLED = new ErrorCode("THROTTLED"); /// <summary> /// Constant TIMEOUT for ErrorCode /// </summary> public static readonly ErrorCode TIMEOUT = new ErrorCode("TIMEOUT"); /// <summary> /// Default Constructor /// </summary> public ErrorCode(string value) : base(value) { } /// <summary> /// Finds the constant for the unique value. /// </summary> /// <param name="value">The unique value for the constant</param> /// <returns>The constant for the unique value</returns> public static ErrorCode FindValue(string value) { return FindValue<ErrorCode>(value); } /// <summary> /// Utility method to convert strings to the constant class. /// </summary> /// <param name="value">The string value to convert to the constant class.</param> /// <returns></returns> public static implicit operator ErrorCode(string value) { return FindValue(value); } } /// <summary> /// Constants used for properties of type InstanceStatus. /// </summary> public class InstanceStatus : ConstantClass { /// <summary> /// Constant Failed for InstanceStatus /// </summary> public static readonly InstanceStatus Failed = new InstanceStatus("Failed"); /// <summary> /// Constant InProgress for InstanceStatus /// </summary> public static readonly InstanceStatus InProgress = new InstanceStatus("InProgress"); /// <summary> /// Constant Pending for InstanceStatus /// </summary> public static readonly InstanceStatus Pending = new InstanceStatus("Pending"); /// <summary> /// Constant Skipped for InstanceStatus /// </summary> public static readonly InstanceStatus Skipped = new InstanceStatus("Skipped"); /// <summary> /// Constant Succeeded for InstanceStatus /// </summary> public static readonly InstanceStatus Succeeded = new InstanceStatus("Succeeded"); /// <summary> /// Constant Unknown for InstanceStatus /// </summary> public static readonly InstanceStatus Unknown = new InstanceStatus("Unknown"); /// <summary> /// Default Constructor /// </summary> public InstanceStatus(string value) : base(value) { } /// <summary> /// Finds the constant for the unique value. /// </summary> /// <param name="value">The unique value for the constant</param> /// <returns>The constant for the unique value</returns> public static InstanceStatus FindValue(string value) { return FindValue<InstanceStatus>(value); } /// <summary> /// Utility method to convert strings to the constant class. /// </summary> /// <param name="value">The string value to convert to the constant class.</param> /// <returns></returns> public static implicit operator InstanceStatus(string value) { return FindValue(value); } } /// <summary> /// Constants used for properties of type LifecycleErrorCode. /// </summary> public class LifecycleErrorCode : ConstantClass { /// <summary> /// Constant ScriptFailed for LifecycleErrorCode /// </summary> public static readonly LifecycleErrorCode ScriptFailed = new LifecycleErrorCode("ScriptFailed"); /// <summary> /// Constant ScriptMissing for LifecycleErrorCode /// </summary> public static readonly LifecycleErrorCode ScriptMissing = new LifecycleErrorCode("ScriptMissing"); /// <summary> /// Constant ScriptNotExecutable for LifecycleErrorCode /// </summary> public static readonly LifecycleErrorCode ScriptNotExecutable = new LifecycleErrorCode("ScriptNotExecutable"); /// <summary> /// Constant ScriptTimedOut for LifecycleErrorCode /// </summary> public static readonly LifecycleErrorCode ScriptTimedOut = new LifecycleErrorCode("ScriptTimedOut"); /// <summary> /// Constant Success for LifecycleErrorCode /// </summary> public static readonly LifecycleErrorCode Success = new LifecycleErrorCode("Success"); /// <summary> /// Constant UnknownError for LifecycleErrorCode /// </summary> public static readonly LifecycleErrorCode UnknownError = new LifecycleErrorCode("UnknownError"); /// <summary> /// Default Constructor /// </summary> public LifecycleErrorCode(string value) : base(value) { } /// <summary> /// Finds the constant for the unique value. /// </summary> /// <param name="value">The unique value for the constant</param> /// <returns>The constant for the unique value</returns> public static LifecycleErrorCode FindValue(string value) { return FindValue<LifecycleErrorCode>(value); } /// <summary> /// Utility method to convert strings to the constant class. /// </summary> /// <param name="value">The string value to convert to the constant class.</param> /// <returns></returns> public static implicit operator LifecycleErrorCode(string value) { return FindValue(value); } } /// <summary> /// Constants used for properties of type LifecycleEventStatus. /// </summary> public class LifecycleEventStatus : ConstantClass { /// <summary> /// Constant Failed for LifecycleEventStatus /// </summary> public static readonly LifecycleEventStatus Failed = new LifecycleEventStatus("Failed"); /// <summary> /// Constant InProgress for LifecycleEventStatus /// </summary> public static readonly LifecycleEventStatus InProgress = new LifecycleEventStatus("InProgress"); /// <summary> /// Constant Pending for LifecycleEventStatus /// </summary> public static readonly LifecycleEventStatus Pending = new LifecycleEventStatus("Pending"); /// <summary> /// Constant Skipped for LifecycleEventStatus /// </summary> public static readonly LifecycleEventStatus Skipped = new LifecycleEventStatus("Skipped"); /// <summary> /// Constant Succeeded for LifecycleEventStatus /// </summary> public static readonly LifecycleEventStatus Succeeded = new LifecycleEventStatus("Succeeded"); /// <summary> /// Constant Unknown for LifecycleEventStatus /// </summary> public static readonly LifecycleEventStatus Unknown = new LifecycleEventStatus("Unknown"); /// <summary> /// Default Constructor /// </summary> public LifecycleEventStatus(string value) : base(value) { } /// <summary> /// Finds the constant for the unique value. /// </summary> /// <param name="value">The unique value for the constant</param> /// <returns>The constant for the unique value</returns> public static LifecycleEventStatus FindValue(string value) { return FindValue<LifecycleEventStatus>(value); } /// <summary> /// Utility method to convert strings to the constant class. /// </summary> /// <param name="value">The string value to convert to the constant class.</param> /// <returns></returns> public static implicit operator LifecycleEventStatus(string value) { return FindValue(value); } } /// <summary> /// Constants used for properties of type ListStateFilterAction. /// </summary> public class ListStateFilterAction : ConstantClass { /// <summary> /// Constant Exclude for ListStateFilterAction /// </summary> public static readonly ListStateFilterAction Exclude = new ListStateFilterAction("exclude"); /// <summary> /// Constant Ignore for ListStateFilterAction /// </summary> public static readonly ListStateFilterAction Ignore = new ListStateFilterAction("ignore"); /// <summary> /// Constant Include for ListStateFilterAction /// </summary> public static readonly ListStateFilterAction Include = new ListStateFilterAction("include"); /// <summary> /// Default Constructor /// </summary> public ListStateFilterAction(string value) : base(value) { } /// <summary> /// Finds the constant for the unique value. /// </summary> /// <param name="value">The unique value for the constant</param> /// <returns>The constant for the unique value</returns> public static ListStateFilterAction FindValue(string value) { return FindValue<ListStateFilterAction>(value); } /// <summary> /// Utility method to convert strings to the constant class. /// </summary> /// <param name="value">The string value to convert to the constant class.</param> /// <returns></returns> public static implicit operator ListStateFilterAction(string value) { return FindValue(value); } } /// <summary> /// Constants used for properties of type MinimumHealthyHostsType. /// </summary> public class MinimumHealthyHostsType : ConstantClass { /// <summary> /// Constant FLEET_PERCENT for MinimumHealthyHostsType /// </summary> public static readonly MinimumHealthyHostsType FLEET_PERCENT = new MinimumHealthyHostsType("FLEET_PERCENT"); /// <summary> /// Constant HOST_COUNT for MinimumHealthyHostsType /// </summary> public static readonly MinimumHealthyHostsType HOST_COUNT = new MinimumHealthyHostsType("HOST_COUNT"); /// <summary> /// Default Constructor /// </summary> public MinimumHealthyHostsType(string value) : base(value) { } /// <summary> /// Finds the constant for the unique value. /// </summary> /// <param name="value">The unique value for the constant</param> /// <returns>The constant for the unique value</returns> public static MinimumHealthyHostsType FindValue(string value) { return FindValue<MinimumHealthyHostsType>(value); } /// <summary> /// Utility method to convert strings to the constant class. /// </summary> /// <param name="value">The string value to convert to the constant class.</param> /// <returns></returns> public static implicit operator MinimumHealthyHostsType(string value) { return FindValue(value); } } /// <summary> /// Constants used for properties of type RegistrationStatus. /// </summary> public class RegistrationStatus : ConstantClass { /// <summary> /// Constant Deregistered for RegistrationStatus /// </summary> public static readonly RegistrationStatus Deregistered = new RegistrationStatus("Deregistered"); /// <summary> /// Constant Registered for RegistrationStatus /// </summary> public static readonly RegistrationStatus Registered = new RegistrationStatus("Registered"); /// <summary> /// Default Constructor /// </summary> public RegistrationStatus(string value) : base(value) { } /// <summary> /// Finds the constant for the unique value. /// </summary> /// <param name="value">The unique value for the constant</param> /// <returns>The constant for the unique value</returns> public static RegistrationStatus FindValue(string value) { return FindValue<RegistrationStatus>(value); } /// <summary> /// Utility method to convert strings to the constant class. /// </summary> /// <param name="value">The string value to convert to the constant class.</param> /// <returns></returns> public static implicit operator RegistrationStatus(string value) { return FindValue(value); } } /// <summary> /// Constants used for properties of type RevisionLocationType. /// </summary> public class RevisionLocationType : ConstantClass { /// <summary> /// Constant GitHub for RevisionLocationType /// </summary> public static readonly RevisionLocationType GitHub = new RevisionLocationType("GitHub"); /// <summary> /// Constant S3 for RevisionLocationType /// </summary> public static readonly RevisionLocationType S3 = new RevisionLocationType("S3"); /// <summary> /// Default Constructor /// </summary> public RevisionLocationType(string value) : base(value) { } /// <summary> /// Finds the constant for the unique value. /// </summary> /// <param name="value">The unique value for the constant</param> /// <returns>The constant for the unique value</returns> public static RevisionLocationType FindValue(string value) { return FindValue<RevisionLocationType>(value); } /// <summary> /// Utility method to convert strings to the constant class. /// </summary> /// <param name="value">The string value to convert to the constant class.</param> /// <returns></returns> public static implicit operator RevisionLocationType(string value) { return FindValue(value); } } /// <summary> /// Constants used for properties of type SortOrder. /// </summary> public class SortOrder : ConstantClass { /// <summary> /// Constant Ascending for SortOrder /// </summary> public static readonly SortOrder Ascending = new SortOrder("ascending"); /// <summary> /// Constant Descending for SortOrder /// </summary> public static readonly SortOrder Descending = new SortOrder("descending"); /// <summary> /// Default Constructor /// </summary> public SortOrder(string value) : base(value) { } /// <summary> /// Finds the constant for the unique value. /// </summary> /// <param name="value">The unique value for the constant</param> /// <returns>The constant for the unique value</returns> public static SortOrder FindValue(string value) { return FindValue<SortOrder>(value); } /// <summary> /// Utility method to convert strings to the constant class. /// </summary> /// <param name="value">The string value to convert to the constant class.</param> /// <returns></returns> public static implicit operator SortOrder(string value) { return FindValue(value); } } /// <summary> /// Constants used for properties of type StopStatus. /// </summary> public class StopStatus : ConstantClass { /// <summary> /// Constant Pending for StopStatus /// </summary> public static readonly StopStatus Pending = new StopStatus("Pending"); /// <summary> /// Constant Succeeded for StopStatus /// </summary> public static readonly StopStatus Succeeded = new StopStatus("Succeeded"); /// <summary> /// Default Constructor /// </summary> public StopStatus(string value) : base(value) { } /// <summary> /// Finds the constant for the unique value. /// </summary> /// <param name="value">The unique value for the constant</param> /// <returns>The constant for the unique value</returns> public static StopStatus FindValue(string value) { return FindValue<StopStatus>(value); } /// <summary> /// Utility method to convert strings to the constant class. /// </summary> /// <param name="value">The string value to convert to the constant class.</param> /// <returns></returns> public static implicit operator StopStatus(string value) { return FindValue(value); } } /// <summary> /// Constants used for properties of type TagFilterType. /// </summary> public class TagFilterType : ConstantClass { /// <summary> /// Constant KEY_AND_VALUE for TagFilterType /// </summary> public static readonly TagFilterType KEY_AND_VALUE = new TagFilterType("KEY_AND_VALUE"); /// <summary> /// Constant KEY_ONLY for TagFilterType /// </summary> public static readonly TagFilterType KEY_ONLY = new TagFilterType("KEY_ONLY"); /// <summary> /// Constant VALUE_ONLY for TagFilterType /// </summary> public static readonly TagFilterType VALUE_ONLY = new TagFilterType("VALUE_ONLY"); /// <summary> /// Default Constructor /// </summary> public TagFilterType(string value) : base(value) { } /// <summary> /// Finds the constant for the unique value. /// </summary> /// <param name="value">The unique value for the constant</param> /// <returns>The constant for the unique value</returns> public static TagFilterType FindValue(string value) { return FindValue<TagFilterType>(value); } /// <summary> /// Utility method to convert strings to the constant class. /// </summary> /// <param name="value">The string value to convert to the constant class.</param> /// <returns></returns> public static implicit operator TagFilterType(string value) { return FindValue(value); } } }
#region License /* * Copyright 2002-2010 the original author or 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. */ #endregion #region Imports using System; using System.Collections; using System.Xml; using Spring.Core.TypeResolution; using Spring.Context.Support; using Spring.Expressions; using Spring.Objects; using Spring.Objects.Factory; using Spring.Objects.Factory.Config; using Spring.Objects.Factory.Support; using Spring.Objects.Factory.Xml; using Spring.Threading; using Spring.Util; #endregion namespace Spring.Validation.Config { /// <summary> /// Implementation of the custom configuration parser for validator definitions. /// </summary> /// <author>Aleksandar Seovic</author> [ NamespaceParser( Namespace = "http://www.springframework.net/validation", SchemaLocationAssemblyHint = typeof(ValidationNamespaceParser), SchemaLocation = "/Spring.Validation.Config/spring-validation-1.3.xsd") ] public sealed class ValidationNamespaceParser : ObjectsNamespaceParser { private const string ValidatorTypePrefix = "validator: "; [ThreadStatic] private int definitionCount = 0; static ValidationNamespaceParser() { TypeRegistry.RegisterType(ValidatorTypePrefix + "group", typeof(ValidatorGroup)); TypeRegistry.RegisterType(ValidatorTypePrefix + "any", typeof(AnyValidatorGroup)); TypeRegistry.RegisterType(ValidatorTypePrefix + "exclusive", typeof(ExclusiveValidatorGroup)); TypeRegistry.RegisterType(ValidatorTypePrefix + "collection", typeof(CollectionValidator)); TypeRegistry.RegisterType(ValidatorTypePrefix + "required", typeof(RequiredValidator)); TypeRegistry.RegisterType(ValidatorTypePrefix + "condition", typeof(ConditionValidator)); TypeRegistry.RegisterType(ValidatorTypePrefix + "regex", typeof(RegularExpressionValidator)); } /// <summary> /// Initializes a new instance of the <see cref="ValidationNamespaceParser"/> class. /// </summary> public ValidationNamespaceParser() { // generate unique key for instance field to be stored in LogicalThreadContext string FIELDPREFIX = typeof(ValidationNamespaceParser).FullName + base.GetHashCode(); } /// <summary> /// Parse the specified element and register any resulting /// IObjectDefinitions with the IObjectDefinitionRegistry that is /// embedded in the supplied ParserContext. /// </summary> /// <param name="element">The element to be parsed into one or more IObjectDefinitions</param> /// <param name="parserContext">The object encapsulating the current state of the parsing /// process.</param> /// <returns> /// The primary IObjectDefinition (can be null as explained above) /// </returns> /// <remarks> /// Implementations should return the primary IObjectDefinition /// that results from the parse phase if they wish to used nested /// inside (for example) a <code>&lt;property&gt;</code> tag. /// <para>Implementations may return null if they will not /// be used in a nested scenario. /// </para> /// </remarks> public override IObjectDefinition ParseElement(XmlElement element, ParserContext parserContext) { if (!element.HasAttribute("id")) { throw new ObjectDefinitionStoreException(parserContext.ReaderContext.Resource, "validator", "Top-level validator element must have an 'id' attribute defined."); } this.definitionCount = 0; ParseAndRegisterValidator(element, parserContext); return null; //return definitionCount; } /// <summary> /// Parses the validator definition. /// </summary> /// <param name="id">Validator's identifier.</param> /// <param name="element">The element to parse.</param> /// <param name="parserContext">The parser helper.</param> /// <returns>Validator object definition.</returns> private IObjectDefinition ParseValidator(string id, XmlElement element, ParserContext parserContext) { string typeName = GetTypeName(element); string parent = GetAttributeValue(element, ObjectDefinitionConstants.ParentAttribute); string name = "validator: " + (StringUtils.HasText(id) ? id : this.definitionCount.ToString()); MutablePropertyValues properties = new MutablePropertyValues(); IConfigurableObjectDefinition od = parserContext.ReaderContext.ObjectDefinitionFactory.CreateObjectDefinition( typeName, parent, parserContext.ReaderContext.Reader.Domain); od.PropertyValues = properties; od.IsSingleton = true; od.IsLazyInit = true; ParseAttributeIntoProperty(element, ValidatorDefinitionConstants.TestAttribute, properties, "Test"); ParseAttributeIntoProperty(element, ValidatorDefinitionConstants.WhenAttribute, properties, "When"); ParseAttributeIntoProperty(element, ValidatorDefinitionConstants.GroupFastValidateAttribute, properties, "FastValidate"); ParseAttributeIntoProperty(element, ValidatorDefinitionConstants.RegexExpressionAttribute, properties, "Expression"); ParseAttributeIntoProperty(element, ValidatorDefinitionConstants.CollectionValidateAllAttribute, properties, "ValidateAll"); ParseAttributeIntoProperty(element, ValidatorDefinitionConstants.CollectionContextAttribute, properties, "Context"); ParseAttributeIntoProperty(element, ValidatorDefinitionConstants.CollectionIncludeElementsErrors, properties, "IncludeElementErrors"); // TODO: (EE) - is this a mistake to check 'validateAll' but add 'context' then? // if (StringUtils.HasText(validateAll)) // { // properties.Add("Context", context); // } ManagedList nestedValidators = new ManagedList(); ManagedList actions = new ManagedList(); ParserContext childParserContext = new ParserContext(parserContext.ParserHelper, od); foreach (XmlNode node in element.ChildNodes) { XmlElement child = node as XmlElement; if (child != null) { switch (child.LocalName) { case ValidatorDefinitionConstants.PropertyElement: string propertyName = GetAttributeValue(child, ValidatorDefinitionConstants.PropertyNameAttribute); properties.Add(propertyName, base.ParsePropertyValue(child, name, childParserContext)); break; case ValidatorDefinitionConstants.MessageElement: actions.Add(ParseErrorMessageAction(child, childParserContext)); break; case ValidatorDefinitionConstants.ActionElement: actions.Add(ParseGenericAction(child, childParserContext)); break; case ValidatorDefinitionConstants.ExceptionElement: actions.Add(ParseExceptionAction(child, childParserContext)); break; case ValidatorDefinitionConstants.ReferenceElement: nestedValidators.Add(ParseValidatorReference(child, childParserContext)); break; default: nestedValidators.Add(ParseAndRegisterValidator(child, childParserContext)); break; } } } if (nestedValidators.Count > 0) { properties.Add("Validators", nestedValidators); } if (actions.Count > 0) { properties.Add("Actions", actions); } return od; } /// <summary> /// Parses the attribute of the given <paramref name="attName"/> from the XmlElement and, if available, adds a property of the given <paramref name="propName"/> with /// the parsed value. /// </summary> private void ParseAttributeIntoProperty(XmlElement element, string attName, MutablePropertyValues properties, string propName) { string test = GetAttributeValue(element, attName); if (StringUtils.HasText(test)) { properties.Add(propName, test); } } /// <summary> /// Parses and potentially registers a validator. /// </summary> /// <remarks> /// Only validators that have <code>id</code> attribute specified are registered /// as separate object definitions within application context. /// </remarks> /// <param name="element">Validator XML element.</param> /// <param name="parserContext">The parser helper.</param> /// <returns>Validator object definition.</returns> private IObjectDefinition ParseAndRegisterValidator(XmlElement element, ParserContext parserContext) { string id = GetAttributeValue(element, ObjectDefinitionConstants.IdAttribute); IObjectDefinition validator = ParseValidator(id, element, parserContext); if (StringUtils.HasText(id)) { parserContext.ReaderContext.Registry.RegisterObjectDefinition(id, validator); this.definitionCount++; } return validator; } /// <summary> /// Gets the name of the object type for the specified element. /// </summary> /// <param name="element">The element.</param> /// <returns>The name of the object type.</returns> private string GetTypeName(XmlElement element) { string typeName = GetAttributeValue(element, ObjectDefinitionConstants.TypeAttribute); if (StringUtils.IsNullOrEmpty(typeName)) { return ValidatorTypePrefix + element.LocalName; } return typeName; } /// <summary> /// Creates an error message action based on the specified message element. /// </summary> /// <param name="message">The message element.</param> /// <param name="parserContext">The parser helper.</param> /// <returns>The error message action definition.</returns> private static IObjectDefinition ParseErrorMessageAction(XmlElement message, ParserContext parserContext) { string messageId = GetAttributeValue(message, MessageConstants.IdAttribute); string[] providers = GetAttributeValue(message, MessageConstants.ProvidersAttribute).Split(','); ArrayList parameters = new ArrayList(); foreach (XmlElement param in message.ChildNodes) { IExpression paramExpression = Expression.Parse(GetAttributeValue(param, MessageConstants.ParameterValueAttribute)); parameters.Add(paramExpression); } string typeName = "Spring.Validation.Actions.ErrorMessageAction, Spring.Core"; ConstructorArgumentValues ctorArgs = new ConstructorArgumentValues(); ctorArgs.AddGenericArgumentValue(messageId); ctorArgs.AddGenericArgumentValue(providers); string when = GetAttributeValue(message, ValidatorDefinitionConstants.WhenAttribute); MutablePropertyValues properties = new MutablePropertyValues(); if (StringUtils.HasText(when)) { properties.Add("When", when); } if (parameters.Count > 0) { properties.Add("Parameters", parameters.ToArray(typeof(IExpression))); } IConfigurableObjectDefinition action = parserContext.ReaderContext.ObjectDefinitionFactory.CreateObjectDefinition(typeName, null, parserContext.ReaderContext.Reader.Domain); action.ConstructorArgumentValues = ctorArgs; action.PropertyValues = properties; return action; } private IObjectDefinition ParseExceptionAction(XmlElement element, ParserContext parserContext) { string typeName = "Spring.Validation.Actions.ExceptionAction, Spring.Core"; string throwExpression = GetAttributeValue(element, ValidatorDefinitionConstants.ThrowAttribute); ConstructorArgumentValues ctorArgs = new ConstructorArgumentValues(); ctorArgs.AddGenericArgumentValue(throwExpression); string when = GetAttributeValue(element, ValidatorDefinitionConstants.WhenAttribute); MutablePropertyValues properties = new MutablePropertyValues(); if (StringUtils.HasText(when)) { properties.Add("When", when); } IConfigurableObjectDefinition action = parserContext.ReaderContext.ObjectDefinitionFactory.CreateObjectDefinition(typeName, null, parserContext.ReaderContext.Reader.Domain); action.ConstructorArgumentValues = ctorArgs; action.PropertyValues = properties; return action; } /// <summary> /// Creates a generic action based on the specified element. /// </summary> /// <param name="element">The action definition element.</param> /// <param name="parserContext">The parser helper.</param> /// <returns>Generic validation action definition.</returns> private IObjectDefinition ParseGenericAction(XmlElement element, ParserContext parserContext) { string typeName = GetAttributeValue(element, ObjectDefinitionConstants.TypeAttribute); string when = GetAttributeValue(element, ValidatorDefinitionConstants.WhenAttribute); MutablePropertyValues properties = base.ParsePropertyElements("validator:action", element, parserContext); if (StringUtils.HasText(when)) { properties.Add("When", when); } IConfigurableObjectDefinition action = parserContext.ReaderContext.ObjectDefinitionFactory.CreateObjectDefinition(typeName, null, parserContext.ReaderContext.Reader.Domain); action.PropertyValues = properties; return action; } /// <summary> /// Creates object definition for the validator reference. /// </summary> /// <param name="element">The action definition element.</param> /// <param name="parserContext">The parser helper.</param> /// <returns>Generic validation action definition.</returns> private IObjectDefinition ParseValidatorReference(XmlElement element, ParserContext parserContext) { string typeName = "Spring.Validation.ValidatorReference, Spring.Core"; string name = GetAttributeValue(element, ValidatorDefinitionConstants.ReferenceNameAttribute); string context = GetAttributeValue(element, ValidatorDefinitionConstants.ReferenceContextAttribute); string when = GetAttributeValue(element, ValidatorDefinitionConstants.WhenAttribute); MutablePropertyValues properties = new MutablePropertyValues(); properties.Add("Name", name); if (StringUtils.HasText(context)) { properties.Add("Context", context); } if (StringUtils.HasText(when)) { properties.Add("When", when); } IConfigurableObjectDefinition reference = parserContext.ReaderContext.ObjectDefinitionFactory.CreateObjectDefinition(typeName, null, parserContext.ReaderContext.Reader.Domain); reference.PropertyValues = properties; return reference; } #region Element & Attribute Name Constants private class ValidatorDefinitionConstants { public const string PropertyElement = "property"; public const string MessageElement = "message"; public const string ActionElement = "action"; public const string ExceptionElement = "exception"; public const string ReferenceElement = "ref"; public const string TypeAttribute = "type"; public const string TestAttribute = "test"; public const string NameAttribute = "name"; public const string WhenAttribute = "when"; public const string ThrowAttribute = "throw"; public const string PropertyNameAttribute = "name"; public const string ReferenceNameAttribute = "name"; public const string ReferenceContextAttribute = "context"; public const string RegexExpressionAttribute = "expression"; public const string GroupFastValidateAttribute = "fast-validate"; public const string CollectionValidateAllAttribute = "validate-all"; public const string CollectionContextAttribute = "context"; public const string CollectionIncludeElementsErrors = "include-element-errors"; } private class MessageConstants { public const string ParamElement = "param"; public const string IdAttribute = "id"; public const string ProvidersAttribute = "providers"; public const string ParameterValueAttribute = "value"; } #endregion } }
namespace Orleans.CodeGenerator { using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Orleans; using Orleans.CodeGeneration; using Orleans.CodeGenerator.Utilities; using Orleans.Runtime; using GrainInterfaceUtils = Orleans.CodeGeneration.GrainInterfaceUtils; using SF = Microsoft.CodeAnalysis.CSharp.SyntaxFactory; /// <summary> /// Methods common to multiple code generators. /// </summary> internal static class CodeGeneratorCommon { /// <summary> /// The name of these code generators. /// </summary> private const string CodeGeneratorName = "Orleans-CodeGenerator"; /// <summary> /// The prefix for class names. /// </summary> internal const string ClassPrefix = "OrleansCodeGen"; /// <summary> /// The current version. /// </summary> private static readonly string CodeGeneratorVersion = RuntimeVersion.FileVersion; /// <summary> /// Generates and compiles an assembly for the provided grains. /// </summary> /// <param name="generatedSyntax"> /// The generated code. /// </param> /// <param name="assemblyName"> /// The name for the generated assembly. /// </param> /// <param name="emitDebugSymbols"> /// Whether or not to emit debug symbols for the generated assembly. /// </param> /// <returns> /// The raw assembly. /// </returns> /// <exception cref="CodeGenerationException"> /// An error occurred generating code. /// </exception> public static GeneratedAssembly CompileAssembly(GeneratedSyntax generatedSyntax, string assemblyName, bool emitDebugSymbols) { // Add the generated code attribute. var code = AddGeneratedCodeAttribute(generatedSyntax); // Reference everything which can be referenced. var assemblies = System.AppDomain.CurrentDomain.GetAssemblies() .Where(asm => !asm.IsDynamic && !string.IsNullOrWhiteSpace(asm.Location)) .Select(asm => MetadataReference.CreateFromFile(asm.Location)) .Cast<MetadataReference>() .ToArray(); var logger = LogManager.GetLogger("CodeGenerator"); // Generate the code. var options = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary); string source = null; if (logger.IsVerbose3) { source = GenerateSourceCode(code); // Compile the code and load the generated assembly. logger.LogWithoutBulkingAndTruncating( Severity.Verbose3, ErrorCode.CodeGenSourceGenerated, "Generating assembly {0} with source:\n{1}", assemblyName, source); } var compilation = CSharpCompilation.Create(assemblyName) .AddSyntaxTrees(code.SyntaxTree) .AddReferences(assemblies) .WithOptions(options); var outputStream = new MemoryStream(); var symbolStream = emitDebugSymbols ? new MemoryStream() : null; try { var compilationResult = compilation.Emit(outputStream, symbolStream); if (!compilationResult.Success) { source = source ?? GenerateSourceCode(code); var errors = string.Join("\n", compilationResult.Diagnostics.Select(_ => _.ToString())); logger.Warn( ErrorCode.CodeGenCompilationFailed, "Compilation of assembly {0} failed with errors:\n{1}\nGenerated Source Code:\n{2}", assemblyName, errors, source); throw new CodeGenerationException(errors); } logger.Verbose( ErrorCode.CodeGenCompilationSucceeded, "Compilation of assembly {0} succeeded.", assemblyName); return new GeneratedAssembly { RawBytes = outputStream.ToArray(), DebugSymbolRawBytes = symbolStream?.ToArray() }; } finally { outputStream.Dispose(); symbolStream?.Dispose(); } } public static CompilationUnitSyntax AddGeneratedCodeAttribute(GeneratedSyntax generatedSyntax) { var codeGenTargetAttributes = SF.AttributeList() .AddAttributes( generatedSyntax.SourceAssemblies.Select( asm => SF.Attribute(typeof(OrleansCodeGenerationTargetAttribute).GetNameSyntax()) .AddArgumentListArguments( SF.AttributeArgument(asm.GetName().FullName.GetLiteralExpression()))).ToArray()) .WithTarget(SF.AttributeTargetSpecifier(SF.Token(SyntaxKind.AssemblyKeyword))); var generatedCodeAttribute = SF.AttributeList() .AddAttributes( SF.Attribute(typeof(GeneratedCodeAttribute).GetNameSyntax()) .AddArgumentListArguments( SF.AttributeArgument("Orleans-CodeGenerator".GetLiteralExpression()), SF.AttributeArgument(RuntimeVersion.FileVersion.GetLiteralExpression()))) .WithTarget(SF.AttributeTargetSpecifier(SF.Token(SyntaxKind.AssemblyKeyword))); return generatedSyntax.Syntax.AddAttributeLists(generatedCodeAttribute, codeGenTargetAttributes); } internal static AttributeSyntax GetGeneratedCodeAttributeSyntax() { return SF.Attribute(typeof(GeneratedCodeAttribute).GetNameSyntax()) .AddArgumentListArguments( SF.AttributeArgument(CodeGeneratorName.GetLiteralExpression()), SF.AttributeArgument(CodeGeneratorVersion.GetLiteralExpression())); } internal static string GenerateSourceCode(CompilationUnitSyntax code) { var syntax = code.NormalizeWhitespace(); var source = syntax.ToFullString(); return source; } /// <summary> /// Generates switch cases for the provided grain type. /// </summary> /// <param name="grainType"> /// The grain type. /// </param> /// <param name="methodIdArgument"> /// The method id argument, which is used to select the correct switch label. /// </param> /// <param name="generateMethodHandler"> /// The function used to generate switch block statements for each method. /// </param> /// <returns> /// The switch cases for the provided grain type. /// </returns> public static SwitchSectionSyntax[] GenerateGrainInterfaceAndMethodSwitch( Type grainType, ExpressionSyntax methodIdArgument, Func<MethodInfo, StatementSyntax[]> generateMethodHandler) { var interfaces = GrainInterfaceUtils.GetRemoteInterfaces(grainType); interfaces[GrainInterfaceUtils.GetGrainInterfaceId(grainType)] = grainType; // Switch on interface id. var interfaceCases = new List<SwitchSectionSyntax>(); foreach (var @interface in interfaces) { var interfaceType = @interface.Value; var interfaceId = @interface.Key; var methods = GrainInterfaceUtils.GetMethods(interfaceType); var methodCases = new List<SwitchSectionSyntax>(); // Switch on method id. foreach (var method in methods) { // Generate switch case. var methodId = GrainInterfaceUtils.ComputeMethodId(method); var methodType = method; // Generate the switch label for this interface id. var methodIdSwitchLabel = SF.CaseSwitchLabel( SF.LiteralExpression(SyntaxKind.NumericLiteralExpression, SF.Literal(methodId))); // Generate the switch body. var methodInvokeStatement = generateMethodHandler(methodType); methodCases.Add( SF.SwitchSection().AddLabels(methodIdSwitchLabel).AddStatements(methodInvokeStatement)); } // Generate the switch label for this interface id. var interfaceIdSwitchLabel = SF.CaseSwitchLabel( SF.LiteralExpression(SyntaxKind.NumericLiteralExpression, SF.Literal(interfaceId))); // Generate the default case, which will throw a NotImplementedException. var errorMessage = SF.BinaryExpression( SyntaxKind.AddExpression, "interfaceId=".GetLiteralExpression(), SF.BinaryExpression( SyntaxKind.AddExpression, SF.LiteralExpression(SyntaxKind.NumericLiteralExpression, SF.Literal(interfaceId)), SF.BinaryExpression( SyntaxKind.AddExpression, ",methodId=".GetLiteralExpression(), methodIdArgument))); var throwStatement = SF.ThrowStatement( SF.ObjectCreationExpression(typeof(NotImplementedException).GetTypeSyntax()) .AddArgumentListArguments(SF.Argument(errorMessage))); var defaultCase = SF.SwitchSection().AddLabels(SF.DefaultSwitchLabel()).AddStatements(throwStatement); // Generate switch statements for the methods in this interface. var methodSwitchStatements = SF.SwitchStatement(methodIdArgument).AddSections(methodCases.ToArray()).AddSections(defaultCase); // Generate the switch section for this interface. interfaceCases.Add( SF.SwitchSection().AddLabels(interfaceIdSwitchLabel).AddStatements(methodSwitchStatements)); } return interfaceCases.ToArray(); } public static string GetRandomNamespace() { return "Generated" + DateTime.Now.Ticks.ToString("X"); } public static string GetGeneratedNamespace(Type type, bool randomize = false) { string result; if (randomize || string.IsNullOrWhiteSpace(type.Namespace)) { result = GetRandomNamespace(); } else { result = type.Namespace; } return result; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.DataLake.Analytics { using Azure; using DataLake; using Management; using Azure; using Management; using DataLake; using Models; using Rest; using Rest.Azure; using Rest.Azure.OData; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// AccountOperations operations. /// </summary> public partial interface IAccountOperations { /// <summary> /// Gets the first page of Data Lake Analytics accounts, if any, within /// a specific resource group. This includes a link to the next page, /// if any. /// </summary> /// <param name='resourceGroupName'> /// The name of the Azure resource group that contains the Data Lake /// Analytics account. /// </param> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> /// <param name='select'> /// OData Select statement. Limits the properties on each entry to just /// those requested, e.g. Categories?$select=CategoryName,Description. /// Optional. /// </param> /// <param name='count'> /// The Boolean value of true or false to request a count of the /// matching resources included with the resources in the response, /// e.g. Categories?$count=true. Optional. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<DataLakeAnalyticsAccount>>> ListByResourceGroupWithHttpMessagesAsync(string resourceGroupName, ODataQuery<DataLakeAnalyticsAccount> odataQuery = default(ODataQuery<DataLakeAnalyticsAccount>), string select = default(string), bool? count = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets the first page of Data Lake Analytics accounts, if any, within /// the current subscription. This includes a link to the next page, if /// any. /// </summary> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> /// <param name='select'> /// OData Select statement. Limits the properties on each entry to just /// those requested, e.g. Categories?$select=CategoryName,Description. /// Optional. /// </param> /// <param name='count'> /// The Boolean value of true or false to request a count of the /// matching resources included with the resources in the response, /// e.g. Categories?$count=true. Optional. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<DataLakeAnalyticsAccount>>> ListWithHttpMessagesAsync(ODataQuery<DataLakeAnalyticsAccount> odataQuery = default(ODataQuery<DataLakeAnalyticsAccount>), string select = default(string), bool? count = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets details of the specified Data Lake Analytics account. /// </summary> /// <param name='resourceGroupName'> /// The name of the Azure resource group that contains the Data Lake /// Analytics account. /// </param> /// <param name='accountName'> /// The name of the Data Lake Analytics account to retrieve. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<DataLakeAnalyticsAccount>> GetWithHttpMessagesAsync(string resourceGroupName, string accountName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Begins the delete delete process for the Data Lake Analytics /// account object specified by the account name. /// </summary> /// <param name='resourceGroupName'> /// The name of the Azure resource group that contains the Data Lake /// Analytics account. /// </param> /// <param name='accountName'> /// The name of the Data Lake Analytics account to delete /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string accountName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Creates the specified Data Lake Analytics account. This supplies /// the user with computation services for Data Lake Analytics /// workloads /// </summary> /// <param name='resourceGroupName'> /// The name of the Azure resource group that contains the Data Lake /// Analytics account.the account will be associated with. /// </param> /// <param name='accountName'> /// The name of the Data Lake Analytics account to create. /// </param> /// <param name='parameters'> /// Parameters supplied to the create Data Lake Analytics account /// operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<DataLakeAnalyticsAccount>> CreateWithHttpMessagesAsync(string resourceGroupName, string accountName, DataLakeAnalyticsAccount parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Updates the Data Lake Analytics account object specified by the /// accountName with the contents of the account object. /// </summary> /// <param name='resourceGroupName'> /// The name of the Azure resource group that contains the Data Lake /// Analytics account. /// </param> /// <param name='accountName'> /// The name of the Data Lake Analytics account to update. /// </param> /// <param name='parameters'> /// Parameters supplied to the update Data Lake Analytics account /// operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<DataLakeAnalyticsAccount>> UpdateWithHttpMessagesAsync(string resourceGroupName, string accountName, DataLakeAnalyticsAccountUpdateParameters parameters = default(DataLakeAnalyticsAccountUpdateParameters), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Begins the delete delete process for the Data Lake Analytics /// account object specified by the account name. /// </summary> /// <param name='resourceGroupName'> /// The name of the Azure resource group that contains the Data Lake /// Analytics account. /// </param> /// <param name='accountName'> /// The name of the Data Lake Analytics account to delete /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string accountName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Creates the specified Data Lake Analytics account. This supplies /// the user with computation services for Data Lake Analytics /// workloads /// </summary> /// <param name='resourceGroupName'> /// The name of the Azure resource group that contains the Data Lake /// Analytics account.the account will be associated with. /// </param> /// <param name='accountName'> /// The name of the Data Lake Analytics account to create. /// </param> /// <param name='parameters'> /// Parameters supplied to the create Data Lake Analytics account /// operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<DataLakeAnalyticsAccount>> BeginCreateWithHttpMessagesAsync(string resourceGroupName, string accountName, DataLakeAnalyticsAccount parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Updates the Data Lake Analytics account object specified by the /// accountName with the contents of the account object. /// </summary> /// <param name='resourceGroupName'> /// The name of the Azure resource group that contains the Data Lake /// Analytics account. /// </param> /// <param name='accountName'> /// The name of the Data Lake Analytics account to update. /// </param> /// <param name='parameters'> /// Parameters supplied to the update Data Lake Analytics account /// operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<DataLakeAnalyticsAccount>> BeginUpdateWithHttpMessagesAsync(string resourceGroupName, string accountName, DataLakeAnalyticsAccountUpdateParameters parameters = default(DataLakeAnalyticsAccountUpdateParameters), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets the first page of Data Lake Analytics accounts, if any, within /// a specific resource group. This includes a link to the next page, /// if any. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<DataLakeAnalyticsAccount>>> ListByResourceGroupNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets the first page of Data Lake Analytics accounts, if any, within /// the current subscription. This includes a link to the next page, if /// any. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<DataLakeAnalyticsAccount>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }
// File: Subscription.cs // Project: ROS_C-Sharp // // ROS.NET // Eric McCann <[email protected]> // UMass Lowell Robotics Laboratory // // Reimplementation of the ROS (ros.org) ros_cpp client in C#. // // Created: 04/28/2015 // Updated: 02/10/2016 #region USINGZ using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using Messages; using XmlRpc_Wrapper; using m = Messages.std_msgs; using gm = Messages.geometry_msgs; using nm = Messages.nav_msgs; #endregion namespace Ros_CSharp { public class Subscription { private bool _dropped; private List<ICallbackInfo> callbacks = new List<ICallbackInfo>(); public object callbacks_mutex = new object(); public string datatype = ""; public Dictionary<PublisherLink, LatchInfo> latched_messages = new Dictionary<PublisherLink, LatchInfo>(); public string md5sum = ""; public object md5sum_mutex = new object(); public MsgTypes msgtype; public string name = ""; public int nonconst_callbacks; public List<PendingConnection> pending_connections = new List<PendingConnection>(); public object pending_connections_mutex = new object(); public List<PublisherLink> publisher_links = new List<PublisherLink>(); public object publisher_links_mutex = new object(), shutdown_mutex = new object(); private bool shutting_down; public Subscription(string n, string md5s, string dt) { name = n; md5sum = md5s; datatype = dt; msgtype = (MsgTypes) Enum.Parse(typeof (MsgTypes), dt.Replace("/", "__")); } public bool IsDropped { get { return _dropped; } } public int NumPublishers { get { lock (publisher_links_mutex) return publisher_links.Count; } } public int NumCallbacks { get { lock (callbacks_mutex) return callbacks.Count; } } public void shutdown() { lock (shutdown_mutex) { shutting_down = true; } drop(); } public XmlRpcValue getStats() { XmlRpcValue stats = new XmlRpcValue(); stats.Set(0, name); XmlRpcValue conn_data = new XmlRpcValue(); conn_data.SetArray(0); lock (publisher_links_mutex) { int cidx = 0; foreach (PublisherLink link in publisher_links) { XmlRpcValue v = new XmlRpcValue(); PublisherLink.Stats s = link.stats; v.Set(0, link.ConnectionID); v.Set(1, s.bytes_received); v.Set(2, s.messages_received); v.Set(3, s.drops); v.Set(4, 0); conn_data.Set(cidx++, v); } } stats.Set(1, conn_data); return stats; } public void getInfo(XmlRpcValue info) { lock (publisher_links_mutex) { //EDB.WriteLine("SUB: getInfo with " + publisher_links.Count + " publinks in list"); foreach (PublisherLink c in publisher_links) { //EDB.WriteLine("PUB: adding a curr_info to info!"); XmlRpcValue curr_info = new XmlRpcValue(); curr_info.Set(0, (int) c.ConnectionID); curr_info.Set(1, c.XmlRpc_Uri); curr_info.Set(2, "i"); curr_info.Set(3, c.TransportType); curr_info.Set(4, name); //EDB.Write("PUB curr_info DUMP:\n\t"); //curr_info.Dump(); info.Set(info.Size, curr_info); } //EDB.WriteLine("SUB: outgoing info is of type: " + info.Type + " and has size: " + info.Size); } } public void drop() { if (!_dropped) { _dropped = true; dropAllConnections(); } } public void dropAllConnections() { List<PublisherLink> localsubscribers = null; lock (publisher_links_mutex) { localsubscribers = new List<PublisherLink>(publisher_links); publisher_links.Clear(); } foreach (PublisherLink it in localsubscribers) { //hot it's like it.drop(); //drop it like it's hot, backwards. } } public bool urisEqual(string uri1, string uri2) { if (uri1 == null || uri2 == null) throw new Exception("ZOMG IT'S NULL IN URISEQUAL!"); string n1; string h1 = n1 = ""; int p2; int p1 = p2 = 0; network.splitURI(uri1, ref h1, ref p1); network.splitURI(uri2, ref n1, ref p2); return h1 == n1 && p1 == p2; } public void removePublisherLink(PublisherLink pub) { lock (publisher_links_mutex) { if (publisher_links.Contains(pub)) { publisher_links.Remove(pub); } if (pub.Latched) latched_messages.Remove(pub); } } public void addPublisherLink(PublisherLink pub) { publisher_links.Add(pub); } public bool pubUpdate(IEnumerable<string> pubs) { lock (shutdown_mutex) { if (shutting_down || _dropped) return false; } bool retval = true; #if DEBUG #if DUMP EDB.WriteLine("Publisher update for [" + name + "]: " + publisher_links.Aggregate(pubs.Aggregate("", (current, s) => current + (s + ", "))+" already have these connections: ", (current, spc) => current + spc.XmlRpc_Uri)); #else EDB.WriteLine("Publisher update for [" + name + "]"); #endif #endif List<string> additions = new List<string>(); List<PublisherLink> subtractions = new List<PublisherLink>(); lock (publisher_links_mutex) { subtractions.AddRange(from spc in publisher_links let found = pubs.Any(up_i => urisEqual(spc.XmlRpc_Uri, up_i)) where !found select spc); foreach (string up_i in pubs) { bool found = publisher_links.Any(spc => urisEqual(up_i, spc.XmlRpc_Uri)); if (found) continue; lock (pending_connections_mutex) { if (pending_connections.Any(pc => urisEqual(up_i, pc.RemoteUri))) { found = true; } if (!found) additions.Add(up_i); } } } foreach (PublisherLink link in subtractions) { if (link.XmlRpc_Uri != XmlRpcManager.Instance.uri) { #if DEBUG EDB.WriteLine("Disconnecting from publisher [" + link.CallerID + "] of topic [" + name + "] at [" + link.XmlRpc_Uri + "]"); #endif link.drop(); } else { EDB.WriteLine("NOT DISCONNECTING FROM MYSELF FOR TOPIC " + name); } } foreach (string i in additions) { if (XmlRpcManager.Instance.uri != i) { retval &= NegotiateConnection(i); //EDB.WriteLine("NEGOTIATINGING"); } else EDB.WriteLine("Skipping myself (" + name + ", " + XmlRpcManager.Instance.uri + ")"); } return retval; } public bool NegotiateConnection(string xmlrpc_uri) { int protos = 0; XmlRpcValue tcpros_array = new XmlRpcValue(), protos_array = new XmlRpcValue(), Params = new XmlRpcValue(); tcpros_array.Set(0, "TCPROS"); protos_array.Set(protos++, tcpros_array); Params.Set(0, this_node.Name); Params.Set(1, name); Params.Set(2, protos_array); string peer_host = ""; int peer_port = 0; if (!network.splitURI(xmlrpc_uri, ref peer_host, ref peer_port)) { EDB.WriteLine("Bad xml-rpc URI: [" + xmlrpc_uri + "]"); return false; } XmlRpcClient c = new XmlRpcClient(peer_host, peer_port); if (!c.IsConnected || !c.ExecuteNonBlock("requestTopic", Params)) { EDB.WriteLine("Failed to contact publisher [" + peer_host + ":" + peer_port + "] for topic [" + name + "]"); c.Dispose(); return false; } #if DEBUG EDB.WriteLine("Began asynchronous xmlrpc connection to http://" + peer_host + ":" + peer_port + "/ for topic [" + name + "]"); #endif PendingConnection conn = new PendingConnection(c, this, xmlrpc_uri, Params); lock (pending_connections_mutex) { pending_connections.Add(conn); } XmlRpcManager.Instance.addAsyncConnection(conn); return true; } public void pendingConnectionDone(PendingConnection conn, XmlRpcValue result) { //XmlRpcValue result = XmlRpcValue.LookUp(res); lock (shutdown_mutex) { if (shutting_down || _dropped) return; } XmlRpcValue proto = new XmlRpcValue(); if (!XmlRpcManager.Instance.validateXmlrpcResponse("requestTopic", result, proto)) { conn.failures++; EDB.WriteLine("Negotiating for " + conn.parent.name + " has failed " + conn.failures + " times"); return; } lock (pending_connections_mutex) { pending_connections.Remove(conn); } string peer_host = conn.client.Host; int peer_port = conn.client.Port; string xmlrpc_uri = "http://" + peer_host + ":" + peer_port + "/"; if (proto.Size == 0) { #if DEBUG EDB.WriteLine("Couldn't agree on any common protocols with [" + xmlrpc_uri + "] for topic [" + name + "]"); #endif return; } if (proto.Type != XmlRpcValue.ValueType.TypeArray) { EDB.WriteLine("Available protocol info returned from " + xmlrpc_uri + " is not a list."); return; } string proto_name = proto[0].Get<string>(); if (proto_name == "UDPROS") { EDB.WriteLine("OWNED! Only tcpros is supported right now."); } else if (proto_name == "TCPROS") { if (proto.Size != 3 || proto[1].Type != XmlRpcValue.ValueType.TypeString || proto[2].Type != XmlRpcValue.ValueType.TypeInt) { EDB.WriteLine("publisher implements TCPROS... BADLY! parameters aren't string,int"); return; } string pub_host = proto[1].Get<string>(); int pub_port = proto[2].Get<int>(); #if DEBUG EDB.WriteLine("Connecting via tcpros to topic [" + name + "] at host [" + pub_host + ":" + pub_port + "]"); #endif TcpTransport transport = new TcpTransport(PollManager.Instance.poll_set) {_topic = name}; if (transport.connect(pub_host, pub_port)) { Connection connection = new Connection(); TransportPublisherLink pub_link = new TransportPublisherLink(this, xmlrpc_uri); connection.initialize(transport, false, null); pub_link.initialize(connection); ConnectionManager.Instance.addConnection(connection); lock (publisher_links_mutex) { addPublisherLink(pub_link); } #if DEBUG EDB.WriteLine("Connected to publisher of topic [" + name + "] at [" + pub_host + ":" + pub_port + "]"); #endif } else { EDB.WriteLine("Failed to connect to publisher of topic [" + name + "] at [" + pub_host + ":" + pub_port + "]"); } } else { EDB.WriteLine("Your xmlrpc server be talking jibber jabber, foo"); } } public void headerReceived(PublisherLink link, Header header) { lock (md5sum_mutex) { if (md5sum == "*") md5sum = link.md5sum; } } internal ulong handleMessage(IRosMessage msg, bool ser, bool nocopy, IDictionary connection_header, PublisherLink link) { IRosMessage t = null; ulong drops = 0; TimeData receipt_time = ROS.GetTime().data; if (msg.Serialized != null) //will be null if self-subscribed msg.Deserialize(msg.Serialized); lock (callbacks_mutex) { foreach (ICallbackInfo info in callbacks) { MsgTypes ti = info.helper.type; if (nocopy || ser) { t = msg; t.connection_header = msg.connection_header; t.Serialized = null; bool was_full = false; bool nonconst_need_copy = callbacks.Count > 1; info.subscription_queue.pushitgood(info.helper, t, nonconst_need_copy, ref was_full, receipt_time); if (was_full) ++drops; else info.callback.addCallback(info.subscription_queue, info.Get()); } } } if (t != null && link.Latched) { LatchInfo li = new LatchInfo { message = t, link = link, connection_header = connection_header, receipt_time = receipt_time }; if (latched_messages.ContainsKey(link)) latched_messages[link] = li; else latched_messages.Add(link, li); } return drops; } public void Dispose() { shutdown(); } internal bool addCallback<M>(SubscriptionCallbackHelper<M> helper, string md5sum, CallbackQueueInterface queue, uint queue_size, bool allow_concurrent_callbacks, string topiclol) where M : IRosMessage, new() { lock (md5sum_mutex) { if (this.md5sum == "*" && md5sum != "*") this.md5sum = md5sum; } if (md5sum != "*" && md5sum != this.md5sum) return false; lock (callbacks_mutex) { CallbackInfo<M> info = new CallbackInfo<M> {helper = helper, callback = queue, subscription_queue = new Callback<M>(helper.Callback.func, topiclol, queue_size, allow_concurrent_callbacks)}; //if (!helper.isConst()) //{ ++nonconst_callbacks; //} callbacks.Add(info); if (latched_messages.Count > 0) { MsgTypes ti = info.helper.type; lock (publisher_links_mutex) { foreach (PublisherLink link in publisher_links) { if (link.Latched) { if (latched_messages.ContainsKey(link)) { LatchInfo latch_info = latched_messages[link]; bool was_full = false; bool nonconst_need_copy = callbacks.Count > 1; info.subscription_queue.pushitgood(info.helper, latched_messages[link].message, nonconst_need_copy, ref was_full, ROS.GetTime().data); if (!was_full) info.callback.addCallback(info.subscription_queue, info.Get()); } } } } } } return true; } public void removeCallback(ISubscriptionCallbackHelper helper) { lock (callbacks_mutex) { foreach (ICallbackInfo info in callbacks) { if (info.helper == helper) { info.subscription_queue.clear(); info.callback.removeByID(info.Get()); callbacks.Remove(info); //if (!helper.isConst()) --nonconst_callbacks; break; } } } } public void addLocalConnection(Publication pub) { lock (publisher_links_mutex) { if (_dropped) return; EDB.WriteLine("Creating intraprocess link for topic [{0}]", name); LocalPublisherLink pub_link = new LocalPublisherLink(this, XmlRpcManager.Instance.uri); LocalSubscriberLink sub_link = new LocalSubscriberLink(pub); pub_link.setPublisher(sub_link); sub_link.setSubscriber(pub_link); addPublisherLink(pub_link); pub.addSubscriberLink(sub_link); } } public void getPublishTypes(ref bool ser, ref bool nocopy, MsgTypes ti) { lock (callbacks_mutex) { foreach (ICallbackInfo info in callbacks) { if (info.helper.type == ti) nocopy = true; else ser = true; if (nocopy && ser) return; } } } #region Nested type: CallbackInfo #if !TRACE [DebuggerStepThrough] #endif public class CallbackInfo<M> : ICallbackInfo where M : IRosMessage, new() { public CallbackInfo() { helper = new SubscriptionCallbackHelper<M>(new M().msgtype()); } } #endregion #region Nested type: ICallbackInfo #if !TRACE [DebuggerStepThrough] #endif public class ICallbackInfo { public CallbackQueueInterface callback; public ISubscriptionCallbackHelper helper; public CallbackInterface subscription_queue; public UInt64 Get() { return subscription_queue.Get(); } } #endregion #region Nested type: LatchInfo #if !TRACE [DebuggerStepThrough] #endif public class LatchInfo { public IDictionary connection_header; public PublisherLink link; public IRosMessage message; public TimeData receipt_time; } #endregion } }
#region Disclaimer/Info /////////////////////////////////////////////////////////////////////////////////////////////////// // Subtext WebLog // // Subtext is an open source weblog system that is a fork of the .TEXT // weblog system. // // For updated news and information please visit http://subtextproject.com/ // Subtext is hosted at SourceForge at http://sourceforge.net/projects/subtext // The development mailing list is at [email protected] // // This project is licensed under the BSD license. See the License.txt file for more information. /////////////////////////////////////////////////////////////////////////////////////////////////// #endregion using System; using System.Collections.Specialized; using System.IO; using System.Text; using System.Web.Hosting; namespace Subtext.TestLibrary { /// <summary> /// Used to simulate an HttpRequest. /// </summary> public class SimulatedHttpRequest : SimpleWorkerRequest { Uri _referer; string _host; string _verb; int _port; string _physicalFilePath; /// <summary> /// Creates a new <see cref="SimulatedHttpRequest"/> instance. /// </summary> /// <param name="applicationPath">App virtual dir.</param> /// <param name="physicalAppPath">Physical Path to the app.</param> /// <param name="physicalFilePath">Physical Path to the file.</param> /// <param name="page">The Part of the URL after the application.</param> /// <param name="query">Query.</param> /// <param name="output">Output.</param> /// <param name="host">Host.</param> /// <param name="port">Port to request.</param> /// <param name="verb">The HTTP Verb to use.</param> public SimulatedHttpRequest(string applicationPath, string physicalAppPath, string physicalFilePath, string page, string query, TextWriter output, string host, int port, string verb) : base(applicationPath, physicalAppPath, page, query, output) { if (host == null) throw new ArgumentNullException("host", "Host cannot be null."); if(host.Length == 0) throw new ArgumentException("Host cannot be empty.", "host"); if (applicationPath == null) throw new ArgumentNullException("applicationPath", "Can't create a request with a null application path. Try empty string."); _host = host; _verb = verb; _port = port; _physicalFilePath = physicalFilePath; } internal void SetReferer(Uri referer) { _referer = referer; } /// <summary> /// Returns the specified member of the request header. /// </summary> /// <returns> /// The HTTP verb returned in the request /// header. /// </returns> public override string GetHttpVerbName() { return _verb; } /// <summary> /// Gets the name of the server. /// </summary> /// <returns></returns> public override string GetServerName() { return _host; } public override int GetLocalPort() { return this._port; } /// <summary> /// Gets the headers. /// </summary> /// <value>The headers.</value> public NameValueCollection Headers { get { return this.headers; } } private NameValueCollection headers = new NameValueCollection(); /// <summary> /// Gets the format exception. /// </summary> /// <value>The format exception.</value> public NameValueCollection Form { get { return formVariables; } } private NameValueCollection formVariables = new NameValueCollection(); /// <summary> /// Get all nonstandard HTTP header name-value pairs. /// </summary> /// <returns>An array of header name-value pairs.</returns> public override string[][] GetUnknownRequestHeaders() { if(this.headers == null || this.headers.Count == 0) { return null; } string[][] headersArray = new string[this.headers.Count][]; for(int i = 0; i < this.headers.Count; i++) { headersArray[i] = new string[2]; headersArray[i][0] = this.headers.Keys[i]; headersArray[i][1] = this.headers[i]; } return headersArray; } public override string GetKnownRequestHeader(int index) { if (index == 0x24) return _referer == null ? string.Empty : _referer.ToString(); if (index == 12 && this._verb == "POST") return "application/x-www-form-urlencoded"; return base.GetKnownRequestHeader(index); } /// <summary> /// Returns the virtual path to the currently executing /// server application. /// </summary> /// <returns> /// The virtual path of the current application. /// </returns> public override string GetAppPath() { string appPath = base.GetAppPath(); return appPath; } public override string GetAppPathTranslated() { string path = base.GetAppPathTranslated(); return path; } public override string GetUriPath() { string uriPath = base.GetUriPath(); return uriPath; } public override string GetFilePathTranslated() { return _physicalFilePath; } /// <summary> /// Reads request data from the client (when not preloaded). /// </summary> /// <returns>The number of bytes read.</returns> public override byte[] GetPreloadedEntityBody() { string formText = string.Empty; foreach(string key in this.formVariables.Keys) { formText += string.Format("{0}={1}&", key, this.formVariables[key]); } return Encoding.UTF8.GetBytes(formText); } /// <summary> /// Returns a value indicating whether all request data /// is available and no further reads from the client are required. /// </summary> /// <returns> /// <see langword="true"/> if all request data is available; otherwise, /// <see langword="false"/>. /// </returns> public override bool IsEntireEntityBodyIsPreloaded() { return true; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Xunit; namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.cnstrctor01.cnstrctor01 { using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.cnstrctor01.cnstrctor01; // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a constructor with OP</Description> // <Expects status=success></Expects> // <Code> public class Parent { public Parent(dynamic i = null) { } public dynamic Foo() { return 0; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Parent p = new Parent(); return p.Foo(); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.cnstrctor01a.cnstrctor01a { using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.cnstrctor01a.cnstrctor01a; // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a constructor with OP</Description> // <Expects status=success></Expects> // <Code> public class Parent { public Parent(dynamic i = default(object)) { } public int Foo() { return 0; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { int? a = null; Parent p = new Parent(a); return p.Foo(); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.cnstrctor02.cnstrctor02 { using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.cnstrctor02.cnstrctor02; // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a constructor with OP</Description> // <Expects status=success></Expects> // <Code> public class Parent { public Parent(dynamic i = default(dynamic), dynamic j = null) { } public int Foo() { return 0; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Parent p = new Parent(); return p.Foo(); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.cnstrctor04.cnstrctor04 { using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.cnstrctor04.cnstrctor04; // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a constructor with OP</Description> // <Expects status=success></Expects> // <Code> public class Parent { public Parent(dynamic i, int j = 1) { } public int Foo() { return 0; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Parent p = new Parent(i: 1); return p.Foo(); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.cnstrctor04a.cnstrctor04a { using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.cnstrctor04a.cnstrctor04a; // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a constructor with OP</Description> // <Expects status=success></Expects> // <Code> public class Parent { public Parent(dynamic i, int j = 1) { } public int Foo() { return 0; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic i = 1; dynamic p = new Parent(i, j: i); return p.Foo(); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.decl01.decl01 { using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.decl01.decl01; // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a method with optional parameters</Description> // <Expects status=success></Expects> // <Code> public class Parent { public int Foo(dynamic x = null, dynamic y = null) { if (x == null && y == null) return 0; return 1; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Parent p = new Parent(); return p.Foo(); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.decl01a.decl01a { using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.decl01a.decl01a; // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a method with optional parameters</Description> // <Expects status=success></Expects> // <Code> public class Parent { public int Foo(int? x = 2, int? y = 1) { if (x == null && y == 1) return 0; return 1; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic x = default(int?); dynamic p = new Parent(); return p.Foo(x); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.decl03a.decl03a { using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.decl03a.decl03a; // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a method with optional parameters</Description> // <Expects status=success></Expects> // <Code> public class Parent { public int Foo(dynamic x, int? y = 1) { if (x == 2 && y == 1) return 0; return 1; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { int? x = 2; Parent p = new Parent(); return p.Foo(x); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.decl05.decl05 { using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.decl05.decl05; // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a method with optional parameters. multiple optional parameters</Description> // <Expects status=success></Expects> // <Code> public class Parent { public int Foo(int z, dynamic x = default(dynamic), dynamic y = default(object)) { if (z == 1 && x == null && y == null) return 0; return 1; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Parent p = new Parent(); return p.Foo(1); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.decl05a.decl05a { using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.decl05a.decl05a; // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a method with optional parameters. multiple optional parameters</Description> // <Expects status=success></Expects> // <Code> public class Parent { public int Foo(int? z, int x = 2, int y = 1) { if (z == 1 && x == 2 && y == 1) return 0; return 1; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic z = 1; Parent p = new Parent(); return p.Foo(z); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.decl06a.decl06a { using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.decl06a.decl06a; // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a method with optional parameters. Expressions ued</Description> // <Expects status=success></Expects> // <Code> public class Parent { public int Foo(int? z = 1 + 1) { if (z == 2) return 0; return 1; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic p = new Parent(); return p.Foo(); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.decl07a.decl07a { using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.decl07a.decl07a; // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a method with optional parameters. Max int</Description> // <Expects status=success></Expects> // <Code> public class Parent { public int Foo(int? z = 2147483647) { if (z == 2147483647) return 0; return 1; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic p = new Parent(); return p.Foo(); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.decl09a.decl09a { using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.decl09a.decl09a; // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a method with optional parameters. cast of an int to long</Description> // <Expects status=success></Expects> // <Code> public class Parent { public int Foo(long? z = (long)1) { if (z == 1) return 0; return 1; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic p = new Parent(); return p.Foo(); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.decl12.decl12 { using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.decl12.decl12; // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a method with optional parameters. cast of an int to long</Description> // <Expects status=success></Expects> // <Code> using System.Runtime.InteropServices; public class Parent { public int Foo( [Optional] dynamic i) { if (i == System.Type.Missing) return 0; return 1; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Parent p = new Parent(); return p.Foo(); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.decl12a.decl12a { using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.decl12a.decl12a; // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a method with optional parameters. cast of an int to long</Description> // <Expects status=success></Expects> // <Code> using System.Runtime.InteropServices; public class Parent { public int Foo( [Optional] int ? i) { if (i == null) return 0; return 1; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic p = new Parent(); return p.Foo(); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.decl13.decl13 { using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.decl13.decl13; // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a method with optional params specified via opt attribute</Description> // <Expects status=success></Expects> // <Code> using System.Runtime.InteropServices; public class Parent { public int Foo( [Optional] dynamic i, [Optional] dynamic j, [Optional] dynamic f, [Optional] dynamic d) { if (d == System.Type.Missing) return 0; return 1; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Parent p = new Parent(); return p.Foo(); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.decl13a.decl13a { using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.decl13a.decl13a; // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a method with optional params specified via opt attribute</Description> // <Expects status=success></Expects> // <Code> using System.Runtime.InteropServices; public class Parent { public int Foo( [Optional] int ? i, [Optional] long ? j, [Optional] float ? f, [Optional] decimal ? d) { if (d == null) return 0; return 1; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic p = new Parent(); return p.Foo(); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.decl14a.decl14a { using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.decl14a.decl14a; // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description> Declaration of OPs with constant values</Description> // <Expects status=success></Expects> // <Code> public class Parent { private const int x = 1; public int Foo(int? z = x) { if (z == 1) return 0; return 1; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic p = new Parent(); return p.Foo(); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.decl16a.decl16a { using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.decl16a.decl16a; // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description> Declaration of OPs with constant values</Description> // <Expects status=success></Expects> // <Code> public class Parent { private const int x = 1; public int Foo(bool? z = true) { if (z.Value) return 0; return 1; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic p = new Parent(); return p.Foo(); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.decl16b.decl16b { using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.decl16b.decl16b; // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description> Declaration of OPs with constant values</Description> // <Expects status=success></Expects> // <Code> public class Parent { private const int x = 1; public int Foo(bool z = true) { if (z) return 0; return 1; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Parent p = new Parent(); return p.Foo(); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.decl18a.decl18a { using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.decl18a.decl18a; // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description> Declaration of OPs with constant values</Description> // <Expects status=success></Expects> // <Code> public class Parent { private const string x = "test"; public int Foo(string z = x) { if (z == "test") return 0; return 1; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic p = new Parent(); return p.Foo(); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.decl19a.decl19a { using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.decl19a.decl19a; // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description> Declaration of OPs with constant values</Description> // <Expects status=success></Expects> // <Code> public class Parent { private const bool x = true; public int Foo(bool? z = x) { if ((bool)z) return 0; return 1; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic p = new Parent(); return p.Foo(); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.decl20a.decl20a { using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.decl20a.decl20a; // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description> Declaration of OPs with constant values</Description> // <Expects status=success></Expects> // <Code> public class Parent { public int Foo(string z = "test", int? y = 3) { if (z == "test" && y == 3) return 1; return 1; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic p = new Parent(); try { p.Foo(3, "test"); } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e) { bool ret = ErrorVerifier.Verify(ErrorMessageId.BadArgTypes, e.Message, "Parent.Foo(string, int?)"); if (ret) return 0; } return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.generic01.generic01 { using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.generic01.generic01; // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description> Declaration of OPs with constant values</Description> // <Expects status=success></Expects> // <Code> public class Parent<T> where T : class { public int Foo(T t = null) { if (t == null) return 0; return 1; } } public class Foo { } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic p = new Parent<Foo>(); return p.Foo(); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.generic02.generic02 { using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.generic02.generic02; // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description> Declaration of OPs with constant values</Description> // <Expects status=success></Expects> // <Code> public class Parent<T> { public int Foo(T t = default(T)) { if (t == null) return 0; return 1; } } public class Foo { } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic p = new Parent<Foo>(); return p.Foo(); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.indexer02.indexer02 { using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.indexer02.indexer02; // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of an indexer with optional parameters</Description> // <Expects status=success></Expects> // <Code> public class Parent { public int this[dynamic index = null, dynamic index2 = default(dynamic)] { get { return index2 ?? 1 - index; } set { } } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Parent p = new Parent(); return p[1]; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.indexer02a.indexer02a { using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.indexer02a.indexer02a; // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of an indexer with optional parameters</Description> // <Expects status=success></Expects> // <Code> public class Parent { public int this[int? index = 1, int? index2 = 1] { get { return (int)index2 - 1; } set { } } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic p = new Parent(); dynamic d = 1; return p[d]; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.indexer03a.indexer03a { using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.indexer03a.indexer03a; // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of an indexer with optional parameters</Description> // <Expects status=success></Expects> // <Code> public class Parent { public int this[int? index = 1, long? index2 = 1] { get { return (int)(index2 - 1); } set { } } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic p = new Parent(); dynamic d = 1; return p[d]; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.indexer05.indexer05 { using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.indexer05.indexer05; // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of an indexer with optional parameters</Description> // <Expects status=success></Expects> // <Code> public class Parent { public int this[int index = 1, dynamic index2 = null] { get { return index2 == null ? 0 : 1; } set { } } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Parent p = new Parent(); return p[1]; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.indexer05a.indexer05a { using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.indexer05a.indexer05a; // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of an indexer with optional parameters</Description> // <Expects status=success></Expects> // <Code> public class Parent { public int this[int? index = 1, string index2 = "test"] { get { return index2 == "test" ? 0 : 1; } set { } } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic d = 1; dynamic p = new Parent(); return p[d]; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.indexer06a.indexer06a { using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.indexer06a.indexer06a; // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of an indexer with optional parameters</Description> // <Expects status=success></Expects> // <Code> public struct S { public int x; } public class Parent { public int this[int? index = 1, S s = default(S)] { get { return s.x == 0 ? 0 : 1; } set { } } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic d = 1; dynamic p = new Parent(); return p[d]; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.indexer07a.indexer07a { using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.indexer07a.indexer07a; // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of an indexer with optional parameters</Description> // <Expects status=success></Expects> // <Code> public class S { } public class Parent { public int this[int? index = 1, S s = null] { get { return s == null ? 0 : 1; } set { } } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic d = 1; dynamic p = new Parent(); return p[d]; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.indexer08.indexer08 { using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.indexer08.indexer08; // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of an indexer with optional parameters</Description> // <Expects status=success></Expects> // <Code> public class Parent { public int this[dynamic index = null, int? s = null] { get { return s == null ? 0 : 1; } set { } } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Parent p = new Parent(); return p[1]; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.indexer08a.indexer08a { using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.indexer08a.indexer08a; // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of an indexer with optional parameters</Description> // <Expects status=success></Expects> // <Code> public class Parent { public int this[int? index = 1, int? s = null] { get { return s == null ? 0 : 1; } set { } } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic d = 1; dynamic p = new Parent(); return p[d]; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.indexer09a.indexer09a { using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.indexer09a.indexer09a; // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of an indexer with optional parameters</Description> // <Expects status=success></Expects> // <Code> public class Parent { public int this[int? index = 1, int? s = 0] { get { return s == 0 ? 0 : 1; } set { } } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic d = 1; dynamic p = new Parent(); return p[d]; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.prms02.prms02 { using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.prms02.prms02; // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a method with optional parameters // Optional before params should be allowed</Description> // <Expects status=success></Expects> // <Code> public class Parent { public int Foo(dynamic x = default(dynamic), params object[] array) { if (x == null) return 0; return 1; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Parent p = new Parent(); return p.Foo(); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.prms02a.prms02a { using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.prms02a.prms02a; // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a method with optional parameters // Optional before params should be allowed</Description> // <Expects status=success></Expects> // <Code> public class Parent { public int Foo(int? x = 2, params object[] array) { if (x == 2) return 0; return 1; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic p = new Parent(); return p.Foo(); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.prms08.prms08 { using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.prms08.prms08; // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a method with optional parameters // Params can't be defaulted</Description> // <Expects status=success></Expects> // <Code> public class Parent { public int Foo(dynamic x = null, params dynamic[] array) { x = 2; if (x == 2) return 0; return 1; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Parent p = new Parent(); return p.Foo(); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.prms08a.prms08a { using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.prms08a.prms08a; // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a method with optional parameters // Params can't be defaulted</Description> // <Expects status=success></Expects> // <Code> public class Parent { public int Foo(int? x = 2, params object[] array) { x = 2; if (x == 2) return 0; return 1; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic p = new Parent(); return p.Foo(); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.prms09.prms09 { using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.prms09.prms09; // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a method with optional parameters // Params can't be defaulted</Description> // <Expects status=success></Expects> // <Code> public class Parent { public int Foo(dynamic x = null, params dynamic[] array) { if (x == 1 && array.Length == 3) return 0; return 1; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Parent p = new Parent(); return p.Foo(1, 2, 3, 4); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.prms09a.prms09a { using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.prms09a.prms09a; // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a method with optional parameters // Params can't be defaulted</Description> // <Expects status=success></Expects> // <Code> public class Parent { public int Foo(int? x = 2, params object[] array) { x = 2; if (array == null) return 1; return 0; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic d1 = 1; dynamic d2 = 2; dynamic d3 = 3; dynamic d4 = 4; dynamic p = new Parent(); return p.Foo(d1, d2, d3, d4); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.prms10a.prms10a { using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.prms10a.prms10a; // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a method with optional parameters // Params can't be defaulted</Description> // <Expects status=success></Expects> // <Code> public class Parent { public int Foo(int? x = 2, params object[] array) { x = 2; if (x == 2) return 0; return 1; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic d = 1; dynamic p = new Parent(); return p.Foo(d); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.prms11.prms11 { using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.prms11.prms11; // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a method with optional parameters // Params can't be defaulted</Description> // <Expects status=success></Expects> // <Code> public class Parent { public int Foo(params dynamic[] array) { if (array.Length == 0) return 1; return 0; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Parent p = new Parent(); return p.Foo(1); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.prms11a.prms11a { using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.prms11a.prms11a; // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a method with optional parameters // Params can't be defaulted</Description> // <Expects status=success></Expects> // <Code> public class Parent { public int Foo(params object[] array) { if (array.Length == 0) return 1; return 0; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic d = 1; dynamic p = new Parent(); return p.Foo(d); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.prms12.prms12 { using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.prms12.prms12; // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a method with optional parameters // Params can't be defaulted</Description> // <Expects status=success></Expects> // <Code> public class Parent { public int Foo(dynamic x = null, params dynamic[] array) { if (x == 1 && (array == null || array.Length == 0)) return 0; return 1; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Parent p = new Parent(); return p.Foo(1); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.prms12a.prms12a { using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.prms12a.prms12a; // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a method with optional parameters // Params can't be defaulted</Description> // <Expects status=success></Expects> // <Code> public class Parent { public int Foo(int? x = 2, params object[] array) { x = 2; if (array == null) return 1; return 0; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic d = 1; dynamic p = new Parent(); return p.Foo(d); } } //</Code> }
// 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; /// <summary> /// System.MathF.Tanh(bouble) /// </summary> public class MathFTanh { public static int Main() { MathFTanh mathTanh = new MathFTanh(); TestLibrary.TestFramework.BeginTestCase("MathFTanh"); if (mathTanh.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; retVal = PosTest5() && retVal; retVal = PosTest6() && retVal; retVal = PosTest7() && retVal; return retVal; } #region PositiveTest public bool PosTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest1: Caculate the tanh of 0 degrees"); try { float sourceA = 0; float desA = MathF.Tanh(sourceA); if (!MathFTestLib.SingleIsWithinEpsilon(desA, sourceA)) { TestLibrary.TestFramework.LogError("001", "Expected: 0, actual: " + desA.ToString() + "; diff > epsilon = " + MathFTestLib.Epsilon.ToString()); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Unexpected exception" + e); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest2: Calculate the tanh of 90 degrees"); try { float sourceA = 90; float desA = MathF.Tanh(sourceA * (MathF.PI / 180)); if (!MathFTestLib.SingleIsWithinEpsilon(desA, 0.917152336f)) { TestLibrary.TestFramework.LogError("003", "Expected: 0.917152336, actual: " + desA.ToString() + "; diff > epsilon = " + MathFTestLib.Epsilon.ToString()); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("004", "Unexpected exception" + e); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest3: Calculate the tanh of 180 degrees"); try { float sourceA = 180; float desA = MathF.Tan(sourceA * (MathF.PI / 180)); if (!MathFTestLib.SingleIsWithinEpsilon(desA, -0.0f)) { TestLibrary.TestFramework.LogError("005", "Expected: -0.0, actual: " + desA.ToString() + "; diff > epsilon = " + MathFTestLib.Epsilon.ToString()); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("006", "Unexpected exception" + e); retVal = false; } return retVal; } public bool PosTest4() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest4: Calculate the tanh of 45 degrees"); try { float sourceA = 45.0f; float desA = MathF.Tanh(sourceA * (MathF.PI / 180)); if (!MathFTestLib.SingleIsWithinEpsilon(desA, 0.655794203f)) { TestLibrary.TestFramework.LogError("007", "Expected: 0.655794203, actual: " + desA.ToString() + "; diff > epsilon = " + MathFTestLib.Epsilon.ToString()); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("008", "Unexpected exception" + e); retVal = false; } return retVal; } public bool PosTest5() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest5: tanh(NaN)=NaN"); try { float sourceA = float.NaN; float desA = MathF.Tanh(sourceA); if (!float.IsNaN(desA)) { TestLibrary.TestFramework.LogError("009", "Expected: NaN, actual: " + desA.ToString()); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("010", "Unexpected exception" + e); retVal = false; } return retVal; } public bool PosTest6() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest6: tanh(-inf)=-1"); try { float sourceA = float.NegativeInfinity; float desA = MathF.Tanh(sourceA); if (!MathFTestLib.SingleIsWithinEpsilon(desA, -1)) { TestLibrary.TestFramework.LogError("011", "Expected: -1, actual: " + desA.ToString()); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("012", "Unexpected exception" + e); retVal = false; } return retVal; } public bool PosTest7() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest7: tanh(+inf) = 1"); try { float sourceA = float.PositiveInfinity; float desA = MathF.Tanh(sourceA); if (!MathFTestLib.SingleIsWithinEpsilon(desA, 1)) { TestLibrary.TestFramework.LogError("013", "Expected 1, actual: " + desA.ToString()); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("014", "Unexpected exception" + e); retVal = false; } return retVal; } #endregion }
using System; using System.Collections.Generic; namespace Godot { /// <summary> /// This class contains color constants created from standardized color names. /// The standardized color set is based on the X11 and .NET color names. /// </summary> public static class Colors { // Color names and values are derived from core/color_names.inc internal static readonly Dictionary<string, Color> namedColors = new Dictionary<string, Color> { {"aliceblue", new Color(0.94f, 0.97f, 1.00f)}, {"antiquewhite", new Color(0.98f, 0.92f, 0.84f)}, {"aqua", new Color(0.00f, 1.00f, 1.00f)}, {"aquamarine", new Color(0.50f, 1.00f, 0.83f)}, {"azure", new Color(0.94f, 1.00f, 1.00f)}, {"beige", new Color(0.96f, 0.96f, 0.86f)}, {"bisque", new Color(1.00f, 0.89f, 0.77f)}, {"black", new Color(0.00f, 0.00f, 0.00f)}, {"blanchedalmond", new Color(1.00f, 0.92f, 0.80f)}, {"blue", new Color(0.00f, 0.00f, 1.00f)}, {"blueviolet", new Color(0.54f, 0.17f, 0.89f)}, {"brown", new Color(0.65f, 0.16f, 0.16f)}, {"burlywood", new Color(0.87f, 0.72f, 0.53f)}, {"cadetblue", new Color(0.37f, 0.62f, 0.63f)}, {"chartreuse", new Color(0.50f, 1.00f, 0.00f)}, {"chocolate", new Color(0.82f, 0.41f, 0.12f)}, {"coral", new Color(1.00f, 0.50f, 0.31f)}, {"cornflower", new Color(0.39f, 0.58f, 0.93f)}, {"cornsilk", new Color(1.00f, 0.97f, 0.86f)}, {"crimson", new Color(0.86f, 0.08f, 0.24f)}, {"cyan", new Color(0.00f, 1.00f, 1.00f)}, {"darkblue", new Color(0.00f, 0.00f, 0.55f)}, {"darkcyan", new Color(0.00f, 0.55f, 0.55f)}, {"darkgoldenrod", new Color(0.72f, 0.53f, 0.04f)}, {"darkgray", new Color(0.66f, 0.66f, 0.66f)}, {"darkgreen", new Color(0.00f, 0.39f, 0.00f)}, {"darkkhaki", new Color(0.74f, 0.72f, 0.42f)}, {"darkmagenta", new Color(0.55f, 0.00f, 0.55f)}, {"darkolivegreen", new Color(0.33f, 0.42f, 0.18f)}, {"darkorange", new Color(1.00f, 0.55f, 0.00f)}, {"darkorchid", new Color(0.60f, 0.20f, 0.80f)}, {"darkred", new Color(0.55f, 0.00f, 0.00f)}, {"darksalmon", new Color(0.91f, 0.59f, 0.48f)}, {"darkseagreen", new Color(0.56f, 0.74f, 0.56f)}, {"darkslateblue", new Color(0.28f, 0.24f, 0.55f)}, {"darkslategray", new Color(0.18f, 0.31f, 0.31f)}, {"darkturquoise", new Color(0.00f, 0.81f, 0.82f)}, {"darkviolet", new Color(0.58f, 0.00f, 0.83f)}, {"deeppink", new Color(1.00f, 0.08f, 0.58f)}, {"deepskyblue", new Color(0.00f, 0.75f, 1.00f)}, {"dimgray", new Color(0.41f, 0.41f, 0.41f)}, {"dodgerblue", new Color(0.12f, 0.56f, 1.00f)}, {"firebrick", new Color(0.70f, 0.13f, 0.13f)}, {"floralwhite", new Color(1.00f, 0.98f, 0.94f)}, {"forestgreen", new Color(0.13f, 0.55f, 0.13f)}, {"fuchsia", new Color(1.00f, 0.00f, 1.00f)}, {"gainsboro", new Color(0.86f, 0.86f, 0.86f)}, {"ghostwhite", new Color(0.97f, 0.97f, 1.00f)}, {"gold", new Color(1.00f, 0.84f, 0.00f)}, {"goldenrod", new Color(0.85f, 0.65f, 0.13f)}, {"gray", new Color(0.75f, 0.75f, 0.75f)}, {"green", new Color(0.00f, 1.00f, 0.00f)}, {"greenyellow", new Color(0.68f, 1.00f, 0.18f)}, {"honeydew", new Color(0.94f, 1.00f, 0.94f)}, {"hotpink", new Color(1.00f, 0.41f, 0.71f)}, {"indianred", new Color(0.80f, 0.36f, 0.36f)}, {"indigo", new Color(0.29f, 0.00f, 0.51f)}, {"ivory", new Color(1.00f, 1.00f, 0.94f)}, {"khaki", new Color(0.94f, 0.90f, 0.55f)}, {"lavender", new Color(0.90f, 0.90f, 0.98f)}, {"lavenderblush", new Color(1.00f, 0.94f, 0.96f)}, {"lawngreen", new Color(0.49f, 0.99f, 0.00f)}, {"lemonchiffon", new Color(1.00f, 0.98f, 0.80f)}, {"lightblue", new Color(0.68f, 0.85f, 0.90f)}, {"lightcoral", new Color(0.94f, 0.50f, 0.50f)}, {"lightcyan", new Color(0.88f, 1.00f, 1.00f)}, {"lightgoldenrod", new Color(0.98f, 0.98f, 0.82f)}, {"lightgray", new Color(0.83f, 0.83f, 0.83f)}, {"lightgreen", new Color(0.56f, 0.93f, 0.56f)}, {"lightpink", new Color(1.00f, 0.71f, 0.76f)}, {"lightsalmon", new Color(1.00f, 0.63f, 0.48f)}, {"lightseagreen", new Color(0.13f, 0.70f, 0.67f)}, {"lightskyblue", new Color(0.53f, 0.81f, 0.98f)}, {"lightslategray", new Color(0.47f, 0.53f, 0.60f)}, {"lightsteelblue", new Color(0.69f, 0.77f, 0.87f)}, {"lightyellow", new Color(1.00f, 1.00f, 0.88f)}, {"lime", new Color(0.00f, 1.00f, 0.00f)}, {"limegreen", new Color(0.20f, 0.80f, 0.20f)}, {"linen", new Color(0.98f, 0.94f, 0.90f)}, {"magenta", new Color(1.00f, 0.00f, 1.00f)}, {"maroon", new Color(0.69f, 0.19f, 0.38f)}, {"mediumaquamarine", new Color(0.40f, 0.80f, 0.67f)}, {"mediumblue", new Color(0.00f, 0.00f, 0.80f)}, {"mediumorchid", new Color(0.73f, 0.33f, 0.83f)}, {"mediumpurple", new Color(0.58f, 0.44f, 0.86f)}, {"mediumseagreen", new Color(0.24f, 0.70f, 0.44f)}, {"mediumslateblue", new Color(0.48f, 0.41f, 0.93f)}, {"mediumspringgreen", new Color(0.00f, 0.98f, 0.60f)}, {"mediumturquoise", new Color(0.28f, 0.82f, 0.80f)}, {"mediumvioletred", new Color(0.78f, 0.08f, 0.52f)}, {"midnightblue", new Color(0.10f, 0.10f, 0.44f)}, {"mintcream", new Color(0.96f, 1.00f, 0.98f)}, {"mistyrose", new Color(1.00f, 0.89f, 0.88f)}, {"moccasin", new Color(1.00f, 0.89f, 0.71f)}, {"navajowhite", new Color(1.00f, 0.87f, 0.68f)}, {"navyblue", new Color(0.00f, 0.00f, 0.50f)}, {"oldlace", new Color(0.99f, 0.96f, 0.90f)}, {"olive", new Color(0.50f, 0.50f, 0.00f)}, {"olivedrab", new Color(0.42f, 0.56f, 0.14f)}, {"orange", new Color(1.00f, 0.65f, 0.00f)}, {"orangered", new Color(1.00f, 0.27f, 0.00f)}, {"orchid", new Color(0.85f, 0.44f, 0.84f)}, {"palegoldenrod", new Color(0.93f, 0.91f, 0.67f)}, {"palegreen", new Color(0.60f, 0.98f, 0.60f)}, {"paleturquoise", new Color(0.69f, 0.93f, 0.93f)}, {"palevioletred", new Color(0.86f, 0.44f, 0.58f)}, {"papayawhip", new Color(1.00f, 0.94f, 0.84f)}, {"peachpuff", new Color(1.00f, 0.85f, 0.73f)}, {"peru", new Color(0.80f, 0.52f, 0.25f)}, {"pink", new Color(1.00f, 0.75f, 0.80f)}, {"plum", new Color(0.87f, 0.63f, 0.87f)}, {"powderblue", new Color(0.69f, 0.88f, 0.90f)}, {"purple", new Color(0.63f, 0.13f, 0.94f)}, {"rebeccapurple", new Color(0.40f, 0.20f, 0.60f)}, {"red", new Color(1.00f, 0.00f, 0.00f)}, {"rosybrown", new Color(0.74f, 0.56f, 0.56f)}, {"royalblue", new Color(0.25f, 0.41f, 0.88f)}, {"saddlebrown", new Color(0.55f, 0.27f, 0.07f)}, {"salmon", new Color(0.98f, 0.50f, 0.45f)}, {"sandybrown", new Color(0.96f, 0.64f, 0.38f)}, {"seagreen", new Color(0.18f, 0.55f, 0.34f)}, {"seashell", new Color(1.00f, 0.96f, 0.93f)}, {"sienna", new Color(0.63f, 0.32f, 0.18f)}, {"silver", new Color(0.75f, 0.75f, 0.75f)}, {"skyblue", new Color(0.53f, 0.81f, 0.92f)}, {"slateblue", new Color(0.42f, 0.35f, 0.80f)}, {"slategray", new Color(0.44f, 0.50f, 0.56f)}, {"snow", new Color(1.00f, 0.98f, 0.98f)}, {"springgreen", new Color(0.00f, 1.00f, 0.50f)}, {"steelblue", new Color(0.27f, 0.51f, 0.71f)}, {"tan", new Color(0.82f, 0.71f, 0.55f)}, {"teal", new Color(0.00f, 0.50f, 0.50f)}, {"thistle", new Color(0.85f, 0.75f, 0.85f)}, {"tomato", new Color(1.00f, 0.39f, 0.28f)}, {"transparent", new Color(1.00f, 1.00f, 1.00f, 0.00f)}, {"turquoise", new Color(0.25f, 0.88f, 0.82f)}, {"violet", new Color(0.93f, 0.51f, 0.93f)}, {"webgreen", new Color(0.00f, 0.50f, 0.00f)}, {"webgray", new Color(0.50f, 0.50f, 0.50f)}, {"webmaroon", new Color(0.50f, 0.00f, 0.00f)}, {"webpurple", new Color(0.50f, 0.00f, 0.50f)}, {"wheat", new Color(0.96f, 0.87f, 0.70f)}, {"white", new Color(1.00f, 1.00f, 1.00f)}, {"whitesmoke", new Color(0.96f, 0.96f, 0.96f)}, {"yellow", new Color(1.00f, 1.00f, 0.00f)}, {"yellowgreen", new Color(0.60f, 0.80f, 0.20f)}, }; public static Color AliceBlue { get { return namedColors["aliceblue"]; } } public static Color AntiqueWhite { get { return namedColors["antiquewhite"]; } } public static Color Aqua { get { return namedColors["aqua"]; } } public static Color Aquamarine { get { return namedColors["aquamarine"]; } } public static Color Azure { get { return namedColors["azure"]; } } public static Color Beige { get { return namedColors["beige"]; } } public static Color Bisque { get { return namedColors["bisque"]; } } public static Color Black { get { return namedColors["black"]; } } public static Color BlanchedAlmond { get { return namedColors["blanchedalmond"]; } } public static Color Blue { get { return namedColors["blue"]; } } public static Color BlueViolet { get { return namedColors["blueviolet"]; } } public static Color Brown { get { return namedColors["brown"]; } } public static Color BurlyWood { get { return namedColors["burlywood"]; } } public static Color CadetBlue { get { return namedColors["cadetblue"]; } } public static Color Chartreuse { get { return namedColors["chartreuse"]; } } public static Color Chocolate { get { return namedColors["chocolate"]; } } public static Color Coral { get { return namedColors["coral"]; } } public static Color Cornflower { get { return namedColors["cornflower"]; } } public static Color Cornsilk { get { return namedColors["cornsilk"]; } } public static Color Crimson { get { return namedColors["crimson"]; } } public static Color Cyan { get { return namedColors["cyan"]; } } public static Color DarkBlue { get { return namedColors["darkblue"]; } } public static Color DarkCyan { get { return namedColors["darkcyan"]; } } public static Color DarkGoldenrod { get { return namedColors["darkgoldenrod"]; } } public static Color DarkGray { get { return namedColors["darkgray"]; } } public static Color DarkGreen { get { return namedColors["darkgreen"]; } } public static Color DarkKhaki { get { return namedColors["darkkhaki"]; } } public static Color DarkMagenta { get { return namedColors["darkmagenta"]; } } public static Color DarkOliveGreen { get { return namedColors["darkolivegreen"]; } } public static Color DarkOrange { get { return namedColors["darkorange"]; } } public static Color DarkOrchid { get { return namedColors["darkorchid"]; } } public static Color DarkRed { get { return namedColors["darkred"]; } } public static Color DarkSalmon { get { return namedColors["darksalmon"]; } } public static Color DarkSeaGreen { get { return namedColors["darkseagreen"]; } } public static Color DarkSlateBlue { get { return namedColors["darkslateblue"]; } } public static Color DarkSlateGray { get { return namedColors["darkslategray"]; } } public static Color DarkTurquoise { get { return namedColors["darkturquoise"]; } } public static Color DarkViolet { get { return namedColors["darkviolet"]; } } public static Color DeepPink { get { return namedColors["deeppink"]; } } public static Color DeepSkyBlue { get { return namedColors["deepskyblue"]; } } public static Color DimGray { get { return namedColors["dimgray"]; } } public static Color DodgerBlue { get { return namedColors["dodgerblue"]; } } public static Color Firebrick { get { return namedColors["firebrick"]; } } public static Color FloralWhite { get { return namedColors["floralwhite"]; } } public static Color ForestGreen { get { return namedColors["forestgreen"]; } } public static Color Fuchsia { get { return namedColors["fuchsia"]; } } public static Color Gainsboro { get { return namedColors["gainsboro"]; } } public static Color GhostWhite { get { return namedColors["ghostwhite"]; } } public static Color Gold { get { return namedColors["gold"]; } } public static Color Goldenrod { get { return namedColors["goldenrod"]; } } public static Color Gray { get { return namedColors["gray"]; } } public static Color Green { get { return namedColors["green"]; } } public static Color GreenYellow { get { return namedColors["greenyellow"]; } } public static Color Honeydew { get { return namedColors["honeydew"]; } } public static Color HotPink { get { return namedColors["hotpink"]; } } public static Color IndianRed { get { return namedColors["indianred"]; } } public static Color Indigo { get { return namedColors["indigo"]; } } public static Color Ivory { get { return namedColors["ivory"]; } } public static Color Khaki { get { return namedColors["khaki"]; } } public static Color Lavender { get { return namedColors["lavender"]; } } public static Color LavenderBlush { get { return namedColors["lavenderblush"]; } } public static Color LawnGreen { get { return namedColors["lawngreen"]; } } public static Color LemonChiffon { get { return namedColors["lemonchiffon"]; } } public static Color LightBlue { get { return namedColors["lightblue"]; } } public static Color LightCoral { get { return namedColors["lightcoral"]; } } public static Color LightCyan { get { return namedColors["lightcyan"]; } } public static Color LightGoldenrod { get { return namedColors["lightgoldenrod"]; } } public static Color LightGray { get { return namedColors["lightgray"]; } } public static Color LightGreen { get { return namedColors["lightgreen"]; } } public static Color LightPink { get { return namedColors["lightpink"]; } } public static Color LightSalmon { get { return namedColors["lightsalmon"]; } } public static Color LightSeaGreen { get { return namedColors["lightseagreen"]; } } public static Color LightSkyBlue { get { return namedColors["lightskyblue"]; } } public static Color LightSlateGray { get { return namedColors["lightslategray"]; } } public static Color LightSteelBlue { get { return namedColors["lightsteelblue"]; } } public static Color LightYellow { get { return namedColors["lightyellow"]; } } public static Color Lime { get { return namedColors["lime"]; } } public static Color Limegreen { get { return namedColors["limegreen"]; } } public static Color Linen { get { return namedColors["linen"]; } } public static Color Magenta { get { return namedColors["magenta"]; } } public static Color Maroon { get { return namedColors["maroon"]; } } public static Color MediumAquamarine { get { return namedColors["mediumaquamarine"]; } } public static Color MediumBlue { get { return namedColors["mediumblue"]; } } public static Color MediumOrchid { get { return namedColors["mediumorchid"]; } } public static Color MediumPurple { get { return namedColors["mediumpurple"]; } } public static Color MediumSeaGreen { get { return namedColors["mediumseagreen"]; } } public static Color MediumSlateBlue { get { return namedColors["mediumslateblue"]; } } public static Color MediumSpringGreen { get { return namedColors["mediumspringgreen"]; } } public static Color MediumTurquoise { get { return namedColors["mediumturquoise"]; } } public static Color MediumVioletRed { get { return namedColors["mediumvioletred"]; } } public static Color MidnightBlue { get { return namedColors["midnightblue"]; } } public static Color MintCream { get { return namedColors["mintcream"]; } } public static Color MistyRose { get { return namedColors["mistyrose"]; } } public static Color Moccasin { get { return namedColors["moccasin"]; } } public static Color NavajoWhite { get { return namedColors["navajowhite"]; } } public static Color NavyBlue { get { return namedColors["navyblue"]; } } public static Color OldLace { get { return namedColors["oldlace"]; } } public static Color Olive { get { return namedColors["olive"]; } } public static Color OliveDrab { get { return namedColors["olivedrab"]; } } public static Color Orange { get { return namedColors["orange"]; } } public static Color OrangeRed { get { return namedColors["orangered"]; } } public static Color Orchid { get { return namedColors["orchid"]; } } public static Color PaleGoldenrod { get { return namedColors["palegoldenrod"]; } } public static Color PaleGreen { get { return namedColors["palegreen"]; } } public static Color PaleTurquoise { get { return namedColors["paleturquoise"]; } } public static Color PaleVioletRed { get { return namedColors["palevioletred"]; } } public static Color PapayaWhip { get { return namedColors["papayawhip"]; } } public static Color PeachPuff { get { return namedColors["peachpuff"]; } } public static Color Peru { get { return namedColors["peru"]; } } public static Color Pink { get { return namedColors["pink"]; } } public static Color Plum { get { return namedColors["plum"]; } } public static Color PowderBlue { get { return namedColors["powderblue"]; } } public static Color Purple { get { return namedColors["purple"]; } } public static Color RebeccaPurple { get { return namedColors["rebeccapurple"]; } } public static Color Red { get { return namedColors["red"]; } } public static Color RosyBrown { get { return namedColors["rosybrown"]; } } public static Color RoyalBlue { get { return namedColors["royalblue"]; } } public static Color SaddleBrown { get { return namedColors["saddlebrown"]; } } public static Color Salmon { get { return namedColors["salmon"]; } } public static Color SandyBrown { get { return namedColors["sandybrown"]; } } public static Color SeaGreen { get { return namedColors["seagreen"]; } } public static Color SeaShell { get { return namedColors["seashell"]; } } public static Color Sienna { get { return namedColors["sienna"]; } } public static Color Silver { get { return namedColors["silver"]; } } public static Color SkyBlue { get { return namedColors["skyblue"]; } } public static Color SlateBlue { get { return namedColors["slateblue"]; } } public static Color SlateGray { get { return namedColors["slategray"]; } } public static Color Snow { get { return namedColors["snow"]; } } public static Color SpringGreen { get { return namedColors["springgreen"]; } } public static Color SteelBlue { get { return namedColors["steelblue"]; } } public static Color Tan { get { return namedColors["tan"]; } } public static Color Teal { get { return namedColors["teal"]; } } public static Color Thistle { get { return namedColors["thistle"]; } } public static Color Tomato { get { return namedColors["tomato"]; } } public static Color Transparent { get { return namedColors["transparent"]; } } public static Color Turquoise { get { return namedColors["turquoise"]; } } public static Color Violet { get { return namedColors["violet"]; } } public static Color WebGreen { get { return namedColors["webgreen"]; } } public static Color WebGray { get { return namedColors["webgray"]; } } public static Color WebMaroon { get { return namedColors["webmaroon"]; } } public static Color WebPurple { get { return namedColors["webpurple"]; } } public static Color Wheat { get { return namedColors["wheat"]; } } public static Color White { get { return namedColors["white"]; } } public static Color WhiteSmoke { get { return namedColors["whitesmoke"]; } } public static Color Yellow { get { return namedColors["yellow"]; } } public static Color YellowGreen { get { return namedColors["yellowgreen"]; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.Xml.Serialization { using System; using System.Xml.Schema; using System.Collections; using System.ComponentModel; using System.Reflection; using System.Configuration; using System.Xml.Serialization.Configuration; using System.CodeDom; using System.CodeDom.Compiler; using System.Xml.Serialization.Advanced; #if DEBUG using System.Diagnostics; #endif /// <include file='doc\SchemaImporter.uex' path='docs/doc[@for="SchemaImporter"]/*' /> ///<internalonly/> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public abstract class SchemaImporter { private XmlSchemas _schemas; private StructMapping _root; private CodeGenerationOptions _options; private CodeDomProvider _codeProvider; private TypeScope _scope; private ImportContext _context; private bool _rootImported; private NameTable _typesInUse; private NameTable _groupsInUse; private SchemaImporterExtensionCollection _extensions; internal SchemaImporter(XmlSchemas schemas, CodeGenerationOptions options, CodeDomProvider codeProvider, ImportContext context) { if (!schemas.Contains(XmlSchema.Namespace)) { schemas.AddReference(XmlSchemas.XsdSchema); schemas.SchemaSet.Add(XmlSchemas.XsdSchema); } if (!schemas.Contains(XmlReservedNs.NsXml)) { schemas.AddReference(XmlSchemas.XmlSchema); schemas.SchemaSet.Add(XmlSchemas.XmlSchema); } _schemas = schemas; _options = options; _codeProvider = codeProvider; _context = context; Schemas.SetCache(Context.Cache, Context.ShareTypes); SchemaImporterExtensionsSection section = PrivilegedConfigurationManager.GetSection(ConfigurationStrings.SchemaImporterExtensionsSectionPath) as SchemaImporterExtensionsSection; if (section != null) _extensions = section.SchemaImporterExtensionsInternal; else _extensions = new SchemaImporterExtensionCollection(); } internal ImportContext Context { get { if (_context == null) _context = new ImportContext(); return _context; } } internal CodeDomProvider CodeProvider { get { if (_codeProvider == null) _codeProvider = new Microsoft.CSharp.CSharpCodeProvider(); return _codeProvider; } } public SchemaImporterExtensionCollection Extensions { get { if (_extensions == null) _extensions = new SchemaImporterExtensionCollection(); return _extensions; } } internal Hashtable ImportedElements { get { return Context.Elements; } } internal Hashtable ImportedMappings { get { return Context.Mappings; } } internal CodeIdentifiers TypeIdentifiers { get { return Context.TypeIdentifiers; } } internal XmlSchemas Schemas { get { if (_schemas == null) _schemas = new XmlSchemas(); return _schemas; } } internal TypeScope Scope { get { if (_scope == null) _scope = new TypeScope(); return _scope; } } internal NameTable GroupsInUse { get { if (_groupsInUse == null) _groupsInUse = new NameTable(); return _groupsInUse; } } internal NameTable TypesInUse { get { if (_typesInUse == null) _typesInUse = new NameTable(); return _typesInUse; } } internal CodeGenerationOptions Options { get { return _options; } } internal void MakeDerived(StructMapping structMapping, Type baseType, bool baseTypeCanBeIndirect) { structMapping.ReferencedByTopLevelElement = true; TypeDesc baseTypeDesc; if (baseType != null) { baseTypeDesc = Scope.GetTypeDesc(baseType); if (baseTypeDesc != null) { TypeDesc typeDescToChange = structMapping.TypeDesc; if (baseTypeCanBeIndirect) { // if baseTypeCanBeIndirect is true, we apply the supplied baseType to the top of the // inheritance chain, not necessarily directly to the imported type. while (typeDescToChange.BaseTypeDesc != null && typeDescToChange.BaseTypeDesc != baseTypeDesc) typeDescToChange = typeDescToChange.BaseTypeDesc; } if (typeDescToChange.BaseTypeDesc != null && typeDescToChange.BaseTypeDesc != baseTypeDesc) throw new InvalidOperationException(SR.Format(SR.XmlInvalidBaseType, structMapping.TypeDesc.FullName, baseType.FullName, typeDescToChange.BaseTypeDesc.FullName)); typeDescToChange.BaseTypeDesc = baseTypeDesc; } } } internal string GenerateUniqueTypeName(string typeName) { typeName = CodeIdentifier.MakeValid(typeName); return TypeIdentifiers.AddUnique(typeName, typeName); } private StructMapping CreateRootMapping() { TypeDesc typeDesc = Scope.GetTypeDesc(typeof(object)); StructMapping mapping = new StructMapping(); mapping.TypeDesc = typeDesc; mapping.Members = new MemberMapping[0]; mapping.IncludeInSchema = false; mapping.TypeName = Soap.UrType; mapping.Namespace = XmlSchema.Namespace; return mapping; } internal StructMapping GetRootMapping() { if (_root == null) _root = CreateRootMapping(); return _root; } internal StructMapping ImportRootMapping() { if (!_rootImported) { _rootImported = true; ImportDerivedTypes(XmlQualifiedName.Empty); } return GetRootMapping(); } internal abstract void ImportDerivedTypes(XmlQualifiedName baseName); internal void AddReference(XmlQualifiedName name, NameTable references, string error) { if (name.Namespace == XmlSchema.Namespace) return; if (references[name] != null) { throw new InvalidOperationException(string.Format(error, name.Name, name.Namespace)); } references[name] = name; } internal void RemoveReference(XmlQualifiedName name, NameTable references) { references[name] = null; } internal void AddReservedIdentifiersForDataBinding(CodeIdentifiers scope) { if ((_options & CodeGenerationOptions.EnableDataBinding) != 0) { scope.AddReserved(CodeExporter.PropertyChangedEvent.Name); scope.AddReserved(CodeExporter.RaisePropertyChangedEventMethod.Name); } } } }
using System; using System.Collections.Generic; using System.Linq; using DotVVM.Framework.Binding; using DotVVM.Framework.Binding.Expressions; using DotVVM.Framework.Compilation.ControlTree; using DotVVM.Framework.Compilation.ControlTree.Resolved; using DotVVM.Framework.Configuration; using DotVVM.Framework.Controls; using DotVVM.Framework.Utils; using Microsoft.Extensions.DependencyInjection; namespace DotVVM.Framework.Compilation.Styles { public interface IStyleApplicator { void ApplyStyle(ResolvedControl control, IStyleMatchContext context); } public sealed class MonoidStyleApplicator : IStyleApplicator { private readonly IEnumerable<IStyleApplicator> applicators; private MonoidStyleApplicator(IEnumerable<IStyleApplicator> applicators) { this.applicators = applicators; } public void ApplyStyle(ResolvedControl control, IStyleMatchContext context) { foreach (var a in this.applicators) a.ApplyStyle(control, context); } public static IStyleApplicator Empty = new MonoidStyleApplicator(Enumerable.Empty<IStyleApplicator>()); public static IStyleApplicator Combine(IEnumerable<IStyleApplicator> applicators) { applicators = applicators.Except(new [] { Empty }); var count = applicators.Take(2).Count(); if (count == 0) return Empty; else if (count == 1) return applicators.First(); else return new MonoidStyleApplicator(applicators); } public override string ToString() => !applicators.Any() ? "Empty" : $"All[ {string.Join(" , ", applicators)} ]"; } class PropertyStyleApplicator : IStyleApplicator { readonly DotvvmProperty property; readonly object? value; readonly StyleOverrideOptions options; public PropertyStyleApplicator(DotvvmProperty property, object? value, StyleOverrideOptions options) { this.property = property; this.value = value; this.options = options; } public void ApplyStyle(ResolvedControl control, IStyleMatchContext context) { var dataContext = property.GetDataContextType(control); var setter = ResolvedControlHelper.TranslateProperty(property, value, dataContext, context.Configuration); if (!control.SetProperty(setter, options, out var error)) throw new DotvvmCompilationException("Cannot apply style property: " + error, control.DothtmlNode?.Tokens); } public override string ToString() => $"{value} (on conflict {options})"; } public class GenericPropertyStyleApplicator<T> : IStyleApplicator { readonly DotvvmProperty property; readonly Func<IStyleMatchContext<T>, object?> value; readonly StyleOverrideOptions options; public GenericPropertyStyleApplicator(DotvvmProperty property, Func<IStyleMatchContext<T>, object?> value, StyleOverrideOptions options) { this.property = property; this.value = value; this.options = options; } public void ApplyStyle(ResolvedControl control, IStyleMatchContext context) { if (context.IsType<T>(out var c)) { var dataContext = property.GetDataContextType(control); var v = value(c); var setter = ResolvedControlHelper.TranslateProperty(property, v, dataContext, context.Configuration); if (!control.SetProperty(setter, options, out var error)) throw new DotvvmCompilationException("Cannot apply style property: " + error, control.DothtmlNode?.Tokens); } } public override string ToString() => $"GenericPropertyStyleApplicator {property} (on conflict {options})"; } internal class PropertyStyleBindingApplicator : IStyleApplicator { private readonly DotvvmProperty property; private readonly string binding; private readonly StyleOverrideOptions options; private readonly BindingParserOptions bindingOptions; private readonly bool allowChangingBindingType; public PropertyStyleBindingApplicator(DotvvmProperty property, string binding, StyleOverrideOptions options, BindingParserOptions bindingOptions, bool allowChangingBindingType = false) { if (property == DotvvmBindableObject.DataContextProperty) throw new NotSupportedException("Cannot set the DataContext property using styles. This property affects the compilation itself, and styles are applied after that."); if (!property.MarkupOptions.AllowBinding && bindingOptions.BindingType != typeof(ResourceBindingExpression)) throw new Exception($"Property {property} does not allow bindings to be set. You could maybe use a resource binding (set bindingOptions to BindingParserOptions.Resource)."); this.property = property; this.binding = binding; this.options = options; this.bindingOptions = bindingOptions; this.allowChangingBindingType = allowChangingBindingType; } public void ApplyStyle(ResolvedControl control, IStyleMatchContext context) { var dataContext = property.GetDataContextType(control); var bindingOptions = this.bindingOptions; if (allowChangingBindingType && control.Properties.GetValueOrDefault(property) is ResolvedPropertyBinding rb) { // when merging attributes, we need to have the same binding type // for example, when there already is a resource binding, we'll also put in a resource instead of failing compilation bindingOptions = rb.Binding.Binding.GetProperty<BindingParserOptions>(); } var b = new ResolvedBinding( context.Configuration.ServiceProvider.GetRequiredService<BindingCompilationService>(), bindingOptions, dataContext, code: binding, property: property ); if (!control.SetProperty(new ResolvedPropertyBinding(property, b), options, out var error)) throw new DotvvmCompilationException("Cannot apply style property binding: " + error, control.DothtmlNode?.Tokens); } public override string ToString() => $"{property}={{{bindingOptions.BindingType.Name}: {binding}}} (on conflict {options})"; } internal class PropertyControlCollectionStyleApplicator : IStyleApplicator { readonly DotvvmProperty property; readonly DotvvmBindableObject prototypeControl; readonly IStyle innerControlStyle; readonly StyleOverrideOptions options; public PropertyControlCollectionStyleApplicator( DotvvmProperty property, StyleOverrideOptions options, DotvvmBindableObject prototypeControl, IStyle innerControlStyle) { this.property = property; this.options = options; this.prototypeControl = prototypeControl; this.innerControlStyle = innerControlStyle; } public void ApplyStyle(ResolvedControl control, IStyleMatchContext context) { var dataContext = property.GetDataContextType(control); var innerControl = ResolvedControlHelper.FromRuntimeControl(this.prototypeControl, dataContext, context.Configuration); innerControl.Parent = control; innerControlStyle.Applicator.ApplyStyle(innerControl, new StyleMatchContext<DotvvmBindableObject>(context, innerControl, context.Configuration)); var value = ResolvedControlHelper.TranslateProperty(property, innerControl, dataContext, context.Configuration); if (!control.SetProperty(value, options, out var error)) throw new DotvvmCompilationException("Cannot apply style property: " + error, control.DothtmlNode?.Tokens); } public override string ToString() { var innerStyleFmt = innerControlStyle.Applicator == MonoidStyleApplicator.Empty ? "" : "\n " + innerControlStyle; var verb = options == StyleOverrideOptions.Ignore ? $"Set {property} if empty to " : $"{options} {property}: "; return $"{verb}{prototypeControl.DebugString()}{innerStyleFmt}"; } } internal class ChildrenStyleApplicator : IStyleApplicator { readonly FunctionOrValue<IStyleMatchContext, IEnumerable<DotvvmBindableObject>> prototypeControls; readonly IStyle innerControlsStyle; readonly StyleOverrideOptions options; public ChildrenStyleApplicator( StyleOverrideOptions options, FunctionOrValue<IStyleMatchContext, IEnumerable<DotvvmBindableObject>> prototypeControls, IStyle innerControlsStyle) { this.options = options; this.prototypeControls = prototypeControls; this.innerControlsStyle = innerControlsStyle; } public void ApplyStyle(ResolvedControl control, IStyleMatchContext context) { if (!context.AllowsContent()) throw new NotSupportedException($"Control {control.Metadata.Name} is not allowed to have content (it was attempted to set it using Styles). If you want to apply this style only controls that can have content, use the context.AllowsContent() method in the style condition."); var dataContext = context.ChildrenDataContextStack(); var innerControls = this.prototypeControls.Invoke(context).Select(c => ResolvedControlHelper.FromRuntimeControl(c, dataContext, context.Configuration)) .ToArray(); foreach (var c in innerControls) { if (c is null) continue; c.Parent = control; innerControlsStyle.Applicator.ApplyStyle(c, new StyleMatchContext<DotvvmBindableObject>(context, c, context.Configuration)); } ResolvedControlHelper.SetContent(control, innerControls, options); } public override string ToString() { var innerStyleFmt = innerControlsStyle.Applicator == MonoidStyleApplicator.Empty ? "" : "\n " + innerControlsStyle; var controlFmt = prototypeControls.DebugString(c => string.Join("\n", c.Select(c => c.DebugString())), "[the content is computed]"); var verb = options == StyleOverrideOptions.Ignore ? "Set content if empty" : $"{options} children"; return $"{verb} {controlFmt}{innerStyleFmt}"; } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Reflection; using System.Text; using System.Xml; using Palaso.Annotations; using Palaso.DictionaryServices.Model; using Palaso.Extensions; using Palaso.Lift; using Palaso.Lift.Options; using Palaso.Lift.Validation; using Palaso.Text; using Palaso.Xml; namespace Palaso.DictionaryServices.Lift { public class LiftWriter : ILiftWriter<LexEntry> { private readonly XmlWriter _writer; private readonly Dictionary<string, int> _allIdsExportedSoFar; #if DEBUG [CLSCompliant(false)] protected StackTrace _constructionStack; #endif private LiftWriter() { #if DEBUG _constructionStack = new StackTrace(); #endif _allIdsExportedSoFar = new Dictionary<string, int>(); } public enum ByteOrderStyle { BOM, NoBOM } ; /// <summary> /// /// </summary> /// <param name="path"></param> /// <param name="includeByteOrderMark">PrinceXML (at least v7 chokes if given a BOM, Lexique Pro chokes without it) </param> public LiftWriter(string path, ByteOrderStyle byteOrderStyle) : this() { _disposed = true; // Just in case we throw in the constructor var settings = CanonicalXmlSettings.CreateXmlWriterSettings(); settings.Encoding = new UTF8Encoding(byteOrderStyle == ByteOrderStyle.BOM); _writer = XmlWriter.Create(path, settings); Start(); _disposed = false; } public LiftWriter(StringBuilder builder, bool produceFragmentOnly): this() { _writer = XmlWriter.Create(builder, CanonicalXmlSettings.CreateXmlWriterSettings( produceFragmentOnly ? ConformanceLevel.Fragment : ConformanceLevel.Document) ); if (!produceFragmentOnly) { Start(); } } private void Start() { Writer.WriteStartDocument(); Writer.WriteStartElement("lift"); Writer.WriteAttributeString("version", Validator.LiftVersion); Writer.WriteAttributeString("producer", ProducerString); // _writer.WriteAttributeString("xmlns", "flex", null, "http://fieldworks.sil.org"); } public void WriteHeader(string headerConentsNotIncludingHeaderElement) { Writer.WriteStartElement("header"); Writer.WriteRaw(headerConentsNotIncludingHeaderElement); Writer.WriteEndElement(); } public static string ProducerString { get { return "Palaso.DictionaryServices.LiftWriter " + Assembly.GetExecutingAssembly().GetName().Version; } } protected XmlWriter Writer { get { return _writer; } } public void End() { if (Writer.Settings.ConformanceLevel != ConformanceLevel.Fragment) { #if MONO // If there are no open elements and you try to WriteEndElement then mono throws a // InvalidOperationException: There is no more open element // WriteEndDocument will close any open elements anyway // // If you try to WriteEndDocument on a closed writer then mono throws a // InvalidOperationException: This XmlWriter does not accept EndDocument at this state Closed if (Writer.WriteState != WriteState.Closed) Writer.WriteEndDocument(); #else Writer.WriteEndElement(); //lift Writer.WriteEndDocument(); #endif } Writer.Flush(); Writer.Close(); } public virtual void Add(LexEntry entry) { Add(entry, 0); } public void Add(LexEntry entry, int order) { List<string> propertiesAlreadyOutput = new List<string>(); Writer.WriteStartElement("entry"); Writer.WriteAttributeString("id", GetHumanReadableIdWithAnyIllegalUnicodeEscaped(entry, _allIdsExportedSoFar)); if (order > 0) { Writer.WriteAttributeString("order", order.ToString()); } Debug.Assert(entry.CreationTime.Kind == DateTimeKind.Utc); Writer.WriteAttributeString("dateCreated", entry.CreationTime.ToLiftDateTimeFormat()); Debug.Assert(entry.ModificationTime.Kind == DateTimeKind.Utc); Writer.WriteAttributeString("dateModified", entry.ModificationTime.ToLiftDateTimeFormat()); Writer.WriteAttributeString("guid", entry.Guid.ToString()); // _writer.WriteAttributeString("flex", "id", "http://fieldworks.sil.org", entry.Guid.ToString()); WriteMultiWithWrapperIfNonEmpty(LexEntry.WellKnownProperties.LexicalUnit, "lexical-unit", entry.LexicalForm); WriteHeadword(entry); WriteWellKnownCustomMultiText(entry, LexEntry.WellKnownProperties.Citation, propertiesAlreadyOutput); WriteWellKnownCustomMultiText(entry, PalasoDataObject.WellKnownProperties.Note, propertiesAlreadyOutput); WriteCustomProperties(entry, propertiesAlreadyOutput); InsertPronunciationIfNeeded(entry, propertiesAlreadyOutput); foreach (LexSense sense in entry.Senses) { Add(sense); } foreach (var variant in entry.Variants) { AddVariant(variant); } foreach (var phonetic in entry.Pronunciations) { AddPronunciation(phonetic); } foreach (var etymology in entry.Etymologies) { AddEtymology(etymology); } foreach (var note in entry.Notes) { AddNote(note); } Writer.WriteEndElement(); } private void AddEtymology(LexEtymology etymology) { // ok if no form is given if (!MultiTextBase.IsEmpty(etymology)) // { Writer.WriteStartElement("etymology"); //type is required, so add the attribute even if it's emtpy Writer.WriteAttributeString("type", etymology.Type.Trim()); //source is required, so add the attribute even if it's emtpy Writer.WriteAttributeString("source", etymology.Source.Trim()); AddMultitextGlosses(string.Empty, etymology.Gloss); WriteCustomMultiTextField("comment", etymology.Comment); AddMultitextForms(string.Empty, etymology); Writer.WriteEndElement(); // } } private void AddPronunciation(LexPhonetic phonetic) { WriteMultiWithWrapperIfNonEmpty(string.Empty, "pronunciation", phonetic); } public void AddVariant(LexVariant variant) { WriteMultiWithWrapperIfNonEmpty(string.Empty, "variant", variant); } public void AddNote(LexNote note) { if (!MultiTextBase.IsEmpty(note)) { Writer.WriteStartElement("note"); if(!string.IsNullOrEmpty(note.Type)) { Writer.WriteAttributeString("type", note.Type.Trim()); } AddMultitextForms(string.Empty, note); Writer.WriteEndElement(); } } public void AddReversal(LexReversal reversal) { if (!MultiTextBase.IsEmpty(reversal)) { Writer.WriteStartElement("reversal"); if (!string.IsNullOrEmpty(reversal.Type)) { Writer.WriteAttributeString("type", reversal.Type.Trim()); } AddMultitextForms(string.Empty, reversal); Writer.WriteEndElement(); } } /// <summary> /// in the plift subclass, we add a pronounciation if we have an audio writing system alternative on the lexical unit /// </summary> protected virtual void InsertPronunciationIfNeeded(LexEntry entry, List<string> propertiesAlreadyOutput) { } protected virtual void WriteHeadword(LexEntry entry) {} /// <summary> /// Get a human readable identifier for this entry taking into account all the rest of the /// identifiers that this has seen /// </summary> /// <param name="entry">the entry to </param> /// <param name="idsAndCounts">the base ids that have been used so far and how many times</param> /// <remarks>This function alters the idsAndCounts and thus is not stable if the entry /// does not already have an id and the same idsAndCounts dictionary is provided. /// A second call to this function with the same entry that lacks an id and the same /// idsAndCounts will produce different results each time it runs /// </remarks> /// <returns>A base id composed with its count</returns> public static string GetHumanReadableIdWithAnyIllegalUnicodeEscaped(LexEntry entry, Dictionary<string, int> idsAndCounts) { string id = entry.GetOrCreateId(true); /* if (id == null || id.Length == 0) // if the entry doesn't claim to have an id { id = entry.LexicalForm.GetFirstAlternative().Trim().Normalize(NormalizationForm.FormD); // use the first form as an id if (id == "") { id = "NoForm"; //review } } id = id.Replace('\r', ' ').Replace('\n', ' ').Replace('\t', ' '); //make this id unique int count; if (idsAndCounts.TryGetValue(id, out count)) { ++count; idsAndCounts.Remove(id); idsAndCounts.Add(id, count); id = string.Format("{0}_{1}", id, count); } else { idsAndCounts.Add(id, 1); } */ return id.EscapeAnyUnicodeCharactersIllegalInXml(); } public void Add(LexSense sense) { List<string> propertiesAlreadyOutput = new List<string>(); Writer.WriteStartElement("sense"); Writer.WriteAttributeString("id", sense.GetOrCreateId()); if (ShouldOutputProperty(LexSense.WellKnownProperties.PartOfSpeech)) { WriteGrammi(sense); propertiesAlreadyOutput.Add(LexSense.WellKnownProperties.PartOfSpeech); } if (ShouldOutputProperty(LexSense.WellKnownProperties.Gloss)) { // review: I (cp) don't think this has the same checking for round tripping that AddMultiText... methods have. WriteGlossOneElementPerFormIfNonEmpty(sense.Gloss); propertiesAlreadyOutput.Add(LexSense.WellKnownProperties.Gloss); } WriteWellKnownCustomMultiText(sense, LexSense.WellKnownProperties.Definition, propertiesAlreadyOutput); foreach (LexExampleSentence example in sense.ExampleSentences) { Add(example); } foreach (var reversal in sense.Reversals) { AddReversal(reversal); } foreach (var note in sense.Notes) { AddNote(note); } WriteWellKnownCustomMultiText(sense, PalasoDataObject.WellKnownProperties.Note, propertiesAlreadyOutput); // WriteWellKnownUnimplementedProperty(sense, LexSense.WellKnownProperties.Note, propertiesAlreadyOutput); WriteCustomProperties(sense, propertiesAlreadyOutput); Writer.WriteEndElement(); } private void WriteGrammi(LexSense sense) { if (!ShouldOutputProperty(LexSense.WellKnownProperties.PartOfSpeech)) { return; } OptionRef pos = sense.GetProperty<OptionRef>(LexSense.WellKnownProperties.PartOfSpeech); if (pos != null && !pos.IsEmpty) { WritePosCore(pos); } } protected virtual void WritePosCore(OptionRef pos) { Writer.WriteStartElement("grammatical-info"); Writer.WriteAttributeString("value", pos.Value); WriteFlags(pos); foreach (string rawXml in pos.EmbeddedXmlElements) { Writer.WriteRaw(rawXml); } Writer.WriteEndElement(); } private void WriteWellKnownCustomMultiText(PalasoDataObject item, string property, ICollection<string> propertiesAlreadyOutput) { if (ShouldOutputProperty(property)) { MultiText m = item.GetProperty<MultiText>(property); if (WriteMultiWithWrapperIfNonEmpty(property, property, m)) { propertiesAlreadyOutput.Add(property); } } } /// <summary> /// this base implementationg is for when we're just exporting to lift, and dont' want to filter or order. /// It is overridden in a child class for writing presentation-ready lift, when /// we do want to filter and order /// </summary> /// <param name="text"></param> /// <param name="propertyName"></param> /// <returns></returns> protected virtual LanguageForm[] GetOrderedAndFilteredForms(MultiTextBase text, string propertyName) { return text.Forms; } private void WriteCustomProperties(PalasoDataObject item, ICollection<string> propertiesAlreadyOutput) { foreach (KeyValuePair<string, IPalasoDataObjectProperty> pair in item.Properties) { if (propertiesAlreadyOutput.Contains(pair.Key)) { continue; } if (!ShouldOutputProperty(pair.Key)) { continue; } if (pair.Value is EmbeddedXmlCollection) { WriteEmbeddedXmlCollection(pair.Value as EmbeddedXmlCollection); continue; } if (pair.Value is MultiText) { WriteCustomMultiTextField(pair.Key, pair.Value as MultiText); continue; } if (pair.Value is OptionRef) { WriteOptionRef(pair.Key, pair.Value as OptionRef); continue; } if (pair.Value is OptionRefCollection) { WriteOptionRefCollection(pair.Key, pair.Value as OptionRefCollection); continue; } if (pair.Value is LexRelationCollection) { WriteRelationCollection(pair.Key, pair.Value as LexRelationCollection); continue; } if (pair.Value is FlagState) { WriteFlagState(pair.Key, pair.Value as FlagState); continue; } PictureRef pictureRef = pair.Value as PictureRef; if (pictureRef != null) { WriteIllustrationElement(pictureRef); continue; } throw new ApplicationException( string.Format( "The LIFT exporter was surprised to find a property '{0}' of type: {1}", pair.Key, pair.Value.GetType())); } } protected virtual void WriteIllustrationElement(PictureRef pictureRef) { WriteURLRef("illustration", pictureRef.Value, pictureRef.Caption); } protected virtual bool ShouldOutputProperty(string key) { return true; } private void WriteEmbeddedXmlCollection(EmbeddedXmlCollection collection) { foreach (string rawXml in collection.Values) { Writer.WriteRaw(rawXml); } } protected void WriteURLRef(string key, string href, MultiText caption) { if (!string.IsNullOrEmpty(href)) { Writer.WriteStartElement(key); Writer.WriteAttributeString("href", href); WriteMultiWithWrapperIfNonEmpty(key, "label", caption); Writer.WriteEndElement(); } } private void WriteFlagState(string key, FlagState state) { if (state.Value) //skip it if it's not set { Writer.WriteStartElement("trait"); Writer.WriteAttributeString("name", key); Writer.WriteAttributeString("value", "set"); //this attr required by lift schema, though we don't use it Writer.WriteEndElement(); } } private void WriteRelationCollection(string key, LexRelationCollection collection) { if (!ShouldOutputProperty(key)) { return; } foreach (LexRelation relation in collection.Relations) { if(string.IsNullOrEmpty(relation.Key)) continue; if(!EntryDoesExist(relation.TargetId)) continue; Writer.WriteStartElement("relation"); Writer.WriteAttributeString("type", GetOutputRelationName(relation)); Writer.WriteAttributeString("ref", relation.Key); WriteRelationTarget(relation); WriteExtensible(relation); foreach (string rawXml in relation.EmbeddedXmlElements) { Writer.WriteRaw(rawXml); } Writer.WriteEndElement(); } } protected virtual bool EntryDoesExist(string id) { return true;// real implementations would check } protected virtual string GetOutputRelationName(LexRelation relation) { return relation.FieldId; } /// <summary> /// allows subclass to output a dereferenced target name, e.g., for plift /// </summary> protected virtual void WriteRelationTarget(LexRelation relation) {} private void WriteOptionRefCollection(string traitName, OptionRefCollection collection) { if (!ShouldOutputProperty(traitName)) { return; } foreach (string key in collection.Keys) { Writer.WriteStartElement("trait"); Writer.WriteAttributeString("name", traitName); Writer.WriteAttributeString("value", key); //yes, the 'value' here is an option key Writer.WriteEndElement(); } } private void WriteCustomMultiTextField(string type, MultiText text) // review cp see WriteEmbeddedXmlCollection { if (!MultiTextBase.IsEmpty(text)) { Writer.WriteStartElement("field"); Writer.WriteAttributeString("type", type); WriteMultiTextNoWrapper(type, text); Writer.WriteEndElement(); } } protected virtual void WriteOptionRef(string key, OptionRef optionRef) { if (optionRef.Value.Length > 0) { Writer.WriteStartElement("trait"); Writer.WriteAttributeString("name", key); Writer.WriteAttributeString("value", optionRef.Value); foreach (string rawXml in optionRef.EmbeddedXmlElements) { Writer.WriteRaw(rawXml); } Writer.WriteEndElement(); } } public void Add(LexExampleSentence example) { if (!ShouldOutputProperty(LexExampleSentence.WellKnownProperties.ExampleSentence)) { return; } List<string> propertiesAlreadyOutput = new List<string>(); Writer.WriteStartElement("example"); OptionRef source = example.GetProperty<OptionRef>(LexExampleSentence.WellKnownProperties.Source); if (source != null && source.Value.Length > 0) { if (ShouldOutputProperty(LexExampleSentence.WellKnownProperties.Source)) { Writer.WriteAttributeString("source", source.Value); propertiesAlreadyOutput.Add("source"); } } WriteMultiTextNoWrapper(LexExampleSentence.WellKnownProperties.ExampleSentence, example.Sentence); propertiesAlreadyOutput.Add(LexExampleSentence.WellKnownProperties.ExampleSentence); // WriteMultiWithWrapperIfNonEmpty(LexExampleSentence.WellKnownProperties.Translation, "translation", example.Translation); if (!MultiTextBase.IsEmpty(example.Translation)) { Writer.WriteStartElement("translation"); if (!string.IsNullOrEmpty(example.TranslationType)) { Writer.WriteAttributeString("type", example.TranslationType); propertiesAlreadyOutput.Add("type"); } AddMultitextForms(LexExampleSentence.WellKnownProperties.Translation, example.Translation); Writer.WriteEndElement(); propertiesAlreadyOutput.Add(LexExampleSentence.WellKnownProperties.Translation); } if (ShouldOutputProperty(LexExampleSentence.WellKnownProperties.ExampleSentence)) { WriteWellKnownCustomMultiText(example, PalasoDataObject.WellKnownProperties.Note, propertiesAlreadyOutput); } WriteCustomProperties(example, propertiesAlreadyOutput); Writer.WriteEndElement(); } public void AddMultitextGlosses(string propertyName, MultiText text) // review cp see WriteEmbeddedXmlCollection { WriteLanguageFormsInWrapper(GetOrderedAndFilteredForms(text, propertyName), "gloss", false); WriteFormsThatNeedToBeTheirOwnFields(text, propertyName); WriteEmbeddedXmlCollection(text); } public void AddMultitextForms(string propertyName, MultiText text) // review cp see WriteEmbeddedXmlCollection { WriteLanguageFormsInWrapper(GetOrderedAndFilteredForms(text, propertyName), "form", false); WriteFormsThatNeedToBeTheirOwnFields(text, propertyName); WriteEmbeddedXmlCollection(text); } private void WriteExtensible(IExtensible extensible) { foreach (var trait in extensible.Traits) { WriteTrait(trait); } foreach (var field in extensible.Fields) { Writer.WriteStartElement("field"); Writer.WriteAttributeString("type", field.Type); WriteMultiTextNoWrapper(string.Empty /*what's this for*/ , field); foreach (var trait in field.Traits) { WriteTrait(trait); } Writer.WriteEndElement(); } } private void WriteTrait(LexTrait trait) { Writer.WriteStartElement("trait"); Writer.WriteAttributeString("name", trait.Name); Writer.WriteAttributeString("value", trait.Value.Trim()); Writer.WriteEndElement(); } private void WriteEmbeddedXmlCollection(MultiText text) { foreach (string rawXml in text.EmbeddedXmlElements) // todo cp Promote roundtripping to Palaso.Lift / Palaso.Data also then can use MultiTextBase here (or a better interface). { Writer.WriteRaw(rawXml); } } protected virtual void WriteFormsThatNeedToBeTheirOwnFields(MultiText text, string name) // review cp For PLiftExporter GetAudioForms { } protected void WriteLanguageFormsInWrapper(IEnumerable<LanguageForm> forms, string wrapper, bool doMarkTheFirst) { foreach (LanguageForm form in forms) { Writer.WriteStartElement(wrapper); Writer.WriteAttributeString("lang", form.WritingSystemId); if (doMarkTheFirst) { doMarkTheFirst = false; Writer.WriteAttributeString("first", "true"); //useful for headword } // string wrappedTextToExport = "<text>" + form.Form + "</text>"; // string wrappedTextToExport = form.Form; XmlReaderSettings fragmentReaderSettings = new XmlReaderSettings(); fragmentReaderSettings.ConformanceLevel = ConformanceLevel.Fragment; string scaryUnicodeEscaped = form.Form.EscapeAnyUnicodeCharactersIllegalInXml(); string safeFromScaryUnicodeSoItStaysEscaped = scaryUnicodeEscaped.Replace("&#x", ""); XmlReader testerForWellFormedness = XmlReader.Create(new StringReader("<temp>" + safeFromScaryUnicodeSoItStaysEscaped + "</temp>")); bool isTextWellFormedXml = true; try { while (testerForWellFormedness.Read()) { //Just checking for well formed XML } } catch { isTextWellFormedXml = false; } if(isTextWellFormedXml) { Writer.WriteStartElement("text"); Writer.WriteRaw(form.Form.EscapeAnyUnicodeCharactersIllegalInXml()); Writer.WriteEndElement(); // Writer.WriteRaw(wrappedTextToExport.EscapeAnyUnicodeCharactersIllegalInXml());// .WriteRaw(wrappedTextToExport); } else { Writer.WriteStartElement("text"); Writer.WriteRaw(form.Form.EscapeSoXmlSeesAsPureTextAndEscapeCharactersIllegalInXml()); Writer.WriteEndElement(); } WriteFlags(form); Writer.WriteEndElement(); } } private void WriteFlags(IAnnotatable thing) { if (thing.IsStarred) { Writer.WriteStartElement("annotation"); Writer.WriteAttributeString("name", "flag"); Writer.WriteAttributeString("value", "1"); Writer.WriteEndElement(); } } private void WriteMultiTextNoWrapper(string propertyName, MultiText text) // review cp see WriteEmbeddedXmlCollection { if (!MultiTextBase.IsEmpty(text)) { AddMultitextForms(propertyName, text); } } private void WriteGlossOneElementPerFormIfNonEmpty(MultiTextBase text) { if (MultiTextBase.IsEmpty(text)) { return; } foreach (var form in GetOrderedAndFilteredForms(text, LexSense.WellKnownProperties.Gloss)) { if (string.IsNullOrEmpty(form.Form)) { continue; } Writer.WriteStartElement("gloss"); Writer.WriteAttributeString("lang", form.WritingSystemId); Writer.WriteStartElement("text"); Writer.WriteString(form.Form); Writer.WriteEndElement(); WriteFlags(form); Writer.WriteEndElement(); } } private bool WriteMultiWithWrapperIfNonEmpty(string propertyName, string wrapperName, MultiText text) // review cp see WriteEmbeddedXmlCollection { if (!MultiTextBase.IsEmpty(text)) { Writer.WriteStartElement(wrapperName); AddMultitextForms(propertyName, text); // review cp see WriteEmbeddedXmlCollection if (text is IExtensible) { WriteExtensible((IExtensible)text); } Writer.WriteEndElement(); return true; } return false; } public void AddNewEntry(LexEntry entry) { Writer.WriteStartElement("entry"); Writer.WriteAttributeString("dateCreated", entry.CreationTime.ToLiftDateTimeFormat()); Writer.WriteAttributeString("dateModified", entry.ModificationTime.ToLiftDateTimeFormat()); Writer.WriteAttributeString("guid", entry.Guid.ToString()); Writer.WriteEndElement(); } public void AddDeletedEntry(LexEntry entry) { Writer.WriteStartElement("entry"); Writer.WriteAttributeString("id", GetHumanReadableIdWithAnyIllegalUnicodeEscaped(entry, _allIdsExportedSoFar)); Writer.WriteAttributeString("dateCreated", entry.CreationTime.ToLiftDateTimeFormat()); Writer.WriteAttributeString("dateModified", entry.ModificationTime.ToLiftDateTimeFormat()); Writer.WriteAttributeString("guid", entry.Guid.ToString()); Writer.WriteAttributeString("dateDeleted", DateTime.UtcNow.ToLiftDateTimeFormat()); Writer.WriteEndElement(); } #region IDisposable Members #if DEBUG ~LiftWriter() { if (!_disposed) { throw new ApplicationException("Disposed not explicitly called on LiftWriter." + "\n" + _constructionStack); } } #endif [CLSCompliantAttribute(false)] protected bool _disposed; public virtual void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (!_disposed) { if (disposing) { // dispose-only, i.e. non-finalizable logic if(_writer !=null) _writer.Close(); } // shared (dispose and finalizable) cleanup logic _disposed = true; } } protected void VerifyNotDisposed() { if (!_disposed) { throw new ObjectDisposedException("WeSayLiftWriter"); } } #endregion } }
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/ // Portions Copyright 2000-2004 Jonathan de Halleux // // 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.Reflection; using Gallio.Common; using Gallio.Common.Collections; using Gallio.Framework.Assertions; using System.Collections.ObjectModel; using MbUnit.Framework.ContractVerifiers.Core; namespace MbUnit.Framework.ContractVerifiers { /// <summary> /// Contract for verifying the implementation of the generic <see cref="IList{T}"/> interface. /// </summary> /// <remarks> /// <para> /// Since the generic <see cref="IList{T}"/> interface is a descendant of the generic <see cref="ICollection{T}"/> interface, /// the contract verifier has the same tests as the <see cref="CollectionContract{TCollection,TItem}"/> contract verifier, /// plus the following built-in verifications: /// <list type="bullet"> /// <item> /// <strong>InsertShouldThrowException</strong> : The read-only collection throws an exception when the method /// <see cref="IList{T}.Insert"/> is called. The test is not run when the contract property /// <see cref="CollectionContract{TCollection,TItem}.IsReadOnly"/> inherited from /// <see cref="CollectionContract{TCollection,TItem}"/>, is set to <c>false</c>. /// </item> /// <item> /// <strong>RemoveAtShouldThrowException</strong> : The read-only collection throws an exception when the /// method <see cref="IList{T}.RemoveAt"/> is called. The test is not run when the contract property /// <see cref="CollectionContract{TCollection,TItem}.IsReadOnly"/> /// inherited from <see cref="CollectionContract{TCollection,TItem}"/>, is set to <c>false</c>. /// </item> /// <item> /// <strong>IndexerSetShouldThrowException</strong> : The read-only collection throws an exception when the /// setter of the indexer <see cref="IList{T}.this"/> is called. /// The test is not run when the contract property <see cref="CollectionContract{TCollection,TItem}.IsReadOnly"/> /// inherited from <see cref="CollectionContract{TCollection,TItem}"/>, is set to <c>false</c>. /// </item> /// <item> /// <strong>InsertNullArgument</strong> : The collection throwns a <see cref="ArgumentNullException"/> /// when the method <see cref="IList{T}.Insert"/> is called with a null reference item. /// The test is not run when the contract property <see cref="CollectionContract{TCollection,TItem}.AcceptNullReference"/> /// inherited from <see cref="CollectionContract{TCollection,TItem}"/>, is set to <c>true</c>. /// </item> /// <item> /// <strong>IndexOfNullArgument</strong> : The collection throwns a <see cref="ArgumentNullException"/> /// when the method <see cref="IList{T}.IndexOf"/> is called with a null reference item. /// The test is not run when the contract property <see cref="CollectionContract{TCollection,TItem}.AcceptNullReference"/> /// inherited from <see cref="CollectionContract{TCollection,TItem}"/>, is set to <c>true</c>. /// </item> /// <item> /// <strong>IndexerSetNullArgument</strong> : The collection throwns a <see cref="ArgumentNullException"/> /// when the setter of the indexer <see cref="IList{T}.this"/> is called with a null reference item. /// The test is not run when the contract property <see cref="CollectionContract{TCollection,TItem}.AcceptNullReference"/> /// inherited from <see cref="CollectionContract{TCollection,TItem}"/>, is set to <c>true</c>. /// </item> /// <item> /// <strong>InsertItems</strong> : The collection handles correctly with the insertion of new items. The method /// <see cref="ICollection{T}.Contains"/> and the property <see cref="ICollection{T}.Count"/> are expected /// to return suitable results as well. The case of duplicate items (object equality) is tested too; according /// to the value of contract property <see cref="CollectionContract{TCollection,TItem}.AcceptEqualItems"/>, /// inherited from <see cref="CollectionContract{TCollection,TItem}"/>. The test is not run when the contract /// property <see cref="CollectionContract{TCollection,TItem}.IsReadOnly"/> /// inherited from <see cref="CollectionContract{TCollection,TItem}"/>, is set to <c>true</c>. /// </item> /// <item> /// <strong>InsertItemsAtInvalidIndex</strong> : The collection handles correctly with the insertion of new /// items at an invalid index. The method should throw an <see cref="ArgumentOutOfRangeException"/> when /// called with a negative index or with an index greater than the number of items in the list. /// The test is not run when the contract property <see cref="CollectionContract{TCollection,TItem}.IsReadOnly"/> /// inherited from <see cref="CollectionContract{TCollection,TItem}"/>, is set to <c>true</c>. /// </item> /// <item> /// <strong>RemoveItemsAt</strong> : The collection handles correctly with the removal of items at specific indexes. /// The method <see cref="ICollection{T}.Contains"/> and the property <see cref="ICollection{T}.Count"/> are expected /// to return suitable results as well. /// The test is not run when the contract property <see cref="CollectionContract{TCollection,TItem}.IsReadOnly"/> /// inherited from <see cref="CollectionContract{TCollection,TItem}"/>, is set to <c>true</c>. /// </item> /// <item> /// <strong>RemoveItemsAtInvalidIndex</strong> : The collection handles correctly with the removal of items at an /// invalid index. The method should throw an <see cref="ArgumentOutOfRangeException"/> when called with a /// negative index or with an index greater than the number of items in the list. /// The test is not run when the contract property <see cref="CollectionContract{TCollection,TItem}.IsReadOnly"/> /// inherited from <see cref="CollectionContract{TCollection,TItem}"/>, is set to <c>true</c>. /// </item> /// <item> /// <strong>GetItemsAtInvalidIndex</strong> : The collection handles correctly with the retrieval of items at /// an invalid index. The indexer should throw an <see cref="ArgumentOutOfRangeException"/> when called with /// a negative index or with an index greater than the number of items in the list. /// </item> /// <item> /// <strong>GetSetItemsWithIndexer</strong> : Setting and getting items by using the indexer property works as expected. /// The test is not run when the contract property <see cref="CollectionContract{TCollection,TItem}.IsReadOnly"/> /// inherited from <see cref="CollectionContract{TCollection,TItem}"/>, is set to <c>true</c>. /// </item> /// <item> /// <strong>IndexOfItem</strong> : The retrieval of the index of an item in the collection works as expected, /// and the index can be used effectively to get the item with the getter of the indexer property. /// </item> /// </list> /// </para> /// </remarks> /// <typeparam name="TList">The type of the collection implementing <see cref="IList{T}"/>.</typeparam> /// <typeparam name="TItem">The type of items contained by the list.</typeparam> public class ListContract<TList, TItem> : CollectionContract<TList, TItem> where TList : IList<TItem> { private IEnumerable<Test> GetBaseTests() { return base.GetContractVerificationTests(); } /// <inheritdoc /> protected override IEnumerable<Test> GetContractVerificationTests() { foreach (var test in GetBaseTests()) { yield return test; } if (IsReadOnly) { yield return CreateNotSupportedWriteTest("Insert", (list, item) => list.Insert(0, item)); yield return CreateNotSupportedWriteTest("RemoveAt", (list, item) => list.RemoveAt(0)); yield return CreateNotSupportedWriteTest("IndexerSet", (list, item) => list[0] = item); } else { if (!typeof(TItem).IsValueType && !AcceptNullReference) { yield return CreateNullArgumentTest("Insert", list => list.Insert(0, default(TItem))); yield return CreateNullArgumentTest("IndexOf", list => list.IndexOf(default(TItem))); yield return CreateNullArgumentTest("IndexerSet", list => { AssertDistinctIntancesNotEmpty(); if (list.Count == 0) // If the list is empty, then add at least one item. list.Add(DistinctInstances.Instances[0]); list[0] = default(TItem); }); } yield return CreateInsertItemsTest(); yield return CreateInsertItemsAtInvalidIndexTest(); yield return CreateRemoveItemsAtTest(); yield return CreateRemoveItemsAtInvalidIndexTest(); yield return CreateIndexerGetSetItemsTest(); } yield return CreateIndexOfItemsTest(); yield return CreateIndexerGetItemsAtInvalidIndexTest(); } private Test CreateInsertItemsTest() { return new TestCase("InsertItems", () => { AssertDistinctIntancesNotEmpty(); DoInsertCycle(list => 0); // Head insertion. DoInsertCycle(list => Math.Min(1, list.Count)); // Insertion at second position . DoInsertCycle(list => list.Count); // Queue insertion. }); } private void DoInsertCycle(Func<TList, int> getIndex) { var list = GetSafeDefaultInstance(); var handler = new ListHandler<TList, TItem>(list, Context); var initialContent = new ReadOnlyCollection<TItem>(list); foreach (var item in DistinctInstances) { if (!initialContent.Contains(item)) { handler.InsertSingleItemOk(getIndex(list), item); } if (AcceptEqualItems) { handler.InsertDuplicateItemOk(getIndex(list), item); } else { handler.InsertDuplicateItemFails(item); } } } private Test CreateInsertItemsAtInvalidIndexTest() { return new TestCase("InsertItemsAtInvalidIndex", () => { AssertDistinctIntancesNotEmpty(); var list = GetSafeDefaultInstance(); var handler = new ListHandler<TList, TItem>(list, Context); var initialContent = new List<TItem>(list); Assert.Multiple(() => { foreach (var item in DistinctInstances) { if (!initialContent.Contains(item)) { handler.DoActionAtInvalidIndex(x => -1, (l, i) => l.Insert(i, item), "Insert"); // Negative index. handler.DoActionAtInvalidIndex(x => x.Count + 1, (l, i) => l.Insert(i, item), "Insert"); // Index too high. } } }); }); } private Test CreateIndexOfItemsTest() { return new TestCase("IndexOfItem", () => { AssertDistinctIntancesNotEmpty(); var handler = new ListHandler<TList, TItem>(GetSafeDefaultInstance(), Context); foreach (var item in DistinctInstances) { handler.IndexOfItem(item, IsReadOnly); } }); } private Test CreateRemoveItemsAtTest() { return new TestCase("RemoveItemsAt", () => { AssertDistinctIntancesNotEmpty(); var list = GetSafeDefaultInstance(); var handler = new ListHandler<TList, TItem>(list, Context); foreach (var item in DistinctInstances) { handler.RemoveItemAtOk(item); } }); } private Test CreateRemoveItemsAtInvalidIndexTest() { return new TestCase("RemoveItemsAtInvalidIndex", () => { AssertDistinctIntancesNotEmpty(); var handler = new ListHandler<TList, TItem>(GetSafeDefaultInstance(), Context); Assert.Multiple(() => { handler.DoActionAtInvalidIndex(x => -1, (list, index) => list.RemoveAt(index), "RemoveAt"); // Negative index. handler.DoActionAtInvalidIndex(x => x.Count + 1, (list, index) => list.RemoveAt(index), "RemoveAt"); // Index too high. }); }); } private Test CreateIndexerGetItemsAtInvalidIndexTest() { return new TestCase("GetItemsAtInvalidIndex", () => { AssertDistinctIntancesNotEmpty(); var handler = new ListHandler<TList, TItem>(GetSafeDefaultInstance(), Context); Assert.Multiple(() => { handler.DoActionAtInvalidIndex(x => -1, (list, index) => { var o = list[index]; }, "Indexer Getter"); // Negative index. handler.DoActionAtInvalidIndex(x => x.Count + 1, (list, index) => { var o = list[index]; }, "Indexer Getter"); // Index too high. }); }); } private Test CreateIndexerGetSetItemsTest() { return new TestCase("GetSetItemsWithIndexer", () => { AssertDistinctIntancesNotEmpty(); var list = GetSafeDefaultInstance(); if (list.Count == 0) // The default instance is empty: add at least one item. list.Add(DistinctInstances.Instances[0]); for (int index = 0; index < list.Count; index++) { foreach (var item in DistinctInstances.Instances) { if (!list.Contains(item) || AcceptEqualItems || list.IndexOf(item) == index) { list[index] = item; var actual = list[index]; AssertionHelper.Explain(() => Assert.AreEqual(item, actual), innerFailures => new AssertionFailureBuilder( "Expected the indexer to return a consistent result.") .AddRawLabeledValue("Index", index) .AddRawLabeledValue("Actual Item", actual) .AddRawLabeledValue("Expected Item", item) .SetStackTrace(Context.GetStackTraceData()) .AddInnerFailures(innerFailures) .ToAssertionFailure()); } } } }); } } }
// Copyright 2021 Maintainers of NUKE. // Distributed under the MIT License. // https://github.com/nuke-build/nuke/blob/master/LICENSE using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Linq.Expressions; using JetBrains.Annotations; using Nuke.Common.IO; using Nuke.Common.Utilities; using Nuke.Common.Utilities.Collections; using Nuke.Common.ValueInjection; using Serilog; namespace Nuke.Common.Execution { /// <summary> /// Gradually executes targets of the execution plan. /// Targets are skipped according to static conditions, dependency behavior, dynamic conditions and previous build attempts. /// </summary> internal static class BuildExecutor { private static AbsolutePath BuildAttemptFile => Constants.GetBuildAttemptFile(NukeBuild.RootDirectory); public static void Execute(NukeBuild build, [CanBeNull] IReadOnlyCollection<string> skippedTargets) { MarkSkippedTargets(build, skippedTargets); RequirementService.ValidateRequirements(build, build.ScheduledTargets.ToList()); var previouslyExecutedTargets = UpdateInvocationHash(build); BuildManager.CancellationHandler += ExecuteAssuredTargets; try { build.ExecutionPlan.ForEach(x => Execute(build, x, previouslyExecutedTargets)); } catch { ExecuteAssuredTargets(); throw; } void ExecuteAssuredTargets() { var assuredScheduledTargets = build.ExecutionPlan.Where(x => x.AssuredAfterFailure && x.Status == ExecutionStatus.Scheduled); assuredScheduledTargets.ForEach(x => Execute(build, x, previouslyExecutedTargets, failureMode: true)); } } private static IReadOnlyCollection<string> UpdateInvocationHash(NukeBuild build) { var continueParameterName = ParameterService.GetParameterMemberName(() => build.Continue); var invocation = EnvironmentInfo.CommandLineArguments .Where(x => !x.StartsWith("-") || x.TrimStart("-").EqualsOrdinalIgnoreCase(continueParameterName)) .JoinSpace(); var invocationHash = invocation.GetMD5Hash(); IReadOnlyCollection<string> GetPreviouslyExecutedTargets() { if (!build.Continue || !File.Exists(BuildAttemptFile)) return new string[0]; var previousBuild = File.ReadAllLines(BuildAttemptFile); if (previousBuild.FirstOrDefault() != invocationHash) { Log.Warning("Build invocation changed. Restarting ..."); return new string[0]; } return previousBuild.Skip(1).ToArray(); } var previouslyExecutedTargets = GetPreviouslyExecutedTargets(); File.WriteAllLines(BuildAttemptFile, new[] { invocationHash }); return previouslyExecutedTargets; } private static void Execute( NukeBuild build, ExecutableTarget target, IReadOnlyCollection<string> previouslyExecutedTargets, bool failureMode = false) { if (target.Status == ExecutionStatus.Skipped || previouslyExecutedTargets.Contains(target.Name) || HasSkippingCondition(target, target.DynamicConditions)) { target.Status = ExecutionStatus.Skipped; build.ExecuteExtension<IOnTargetSkipped>(x => x.OnTargetSkipped(build, target)); AppendToBuildAttemptFile(target.Name); return; } if (target.Actions.Count == 0) { target.Status = ExecutionStatus.Collective; return; } using (Logging.SetTarget(target.Name)) using (NukeBuild.Host.WriteBlock(target.Name)) { target.Stopwatch.Start(); target.Status = ExecutionStatus.Running; build.ExecuteExtension<IOnTargetRunning>(x => x.OnTargetRunning(build, target)); try { target.Actions.ForEach(x => x()); target.Stopwatch.Stop(); target.Status = ExecutionStatus.Succeeded; build.ExecuteExtension<IOnTargetSucceeded>(x => x.OnTargetSucceeded(build, target)); AppendToBuildAttemptFile(target.Name); } catch (Exception exception) { build.ReportSummary(_ => target.SummaryInformation.Any() ? target.SummaryInformation : _.AddPair(exception.GetType().Name, exception.Message.SplitLineBreaks().First())); Log.Error(exception, "Target {TargetName} failed", target.Name); target.Stopwatch.Stop(); target.Status = ExecutionStatus.Failed; build.ExecuteExtension<IOnTargetFailed>(x => x.OnTargetFailed(build, target)); if (!target.ProceedAfterFailure && !failureMode) throw new TargetExecutionException(target.Name, exception); } } } private static void MarkSkippedTargets(NukeBuild build, IReadOnlyCollection<string> skippedTargets) { void MarkTargetSkipped(ExecutableTarget target, string reason = null) { if (target.Invoked) return; target.Status = ExecutionStatus.Skipped; target.SkipReason ??= reason; if (target.DependencyBehavior == DependencyBehavior.Execute) return; target.ExecutionDependencies.ForEach(TryMarkTargetSkipped); target.Triggers.ForEach(TryMarkTargetSkipped); void TryMarkTargetSkipped(ExecutableTarget dependentTarget) { var scheduledTargets = build.ExecutionPlan.Where(x => x.Status == ExecutionStatus.Scheduled); if (scheduledTargets.Any(x => x.ExecutionDependencies.Contains(dependentTarget) || x.Triggers.Contains(dependentTarget))) return; MarkTargetSkipped(dependentTarget, reason: $"skipping {target.Name}"); } } if (skippedTargets != null) { build.ExecutionPlan .Where(x => skippedTargets.Count == 0 || skippedTargets.Contains(x.Name, StringComparer.OrdinalIgnoreCase)) .ForEach(x => MarkTargetSkipped(x, reason: "via --skip parameter")); } build.ExecutionPlan .Where(x => HasSkippingCondition(x, x.StaticConditions)) .ForEach(x => MarkTargetSkipped(x)); } private static bool HasSkippingCondition(ExecutableTarget target, IEnumerable<Expression<Func<bool>>> conditions) { // TODO: trim outer parenthesis static string GetSkipReason(Expression<Func<bool>> condition) => condition.Body.ToString() .Replace("False", "false") .Replace("True", "true") .Replace("OrElse", "||") .Replace("AndAlso", "&&") // TODO: should get actual build type name .Replace("value(Build).", string.Empty); foreach (var condition in conditions) { if (!condition.Compile().Invoke()) target.SkipReason = GetSkipReason(condition); } return target.SkipReason != null; } private static void AppendToBuildAttemptFile(string value) { File.AppendAllLines(BuildAttemptFile, new[] { value }); } } }
using System.Diagnostics; namespace Community.CsharpSqlite { using u8 = System.Byte; public partial class Sqlite3 { /* ** 2001 September 15 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** An tokenizer for SQL ** ** This file contains C code that implements the sqlite3_complete() API. ** This code used to be part of the tokenizer.c source file. But by ** separating it out, the code will be automatically omitted from ** static links that do not use it. ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ** ** SQLITE_SOURCE_ID: 2010-08-23 18:52:01 42537b60566f288167f1b5864a5435986838e3a3 ** ************************************************************************* */ //#include "sqliteInt.h" #if !SQLITE_OMIT_COMPLETE /* ** This is defined in tokenize.c. We just have to import the definition. */ #if !SQLITE_AMALGAMATION #if !NO_SQLITE_ASCII //#define IdChar(C) ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0) static bool IdChar( u8 C ) { return ( sqlite3CtypeMap[(char)C] & 0x46 ) != 0; } #endif //#if SQLITE_EBCDIC //extern const char sqlite3IsEbcdicIdChar[]; //#define IdChar(C) (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40])) //#endif #endif // * SQLITE_AMALGAMATION */ /* ** Token types used by the sqlite3_complete() routine. See the header ** comments on that procedure for additional information. */ const int tkSEMI = 0; const int tkWS = 1; const int tkOTHER = 2; #if !SQLITE_OMIT_TRIGGER const int tkEXPLAIN = 3; const int tkCREATE = 4; const int tkTEMP = 5; const int tkTRIGGER = 6; const int tkEND = 7; #endif /* ** Return TRUE if the given SQL string ends in a semicolon. ** ** Special handling is require for CREATE TRIGGER statements. ** Whenever the CREATE TRIGGER keywords are seen, the statement ** must end with ";END;". ** ** This implementation uses a state machine with 8 states: ** ** (0) INVALID We have not yet seen a non-whitespace character. ** ** (1) START At the beginning or end of an SQL statement. This routine ** returns 1 if it ends in the START state and 0 if it ends ** in any other state. ** ** (2) NORMAL We are in the middle of statement which ends with a single ** semicolon. ** ** (3) EXPLAIN The keyword EXPLAIN has been seen at the beginning of ** a statement. ** ** (4) CREATE The keyword CREATE has been seen at the beginning of a ** statement, possibly preceeded by EXPLAIN and/or followed by ** TEMP or TEMPORARY ** ** (5) TRIGGER We are in the middle of a trigger definition that must be ** ended by a semicolon, the keyword END, and another semicolon. ** ** (6) SEMI We've seen the first semicolon in the ";END;" that occurs at ** the end of a trigger definition. ** ** (7) END We've seen the ";END" of the ";END;" that occurs at the end ** of a trigger difinition. ** ** Transitions between states above are determined by tokens extracted ** from the input. The following tokens are significant: ** ** (0) tkSEMI A semicolon. ** (1) tkWS Whitespace. ** (2) tkOTHER Any other SQL token. ** (3) tkEXPLAIN The "explain" keyword. ** (4) tkCREATE The "create" keyword. ** (5) tkTEMP The "temp" or "temporary" keyword. ** (6) tkTRIGGER The "trigger" keyword. ** (7) tkEND The "end" keyword. ** ** Whitespace never causes a state transition and is always ignored. ** This means that a SQL string of all whitespace is invalid. ** ** If we compile with SQLITE_OMIT_TRIGGER, all of the computation needed ** to recognize the end of a trigger can be omitted. All we have to do ** is look for a semicolon that is not part of an string or comment. */ static public int sqlite3_complete( string zSql ) { int state = 0; /* Current state, using numbers defined in header comment */ int token; /* Value of the next token */ #if !SQLITE_OMIT_TRIGGER /* A complex statement machine used to detect the end of a CREATE TRIGGER ** statement. This is the normal case. */ u8[][] trans = new u8[][] { /* Token: */ /* State: ** SEMI WS OTHER EXPLAIN CREATE TEMP TRIGGER END */ /* 0 INVALID: */ new u8[]{ 1, 0, 2, 3, 4, 2, 2, 2, }, /* 1 START: */ new u8[]{ 1, 1, 2, 3, 4, 2, 2, 2, }, /* 2 NORMAL: */ new u8[]{ 1, 2, 2, 2, 2, 2, 2, 2, }, /* 3 EXPLAIN: */ new u8[]{ 1, 3, 3, 2, 4, 2, 2, 2, }, /* 4 CREATE: */ new u8[]{ 1, 4, 2, 2, 2, 4, 5, 2, }, /* 5 TRIGGER: */ new u8[]{ 6, 5, 5, 5, 5, 5, 5, 5, }, /* 6 SEMI: */ new u8[]{ 6, 6, 5, 5, 5, 5, 5, 7, }, /* 7 END: */ new u8[]{ 1, 7, 5, 5, 5, 5, 5, 5, }, }; #else /* If triggers are not supported by this compile then the statement machine ** used to detect the end of a statement is much simplier */ u8[][] trans = new u8[][] { /* Token: */ /* State: ** SEMI WS OTHER */ /* 0 INVALID: */new u8[] { 1, 0, 2, }, /* 1 START: */new u8[] { 1, 1, 2, }, /* 2 NORMAL: */new u8[] { 1, 2, 2, }, }; #endif // * SQLITE_OMIT_TRIGGER */ int zIdx = 0; while ( zIdx < zSql.Length ) { switch ( zSql[zIdx] ) { case ';': { /* A semicolon */ token = tkSEMI; break; } case ' ': case '\r': case '\t': case '\n': case '\f': { /* White space is ignored */ token = tkWS; break; } case '/': { /* C-style comments */ if ( zSql[zIdx + 1] != '*' ) { token = tkOTHER; break; } zIdx += 2; while ( zIdx < zSql.Length && zSql[zIdx] != '*' || zIdx < zSql.Length - 1 && zSql[zIdx + 1] != '/' ) { zIdx++; } if ( zIdx == zSql.Length ) return 0; zIdx++; token = tkWS; break; } case '-': { /* SQL-style comments from "--" to end of line */ if ( zSql[zIdx + 1] != '-' ) { token = tkOTHER; break; } while ( zIdx < zSql.Length && zSql[zIdx] != '\n' ) { zIdx++; } if ( zIdx == zSql.Length ) return state == 1 ? 1 : 0;//if( *zSql==0 ) return state==1; token = tkWS; break; } case '[': { /* Microsoft-style identifiers in [...] */ zIdx++; while ( zIdx < zSql.Length && zSql[zIdx] != ']' ) { zIdx++; } if ( zIdx == zSql.Length ) return 0; token = tkOTHER; break; } case '`': /* Grave-accent quoted symbols used by MySQL */ case '"': /* single- and double-quoted strings */ case '\'': { int c = zSql[zIdx]; zIdx++; while ( zIdx < zSql.Length && zSql[zIdx] != c ) { zIdx++; } if ( zIdx == zSql.Length ) return 0; token = tkOTHER; break; } default: { //#if SQLITE_EBCDIC // unsigned char c; //#endif if ( IdChar( (u8)zSql[zIdx] ) ) { /* Keywords and unquoted identifiers */ int nId; for ( nId = 1; ( zIdx + nId ) < zSql.Length && IdChar( (u8)zSql[zIdx + nId] ); nId++ ) { } #if SQLITE_OMIT_TRIGGER token = tkOTHER; #else switch ( zSql[zIdx] ) { case 'c': case 'C': { if ( nId == 6 && sqlite3StrNICmp( zSql, zIdx, "create", 6 ) == 0 ) { token = tkCREATE; } else { token = tkOTHER; } break; } case 't': case 'T': { if ( nId == 7 && sqlite3StrNICmp( zSql, zIdx, "trigger", 7 ) == 0 ) { token = tkTRIGGER; } else if ( nId == 4 && sqlite3StrNICmp( zSql, zIdx, "temp", 4 ) == 0 ) { token = tkTEMP; } else if ( nId == 9 && sqlite3StrNICmp( zSql, zIdx, "temporary", 9 ) == 0 ) { token = tkTEMP; } else { token = tkOTHER; } break; } case 'e': case 'E': { if ( nId == 3 && sqlite3StrNICmp( zSql, zIdx, "end", 3 ) == 0 ) { token = tkEND; } else #if !SQLITE_OMIT_EXPLAIN if ( nId == 7 && sqlite3StrNICmp( zSql, zIdx, "explain", 7 ) == 0 ) { token = tkEXPLAIN; } else #endif { token = tkOTHER; } break; } default: { token = tkOTHER; break; } } #endif // * SQLITE_OMIT_TRIGGER */ zIdx += nId - 1; } else { /* Operators and special symbols */ token = tkOTHER; } break; } } state = trans[state][token]; zIdx++; } return ( state == 1 ) ? 1 : 0;//return state==1; } #if NO_SQLITE_OMIT_UTF16 //#if !SQLITE_OMIT_UTF16 /* ** This routine is the same as the sqlite3_complete() routine described ** above, except that the parameter is required to be UTF-16 encoded, not ** UTF-8. */ int sqlite3_complete16(const void *zSql){ sqlite3_value pVal; char const *zSql8; int rc = SQLITE_NOMEM; #if !SQLITE_OMIT_AUTOINIT rc = sqlite3_initialize(); if( rc !=0) return rc; #endif pVal = sqlite3ValueNew(0); sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC); zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8); if( zSql8 ){ rc = sqlite3_complete(zSql8); }else{ rc = SQLITE_NOMEM; } sqlite3ValueFree(pVal); return sqlite3ApiExit(0, rc); } #endif // * SQLITE_OMIT_UTF16 */ #endif // * SQLITE_OMIT_COMPLETE */ } }
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Reflection; using Autofac; using NUnit.Framework; using Orchard.Caching; using Orchard.Environment.Extensions; using Orchard.Environment.Extensions.Folders; using Orchard.Environment.Extensions.Loaders; using Orchard.Environment.Extensions.Models; using Orchard.FileSystems.Dependencies; using Orchard.Tests.Extensions.ExtensionTypes; using Orchard.Tests.Stubs; namespace Orchard.Tests.Environment.Extensions { [TestFixture] public class ExtensionManagerTests { private IContainer _container; private IExtensionManager _manager; private StubFolders _folders; [SetUp] public void Init() { var builder = new ContainerBuilder(); _folders = new StubFolders(); builder.RegisterInstance(_folders).As<IExtensionFolders>(); builder.RegisterType<ExtensionManager>().As<IExtensionManager>(); builder.RegisterType<StubCacheManager>().As<ICacheManager>(); builder.RegisterType<StubParallelCacheContext>().As<IParallelCacheContext>(); builder.RegisterType<StubAsyncTokenProvider>().As<IAsyncTokenProvider>(); _container = builder.Build(); _manager = _container.Resolve<IExtensionManager>(); } public class StubFolders : IExtensionFolders { private readonly string _extensionType; public StubFolders(string extensionType) { Manifests = new Dictionary<string, string>(); _extensionType = extensionType; } public StubFolders() : this(DefaultExtensionTypes.Module) { } public IDictionary<string, string> Manifests { get; set; } public IEnumerable<ExtensionDescriptor> AvailableExtensions() { foreach (var e in Manifests) { string name = e.Key; yield return ExtensionHarvester.GetDescriptorForExtension("~/", name, _extensionType, Manifests[name]); } } } public class StubLoaders : IExtensionLoader { #region Implementation of IExtensionLoader public int Order { get { return 1; } } public string Name { get { throw new NotImplementedException(); } } public Assembly LoadReference(DependencyReferenceDescriptor reference) { throw new NotImplementedException(); } public void ReferenceActivated(ExtensionLoadingContext context, ExtensionReferenceProbeEntry referenceEntry) { throw new NotImplementedException(); } public void ReferenceDeactivated(ExtensionLoadingContext context, ExtensionReferenceProbeEntry referenceEntry) { throw new NotImplementedException(); } public bool IsCompatibleWithModuleReferences(ExtensionDescriptor extension, IEnumerable<ExtensionProbeEntry> references) { throw new NotImplementedException(); } public ExtensionProbeEntry Probe(ExtensionDescriptor descriptor) { return new ExtensionProbeEntry { Descriptor = descriptor, Loader = this }; } public IEnumerable<ExtensionReferenceProbeEntry> ProbeReferences(ExtensionDescriptor extensionDescriptor) { throw new NotImplementedException(); } public ExtensionEntry Load(ExtensionDescriptor descriptor) { return new ExtensionEntry { Descriptor = descriptor, ExportedTypes = new[] { typeof(Alpha), typeof(Beta), typeof(Phi) } }; } public void ExtensionActivated(ExtensionLoadingContext ctx, ExtensionDescriptor extension) { throw new NotImplementedException(); } public void ExtensionDeactivated(ExtensionLoadingContext ctx, ExtensionDescriptor extension) { throw new NotImplementedException(); } public void ExtensionRemoved(ExtensionLoadingContext ctx, DependencyDescriptor dependency) { throw new NotImplementedException(); } public void Monitor(ExtensionDescriptor extension, Action<IVolatileToken> monitor) { } public IEnumerable<ExtensionCompilationReference> GetCompilationReferences(DependencyDescriptor dependency) { throw new NotImplementedException(); } public IEnumerable<string> GetVirtualPathDependencies(DependencyDescriptor dependency) { throw new NotImplementedException(); } public bool LoaderIsSuitable(ExtensionDescriptor descriptor) { throw new NotImplementedException(); } #endregion } [Test] public void AvailableExtensionsShouldFollowCatalogLocations() { _folders.Manifests.Add("foo", "Name: Foo"); _folders.Manifests.Add("bar", "Name: Bar"); _folders.Manifests.Add("frap", "Name: Frap"); _folders.Manifests.Add("quad", "Name: Quad"); var available = _manager.AvailableExtensions(); Assert.That(available.Count(), Is.EqualTo(4)); Assert.That(available, Has.Some.Property("Id").EqualTo("foo")); } [Test] public void ExtensionDescriptorKeywordsAreCaseInsensitive() { _folders.Manifests.Add("Sample", @" NaMe: Sample Extension SESSIONSTATE: disabled version: 2.x DESCRIPTION: HELLO "); var descriptor = _manager.AvailableExtensions().Single(); Assert.That(descriptor.Id, Is.EqualTo("Sample")); Assert.That(descriptor.Name, Is.EqualTo("Sample Extension")); Assert.That(descriptor.Version, Is.EqualTo("2.x")); Assert.That(descriptor.Description, Is.EqualTo("HELLO")); Assert.That(descriptor.SessionState, Is.EqualTo("disabled")); } [Test] public void ExtensionDescriptorsShouldHaveNameAndVersion() { _folders.Manifests.Add("Sample", @" Name: Sample Extension Version: 2.x "); var descriptor = _manager.AvailableExtensions().Single(); Assert.That(descriptor.Id, Is.EqualTo("Sample")); Assert.That(descriptor.Name, Is.EqualTo("Sample Extension")); Assert.That(descriptor.Version, Is.EqualTo("2.x")); } [Test] public void ExtensionDescriptorsShouldBeParsedForMinimalModuleTxt() { _folders.Manifests.Add("SuperWiki", @" Name: SuperWiki Version: 1.0.3 OrchardVersion: 1 Features: SuperWiki: Description: My super wiki module for Orchard. "); var descriptor = _manager.AvailableExtensions().Single(); Assert.That(descriptor.Id, Is.EqualTo("SuperWiki")); Assert.That(descriptor.Version, Is.EqualTo("1.0.3")); Assert.That(descriptor.OrchardVersion, Is.EqualTo("1")); Assert.That(descriptor.Features.Count(), Is.EqualTo(1)); Assert.That(descriptor.Features.First().Id, Is.EqualTo("SuperWiki")); Assert.That(descriptor.Features.First().Extension.Id, Is.EqualTo("SuperWiki")); Assert.That(descriptor.Features.First().Description, Is.EqualTo("My super wiki module for Orchard.")); } [Test] public void ExtensionDescriptorsShouldBeParsedForCompleteModuleTxt() { _folders.Manifests.Add("MyCompany.AnotherWiki", @" Name: AnotherWiki SessionState: required Author: Coder Notaprogrammer Website: https://github.com/MyCompany/AnotherWiki Version: 1.2.3 OrchardVersion: 1 Features: AnotherWiki: Description: My super wiki module for Orchard. Dependencies: Versioning, Search Category: Content types AnotherWiki Editor: Description: A rich editor for wiki contents. Dependencies: TinyMce, AnotherWiki Category: Input methods AnotherWiki DistributionList: Description: Sends e-mail alerts when wiki contents gets published. Dependencies: AnotherWiki, Email Subscriptions Category: Email AnotherWiki Captcha: Description: Kills spam. Or makes it zombie-like. Dependencies: AnotherWiki, reCaptcha Category: Spam "); var descriptor = _manager.AvailableExtensions().Single(); Assert.That(descriptor.Id, Is.EqualTo("MyCompany.AnotherWiki")); Assert.That(descriptor.Name, Is.EqualTo("AnotherWiki")); Assert.That(descriptor.Author, Is.EqualTo("Coder Notaprogrammer")); Assert.That(descriptor.WebSite, Is.EqualTo("https://github.com/MyCompany/AnotherWiki")); Assert.That(descriptor.Version, Is.EqualTo("1.2.3")); Assert.That(descriptor.OrchardVersion, Is.EqualTo("1")); Assert.That(descriptor.Features.Count(), Is.EqualTo(5)); Assert.That(descriptor.SessionState, Is.EqualTo("required")); foreach (var featureDescriptor in descriptor.Features) { switch (featureDescriptor.Id) { case "AnotherWiki": Assert.That(featureDescriptor.Extension, Is.SameAs(descriptor)); Assert.That(featureDescriptor.Description, Is.EqualTo("My super wiki module for Orchard.")); Assert.That(featureDescriptor.Category, Is.EqualTo("Content types")); Assert.That(featureDescriptor.Dependencies.Count(), Is.EqualTo(2)); Assert.That(featureDescriptor.Dependencies.Contains("Versioning")); Assert.That(featureDescriptor.Dependencies.Contains("Search")); break; case "AnotherWiki Editor": Assert.That(featureDescriptor.Extension, Is.SameAs(descriptor)); Assert.That(featureDescriptor.Description, Is.EqualTo("A rich editor for wiki contents.")); Assert.That(featureDescriptor.Category, Is.EqualTo("Input methods")); Assert.That(featureDescriptor.Dependencies.Count(), Is.EqualTo(2)); Assert.That(featureDescriptor.Dependencies.Contains("TinyMce")); Assert.That(featureDescriptor.Dependencies.Contains("AnotherWiki")); break; case "AnotherWiki DistributionList": Assert.That(featureDescriptor.Extension, Is.SameAs(descriptor)); Assert.That(featureDescriptor.Description, Is.EqualTo("Sends e-mail alerts when wiki contents gets published.")); Assert.That(featureDescriptor.Category, Is.EqualTo("Email")); Assert.That(featureDescriptor.Dependencies.Count(), Is.EqualTo(2)); Assert.That(featureDescriptor.Dependencies.Contains("AnotherWiki")); Assert.That(featureDescriptor.Dependencies.Contains("Email Subscriptions")); break; case "AnotherWiki Captcha": Assert.That(featureDescriptor.Extension, Is.SameAs(descriptor)); Assert.That(featureDescriptor.Description, Is.EqualTo("Kills spam. Or makes it zombie-like.")); Assert.That(featureDescriptor.Category, Is.EqualTo("Spam")); Assert.That(featureDescriptor.Dependencies.Count(), Is.EqualTo(2)); Assert.That(featureDescriptor.Dependencies.Contains("AnotherWiki")); Assert.That(featureDescriptor.Dependencies.Contains("reCaptcha")); break; // default feature. case "MyCompany.AnotherWiki": Assert.That(featureDescriptor.Extension, Is.SameAs(descriptor)); break; default: Assert.Fail("Features not parsed correctly"); break; } } } [Test] public void ExtensionManagerShouldLoadFeatures() { var extensionLoader = new StubLoaders(); var extensionFolder = new StubFolders(); extensionFolder.Manifests.Add("TestModule", @" Name: TestModule Version: 1.0.3 OrchardVersion: 1 Features: TestModule: Description: My test module for Orchard. TestFeature: Description: Contains the Phi type. "); IExtensionManager extensionManager = CreateExtensionManager(extensionFolder, extensionLoader); var testFeature = extensionManager.AvailableExtensions() .SelectMany(x => x.Features); var features = extensionManager.LoadFeatures(testFeature); var types = features.SelectMany(x => x.ExportedTypes); Assert.That(types.Count(), Is.Not.EqualTo(0)); } [Test] public void ExtensionManagerFeaturesContainNonAbstractClasses() { var extensionLoader = new StubLoaders(); var extensionFolder = new StubFolders(); extensionFolder.Manifests.Add("TestModule", @" Name: TestModule Version: 1.0.3 OrchardVersion: 1 Features: TestModule: Description: My test module for Orchard. TestFeature: Description: Contains the Phi type. "); IExtensionManager extensionManager = CreateExtensionManager(extensionFolder, extensionLoader); var testFeature = extensionManager.AvailableExtensions() .SelectMany(x => x.Features); var features = extensionManager.LoadFeatures(testFeature); var types = features.SelectMany(x => x.ExportedTypes); foreach (var type in types) { Assert.That(type.IsClass); Assert.That(!type.IsAbstract); } } private static ExtensionManager CreateExtensionManager(StubFolders extensionFolder, StubLoaders extensionLoader) { return CreateExtensionManager(new[] { extensionFolder }, new[] { extensionLoader }); } private static ExtensionManager CreateExtensionManager(IEnumerable<StubFolders> extensionFolder, IEnumerable<StubLoaders> extensionLoader) { return new ExtensionManager(extensionFolder, extensionLoader, new StubCacheManager(), new StubParallelCacheContext(), new StubAsyncTokenProvider()); } [Test] public void ExtensionManagerShouldReturnEmptyFeatureIfFeatureDoesNotExist() { var featureDescriptor = new FeatureDescriptor { Id = "NoSuchFeature", Extension = new ExtensionDescriptor { Id = "NoSuchFeature" } }; Feature feature = _manager.LoadFeatures(new[] { featureDescriptor }).First(); Assert.AreEqual(featureDescriptor, feature.Descriptor); Assert.AreEqual(0, feature.ExportedTypes.Count()); } [Test] public void ExtensionManagerTestFeatureAttribute() { var extensionLoader = new StubLoaders(); var extensionFolder = new StubFolders(); extensionFolder.Manifests.Add("TestModule", @" Name: TestModule Version: 1.0.3 OrchardVersion: 1 Features: TestModule: Description: My test module for Orchard. TestFeature: Description: Contains the Phi type. "); IExtensionManager extensionManager = CreateExtensionManager(extensionFolder, extensionLoader); var testFeature = extensionManager.AvailableExtensions() .SelectMany(x => x.Features) .Single(x => x.Id == "TestFeature"); foreach (var feature in extensionManager.LoadFeatures(new[] { testFeature })) { foreach (var type in feature.ExportedTypes) { foreach (OrchardFeatureAttribute featureAttribute in type.GetCustomAttributes(typeof(OrchardFeatureAttribute), false)) { Assert.That(featureAttribute.FeatureName, Is.EqualTo("TestFeature")); } } } } [Test] public void ExtensionManagerLoadFeatureReturnsTypesFromSpecificFeaturesWithFeatureAttribute() { var extensionLoader = new StubLoaders(); var extensionFolder = new StubFolders(); extensionFolder.Manifests.Add("TestModule", @" Name: TestModule Version: 1.0.3 OrchardVersion: 1 Features: TestModule: Description: My test module for Orchard. TestFeature: Description: Contains the Phi type. "); IExtensionManager extensionManager = CreateExtensionManager(extensionFolder, extensionLoader); var testFeature = extensionManager.AvailableExtensions() .SelectMany(x => x.Features) .Single(x => x.Id == "TestFeature"); foreach (var feature in extensionManager.LoadFeatures(new[] { testFeature })) { foreach (var type in feature.ExportedTypes) { Assert.That(type == typeof(Phi)); } } } [Test] public void ExtensionManagerLoadFeatureDoesNotReturnTypesFromNonMatchingFeatures() { var extensionLoader = new StubLoaders(); var extensionFolder = new StubFolders(); extensionFolder.Manifests.Add("TestModule", @" Name: TestModule Version: 1.0.3 OrchardVersion: 1 Features: TestModule: Description: My test module for Orchard. TestFeature: Description: Contains the Phi type. "); IExtensionManager extensionManager = CreateExtensionManager(extensionFolder, extensionLoader); var testModule = extensionManager.AvailableExtensions() .SelectMany(x => x.Features) .Single(x => x.Id == "TestModule"); foreach (var feature in extensionManager.LoadFeatures(new[] { testModule })) { foreach (var type in feature.ExportedTypes) { Assert.That(type != typeof(Phi)); Assert.That((type == typeof(Alpha) || (type == typeof(Beta)))); } } } [Test] public void ModuleNameIsIntroducedAsFeatureImplicitly() { var extensionLoader = new StubLoaders(); var extensionFolder = new StubFolders(); extensionFolder.Manifests.Add("Minimalistic", @" Name: Minimalistic Version: 1.0.3 OrchardVersion: 1 "); IExtensionManager extensionManager = CreateExtensionManager(extensionFolder, extensionLoader); var minimalisticModule = extensionManager.AvailableExtensions().Single(x => x.Id == "Minimalistic"); Assert.That(minimalisticModule.Features.Count(), Is.EqualTo(1)); Assert.That(minimalisticModule.Features.Single().Id, Is.EqualTo("Minimalistic")); } [Test] public void FeatureDescriptorsAreInDependencyOrder() { var extensionLoader = new StubLoaders(); var extensionFolder = new StubFolders(); extensionFolder.Manifests.Add("Alpha", @" Name: Alpha Version: 1.0.3 OrchardVersion: 1 Features: Alpha: Dependencies: Gamma "); extensionFolder.Manifests.Add("Beta", @" Name: Beta Version: 1.0.3 OrchardVersion: 1 "); extensionFolder.Manifests.Add("Gamma", @" Name: Gamma Version: 1.0.3 OrchardVersion: 1 Features: Gamma: Dependencies: Beta "); IExtensionManager extensionManager = CreateExtensionManager(extensionFolder, extensionLoader); var features = extensionManager.AvailableFeatures(); Assert.That(features.Aggregate("<", (a, b) => a + b.Id + "<"), Is.EqualTo("<Beta<Gamma<Alpha<")); } [Test] public void FeatureDescriptorsShouldBeLoadedInThemes() { var extensionLoader = new StubLoaders(); var moduleExtensionFolder = new StubFolders(); var themeExtensionFolder = new StubFolders(DefaultExtensionTypes.Theme); moduleExtensionFolder.Manifests.Add("Alpha", @" Name: Alpha Version: 1.0.3 OrchardVersion: 1 Features: Alpha: Dependencies: Gamma "); moduleExtensionFolder.Manifests.Add("Beta", @" Name: Beta Version: 1.0.3 OrchardVersion: 1 "); moduleExtensionFolder.Manifests.Add("Gamma", @" Name: Gamma Version: 1.0.3 OrchardVersion: 1 Features: Gamma: Dependencies: Beta "); themeExtensionFolder.Manifests.Add("Classic", @" Name: Classic Version: 1.0.3 OrchardVersion: 1 "); IExtensionManager extensionManager = CreateExtensionManager(new[] { moduleExtensionFolder, themeExtensionFolder }, new[] { extensionLoader }); var features = extensionManager.AvailableFeatures(); Assert.That(features.Count(), Is.EqualTo(4)); } [Test] public void ThemeFeatureDescriptorsShouldBeAbleToDependOnModules() { var extensionLoader = new StubLoaders(); var moduleExtensionFolder = new StubFolders(); var themeExtensionFolder = new StubFolders(DefaultExtensionTypes.Theme); moduleExtensionFolder.Manifests.Add("Alpha", CreateManifest("Alpha", null, "Gamma")); moduleExtensionFolder.Manifests.Add("Beta", CreateManifest("Beta")); moduleExtensionFolder.Manifests.Add("Gamma", CreateManifest("Gamma", null, "Beta")); moduleExtensionFolder.Manifests.Add("Classic", CreateManifest("Classic", null, "Alpha")); AssertFeaturesAreInOrder(new[] { moduleExtensionFolder, themeExtensionFolder }, extensionLoader, "<Beta<Gamma<Alpha<Classic<"); } private static string CreateManifest(string name, string priority = null, string dependencies = null) { return string.Format(CultureInfo.InvariantCulture, @" Name: {0} Version: 1.0.3 OrchardVersion: 1{1}{2}", name, (dependencies == null ? null : "\nDependencies: " + dependencies), (priority == null ? null : "\nPriority:" + priority)); } private static void AssertFeaturesAreInOrder(StubFolders folder, StubLoaders loader, string expectedOrder) { AssertFeaturesAreInOrder(new StubFolders[] { folder }, loader, expectedOrder); } private static void AssertFeaturesAreInOrder(IEnumerable<StubFolders> folders, StubLoaders loader, string expectedOrder) { var extensionManager = CreateExtensionManager(folders, new[] { loader }); var features = extensionManager.AvailableFeatures(); Assert.That(features.Aggregate("<", (a, b) => a + b.Id + "<"), Is.EqualTo(expectedOrder)); } [Test] public void FeatureDescriptorsAreInDependencyAndPriorityOrder() { var extensionLoader = new StubLoaders(); var extensionFolder = new StubFolders(); // Check that priorities apply correctly on items on the same level of dependencies and are overwritten by dependencies extensionFolder.Manifests.Add("Alpha", CreateManifest("Alpha", "2", "Gamma")); // More important than Gamma but will get overwritten by the dependency extensionFolder.Manifests.Add("Beta", CreateManifest("Beta", "2")); extensionFolder.Manifests.Add("Foo", CreateManifest("Foo", "1")); extensionFolder.Manifests.Add("Gamma", CreateManifest("Gamma", "3", "Beta, Foo")); AssertFeaturesAreInOrder(extensionFolder, extensionLoader, "<Foo<Beta<Gamma<Alpha<"); // Change priorities and see that it reflects properly // Gamma comes after Foo (same priority) because their order in the Manifests is preserved extensionFolder.Manifests["Foo"] = CreateManifest("Foo", "3"); AssertFeaturesAreInOrder(extensionFolder, extensionLoader, "<Beta<Foo<Gamma<Alpha<"); // Remove dependency on Foo and see that it moves down the list since no one depends on it anymore extensionFolder.Manifests["Gamma"] = CreateManifest("Gamma", "3", "Beta"); AssertFeaturesAreInOrder(extensionFolder, extensionLoader, "<Beta<Gamma<Alpha<Foo<"); // Change Foo to depend on Gamma and see that it says in its position (same dependencies as alpha but lower priority) extensionFolder.Manifests["Foo"] = CreateManifest("Foo", "3", "Gamma"); AssertFeaturesAreInOrder(extensionFolder, extensionLoader, "<Beta<Gamma<Alpha<Foo<"); // Update Foo to a higher priority than alpha and see that it moves before alpha extensionFolder.Manifests["Foo"] = CreateManifest("Foo", "1", "Gamma"); AssertFeaturesAreInOrder(extensionFolder, extensionLoader, "<Beta<Gamma<Foo<Alpha<"); } [Test] public void FeatureDescriptorsAreInPriorityOrder() { var extensionLoader = new StubLoaders(); var extensionFolder = new StubFolders(); // Check that priorities apply correctly on items on the same level of dependencies and are overwritten by dependencies extensionFolder.Manifests.Add("Alpha", CreateManifest("Alpha", "4")); // More important than Gamma but will get overwritten by the dependency extensionFolder.Manifests.Add("Beta", CreateManifest("Beta", "3")); extensionFolder.Manifests.Add("Foo", CreateManifest("Foo", "1")); extensionFolder.Manifests.Add("Gamma", CreateManifest("Gamma", "2")); AssertFeaturesAreInOrder(extensionFolder, extensionLoader, "<Foo<Gamma<Beta<Alpha<"); } [Test] public void FeatureDescriptorsAreInManifestOrderWhenTheyHaveEqualPriority() { var extensionLoader = new StubLoaders(); var extensionFolder = new StubFolders(); extensionFolder.Manifests.Add("Alpha", CreateManifest("Alpha", "4")); extensionFolder.Manifests.Add("Beta", CreateManifest("Beta", "4")); extensionFolder.Manifests.Add("Gamma", CreateManifest("Gamma", "4")); extensionFolder.Manifests.Add("Foo", CreateManifest("Foo", "3")); extensionFolder.Manifests.Add("Bar", CreateManifest("Bar", "3")); extensionFolder.Manifests.Add("Baz", CreateManifest("Baz", "3")); AssertFeaturesAreInOrder(extensionFolder, extensionLoader, "<Foo<Bar<Baz<Alpha<Beta<Gamma<"); } } }
// 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 OLEDB.Test.ModuleCore; using System.IO; using XmlCoreTest.Common; namespace System.Xml.Tests { //////////////////////////////////////////////////////////////// // Module // //////////////////////////////////////////////////////////////// [TestModule(Name = "Name Table", Desc = "Test for Get and Add methods")] public partial class CNameTableTestModule : CTestModule { //Accessors private string _TestData = null; public string TestData { get { return _TestData; } } public override int Init(object objParam) { int ret = base.Init(objParam); _TestData = Path.Combine(FilePathUtil.GetTestDataPath(), @"XmlReader\"); // Create global usage test files string strFile = String.Empty; NameTable_TestFiles.CreateTestFile(ref strFile, EREADER_TYPE.GENERIC); return ret; } public override int Terminate(object objParam) { return base.Terminate(objParam); } } //////////////////////////////////////////////////////////////// // TestCase TCBase // //////////////////////////////////////////////////////////////// public partial class TCBase : CTestCase { public enum ENAMETABLE_VER { VERIFY_WITH_GETSTR, VERIFY_WITH_GETCHAR, VERIFY_WITH_ADDSTR, VERIFY_WITH_ADDCHAR, }; private ENAMETABLE_VER _eNTVer; public ENAMETABLE_VER NameTableVer { get { return _eNTVer; } set { _eNTVer = value; } } public static string WRONG_EXCEPTION = "Catching Wrong Exception"; protected static string BigStr = new String('Z', (1 << 20) - 1); protected XmlReader DataReader; public override int Init(object objParam) { if (GetDescription() == "VerifyWGetString") { NameTableVer = ENAMETABLE_VER.VERIFY_WITH_GETSTR; } else if (GetDescription() == "VerifyWGetChar") { NameTableVer = ENAMETABLE_VER.VERIFY_WITH_GETCHAR; } else if (GetDescription() == "VerifyWAddString") { NameTableVer = ENAMETABLE_VER.VERIFY_WITH_ADDSTR; } else if (GetDescription() == "VerifyWAddChar") { NameTableVer = ENAMETABLE_VER.VERIFY_WITH_ADDCHAR; } else throw (new Exception()); int ival = base.Init(objParam); ReloadSource(); if (TEST_PASS == ival) { while (DataReader.Read() == true) ; } return ival; } protected void ReloadSource() { if (DataReader != null) { DataReader.Dispose(); } string strFile = NameTable_TestFiles.GetTestFileName(EREADER_TYPE.GENERIC); DataReader = XmlReader.Create(FilePathUtil.getStream(strFile), new XmlReaderSettings() { DtdProcessing = DtdProcessing.Ignore });//new XmlTextReader(strFile); } public void VerifyNameTable(object objActual, string str, char[] ach, int offset, int length) { VerifyNameTableGet(objActual, str, ach, offset, length); VerifyNameTableAdd(objActual, str, ach, offset, length); } public void VerifyNameTableGet(object objActual, string str, char[] ach, int offset, int length) { object objExpected = null; if (NameTableVer == ENAMETABLE_VER.VERIFY_WITH_GETSTR) { objExpected = DataReader.NameTable.Get(str); CError.WriteLine("VerifyNameTableWGetStr"); CError.Compare(objActual, objExpected, "VerifyNameTableWGetStr"); } else if (NameTableVer == ENAMETABLE_VER.VERIFY_WITH_GETCHAR) { objExpected = DataReader.NameTable.Get(ach, offset, length); CError.WriteLine("VerifyNameTableWGetChar"); CError.Compare(objActual, objExpected, "VerifyNameTableWGetChar"); } } public void VerifyNameTableAdd(object objActual, string str, char[] ach, int offset, int length) { object objExpected = null; if (NameTableVer == ENAMETABLE_VER.VERIFY_WITH_ADDSTR) { objExpected = DataReader.NameTable.Add(ach, offset, length); CError.WriteLine("VerifyNameTableWAddStr"); CError.Compare(objActual, objExpected, "VerifyNameTableWAddStr"); } else if (NameTableVer == ENAMETABLE_VER.VERIFY_WITH_ADDCHAR) { objExpected = DataReader.NameTable.Add(str); CError.WriteLine("VerifyNameTableWAddChar"); CError.Compare(objActual, objExpected, "VerifyNameTableWAddChar"); } } } //////////////////////////////////////////////////////////////// // TestCase TCRecord NameTable.Get // //////////////////////////////////////////////////////////////// //[TestCase(Name="NameTable(Get) VerifyWGetChar", Desc="VerifyWGetChar")] //[TestCase(Name="NameTable(Get) VerifyWGetString", Desc="VerifyWGetString")] //[TestCase(Name="NameTable(Get) VerifyWAddString", Desc="VerifyWAddString")] //[TestCase(Name="NameTable(Get) VerifyWAddChar", Desc="VerifyWAddChar")] public partial class TCRecordNameTableGet : TCBase { public static char[] chInv = { 'U', 'n', 'a', 't', 'o', 'm', 'i', 'z', 'e', 'd' }; public static char[] chVal = { 'P', 'L', 'A', 'Y' }; public static char[] chValW1EndExtra = { 'P', 'L', 'A', 'Y', 'Y' }; public static char[] chValW1FrExtra = { 'P', 'P', 'L', 'A', 'Y' }; public static char[] chValW1Fr1EndExtra = { 'P', 'P', 'L', 'A', 'Y', 'Y' }; public static char[] chValWEndExtras = { 'P', 'L', 'A', 'Y', 'Y', 'Y' }; public static char[] chValWFrExtras = { 'P', 'P', 'P', 'P', 'P', 'P', 'P', 'L', 'A', 'Y' }; public static char[] chValWFrEndExtras = { 'P', 'P', 'P', 'P', 'P', 'P', 'P', 'L', 'A', 'Y', 'Y', 'Y' }; public static string[] strPerVal = { "PLYA", "PALY", "PAYL", "PYLA", "PYAL", "LPAY", "LPYA", "LAPY", "LAYP", "LYPA", "LYAP", "ALPY", "ALYP", "APLY", "APYL", "AYLP", "AYPL", "YLPA", "YLAP", "YPLA", "YPAL", "YALP", "YAPL", }; public static string[] strPerValCase = { "pLAY", "plAY", "plaY", "play", "plAY", "plaY", "pLaY", "pLay", "pLAy", "PlAY", "PlaY", "Play", "PLaY", "PLAy" }; public static string strInv = "Unatomized"; public static string strVal = "PLAY"; [Variation("GetUnAutomized", Pri = 0)] public int Variation_1() { object objActual = DataReader.NameTable.Get(strInv); object objActual1 = DataReader.NameTable.Get(strInv); CError.Compare(objActual, null, CurVariation.Desc); CError.Compare(objActual1, null, CurVariation.Desc); CError.Compare(objActual, objActual1, CurVariation.Desc); VerifyNameTableGet(objActual, strInv, chInv, 0, chInv.Length); return TEST_PASS; } [Variation("Get Atomized String", Pri = 0)] public int Variation_2() { object objActual = DataReader.NameTable.Get(chVal, 0, chVal.Length); object objActual1 = DataReader.NameTable.Get(chVal, 0, chVal.Length); CError.Compare(objActual, objActual1, CurVariation.Desc); VerifyNameTable(objActual, strVal, chVal, 0, chVal.Length); return TEST_PASS; } [Variation("Get Atomized String with end padded", Pri = 0)] public int Variation_3() { object objActual = DataReader.NameTable.Get(chValW1EndExtra, 0, strVal.Length); object objActual1 = DataReader.NameTable.Get(chValW1EndExtra, 0, strVal.Length); CError.Compare(objActual, objActual1, CurVariation.Desc); VerifyNameTable(objActual, strVal, chValW1EndExtra, 0, strVal.Length); return TEST_PASS; } [Variation("Get Atomized String with front and end padded", Pri = 0)] public int Variation_4() { object objActual = DataReader.NameTable.Get(chValW1Fr1EndExtra, 1, strVal.Length); object objActual1 = DataReader.NameTable.Get(chValW1Fr1EndExtra, 1, strVal.Length); CError.Compare(objActual, objActual1, CurVariation.Desc); VerifyNameTable(objActual, strVal, chValW1Fr1EndExtra, 1, strVal.Length); return TEST_PASS; } [Variation("Get Atomized String with front padded", Pri = 0)] public int Variation_5() { object objActual = DataReader.NameTable.Get(chValW1FrExtra, 1, strVal.Length); object objActual1 = DataReader.NameTable.Get(chValW1FrExtra, 1, strVal.Length); CError.Compare(objActual, objActual1, CurVariation.Desc); VerifyNameTable(objActual, strVal, chValW1FrExtra, 1, strVal.Length); return TEST_PASS; } [Variation("Get Atomized String with end multi-padded", Pri = 0)] public int Variation_6() { object objActual = DataReader.NameTable.Get(chValWEndExtras, 0, strVal.Length); object objActual1 = DataReader.NameTable.Get(chValWEndExtras, 0, strVal.Length); CError.Compare(objActual, objActual1, CurVariation.Desc); VerifyNameTable(objActual, strVal, chValWEndExtras, 0, strVal.Length); return TEST_PASS; } [Variation("Get Atomized String with front and end multi-padded", Pri = 0)] public int Variation_7() { object objActual = DataReader.NameTable.Get(chValWFrEndExtras, 6, strVal.Length); object objActual1 = DataReader.NameTable.Get(chValWFrEndExtras, 6, strVal.Length); CError.Compare(objActual, objActual1, CurVariation.Desc); VerifyNameTable(objActual, strVal, chValWFrEndExtras, 6, strVal.Length); return TEST_PASS; } [Variation("Get Atomized String with front multi-padded", Pri = 0)] public int Variation_8() { object objActual = DataReader.NameTable.Get(chValWFrExtras, chValWFrExtras.Length - strVal.Length, strVal.Length); object objActual1 = DataReader.NameTable.Get(chValWFrExtras, chValWFrExtras.Length - strVal.Length, strVal.Length); CError.Compare(objActual, objActual1, CurVariation.Desc); VerifyNameTable(objActual, strVal, chValWFrExtras, chValWFrExtras.Length - strVal.Length, strVal.Length); return TEST_PASS; } [Variation("Get Invalid permutation of valid string", Pri = 0)] public int Variation_9() { for (int i = 0; i < strPerVal.Length; i++) { char[] ach = strPerVal[i].ToCharArray(); object objActual = DataReader.NameTable.Get(ach, 0, ach.Length); object objActual1 = DataReader.NameTable.Get(ach, 0, ach.Length); CError.Compare(objActual, null, CurVariation.Desc); CError.Compare(objActual1, null, CurVariation.Desc); CError.Compare(objActual, objActual1, CurVariation.Desc); VerifyNameTableGet(objActual, strPerVal[i], ach, 0, ach.Length); } return TEST_PASS; } [Variation("Get Valid Super String")] public int Variation_10() { string filename = null; NameTable_TestFiles.CreateTestFile(ref filename, EREADER_TYPE.BIG_ELEMENT_SIZE); XmlReader rDataReader = XmlReader.Create(FilePathUtil.getStream(filename)); while (rDataReader.Read() == true) ; XmlNameTable nt = rDataReader.NameTable; object objTest1 = nt.Get(BigStr + "Z"); object objTest2 = nt.Get(BigStr + "X"); object objTest3 = nt.Get(BigStr + "Y"); if (objTest1 != null) { throw new CTestException(CTestBase.TEST_FAIL, "objTest1 is not null"); } if (objTest2 == null) { throw new CTestException(CTestBase.TEST_FAIL, "objTest2 is null"); } if (objTest3 == null) { throw new CTestException(CTestBase.TEST_FAIL, "objTest3 is null"); } if ((objTest1 == objTest2) || (objTest1 == objTest3) || (objTest2 == objTest3)) throw new CTestException(CTestBase.TEST_FAIL, "objTest1 is equal to objTest2, or objTest3"); return TEST_PASS; } [Variation("Get invalid Super String")] public int Variation_11() { int size = (1 << 24); string str = ""; char[] ach = str.ToCharArray(); bool fRetry = false; for (; ;) { try { str = new String('Z', size); ach = str.ToCharArray(); } catch (OutOfMemoryException exc) { size >>= 1; CError.WriteLine(exc + " : " + exc.Message + " Retry with " + size); fRetry = true; } if (size < (1 << 30)) { fRetry = true; } if (fRetry) { CError.WriteLine("Tested size == " + size); if (str == null) CError.WriteLine("string is null"); break; } } object objActual = DataReader.NameTable.Get(ach, 0, ach.Length); object objActual1 = DataReader.NameTable.Get(ach, 0, ach.Length); CError.Compare(objActual, objActual1, CurVariation.Desc); VerifyNameTableGet(objActual, str, ach, 0, ach.Length); return TEST_PASS; } [Variation("Get empty string, valid offset and length = 0", Pri = 0)] public int Variation_12() { string str = String.Empty; char[] ach = str.ToCharArray(); object objActual = DataReader.NameTable.Get(ach, 0, ach.Length); object objActual1 = DataReader.NameTable.Get(ach, 0, 0); object objActual2 = DataReader.NameTable.Get(str); CError.Compare(objActual, objActual1, "Char with StringEmpty"); CError.Compare(String.Empty, objActual1, "Char with StringEmpty"); CError.Compare(String.Empty, objActual2, "StringEmpty"); VerifyNameTable(objActual, str, ach, 0, 0); return TEST_PASS; } [Variation("Get empty string, valid offset and length = 1", Pri = 0)] public int Variation_13() { char[] ach = new char[] { }; try { object objActual = DataReader.NameTable.Get(ach, 0, 1); } catch (IndexOutOfRangeException exc) { CError.WriteLine(exc + " : " + exc.Message); return TEST_PASS; } throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION); } [Variation("Get null char[], valid offset and length = 0", Pri = 0)] public int Variation_14() { char[] ach = null; object objActual = DataReader.NameTable.Add(ach, 0, 0); CError.Compare(String.Empty, objActual, "Char with null"); return TEST_PASS; } [Variation("Get null string", Pri = 0)] public int Variation_15() { string str = null; try { object objActual = DataReader.NameTable.Get(str); } catch (ArgumentNullException exc) { CError.WriteLine(exc + " : " + exc.Message); return TEST_PASS; } throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION); } [Variation("Get null char[], valid offset and length = 1", Pri = 0)] public int Variation_16() { char[] ach = null; try { object objActual = DataReader.NameTable.Add(ach, 0, 1); } catch (NullReferenceException exc) { CError.WriteLine(exc + " : " + exc.Message); return TEST_PASS; } throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION); } [Variation("Get valid string, invalid length, length = 0", Pri = 0)] public int Variation_17() { object objActual = DataReader.NameTable.Get(chVal, 0, 0); object objActual1 = DataReader.NameTable.Get(chVal, 0, 0); CError.WriteLine("Here " + chVal.ToString()); CError.WriteLine("Here2 " + DataReader.NameTable.Get(chVal, 0, 0)); if (DataReader.NameTable.Get(chVal, 0, 0) == String.Empty) CError.WriteLine("here"); if (DataReader.NameTable.Get(chVal, 0, 0) == null) CError.WriteLine("null"); CError.Compare(objActual, objActual1, CurVariation.Desc); VerifyNameTable(objActual, String.Empty, chVal, 0, 0); return TEST_PASS; } [Variation("Get valid string, invalid length, length = Length+1", Pri = 0)] public int Variation_18() { try { object objActual = DataReader.NameTable.Get(chVal, 0, chVal.Length + 1); } catch (IndexOutOfRangeException exc) { CError.WriteLine(exc + " : " + exc.Message); return TEST_PASS; } throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION); } [Variation("Get valid string, invalid length, length = max_int", Pri = 0)] public int Variation_19() { try { object objActual = DataReader.NameTable.Get(chVal, 0, Int32.MaxValue); } catch (IndexOutOfRangeException exc) { CError.WriteLine(exc + " : " + exc.Message); return TEST_PASS; } throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION); } [Variation("Get valid string, invalid length, length = -1", Pri = 0)] public int Variation_20() { object objActual = DataReader.NameTable.Get(chVal, 0, -1); CError.WriteLine("HERE " + objActual); return TEST_PASS; } [Variation("Get valid string, invalid offset > Length", Pri = 0)] public int Variation_21() { try { object objActual = DataReader.NameTable.Get(chVal, chVal.Length + 1, chVal.Length); } catch (IndexOutOfRangeException exc) { CError.WriteLine(exc + " : " + exc.Message); return TEST_PASS; } throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION); } [Variation("Get valid string, invalid offset = max_int", Pri = 0)] public int Variation_22() { try { object objActual = DataReader.NameTable.Get(chVal, Int32.MaxValue, chVal.Length); } catch (IndexOutOfRangeException exc) { CError.WriteLine(exc + " : " + exc.Message); return TEST_PASS; } throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION); } [Variation("Get valid string, invalid offset = Length", Pri = 0)] public int Variation_23() { try { object objActual = DataReader.NameTable.Get(chVal, chVal.Length, chVal.Length); } catch (IndexOutOfRangeException exc) { CError.WriteLine(exc + " : " + exc.Message); return TEST_PASS; } throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION); } [Variation("Get valid string, invalid offset -1", Pri = 0)] public int Variation_24() { try { object objActual = DataReader.NameTable.Get(chVal, -1, chVal.Length); } catch (IndexOutOfRangeException exc) { CError.WriteLine(exc + " : " + exc.Message); return TEST_PASS; } throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION); } [Variation("Get valid string, invalid offset and length", Pri = 0)] public int Variation_25() { try { object objActual = DataReader.NameTable.Get(chVal, -1, -1); } catch (IndexOutOfRangeException exc) { CError.WriteLine(exc + " : " + exc.Message); return TEST_PASS; } throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION); } } //////////////////////////////////////////////////////////////// // TestCase TCRecord NameTable.Add // //////////////////////////////////////////////////////////////// //[TestCase(Name="NameTable(Add) VerifyWGetString", Desc="VerifyWGetString")] //[TestCase(Name="NameTable(Add) VerifyWGetChar", Desc="VerifyWGetChar")] //[TestCase(Name="NameTable(Add) VerifyWAddString", Desc="VerifyWAddString")] //[TestCase(Name="NameTable(Add) VerifyWAddChar", Desc="VerifyWAddChar")] public partial class TCRecordNameTableAdd : TCBase { public static char[] chVal = { 'F', 'O', 'O' }; public static char[] chValW1EndExtra = { 'F', 'O', 'O', 'O' }; public static char[] chValW1FrExtra = { 'F', 'F', 'O', 'O', 'O' }; public static char[] chValW1Fr1EndExtra = { 'F', 'F', 'O', 'O', 'O' }; public static char[] chValWEndExtras = { 'F', 'O', 'O', 'O', 'O', 'O' }; public static char[] chValWFrExtras = { 'F', 'F', 'F', 'F', 'F', 'F', 'F', 'O', 'O', 'O' }; public static char[] chValWFrEndExtras = { 'F', 'F', 'F', 'F', 'F', 'F', 'F', 'O', 'O', 'O', 'O', 'O' }; public static string[] strPerVal = { "OFO", "OOF" }; public static string[] strPerValCase = { "fOO", "foO", "foo", "FoO", "Foo", "FOo" }; public static string strVal = "FOO"; public static string strWhitespaceVal = "WITH WHITESPACE"; public static string strAlphaNumVal = "WITH1Number"; public static string strSignVal = "+SIGN-"; [Variation("Add a new atomized string (padded with chars at the end), valid offset and length = str_length", Pri = 0)] public int Variation_1() { ReloadSource(); object objActual = DataReader.NameTable.Add(chValWEndExtras, 0, strVal.Length); object objActual1 = DataReader.NameTable.Add(chValWEndExtras, 0, strVal.Length); if (objActual == objActual1) CError.WriteLine(objActual + " and ", objActual1); CError.Compare(objActual, objActual1, CurVariation.Desc); VerifyNameTable(objActual, strVal, chValWEndExtras, 0, strVal.Length); return TEST_PASS; } [Variation("Add a new atomized string (padded with chars at both front and end), valid offset and length = str_length", Pri = 0)] public int Variation_2() { ReloadSource(); object objActual = DataReader.NameTable.Add(chValWFrEndExtras, 6, strVal.Length); object objActual1 = DataReader.NameTable.Add(chValWFrEndExtras, 6, strVal.Length); CError.Compare(objActual, objActual1, CurVariation.Desc); VerifyNameTable(objActual, strVal, chValWFrExtras, 6, strVal.Length); return TEST_PASS; } [Variation("Add a new atomized string (padded with chars at the front), valid offset and length = str_length", Pri = 0)] public int Variation_3() { ReloadSource(); object objActual = DataReader.NameTable.Add(chValWFrEndExtras, 6, strVal.Length); object objActual1 = DataReader.NameTable.Add(chValWFrEndExtras, 6, strVal.Length); CError.Compare(objActual, objActual1, CurVariation.Desc); VerifyNameTable(objActual, strVal, chValWFrEndExtras, 6, strVal.Length); return TEST_PASS; } [Variation("Add a new atomized string (padded a char at the end), valid offset and length = str_length", Pri = 0)] public int Variation_4() { ReloadSource(); object objActual = DataReader.NameTable.Add(chValW1EndExtra, 0, strVal.Length); object objActual1 = DataReader.NameTable.Add(chValW1EndExtra, 0, strVal.Length); CError.Compare(objActual, objActual1, CurVariation.Desc); VerifyNameTable(objActual, strVal, chValW1EndExtra, 0, strVal.Length); return TEST_PASS; } [Variation("Add a new atomized string (padded with a char at both front and end), valid offset and length = str_length", Pri = 0)] public int Variation_5() { ReloadSource(); object objActual = DataReader.NameTable.Add(chValW1Fr1EndExtra, 1, strVal.Length); object objActual1 = DataReader.NameTable.Add(chValW1Fr1EndExtra, 1, strVal.Length); CError.Compare(objActual, objActual1, CurVariation.Desc); VerifyNameTable(objActual, strVal, chValW1Fr1EndExtra, 1, strVal.Length); return TEST_PASS; } [Variation("Add a new atomized string (padded with a char at the front), valid offset and length = str_length", Pri = 0)] public int Variation_6() { ReloadSource(); object objActual = DataReader.NameTable.Add(chValW1FrExtra, 1, strVal.Length); object objActual1 = DataReader.NameTable.Add(chValW1FrExtra, 1, strVal.Length); CError.Compare(objActual, objActual1, CurVariation.Desc); VerifyNameTable(objActual, strVal, chValW1FrExtra, 1, strVal.Length); return TEST_PASS; } [Variation("Add new string between 1M - 2M in size, valid offset and length")] public int Variation_7() { char[] chTest = BigStr.ToCharArray(); object objActual1 = DataReader.NameTable.Add(chTest, 0, chTest.Length); object objActual2 = DataReader.NameTable.Add(chTest, 0, chTest.Length); CError.Compare(objActual1, objActual2, CurVariation.Desc); VerifyNameTable(objActual1, BigStr, chTest, 0, chTest.Length); return TEST_PASS; } [Variation("Add an existing atomized string (with Max string for test: 1-2M), valid offset and valid length")] public int Variation_8() { //////////////////////////// // Add strings again and verify string filename = null; NameTable_TestFiles.CreateTestFile(ref filename, EREADER_TYPE.BIG_ELEMENT_SIZE); XmlReader rDataReader = XmlReader.Create(FilePathUtil.getStream(filename)); while (rDataReader.Read() == true) ; XmlNameTable nt = rDataReader.NameTable; string strTest = BigStr + "X"; char[] chTest = strTest.ToCharArray(); Object objActual1 = nt.Add(chTest, 0, chTest.Length); Object objActual2 = nt.Add(chTest, 0, chTest.Length); CError.Compare(objActual1, objActual2, "Comparing objActual1 and objActual2"); CError.Compare(objActual1, nt.Get(chTest, 0, chTest.Length), "Comparing objActual1 and GetCharArray"); CError.Compare(objActual1, nt.Get(strTest), "Comparing objActual1 and GetString"); CError.Compare(objActual1, nt.Add(strTest), "Comparing objActual1 and AddString"); NameTable_TestFiles.RemoveDataReader(EREADER_TYPE.BIG_ELEMENT_SIZE); return TEST_PASS; } [Variation("Add new string, and do Get with a combination of the same string in different order", Pri = 0)] public int Variation_9() { ReloadSource(); // Add string Object objAdded = DataReader.NameTable.Add(strVal); // Look for permutations of strings, should be null. for (int i = 0; i < strPerVal.Length; i++) { char[] ach = strPerVal[i].ToCharArray(); object objActual = DataReader.NameTable.Get(ach, 0, ach.Length); object objActual1 = DataReader.NameTable.Get(ach, 0, ach.Length); CError.Compare(objActual, null, CurVariation.Desc); CError.Compare(objActual, objActual1, CurVariation.Desc); } return TEST_PASS; } [Variation("Add new string, and Add a combination of the same string in different case, all are different objects", Pri = 0)] public int Variation_10() { ReloadSource(); // Add string Object objAdded = DataReader.NameTable.Add(strVal); // Look for permutations of strings, should be null. for (int i = 0; i < strPerValCase.Length; i++) { char[] ach = strPerValCase[i].ToCharArray(); object objActual = DataReader.NameTable.Add(ach, 0, ach.Length); object objActual1 = DataReader.NameTable.Add(ach, 0, ach.Length); CError.Compare(objActual, objActual1, CurVariation.Desc); VerifyNameTable(objActual1, strPerValCase[i], ach, 0, ach.Length); if (objAdded == objActual) { throw new Exception("\n Object are the same for " + strVal + " and " + strPerValCase[i]); } } return TEST_PASS; } [Variation("Add 1M new string, and do Get with the last char different than the original string", Pri = 0)] public int Variation_11() { object objAdded = DataReader.NameTable.Add(BigStr + "M"); object objActual = DataReader.NameTable.Get(BigStr + "D"); CError.Compare(objActual, null, CurVariation.Desc); return TEST_PASS; } [Variation("Add new alpha numeric, valid offset, valid length", Pri = 0)] public int Variation_12() { ReloadSource(); char[] chTest = strAlphaNumVal.ToCharArray(); object objAdded = DataReader.NameTable.Add(chTest, 0, chTest.Length); object objActual1 = DataReader.NameTable.Add(chTest, 0, chTest.Length); CError.Compare(objActual1, objAdded, CurVariation.Desc); VerifyNameTable(objAdded, strAlphaNumVal, chTest, 0, chTest.Length); return TEST_PASS; } [Variation("Add new alpha numeric, valid offset, length= 0", Pri = 0)] public int Variation_13() { ReloadSource(); char[] chTest = strAlphaNumVal.ToCharArray(); object objAdded = DataReader.NameTable.Add(chTest, 0, 0); object objActual1 = DataReader.NameTable.Get(chVal, 0, chVal.Length); object objActual2 = DataReader.NameTable.Get(strVal); CError.Compare(objActual1, null, "Get should fail since Add with length=0 should fail"); CError.Compare(objActual1, objActual2, "Both Get should fail"); return TEST_PASS; } [Variation("Add new with whitespace, valid offset, valid length", Pri = 0)] public int Variation_14() { ReloadSource(); char[] chTest = strWhitespaceVal.ToCharArray(); object objAdded = DataReader.NameTable.Add(chTest, 0, chTest.Length); object objActual1 = DataReader.NameTable.Add(chTest, 0, chTest.Length); CError.Compare(objActual1, objAdded, CurVariation.Desc); VerifyNameTable(objAdded, strWhitespaceVal, chTest, 0, chTest.Length); return TEST_PASS; } [Variation("Add new with sign characters, valid offset, valid length", Pri = 0)] public int Variation_15() { ReloadSource(); char[] chTest = strSignVal.ToCharArray(); object objAdded = DataReader.NameTable.Add(chTest, 0, chTest.Length); object objActual1 = DataReader.NameTable.Add(chTest, 0, chTest.Length); CError.Compare(objActual1, objAdded, CurVariation.Desc); VerifyNameTable(objAdded, strSignVal, chTest, 0, chTest.Length); return TEST_PASS; } [Variation("Add new string between 1M - 2M in size, valid offset and length", Pri = 0)] public int Variation_16() { ReloadSource(); char[] chTest = BigStr.ToCharArray(); object objActual1 = DataReader.NameTable.Add(chTest, 0, chTest.Length); object objActual2 = DataReader.NameTable.Add(chTest, 0, chTest.Length); CError.Compare(objActual1, objActual2, CurVariation.Desc); VerifyNameTable(objActual1, BigStr, chTest, 0, chTest.Length); return TEST_PASS; } [Variation("Add new string, get object using permutations of upper & lowecase, should be null", Pri = 0)] public int Variation_17() { ReloadSource(); // Add string Object objAdded = DataReader.NameTable.Add(strVal); // Look for permutations of strings, should be null. for (int i = 0; i < strPerValCase.Length; i++) { char[] ach = strPerValCase[i].ToCharArray(); object objActual = DataReader.NameTable.Get(ach, 0, ach.Length); object objActual1 = DataReader.NameTable.Get(ach, 0, ach.Length); CError.Compare(objActual, null, CurVariation.Desc); CError.Compare(objActual, objActual1, CurVariation.Desc); } return TEST_PASS; } [Variation("Add an empty atomized string, valid offset and length = 0", Pri = 0)] public int Variation_18() { ReloadSource(); string strEmpty = String.Empty; object objAdded = DataReader.NameTable.Add(strEmpty); object objAdded1 = DataReader.NameTable.Add(strEmpty.ToCharArray(), 0, strEmpty.Length); object objActual1 = DataReader.NameTable.Get(strEmpty.ToCharArray(), 0, strEmpty.Length); object objActual2 = DataReader.NameTable.Get(strEmpty); CError.WriteLine("String " + DataReader.NameTable.Get(strEmpty)); CError.WriteLine("String " + objAdded1 + " String2 " + objAdded1); if (objAdded != objAdded1) CError.WriteLine("HERE"); CError.Compare(objActual1, objActual2, CurVariation.Desc); VerifyNameTable(objActual1, strEmpty, strEmpty.ToCharArray(), 0, 0); return TEST_PASS; } [Variation("Add an empty atomized string (array char only), valid offset and length = 1", Pri = 0)] public int Variation_19() { try { char[] chTest = String.Empty.ToCharArray(); object objAdded = DataReader.NameTable.Add(chTest, 0, 1); } catch (IndexOutOfRangeException) { return TEST_PASS; } throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION); } [Variation("Add a NULL atomized string, valid offset and length = 0", Pri = 0)] public int Variation_20() { object objAdded = DataReader.NameTable.Add(null, 0, 0); VerifyNameTable(objAdded, String.Empty, (String.Empty).ToCharArray(), 0, 0); return TEST_PASS; } [Variation("Add a NULL atomized string, valid offset and length = 1", Pri = 0)] public int Variation_21() { try { object objAdded = DataReader.NameTable.Add(null, 0, 1); } catch (NullReferenceException) { return TEST_PASS; } throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION); } [Variation("Add a valid atomized string, valid offset and length = 0", Pri = 0)] public int Variation_22() { ReloadSource(); object objAdded = DataReader.NameTable.Add(chVal, 0, 0); object objActual1 = DataReader.NameTable.Get(chVal, 0, chVal.Length); object objActual2 = DataReader.NameTable.Get(strVal); CError.Compare(objActual1, null, "Get should fail since Add with length=0 should fail"); CError.Compare(objActual1, objActual2, "Both Get should fail"); return TEST_PASS; } [Variation("Add a valid atomized string, valid offset and length > valid_length", Pri = 0)] public int Variation_23() { try { object objAdded = DataReader.NameTable.Add(chVal, 0, chVal.Length * 2); } catch (IndexOutOfRangeException) { return TEST_PASS; } throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION); } [Variation("Add a valid atomized string, valid offset and length = max_int", Pri = 0)] public int Variation_24() { try { object objAdded = DataReader.NameTable.Add(chVal, 0, Int32.MaxValue); } catch (IndexOutOfRangeException) { return TEST_PASS; } throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION); } [Variation("Add a valid atomized string, valid offset and length = - 1", Pri = 0)] public int Variation_25() { try { object objAdded = DataReader.NameTable.Add(chVal, 0, -1); } catch (ArgumentOutOfRangeException) { return TEST_PASS; } throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION); } [Variation("Add a valid atomized string, valid length and offset > str_length", Pri = 0)] public int Variation_26() { try { object objAdded = DataReader.NameTable.Add(chVal, chVal.Length * 2, chVal.Length); } catch (IndexOutOfRangeException) { return TEST_PASS; } throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION); } [Variation("Add a valid atomized string, valid length and offset = max_int", Pri = 0)] public int Variation_27() { try { object objAdded = DataReader.NameTable.Add(chVal, Int32.MaxValue, chVal.Length); } catch (IndexOutOfRangeException) { return TEST_PASS; } throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION); } [Variation("Add a valid atomized string, valid length and offset = str_length", Pri = 0)] public int Variation_28() { try { object objAdded = DataReader.NameTable.Add(chVal, chVal.Length, chVal.Length); } catch (IndexOutOfRangeException) { return TEST_PASS; } throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION); } [Variation("Add a valid atomized string, valid length and offset = - 1", Pri = 0)] public int Variation_29() { try { object objAdded = DataReader.NameTable.Add(chVal, -1, chVal.Length); } catch (IndexOutOfRangeException) { return TEST_PASS; } throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION); } [Variation("Add a valid atomized string, with both invalid offset and length", Pri = 0)] public int Variation_30() { try { object objAdded = DataReader.NameTable.Add(chVal, -1, -1); } catch (IndexOutOfRangeException) { return TEST_PASS; } throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.Drawing; using System.Globalization; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Web; using System.Web.Script; using System.Web.UI; using System.Web.UI.WebControls; using AjaxControlToolkit.Design; using BindingDirection = System.ComponentModel.BindingDirection; namespace AjaxControlToolkit { /// <summary> /// ReorderList is an ASP.NET AJAX control that implements a bulleted data-bound list with items that /// can be reordered interactively. To reorder items in the list, a user simply drags the item's control /// bar to its new location. Graphical feedback is shown where the item will be placed as it is dragged by /// the user. The data source is updated after the item is dropped in its new location. /// </summary> /// <remarks> /// When bound to data, the ReorderList control will behave like many other databound controls. If data you are /// displaying has a field that determines sort order (e.g. the select query is sorted by this column), and /// that column is of an integer type, the ReorderList can automatically perform reorders if its SortOrderField /// property is set. ReorderList can also be bound to a data source that implements IList (such as Arrays). /// /// The ReorderList control is different than other samples because it is an ASP.NET server-side control that is /// aware of ASP.NET AJAX behavior. Rather than extending existing controls on a page, it delivers rich client-side /// experience directly and still has a traditional postback server model for interaction with an application. /// /// ReorderList can handle reorders in two ways either via a callback or postback. In the case of a callback, no /// page postback happens on reordering. This is useful if data is only to be ordered. If data items are to be /// deleted or edited, a full postback needs to occur to sync the server side-state with the client0side state. /// The PostbackOnReorder property enables this. /// </remarks> [Designer(typeof(ReorderListDesigner))] [ToolboxBitmap(typeof(ToolboxIcons.Accessor), Constants.ReorderListName + Constants.IconPostfix)] public class ReorderList : CompositeDataBoundControl, IRepeatInfoUser, INamingContainer, ICallbackEventHandler, IPostBackEventHandler { static object ItemCommandKey = new object(); static object CancelCommandKey = new object(); static object EditCommandKey = new object(); static object DeleteCommandKey = new object(); static object UpdateCommandKey = new object(); static object InsertCommandKey = new object(); static object ItemDataBoundKey = new object(); static object ItemCreatedKey = new object(); static object ItemReorderKey = new object(); static object KeysKey = new object(); public event EventHandler<ReorderListCommandEventArgs> ItemCommand { add { Events.AddHandler(ItemCommandKey, value); } remove { Events.RemoveHandler(ItemCommandKey, value); } } public event EventHandler<ReorderListCommandEventArgs> CancelCommand { add { Events.AddHandler(CancelCommandKey, value); } remove { Events.RemoveHandler(CancelCommandKey, value); } } public event EventHandler<ReorderListCommandEventArgs> DeleteCommand { add { Events.AddHandler(DeleteCommandKey, value); } remove { Events.RemoveHandler(DeleteCommandKey, value); } } public event EventHandler<ReorderListCommandEventArgs> EditCommand { add { Events.AddHandler(EditCommandKey, value); } remove { Events.RemoveHandler(EditCommandKey, value); } } public event EventHandler<ReorderListCommandEventArgs> InsertCommand { add { Events.AddHandler(InsertCommandKey, value); } remove { Events.RemoveHandler(InsertCommandKey, value); } } public event EventHandler<ReorderListCommandEventArgs> UpdateCommand { add { Events.AddHandler(UpdateCommandKey, value); } remove { Events.RemoveHandler(UpdateCommandKey, value); } } public event EventHandler<ReorderListItemEventArgs> ItemDataBound { add { Events.AddHandler(ItemDataBoundKey, value); } remove { Events.RemoveHandler(ItemDataBoundKey, value); } } public event EventHandler<ReorderListItemEventArgs> ItemCreated { add { Events.AddHandler(ItemCreatedKey, value); } remove { Events.RemoveHandler(ItemCreatedKey, value); } } public event EventHandler<ReorderListItemReorderEventArgs> ItemReorder { add { Events.AddHandler(ItemReorderKey, value); } remove { Events.RemoveHandler(ItemReorderKey, value); } } // The actual list control. This control actually renders a DIV with some children: // * UL control // * DropWatcherExtender // * DraggableListitemExtender // * drop template control BulletedList _childList; // A control that we generate for the drop template Control _dropTemplateControl; ITemplate _reorderTemplate; ITemplate _itemTemplate; ITemplate _editItemTemplate; ITemplate _insertItemTemplate; ITemplate _dragHandleTemplate; ITemplate _emptyListTemplate; // The list of items that can be dragged around. We maintain this list so we know // what to generate later in the draggableListItems Extender List<DraggableListItemInfo> _draggableItems; DropWatcherExtender _dropWatcherExtender; private class DraggableListItemInfo { public Control TargetControl; public Control HandleControl; public DraggableListItemExtender Extender; } ArrayList itemsArray; const string ArgReplace = "_~Arg~_"; const string ArgContext = "_~Context~_"; const string ArgSuccess = "_~Success~_"; const string ArgError = "_~Error~_"; ReorderListItemLayoutType _layoutType = ReorderListItemLayoutType.Table; /// <summary> /// Determines whether or not to allow drag/drop reordering. It is automatically set to true if ReorderTemplate is present /// </summary> [DefaultValue(false)] public bool AllowReorder { get { return GetPropertyValue("AllowReorder", true); } set { SetPropertyValue("AllowReorder", value); } } IOrderedDictionary BoundFieldValues { get { if(ViewState["BoundFieldValues"] == null) { var bfv = new OrderedDictionary(); ViewState["BoundFieldValues"] = bfv; } return (IOrderedDictionary)ViewState["BoundFieldValues"]; } } /// <summary> /// A callback CSS style /// </summary> [DefaultValue("")] public string CallbackCssStyle { get { return GetPropertyValue("CallbackCssStyle", String.Empty); } set { SetPropertyValue("CallbackCssStyle", value); } } internal BulletedList ChildList { get { if(_childList == null) { _childList = new BulletedList(); _childList.ID = "_rbl"; this.Controls.Add(_childList); } else if(_childList.Parent == null) { // this gets cleared by base databinding code since the ChildList // is parented to the ReorderList. // this.Controls.Add(_childList); } return _childList; } } /// <summary> /// The primary key field for data /// </summary> [DefaultValue("")] public string DataKeyField { get { return GetPropertyValue("DataKeyName", String.Empty); } set { SetPropertyValue("DataKeyName", value); } } /// <summary> /// The indexed collection of data keys (one key for each row when data is bound) /// </summary> [Browsable(false)] public DataKeyCollection DataKeys { get { return new DataKeyCollection(DataKeysArray); } } // Set to true when a reorder callback happens. We check this on a // postback to see if we need to re-databind. bool DataBindPending { get { EnsureChildControls(); if(_dropWatcherExtender != null) { var state = _dropWatcherExtender.ClientState; return !String.IsNullOrEmpty(state); } return false; } } protected ArrayList DataKeysArray { get { if(ViewState["DataKeysArray"] == null) ViewState["DataKeysArray"] = new ArrayList(); return (ArrayList)ViewState["DataKeysArray"]; } } /// <summary> /// ID of the data source to use to populate this control /// </summary> [TypeConverter(typeof(TypedControlIDConverter<IDataSource>))] public override string DataSourceID { get { return base.DataSourceID; } set { base.DataSourceID = value; } } /// <summary> /// Sets the drag handle relative to the item row (Top, Bottom, Left, or Right) /// </summary> [DefaultValue(ReorderHandleAlignment.Left)] public ReorderHandleAlignment DragHandleAlignment { get { return GetPropertyValue("DragHandleAlignment", ReorderHandleAlignment.Left); } set { SetPropertyValue("DragHandleAlignment", value); } } /// <summary> /// A template for the drag handle that a user clicks and drags to reorder items /// </summary> [Browsable(false)] [TemplateContainer(typeof(ReorderListItem))] [PersistenceMode(PersistenceMode.InnerProperty)] [DefaultValue("")] public ITemplate DragHandleTemplate { get { return _dragHandleTemplate; } set { _dragHandleTemplate = value; } } /// <summary> /// A template to show when a list has no data. This item is not data-bindable /// </summary> [Browsable(false)] [TemplateContainer(typeof(ReorderListItem))] [PersistenceMode(PersistenceMode.InnerProperty)] [DefaultValue("")] public ITemplate EmptyListTemplate { get { return _emptyListTemplate; } set { _emptyListTemplate = value; } } /// <summary> /// An index of an item that is currently in Edit mode. /// The default value is -1, which means no item is in edit mode /// </summary> [DefaultValue(-1)] public int EditItemIndex { get { return GetPropertyValue("EditItemIndex", -1); } set { SetPropertyValue("EditItemIndex", value); } } /// <summary> /// A template to display for a row that is in Edit mode /// </summary> [Browsable(false)] [TemplateContainer(typeof(IDataItemContainer), BindingDirection.TwoWay)] [PersistenceMode(PersistenceMode.InnerProperty)] [DefaultValue("")] public ITemplate EditItemTemplate { get { return _editItemTemplate; } set { _editItemTemplate = value; } } /// <summary> /// Determines where new items are inserted into the list (Beginning or End) /// </summary> [DefaultValue(ReorderListInsertLocation.Beginning)] public ReorderListInsertLocation ItemInsertLocation { get { return GetPropertyValue("ItemInsertLocation", ReorderListInsertLocation.Beginning); } set { SetPropertyValue("ItemInsertLocation", value); } } /// <summary> /// A template to show for adding new items to the list /// </summary> [Browsable(false)] [TemplateContainer(typeof(IDataItemContainer), BindingDirection.TwoWay)] [PersistenceMode(PersistenceMode.InnerProperty)] [DefaultValue("")] public ITemplate InsertItemTemplate { get { return _insertItemTemplate; } set { _insertItemTemplate = value; } } /// <summary> /// A template to display for items in the list /// </summary> [Browsable(false)] [TemplateContainer(typeof(IDataItemContainer), BindingDirection.TwoWay)] [PersistenceMode(PersistenceMode.InnerProperty)] [DefaultValue("")] public ITemplate ItemTemplate { get { return _itemTemplate; } set { _itemTemplate = value; } } /// <summary> /// A collection of reodered list items /// </summary> [Browsable(false)] public ReorderListItemCollection Items { get { EnsureDataBound(); return new ReorderListItemCollection(this); } } /// <summary> /// The type of a layout to apply to items. If Table is selected, the DragHandleAlignment property /// is used to lay out items in relation to the drag handle. If not, items are simply wrapped in /// the Panel controls and can be positioned using CSS /// </summary> [DefaultValue(ReorderListItemLayoutType.Table)] public ReorderListItemLayoutType LayoutType { get { return _layoutType; } set { _layoutType = value; } } /// <summary> /// Determines whether or not to do a postback on reordering /// </summary> [DefaultValue("true")] public bool PostBackOnReorder { get { return GetPropertyValue("PostBackOnReorder", false); } set { SetPropertyValue("PostBackOnReorder", value); } } /// <summary> /// The name of a column that controls the sort order of rows in the data base /// </summary> [DefaultValue("")] public string SortOrderField { get { return GetPropertyValue("SortOrderField", String.Empty); } set { SetPropertyValue("SortOrderField", value); } } /// <summary> /// A template to use as a visible drop element when a user is dragging an item. /// This template is not data-bindable /// </summary> [Browsable(false)] [TemplateContainer(typeof(ReorderListItem))] [PersistenceMode(PersistenceMode.InnerDefaultProperty)] [DefaultValue("")] public ITemplate ReorderTemplate { get { return _reorderTemplate; } set { _reorderTemplate = value; } } /// <summary> /// Determines whether or not the InsertItem is shown. If this value is /// not set and the InsertItemTemplate is set, the default value is set to true /// </summary> [DefaultValue(false)] public bool ShowInsertItem { get { return GetPropertyValue("ShowInsertItem", InsertItemTemplate != null); } set { SetPropertyValue("ShowInsertItem", value); } } // This control renders a DIV protected override HtmlTextWriterTag TagKey { get { return HtmlTextWriterTag.Div; } } public ReorderList() { } // Helper method to copy the values from one dictionary to another. static IDictionary CopyDictionary(IDictionary source, IDictionary dest) { if(dest == null) dest = new OrderedDictionary(source.Count); foreach(DictionaryEntry de in source) { dest[de.Key] = de.Value; } return dest; } void ClearChildren() { ChildList.Controls.Clear(); _dropTemplateControl = null; if(_draggableItems != null) { foreach(var item in _draggableItems) { if(item.Extender != null) item.Extender.Dispose(); } } _draggableItems = null; for(int i = Controls.Count - 1; i >= 0; i--) { if(Controls[i] is DropWatcherExtender) { Controls[i].Dispose(); } } } // This method does the heavy lifting of building the control hierarchy from a dataSource. // If no datasource is passed in, for example when a postback occurs, it creates a dummy list // based on the number of items it last had. protected override int CreateChildControls(IEnumerable dataSource, bool dataBinding) { ClearChildren(); var countDelta = 0; var keysArray = DataKeysArray; itemsArray = new ArrayList(); var count = DesignMode ? 1 : 0; if(dataBinding) { keysArray.Clear(); var c = dataSource as ICollection; if(c != null) { keysArray.Capacity = c.Count; itemsArray.Capacity = c.Count; } } if(dataSource != null) { var keyField = DataKeyField; var storeKey = (dataBinding && !String.IsNullOrEmpty(keyField)); var hasDragHandle = AllowReorder && (DragHandleTemplate != null); count = 0; var index = 0; // for each item in the list, create it's ReorderListItem // which gets automatically added to the parent. // foreach(var dataItem in dataSource) { if(storeKey) keysArray.Add(DataBinder.GetPropertyValue(dataItem, keyField)); var itemType = ListItemType.Item; if(index == EditItemIndex) itemType = ListItemType.EditItem; CreateItem(index, dataBinding, dataItem, itemType, hasDragHandle); count++; index++; } // add the insert item if needed. // if(ShowInsertItem && InsertItemTemplate != null) { CreateInsertItem(index); countDelta++; } } if(AllowReorder && count > 1 && _draggableItems != null) { // we should now have a list of items that can be dragged, // setup the the extender behaviors for them. // foreach(DraggableListItemInfo dlii in _draggableItems) { dlii.Extender = new DraggableListItemExtender(); dlii.Extender.TargetControlID = dlii.TargetControl.ID; dlii.Extender.Handle = dlii.HandleControl.ClientID; dlii.Extender.ID = String.Format(CultureInfo.InvariantCulture, "{0}_{1}", this.ID, dlii.Extender.TargetControlID); this.Controls.Add(dlii.Extender); } // render our drag templates. // Control dropArea, emptyItem; GetDropTemplateControl(out dropArea, out emptyItem); _dropWatcherExtender = new DropWatcherExtender(); _dropWatcherExtender.ArgReplaceString = ArgReplace; _dropWatcherExtender.CallbackCssStyle = CallbackCssStyle; _dropWatcherExtender.DropLayoutElement = dropArea.ID; if(PostBackOnReorder) _dropWatcherExtender.PostBackCode = Page.ClientScript.GetPostBackEventReference(this, ArgReplace); else { _dropWatcherExtender.PostBackCode = Page.ClientScript.GetCallbackEventReference(this, "'" + ArgReplace + "'", ArgSuccess, "'" + ArgContext + "'", ArgError, true); _dropWatcherExtender.ArgContextString = ArgContext; _dropWatcherExtender.ArgSuccessString = ArgSuccess; _dropWatcherExtender.ArgErrorString = ArgError; } _dropWatcherExtender.EnableClientState = !PostBackOnReorder; _dropWatcherExtender.BehaviorID = UniqueID + "_dItemEx"; _dropWatcherExtender.TargetControlID = ChildList.ID; this.Controls.Add(_dropWatcherExtender); } return ChildList.Controls.Count - countDelta; } // Creates the control that will be our reorder template. Control CreateReorderArea(int index, string reorderKey) { var reorderContainer = new Panel(); reorderContainer.ID = String.Format(CultureInfo.InvariantCulture, "__drop{1}{0}", index, reorderKey); if(ReorderTemplate != null) ReorderTemplate.InstantiateIn(reorderContainer); return reorderContainer; } protected virtual ReorderListItem CreateInsertItem(int index) { if(InsertItemTemplate != null && ShowInsertItem) { var item = new ReorderListItem(index, true); InsertItemTemplate.InstantiateIn(item); ChildList.Controls.Add(item); return item; } return null; } // Builds the drag handle element and the table which controls it's alignment protected virtual void CreateDragHandle(ReorderListItem item) { if(!AllowReorder) return; Control dragHolder = item; if(DragHandleTemplate != null) { Control outerItem = null; Control itemParent = null; if(LayoutType == ReorderListItemLayoutType.User) { outerItem = new Panel(); Panel itemCell = new Panel(); Panel handleCell = new Panel(); dragHolder = handleCell; itemParent = itemCell; if(DragHandleAlignment == ReorderHandleAlignment.Left || DragHandleAlignment == ReorderHandleAlignment.Top) { outerItem.Controls.Add(handleCell); outerItem.Controls.Add(itemCell); } else { outerItem.Controls.Add(itemCell); outerItem.Controls.Add(handleCell); } } else { // we'll use a table to organize all of this. Set it up. // var itemTable = new Table(); outerItem = itemTable; itemTable.BorderWidth = 0; itemTable.Style.Add("border-spacing", "0 0"); // we keep track of two cells: one to put the item in, // on to put the handle in. // var itemCell = new TableCell(); itemParent = itemCell; itemCell.Width = new Unit(100, UnitType.Percentage); itemCell.Style.Add("padding", "0"); var handleCell = new TableCell(); handleCell.Style.Add("padding", "0"); dragHolder = handleCell; // based on the alignment value, we set up the cells in the table. // switch(DragHandleAlignment) { case ReorderHandleAlignment.Left: case ReorderHandleAlignment.Right: var r = new TableRow(); if(DragHandleAlignment == ReorderHandleAlignment.Left) { r.Cells.Add(handleCell); r.Cells.Add(itemCell); } else { r.Cells.Add(itemCell); r.Cells.Add(handleCell); } itemTable.Rows.Add(r); break; case ReorderHandleAlignment.Top: case ReorderHandleAlignment.Bottom: var itemRow = new TableRow(); var handleRow = new TableRow(); itemRow.Cells.Add(itemCell); handleRow.Cells.Add(handleCell); if(DragHandleAlignment == ReorderHandleAlignment.Top) { itemTable.Rows.Add(handleRow); itemTable.Rows.Add(itemRow); } else { itemTable.Rows.Add(itemRow); itemTable.Rows.Add(handleRow); } break; } } // move the controls into the item cell from the item itself. // MoveChildren(item, itemParent); // create the dragholder // var holderItem = new ReorderListItem(item, HtmlTextWriterTag.Div); DragHandleTemplate.InstantiateIn(holderItem); dragHolder.Controls.Add(holderItem); // add the table // item.Controls.Add(outerItem); } else { // otherwise we just create dummy holder (apologies to dummies). // var holderPanel = new Panel(); MoveChildren(item, holderPanel); dragHolder = holderPanel; item.Controls.Add(holderPanel); } dragHolder.ID = String.Format(CultureInfo.InvariantCulture, "__dih{0}", item.ItemIndex); // add the item we created to the draggableItems list. // if(_draggableItems == null) _draggableItems = new List<DraggableListItemInfo>(); var dlii = new DraggableListItemInfo(); dlii.TargetControl = item; dlii.HandleControl = dragHolder; _draggableItems.Add(dlii); } // Creates a item at the specified index and binds it to the given data source. protected virtual ReorderListItem CreateItem(int index, bool dataBind, object dataItem, ListItemType itemType, bool hasDragHandle) { if(itemType != ListItemType.Item && itemType != ListItemType.EditItem && itemType != ListItemType.Separator) throw new ArgumentException("Unknown value", "itemType"); var item = new ReorderListItem(dataItem, index, itemType); item.ClientIDMode = ClientIDMode.AutoID; OnItemCreated(new ReorderListItemEventArgs(item)); var template = ItemTemplate; if(index == EditItemIndex) { template = EditItemTemplate; } if(itemType == ListItemType.Separator) { template = ReorderTemplate; } if(template != null) { template.InstantiateIn(item); } if(itemType == ListItemType.Item && template == null && dataItem != null && DataSource is IList) { // if we don't have a type, and we're bound to an IList, just convert the value. // var tc = TypeDescriptor.GetConverter(dataItem); if(tc != null) { var l = new Label(); l.Text = tc.ConvertToString(null, CultureInfo.CurrentUICulture, dataItem); item.Controls.Add(l); } } CreateDragHandle(item); ChildList.Controls.Add(item); if(dataBind) { item.DataBind(); OnItemDataBound(new ReorderListItemEventArgs(item)); item.DataItem = null; } return item; } protected virtual bool DoReorder(int oldIndex, int newIndex) { if(IsBoundUsingDataSourceID && SortOrderField != null) { var dsv = GetData(); var w = new System.Threading.EventWaitHandle(false, EventResetMode.AutoReset); var success = false; RequiresDataBinding = true; try { // get the data that's currently in the database // dsv.Select(new DataSourceSelectArguments(), delegate(IEnumerable dataSource) { success = DoReorderInternal(dataSource, oldIndex, newIndex, dsv); w.Set(); } ); w.WaitOne(); // wait for the select to finish - this makes an async operation look // like a synchronous one. // } catch(Exception ex) { CallbackResult = ex.Message; throw; } return success; } else if(DataSource is DataTable || DataSource is DataView) { var dt = DataSource as DataTable; if(dt == null) { dt = ((DataView)DataSource).Table; } return DoReorderInternal(dt, oldIndex, newIndex); } else if(DataSource is IList && !((IList)DataSource).IsReadOnly) { var ds = (IList)DataSource; var value = ds[oldIndex]; if(oldIndex > newIndex) { for(var i = oldIndex; i > newIndex; i--) { // copy all the items up ds[i] = ds[i - 1]; } } else { for(var i = oldIndex; i < newIndex; i++) { ds[i] = ds[i + 1]; } } ds[newIndex] = value; return true; } return false; } // Reorder row [oldIndex] to position [newIndex] in a datatable. bool DoReorderInternal(DataTable dataSource, int oldIndex, int newIndex) { if(String.IsNullOrEmpty(SortOrderField)) { return false; } var start = Math.Min(oldIndex, newIndex); var end = Math.Max(oldIndex, newIndex); var filter = String.Format(CultureInfo.InvariantCulture, "{0} >= {1} AND {0} <= {2}", SortOrderField, start, end); var rows = dataSource.Select(filter, SortOrderField + " ASC"); var column = dataSource.Columns[SortOrderField]; var newValue = rows[newIndex - start][column]; // reorder the list to reflect the new sort. // if(oldIndex > newIndex) { for(var i = 0; i < rows.Length - 1; i++) { rows[i][column] = rows[i + 1][column]; } } else { for(var i = rows.Length - 1; i > 0; i--) { rows[i][column] = rows[i - 1][column]; } } rows[oldIndex - start][column] = newValue; dataSource.AcceptChanges(); return true; } // Does the real work of the reorder. It moves the item from oldIndex to newIndex in the given data source. bool DoReorderInternal(IEnumerable dataSource, int oldIndex, int newIndex, DataSourceView dsv) { var sortField = SortOrderField; // get the values for each row that we'll be modifying. // var valuesList = new List<IOrderedDictionary>(Math.Abs(oldIndex - newIndex)); var start = Math.Min(oldIndex, newIndex); var end = Math.Max(oldIndex, newIndex); if(start == end) { return false; } var i = 0; foreach(var row in dataSource) { try { if(i < start) { continue; } if(i > end) { break; } var values = new OrderedDictionary(); var keys = new Hashtable(); var props = TypeDescriptor.GetProperties(row); foreach(PropertyDescriptor p in props) { var value = p.GetValue(row); // convert DBNulls to Null (See Issue 5900) if(p.PropertyType.IsValueType && value == DBNull.Value) { value = null; } values[p.Name] = value; if(p.Name == DataKeyField) { keys[p.Name] = values[p.Name]; values.Remove(p.Name); } } // stuff the row into the newValues, we'll use it later. // values[KeysKey] = keys; valuesList.Add(values); } finally { i++; } } // now that we've got the values, swap them in the list. // First, make the indexes zero-based. // oldIndex -= start; newIndex -= start; var startOrder = int.MinValue; // figure out the current sort value of the highest item in the // list. // if(valuesList.Count > 0 && valuesList[0].Contains(sortField)) { var startValue = valuesList[0][sortField]; string startValueAsString; if(startValue is int) { // optimize the common case // startOrder = (int)startValue; } else if((startValueAsString = startValue as string) != null) { if(!Int32.TryParse(startValueAsString, NumberStyles.Integer, CultureInfo.InvariantCulture, out startOrder)) { return false; } } else { // handle all the various int flavors... // if(startValue != null && startValue.GetType().IsValueType && startValue.GetType().IsPrimitive) { startOrder = Convert.ToInt32(startValue, CultureInfo.InvariantCulture); return true; } return false; } } else { throw new InvalidOperationException("Couldn't find sort field '" + SortOrderField + "' in bound data."); } // start at zero if we couldn't find anything. if(startOrder == int.MinValue) { startOrder = 0; } // swap the items in the list itself. // var targetItem = valuesList[oldIndex]; valuesList.RemoveAt(oldIndex); valuesList.Insert(newIndex, targetItem); // walk through each of them and update the source column // foreach(var values in valuesList) { // pull the keys back out. // var keys = (IDictionary)values[KeysKey]; // remove it from our values collection so it doesn't // get based to the data source // values.Remove(KeysKey); // Copy the current values to use as the old values. // var oldValues = CopyDictionary(values, null); // update the sort index // values[sortField] = startOrder++; // now call update with the new sort value. // dsv.Update(keys, values, oldValues, delegate(int rowsAffected, Exception ex) { if(ex != null) throw new Exception("Failed to reorder.", ex); return true; } ); } return true; } protected override void OnPreRender(EventArgs e) { // on pre render, see if an async call back happened. // if so, flip requires data binding. // if(DataBindPending) RequiresDataBinding = true; base.OnPreRender(e); } // Get the template to give us the current values for each field we need. void ExtractRowValues(IOrderedDictionary fieldValues, ReorderListItem item, bool includePrimaryKey, bool isAddOperation) { if(fieldValues == null) return; var bindableTemplate = ItemTemplate as IBindableTemplate; if(!isAddOperation) { switch(item.ItemType) { case ListItemType.Item: break; case ListItemType.EditItem: bindableTemplate = EditItemTemplate as IBindableTemplate; break; default: return; } } else { bindableTemplate = InsertItemTemplate as IBindableTemplate; } if(bindableTemplate != null) { var keyName = DataKeyField; var newValues = bindableTemplate.ExtractValues(item); foreach(DictionaryEntry entry in newValues) { // put the value in unless it's the primary key, we get that elsewhere. // if(includePrimaryKey || 0 != String.Compare((string)entry.Key, keyName, StringComparison.OrdinalIgnoreCase)) { fieldValues[entry.Key] = entry.Value; } } } } // Creates our DropTemplate control. The DragDropList behavior uses a second UL control to // do the actual drags. That control has children that represent the item to use as the dropTemplate // or empty template. This method creates that structure. protected WebControl GetDropTemplateControl(out Control dropItem, out Control emptyItem) { dropItem = null; emptyItem = null; if(!AllowReorder || DesignMode) return null; if(_dropTemplateControl == null) { var bl = new BulletedList(); // make sure it doesn't show up. bl.Style["visibility"] = "hidden"; bl.Style["display"] = "none"; var dropAreaItem = new BulletedListItem(); dropAreaItem.ID = "_dat"; dropAreaItem.Style["vertical-align"] = "middle"; if(ReorderTemplate == null) dropAreaItem.Style["border"] = "1px solid black"; else ReorderTemplate.InstantiateIn(dropAreaItem); dropItem = dropAreaItem; bl.Controls.Add(dropAreaItem); _dropTemplateControl = bl; this.Controls.Add(bl); } else { dropItem = _dropTemplateControl.FindControl("_dat"); emptyItem = null; } return (WebControl)_dropTemplateControl; } // Walks the database to find the correct value for a new item inserted into the list. int GetNewItemSortValue(out bool success) { var dsv = GetData(); var w = new System.Threading.EventWaitHandle(false, EventResetMode.AutoReset); var newIndex = 0; var bSuccess = false; dsv.Select(new DataSourceSelectArguments(), delegate(IEnumerable dataSource) { try { // look for the first or last row, based on our InsertItemLocation // var list = dataSource as IList; if(list == null) { return; } if(0 == list.Count) { bSuccess = true; return; } object row = null; var delta = 1; if(ItemInsertLocation == ReorderListInsertLocation.End) { row = list[list.Count - 1]; } else { row = list[0]; delta = -1; } var rowProp = TypeDescriptor.GetProperties(row)[SortOrderField]; if(rowProp != null) { var rowValue = rowProp.GetValue(row); if(rowValue is int) { newIndex = (int)rowValue + delta; bSuccess = true; } } } finally { w.Set(); } } ); w.WaitOne(); success = bSuccess; return newIndex; } void HandleCancel(ReorderListCommandEventArgs e) { if(IsBoundUsingDataSourceID) { EditItemIndex = -1; RequiresDataBinding = true; } OnCancelCommand(e); } void HandleDelete(ReorderListCommandEventArgs e) { if(IsBoundUsingDataSourceID) { var view = GetData(); if(view != null) { IDictionary oldValues; IOrderedDictionary newValues; IDictionary keys; PrepareRowValues(e, out oldValues, out newValues, out keys); view.Delete(keys, oldValues, delegate(int rows, Exception ex) { if(ex != null) return false; OnDeleteCommand(e); return true; } ); return; } } OnDeleteCommand(e); RequiresDataBinding = true; } void HandleEdit(ReorderListCommandEventArgs e) { if(e.Item.ItemType == ListItemType.Item) { EditItemIndex = e.Item.ItemIndex; RequiresDataBinding = true; } OnEditCommand(e); } void HandleInsert(ReorderListCommandEventArgs e) { if(IsBoundUsingDataSourceID && SortOrderField != null) { IDictionary oldValues; IOrderedDictionary newValues; IDictionary keys; PrepareRowValues(e, out oldValues, out newValues, out keys, true); var view = GetData(); bool success; var newIndex = GetNewItemSortValue(out success); if(success) newValues[SortOrderField] = newIndex; if(view != null) { view.Insert(newValues, delegate(int rows, Exception ex) { if(ex != null) return false; OnInsertCommand(e); return true; } ); return; } } OnInsertCommand(e); RequiresDataBinding = true; } void HandleUpdate(ReorderListCommandEventArgs e, int itemIndex) { if(IsBoundUsingDataSourceID) { IDictionary oldValues; IOrderedDictionary newValues; IDictionary keys; if(e == null && itemIndex != -1) { e = new ReorderListCommandEventArgs(new CommandEventArgs("Update", null), this, (ReorderListItem)ChildList.Controls[itemIndex]); } PrepareRowValues(e, out oldValues, out newValues, out keys); var view = GetData(); if(view != null) { view.Update(keys, newValues, oldValues, delegate(int rows, Exception ex) { if(ex != null) return false; OnUpdateCommand(e); EditItemIndex = -1; return true; } ); return; } } OnUpdateCommand(e); } static void MoveChildren(Control source, Control dest) { for(var i = source.Controls.Count - 1; i >= 0; i--) dest.Controls.AddAt(0, source.Controls[i]); } protected override bool OnBubbleEvent(object source, EventArgs args) { var ce = args as ReorderListCommandEventArgs; if(ce != null) { OnItemCommand(ce); if(ce.CommandArgument != null) { var command = ce.CommandName.ToString(CultureInfo.InvariantCulture).ToUpperInvariant(); switch(command) { case "INSERT": HandleInsert(ce); return true; case "UPDATE": HandleUpdate(ce, -1); return true; case "EDIT": HandleEdit(ce); return true; case "DELETE": HandleDelete(ce); return true; case "CANCEL": HandleCancel(ce); return true; } } } return false; } protected virtual void OnItemCreated(EventArgs e) { Invoke(ItemCreatedKey, e); } protected virtual void OnItemDataBound(EventArgs e) { Invoke(ItemDataBoundKey, e); } protected virtual void OnItemCommand(EventArgs e) { Invoke(ItemCommandKey, e); } protected virtual void OnItemReorder(ReorderListItemReorderEventArgs e) { try { if((DataSource != null || IsBoundUsingDataSourceID) && !DoReorder(e.OldIndex, e.NewIndex)) throw new InvalidOperationException("Can't reorder data source. It is not a DataSource and does not implement IList."); } catch(Exception ex) { CallbackResult = ex.Message; throw; } Invoke(ItemReorderKey, e); } protected virtual void OnCancelCommand(EventArgs e) { Invoke(CancelCommandKey, e); } protected virtual void OnDeleteCommand(EventArgs e) { Invoke(DeleteCommandKey, e); } protected virtual void OnEditCommand(EventArgs e) { Invoke(EditCommandKey, e); } protected virtual void OnInsertCommand(EventArgs e) { Invoke(InsertCommandKey, e); } protected virtual void OnUpdateCommand(EventArgs e) { Invoke(UpdateCommandKey, e); } protected void Invoke(object key, EventArgs e) { var eventHandler = Events[key]; if(eventHandler != null) eventHandler.DynamicInvoke(this, e); } protected override void PerformDataBinding(IEnumerable data) { ClearChildren(); base.PerformDataBinding(data); if(IsBoundUsingDataSourceID && EditItemIndex != -1 && EditItemIndex < Controls.Count && IsViewStateEnabled) { // if we're editing, pick up the bound original values. // BoundFieldValues.Clear(); ExtractRowValues(BoundFieldValues, ChildList.Controls[EditItemIndex] as ReorderListItem, false, false); } } void PrepareRowValues(ReorderListCommandEventArgs e, out IDictionary oldValues, out IOrderedDictionary newValues, out IDictionary keys) { PrepareRowValues(e, out oldValues, out newValues, out keys, false); } // Extracts the values from an editable row into the given dictionaries. private void PrepareRowValues(ReorderListCommandEventArgs e, out IDictionary oldValues, out IOrderedDictionary newValues, out IDictionary keys, bool isAddOperation) { if(!isAddOperation) oldValues = CopyDictionary(BoundFieldValues, null); else oldValues = null; newValues = new OrderedDictionary(oldValues == null ? 0 : oldValues.Count); if(DataKeyField != null && !isAddOperation) { keys = new OrderedDictionary(1); keys[DataKeyField] = DataKeysArray[e.Item.ItemIndex]; } else keys = null; ExtractRowValues(newValues, e.Item, true, isAddOperation); } // Handle a reorder event from a server postback. void ProcessReorder(int oldIndex, int newIndex) { try { Debug.Assert(oldIndex >= 0, "Old index for reorder is < 0 (" + oldIndex + ")"); Debug.Assert(oldIndex < Items.Count, "Old index for reorder is > items (" + oldIndex + ")"); Debug.Assert(newIndex >= 0, "New index for reorder is < 0 (" + newIndex + ")"); Debug.Assert(newIndex < Items.Count, "New index for reorder is > items (" + newIndex + ")"); // fire the event. // if((oldIndex != newIndex) && (Math.Max(oldIndex, newIndex) != DataKeysArray.Count)) { Control item = Items[oldIndex]; OnItemReorder(new ReorderListItemReorderEventArgs(item as ReorderListItem, oldIndex, newIndex)); } else { //DataBind(); } } catch(Exception ex) { Debug.Fail(ex.ToString()); //TODO WHY ARE SWALLOWING THIS EXCEPTION!!! } } protected override void RenderContents(HtmlTextWriter writer) { // show the empty item template if necessary. // if(ChildList.Controls.Count == 0) { if(EmptyListTemplate != null) { var p = new Panel(); p.ID = ClientID; EmptyListTemplate.InstantiateIn(p); p.RenderControl(writer); } return; } base.RenderContents(writer); } /// <summary> /// Updates the specified row with its current values /// </summary> /// <param name="rowIndex" type="Int">Row index</param> public void UpdateItem(int rowIndex) { HandleUpdate(null, rowIndex); } #region IRepeatInfoUser Members /// <summary> /// Returns style of the reorder list item /// </summary> /// <param name="itemType" type="ListItemType">Item type</param> /// <param name="repeatIndex" type="Int">Repeat index</param> /// <returns>Item style</returns> public Style GetItemStyle(ListItemType itemType, int repeatIndex) { var item = GetItem(itemType, repeatIndex); return item.ControlStyle; } /// <summary> /// Determines whether or not the list has a footer /// </summary> public bool HasFooter { get { return false; } } /// <summary> /// Determines whether or not the list has a header /// </summary> public bool HasHeader { get { return false; } } /// <summary> /// Determines whether or not the list has separators /// </summary> public bool HasSeparators { get { return false; } } /// <summary> /// Renders an item /// </summary> /// <param name="itemType" type="ListItemType">Item type</param> /// <param name="repeatIndex" type="Int">Repeat index</param> /// <param name="repeatInfo" type="RepeatInfo">Repeat into</param> /// <param name="writer" type="HtmlTextWriter">Writer</param> public void RenderItem(ListItemType itemType, int repeatIndex, RepeatInfo repeatInfo, HtmlTextWriter writer) { var item = GetItem(itemType, repeatIndex); item.RenderControl(writer); } ReorderListItem GetItem(ListItemType itemType, int repeatIndex) { switch(itemType) { case ListItemType.Item: case ListItemType.EditItem: return (ReorderListItem)Controls[repeatIndex]; case ListItemType.Separator: return (ReorderListItem)Controls[repeatIndex * 2]; default: throw new ArgumentException("Unknown value", "itemType"); } } /// <summary> /// Determines the count of repeated items /// </summary> public int RepeatedItemCount { get { if(itemsArray != null) return itemsArray.Count; return 0; } } #endregion // Parse our postback string into the event name, which item it's on, and any arguments static bool ParsePostBack(string eventArgument, out string eventName, out string itemId, out string[] args) { // format is like: // reorder:childItem0:1 // which parses to: // eventName = "reorder" // itemId = "childItem0" // args = new string[]{"1"}; // itemId = null; eventName = null; args = new string[0]; var argParts = eventArgument.Split(':'); if(argParts.Length < 2) return false; eventName = argParts[0]; itemId = argParts[1]; if(argParts.Length > 2) { args = new string[argParts.Length - 2]; Array.Copy(argParts, 2, args, 0, args.Length); } return true; } protected void RaisePostBackEvent(string eventArgument) { string eventName; string itemId; string[] args; if(ParsePostBack(eventArgument, out eventName, out itemId, out args)) { switch(eventName) { case "reorder": ProcessReorder(Int32.Parse(args[0], CultureInfo.InvariantCulture), Int32.Parse(args[1], CultureInfo.InvariantCulture)); break; } } } #region ICallbackEventHandler Members string _callbackResult = String.Empty; string CallbackResult { get { return _callbackResult; } set { _callbackResult = value; } } string ICallbackEventHandler.GetCallbackResult() { return CallbackResult; } void ICallbackEventHandler.RaiseCallbackEvent(string eventArgument) { CallbackResult = string.Empty; RaisePostBackEvent(eventArgument); } #endregion #region IPostBackEventHandler Members void IPostBackEventHandler.RaisePostBackEvent(string eventArgument) { CallbackResult = string.Empty; RaisePostBackEvent(eventArgument); } #endregion protected V GetPropertyValue<V>(string propertyName, V nullValue) { if(ViewState[propertyName] == null) { return nullValue; } return (V)ViewState[propertyName]; } protected void SetPropertyValue<V>(string propertyName, V value) { ViewState[propertyName] = value; } } }
/* * Swagger Petstore * * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: [email protected] * Generated by: https://github.com/swagger-api/swagger-codegen.git * * 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.Linq; using System.IO; using System.Text; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace IO.Swagger.Model { /// <summary> /// FormatTest /// </summary> [DataContract] public partial class FormatTest : IEquatable<FormatTest> { /// <summary> /// Initializes a new instance of the <see cref="FormatTest" /> class. /// </summary> [JsonConstructorAttribute] protected FormatTest() { } /// <summary> /// Initializes a new instance of the <see cref="FormatTest" /> class. /// </summary> /// <param name="Integer">Integer.</param> /// <param name="Int32">Int32.</param> /// <param name="Int64">Int64.</param> /// <param name="Number">Number (required).</param> /// <param name="_Float">_Float.</param> /// <param name="_Double">_Double.</param> /// <param name="_String">_String.</param> /// <param name="_Byte">_Byte (required).</param> /// <param name="Binary">Binary.</param> /// <param name="Date">Date (required).</param> /// <param name="DateTime">DateTime.</param> /// <param name="Uuid">Uuid.</param> /// <param name="Password">Password (required).</param> public FormatTest(int? Integer = null, int? Int32 = null, long? Int64 = null, decimal? Number = null, float? _Float = null, double? _Double = null, string _String = null, byte[] _Byte = null, byte[] Binary = null, DateTime? Date = null, DateTime? DateTime = null, Guid? Uuid = null, string Password = null) { // to ensure "Number" is required (not null) if (Number == null) { throw new InvalidDataException("Number is a required property for FormatTest and cannot be null"); } else { this.Number = Number; } // to ensure "_Byte" is required (not null) if (_Byte == null) { throw new InvalidDataException("_Byte is a required property for FormatTest and cannot be null"); } else { this._Byte = _Byte; } // to ensure "Date" is required (not null) if (Date == null) { throw new InvalidDataException("Date is a required property for FormatTest and cannot be null"); } else { this.Date = Date; } // to ensure "Password" is required (not null) if (Password == null) { throw new InvalidDataException("Password is a required property for FormatTest and cannot be null"); } else { this.Password = Password; } this.Integer = Integer; this.Int32 = Int32; this.Int64 = Int64; this._Float = _Float; this._Double = _Double; this._String = _String; this.Binary = Binary; this.DateTime = DateTime; this.Uuid = Uuid; } /// <summary> /// Gets or Sets Integer /// </summary> [DataMember(Name="integer", EmitDefaultValue=false)] public int? Integer { get; set; } /// <summary> /// Gets or Sets Int32 /// </summary> [DataMember(Name="int32", EmitDefaultValue=false)] public int? Int32 { get; set; } /// <summary> /// Gets or Sets Int64 /// </summary> [DataMember(Name="int64", EmitDefaultValue=false)] public long? Int64 { get; set; } /// <summary> /// Gets or Sets Number /// </summary> [DataMember(Name="number", EmitDefaultValue=false)] public decimal? Number { get; set; } /// <summary> /// Gets or Sets _Float /// </summary> [DataMember(Name="float", EmitDefaultValue=false)] public float? _Float { get; set; } /// <summary> /// Gets or Sets _Double /// </summary> [DataMember(Name="double", EmitDefaultValue=false)] public double? _Double { get; set; } /// <summary> /// Gets or Sets _String /// </summary> [DataMember(Name="string", EmitDefaultValue=false)] public string _String { get; set; } /// <summary> /// Gets or Sets _Byte /// </summary> [DataMember(Name="byte", EmitDefaultValue=false)] public byte[] _Byte { get; set; } /// <summary> /// Gets or Sets Binary /// </summary> [DataMember(Name="binary", EmitDefaultValue=false)] public byte[] Binary { get; set; } /// <summary> /// Gets or Sets Date /// </summary> [DataMember(Name="date", EmitDefaultValue=false)] public DateTime? Date { get; set; } /// <summary> /// Gets or Sets DateTime /// </summary> [DataMember(Name="dateTime", EmitDefaultValue=false)] public DateTime? DateTime { get; set; } /// <summary> /// Gets or Sets Uuid /// </summary> [DataMember(Name="uuid", EmitDefaultValue=false)] public Guid? Uuid { get; set; } /// <summary> /// Gets or Sets Password /// </summary> [DataMember(Name="password", EmitDefaultValue=false)] public string Password { 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 FormatTest {\n"); sb.Append(" Integer: ").Append(Integer).Append("\n"); sb.Append(" Int32: ").Append(Int32).Append("\n"); sb.Append(" Int64: ").Append(Int64).Append("\n"); sb.Append(" Number: ").Append(Number).Append("\n"); sb.Append(" _Float: ").Append(_Float).Append("\n"); sb.Append(" _Double: ").Append(_Double).Append("\n"); sb.Append(" _String: ").Append(_String).Append("\n"); sb.Append(" _Byte: ").Append(_Byte).Append("\n"); sb.Append(" Binary: ").Append(Binary).Append("\n"); sb.Append(" Date: ").Append(Date).Append("\n"); sb.Append(" DateTime: ").Append(DateTime).Append("\n"); sb.Append(" Uuid: ").Append(Uuid).Append("\n"); sb.Append(" Password: ").Append(Password).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 FormatTest); } /// <summary> /// Returns true if FormatTest instances are equal /// </summary> /// <param name="other">Instance of FormatTest to be compared</param> /// <returns>Boolean</returns> public bool Equals(FormatTest other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.Integer == other.Integer || this.Integer != null && this.Integer.Equals(other.Integer) ) && ( this.Int32 == other.Int32 || this.Int32 != null && this.Int32.Equals(other.Int32) ) && ( this.Int64 == other.Int64 || this.Int64 != null && this.Int64.Equals(other.Int64) ) && ( this.Number == other.Number || this.Number != null && this.Number.Equals(other.Number) ) && ( this._Float == other._Float || this._Float != null && this._Float.Equals(other._Float) ) && ( this._Double == other._Double || this._Double != null && this._Double.Equals(other._Double) ) && ( this._String == other._String || this._String != null && this._String.Equals(other._String) ) && ( this._Byte == other._Byte || this._Byte != null && this._Byte.Equals(other._Byte) ) && ( this.Binary == other.Binary || this.Binary != null && this.Binary.Equals(other.Binary) ) && ( this.Date == other.Date || this.Date != null && this.Date.Equals(other.Date) ) && ( this.DateTime == other.DateTime || this.DateTime != null && this.DateTime.Equals(other.DateTime) ) && ( this.Uuid == other.Uuid || this.Uuid != null && this.Uuid.Equals(other.Uuid) ) && ( this.Password == other.Password || this.Password != null && this.Password.Equals(other.Password) ); } /// <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.Integer != null) hash = hash * 59 + this.Integer.GetHashCode(); if (this.Int32 != null) hash = hash * 59 + this.Int32.GetHashCode(); if (this.Int64 != null) hash = hash * 59 + this.Int64.GetHashCode(); if (this.Number != null) hash = hash * 59 + this.Number.GetHashCode(); if (this._Float != null) hash = hash * 59 + this._Float.GetHashCode(); if (this._Double != null) hash = hash * 59 + this._Double.GetHashCode(); if (this._String != null) hash = hash * 59 + this._String.GetHashCode(); if (this._Byte != null) hash = hash * 59 + this._Byte.GetHashCode(); if (this.Binary != null) hash = hash * 59 + this.Binary.GetHashCode(); if (this.Date != null) hash = hash * 59 + this.Date.GetHashCode(); if (this.DateTime != null) hash = hash * 59 + this.DateTime.GetHashCode(); if (this.Uuid != null) hash = hash * 59 + this.Uuid.GetHashCode(); if (this.Password != null) hash = hash * 59 + this.Password.GetHashCode(); return hash; } } } }
// 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.Security; using System; using System.Runtime.InteropServices; // For SafeHanlde [SecurityCritical] public class MySafeValidHandle : SafeHandle { public MySafeValidHandle() : base(IntPtr.Zero, true) { } public MySafeValidHandle(IntPtr handleValue) : base(IntPtr.Zero, true) { handle = handleValue; } public override bool IsInvalid { [SecurityCritical] get { return false; } } [SecurityCritical] protected override bool ReleaseHandle() { return true; } } [SecurityCritical] public class MySafeInValidHandle : SafeHandle { public MySafeInValidHandle() : base(IntPtr.Zero, true) { } public MySafeInValidHandle(IntPtr handleValue) : base(IntPtr.Zero, true) { handle = handleValue; } public override bool IsInvalid { [SecurityCritical] get { return true; } } [SecurityCritical] protected override bool ReleaseHandle() { return true; } } /// <summary> /// Dispose /// </summary> public class SafeHandleDispose1 { #region Public Methods [SecuritySafeCritical] public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; TestLibrary.TestFramework.LogInformation("[Negative]"); retVal = NegTest1() && retVal; return retVal; } #region Positive Test Cases [SecuritySafeCritical] public bool PosTest1() { bool retVal = true; int randValue = 0; TestLibrary.TestFramework.BeginScenario("PosTest1: call Dispose on valid SafeHandle instance"); try { SafeHandle handle = new MySafeValidHandle(); handle.Dispose(); randValue = TestLibrary.Generator.GetInt32(-55); handle = new MySafeValidHandle(new IntPtr(randValue)); handle.Dispose(); } catch (Exception e) { TestLibrary.TestFramework.LogError("001", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation("WARNING: [LOCAL VARIABLES] randValue = " + randValue); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } [SecuritySafeCritical] public bool PosTest2() { bool retVal = true; int randValue = 0; TestLibrary.TestFramework.BeginScenario("PosTest2: call Dispose on an invalid SafeHandle instance"); try { SafeHandle handle = new MySafeInValidHandle(); handle.Dispose(); randValue = TestLibrary.Generator.GetInt32(-55); handle = new MySafeInValidHandle(new IntPtr(randValue)); handle.Dispose(); } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation("WARNING: [LOCAL VARIABLES] randValue = " + randValue); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } [SecuritySafeCritical] public bool PosTest3() { bool retVal = true; int randValue = 0; TestLibrary.TestFramework.BeginScenario("PosTest3: call Dispose through IDispose interface"); try { SafeHandle handle = new MySafeInValidHandle(); IDisposable idisp = handle as IDisposable; idisp.Dispose(); randValue = TestLibrary.Generator.GetInt32(-55); handle = new MySafeInValidHandle(new IntPtr(randValue)); idisp = handle as IDisposable; idisp.Dispose(); handle = new MySafeValidHandle(); idisp = handle as IDisposable; idisp.Dispose(); randValue = TestLibrary.Generator.GetInt32(-55); handle = new MySafeValidHandle(new IntPtr(randValue)); idisp = handle as IDisposable; idisp.Dispose(); } catch (Exception e) { TestLibrary.TestFramework.LogError("003", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation("WARNING: [LOCAL VARIABLES] randValue = " + randValue); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } #endregion #region Nagetive Test Cases [SecuritySafeCritical] public bool NegTest1() { bool retVal = true; int randValue = 0; TestLibrary.TestFramework.BeginScenario("NegTest1: Call Dispose twice"); try { randValue = TestLibrary.Generator.GetInt32(-55); SafeHandle handle = new MySafeValidHandle(new IntPtr(randValue)); handle.Dispose(); handle.Dispose(); } catch (Exception e) { TestLibrary.TestFramework.LogError("101", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation("WARNING: [LOCAL VARIABLES] randValue = " + randValue); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } #endregion #endregion [SecuritySafeCritical] public static int Main() { SafeHandleDispose1 test = new SafeHandleDispose1(); TestLibrary.TestFramework.BeginTestCase("SafeHandleDispose1"); if (test.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. using System; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; using System.Text; using System.Security; using System.Runtime.Versioning; using System.Runtime.ConstrainedExecution; using Microsoft.Win32.SafeHandles; namespace Microsoft.Web.Management.PInvoke.AdvApi32 { [StructLayout(LayoutKind.Sequential, Pack = 1)] internal struct TOKEN_PRIVILEGES { public UInt32 PrivilegeCount; public long Luid; public UInt32 Attributes; } internal enum TOKEN_INFORMATION_CLASS { /// <summary> /// The buffer receives a TOKEN_USER structure that contains the user account of the token. /// </summary> TokenUser = 1, /// <summary> /// The buffer receives a TOKEN_GROUPS structure that contains the group accounts associated with the token. /// </summary> TokenGroups, /// <summary> /// The buffer receives a TOKEN_PRIVILEGES structure that contains the privileges of the token. /// </summary> TokenPrivileges, /// <summary> /// The buffer receives a TOKEN_OWNER structure that contains the default owner security identifier (SID) for newly created objects. /// </summary> TokenOwner, /// <summary> /// The buffer receives a TOKEN_PRIMARY_GROUP structure that contains the default primary group SID for newly created objects. /// </summary> TokenPrimaryGroup, /// <summary> /// The buffer receives a TOKEN_DEFAULT_DACL structure that contains the default DACL for newly created objects. /// </summary> TokenDefaultDacl, /// <summary> /// The buffer receives a TOKEN_SOURCE structure that contains the source of the token. TOKEN_QUERY_SOURCE access is needed to retrieve this information. /// </summary> TokenSource, /// <summary> /// The buffer receives a TOKEN_TYPE value that indicates whether the token is a primary or impersonation token. /// </summary> TokenType, /// <summary> /// The buffer receives a SECURITY_IMPERSONATION_LEVEL value that indicates the impersonation level of the token. If the access token is not an impersonation token, the function fails. /// </summary> TokenImpersonationLevel, /// <summary> /// The buffer receives a TOKEN_STATISTICS structure that contains various token statistics. /// </summary> TokenStatistics, /// <summary> /// The buffer receives a TOKEN_GROUPS structure that contains the list of restricting SIDs in a restricted token. /// </summary> TokenRestrictedSids, /// <summary> /// The buffer receives a DWORD value that indicates the Terminal Services session identifier that is associated with the token. /// </summary> TokenSessionId, /// <summary> /// The buffer receives a TOKEN_GROUPS_AND_PRIVILEGES structure that contains the user SID, the group accounts, the restricted SIDs, and the authentication ID associated with the token. /// </summary> TokenGroupsAndPrivileges, /// <summary> /// Reserved. /// </summary> TokenSessionReference, /// <summary> /// The buffer receives a DWORD value that is nonzero if the token includes the SANDBOX_INERT flag. /// </summary> TokenSandBoxInert, /// <summary> /// Reserved. /// </summary> TokenAuditPolicy, /// <summary> /// The buffer receives a TOKEN_ORIGIN value. /// </summary> TokenOrigin, /// <summary> /// The buffer receives a TOKEN_ELEVATION_TYPE value that specifies the elevation level of the token. /// </summary> TokenElevationType, /// <summary> /// The buffer receives a TOKEN_LINKED_TOKEN structure that contains a handle to another token that is linked to this token. /// </summary> TokenLinkedToken, /// <summary> /// The buffer receives a TOKEN_ELEVATION structure that specifies whether the token is elevated. /// </summary> TokenElevation, /// <summary> /// The buffer receives a DWORD value that is nonzero if the token has ever been filtered. /// </summary> TokenHasRestrictions, /// <summary> /// The buffer receives a TOKEN_ACCESS_INFORMATION structure that specifies security information contained in the token. /// </summary> TokenAccessInformation, /// <summary> /// The buffer receives a DWORD value that is nonzero if virtualization is allowed for the token. /// </summary> TokenVirtualizationAllowed, /// <summary> /// The buffer receives a DWORD value that is nonzero if virtualization is enabled for the token. /// </summary> TokenVirtualizationEnabled, /// <summary> /// The buffer receives a TOKEN_MANDATORY_LABEL structure that specifies the token's integrity level. /// </summary> TokenIntegrityLevel, /// <summary> /// The buffer receives a DWORD value that is nonzero if the token has the UIAccess flag set. /// </summary> TokenUIAccess, /// <summary> /// The buffer receives a TOKEN_MANDATORY_POLICY structure that specifies the token's mandatory integrity policy. /// </summary> TokenMandatoryPolicy, /// <summary> /// The buffer receives the token's logon security identifier (SID). /// </summary> TokenLogonSid, /// <summary> /// The maximum value for this enumeration /// </summary> MaxTokenInfoClass } internal enum TOKEN_ELEVATION_TYPE { TokenElevationTypeDefault = 1, TokenElevationTypeFull, TokenElevationTypeLimited } [Flags] internal enum AccessTokenRights : uint { STANDARD_RIGHTS_REQUIRED = 0x000F0000, STANDARD_RIGHTS_READ = 0x00020000, TOKEN_ASSIGN_PRIMARY = 0x0001, TOKEN_DUPLICATE = 0x0002, TOKEN_IMPERSONATE = 0x0004, TOKEN_QUERY = 0x0008, TOKEN_QUERY_SOURCE = 0x0010, TOKEN_ADJUST_PRIVILEGES = 0x0020, TOKEN_ADJUST_GROUPS = 0x0040, TOKEN_ADJUST_DEFAULT = 0x0080, TOKEN_ADJUST_SESSIONID = 0x0100, TOKEN_READ = STANDARD_RIGHTS_READ | TOKEN_QUERY, TOKEN_ALL_ACCESS = STANDARD_RIGHTS_REQUIRED | TOKEN_ASSIGN_PRIMARY | TOKEN_DUPLICATE | TOKEN_IMPERSONATE | TOKEN_QUERY | TOKEN_QUERY_SOURCE | TOKEN_ADJUST_PRIVILEGES | TOKEN_ADJUST_GROUPS | TOKEN_ADJUST_DEFAULT | TOKEN_ADJUST_SESSIONID } internal static class NativeMethods { private const String ADVAPI32 = "advapi32.dll"; // TODO: Should be moved into enums? internal const int READ_CONTROL = 0x00020000; internal const int SYNCHRONIZE = 0x00100000; internal const int STANDARD_RIGHTS_READ = READ_CONTROL; internal const int STANDARD_RIGHTS_WRITE = READ_CONTROL; internal const int KEY_QUERY_VALUE = 0x0001; internal const int KEY_SET_VALUE = 0x0002; internal const int KEY_CREATE_SUB_KEY = 0x0004; internal const int KEY_ENUMERATE_SUB_KEYS = 0x0008; internal const int KEY_NOTIFY = 0x0010; internal const int KEY_READ = ((STANDARD_RIGHTS_READ | KEY_QUERY_VALUE | KEY_ENUMERATE_SUB_KEYS | KEY_NOTIFY) & (~SYNCHRONIZE)); internal const int KEY_WRITE = ((STANDARD_RIGHTS_WRITE | KEY_SET_VALUE | KEY_CREATE_SUB_KEY) & (~SYNCHRONIZE)); internal const int KEY_WOW64_64KEY = 0x0100; internal const int KEY_WOW64_32KEY = 0x0200; internal const int ERROR_MORE_DATA = 0xEA; internal const int ERROR_ACCESS_DENIED = 0x5; internal const int REG_OPTION_NON_VOLATILE = 0x0000; // (default) keys are persisted beyond reboot/unload internal const int REG_OPTION_VOLATILE = 0x0001; // All keys created by the function are volatile internal const int REG_OPTION_CREATE_LINK = 0x0002; // They key is a symbolic link internal const int REG_OPTION_BACKUP_RESTORE = 0x0004; // Use SE_BACKUP_NAME process special privileges internal const int REG_NONE = 0; // No value type internal const int REG_SZ = 1; // Unicode nul terminated string internal const int REG_EXPAND_SZ = 2; // Unicode nul terminated string internal const int REG_BINARY = 3; // Free form binary internal const int REG_DWORD = 4; // 32-bit number internal const int REG_DWORD_LITTLE_ENDIAN = 4; // 32-bit number (same as REG_DWORD) internal const int REG_DWORD_BIG_ENDIAN = 5; // 32-bit number internal const int REG_LINK = 6; // Symbolic Link (unicode) internal const int REG_MULTI_SZ = 7; // Multiple Unicode strings internal const int REG_RESOURCE_LIST = 8; // Resource list in the resource map internal const int REG_FULL_RESOURCE_DESCRIPTOR = 9; // Resource list in the hardware description internal const int REG_RESOURCE_REQUIREMENTS_LIST = 10; internal const int REG_QWORD = 11; // 64-bit number [DllImport("advapi32.dll", ExactSpelling = true, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool AdjustTokenPrivileges( SafeHandleZeroIsInvalid TokenHandle, [MarshalAs(UnmanagedType.Bool)] bool DisableAllPrivileges, ref TOKEN_PRIVILEGES NewState, int len, IntPtr prev, IntPtr relen); [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool LookupPrivilegeValue(string host, string name, ref long pluid); [DllImport("advapi32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool GetTokenInformation( SafeHandleZeroIsInvalid TokenHandle, TOKEN_INFORMATION_CLASS TokenInformationClass, HGlobalBuffer TokenInformation, int TokenInformationLength, out int ReturnLength); [DllImport("advapi32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool OpenProcessToken( SafeHandleZeroIsInvalid ProcessHandle, AccessTokenRights DesiredAccess, out SafeHandleZeroIsInvalid TokenHandle); [DllImport("ADVAPI32.DLL"), SuppressUnmanagedCodeSecurity, ResourceExposure(ResourceScope.None), ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] internal static extern int RegCloseKey(IntPtr hKey); [DllImport(ADVAPI32, CharSet = CharSet.Auto, BestFitMapping = false)] internal static extern int RegOpenKeyEx(SafeRegistryHandle hKey, String lpSubKey, int ulOptions, int samDesired, out SafeRegistryHandle hkResult); [DllImport(ADVAPI32, CharSet = CharSet.Auto, BestFitMapping = false)] internal static extern int RegQueryValueEx(SafeRegistryHandle hKey, String lpValueName, int[] lpReserved, ref int lpType, [Out] byte[] lpData, ref int lpcbData); [DllImport(ADVAPI32, CharSet = CharSet.Auto, BestFitMapping = false)] internal static extern int RegQueryValueEx(SafeRegistryHandle hKey, String lpValueName, int[] lpReserved, ref int lpType, ref int lpData, ref int lpcbData); [DllImport(ADVAPI32, CharSet = CharSet.Auto, BestFitMapping = false)] internal static extern int RegQueryValueEx(SafeRegistryHandle hKey, String lpValueName, int[] lpReserved, ref int lpType, ref long lpData, ref int lpcbData); [DllImport(ADVAPI32, CharSet = CharSet.Auto, BestFitMapping = false)] internal static extern int RegQueryValueEx(SafeRegistryHandle hKey, String lpValueName, int[] lpReserved, ref int lpType, [Out] char[] lpData, ref int lpcbData); [DllImport(ADVAPI32, CharSet = CharSet.Auto, BestFitMapping = false)] internal static extern int RegQueryValueEx(SafeRegistryHandle hKey, String lpValueName, int[] lpReserved, ref int lpType, StringBuilder lpData, ref int lpcbData); public static void EnableShutdownPrivilege() { const int SE_PRIVILEGE_ENABLED = 0x00000002; const string SE_SHUTDOWN_NAME = "SeShutdownPrivilege"; bool retVal; using (SafeHandleZeroIsInvalid hproc = Kernel32.NativeMethods.GetCurrentProcess()) { TOKEN_PRIVILEGES tp; SafeHandleZeroIsInvalid htok; retVal = OpenProcessToken(hproc, AccessTokenRights.TOKEN_ADJUST_PRIVILEGES | AccessTokenRights.TOKEN_QUERY, out htok); if (!retVal) { throw new Win32Exception(Marshal.GetLastWin32Error()); } using (htok) { tp.PrivilegeCount = 1; tp.Luid = 0; tp.Attributes = SE_PRIVILEGE_ENABLED; retVal = LookupPrivilegeValue(null, SE_SHUTDOWN_NAME, ref tp.Luid); if (!retVal) { throw new Win32Exception(Marshal.GetLastWin32Error()); } retVal = AdjustTokenPrivileges(htok, false, ref tp, 0, IntPtr.Zero, IntPtr.Zero); if (!retVal) { throw new Win32Exception(Marshal.GetLastWin32Error()); } } } } } [SecurityCritical] internal sealed class SafeRegistryHandle : SafeHandleZeroOrMinusOneIsInvalid { [SecurityCritical] internal SafeRegistryHandle() : base(true) { } [SecurityCritical] public SafeRegistryHandle(IntPtr preexistingHandle, bool ownsHandle) : base(ownsHandle) { SetHandle(preexistingHandle); } [SecurityCritical] override protected bool ReleaseHandle() { return (Microsoft.Web.Management.PInvoke.AdvApi32.NativeMethods.RegCloseKey(handle) == 0); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; namespace Internal.TypeSystem { public class InstantiationContext { public readonly Instantiation TypeInstantiation; public readonly Instantiation MethodInstantiation; public InstantiationContext(Instantiation typeInstantiation, Instantiation methodInstantiation) { TypeInstantiation = typeInstantiation; MethodInstantiation = methodInstantiation; } } public static class TypeSystemConstraintsHelpers { private static bool VerifyGenericParamConstraint(InstantiationContext genericParamContext, GenericParameterDesc genericParam, InstantiationContext instantiationParamContext, TypeDesc instantiationParam) { GenericConstraints constraints = genericParam.Constraints; // Check class constraint if ((constraints & GenericConstraints.ReferenceTypeConstraint) != 0) { if (!instantiationParam.IsGCPointer && !CheckGenericSpecialConstraint(instantiationParam, GenericConstraints.ReferenceTypeConstraint)) return false; } // Check default constructor constraint if ((constraints & GenericConstraints.DefaultConstructorConstraint) != 0) { if (!instantiationParam.HasExplicitOrImplicitDefaultConstructor() && !CheckGenericSpecialConstraint(instantiationParam, GenericConstraints.DefaultConstructorConstraint)) return false; } // Check struct constraint if ((constraints & GenericConstraints.NotNullableValueTypeConstraint) != 0) { if ((!instantiationParam.IsValueType || instantiationParam.IsNullable) && !CheckGenericSpecialConstraint(instantiationParam, GenericConstraints.NotNullableValueTypeConstraint)) return false; } var instantiatedConstraints = new ArrayBuilder<TypeDesc>(); GetInstantiatedConstraintsRecursive(instantiationParamContext, instantiationParam, ref instantiatedConstraints); foreach (var constraintType in genericParam.TypeConstraints) { var instantiatedType = constraintType.InstantiateSignature(genericParamContext.TypeInstantiation, genericParamContext.MethodInstantiation); if (CanCastConstraint(ref instantiatedConstraints, instantiatedType)) continue; if (!instantiationParam.CanCastTo(instantiatedType)) return false; } return true; } // Used to determine whether a type parameter used to instantiate another type parameter with a specific special // constraint satisfies that constraint. private static bool CheckGenericSpecialConstraint(TypeDesc type, GenericConstraints specialConstraint) { if (!type.IsGenericParameter) return false; var genericType = (GenericParameterDesc)type; GenericConstraints constraints = genericType.Constraints; // Check if type has specialConstraint on its own if ((constraints & specialConstraint) != 0) return true; // Value type always has default constructor if (specialConstraint == GenericConstraints.DefaultConstructorConstraint && (constraints & GenericConstraints.NotNullableValueTypeConstraint) != 0) return true; // The special constraints did not match, check if there is a primary type constraint, // that would always satisfy the special constraint foreach (var constraint in genericType.TypeConstraints) { if (constraint.IsGenericParameter || constraint.IsInterface) continue; switch (specialConstraint) { case GenericConstraints.NotNullableValueTypeConstraint: if (constraint.IsValueType && !constraint.IsNullable) return true; break; case GenericConstraints.ReferenceTypeConstraint: if (!constraint.IsValueType) return true; break; case GenericConstraints.DefaultConstructorConstraint: // As constraint is only ancestor, can only be sure whether type has public default constructor if it is a value type if (constraint.IsValueType) return true; break; default: Debug.Assert(false); break; } } // type did not satisfy special constraint in any way return false; } private static void GetInstantiatedConstraintsRecursive(InstantiationContext typeContext, TypeDesc type, ref ArrayBuilder<TypeDesc> instantiatedConstraints) { if (!type.IsGenericParameter || typeContext == null) return; GenericParameterDesc genericParam = (GenericParameterDesc)type; foreach (var constraint in genericParam.TypeConstraints) { var instantiatedType = constraint.InstantiateSignature(typeContext.TypeInstantiation, typeContext.MethodInstantiation); if (instantiatedType.IsGenericParameter) { // Make sure it is save to call this method recursively if (!instantiatedConstraints.Contains(instantiatedType)) { instantiatedConstraints.Add(instantiatedType); // Constraints of this constraint apply to 'genericParam' too GetInstantiatedConstraintsRecursive(typeContext, instantiatedType, ref instantiatedConstraints); } } else { instantiatedConstraints.Add(instantiatedType); } } } private static bool CanCastConstraint(ref ArrayBuilder<TypeDesc> instantiatedConstraints, TypeDesc instantiatedType) { for (int i = 0; i < instantiatedConstraints.Count; ++i) { if (instantiatedConstraints[i].CanCastTo(instantiatedType)) return true; } return false; } public static bool CheckValidInstantiationArguments(this Instantiation instantiation) { foreach(var arg in instantiation) { if (arg.IsPointer || arg.IsByRef || arg.IsGenericParameter || arg.IsVoid) return false; if (arg.HasInstantiation) { if (!CheckValidInstantiationArguments(arg.Instantiation)) return false; } } return true; } public static bool CheckConstraints(this TypeDesc type, InstantiationContext context = null) { TypeDesc uninstantiatedType = type.GetTypeDefinition(); // Non-generic types always pass constraints check if (uninstantiatedType == type) return true; var paramContext = new InstantiationContext(type.Instantiation, default(Instantiation)); for (int i = 0; i < uninstantiatedType.Instantiation.Length; i++) { if (!VerifyGenericParamConstraint(paramContext, (GenericParameterDesc)uninstantiatedType.Instantiation[i], context, type.Instantiation[i])) return false; } return true; } public static bool CheckConstraints(this MethodDesc method, InstantiationContext context = null) { if (!method.OwningType.CheckConstraints(context)) return false; // Non-generic methods always pass constraints check if (!method.HasInstantiation) return true; var paramContext = new InstantiationContext(method.OwningType.Instantiation, method.Instantiation); MethodDesc uninstantiatedMethod = method.GetMethodDefinition(); for (int i = 0; i < uninstantiatedMethod.Instantiation.Length; i++) { if (!VerifyGenericParamConstraint(paramContext, (GenericParameterDesc)uninstantiatedMethod.Instantiation[i], context, method.Instantiation[i])) return false; } return true; } } }
// Project: Loading Screen for Daggerfall Unity // Web Site: http://forums.dfworkshop.net/viewtopic.php?f=14&t=469 // License: MIT License (http://www.opensource.org/licenses/mit-license.php) // Source Code: https://github.com/TheLacus/loadingscreen-du-mod // Original Author: TheLacus ([email protected]) // Contributors: using System.IO; using System.Collections.Generic; using UnityEngine; using FullSerializer; using DaggerfallWorkshop.Game; using DaggerfallWorkshop.Game.Entity; using DaggerfallWorkshop.Game.Serialization; using DaggerfallWorkshop.Game.Utility.ModSupport; using DaggerfallWorkshop.Game.UserInterfaceWindows; /* * TODO: * - Improve GenderTip(). * - Seek informations from quests. */ namespace LoadingScreen.Components { /// <summary> /// Provide a string to be shown on the loading screen, /// taking in consideration informations obtained from the save game /// with the purpose of providing useful tips. /// </summary> public class DfTips : LoadingScreenComponent { #region Tips Definition #pragma warning disable 0649 class DaggerfallTips { public List<string> generic; public Location location; public Career career; public Character character; public Progress progress; public List<string> death; } class Location { public List<string> exterior, dungeon; } class Career { public List<string> LOWHEALT, LOWGOLD, HIGHGOLD, LOWLEVEL; public string HIGHLEVEL; public List<string> WAGON; } class Character { public Dictionary<string, List<string>> race; } class Progress { public List<string> basic, advanced; } #pragma warning restore 0649 #endregion #region Fields /// <summary> /// All tips from language-specific file. /// </summary> DaggerfallTips tips; /// <summary> /// Fallback tip. /// </summary> const string fallbackTip = "Something wrong with your tips file..."; /// <summary> /// Fallback tip. /// </summary> readonly List<string> fallbackTips = new List<string>() { fallbackTip }; // UI fields string tip = string.Empty; #endregion #region Public Methods /// <summary> /// Constructor for Daggerfall Tips. /// </summary> public DfTips(Rect rect) :base(rect, 9) { this.style.wordWrap = true; ParseTips(); } public override void Draw() { GUI.Label(rect, tip, style); } public override void OnLoadingScreen(SaveData_v1 saveData) { tip = GetTip(saveData); } public override void OnLoadingScreen(DaggerfallTravelPopUp sender) { tip = GetTip(sender); } public override void OnLoadingScreen(PlayerEnterExit.TransitionEventArgs args) { tip = GetTip(args.TransitionType); } public override void OnDeathScreen() { tip = GetTip(); } #endregion #region Algorithm /// <summary> /// Get a tip to show on screen for save loading. /// </summary> /// <param name="saveData">Save being loaded.</param> /// <returns>Tip</returns> private string GetTip(SaveData_v1 saveData) { SetSeed(); switch (Random.Range(0, 6)) { case 0: // Save specific return RandomTip(SaveTips(saveData)); case 1: case 2: // Scaled on level int playerLevel = saveData.playerData.playerEntity.level; return RandomTip(ScaledTips(playerLevel)); case 3: case 4: // Location return RandomTip(LocationTips(saveData.playerData.playerPosition.insideDungeon)); default: // Generic tips return RandomTip(tips.generic); } } /// <summary> /// Gets a tip to show on screen for fast travel. /// </summary> /// <param name="sender">Travel popup.</param> /// <returns>Tip</returns> private string GetTip(DaggerfallTravelPopUp sender) { SetSeed(); switch (Random.Range(0, 5)) { case 0: case 1: // Scaled on level int playerLevel = GameManager.Instance.PlayerEntity.Level; return RandomTip(ScaledTips(playerLevel)); case 2: case 3: // Location return RandomTip(LocationTips(false)); default: // Generic tips return RandomTip(tips.generic); } } /// <summary> /// Get a tip to show on screen for entering/exiting. /// </summary> /// <param name="transitionType">Transition in action.</param> /// <returns>Tip</returns> private string GetTip(PlayerEnterExit.TransitionType transitionType) { SetSeed(); const int maxValue = 5; switch (Random.Range(0, maxValue)) { case 0: // Generic tips return RandomTip(tips.generic); case 1: // Based on player informations return RandomTip(PlayerTips()); case 2: // Scaled on level int playerLevel = GameManager.Instance.PlayerEntity.Level; return RandomTip(ScaledTips(playerLevel)); default: // Location bool inDungeon = (transitionType == PlayerEnterExit.TransitionType.ToDungeonInterior); return RandomTip(LocationTips(inDungeon)); } } /// <summary> /// Get a tip to show on screen for Death Screen. /// </summary> /// <returns>Tip</returns> private string GetTip() { SetSeed(); switch (Random.Range(0, 6)) { case 0: // Generic tips return RandomTip(tips.generic); case 1: case 2: // Location bool inDungeon = GameManager.Instance.IsPlayerInsideDungeon; return RandomTip(LocationTips(inDungeon)); default: // Death return RandomTip(tips.death); } } #endregion #region Algorithm Methods /// <summary> /// Get tip specific to location /// </summary> /// <param name="inDungeon">Dungeon or exteriors?</param> /// <returns>List of tips</returns> private List<string> LocationTips(bool inDungeon) { const int maxValue = 6; // the higher, the more probable it will be specific Location l = tips.location; switch (Random.Range(0, maxValue)) { case 0: return l.dungeon; case 1: return l.exterior; default: return inDungeon ? l.dungeon : l.exterior; } } /// <summary> /// Get tips seeking information from the savegame. /// </summary> /// <param name="saveData">Save.</param> private List<string> SaveTips(SaveData_v1 saveData) { // Variables var tips = new List<string>(); PlayerEntityData_v1 data = saveData.playerData.playerEntity; // Race tips.AddRange(RaceTip((Races)data.raceTemplate.ID)); // Others HealthTips(tips, data.currentHealth, data.maxHealth); GoldTips(tips, data.goldPieces); LevelTips(tips, data.level, data.name); WagonTips(tips, data.wagonItems.Length); return tips; } /// <summary> /// Get tips seeking information from PlayerEntity. /// </summary> private List<string> PlayerTips() { // Variables var tips = new List<string>(); PlayerEntity player = GameManager.Instance.PlayerEntity; // Race tips.AddRange(RaceTip((Races)player.RaceTemplate.ID)); // Others HealthTips(tips, player.CurrentHealth, player.MaxHealth); GoldTips(tips, player.GoldPieces); LevelTips(tips, player.Level, player.Name); WagonTips(tips, player.WagonItems.Count); return tips; } /// <summary> /// Race-specific tips /// </summary> /// <param name="race">Race of player charachter.</param> /// <returns>Tips for race</returns> private List<string> RaceTip(Races race) { List<string> raceTips; if (tips.character.race.TryGetValue(race.ToString(), out raceTips)) return raceTips; Debug.LogErrorFormat("Failed to get tip for race {0}", race.ToString()); if (race != Races.None) return RaceTip(Races.None); return fallbackTips; } private void HealthTips(List<string> list, int current, int max) { if (current < (max / 4)) list.AddRange(tips.career.LOWHEALT); } private void GoldTips(List<string> list, int gold) { const int lowGold = 2000, highGold = 5000; if (gold < lowGold) list.AddRange(tips.career.LOWGOLD); else if (gold > highGold) list.AddRange(tips.career.HIGHGOLD); } private void LevelTips(List<string> list, int level, string name) { const int lowLevel = 11, highLevel = 29; if (level < lowLevel) list.AddRange(tips.career.LOWLEVEL); else if (level > highLevel) list.Add(string.Format(tips.career.HIGHLEVEL, name)); } private void WagonTips(List<string> list, int items) { if (items == 0) list.AddRange(tips.career.WAGON); } /// <summary> /// Choose tips according to player level. /// </summary> /// <param name="playerLevel">Level of player in game.</param> /// <returns>List of tips</returns> private List<string> ScaledTips(int playerLevel) { return Random.Range(0, 33) > playerLevel ? tips.progress.basic : tips.progress.advanced; } #endregion #region Helpers /// <summary> /// Loads and parses tips from resources. /// </summary> private void ParseTips() { var textAsset = LoadingScreen.Mod.GetAsset<TextAsset>("Tips"); fsData data = fsJsonParser.Parse(textAsset.text); var result = ModManager._serializer.TryDeserialize(data, ref tips); if (result.HasWarnings) Debug.LogFormat("{0}: {1}", LoadingScreen.Mod.Title, result.FormattedMessages); } /// <summary> /// Init seed for random methods. /// </summary> private static void SetSeed() { Random.InitState(System.Environment.TickCount); } /// <summary> /// Get one tip from a list. /// </summary> /// <param name="tips">List of tips.</param> /// <returns>One tip.</returns> private static string RandomTip(List<string> tips) { try { int index = Random.Range(0, tips.Count); return tips[index]; } catch (System.Exception e) { Debug.LogError("LoadingScreen: Failed to get a tip string\n" + e.ToString()); return string.Format("{0}({1})", fallbackTip, e.Message); } } #endregion } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.WindowsAzure.Management.VirtualNetworks; using Microsoft.WindowsAzure.Management.VirtualNetworks.Models; namespace Microsoft.WindowsAzure.Management.VirtualNetworks { public static partial class ClientRootCertificateOperationsExtensions { /// <summary> /// The Upload Client Root Certificate operation is used to upload a /// new client root certificate to Windows Azure. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/dn205129.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.VirtualNetworks.IClientRootCertificateOperations. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network for this gateway. /// </param> /// <param name='parameters'> /// Parameters supplied to the Upload client certificate Virtual /// Network Gateway operation. /// </param> /// <returns> /// A standard storage response including an HTTP status code and /// request ID. /// </returns> public static GatewayOperationResponse Create(this IClientRootCertificateOperations operations, string virtualNetworkName, ClientRootCertificateCreateParameters parameters) { try { return operations.CreateAsync(virtualNetworkName, parameters).Result; } catch (AggregateException ex) { if (ex.InnerExceptions.Count > 1) { throw; } else { throw ex.InnerException; } } } /// <summary> /// The Upload Client Root Certificate operation is used to upload a /// new client root certificate to Windows Azure. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/dn205129.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.VirtualNetworks.IClientRootCertificateOperations. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network for this gateway. /// </param> /// <param name='parameters'> /// Parameters supplied to the Upload client certificate Virtual /// Network Gateway operation. /// </param> /// <returns> /// A standard storage response including an HTTP status code and /// request ID. /// </returns> public static Task<GatewayOperationResponse> CreateAsync(this IClientRootCertificateOperations operations, string virtualNetworkName, ClientRootCertificateCreateParameters parameters) { return operations.CreateAsync(virtualNetworkName, parameters, CancellationToken.None); } /// <summary> /// The Delete Client Root Certificate operation deletes a previously /// uploaded client root certificate. from Windows Azure (see /// http://msdn.microsoft.com/en-us/library/windowsazure/dn205128.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.VirtualNetworks.IClientRootCertificateOperations. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network for this gateway. /// </param> /// <param name='certificateThumbprint'> /// The X509 certificate thumbprint. /// </param> /// <returns> /// A standard storage response including an HTTP status code and /// request ID. /// </returns> public static GatewayOperationResponse Delete(this IClientRootCertificateOperations operations, string virtualNetworkName, string certificateThumbprint) { try { return operations.DeleteAsync(virtualNetworkName, certificateThumbprint).Result; } catch (AggregateException ex) { if (ex.InnerExceptions.Count > 1) { throw; } else { throw ex.InnerException; } } } /// <summary> /// The Delete Client Root Certificate operation deletes a previously /// uploaded client root certificate. from Windows Azure (see /// http://msdn.microsoft.com/en-us/library/windowsazure/dn205128.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.VirtualNetworks.IClientRootCertificateOperations. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network for this gateway. /// </param> /// <param name='certificateThumbprint'> /// The X509 certificate thumbprint. /// </param> /// <returns> /// A standard storage response including an HTTP status code and /// request ID. /// </returns> public static Task<GatewayOperationResponse> DeleteAsync(this IClientRootCertificateOperations operations, string virtualNetworkName, string certificateThumbprint) { return operations.DeleteAsync(virtualNetworkName, certificateThumbprint, CancellationToken.None); } /// <summary> /// The Get Client Root Certificate operation returns the public /// portion of a previously uploaded client root certificate in a /// base-64 encoded format from Windows Azure. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/dn205127.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.VirtualNetworks.IClientRootCertificateOperations. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network for this gateway. /// </param> /// <param name='certificateThumbprint'> /// The X509 certificate thumbprint. /// </param> /// <returns> /// A standard storage response including an HTTP status code and /// request ID. /// </returns> public static ClientRootCertificateGetResponse Get(this IClientRootCertificateOperations operations, string virtualNetworkName, string certificateThumbprint) { try { return operations.GetAsync(virtualNetworkName, certificateThumbprint).Result; } catch (AggregateException ex) { if (ex.InnerExceptions.Count > 1) { throw; } else { throw ex.InnerException; } } } /// <summary> /// The Get Client Root Certificate operation returns the public /// portion of a previously uploaded client root certificate in a /// base-64 encoded format from Windows Azure. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/dn205127.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.VirtualNetworks.IClientRootCertificateOperations. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network for this gateway. /// </param> /// <param name='certificateThumbprint'> /// The X509 certificate thumbprint. /// </param> /// <returns> /// A standard storage response including an HTTP status code and /// request ID. /// </returns> public static Task<ClientRootCertificateGetResponse> GetAsync(this IClientRootCertificateOperations operations, string virtualNetworkName, string certificateThumbprint) { return operations.GetAsync(virtualNetworkName, certificateThumbprint, CancellationToken.None); } /// <summary> /// The List Client Root Certificates operation returns a list of all /// the client root certificates that are associated with the /// specified virtual network in Windows Azure. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/dn205130.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.VirtualNetworks.IClientRootCertificateOperations. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network for this gateway. /// </param> /// <returns> /// The response to the list client root certificates request. /// </returns> public static ClientRootCertificateListResponse List(this IClientRootCertificateOperations operations, string virtualNetworkName) { try { return operations.ListAsync(virtualNetworkName).Result; } catch (AggregateException ex) { if (ex.InnerExceptions.Count > 1) { throw; } else { throw ex.InnerException; } } } /// <summary> /// The List Client Root Certificates operation returns a list of all /// the client root certificates that are associated with the /// specified virtual network in Windows Azure. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/dn205130.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.VirtualNetworks.IClientRootCertificateOperations. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network for this gateway. /// </param> /// <returns> /// The response to the list client root certificates request. /// </returns> public static Task<ClientRootCertificateListResponse> ListAsync(this IClientRootCertificateOperations operations, string virtualNetworkName) { return operations.ListAsync(virtualNetworkName, CancellationToken.None); } } }
using System; using System.Diagnostics; using Microsoft.Xna.Framework; namespace CocosSharp { public class CCSpriteBatchNode : CCNode, ICCTexture { const int defaultSpriteBatchCapacity = 29; #region Properties public CCTextureAtlas TextureAtlas { get ; private set; } public CCRawList<CCSprite> Descendants { get; private set; } public CCBlendFunc BlendFunc { get; set; } public bool IsAntialiased { get { return Texture.IsAntialiased; } set { Texture.IsAntialiased = value; } } public virtual CCTexture2D Texture { get { return TextureAtlas.Texture; } set { TextureAtlas.Texture = value; UpdateBlendFunc(); } } // // Size of batch node in world space makes no sense // public override CCSize ContentSize // { // get { return CCSize.Zero; } // set // { // } // } // // public override CCAffineTransform AffineLocalTransform // { // get { return CCAffineTransform.Identity; } // } // // protected internal override Matrix XnaLocalMatrix // { // get { return Matrix.Identity; } // protected set // { // } // } // #endregion Properties #region Constructors // We need this constructor for all the subclasses that initialise by directly calling InitCCSpriteBatchNode public CCSpriteBatchNode() { } public CCSpriteBatchNode(CCTexture2D tex, int capacity=defaultSpriteBatchCapacity) { InitCCSpriteBatchNode(tex, capacity); } public CCSpriteBatchNode(string fileImage, int capacity=defaultSpriteBatchCapacity) : this(CCTextureCache.SharedTextureCache.AddImage(fileImage), capacity) { } protected void InitCCSpriteBatchNode(CCTexture2D tex, int capacity=defaultSpriteBatchCapacity) { BlendFunc = CCBlendFunc.AlphaBlend; if (capacity == 0) { capacity = defaultSpriteBatchCapacity; } TextureAtlas = new CCTextureAtlas(tex, capacity); UpdateBlendFunc(); // no lazy alloc in this node Children = new CCRawList<CCNode>(capacity); Descendants = new CCRawList<CCSprite>(capacity); } #endregion Constructors protected override void AddedToScene () { base.AddedToScene (); if(ContentSize == CCSize.Zero) ContentSize = Layer.VisibleBoundsWorldspace.Size; } public override void Visit() { // CAREFUL: // This visit is almost identical to CocosNode#visit // with the exception that it doesn't call visit on it's children // // The alternative is to have a void CCSprite#visit, but // although this is less mantainable, is faster // if (!Visible) { return; } Window.DrawManager.PushMatrix(); if (Grid != null && Grid.Active) { Grid.BeforeDraw(); TransformAncestors(); } SortAllChildren(); CCDrawManager.SharedDrawManager.SetIdentityMatrix(); Draw(); if (Grid != null && Grid.Active) { Grid.AfterDraw(this); } Window.DrawManager.PopMatrix(); } protected override void Draw() { // Optimization: Fast Dispatch if (TextureAtlas.TotalQuads == 0) { return; } Window.DrawManager.BlendFunc(BlendFunc); TextureAtlas.DrawQuads(); } #region Child management public override void AddChild(CCNode child, int zOrder = 0, int tag = CCNode.TagInvalid) { Debug.Assert(child != null, "child should not be null"); Debug.Assert(child is CCSprite, "CCSpriteBatchNode only supports CCSprites as children"); var pSprite = (CCSprite) child; // check CCSprite is using the same texture id Debug.Assert(pSprite.Texture.Name == TextureAtlas.Texture.Name, "CCSprite is not using the same texture id"); base.AddChild(child, zOrder, tag); AppendChild(pSprite); } public override void ReorderChild(CCNode child, int zOrder) { Debug.Assert(child != null, "the child should not be null"); Debug.Assert(Children.Contains(child), "Child doesn't belong to Sprite"); if (zOrder == child.ZOrder) { return; } //set the z-order and sort later base.ReorderChild(child, zOrder); } public override void RemoveChild(CCNode child, bool cleanup) { var pSprite = (CCSprite) child; Debug.Assert(Children.Contains(pSprite), "sprite batch node should contain the child"); // cleanup before removing RemoveSpriteFromAtlas(pSprite); base.RemoveChild(pSprite, cleanup); } public void RemoveChildAtIndex(int index, bool doCleanup) { RemoveChild((Children[index]), doCleanup); } public override void RemoveAllChildren(bool cleanup) { // Invalidate atlas index. issue #569 // useSelfRender should be performed on all descendants. issue #1216 CCSprite[] elements = Descendants.Elements; for (int i = 0, count = Descendants.Count; i < count; i++) { elements[i].BatchNode = null; } base.RemoveAllChildren(cleanup); Descendants.Clear(); TextureAtlas.RemoveAllQuads(); } public override void SortAllChildren() { if (IsReorderChildDirty) { int count = Children.Count; CCNode[] elements = Children.Elements; Array.Sort(elements, 0, count, this); //sorted now check all children if (count > 0) { //first sort all children recursively based on zOrder for (int i = 0; i < count; i++) { elements[i].SortAllChildren(); } int index = 0; //fast dispatch, give every child a new atlasIndex based on their relative zOrder (keep parent -> child relations intact) // and at the same time reorder descedants and the quads to the right index for (int i = 0; i < count; i++) { UpdateAtlasIndex((CCSprite) elements[i], ref index); } } IsReorderChildDirty = false; } } public void InsertChild(CCSprite sprite, int uIndex) { if (TextureAtlas.TotalQuads == TextureAtlas.Capacity) { IncreaseAtlasCapacity(); } TextureAtlas.InsertQuad(ref sprite.transformedQuad, uIndex); sprite.BatchNode = this; sprite.AtlasIndex = uIndex; Descendants.Insert(uIndex, sprite); // update indices CCSprite[] delements = Descendants.Elements; for (int i = uIndex + 1, count = Descendants.Count; i < count; i++) { delements[i].AtlasIndex++; } // add children recursively CCRawList<CCNode> children = sprite.Children; if (children != null && children.Count > 0) { CCNode[] elements = children.Elements; for (int j = 0, count = children.Count; j < count; j++) { var child = (CCSprite) elements[j]; uIndex = AtlasIndexForChild(child, child.ZOrder); InsertChild(child, uIndex); } } } // addChild helper, faster than insertChild public void AppendChild(CCSprite sprite) { IsReorderChildDirty = true; if (TextureAtlas.TotalQuads == TextureAtlas.Capacity) { IncreaseAtlasCapacity(); } Descendants.Add(sprite); int index = Descendants.Count - 1; sprite.AtlasIndex = index; sprite.BatchNode = this; TextureAtlas.UpdateQuad(ref sprite.transformedQuad, index); // add children recursively CCRawList<CCNode> children = sprite.Children; if (children != null && children.Count > 0) { CCNode[] elements = children.Elements; int count = children.Count; for (int i = 0; i < count; i++) { AppendChild((CCSprite) elements[i]); } } } #endregion Child management void UpdateAtlasIndex(CCSprite sprite, ref int curIndex) { int count = 0; CCRawList<CCNode> pArray = sprite.Children; if (pArray != null) { count = pArray.Count; } int oldIndex = 0; if (count == 0) { oldIndex = sprite.AtlasIndex; sprite.AtlasIndex = curIndex; sprite.OrderOfArrival = 0; if (oldIndex != curIndex) { Swap(oldIndex, curIndex); } curIndex++; } else { bool needNewIndex = true; if (pArray.Elements[0].ZOrder >= 0) { //all children are in front of the parent oldIndex = sprite.AtlasIndex; sprite.AtlasIndex = curIndex; sprite.OrderOfArrival = 0; if (oldIndex != curIndex) { Swap(oldIndex, curIndex); } curIndex++; needNewIndex = false; } for (int i = 0; i < count; i++) { var child = (CCSprite) pArray.Elements[i]; if (needNewIndex && child.ZOrder >= 0) { oldIndex = sprite.AtlasIndex; sprite.AtlasIndex = curIndex; sprite.OrderOfArrival = 0; if (oldIndex != curIndex) { Swap(oldIndex, curIndex); } curIndex++; needNewIndex = false; } UpdateAtlasIndex(child, ref curIndex); } if (needNewIndex) { //all children have a zOrder < 0) oldIndex = sprite.AtlasIndex; sprite.AtlasIndex = curIndex; sprite.OrderOfArrival = 0; if (oldIndex != curIndex) { Swap(oldIndex, curIndex); } curIndex++; } } } void Swap(int oldIndex, int newIndex) { CCSprite[] sprites = Descendants.Elements; CCRawList<CCV3F_C4B_T2F_Quad> quads = TextureAtlas.Quads; TextureAtlas.Dirty = true; CCSprite tempItem = sprites[oldIndex]; CCV3F_C4B_T2F_Quad tempItemQuad = quads[oldIndex]; //update the index of other swapped item sprites[newIndex].AtlasIndex = oldIndex; sprites[oldIndex] = sprites[newIndex]; quads[oldIndex] = quads[newIndex]; sprites[newIndex] = tempItem; quads[newIndex] = tempItemQuad; } public void ReorderBatch(bool reorder) { IsReorderChildDirty = reorder; } public void IncreaseAtlasCapacity() { // if we're going beyond the current TextureAtlas's capacity, // all the previously initialized sprites will need to redo their texture coords // this is likely computationally expensive int quantity = (TextureAtlas.Capacity + 1) * 4 / 3; CCLog.Log(string.Format( "CocosSharp: CCSpriteBatchNode: resizing TextureAtlas capacity from [{0}] to [{1}].", TextureAtlas.Capacity, quantity)); TextureAtlas.ResizeCapacity(quantity); } public int RebuildIndexInOrder(CCSprite pobParent, int uIndex) { CCRawList<CCNode> pChildren = pobParent.Children; if (pChildren != null && pChildren.Count > 0) { CCNode[] elements = pChildren.Elements; for (int i = 0, count = pChildren.Count; i < count; i++) { if (elements[i].ZOrder < 0) { uIndex = RebuildIndexInOrder((CCSprite) pChildren[i], uIndex); } } } // ignore self (batch node) if (!pobParent.Equals(this)) { pobParent.AtlasIndex = uIndex; uIndex++; } if (pChildren != null && pChildren.Count > 0) { CCNode[] elements = pChildren.Elements; for (int i = 0, count = pChildren.Count; i < count; i++) { if (elements[i].ZOrder >= 0) { uIndex = RebuildIndexInOrder((CCSprite) elements[i], uIndex); } } } return uIndex; } public int HighestAtlasIndexInChild(CCSprite pSprite) { CCRawList<CCNode> pChildren = pSprite.Children; if (pChildren == null || pChildren.Count == 0) { return pSprite.AtlasIndex; } else { return HighestAtlasIndexInChild((CCSprite) pChildren.Elements[pChildren.Count - 1]); } } public int LowestAtlasIndexInChild(CCSprite pSprite) { CCRawList<CCNode> pChildren = pSprite.Children; if (pChildren == null || pChildren.Count == 0) { return pSprite.AtlasIndex; } else { return LowestAtlasIndexInChild((CCSprite) pChildren.Elements[0]); } } public int AtlasIndexForChild(CCSprite pobSprite, int nZ) { CCRawList<CCNode> pBrothers = pobSprite.Parent.Children; int uChildIndex = pBrothers.IndexOf(pobSprite); // ignore parent Z if parent is spriteSheet bool bIgnoreParent = (pobSprite.Parent == this); CCSprite pPrevious = null; if (uChildIndex > 0) { pPrevious = (CCSprite) pBrothers[uChildIndex - 1]; } // first child of the sprite sheet if (bIgnoreParent) { if (uChildIndex == 0) { return 0; } return HighestAtlasIndexInChild(pPrevious) + 1; } // parent is a CCSprite, so, it must be taken into account // first child of an CCSprite ? if (uChildIndex == 0) { var p = (CCSprite) pobSprite.Parent; // less than parent and brothers if (nZ < 0) { return p.AtlasIndex; } else { return p.AtlasIndex + 1; } } else { // previous & sprite belong to the same branch if ((pPrevious.ZOrder < 0 && nZ < 0) || (pPrevious.ZOrder >= 0 && nZ >= 0)) { return HighestAtlasIndexInChild(pPrevious) + 1; } // else (previous < 0 and sprite >= 0 ) var p = (CCSprite) pobSprite.Parent; return p.AtlasIndex + 1; } } public void RemoveSpriteFromAtlas(CCSprite sprite) { // remove from TextureAtlas TextureAtlas.RemoveQuadAtIndex(sprite.AtlasIndex); // Cleanup sprite. It might be reused (issue #569) sprite.BatchNode = null; var uIndex = Descendants.IndexOf(sprite); if (uIndex >= 0) { // update all sprites beyond this one var count = Descendants.Count; var elements = Descendants.Elements; for (var index = uIndex; index < count; ++index) { elements[index].AtlasIndex--; } Descendants.RemoveAt(uIndex); } // remove children recursively var spriteChildren = sprite.Children; if (spriteChildren != null && spriteChildren.Count > 0) { var elements = spriteChildren.Elements; for (int i = 0, count = spriteChildren.Count; i < count; i++) { RemoveSpriteFromAtlas((CCSprite) elements[i]); } } } void UpdateBlendFunc() { if (!TextureAtlas.Texture.HasPremultipliedAlpha) { BlendFunc = CCBlendFunc.NonPremultiplied; } } //CCSpriteSheet Extension //implementation CCSpriteSheet (TMXTiledMapExtension) protected void InsertQuadFromSprite(CCSprite sprite, int index) { Debug.Assert(sprite != null, "Argument must be non-NULL"); while (index >= TextureAtlas.Capacity || TextureAtlas.Capacity == TextureAtlas.TotalQuads) { IncreaseAtlasCapacity(); } // // update the quad directly. Don't add the sprite to the scene graph // sprite.BatchNode = this; sprite.AtlasIndex = index; TextureAtlas.InsertQuad(ref sprite.transformedQuad, index); // XXX: updateTransform will update the textureAtlas too using updateQuad. // XXX: so, it should be AFTER the insertQuad sprite.UpdateTransformedSpriteTextureQuads(); } protected void UpdateQuadFromSprite(CCSprite sprite, int index) { Debug.Assert(sprite != null, "Argument must be non-NULL"); while (index >= TextureAtlas.Capacity || TextureAtlas.Capacity == TextureAtlas.TotalQuads) { IncreaseAtlasCapacity(); } // // update the quad directly. Don't add the sprite to the scene graph // sprite.BatchNode = this; sprite.AtlasIndex = index; // UpdateTransform updates the textureAtlas quad sprite.UpdateTransformedSpriteTextureQuads(); } protected CCSpriteBatchNode AddSpriteWithoutQuad(CCSprite child, int z, int aTag) { Debug.Assert(child != null, "Argument must be non-NULL"); // quad index is Z child.AtlasIndex = z; // XXX: optimize with a binary search int i = 0; if (Descendants.Count > 0) { CCSprite[] elements = Descendants.Elements; for (int j = 0, count = Descendants.Count; j < count; j++) { if (elements[i].AtlasIndex <= z) { ++i; } } } Descendants.Insert(i, child); base.AddChild(child, z, aTag); //#issue 1262 don't use lazy sorting, tiles are added as quads not as sprites, so sprites need to be added in order ReorderBatch(false); return this; } } }
using System; using System.Collections.Generic; using Lucene.Net.Documents; namespace Lucene.Net.Index { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using Lucene.Net.Analysis; using Lucene.Net.Randomized.Generators; using Lucene.Net.Support; using NUnit.Framework; using System.IO; using Directory = Lucene.Net.Store.Directory; using Document = Documents.Document; using Field = Field; using IndexSearcher = Lucene.Net.Search.IndexSearcher; using LuceneTestCase = Lucene.Net.Util.LuceneTestCase; using MockDirectoryWrapper = Lucene.Net.Store.MockDirectoryWrapper; using OpenMode_e = Lucene.Net.Index.IndexWriterConfig.OpenMode_e; using ScoreDoc = Lucene.Net.Search.ScoreDoc; using TermQuery = Lucene.Net.Search.TermQuery; using TestUtil = Lucene.Net.Util.TestUtil; [TestFixture] public class TestIndexWriterCommit : LuceneTestCase { /* * Simple test for "commit on close": open writer then * add a bunch of docs, making sure reader does not see * these docs until writer is closed. */ [Test] public virtual void TestCommitOnClose() { Directory dir = NewDirectory(); IndexWriter writer = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random()))); for (int i = 0; i < 14; i++) { TestIndexWriter.AddDoc(writer); } writer.Dispose(); Term searchTerm = new Term("content", "aaa"); DirectoryReader reader = DirectoryReader.Open(dir); IndexSearcher searcher = NewSearcher(reader); ScoreDoc[] hits = searcher.Search(new TermQuery(searchTerm), null, 1000).ScoreDocs; Assert.AreEqual(14, hits.Length, "first number of hits"); reader.Dispose(); reader = DirectoryReader.Open(dir); writer = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random()))); for (int i = 0; i < 3; i++) { for (int j = 0; j < 11; j++) { TestIndexWriter.AddDoc(writer); } IndexReader r = DirectoryReader.Open(dir); searcher = NewSearcher(r); hits = searcher.Search(new TermQuery(searchTerm), null, 1000).ScoreDocs; Assert.AreEqual(14, hits.Length, "reader incorrectly sees changes from writer"); r.Dispose(); Assert.IsTrue(reader.Current, "reader should have still been current"); } // Now, close the writer: writer.Dispose(); Assert.IsFalse(reader.Current, "reader should not be current now"); IndexReader ir = DirectoryReader.Open(dir); searcher = NewSearcher(ir); hits = searcher.Search(new TermQuery(searchTerm), null, 1000).ScoreDocs; Assert.AreEqual(47, hits.Length, "reader did not see changes after writer was closed"); ir.Dispose(); reader.Dispose(); dir.Dispose(); } /* * Simple test for "commit on close": open writer, then * add a bunch of docs, making sure reader does not see * them until writer has closed. Then instead of * closing the writer, call abort and verify reader sees * nothing was added. Then verify we can open the index * and add docs to it. */ [Test] public virtual void TestCommitOnCloseAbort() { Directory dir = NewDirectory(); IndexWriter writer = new IndexWriter(dir, (IndexWriterConfig)NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetMaxBufferedDocs(10)); for (int i = 0; i < 14; i++) { TestIndexWriter.AddDoc(writer); } writer.Dispose(); Term searchTerm = new Term("content", "aaa"); IndexReader reader = DirectoryReader.Open(dir); IndexSearcher searcher = NewSearcher(reader); ScoreDoc[] hits = searcher.Search(new TermQuery(searchTerm), null, 1000).ScoreDocs; Assert.AreEqual(14, hits.Length, "first number of hits"); reader.Dispose(); writer = new IndexWriter(dir, (IndexWriterConfig)NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetOpenMode(OpenMode_e.APPEND).SetMaxBufferedDocs(10)); for (int j = 0; j < 17; j++) { TestIndexWriter.AddDoc(writer); } // Delete all docs: writer.DeleteDocuments(searchTerm); reader = DirectoryReader.Open(dir); searcher = NewSearcher(reader); hits = searcher.Search(new TermQuery(searchTerm), null, 1000).ScoreDocs; Assert.AreEqual(14, hits.Length, "reader incorrectly sees changes from writer"); reader.Dispose(); // Now, close the writer: writer.Rollback(); TestIndexWriter.AssertNoUnreferencedFiles(dir, "unreferenced files remain after rollback()"); reader = DirectoryReader.Open(dir); searcher = NewSearcher(reader); hits = searcher.Search(new TermQuery(searchTerm), null, 1000).ScoreDocs; Assert.AreEqual(14, hits.Length, "saw changes after writer.abort"); reader.Dispose(); // Now make sure we can re-open the index, add docs, // and all is good: writer = new IndexWriter(dir, (IndexWriterConfig)NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetOpenMode(OpenMode_e.APPEND).SetMaxBufferedDocs(10)); // On abort, writer in fact may write to the same // segments_N file: if (dir is MockDirectoryWrapper) { ((MockDirectoryWrapper)dir).PreventDoubleWrite = false; } for (int i = 0; i < 12; i++) { for (int j = 0; j < 17; j++) { TestIndexWriter.AddDoc(writer); } IndexReader r = DirectoryReader.Open(dir); searcher = NewSearcher(r); hits = searcher.Search(new TermQuery(searchTerm), null, 1000).ScoreDocs; Assert.AreEqual(14, hits.Length, "reader incorrectly sees changes from writer"); r.Dispose(); } writer.Dispose(); IndexReader ir = DirectoryReader.Open(dir); searcher = NewSearcher(ir); hits = searcher.Search(new TermQuery(searchTerm), null, 1000).ScoreDocs; Assert.AreEqual(218, hits.Length, "didn't see changes after close"); ir.Dispose(); dir.Dispose(); } /* * Verify that a writer with "commit on close" indeed * cleans up the temp segments created after opening * that are not referenced by the starting segments * file. We check this by using MockDirectoryWrapper to * measure max temp disk space used. */ [Test] public virtual void TestCommitOnCloseDiskUsage() { // MemoryCodec, since it uses FST, is not necessarily // "additive", ie if you add up N small FSTs, then merge // them, the merged result can easily be larger than the // sum because the merged FST may use array encoding for // some arcs (which uses more space): string idFormat = TestUtil.GetPostingsFormat("id"); string contentFormat = TestUtil.GetPostingsFormat("content"); AssumeFalse("this test cannot run with Memory codec", idFormat.Equals("Memory") || contentFormat.Equals("Memory")); MockDirectoryWrapper dir = NewMockDirectory(); Analyzer analyzer; if (Random().NextBoolean()) { // no payloads analyzer = new AnalyzerAnonymousInnerClassHelper(this); } else { // fixed length payloads int length = Random().Next(200); analyzer = new AnalyzerAnonymousInnerClassHelper2(this, length); } IndexWriter writer = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, analyzer).SetMaxBufferedDocs(10).SetReaderPooling(false).SetMergePolicy(NewLogMergePolicy(10))); for (int j = 0; j < 30; j++) { TestIndexWriter.AddDocWithIndex(writer, j); } writer.Dispose(); dir.ResetMaxUsedSizeInBytes(); dir.TrackDiskUsage = true; long startDiskUsage = dir.MaxUsedSizeInBytes; writer = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, analyzer).SetOpenMode(OpenMode_e.APPEND).SetMaxBufferedDocs(10).SetMergeScheduler(new SerialMergeScheduler()).SetReaderPooling(false).SetMergePolicy(NewLogMergePolicy(10))); for (int j = 0; j < 1470; j++) { TestIndexWriter.AddDocWithIndex(writer, j); } long midDiskUsage = dir.MaxUsedSizeInBytes; dir.ResetMaxUsedSizeInBytes(); writer.ForceMerge(1); writer.Dispose(); DirectoryReader.Open(dir).Dispose(); long endDiskUsage = dir.MaxUsedSizeInBytes; // Ending index is 50X as large as starting index; due // to 3X disk usage normally we allow 150X max // transient usage. If something is wrong w/ deleter // and it doesn't delete intermediate segments then it // will exceed this 150X: // System.out.println("start " + startDiskUsage + "; mid " + midDiskUsage + ";end " + endDiskUsage); Assert.IsTrue(midDiskUsage < 150 * startDiskUsage, "writer used too much space while adding documents: mid=" + midDiskUsage + " start=" + startDiskUsage + " end=" + endDiskUsage + " max=" + (startDiskUsage * 150)); Assert.IsTrue(endDiskUsage < 150 * startDiskUsage, "writer used too much space after close: endDiskUsage=" + endDiskUsage + " startDiskUsage=" + startDiskUsage + " max=" + (startDiskUsage * 150)); dir.Dispose(); } private class AnalyzerAnonymousInnerClassHelper : Analyzer { private readonly TestIndexWriterCommit OuterInstance; public AnalyzerAnonymousInnerClassHelper(TestIndexWriterCommit outerInstance) { this.OuterInstance = outerInstance; } public override TokenStreamComponents CreateComponents(string fieldName, TextReader reader) { return new TokenStreamComponents(new MockTokenizer(reader, MockTokenizer.WHITESPACE, true)); } } private class AnalyzerAnonymousInnerClassHelper2 : Analyzer { private readonly TestIndexWriterCommit OuterInstance; private int Length; public AnalyzerAnonymousInnerClassHelper2(TestIndexWriterCommit outerInstance, int length) { this.OuterInstance = outerInstance; this.Length = length; } public override TokenStreamComponents CreateComponents(string fieldName, TextReader reader) { Tokenizer tokenizer = new MockTokenizer(reader, MockTokenizer.WHITESPACE, true); return new TokenStreamComponents(tokenizer, new MockFixedLengthPayloadFilter(Random(), tokenizer, Length)); } } /* * Verify that calling forceMerge when writer is open for * "commit on close" works correctly both for rollback() * and close(). */ [Test] public virtual void TestCommitOnCloseForceMerge() { Directory dir = NewDirectory(); // Must disable throwing exc on double-write: this // test uses IW.rollback which easily results in // writing to same file more than once if (dir is MockDirectoryWrapper) { ((MockDirectoryWrapper)dir).PreventDoubleWrite = false; } IndexWriter writer = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetMaxBufferedDocs(10).SetMergePolicy(NewLogMergePolicy(10))); for (int j = 0; j < 17; j++) { TestIndexWriter.AddDocWithIndex(writer, j); } writer.Dispose(); writer = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetOpenMode(OpenMode_e.APPEND)); writer.ForceMerge(1); // Open a reader before closing (commiting) the writer: DirectoryReader reader = DirectoryReader.Open(dir); // Reader should see index as multi-seg at this // point: Assert.IsTrue(reader.Leaves.Count > 1, "Reader incorrectly sees one segment"); reader.Dispose(); // Abort the writer: writer.Rollback(); TestIndexWriter.AssertNoUnreferencedFiles(dir, "aborted writer after forceMerge"); // Open a reader after aborting writer: reader = DirectoryReader.Open(dir); // Reader should still see index as multi-segment Assert.IsTrue(reader.Leaves.Count > 1, "Reader incorrectly sees one segment"); reader.Dispose(); if (VERBOSE) { Console.WriteLine("TEST: do real full merge"); } writer = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetOpenMode(OpenMode_e.APPEND)); writer.ForceMerge(1); writer.Dispose(); if (VERBOSE) { Console.WriteLine("TEST: writer closed"); } TestIndexWriter.AssertNoUnreferencedFiles(dir, "aborted writer after forceMerge"); // Open a reader after aborting writer: reader = DirectoryReader.Open(dir); // Reader should see index as one segment Assert.AreEqual(1, reader.Leaves.Count, "Reader incorrectly sees more than one segment"); reader.Dispose(); dir.Dispose(); } // LUCENE-2095: make sure with multiple threads commit // doesn't return until all changes are in fact in the // index [Test] public virtual void TestCommitThreadSafety() { const int NUM_THREADS = 5; const double RUN_SEC = 0.5; var dir = NewDirectory(); var w = new RandomIndexWriter(Random(), dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetMergePolicy(NewLogMergePolicy())); TestUtil.ReduceOpenFiles(w.w); w.Commit(); var failed = new AtomicBoolean(); var threads = new ThreadClass[NUM_THREADS]; long endTime = Environment.TickCount + ((long)(RUN_SEC * 1000)); for (int i = 0; i < NUM_THREADS; i++) { int finalI = i; threads[i] = new ThreadAnonymousInnerClassHelper(dir, w, failed, endTime, finalI); threads[i].Start(); } for (int i = 0; i < NUM_THREADS; i++) { threads[i].Join(); } Assert.IsFalse(failed.Get()); w.Dispose(); dir.Dispose(); } private class ThreadAnonymousInnerClassHelper : ThreadClass { private Directory Dir; private RandomIndexWriter w; private AtomicBoolean Failed; private long EndTime; private int FinalI; public ThreadAnonymousInnerClassHelper(Directory dir, RandomIndexWriter w, AtomicBoolean failed, long endTime, int finalI) { this.Dir = dir; this.w = w; this.Failed = failed; this.EndTime = endTime; this.FinalI = finalI; } public override void Run() { try { Document doc = new Document(); DirectoryReader r = DirectoryReader.Open(Dir); Field f = NewStringField("f", "", Field.Store.NO); doc.Add(f); int count = 0; do { if (Failed.Get()) { break; } for (int j = 0; j < 10; j++) { string s = FinalI + "_" + Convert.ToString(count++); f.StringValue = s; w.AddDocument(doc); w.Commit(); DirectoryReader r2 = DirectoryReader.OpenIfChanged(r); Assert.IsNotNull(r2); Assert.IsTrue(!r2.Equals(r)); r.Dispose(); r = r2; Assert.AreEqual(1, r.DocFreq(new Term("f", s)), "term=f:" + s + "; r=" + r); } } while (Environment.TickCount < EndTime); r.Dispose(); } catch (Exception t) { Failed.Set(true); throw new Exception(t.Message, t); } } } // LUCENE-1044: test writer.Commit() when ac=false [Test] public virtual void TestForceCommit() { Directory dir = NewDirectory(); IndexWriter writer = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetMaxBufferedDocs(2).SetMergePolicy(NewLogMergePolicy(5))); writer.Commit(); for (int i = 0; i < 23; i++) { TestIndexWriter.AddDoc(writer); } DirectoryReader reader = DirectoryReader.Open(dir); Assert.AreEqual(0, reader.NumDocs); writer.Commit(); DirectoryReader reader2 = DirectoryReader.OpenIfChanged(reader); Assert.IsNotNull(reader2); Assert.AreEqual(0, reader.NumDocs); Assert.AreEqual(23, reader2.NumDocs); reader.Dispose(); for (int i = 0; i < 17; i++) { TestIndexWriter.AddDoc(writer); } Assert.AreEqual(23, reader2.NumDocs); reader2.Dispose(); reader = DirectoryReader.Open(dir); Assert.AreEqual(23, reader.NumDocs); reader.Dispose(); writer.Commit(); reader = DirectoryReader.Open(dir); Assert.AreEqual(40, reader.NumDocs); reader.Dispose(); writer.Dispose(); dir.Dispose(); } [Test] public virtual void TestFutureCommit() { Directory dir = NewDirectory(); IndexWriter w = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetIndexDeletionPolicy(NoDeletionPolicy.INSTANCE)); Document doc = new Document(); w.AddDocument(doc); // commit to "first" IDictionary<string, string> commitData = new Dictionary<string, string>(); commitData["tag"] = "first"; w.CommitData = commitData; w.Commit(); // commit to "second" w.AddDocument(doc); commitData["tag"] = "second"; w.CommitData = commitData; w.Dispose(); // open "first" with IndexWriter IndexCommit commit = null; foreach (IndexCommit c in DirectoryReader.ListCommits(dir)) { if (c.UserData["tag"].Equals("first")) { commit = c; break; } } Assert.IsNotNull(commit); w = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetIndexDeletionPolicy(NoDeletionPolicy.INSTANCE).SetIndexCommit(commit)); Assert.AreEqual(1, w.NumDocs()); // commit IndexWriter to "third" w.AddDocument(doc); commitData["tag"] = "third"; w.CommitData = commitData; w.Dispose(); // make sure "second" commit is still there commit = null; foreach (IndexCommit c in DirectoryReader.ListCommits(dir)) { if (c.UserData["tag"].Equals("second")) { commit = c; break; } } Assert.IsNotNull(commit); dir.Dispose(); } [Test] public virtual void TestZeroCommits() { // Tests that if we don't call commit(), the directory has 0 commits. this has // changed since LUCENE-2386, where before IW would always commit on a fresh // new index. Directory dir = NewDirectory(); IndexWriter writer = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random()))); try { DirectoryReader.ListCommits(dir); Assert.Fail("listCommits should have thrown an exception over empty index"); } catch (IndexNotFoundException e) { // that's expected ! } // No changes still should generate a commit, because it's a new index. writer.Dispose(); Assert.AreEqual(1, DirectoryReader.ListCommits(dir).Count, "expected 1 commits!"); dir.Dispose(); } // LUCENE-1274: test writer.PrepareCommit() [Test] public virtual void TestPrepareCommit() { Directory dir = NewDirectory(); IndexWriter writer = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetMaxBufferedDocs(2).SetMergePolicy(NewLogMergePolicy(5))); writer.Commit(); for (int i = 0; i < 23; i++) { TestIndexWriter.AddDoc(writer); } DirectoryReader reader = DirectoryReader.Open(dir); Assert.AreEqual(0, reader.NumDocs); writer.PrepareCommit(); IndexReader reader2 = DirectoryReader.Open(dir); Assert.AreEqual(0, reader2.NumDocs); writer.Commit(); IndexReader reader3 = DirectoryReader.OpenIfChanged(reader); Assert.IsNotNull(reader3); Assert.AreEqual(0, reader.NumDocs); Assert.AreEqual(0, reader2.NumDocs); Assert.AreEqual(23, reader3.NumDocs); reader.Dispose(); reader2.Dispose(); for (int i = 0; i < 17; i++) { TestIndexWriter.AddDoc(writer); } Assert.AreEqual(23, reader3.NumDocs); reader3.Dispose(); reader = DirectoryReader.Open(dir); Assert.AreEqual(23, reader.NumDocs); reader.Dispose(); writer.PrepareCommit(); reader = DirectoryReader.Open(dir); Assert.AreEqual(23, reader.NumDocs); reader.Dispose(); writer.Commit(); reader = DirectoryReader.Open(dir); Assert.AreEqual(40, reader.NumDocs); reader.Dispose(); writer.Dispose(); dir.Dispose(); } // LUCENE-1274: test writer.PrepareCommit() [Test] public virtual void TestPrepareCommitRollback() { Directory dir = NewDirectory(); if (dir is MockDirectoryWrapper) { ((MockDirectoryWrapper)dir).PreventDoubleWrite = false; } IndexWriter writer = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetMaxBufferedDocs(2).SetMergePolicy(NewLogMergePolicy(5))); writer.Commit(); for (int i = 0; i < 23; i++) { TestIndexWriter.AddDoc(writer); } DirectoryReader reader = DirectoryReader.Open(dir); Assert.AreEqual(0, reader.NumDocs); writer.PrepareCommit(); IndexReader reader2 = DirectoryReader.Open(dir); Assert.AreEqual(0, reader2.NumDocs); writer.Rollback(); IndexReader reader3 = DirectoryReader.OpenIfChanged(reader); Assert.IsNull(reader3); Assert.AreEqual(0, reader.NumDocs); Assert.AreEqual(0, reader2.NumDocs); reader.Dispose(); reader2.Dispose(); writer = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random()))); for (int i = 0; i < 17; i++) { TestIndexWriter.AddDoc(writer); } reader = DirectoryReader.Open(dir); Assert.AreEqual(0, reader.NumDocs); reader.Dispose(); writer.PrepareCommit(); reader = DirectoryReader.Open(dir); Assert.AreEqual(0, reader.NumDocs); reader.Dispose(); writer.Commit(); reader = DirectoryReader.Open(dir); Assert.AreEqual(17, reader.NumDocs); reader.Dispose(); writer.Dispose(); dir.Dispose(); } // LUCENE-1274 [Test] public virtual void TestPrepareCommitNoChanges() { Directory dir = NewDirectory(); IndexWriter writer = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random()))); writer.PrepareCommit(); writer.Commit(); writer.Dispose(); IndexReader reader = DirectoryReader.Open(dir); Assert.AreEqual(0, reader.NumDocs); reader.Dispose(); dir.Dispose(); } // LUCENE-1382 [Test] public virtual void TestCommitUserData() { Directory dir = NewDirectory(); IndexWriter w = new IndexWriter(dir, (IndexWriterConfig)NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetMaxBufferedDocs(2)); for (int j = 0; j < 17; j++) { TestIndexWriter.AddDoc(w); } w.Dispose(); DirectoryReader r = DirectoryReader.Open(dir); // commit(Map) never called for this index Assert.AreEqual(0, r.IndexCommit.UserData.Count); r.Dispose(); w = new IndexWriter(dir, (IndexWriterConfig)NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetMaxBufferedDocs(2)); for (int j = 0; j < 17; j++) { TestIndexWriter.AddDoc(w); } IDictionary<string, string> data = new Dictionary<string, string>(); data["label"] = "test1"; w.CommitData = data; w.Dispose(); r = DirectoryReader.Open(dir); Assert.AreEqual("test1", r.IndexCommit.UserData["label"]); r.Dispose(); w = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random()))); w.ForceMerge(1); w.Dispose(); dir.Dispose(); } } }
// Copyright 2007-2016 Chris Patterson, Dru Sellers, Travis Smith, et. al. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. namespace MassTransit { using System; using System.Threading.Tasks; using GreenPipes; using Scheduling; /// <summary> /// Extensions for scheduling publish/send message /// </summary> public static class ScheduleMessageExtensions { /// <summary> /// Schedules a message to be sent to the bus using a Publish, which should only be used when /// the quartz service is on a single shared queue or behind a distributor /// </summary> /// <typeparam name="T">The scheduled message type</typeparam> /// <param name="publishEndpoint">The bus from which the scheduled message command should be published</param> /// <param name="destinationAddress">The destination address where the schedule message should be sent</param> /// <param name="scheduledTime">The time when the message should be sent to the endpoint</param> /// <param name="message">The message to send</param> /// <returns>A handled to the scheduled message</returns> [Obsolete("Use ScheduleSend instead, it's the future")] public static Task<ScheduledMessage<T>> ScheduleMessage<T>(this IPublishEndpoint publishEndpoint, Uri destinationAddress, DateTime scheduledTime, T message) where T : class { return publishEndpoint.ScheduleSend(destinationAddress, scheduledTime, message); } /// <summary> /// Schedules a message to be sent to the bus using a Publish, which should only be used when /// the quartz service is on a single shared queue or behind a distributor /// </summary> /// <typeparam name="T">The scheduled message type</typeparam> /// <param name="publishEndpoint">The bus from which the scheduled message command should be published</param> /// <param name="destinationAddress">The destination address where the schedule message should be sent</param> /// <param name="scheduledTime">The time when the message should be sent to the endpoint</param> /// <param name="message">The message to send</param> /// <param name="pipe">Optional: A callback that gives the caller access to the publish context.</param> /// <returns>A handled to the scheduled message</returns> [Obsolete("Use ScheduleSend instead, it's the future")] public static Task<ScheduledMessage<T>> ScheduleMessage<T>(this IPublishEndpoint publishEndpoint, Uri destinationAddress, DateTime scheduledTime, T message, IPipe<SendContext<T>> pipe) where T : class { return publishEndpoint.ScheduleSend(destinationAddress, scheduledTime, message, pipe); } /// <summary> /// Schedules a message to be sent to the bus using a Publish, which should only be used when /// the quartz service is on a single shared queue or behind a distributor /// </summary> /// <typeparam name="T">The scheduled message type</typeparam> /// <param name="publishEndpoint">The bus from which the scheduled message command should be published</param> /// <param name="destinationAddress">The destination address where the schedule message should be sent</param> /// <param name="scheduledTime">The time when the message should be sent to the endpoint</param> /// <param name="message">The message to send</param> /// <param name="pipe">Optional: A callback that gives the caller access to the publish context.</param> /// <returns>A handled to the scheduled message</returns> [Obsolete("Use ScheduleSend instead, it's the future")] public static Task<ScheduledMessage<T>> ScheduleMessage<T>(this IPublishEndpoint publishEndpoint, Uri destinationAddress, DateTime scheduledTime, T message, IPipe<SendContext> pipe) where T : class { return publishEndpoint.ScheduleSend(destinationAddress, scheduledTime, message, pipe); } /// <summary> /// Schedules a message to be sent to the bus using a Publish, which should only be used when /// the quartz service is on a single shared queue or behind a distributor /// </summary> /// <typeparam name="T">The scheduled message type</typeparam> /// <param name="bus">The bus from which the scheduled message command should be published and delivered</param> /// <param name="scheduledTime">The time when the message should be sent to the endpoint</param> /// <param name="message">The message to send</param> /// <returns>A handled to the scheduled message</returns> [Obsolete("Use ScheduleSend instead, it's the future")] public static Task<ScheduledMessage<T>> ScheduleMessage<T>(this IBus bus, DateTime scheduledTime, T message) where T : class { return bus.ScheduleSend(bus.Address, scheduledTime, message); } /// <summary> /// Schedules a message to be sent to the bus using a Publish, which should only be used when /// the quartz service is on a single shared queue or behind a distributor /// </summary> /// <typeparam name="T">The scheduled message type</typeparam> /// <param name="bus">The bus from which the scheduled message command should be published and delivered</param> /// <param name="scheduledTime">The time when the message should be sent to the endpoint</param> /// <param name="message">The message to send</param> /// /// <param name="pipe">Optional: A callback that gives the caller access to the publish context.</param> /// <returns>A handled to the scheduled message</returns> [Obsolete("Use ScheduleSend instead, it's the future")] public static Task<ScheduledMessage<T>> ScheduleMessage<T>(this IBus bus, DateTime scheduledTime, T message, IPipe<SendContext<T>> pipe) where T : class { return bus.ScheduleSend(bus.Address, scheduledTime, message, pipe); } /// <summary> /// Schedules a message to be sent to the bus using a Publish, which should only be used when /// the quartz service is on a single shared queue or behind a distributor /// </summary> /// <typeparam name="T">The scheduled message type</typeparam> /// <param name="bus">The bus from which the scheduled message command should be published and delivered</param> /// <param name="scheduledTime">The time when the message should be sent to the endpoint</param> /// <param name="message">The message to send</param> /// <param name="pipe">Optional: A callback that gives the caller access to the publish context.</param> /// <returns>A handled to the scheduled message</returns> [Obsolete("Use ScheduleSend instead, it's the future")] public static Task<ScheduledMessage<T>> ScheduleMessage<T>(this IBus bus, DateTime scheduledTime, T message, IPipe<SendContext> pipe) where T : class { return bus.ScheduleSend(bus.Address, scheduledTime, message, pipe); } /// <summary> /// Schedules a message to be sent to the bus using a Publish, which should only be used when /// the quartz service is on a single shared queue or behind a distributor /// </summary> /// <typeparam name="T">The scheduled message type</typeparam> /// <param name="context">The bus from which the scheduled message command should be published and delivered</param> /// <param name="scheduledTime">The time when the message should be sent to the endpoint</param> /// <param name="message">The message to send</param> /// <returns>A handled to the scheduled message</returns> [Obsolete("Use ScheduleSend instead, it's the future")] public static Task<ScheduledMessage<T>> ScheduleMessage<T>(this ConsumeContext context, DateTime scheduledTime, T message) where T : class { MessageSchedulerContext schedulerContext; if (context.TryGetPayload(out schedulerContext)) { return schedulerContext.ScheduleSend(scheduledTime, message); } return ScheduleMessage(context, context.ReceiveContext.InputAddress, scheduledTime, message); } /// <summary> /// Schedules a message to be sent to the bus using a Publish, which should only be used when /// the quartz service is on a single shared queue or behind a distributor /// </summary> /// <typeparam name="T">The scheduled message type</typeparam> /// <param name="context">The bus from which the scheduled message command should be published and delivered</param> /// <param name="scheduledTime">The time when the message should be sent to the endpoint</param> /// <param name="message">The message to send</param> /// <param name="pipe">A callback that gives the caller access to the publish context.</param> /// <returns>A handled to the scheduled message</returns> [Obsolete("Use ScheduleSend instead, it's the future")] public static Task<ScheduledMessage<T>> ScheduleMessage<T>(this ConsumeContext context, DateTime scheduledTime, T message, IPipe<SendContext> pipe) where T : class { MessageSchedulerContext schedulerContext; if (context.TryGetPayload(out schedulerContext)) { return schedulerContext.ScheduleSend(scheduledTime, message, pipe); } return ScheduleMessage(context, context.ReceiveContext.InputAddress, scheduledTime, message, pipe); } /// <summary> /// Schedules a message to be sent to the bus using a Publish, which should only be used when /// the quartz service is on a single shared queue or behind a distributor /// </summary> /// <typeparam name="T">The scheduled message type</typeparam> /// <param name="context">The bus from which the scheduled message command should be published and delivered</param> /// <param name="destinationAddress"></param> /// <param name="scheduledTime">The time when the message should be sent to the endpoint</param> /// <param name="message">The message to send</param> /// <returns>A handled to the scheduled message</returns> [Obsolete("Use ScheduleSend instead, it's the future")] public static Task<ScheduledMessage<T>> ScheduleMessage<T>(this ConsumeContext context, Uri destinationAddress, DateTime scheduledTime, T message) where T : class { MessageSchedulerContext schedulerContext; if (context.TryGetPayload(out schedulerContext)) { return schedulerContext.ScheduleSend(destinationAddress, scheduledTime, message); } IPublishEndpoint endpoint = context; return endpoint.ScheduleSend(destinationAddress, scheduledTime, message); } /// <summary> /// Schedules a message to be sent to the bus using a Publish, which should only be used when /// the quartz service is on a single shared queue or behind a distributor /// </summary> /// <typeparam name="T">The scheduled message type</typeparam> /// <param name="context">The bus from which the scheduled message command should be published and delivered</param> /// <param name="destinationAddress"></param> /// <param name="scheduledTime">The time when the message should be sent to the endpoint</param> /// <param name="message">The message to send</param> /// <param name="pipe">A callback that gives the caller access to the publish context.</param> /// <returns>A handled to the scheduled message</returns> [Obsolete("Use ScheduleSend instead, it's the future")] public static Task<ScheduledMessage<T>> ScheduleMessage<T>(this ConsumeContext context, Uri destinationAddress, DateTime scheduledTime, T message, IPipe<SendContext> pipe) where T : class { MessageSchedulerContext schedulerContext; if (context.TryGetPayload(out schedulerContext)) { return schedulerContext.ScheduleSend(destinationAddress, scheduledTime, message, pipe); } IPublishEndpoint endpoint = context; return endpoint.ScheduleSend(destinationAddress, scheduledTime, message, pipe); } /// <summary> /// Cancel a scheduled message using the scheduled message instance /// </summary> /// <param name="publishEndpoint"></param> /// <param name="message"> </param> [Obsolete("Use CancelScheduledSend() instead")] public static Task CancelScheduledMessage<T>(this IPublishEndpoint publishEndpoint, ScheduledMessage<T> message) where T : class { return publishEndpoint.CancelScheduledSend(message); } /// <summary> /// Cancel a scheduled message using the tokenId that was returned when the message was scheduled. /// </summary> /// <param name="publishEndpoint"></param> /// <param name="tokenId">The tokenId of the scheduled message</param> [Obsolete("Use CancelScheduledSend() instead")] public static Task CancelScheduledMessage(this IPublishEndpoint publishEndpoint, Guid tokenId) { return publishEndpoint.CancelScheduledSend(tokenId); } } }
// 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.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.Implementation.Diagnostics; using Microsoft.CodeAnalysis.Editor.Shared.Preview; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.SolutionCrawler; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Composition; using Microsoft.VisualStudio.Text; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Preview { public class PreviewWorkspaceTests { [Fact, Trait(Traits.Editor, Traits.Editors.Preview)] public void TestPreviewCreationDefault() { using (var previewWorkspace = new PreviewWorkspace()) { Assert.NotNull(previewWorkspace.CurrentSolution); } } [Fact, Trait(Traits.Editor, Traits.Editors.Preview)] public void TestPreviewCreationWithExplicitHostServices() { var assembly = typeof(ISolutionCrawlerRegistrationService).Assembly; using (var previewWorkspace = new PreviewWorkspace(MefHostServices.Create(MefHostServices.DefaultAssemblies.Concat(assembly)))) { Assert.NotNull(previewWorkspace.CurrentSolution); } } [Fact, Trait(Traits.Editor, Traits.Editors.Preview)] public void TestPreviewCreationWithSolution() { using (var custom = new AdhocWorkspace()) using (var previewWorkspace = new PreviewWorkspace(custom.CurrentSolution)) { Assert.NotNull(previewWorkspace.CurrentSolution); } } [Fact, Trait(Traits.Editor, Traits.Editors.Preview)] public void TestPreviewAddRemoveProject() { using (var previewWorkspace = new PreviewWorkspace()) { var solution = previewWorkspace.CurrentSolution; var project = solution.AddProject("project", "project.dll", LanguageNames.CSharp); Assert.True(previewWorkspace.TryApplyChanges(project.Solution)); var newSolution = previewWorkspace.CurrentSolution.RemoveProject(project.Id); Assert.True(previewWorkspace.TryApplyChanges(newSolution)); Assert.Equal(0, previewWorkspace.CurrentSolution.ProjectIds.Count); } } [Fact, Trait(Traits.Editor, Traits.Editors.Preview)] public void TestPreviewProjectChanges() { using (var previewWorkspace = new PreviewWorkspace()) { var solution = previewWorkspace.CurrentSolution; var project = solution.AddProject("project", "project.dll", LanguageNames.CSharp); Assert.True(previewWorkspace.TryApplyChanges(project.Solution)); var addedSolution = previewWorkspace.CurrentSolution.Projects.First() .AddMetadataReference(TestReferences.NetFx.v4_0_30319.mscorlib) .AddDocument("document", "").Project.Solution; Assert.True(previewWorkspace.TryApplyChanges(addedSolution)); Assert.Equal(1, previewWorkspace.CurrentSolution.Projects.First().MetadataReferences.Count); Assert.Equal(1, previewWorkspace.CurrentSolution.Projects.First().DocumentIds.Count); var text = "class C {}"; var changedSolution = previewWorkspace.CurrentSolution.Projects.First().Documents.First().WithText(SourceText.From(text)).Project.Solution; Assert.True(previewWorkspace.TryApplyChanges(changedSolution)); Assert.Equal(previewWorkspace.CurrentSolution.Projects.First().Documents.First().GetTextAsync().Result.ToString(), text); var removedSolution = previewWorkspace.CurrentSolution.Projects.First() .RemoveMetadataReference(previewWorkspace.CurrentSolution.Projects.First().MetadataReferences[0]) .RemoveDocument(previewWorkspace.CurrentSolution.Projects.First().DocumentIds[0]).Solution; Assert.True(previewWorkspace.TryApplyChanges(removedSolution)); Assert.Equal(0, previewWorkspace.CurrentSolution.Projects.First().MetadataReferences.Count); Assert.Equal(0, previewWorkspace.CurrentSolution.Projects.First().DocumentIds.Count); } } [WorkItem(923121)] [Fact, Trait(Traits.Editor, Traits.Editors.Preview)] public void TestPreviewOpenCloseFile() { using (var previewWorkspace = new PreviewWorkspace()) { var solution = previewWorkspace.CurrentSolution; var project = solution.AddProject("project", "project.dll", LanguageNames.CSharp); var document = project.AddDocument("document", ""); Assert.True(previewWorkspace.TryApplyChanges(document.Project.Solution)); previewWorkspace.OpenDocument(document.Id); Assert.Equal(1, previewWorkspace.GetOpenDocumentIds().Count()); Assert.True(previewWorkspace.IsDocumentOpen(document.Id)); previewWorkspace.CloseDocument(document.Id); Assert.Equal(0, previewWorkspace.GetOpenDocumentIds().Count()); Assert.False(previewWorkspace.IsDocumentOpen(document.Id)); } } [Fact, Trait(Traits.Editor, Traits.Editors.Preview)] public void TestPreviewServices() { using (var previewWorkspace = new PreviewWorkspace(MefV1HostServices.Create(TestExportProvider.ExportProviderWithCSharpAndVisualBasic.AsExportProvider()))) { var service = previewWorkspace.Services.GetService<ISolutionCrawlerRegistrationService>(); Assert.True(service is PreviewSolutionCrawlerRegistrationService); var persistentService = previewWorkspace.Services.GetService<IPersistentStorageService>(); Assert.NotNull(persistentService); var storage = persistentService.GetStorage(previewWorkspace.CurrentSolution); Assert.True(storage is NoOpPersistentStorage); } } [WorkItem(923196)] [Fact, Trait(Traits.Editor, Traits.Editors.Preview)] public void TestPreviewDiagnostic() { var diagnosticService = TestExportProvider.ExportProviderWithCSharpAndVisualBasic.GetExportedValue<IDiagnosticAnalyzerService>() as IDiagnosticUpdateSource; var taskSource = new TaskCompletionSource<DiagnosticsUpdatedArgs>(); diagnosticService.DiagnosticsUpdated += (s, a) => taskSource.TrySetResult(a); using (var previewWorkspace = new PreviewWorkspace(MefV1HostServices.Create(TestExportProvider.ExportProviderWithCSharpAndVisualBasic.AsExportProvider()))) { var solution = previewWorkspace.CurrentSolution .AddProject("project", "project.dll", LanguageNames.CSharp) .AddDocument("document", "class { }") .Project .Solution; Assert.True(previewWorkspace.TryApplyChanges(solution)); previewWorkspace.OpenDocument(previewWorkspace.CurrentSolution.Projects.First().DocumentIds[0]); previewWorkspace.EnableDiagnostic(); // wait 20 seconds taskSource.Task.Wait(20000); if (!taskSource.Task.IsCompleted) { // something is wrong FatalError.Report(new System.Exception("not finished after 20 seconds")); } var args = taskSource.Task.Result; Assert.True(args.Diagnostics.Length > 0); } } [Fact] public void TestPreviewDiagnosticTagger() { using (var workspace = CSharpWorkspaceFactory.CreateWorkspaceFromLines("class { }")) using (var previewWorkspace = new PreviewWorkspace(workspace.CurrentSolution)) { // set up to listen diagnostic changes so that we can wait until it happens var diagnosticService = workspace.ExportProvider.GetExportedValue<IDiagnosticService>() as DiagnosticService; var taskSource = new TaskCompletionSource<DiagnosticsUpdatedArgs>(); diagnosticService.DiagnosticsUpdated += (s, a) => taskSource.TrySetResult(a); // preview workspace and owner of the solution now share solution and its underlying text buffer var hostDocument = workspace.Projects.First().Documents.First(); var buffer = hostDocument.GetTextBuffer(); // enable preview diagnostics previewWorkspace.OpenDocument(hostDocument.Id); previewWorkspace.EnableDiagnostic(); var foregroundService = new TestForegroundNotificationService(); var optionsService = workspace.Services.GetService<IOptionService>(); var squiggleWaiter = new ErrorSquiggleWaiter(); // create a tagger for preview workspace var taggerSource = new DiagnosticsSquiggleTaggerProvider.TagSource(buffer, foregroundService, diagnosticService, optionsService, squiggleWaiter); // wait up to 20 seconds for diagnostic service taskSource.Task.Wait(20000); if (!taskSource.Task.IsCompleted) { // something is wrong FatalError.Report(new System.Exception("not finished after 20 seconds")); } // wait for tagger squiggleWaiter.CreateWaitTask().PumpingWait(); var snapshot = buffer.CurrentSnapshot; var intervalTree = taggerSource.GetTagIntervalTreeForBuffer(buffer); var spans = intervalTree.GetIntersectingSpans(new SnapshotSpan(snapshot, 0, snapshot.Length)); taggerSource.TestOnly_Dispose(); Assert.Equal(1, spans.Count); } } [Fact] public void TestPreviewDiagnosticTaggerInPreviewPane() { using (var workspace = CSharpWorkspaceFactory.CreateWorkspaceFromLines("class { }")) { // set up listener to wait until diagnostic finish running var diagnosticService = workspace.ExportProvider.GetExportedValue<IDiagnosticService>() as DiagnosticService; // no easy way to setup waiter. kind of hacky way to setup waiter var source = new CancellationTokenSource(); var taskSource = new TaskCompletionSource<DiagnosticsUpdatedArgs>(); diagnosticService.DiagnosticsUpdated += (s, a) => { source.Cancel(); source = new CancellationTokenSource(); var cancellationToken = source.Token; Task.Delay(2000, cancellationToken).ContinueWith(t => taskSource.TrySetResult(a), CancellationToken.None, TaskContinuationOptions.OnlyOnRanToCompletion, TaskScheduler.Current); }; var hostDocument = workspace.Projects.First().Documents.First(); // make a change to remove squiggle var oldDocument = workspace.CurrentSolution.GetDocument(hostDocument.Id); var oldText = oldDocument.GetTextAsync().Result; var newDocument = oldDocument.WithText(oldText.WithChanges(new TextChange(new TextSpan(0, oldText.Length), "class C { }"))); // create a diff view var previewFactoryService = workspace.ExportProvider.GetExportedValue<IPreviewFactoryService>(); var diffView = previewFactoryService.CreateChangedDocumentPreviewView(oldDocument, newDocument, CancellationToken.None); var foregroundService = new TestForegroundNotificationService(); var optionsService = workspace.Services.GetService<IOptionService>(); // set up tagger for both buffers var leftBuffer = diffView.LeftView.BufferGraph.GetTextBuffers(t => t.ContentType.IsOfType(ContentTypeNames.CSharpContentType)).First(); var leftWaiter = new ErrorSquiggleWaiter(); var leftTaggerSource = new DiagnosticsSquiggleTaggerProvider.TagSource(leftBuffer, foregroundService, diagnosticService, optionsService, leftWaiter); var rightBuffer = diffView.RightView.BufferGraph.GetTextBuffers(t => t.ContentType.IsOfType(ContentTypeNames.CSharpContentType)).First(); var rightWaiter = new ErrorSquiggleWaiter(); var rightTaggerSource = new DiagnosticsSquiggleTaggerProvider.TagSource(rightBuffer, foregroundService, diagnosticService, optionsService, rightWaiter); // wait up to 20 seconds for diagnostics taskSource.Task.Wait(20000); if (!taskSource.Task.IsCompleted) { // something is wrong FatalError.Report(new System.Exception("not finished after 20 seconds")); } // wait taggers leftWaiter.CreateWaitTask().PumpingWait(); rightWaiter.CreateWaitTask().PumpingWait(); // check left buffer var leftSnapshot = leftBuffer.CurrentSnapshot; var leftIntervalTree = leftTaggerSource.GetTagIntervalTreeForBuffer(leftBuffer); var leftSpans = leftIntervalTree.GetIntersectingSpans(new SnapshotSpan(leftSnapshot, 0, leftSnapshot.Length)); leftTaggerSource.TestOnly_Dispose(); Assert.Equal(1, leftSpans.Count); // check right buffer var rightSnapshot = rightBuffer.CurrentSnapshot; var rightIntervalTree = rightTaggerSource.GetTagIntervalTreeForBuffer(rightBuffer); var rightSpans = rightIntervalTree.GetIntersectingSpans(new SnapshotSpan(rightSnapshot, 0, rightSnapshot.Length)); rightTaggerSource.TestOnly_Dispose(); Assert.Equal(0, rightSpans == null ? 0 : rightSpans.Count); } } private class ErrorSquiggleWaiter : AsynchronousOperationListener { } } }
using System; using PcapDotNet.Base; using PcapDotNet.Packets.Ip; namespace PcapDotNet.Packets.IpV4 { /// <summary> /// This option identifies the U.S. classification level at which the datagram is to be protected /// and the authorities whose protection rules apply to each datagram. /// /// <para> /// This option is used by end systems and intermediate systems of an internet to: /// <list type="number"> /// <item>Transmit from source to destination in a network standard representation the common security labels required by computer security models.</item> /// <item>Validate the datagram as appropriate for transmission from the source and delivery to the destination.</item> /// <item> /// Ensure that the route taken by the datagram is protected to the level required by all protection authorities indicated on the datagram. /// In order to provide this facility in a general Internet environment, interior and exterior gateway protocols must be augmented /// to include security label information in support of routing control. /// </item> /// </list> /// </para> /// /// <para> /// The DoD Basic Security option must be copied on fragmentation. /// This option appears at most once in a datagram. /// Some security systems require this to be the first option if more than one option is carried in the IP header, /// but this is not a generic requirement levied by this specification. /// </para> /// /// <para> /// The format of the DoD Basic Security option is as follows: /// <pre> /// +------------+------------+------------+-------------//----------+ /// | 10000010 | XXXXXXXX | SSSSSSSS | AAAAAAA[1] AAAAAAA0 | /// | | | | [0] | /// +------------+------------+------------+-------------//----------+ /// TYPE = 130 LENGTH CLASSIFICATION PROTECTION /// LEVEL AUTHORITY /// FLAGS /// </pre> /// </para> /// </summary> [IpV4OptionTypeRegistration(IpV4OptionType.BasicSecurity)] public sealed class IpV4OptionBasicSecurity : IpV4OptionComplex, IOptionComplexFactory, IEquatable<IpV4OptionBasicSecurity> { /// <summary> /// The minimum number of bytes this option take. /// </summary> public const int OptionMinimumLength = 3; /// <summary> /// The minimum number of bytes this option's value take. /// </summary> public const int OptionValueMinimumLength = OptionMinimumLength - OptionHeaderLength; /// <summary> /// Create the security option from the different security field values. /// </summary> /// <param name="classificationLevel"> /// This field specifies the (U.S.) classification level at which the datagram must be protected. /// The information in the datagram must be protected at this level. /// </param> /// <param name="protectionAuthorities"> /// This field identifies the National Access Programs or Special Access Programs /// which specify protection rules for transmission and processing of the information contained in the datagram. /// </param> /// <param name="length"> /// The number of bytes this option will take. /// </param> public IpV4OptionBasicSecurity(IpV4OptionSecurityClassificationLevel classificationLevel, IpV4OptionSecurityProtectionAuthorities protectionAuthorities, byte length) : base(IpV4OptionType.BasicSecurity) { if (length < OptionMinimumLength) throw new ArgumentOutOfRangeException("length", length, "Minimum option length is " + OptionMinimumLength); if (length == OptionMinimumLength && protectionAuthorities != IpV4OptionSecurityProtectionAuthorities.None) { throw new ArgumentException("Can't have a protection authority without minimum of " + (OptionValueMinimumLength + 1) + " length", "protectionAuthorities"); } if (classificationLevel != IpV4OptionSecurityClassificationLevel.Confidential && classificationLevel != IpV4OptionSecurityClassificationLevel.Secret && classificationLevel != IpV4OptionSecurityClassificationLevel.TopSecret && classificationLevel != IpV4OptionSecurityClassificationLevel.Unclassified) { throw new ArgumentException("Invalid classification level " + classificationLevel); } _classificationLevel = classificationLevel; _protectionAuthorities = protectionAuthorities; _length = length; } /// <summary> /// Create the security option with only classification level. /// </summary> /// <param name="classificationLevel"> /// This field specifies the (U.S.) classification level at which the datagram must be protected. /// The information in the datagram must be protected at this level. /// </param> public IpV4OptionBasicSecurity(IpV4OptionSecurityClassificationLevel classificationLevel) : this(classificationLevel, IpV4OptionSecurityProtectionAuthorities.None, OptionMinimumLength) { } /// <summary> /// Creates unclassified security option. /// </summary> public IpV4OptionBasicSecurity() : this(IpV4OptionSecurityClassificationLevel.Unclassified) { } /// <summary> /// This field specifies the (U.S.) classification level at which the datagram must be protected. /// The information in the datagram must be protected at this level. /// </summary> public IpV4OptionSecurityClassificationLevel ClassificationLevel { get { return _classificationLevel; } } /// <summary> /// This field identifies the National Access Programs or Special Access Programs /// which specify protection rules for transmission and processing of the information contained in the datagram. /// </summary> public IpV4OptionSecurityProtectionAuthorities ProtectionAuthorities { get { return _protectionAuthorities; } } /// <summary> /// The number of bytes this option will take. /// </summary> public override int Length { get { return _length; } } /// <summary> /// True iff this option may appear at most once in a datagram. /// </summary> public override bool IsAppearsAtMostOnce { get { return true; } } /// <summary> /// Two security options are equal iff they have the exact same field values. /// </summary> public bool Equals(IpV4OptionBasicSecurity other) { if (other == null) return false; return ClassificationLevel == other.ClassificationLevel && ProtectionAuthorities == other.ProtectionAuthorities && Length == other.Length; } /// <summary> /// Two security options are equal iff they have the exact same field values. /// </summary> public override bool Equals(IpV4Option other) { return Equals(other as IpV4OptionBasicSecurity); } /// <summary> /// The hash code is the xor of the base class hash code /// with the hash code of the combination of the classification level, protection authority and length. /// </summary> /// <returns></returns> internal override int GetDataHashCode() { return BitSequence.Merge((byte)ClassificationLevel, (byte)ProtectionAuthorities,(byte)Length).GetHashCode(); } /// <summary> /// Tries to read the option from a buffer starting from the option value (after the type and length). /// </summary> /// <param name="buffer">The buffer to read the option from.</param> /// <param name="offset">The offset to the first byte to read the buffer. Will be incremented by the number of bytes read.</param> /// <param name="valueLength">The number of bytes the option value should take according to the length field that was already read.</param> /// <returns>On success - the complex option read. On failure - null.</returns> Option IOptionComplexFactory.CreateInstance(byte[] buffer, ref int offset, byte valueLength) { if (valueLength < OptionValueMinimumLength) return null; // Classification level IpV4OptionSecurityClassificationLevel classificationLevel = (IpV4OptionSecurityClassificationLevel)buffer[offset++]; if (classificationLevel != IpV4OptionSecurityClassificationLevel.Confidential && classificationLevel != IpV4OptionSecurityClassificationLevel.Secret && classificationLevel != IpV4OptionSecurityClassificationLevel.TopSecret && classificationLevel != IpV4OptionSecurityClassificationLevel.Unclassified) { return null; } // Protection authorities int protectionAuthoritiesLength = valueLength - OptionValueMinimumLength; IpV4OptionSecurityProtectionAuthorities protectionAuthorities = IpV4OptionSecurityProtectionAuthorities.None; if (protectionAuthoritiesLength > 0) { for (int i = 0; i < protectionAuthoritiesLength - 1; ++i) { if ((buffer[offset + i] & 0x01) == 0) return null; } if ((buffer[offset + protectionAuthoritiesLength - 1] & 0x01) != 0) return null; protectionAuthorities = (IpV4OptionSecurityProtectionAuthorities)(buffer[offset] & 0xFE); } offset += protectionAuthoritiesLength; return new IpV4OptionBasicSecurity(classificationLevel, protectionAuthorities, (byte)(OptionMinimumLength + protectionAuthoritiesLength)); } internal override void Write(byte[] buffer, ref int offset) { base.Write(buffer, ref offset); buffer[offset++] = (byte)ClassificationLevel; int protectionAuthorityLength = Length - OptionMinimumLength; if (protectionAuthorityLength > 0) { buffer[offset++] = (byte)ProtectionAuthorities; if (protectionAuthorityLength > 1) { buffer[offset - 1] |= 0x01; for (int i = 0; i != protectionAuthorityLength - 2; ++i) buffer[offset++] = 0x01; buffer[offset++] = 0x00; } } } private readonly IpV4OptionSecurityClassificationLevel _classificationLevel; private readonly IpV4OptionSecurityProtectionAuthorities _protectionAuthorities; private readonly byte _length; } }
using System; using UnityEngine; namespace UnityStandardAssets.Characters.ThirdPerson { [RequireComponent(typeof(Rigidbody))] [RequireComponent(typeof(CapsuleCollider))] [RequireComponent(typeof(Animator))] public class ThirdPersonCharacter : MonoBehaviour { [SerializeField] float m_MovingTurnSpeed = 360; [SerializeField] float m_StationaryTurnSpeed = 180; [SerializeField] float m_JumpPower = 12f; [Range(1f, 4f)][SerializeField] float m_GravityMultiplier = 2f; //[SerializeField] float m_RunCycleLegOffset = 0.2f; //specific to the character in sample assets, will need to be modified to work with others [SerializeField] float m_MoveSpeedMultiplier = 1f; [SerializeField] float m_AnimSpeedMultiplier = 1f; [SerializeField] float m_GroundCheckDistance = 0.1f; Rigidbody m_Rigidbody; Animator m_Animator; bool m_IsGrounded; float m_OrigGroundCheckDistance; const float k_Half = 0.5f; float m_TurnAmount; float m_ForwardAmount; Vector3 m_GroundNormal; float m_CapsuleHeight; Vector3 m_CapsuleCenter; CapsuleCollider m_Capsule; bool m_Crouching; void Start() { m_Animator = GetComponent<Animator>(); m_Rigidbody = GetComponent<Rigidbody>(); m_Capsule = GetComponent<CapsuleCollider>(); m_CapsuleHeight = m_Capsule.height; m_CapsuleCenter = m_Capsule.center; m_Rigidbody.constraints = RigidbodyConstraints.FreezeRotationX | RigidbodyConstraints.FreezeRotationY | RigidbodyConstraints.FreezeRotationZ; m_OrigGroundCheckDistance = m_GroundCheckDistance; } public void Move(Vector3 move, bool crouch, bool jump) { // convert the world relative moveInput vector into a local-relative // turn amount and forward amount required to head in the desired // direction. if (move.magnitude > 1f) move.Normalize(); move = transform.InverseTransformDirection(move); CheckGroundStatus(); move = Vector3.ProjectOnPlane(move, m_GroundNormal); m_TurnAmount = Mathf.Atan2(move.x, move.z); m_ForwardAmount = move.z; ApplyExtraTurnRotation(); // control and velocity handling is different when grounded and airborne: if (m_IsGrounded) { HandleGroundedMovement(crouch, jump); } else { HandleAirborneMovement(); } ScaleCapsuleForCrouching(crouch); PreventStandingInLowHeadroom(); // send input and other state parameters to the animator UpdateAnimator(move); } void ScaleCapsuleForCrouching(bool crouch) { if (m_IsGrounded && crouch) { if (m_Crouching) return; m_Capsule.height = m_Capsule.height / 2f; m_Capsule.center = m_Capsule.center / 2f; m_Crouching = true; } else { Ray crouchRay = new Ray(m_Rigidbody.position + Vector3.up * m_Capsule.radius * k_Half, Vector3.up); float crouchRayLength = m_CapsuleHeight - m_Capsule.radius * k_Half; if (Physics.SphereCast(crouchRay, m_Capsule.radius * k_Half, crouchRayLength)) { m_Crouching = true; return; } m_Capsule.height = m_CapsuleHeight; m_Capsule.center = m_CapsuleCenter; m_Crouching = false; } } void PreventStandingInLowHeadroom() { // prevent standing up in crouch-only zones if (!m_Crouching) { Ray crouchRay = new Ray(m_Rigidbody.position + Vector3.up * m_Capsule.radius * k_Half, Vector3.up); float crouchRayLength = m_CapsuleHeight - m_Capsule.radius * k_Half; if (Physics.SphereCast(crouchRay, m_Capsule.radius * k_Half, crouchRayLength)) { m_Crouching = true; } } } void UpdateAnimator(Vector3 move) { // update the animator parameters m_Animator.SetFloat("Forward", m_ForwardAmount, 0.1f, Time.deltaTime); m_Animator.SetFloat("Turn", m_TurnAmount, 0.1f, Time.deltaTime); // the anim speed multiplier allows the overall speed of walking/running to be tweaked in the inspector, // which affects the movement speed because of the root motion. if (m_IsGrounded && move.magnitude > 0) { m_Animator.speed = m_AnimSpeedMultiplier; } else { // don't use that while airborne m_Animator.speed = 1; } } void HandleAirborneMovement() { // apply extra gravity from multiplier: Vector3 extraGravityForce = (Physics.gravity * m_GravityMultiplier) - Physics.gravity; m_Rigidbody.AddForce(extraGravityForce); m_GroundCheckDistance = m_Rigidbody.velocity.y < 0 ? m_OrigGroundCheckDistance : 0.01f; } void HandleGroundedMovement(bool crouch, bool jump) { // check whether conditions are right to allow a jump: if (jump && !crouch && m_Animator.GetCurrentAnimatorStateInfo(0).IsName("Grounded")) { // jump! m_Rigidbody.velocity = new Vector3(m_Rigidbody.velocity.x, m_JumpPower, m_Rigidbody.velocity.z); m_IsGrounded = false; m_Animator.applyRootMotion = false; m_GroundCheckDistance = 0.1f; } } void ApplyExtraTurnRotation() { // help the character turn faster (this is in addition to root rotation in the animation) float turnSpeed = Mathf.Lerp(m_StationaryTurnSpeed, m_MovingTurnSpeed, m_ForwardAmount); transform.Rotate(0, m_TurnAmount * turnSpeed * Time.deltaTime, 0); } public void OnAnimatorMove() { // we implement this function to override the default root motion. // this allows us to modify the positional speed before it's applied. if (m_IsGrounded && Time.deltaTime > 0) { Vector3 v = (m_Animator.deltaPosition * m_MoveSpeedMultiplier) / Time.deltaTime; // we preserve the existing y part of the current velocity. v.y = m_Rigidbody.velocity.y; m_Rigidbody.velocity = v; } } void CheckGroundStatus() { RaycastHit hitInfo; #if UNITY_EDITOR // helper to visualise the ground check ray in the scene view Debug.DrawLine(transform.position + (Vector3.up * 0.1f), transform.position + (Vector3.up * 0.1f) + (Vector3.down * m_GroundCheckDistance)); #endif // 0.1f is a small offset to start the ray from inside the character // it is also good to note that the transform position in the sample assets is at the base of the character if (Physics.Raycast(transform.position + (Vector3.up * 0.1f), Vector3.down, out hitInfo, m_GroundCheckDistance)) { m_GroundNormal = hitInfo.normal; m_IsGrounded = true; m_Animator.applyRootMotion = true; } else { m_IsGrounded = false; m_GroundNormal = Vector3.up; m_Animator.applyRootMotion = false; } } private Action<GameObject> _disposeAction; private ZombieDieBehaviour _dieBehaviour; private ZombieAttackBehaviour _attackBehaviour; public void Die(Action<GameObject> disposeAction) { _disposeAction = disposeAction; m_Animator.SetTrigger("Die"); _dieBehaviour = m_Animator.GetBehaviour<ZombieDieBehaviour>(); _dieBehaviour.ExitCallback = OnDie; } private void OnDie() { m_Animator.ResetTrigger("Die"); _dieBehaviour.ExitCallback = null; _dieBehaviour = null; _disposeAction(gameObject); } public void Attack(Action<GameObject> disposeAction) { _disposeAction = disposeAction; m_Animator.SetTrigger("Attack"); _attackBehaviour = m_Animator.GetBehaviour<ZombieAttackBehaviour>(); _attackBehaviour.ExitCallback = OnAttackComplete; } private void OnAttackComplete() { m_Animator.ResetTrigger("Attack"); _attackBehaviour.ExitCallback = null; _attackBehaviour = null; _disposeAction(gameObject); } } }
/** * Kronometer - Makes the KSP clock easily editable * Copyright (c) 2017 Sigma88, Thomas P. * Licensed under the Terms of the MIT License */ using System; using System.Text; using UnityEngine; using Kopernicus.ConfigParser; namespace Kronometer { // KRONOMETER STARTS HERE [KSPAddon(KSPAddon.Startup.MainMenu, true)] public class Kronometer : MonoBehaviour { /// <summary> /// Name of the config node group which manages Kronometer /// </summary> public const string rootNodeName = "Kronometer"; void Start() { // Get the configNode ConfigNode kronometer = GameDatabase.Instance.GetConfigs(rootNodeName)[0].config; // Parse the config node SettingsLoader loader = Parser.CreateObjectFromConfigNode<SettingsLoader>(kronometer); if // Make sure we need the clock and all values are defined properly ( double.PositiveInfinity > loader.Clock.hour.value && loader.Clock.hour.value > loader.Clock.minute.value && loader.Clock.minute.value > loader.Clock.second.value && loader.Clock.second.value > 0 ) { // Find the home planet CelestialBody homePlanet = FlightGlobals.GetHomeBody(); // Get home planet day (rotation) and year (revolution) if (loader.useHomeDay) loader.Clock.day.value = homePlanet.solarDayLength; if (loader.useHomeYear) loader.Clock.year.value = homePlanet.orbitDriver.orbit.period; // If tidally locked set day = year if (loader.Clock.year.value == homePlanet.rotationPeriod) loader.Clock.day.value = loader.Clock.year.value; // Convert negative numbers to positive loader.Clock.year.value = Math.Abs(loader.Clock.year.value); loader.Clock.day.value = Math.Abs(loader.Clock.day.value); // Round values where it is required if (loader.Clock.year.round) loader.Clock.year.value = Math.Round(loader.Clock.year.value, 0); if (loader.Clock.day.round) loader.Clock.day.value = Math.Round(loader.Clock.day.value, 0); if (loader.Clock.hour.round) loader.Clock.hour.value = Math.Round(loader.Clock.hour.value, 0); if (loader.Clock.minute.round) loader.Clock.minute.value = Math.Round(loader.Clock.minute.value, 0); if (loader.Clock.second.round) loader.Clock.second.value = Math.Round(loader.Clock.second.value, 0); if // Make sure we still need the clock and all values are still defined properly ( double.PositiveInfinity > loader.Clock.hour.value && loader.Clock.hour.value > loader.Clock.minute.value && loader.Clock.minute.value > loader.Clock.second.value && loader.Clock.second.value > 0 ) { // Replace the stock Formatter KSPUtil.dateTimeFormatter = new ClockFormatter(loader); } } } } // THIS IS THE REAL STUFF! public class ClockFormatter : IDateTimeFormatter { /// <summary> /// Required by IDateTimeFormatter /// </summary> public string PrintTime(double time, int valuesOfInterest, bool explicitPositive, bool logEnglish) { return PrintTime(time, valuesOfInterest, explicitPositive); } /// <summary> /// The object that contains the settings for the new clock /// </summary> protected SettingsLoader loader { get; set; } /// <summary> /// Create a new clock formatter /// </summary> public ClockFormatter(SettingsLoader loader) { this.loader = loader; FormatFixer(); } /// <summary> /// Create a new clock formatter /// </summary> public ClockFormatter(ClockFormatter cloneFrom) { loader = cloneFrom.loader; FormatFixer(); } // GET TIME // Splits seconds in years/days/hours/minutes/seconds protected int[] data = new int[6]; /// <summary> /// This will count the number of Years, Days, Hours, Minutes and Seconds /// If a Year lasts 10.5 days, and time = 14 days, the result will be: /// 1 Year, 3 days, and whatever hours-minutes-seconds fit in 0.5 dayloader.Clock.second. /// ( 10.5 + 3 + 0.5 = 14 ) /// </summary> public virtual void GetTime(double time) { // Number of years int years = (int)(time / loader.Clock.year.value); // Time left to count double left = time - years * loader.Clock.year.value; // Number of days int days = (int)(left / loader.Clock.day.value); // Time left to count left = left - days * loader.Clock.day.value; // Number of hours int hours = (int)(left / loader.Clock.hour.value); // Time left to count left = left - hours * loader.Clock.hour.value; // Number of minutes int minutes = (int)(left / loader.Clock.minute.value); // Time left to count left = left - minutes * loader.Clock.minute.value; // Number of seconds int seconds = (int)(left / loader.Clock.second.value); data = new[] { 0, years, seconds, minutes, hours, days }; } // PRINT TIME // Prints the time in the selected format public virtual string PrintTimeLong(double time) { string text = CheckNum(time); if (text != null) return text; GetTime(time); StringBuilder sb = StringBuilderCache.Acquire(); sb.Append(data[1]).Append(data[1] == 1 ? loader.Clock.year.singular : loader.Clock.year.plural).Append(", "); sb.Append(data[5]).Append(data[5] == 1 ? loader.Clock.day.singular : loader.Clock.day.plural).Append(", "); sb.Append(data[4]).Append(data[4] == 1 ? loader.Clock.hour.singular : loader.Clock.hour.plural).Append(", "); sb.Append(data[3]).Append(data[3] == 1 ? loader.Clock.minute.singular : loader.Clock.minute.plural).Append(", "); sb.Append(data[2]).Append(data[2] == 1 ? loader.Clock.second.singular : loader.Clock.second.plural); return sb.ToStringAndRelease(); } public virtual string PrintTimeStamp(double time, bool days = false, bool years = false) { string text = CheckNum(time); if (text != null) return text; GetTime(time); StringBuilder stringBuilder = StringBuilderCache.Acquire(); if (years) stringBuilder.Append(loader.Clock.year.singular + " ").Append(data[1]).Append(", "); if (days) stringBuilder.Append("Day ").Append(data[5]).Append(" - "); stringBuilder.AppendFormat("{0:00}:{1:00}", data[4], data[3]); if (data[1] < 10) stringBuilder.AppendFormat(":{0:00}", data[2]); return stringBuilder.ToStringAndRelease(); } public virtual string PrintTimeStampCompact(double time, bool days = false, bool years = false) { string text = CheckNum(time); if (text != null) return text; GetTime(time); StringBuilder stringBuilder = StringBuilderCache.Acquire(); if (years) stringBuilder.Append(data[1]).Append(loader.Clock.year.symbol + ", "); if (days) stringBuilder.Append(data[5]).Append(loader.Clock.day.symbol + ", "); stringBuilder.AppendFormat("{0:00}:{1:00}", data[4], data[3]); if (data[1] < 10) stringBuilder.AppendFormat(":{0:00}", data[2]); return stringBuilder.ToStringAndRelease(); } public virtual string PrintTime(double time, int valuesOfInterest, bool explicitPositive) { string text = CheckNum(time); if (text != null) return text; bool flag = time < 0.0; GetTime(time); string[] symbols = { loader.Clock.second.symbol, loader.Clock.minute.symbol, loader.Clock.hour.symbol, loader.Clock.day.symbol, loader.Clock.year.symbol }; StringBuilder stringBuilder = StringBuilderCache.Acquire(); if (flag) stringBuilder.Append("- "); else if (explicitPositive) stringBuilder.Append("+ "); int[] list = { data[2], data[3], data[4], data[5], data[1] }; int j = list.Length; while (j-- > 0) { if (list[j] != 0) { for (int i = j; i > Mathf.Max(j - valuesOfInterest, -1); i--) { stringBuilder.Append(Math.Abs(list[i])).Append(symbols[i]); if (i - 1 > Mathf.Max(j - valuesOfInterest, -1)) stringBuilder.Append(", "); } break; } } return stringBuilder.ToStringAndRelease(); } public virtual string PrintTimeCompact(double time, bool explicitPositive) { string text = CheckNum(time); if (text != null) return text; GetTime(time); StringBuilder stringBuilder = StringBuilderCache.Acquire(); if (time < 0.0) stringBuilder.Append("T- "); else if (explicitPositive) stringBuilder.Append("T+ "); if (data[5] > 0) stringBuilder.Append(Math.Abs(data[5])).Append(":"); stringBuilder.AppendFormat("{0:00}:{1:00}:{2:00}", data[4], data[3], data[2]); return stringBuilder.ToStringAndRelease(); } public virtual string PrintDateDelta(double time, bool includeTime, bool includeSeconds, bool useAbs) { string text = CheckNum(time); if (text != null) return text; if (useAbs && time < 0.0) time = -time; StringBuilder stringBuilder = StringBuilderCache.Acquire(); GetTime(time); if (data[1] > 1) stringBuilder.Append(data[1]).Append(" " + loader.Clock.year.plural); else if (data[1] == 1) stringBuilder.Append(data[1]).Append(" " + loader.Clock.year.singular); if (data[5] > 1) { if (stringBuilder.Length != 0) stringBuilder.Append(", "); stringBuilder.Append(data[5]).Append(" " + loader.Clock.day.plural); } else if (data[5] == 1) { if (stringBuilder.Length != 0) stringBuilder.Append(", "); stringBuilder.Append(data[5]).Append(" " + loader.Clock.day.singular); } if (includeTime) { if (data[4] > 1) { if (stringBuilder.Length != 0) stringBuilder.Append(", "); stringBuilder.Append(data[4]).Append(" " + loader.Clock.hour.plural); } else if (data[4] == 1) { if (stringBuilder.Length != 0) stringBuilder.Append(", "); stringBuilder.Append(data[4]).Append(" " + loader.Clock.hour.singular); } if (data[3] > 1) { if (stringBuilder.Length != 0) stringBuilder.Append(", "); stringBuilder.Append(data[3]).Append(" " + loader.Clock.minute.plural); } else if (data[3] == 1) { if (stringBuilder.Length != 0) stringBuilder.Append(", "); stringBuilder.Append(data[3]).Append(" " + loader.Clock.minute.singular); } if (includeSeconds) { if (data[2] > 1) { if (stringBuilder.Length != 0) stringBuilder.Append(", "); stringBuilder.Append(data[2]).Append(" " + loader.Clock.second.plural); } else if (data[2] == 1) { if (stringBuilder.Length != 0) stringBuilder.Append(", "); stringBuilder.Append(data[2]).Append(" " + loader.Clock.second.singular); } } } if (stringBuilder.Length == 0) stringBuilder.Append((!includeTime) ? "0 " + loader.Clock.day.plural : ((!includeSeconds) ? "0 " + loader.Clock.minute.plural : "0 " + loader.Clock.second.plural)); return stringBuilder.ToStringAndRelease(); } public virtual string PrintDateDeltaCompact(double time, bool includeTime, bool includeSeconds, bool useAbs) { string text = CheckNum(time); if (text != null) return text; if (useAbs && time < 0.0) time = -time; StringBuilder stringBuilder = StringBuilderCache.Acquire(); GetTime(time); if (data[1] > 0) stringBuilder.Append(data[1]).Append(loader.Clock.year.symbol); if (data[5] > 0) { if (stringBuilder.Length != 0) stringBuilder.Append(", "); stringBuilder.Append(data[5]).Append(loader.Clock.day.symbol); } if (includeTime) { if (data[4] > 0) { if (stringBuilder.Length != 0) stringBuilder.Append(", "); stringBuilder.Append(data[4]).Append(loader.Clock.hour.symbol); } if (data[3] > 0) { if (stringBuilder.Length != 0) stringBuilder.Append(", "); stringBuilder.Append(data[3]).Append(loader.Clock.minute.symbol); } if (includeSeconds && data[2] > 0) { if (stringBuilder.Length != 0) stringBuilder.Append(", "); stringBuilder.Append(data[2]).Append(loader.Clock.second.symbol); } } if (stringBuilder.Length == 0) stringBuilder.Append((!includeTime) ? "0" + loader.Clock.day.symbol : ((!includeSeconds) ? "0" + loader.Clock.minute.symbol : "0" + loader.Clock.second.symbol)); return stringBuilder.ToStringAndRelease(); } /// <summary> /// Calculates the current date /// This will work also when a year cannot be divided in days without a remainder /// If the year ends halfway through a day, the clock will go: /// Year 1 Day 365 ==> Year 2 Day 1 (Hours, Minutes and Seconds do not reset) /// Day 1 will last untill Day 365 would have ended, then Day 2 will start. /// This way the time shown by the clock will always be consistent with the position of the sun in the sky /// </summary> public virtual Date GetDate(double time) { // Current Year int year = (int)Math.Floor(time / loader.Clock.year.value); // Time carried over each year double AnnualCarryOver = loader.Clock.year.value % loader.Clock.day.value; // Time carried over this year double CarryOverThisYear = MOD(AnnualCarryOver * year, loader.Clock.day.value); // Time passed this year double timeThisYear = MOD(time, loader.Clock.year.value) + CarryOverThisYear; // Current Day of the year int day = (int)Math.Floor(timeThisYear / loader.Clock.day.value.Value); // Time left to count double left = MOD(time, loader.Clock.day.value); // Number of hours in this day int hours = (int)(left / loader.Clock.hour.value); // Time left to count left = left - hours * loader.Clock.hour.value; // Number of minutes in this hour int minutes = (int)(left / loader.Clock.minute.value); // Time left to count left = left - minutes * loader.Clock.minute.value; // Number of seconds in this minute int seconds = (int)(left / loader.Clock.second.value); // Get Month Month month = null; for (int i = 0; i < loader?.calendar?.Count; i++) { Month Mo = loader.calendar[i]; month = Mo; if (day < Mo.days) break; else if (Mo != loader.calendar[loader.calendar.Count - 1]) day -= Mo.days; } return new Date(year, month, day, hours, minutes, seconds); } /// <summary> /// Calculates the current date /// This will work also when a year cannot be divided in days without a remainder /// Every year will end at the last full day of the year. /// The time difference carries over from year to year, untill it's enough to get another full day. /// Example: if a year is 365.25 days, the first three years will have 365 days and 0.25 will carry over. /// On the fourth year there will be enough time carried over, so it will have 366 days. /// </summary> /// <param name="time"></param> /// <returns></returns> public virtual Date GetLeapDate(double time) { // Time in a short (non-leap) year double shortYear = loader.Clock.year.value - (loader.Clock.year.value % loader.Clock.day.value); // Chance of getting a leap day in a year double chanceOfLeapDay = (loader.Clock.year.value % loader.Clock.day.value) / loader.Clock.day.value; // Number of days in a short (non-leap) year int daysInOneShortYear = (int)(shortYear / loader.Clock.day.value); // Time left to count double left = time; double leap = 0; int year = 0; int day = 0; int hours = 0; int minutes = 0; int seconds = 0; //Console.WriteLine("time = " + time); while (!(left < shortYear)) { left -= shortYear; leap += chanceOfLeapDay; year += 1; while (!(leap < 1)) { leap -= 1; if (!(left < loader.Clock.day.value)) { left -= loader.Clock.day.value; } else { year -= 1; day += daysInOneShortYear; } } } day += (int)(left / loader.Clock.day.value); left -= (int)(left / loader.Clock.day.value) * loader.Clock.day.value; hours = (int)(left / 3600); left -= hours * 3600; minutes = (int)(left / 60); left -= minutes * 60; seconds = (int)left; // DATE CALCULATION COMPLETE // Temporary Month (needed later) Month month = null; // If there are months, change 'day' to indicate the current 'day of the month' if (loader.calendar.Count > 0) { // Calculate the time passed from the last month reset // Note: months reset every N years (Kronometer.resetMonths) // Total days passed untill now int daysPassedTOT = (int)Math.Floor(time / loader.Clock.day.value); // Days between month resets = normal days between month resets + leap days between month resets int daysBetweenResets = (daysInOneShortYear * loader.resetMonths) + (int)(chanceOfLeapDay * loader.resetMonths); // Days passed since last month reset int daysFromReset = (int)MOD(daysPassedTOT, daysBetweenResets); // Go through each month in the calendar for (int i = 0; i < loader?.calendar?.Count; i++) { Month Mo = loader.calendar[i]; month = Mo; // If there are more days left than there are in this month // AND // this is not the last month of the calendar if (daysFromReset >= Mo.days && Mo != loader.calendar[loader.calendar.Count - 1]) { // Remove this month worth of days and move on to check next month daysFromReset -= Mo.days; } else break; // If we run out of months, the last month will last until the next reset } // Set 'day' as 'day of the month' day = daysFromReset; } // The final date return new Date(year, month, day, hours, minutes, seconds); } // PRINT DATE // Prints the date in the selected format public virtual string PrintDate(double time, bool includeTime, bool includeSeconds = false) { // Check that the time is a meaningful number string text = CheckNum(time); if (text != null) return text; // The StringBuilder we will use to assemble the date StringBuilder stringBuilder = StringBuilderCache.Acquire(); // Offset time time += loader.Display.CustomPrintDate.offsetTime; // Get the current date Date date = loader.useLeapYears ? GetLeapDate(time) : GetDate(time); // Offset years and days date.year += loader.Display.CustomPrintDate.offsetYear; date.day += loader.Display.CustomPrintDate.offsetDay; // The format in which we will display the date string format = loader.Display.CustomPrintDate.displayDate; // Include time when necessary if (includeTime) format += loader.Display.CustomPrintDate.displayTime; // Include seconds when necessary if (includeSeconds) format += loader.Display.CustomPrintDate.displaySeconds; // Fix the syntax to .NET Framework composite formatting format = FormatFixer(format, date); // Create the date in the required format and return stringBuilder.AppendFormat(format, date.year, date.month != null ? date.month.Number(loader.calendar, loader.resetMonthNum).ToString() : "NaM", date.day, date.hours, date.minutes, date.seconds); return stringBuilder.ToStringAndRelease(); } public virtual string PrintDateNew(double time, bool includeTime) { // Check that the time is a meaningful number string text = CheckNum(time); if (text != null) return text; // The StringBuilder we will use to assemble the date StringBuilder stringBuilder = StringBuilderCache.Acquire(); // Offset time time += loader.Display.CustomPrintDateNew.offsetTime; // Get the current date Date date = loader.useLeapYears ? GetLeapDate(time) : GetDate(time); // Offset years and days date.year += loader.Display.CustomPrintDateNew.offsetYear; date.day += loader.Display.CustomPrintDateNew.offsetDay; // The format in which we will display the date string format = loader.Display.CustomPrintDateNew.displayDate; // Include time when necessary if (includeTime) format += loader.Display.CustomPrintDateNew.displayTime + loader.Display.CustomPrintDateNew.displaySeconds; // Fix the syntax to .NET Framework composite formatting format = FormatFixer(format, date); // Create the date in the required format and return stringBuilder.AppendFormat(format, date.year, date.month != null ? date.month.Number(loader.calendar, loader.resetMonthNum).ToString() : "NaM", date.day, date.hours, date.minutes, date.seconds); return stringBuilder.ToStringAndRelease(); } public virtual string PrintDateCompact(double time, bool includeTime, bool includeSeconds = false) { // Check that the time is a meaningful number string text = CheckNum(time); if (text != null) return text; // The StringBuilder we will use to assemble the date StringBuilder stringBuilder = StringBuilderCache.Acquire(); // Offset time time += loader.Display.CustomPrintDateCompact.offsetTime; // Get the current date Date date = loader.useLeapYears ? GetLeapDate(time) : GetDate(time); // Offset years and days date.year += loader.Display.CustomPrintDateCompact.offsetYear; date.day += loader.Display.CustomPrintDateCompact.offsetDay; // The format in which we will display the date string format = loader.Display.CustomPrintDateCompact.displayDate; // Include time when necessary if (includeTime) format += loader.Display.CustomPrintDateCompact.displayTime; // Include seconds when necessary if (includeSeconds) format += loader.Display.CustomPrintDateCompact.displaySeconds; // Fix the syntax to .NET Framework composite formatting format = FormatFixer(format, date); // Create the date in the required format and return stringBuilder.AppendFormat(format, date.year, date.month != null ? date.month.Number(loader.calendar, loader.resetMonthNum).ToString() : "NaM", date.day, date.hours, date.minutes, date.seconds); return stringBuilder.ToStringAndRelease(); } /// <summary> /// Call FormatFixer on all 'DisplayLoader's /// </summary> public void FormatFixer() { FormatFixer(loader.Display.CustomPrintDate); FormatFixer(loader.Display.CustomPrintDateNew); FormatFixer(loader.Display.CustomPrintDateCompact); } /// <summary> /// Fix the syntax to .NET Framework composite formatting /// This changes only the fixed parameters /// Some parameters will require to be changed live /// </summary> public virtual void FormatFixer(DisplayLoader display) { display.displayDate = FormatFixer(display.displayDate); display.displayTime = FormatFixer(display.displayTime); display.displaySeconds = FormatFixer(display.displaySeconds); } /// <summary> /// Replaces Kronometer syntax with .NET Framework composite formatting /// RULES: /// Angle brackets are used in place of curly brackets /// </summary> /// <Y> <Mo> <D> <M> <H> <S> - number of the relative unit in the date /// <Y0> <D0> <M0> <H0> <S0> - symbol of the relative unit /// <Y1> <D1> <M1> <H1> <S1> - singular name of the relative unit public virtual string FormatFixer(string format) { return format // Fix Brackets .Replace("<", "{") .Replace(">", "}") .Replace("{{", "<") .Replace("}}", ">") .Replace("{ ", " ") .Replace(" }", " ") // Fix Years .Replace("{Y}", "{0}") .Replace("{Y:", "{0:") .Replace("{Y,", "{0,") .Replace("{Y0}", loader.Clock.year.symbol) .Replace("{Y1}", loader.Clock.year.singular) // Fix Months .Replace("{Mo}", "{1}") .Replace("{Mo:", "{1:") // Fix Days .Replace("{D}", "{2}") .Replace("{D:", "{2:") .Replace("{D,", "{2,") .Replace("{D0}", loader.Clock.day.symbol) .Replace("{D1}", loader.Clock.day.singular) // Fix Hours .Replace("{H}", "{3}") .Replace("{H:", "{3:") .Replace("{H,", "{3,") .Replace("{H0}", loader.Clock.hour.symbol) .Replace("{H1}", loader.Clock.hour.singular) // Fix Minutes .Replace("{M}", "{4}") .Replace("{M:", "{4:") .Replace("{M,", "{4,") .Replace("{M0}", loader.Clock.minute.symbol) .Replace("{M1}", loader.Clock.minute.singular) // Fix Seconds .Replace("{S}", "{5}") .Replace("{S:", "{5:") .Replace("{S,", "{5,") .Replace("{S0}", loader.Clock.second.symbol) .Replace("{S1}", loader.Clock.second.singular); } /// <summary> /// Translate Kopernicus syntax to .NET Framework composite formatting /// The syntax for these parameter is linked to their value /// for this reason they need to be changed changed live /// RULES: /// Angle brackets are used in place of curly brackets /// <Mo0> <Mo1> - symbol and name of the required month /// <Y2> <D2> <M2> <H2> <S2> - plural name of the relative unit (uses singular when the number is 1) /// <Dth> - ordinal suffix for the number of the day ("st", "nd", "rd", "th") /// </summary> public virtual string FormatFixer(string format, Date date) { return format // Fix Plurals .Replace("{Y2}", date.year == 1 ? loader.Clock.year.singular : loader.Clock.year.plural) .Replace("{D2}", date.day == 1 ? loader.Clock.day.singular : loader.Clock.day.plural) .Replace("{H2}", date.hours == 1 ? loader.Clock.hour.singular : loader.Clock.hour.plural) .Replace("{M2}", date.minutes == 1 ? loader.Clock.minute.singular : loader.Clock.minute.plural) .Replace("{S2}", date.seconds == 1 ? loader.Clock.second.singular : loader.Clock.second.plural) // Fix Months .Replace("{Mo0}", date.month != null ? date.month.symbol : "NaM") .Replace("{Mo1}", date.month != null ? date.month.name : "NaM") // Fix Days .Replace("{Dth}", GetOrdinal(date.day)); } /// <summary> /// From an integer input, outputs the correct ordinal suffix /// RULES: /// All numbers ending in '1' (except those ending in '11') get 'st' /// All numbers ending in '2' (except those ending in '12') get 'nd' /// All numbers ending in '3' (except those ending in '13') get 'rd' /// All remaining numbers get 'th' /// </summary> public virtual string GetOrdinal(int number) { string s = (number % 100).ToString(); if (s.Length == 1 || (s.Length > 1 && s[s.Length - 2] != '1')) { if (s[s.Length - 1] == '1') return "st"; if (s[s.Length - 1] == '2') return "nd"; if (s[s.Length - 1] == '3') return "rd"; } return "th"; } /// <summary> /// Check Num and Stock Properties /// </summary> private static string CheckNum(double time) { if (double.IsNaN(time)) return "NaN"; if (double.IsPositiveInfinity(time)) return "+Inf"; if (double.IsNegativeInfinity(time)) return "-Inf"; return null; } /// <summary> /// Returns the remainder after number is divided by divisor. The result has the same sign as divisor. /// </summary> /// <param name="number">The number for which you want to find the remainder.</param> /// <param name="divisor">The number by which you want to divide number.</param> /// <returns></returns> public double MOD(double number, double divisor) { return (number % divisor + divisor) % divisor; } /// In these Properties is stored the length of each time unit in game seconds /// These can be found in stock as well, and should be used by other mods that deal with time public virtual int Second { get { return (int)loader.Clock.second.value; } } public virtual int Minute { get { return (int)loader.Clock.minute.value; } } public virtual int Hour { get { return (int)loader.Clock.hour.value; } } public virtual int Day { get { return (int)loader.Clock.day.value; } } public virtual int Year { get { return (int)loader.Clock.year.value; } } } /// <summary> /// Small class to handle dates easily /// </summary> public class Date { public int year { get; set; } public Month month { get; set; } public int day { get; set; } public int hours { get; set; } public int minutes { get; set; } public int seconds { get; set; } public Date(int year, Month month, int day, int hours, int minutes, int seconds) { this.year = year; this.day = day; this.month = month; this.hours = hours; this.minutes = minutes; this.seconds = seconds; } public Date(Date date) { year = date.year; day = date.day; month = date.month; hours = date.hours; minutes = date.minutes; seconds = date.seconds; } } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; using System.Management.Automation; using System.Management.Automation.Host; using System.Management.Automation.Internal; using System.Management.Automation.Remoting; using System.Management.Automation.Runspaces; using System.Threading; using Microsoft.PowerShell.Commands.Internal.Format; using Dbg = System.Management.Automation.Diagnostics; namespace Microsoft.PowerShell.Commands { /// <summary> /// Enter-PSSession cmdlet. /// </summary> [Cmdlet(VerbsCommon.Enter, "PSSession", DefaultParameterSetName = "ComputerName", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096695", RemotingCapability = RemotingCapability.OwnedByCommand)] public class EnterPSSessionCommand : PSRemotingBaseCmdlet { #region Strings private const string InstanceIdParameterSet = "InstanceId"; private const string IdParameterSet = "Id"; private const string NameParameterSet = "Name"; #endregion #region Members /// <summary> /// Disable ThrottleLimit parameter inherited from base class. /// </summary> public new int ThrottleLimit { get { return 0; } set { } } private ObjectStream _stream; private RemoteRunspace _tempRunspace; #endregion #region Parameters #region SSH Parameter Set /// <summary> /// Host name for an SSH remote connection. /// </summary> [Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true, ParameterSetName = PSRemotingBaseCmdlet.SSHHostParameterSet)] [ValidateNotNullOrEmpty()] public new string HostName { get; set; } #endregion /// <summary> /// Computer name parameter. /// </summary> [Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, ParameterSetName = ComputerNameParameterSet)] [Alias("Cn")] [ValidateNotNullOrEmpty] public new string ComputerName { get; set; } /// <summary> /// Runspace parameter. /// </summary> [Parameter(Position = 0, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true, ParameterSetName = SessionParameterSet)] [ValidateNotNullOrEmpty] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Runspace")] public new PSSession Session { get; set; } /// <summary> /// ConnectionUri parameter. /// </summary> [Parameter(Position = 1, ValueFromPipelineByPropertyName = true, ParameterSetName = UriParameterSet)] [ValidateNotNullOrEmpty] [Alias("URI", "CU")] public new Uri ConnectionUri { get; set; } /// <summary> /// RemoteRunspaceId of the remote runspace info object. /// </summary> [Parameter(ValueFromPipelineByPropertyName = true, ParameterSetName = InstanceIdParameterSet)] [ValidateNotNull] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Runspace")] public Guid InstanceId { get; set; } /// <summary> /// SessionId of the remote runspace info object. /// </summary> [Parameter(Position = 0, ValueFromPipelineByPropertyName = true, ParameterSetName = IdParameterSet)] [ValidateNotNull] public int Id { get; set; } /// <summary> /// Name of the remote runspace info object. /// </summary> [Parameter(ValueFromPipelineByPropertyName = true, ParameterSetName = NameParameterSet)] public string Name { get; set; } /// <summary> /// When set and in loopback scenario (localhost) this enables creation of WSMan /// host process with the user interactive token, allowing PowerShell script network access, /// i.e., allows going off box. When this property is true and a PSSession is disconnected, /// reconnection is allowed only if reconnecting from a PowerShell session on the same box. /// </summary> [Parameter(ParameterSetName = ComputerNameParameterSet)] [Parameter(ParameterSetName = UriParameterSet)] public SwitchParameter EnableNetworkAccess { get; set; } /// <summary> /// Virtual machine ID. /// </summary> [ValidateNotNullOrEmpty] [Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, ParameterSetName = VMIdParameterSet)] [Alias("VMGuid")] public new Guid VMId { get; set; } /// <summary> /// Virtual machine name. /// </summary> [ValidateNotNullOrEmpty] [Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, ParameterSetName = VMNameParameterSet)] public new string VMName { get; set; } /// <summary> /// Specifies the credentials of the user to impersonate in the /// virtual machine. If this parameter is not specified then the /// credentials of the current user process will be assumed. /// </summary> [Parameter(ValueFromPipelineByPropertyName = true, ParameterSetName = PSRemotingBaseCmdlet.ComputerNameParameterSet)] [Parameter(ValueFromPipelineByPropertyName = true, ParameterSetName = PSRemotingBaseCmdlet.UriParameterSet)] [Parameter(Position = 1, Mandatory = true, ValueFromPipelineByPropertyName = true, ParameterSetName = VMIdParameterSet)] [Parameter(Position = 1, Mandatory = true, ValueFromPipelineByPropertyName = true, ParameterSetName = VMNameParameterSet)] [Credential()] public override PSCredential Credential { get { return base.Credential; } set { base.Credential = value; } } /// <summary> /// The Id of the target container. /// </summary> [ValidateNotNullOrEmpty] [Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, ParameterSetName = ContainerIdParameterSet)] public new string ContainerId { get; set; } /// <summary> /// For WSMan sessions: /// If this parameter is not specified then the value specified in /// the environment variable DEFAULTREMOTESHELLNAME will be used. If /// this is not set as well, then Microsoft.PowerShell is used. /// /// For VM/Container sessions: /// If this parameter is not specified then no configuration is used. /// </summary> [Parameter(ValueFromPipelineByPropertyName = true, ParameterSetName = EnterPSSessionCommand.ComputerNameParameterSet)] [Parameter(ValueFromPipelineByPropertyName = true, ParameterSetName = EnterPSSessionCommand.UriParameterSet)] [Parameter(ValueFromPipelineByPropertyName = true, ParameterSetName = EnterPSSessionCommand.ContainerIdParameterSet)] [Parameter(ValueFromPipelineByPropertyName = true, ParameterSetName = EnterPSSessionCommand.VMIdParameterSet)] [Parameter(ValueFromPipelineByPropertyName = true, ParameterSetName = EnterPSSessionCommand.VMNameParameterSet)] public string ConfigurationName { get; set; } #region Suppress PSRemotingBaseCmdlet SSH hash parameter set /// <summary> /// Suppress SSHConnection parameter set. /// </summary> public override Hashtable[] SSHConnection { get { return null; } } #endregion #endregion #region Overrides /// <summary> /// Resolves shellname and appname. /// </summary> protected override void BeginProcessing() { base.BeginProcessing(); if (string.IsNullOrEmpty(ConfigurationName)) { if ((ParameterSetName == EnterPSSessionCommand.ComputerNameParameterSet) || (ParameterSetName == EnterPSSessionCommand.UriParameterSet)) { // set to default value for WSMan session ConfigurationName = ResolveShell(null); } else { // convert null to string.Empty for VM/Container session ConfigurationName = string.Empty; } } } /// <summary> /// Process record. /// </summary> protected override void ProcessRecord() { // Push the remote runspace on the local host. IHostSupportsInteractiveSession host = this.Host as IHostSupportsInteractiveSession; if (host == null) { WriteError( new ErrorRecord( new ArgumentException(GetMessage(RemotingErrorIdStrings.HostDoesNotSupportPushRunspace)), nameof(PSRemotingErrorId.HostDoesNotSupportPushRunspace), ErrorCategory.InvalidArgument, null)); return; } // for the console host and Graphical PowerShell host // we want to skip pushing into the the runspace if // the host is in a nested prompt System.Management.Automation.Internal.Host.InternalHost chost = this.Host as System.Management.Automation.Internal.Host.InternalHost; if (!IsParameterSetForVM() && !IsParameterSetForContainer() && !IsParameterSetForVMContainerSession() && chost != null && chost.HostInNestedPrompt()) { ThrowTerminatingError(new ErrorRecord( new InvalidOperationException(PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.HostInNestedPrompt)), "HostInNestedPrompt", ErrorCategory.InvalidOperation, chost)); } /*Microsoft.Windows.PowerShell.Gui.Internal.GPSHost ghost = this.Host as Microsoft.Windows.PowerShell.Gui.Internal.GPSHost; if (ghost != null && ghost.HostInNestedPrompt()) { ThrowTerminatingError(new ErrorRecord( new InvalidOperationException(PSRemotingErrorInvariants.FormatResourceString(PSRemotingErrorId.HostInNestedPrompt)), "HostInNestedPrompt", ErrorCategory.InvalidOperation, wpshost)); }*/ // Get the remote runspace. RemoteRunspace remoteRunspace = null; switch (ParameterSetName) { case ComputerNameParameterSet: remoteRunspace = CreateRunspaceWhenComputerNameParameterSpecified(); break; case UriParameterSet: remoteRunspace = CreateRunspaceWhenUriParameterSpecified(); break; case SessionParameterSet: remoteRunspace = (RemoteRunspace)Session.Runspace; break; case InstanceIdParameterSet: remoteRunspace = GetRunspaceMatchingRunspaceId(this.InstanceId); break; case IdParameterSet: remoteRunspace = GetRunspaceMatchingSessionId(this.Id); break; case NameParameterSet: remoteRunspace = GetRunspaceMatchingName(this.Name); break; case VMIdParameterSet: case VMNameParameterSet: remoteRunspace = GetRunspaceForVMSession(); break; case ContainerIdParameterSet: remoteRunspace = GetRunspaceForContainerSession(); break; case SSHHostParameterSet: remoteRunspace = GetRunspaceForSSHSession(); break; } // If runspace is null then the error record has already been written and we can exit. if (remoteRunspace == null) { return; } // If the runspace is in a disconnected state try to connect. bool runspaceConnected = false; if (remoteRunspace.RunspaceStateInfo.State == RunspaceState.Disconnected) { if (!remoteRunspace.CanConnect) { string message = StringUtil.Format(RemotingErrorIdStrings.SessionNotAvailableForConnection); WriteError( new ErrorRecord( new RuntimeException(message), "EnterPSSessionCannotConnectDisconnectedSession", ErrorCategory.InvalidOperation, remoteRunspace)); return; } // Connect the runspace. Exception ex = null; try { remoteRunspace.Connect(); runspaceConnected = true; } catch (System.Management.Automation.Remoting.PSRemotingTransportException e) { ex = e; } catch (PSInvalidOperationException e) { ex = e; } catch (InvalidRunspacePoolStateException e) { ex = e; } if (ex != null) { string message = StringUtil.Format(RemotingErrorIdStrings.SessionConnectFailed); WriteError( new ErrorRecord( new RuntimeException(message, ex), "EnterPSSessionConnectSessionFailed", ErrorCategory.InvalidOperation, remoteRunspace)); return; } } // Verify that the runspace is open. if (remoteRunspace.RunspaceStateInfo.State != RunspaceState.Opened) { if (ParameterSetName == SessionParameterSet) { string sessionName = (Session != null) ? Session.Name : string.Empty; WriteError( new ErrorRecord( new ArgumentException(GetMessage(RemotingErrorIdStrings.EnterPSSessionBrokenSession, sessionName, remoteRunspace.ConnectionInfo.ComputerName, remoteRunspace.InstanceId)), nameof(PSRemotingErrorId.PushedRunspaceMustBeOpen), ErrorCategory.InvalidArgument, null)); } else { WriteError( new ErrorRecord( new ArgumentException(GetMessage(RemotingErrorIdStrings.PushedRunspaceMustBeOpen)), nameof(PSRemotingErrorId.PushedRunspaceMustBeOpen), ErrorCategory.InvalidArgument, null)); } return; } Debugger debugger = null; try { if (host.Runspace != null) { debugger = host.Runspace.Debugger; } } catch (PSNotImplementedException) { } bool supportRunningCommand = ((debugger != null) && ((debugger.DebugMode & DebugModes.RemoteScript) == DebugModes.RemoteScript)); if (remoteRunspace.RunspaceAvailability != RunspaceAvailability.Available) { // Session has running command. if (!supportRunningCommand) { // Host does not support remote debug and cannot connect to running command. if (runspaceConnected) { // If we succeeded connecting the session (runspace) but it is already running a command, // emit an error for this case because since it is disconnected this session object will // never complete and the user must use *reconstruct* scenario to retrieve data. string message = StringUtil.Format(RemotingErrorIdStrings.EnterPSSessionDisconnected, remoteRunspace.PSSessionName); WriteError( new ErrorRecord( new RuntimeException(message), "EnterPSSessionConnectSessionNotAvailable", ErrorCategory.InvalidOperation, Session)); // Leave session in original disconnected state. remoteRunspace.DisconnectAsync(); return; } else { // If the remote runspace is currently not available then let user know that this command // will not complete until it becomes available. WriteWarning(GetMessage(RunspaceStrings.RunspaceNotReady)); } } else { // Running commands supported. // Warn user that they are entering a session that is running a command and output may // be going to a job object. Job job = FindJobForRunspace(remoteRunspace.InstanceId); string msg; if (job != null) { msg = StringUtil.Format( RunspaceStrings.RunningCmdWithJob, (!string.IsNullOrEmpty(job.Name)) ? job.Name : string.Empty); } else { if (remoteRunspace.RunspaceAvailability == RunspaceAvailability.RemoteDebug) { msg = StringUtil.Format( RunspaceStrings.RunningCmdDebugStop); } else { msg = StringUtil.Format( RunspaceStrings.RunningCmdWithoutJob); } } WriteWarning(msg); } } // Make sure any PSSession object passed in is saved in the local runspace repository. if (Session != null) { this.RunspaceRepository.AddOrReplace(Session); } // prepare runspace for prompt SetRunspacePrompt(remoteRunspace); try { host.PushRunspace(remoteRunspace); } catch (Exception) { // A third-party host can throw any exception here..we should // clean the runspace created in this case. if ((remoteRunspace != null) && (remoteRunspace.ShouldCloseOnPop)) { remoteRunspace.Close(); } // rethrow the exception after cleanup. throw; } } /// <summary> /// This method will until the runspace is opened and warnings if any /// are reported. /// </summary> protected override void EndProcessing() { if (_stream != null) { while (true) { // Keep reading objects until end of stream is encountered _stream.ObjectReader.WaitHandle.WaitOne(); if (!_stream.ObjectReader.EndOfPipeline) { object streamObject = _stream.ObjectReader.Read(); WriteStreamObject((Action<Cmdlet>)streamObject); } else { break; } } } } /// <summary> /// </summary> protected override void StopProcessing() { var remoteRunspace = _tempRunspace; if (remoteRunspace != null) { try { remoteRunspace.CloseAsync(); } catch (InvalidRunspaceStateException) { } return; } IHostSupportsInteractiveSession host = this.Host as IHostSupportsInteractiveSession; if (host == null) { WriteError( new ErrorRecord( new ArgumentException(GetMessage(RemotingErrorIdStrings.HostDoesNotSupportPushRunspace)), nameof(PSRemotingErrorId.HostDoesNotSupportPushRunspace), ErrorCategory.InvalidArgument, null)); return; } host.PopRunspace(); } #endregion #region Private Methods /// <summary> /// Create temporary remote runspace. /// </summary> private RemoteRunspace CreateTemporaryRemoteRunspace(PSHost host, WSManConnectionInfo connectionInfo) { // Create and open the runspace. int rsId; string rsName = PSSession.GenerateRunspaceName(out rsId); RemoteRunspace remoteRunspace = new RemoteRunspace( Utils.GetTypeTableFromExecutionContextTLS(), connectionInfo, host, this.SessionOption.ApplicationArguments, rsName, rsId); Dbg.Assert(remoteRunspace != null, "Expected remoteRunspace != null"); remoteRunspace.URIRedirectionReported += HandleURIDirectionReported; _stream = new ObjectStream(); try { remoteRunspace.Open(); // Mark this temporary runspace so that it closes on pop. remoteRunspace.ShouldCloseOnPop = true; } finally { // unregister uri redirection handler remoteRunspace.URIRedirectionReported -= HandleURIDirectionReported; // close the internal object stream after runspace is opened // Runspace.Open() might throw exceptions..this will make sure // the stream is always closed. _stream.ObjectWriter.Close(); // make sure we dispose the temporary runspace if something bad happens if (remoteRunspace.RunspaceStateInfo.State != RunspaceState.Opened) { remoteRunspace.Dispose(); remoteRunspace = null; } } return remoteRunspace; } /// <summary> /// Write error create remote runspace failed. /// </summary> private void WriteErrorCreateRemoteRunspaceFailed(Exception exception, object argument) { // set the transport message in the error detail so that // the user can directly get to see the message without // having to mine through the error record details PSRemotingTransportException transException = exception as PSRemotingTransportException; string errorDetails = null; if ((transException != null) && (transException.ErrorCode == System.Management.Automation.Remoting.Client.WSManNativeApi.ERROR_WSMAN_REDIRECT_REQUESTED)) { // Handling a special case for redirection..we should talk about // AllowRedirection parameter and WSManMaxRedirectionCount preference // variables string message = PSRemotingErrorInvariants.FormatResourceString( RemotingErrorIdStrings.URIRedirectionReported, transException.Message, "MaximumConnectionRedirectionCount", Microsoft.PowerShell.Commands.PSRemotingBaseCmdlet.DEFAULT_SESSION_OPTION, "AllowRedirection"); errorDetails = message; } ErrorRecord errorRecord = new ErrorRecord(exception, argument, "CreateRemoteRunspaceFailed", ErrorCategory.InvalidArgument, null, null, null, null, null, errorDetails, null); WriteError(errorRecord); } /// <summary> /// Write invalid argument error. /// </summary> private void WriteInvalidArgumentError(PSRemotingErrorId errorId, string resourceString, object errorArgument) { string message = GetMessage(resourceString, errorArgument); WriteError(new ErrorRecord(new ArgumentException(message), errorId.ToString(), ErrorCategory.InvalidArgument, errorArgument)); } /// <summary> /// When the client remote session reports a URI redirection, this method will report the /// message to the user as a Warning using Host method calls. /// </summary> /// <param name="sender"></param> /// <param name="eventArgs"></param> private void HandleURIDirectionReported(object sender, RemoteDataEventArgs<Uri> eventArgs) { string message = StringUtil.Format(RemotingErrorIdStrings.URIRedirectWarningToHost, eventArgs.Data.OriginalString); Action<Cmdlet> streamObject = (Cmdlet cmdlet) => cmdlet.WriteWarning(message); _stream.Write(streamObject); } /// <summary> /// Create runspace when computer name parameter specified. /// </summary> private RemoteRunspace CreateRunspaceWhenComputerNameParameterSpecified() { RemoteRunspace remoteRunspace = null; string resolvedComputerName = ResolveComputerName(ComputerName); try { WSManConnectionInfo connectionInfo = null; connectionInfo = new WSManConnectionInfo(); string scheme = UseSSL.IsPresent ? WSManConnectionInfo.HttpsScheme : WSManConnectionInfo.HttpScheme; connectionInfo.ComputerName = resolvedComputerName; connectionInfo.Port = Port; connectionInfo.AppName = ApplicationName; connectionInfo.ShellUri = ConfigurationName; connectionInfo.Scheme = scheme; if (CertificateThumbprint != null) { connectionInfo.CertificateThumbprint = CertificateThumbprint; } else { connectionInfo.Credential = Credential; } connectionInfo.AuthenticationMechanism = Authentication; UpdateConnectionInfo(connectionInfo); connectionInfo.EnableNetworkAccess = EnableNetworkAccess; remoteRunspace = CreateTemporaryRemoteRunspace(this.Host, connectionInfo); } catch (InvalidOperationException e) { WriteErrorCreateRemoteRunspaceFailed(e, resolvedComputerName); } catch (ArgumentException e) { WriteErrorCreateRemoteRunspaceFailed(e, resolvedComputerName); } catch (PSRemotingTransportException e) { WriteErrorCreateRemoteRunspaceFailed(e, resolvedComputerName); } return remoteRunspace; } /// <summary> /// Create runspace when uri parameter specified. /// </summary> private RemoteRunspace CreateRunspaceWhenUriParameterSpecified() { RemoteRunspace remoteRunspace = null; try { WSManConnectionInfo connectionInfo = new WSManConnectionInfo(); connectionInfo.ConnectionUri = ConnectionUri; connectionInfo.ShellUri = ConfigurationName; if (CertificateThumbprint != null) { connectionInfo.CertificateThumbprint = CertificateThumbprint; } else { connectionInfo.Credential = Credential; } connectionInfo.AuthenticationMechanism = Authentication; UpdateConnectionInfo(connectionInfo); connectionInfo.EnableNetworkAccess = EnableNetworkAccess; remoteRunspace = CreateTemporaryRemoteRunspace(this.Host, connectionInfo); } catch (UriFormatException e) { WriteErrorCreateRemoteRunspaceFailed(e, ConnectionUri); } catch (InvalidOperationException e) { WriteErrorCreateRemoteRunspaceFailed(e, ConnectionUri); } catch (ArgumentException e) { WriteErrorCreateRemoteRunspaceFailed(e, ConnectionUri); } catch (PSRemotingTransportException e) { WriteErrorCreateRemoteRunspaceFailed(e, ConnectionUri); } catch (NotSupportedException e) { WriteErrorCreateRemoteRunspaceFailed(e, ConnectionUri); } return remoteRunspace; } /// <summary> /// Get runspace matching condition. /// </summary> private RemoteRunspace GetRunspaceMatchingCondition( Predicate<PSSession> condition, PSRemotingErrorId tooFew, PSRemotingErrorId tooMany, string tooFewResourceString, string tooManyResourceString, object errorArgument) { // Find matches. List<PSSession> matches = this.RunspaceRepository.Runspaces.FindAll(condition); // Validate. RemoteRunspace remoteRunspace = null; if (matches.Count == 0) { WriteInvalidArgumentError(tooFew, tooFewResourceString, errorArgument); } else if (matches.Count > 1) { WriteInvalidArgumentError(tooMany, tooManyResourceString, errorArgument); } else { remoteRunspace = (RemoteRunspace)matches[0].Runspace; Dbg.Assert(remoteRunspace != null, "Expected remoteRunspace != null"); } return remoteRunspace; } /// <summary> /// Get runspace matching runspace id. /// </summary> private RemoteRunspace GetRunspaceMatchingRunspaceId(Guid remoteRunspaceId) { return GetRunspaceMatchingCondition( condition: info => info.InstanceId == remoteRunspaceId, tooFew: PSRemotingErrorId.RemoteRunspaceNotAvailableForSpecifiedRunspaceId, tooMany: PSRemotingErrorId.RemoteRunspaceHasMultipleMatchesForSpecifiedRunspaceId, tooFewResourceString: RemotingErrorIdStrings.RemoteRunspaceNotAvailableForSpecifiedRunspaceId, tooManyResourceString: RemotingErrorIdStrings.RemoteRunspaceHasMultipleMatchesForSpecifiedRunspaceId, errorArgument: remoteRunspaceId); } /// <summary> /// Get runspace matching session id. /// </summary> private RemoteRunspace GetRunspaceMatchingSessionId(int sessionId) { return GetRunspaceMatchingCondition( condition: info => info.Id == sessionId, tooFew: PSRemotingErrorId.RemoteRunspaceNotAvailableForSpecifiedSessionId, tooMany: PSRemotingErrorId.RemoteRunspaceHasMultipleMatchesForSpecifiedSessionId, tooFewResourceString: RemotingErrorIdStrings.RemoteRunspaceNotAvailableForSpecifiedSessionId, tooManyResourceString: RemotingErrorIdStrings.RemoteRunspaceHasMultipleMatchesForSpecifiedSessionId, errorArgument: sessionId); } /// <summary> /// Get runspace matching name. /// </summary> private RemoteRunspace GetRunspaceMatchingName(string name) { return GetRunspaceMatchingCondition( condition: info => info.Name.Equals(name, StringComparison.OrdinalIgnoreCase), tooFew: PSRemotingErrorId.RemoteRunspaceNotAvailableForSpecifiedName, tooMany: PSRemotingErrorId.RemoteRunspaceHasMultipleMatchesForSpecifiedName, tooFewResourceString: RemotingErrorIdStrings.RemoteRunspaceNotAvailableForSpecifiedName, tooManyResourceString: RemotingErrorIdStrings.RemoteRunspaceHasMultipleMatchesForSpecifiedName, errorArgument: name); } private Job FindJobForRunspace(Guid id) { foreach (var repJob in this.JobRepository.Jobs) { foreach (Job childJob in repJob.ChildJobs) { PSRemotingChildJob remotingChildJob = childJob as PSRemotingChildJob; if (remotingChildJob != null && remotingChildJob.Runspace != null && remotingChildJob.JobStateInfo.State == JobState.Running && remotingChildJob.Runspace.InstanceId.Equals(id)) { return repJob; } } } return null; } private bool IsParameterSetForVM() { return ((ParameterSetName == VMIdParameterSet) || (ParameterSetName == VMNameParameterSet)); } private bool IsParameterSetForContainer() { return (ParameterSetName == ContainerIdParameterSet); } /// <summary> /// Whether the input is a session object or property that corresponds to /// VM or container. /// </summary> private bool IsParameterSetForVMContainerSession() { RemoteRunspace remoteRunspace = null; switch (ParameterSetName) { case SessionParameterSet: if (this.Session != null) { remoteRunspace = (RemoteRunspace)this.Session.Runspace; } break; case InstanceIdParameterSet: remoteRunspace = GetRunspaceMatchingRunspaceId(this.InstanceId); break; case IdParameterSet: remoteRunspace = GetRunspaceMatchingSessionId(this.Id); break; case NameParameterSet: remoteRunspace = GetRunspaceMatchingName(this.Name); break; default: break; } if ((remoteRunspace != null) && (remoteRunspace.ConnectionInfo != null)) { if ((remoteRunspace.ConnectionInfo is VMConnectionInfo) || (remoteRunspace.ConnectionInfo is ContainerConnectionInfo)) { return true; } } return false; } /// <summary> /// Create runspace for VM session. /// </summary> private RemoteRunspace GetRunspaceForVMSession() { RemoteRunspace remoteRunspace = null; string command; Collection<PSObject> results; if (ParameterSetName == VMIdParameterSet) { command = "Get-VM -Id $args[0]"; try { results = this.InvokeCommand.InvokeScript( command, false, PipelineResultTypes.None, null, this.VMId); } catch (CommandNotFoundException) { WriteError( new ErrorRecord( new ArgumentException(RemotingErrorIdStrings.HyperVModuleNotAvailable), nameof(PSRemotingErrorId.HyperVModuleNotAvailable), ErrorCategory.NotInstalled, null)); return null; } if (results.Count != 1) { WriteError( new ErrorRecord( new ArgumentException(RemotingErrorIdStrings.InvalidVMId), nameof(PSRemotingErrorId.InvalidVMId), ErrorCategory.InvalidArgument, null)); return null; } this.VMName = (string)results[0].Properties["VMName"].Value; } else { Dbg.Assert(ParameterSetName == VMNameParameterSet, "Expected ParameterSetName == VMName"); command = "Get-VM -Name $args"; try { results = this.InvokeCommand.InvokeScript( command, false, PipelineResultTypes.None, null, this.VMName); } catch (CommandNotFoundException) { WriteError( new ErrorRecord( new ArgumentException(RemotingErrorIdStrings.HyperVModuleNotAvailable), nameof(PSRemotingErrorId.HyperVModuleNotAvailable), ErrorCategory.NotInstalled, null)); return null; } if (results.Count == 0) { WriteError( new ErrorRecord( new ArgumentException(RemotingErrorIdStrings.InvalidVMNameNoVM), nameof(PSRemotingErrorId.InvalidVMNameNoVM), ErrorCategory.InvalidArgument, null)); return null; } else if (results.Count > 1) { WriteError( new ErrorRecord( new ArgumentException(RemotingErrorIdStrings.InvalidVMNameMultipleVM), nameof(PSRemotingErrorId.InvalidVMNameMultipleVM), ErrorCategory.InvalidArgument, null)); return null; } this.VMId = (Guid)results[0].Properties["VMId"].Value; this.VMName = (string)results[0].Properties["VMName"].Value; } // // VM should be in running state. // if ((VMState)results[0].Properties["State"].Value != VMState.Running) { WriteError( new ErrorRecord( new ArgumentException(GetMessage(RemotingErrorIdStrings.InvalidVMState, this.VMName)), nameof(PSRemotingErrorId.InvalidVMState), ErrorCategory.InvalidArgument, null)); return null; } try { VMConnectionInfo connectionInfo; connectionInfo = new VMConnectionInfo(this.Credential, this.VMId, this.VMName, this.ConfigurationName); remoteRunspace = CreateTemporaryRemoteRunspaceForPowerShellDirect(this.Host, connectionInfo); } catch (InvalidOperationException e) { ErrorRecord errorRecord = new ErrorRecord(e, "CreateRemoteRunspaceForVMFailed", ErrorCategory.InvalidOperation, null); WriteError(errorRecord); } catch (ArgumentException e) { ErrorRecord errorRecord = new ErrorRecord(e, "CreateRemoteRunspaceForVMFailed", ErrorCategory.InvalidArgument, null); WriteError(errorRecord); } catch (PSRemotingDataStructureException e) { ErrorRecord errorRecord; // // In case of PSDirectException, we should output the precise error message // in inner exception instead of the generic one in outer exception. // if ((e.InnerException != null) && (e.InnerException is PSDirectException)) { errorRecord = new ErrorRecord(e.InnerException, "CreateRemoteRunspaceForVMFailed", ErrorCategory.InvalidArgument, null); } else { errorRecord = new ErrorRecord(e, "CreateRemoteRunspaceForVMFailed", ErrorCategory.InvalidOperation, null); } WriteError(errorRecord); } catch (Exception e) { ErrorRecord errorRecord = new ErrorRecord(e, "CreateRemoteRunspaceForVMFailed", ErrorCategory.InvalidOperation, null); WriteError(errorRecord); } return remoteRunspace; } /// <summary> /// Create temporary remote runspace. /// </summary> private static RemoteRunspace CreateTemporaryRemoteRunspaceForPowerShellDirect(PSHost host, RunspaceConnectionInfo connectionInfo) { // Create and open the runspace. TypeTable typeTable = TypeTable.LoadDefaultTypeFiles(); RemoteRunspace remoteRunspace = RunspaceFactory.CreateRunspace(connectionInfo, host, typeTable) as RemoteRunspace; remoteRunspace.Name = "PowerShellDirectAttach"; Dbg.Assert(remoteRunspace != null, "Expected remoteRunspace != null"); try { remoteRunspace.Open(); // Mark this temporary runspace so that it closes on pop. remoteRunspace.ShouldCloseOnPop = true; } finally { // Make sure we dispose the temporary runspace if something bad happens. if (remoteRunspace.RunspaceStateInfo.State != RunspaceState.Opened) { remoteRunspace.Dispose(); remoteRunspace = null; } } return remoteRunspace; } /// <summary> /// Set prompt for VM/Container sessions. /// </summary> private void SetRunspacePrompt(RemoteRunspace remoteRunspace) { if (IsParameterSetForVM() || IsParameterSetForContainer() || IsParameterSetForVMContainerSession()) { string targetName = string.Empty; switch (ParameterSetName) { case VMIdParameterSet: case VMNameParameterSet: targetName = this.VMName; break; case ContainerIdParameterSet: targetName = (this.ContainerId.Length <= 15) ? this.ContainerId : this.ContainerId.Remove(14) + PSObjectHelper.Ellipsis; break; case SessionParameterSet: targetName = (this.Session != null) ? this.Session.ComputerName : string.Empty; break; case InstanceIdParameterSet: case IdParameterSet: case NameParameterSet: if ((remoteRunspace != null) && (remoteRunspace.ConnectionInfo != null)) { targetName = remoteRunspace.ConnectionInfo.ComputerName; } break; default: Dbg.Assert(false, "Unrecognized parameter set."); break; } string promptFn = StringUtil.Format(RemotingErrorIdStrings.EnterVMSessionPrompt, @"function global:prompt { """, targetName, @"PS $($executionContext.SessionState.Path.CurrentLocation)> "" }"); // Set prompt in pushed named pipe runspace. using (System.Management.Automation.PowerShell ps = System.Management.Automation.PowerShell.Create()) { ps.Runspace = remoteRunspace; try { // Set pushed runspace prompt. ps.AddScript(promptFn).Invoke(); } catch (Exception) { } } } return; } /// <summary> /// Create runspace for container session. /// </summary> private RemoteRunspace GetRunspaceForContainerSession() { RemoteRunspace remoteRunspace = null; try { Dbg.Assert(!string.IsNullOrEmpty(ContainerId), "ContainerId has to be set."); ContainerConnectionInfo connectionInfo = null; // // Hyper-V container uses Hype-V socket as transport. // Windows Server container uses named pipe as transport. // connectionInfo = ContainerConnectionInfo.CreateContainerConnectionInfo(ContainerId, RunAsAdministrator.IsPresent, this.ConfigurationName); connectionInfo.CreateContainerProcess(); remoteRunspace = CreateTemporaryRemoteRunspaceForPowerShellDirect(this.Host, connectionInfo); } catch (InvalidOperationException e) { ErrorRecord errorRecord = new ErrorRecord(e, "CreateRemoteRunspaceForContainerFailed", ErrorCategory.InvalidOperation, null); WriteError(errorRecord); } catch (ArgumentException e) { ErrorRecord errorRecord = new ErrorRecord(e, "CreateRemoteRunspaceForContainerFailed", ErrorCategory.InvalidArgument, null); WriteError(errorRecord); } catch (PSRemotingDataStructureException e) { ErrorRecord errorRecord; // // In case of PSDirectException, we should output the precise error message // in inner exception instead of the generic one in outer exception. // if ((e.InnerException != null) && (e.InnerException is PSDirectException)) { errorRecord = new ErrorRecord(e.InnerException, "CreateRemoteRunspaceForContainerFailed", ErrorCategory.InvalidOperation, null); } else { errorRecord = new ErrorRecord(e, "CreateRemoteRunspaceForContainerFailed", ErrorCategory.InvalidOperation, null); } WriteError(errorRecord); } catch (Exception e) { ErrorRecord errorRecord = new ErrorRecord(e, "CreateRemoteRunspaceForContainerFailed", ErrorCategory.InvalidOperation, null); WriteError(errorRecord); } return remoteRunspace; } /// <summary> /// Create remote runspace for SSH session. /// </summary> private RemoteRunspace GetRunspaceForSSHSession() { ParseSshHostName(HostName, out string host, out string userName, out int port); var sshConnectionInfo = new SSHConnectionInfo(userName, host, KeyFilePath, port, Subsystem, ConnectingTimeout); var typeTable = TypeTable.LoadDefaultTypeFiles(); // Use the class _tempRunspace field while the runspace is being opened so that StopProcessing can be handled at that time. // This is only needed for SSH sessions where a Ctrl+C during an SSH password prompt can abort the session before a connection // is established. _tempRunspace = RunspaceFactory.CreateRunspace(sshConnectionInfo, this.Host, typeTable) as RemoteRunspace; _tempRunspace.Open(); _tempRunspace.ShouldCloseOnPop = true; var remoteRunspace = _tempRunspace; _tempRunspace = null; return remoteRunspace; } #endregion #region Internal Methods internal static RemotePipeline ConnectRunningPipeline(RemoteRunspace remoteRunspace) { RemotePipeline cmd = null; if (remoteRunspace.RemoteCommand != null) { // Reconstruct scenario. // Newly connected pipeline object is added to the RemoteRunspace running // pipeline list. cmd = new RemotePipeline(remoteRunspace); } else { // Reconnect scenario. cmd = remoteRunspace.GetCurrentlyRunningPipeline() as RemotePipeline; } // Connect the runspace pipeline so that debugging and output data from // remote server can continue. if (cmd != null && cmd.PipelineStateInfo.State == PipelineState.Disconnected) { using (ManualResetEvent connected = new ManualResetEvent(false)) { cmd.StateChanged += (sender, args) => { if (args.PipelineStateInfo.State != PipelineState.Disconnected) { try { connected.Set(); } catch (ObjectDisposedException) { } } }; cmd.ConnectAsync(); connected.WaitOne(); } } return cmd; } internal static void ContinueCommand(RemoteRunspace remoteRunspace, Pipeline cmd, PSHost host, bool inDebugMode, System.Management.Automation.ExecutionContext context) { RemotePipeline remotePipeline = cmd as RemotePipeline; if (remotePipeline != null) { using (System.Management.Automation.PowerShell ps = System.Management.Automation.PowerShell.Create()) { PSInvocationSettings settings = new PSInvocationSettings() { Host = host }; PSDataCollection<PSObject> input = new PSDataCollection<PSObject>(); CommandInfo commandInfo = new CmdletInfo("Out-Default", typeof(OutDefaultCommand), null, null, context); Command outDefaultCommand = new Command(commandInfo); ps.AddCommand(outDefaultCommand); IAsyncResult async = ps.BeginInvoke<PSObject>(input, settings, null, null); RemoteDebugger remoteDebugger = remoteRunspace.Debugger as RemoteDebugger; if (remoteDebugger != null) { // Update client with breakpoint information from pushed runspace. // Information will be passed to the client via the Debugger.BreakpointUpdated event. remoteDebugger.SendBreakpointUpdatedEvents(); if (!inDebugMode) { // Enter debug mode if remote runspace is in debug stop mode. remoteDebugger.CheckStateAndRaiseStopEvent(); } } // Wait for debugged cmd to complete. while (!remotePipeline.Output.EndOfPipeline) { remotePipeline.Output.WaitHandle.WaitOne(); while (remotePipeline.Output.Count > 0) { input.Add(remotePipeline.Output.Read()); } } input.Complete(); ps.EndInvoke(async); } } } #endregion } }
// // Copyright (c) 2008-2011, Kenneth Bell // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // using System; using System.IO; using DiscUtils; using DiscUtils.Common; using DiscUtils.Ntfs; using DiscUtils.Ntfs.Internals; namespace FileRecover { class Program : ProgramBase { private CommandLineMultiParameter _diskFiles; private CommandLineSwitch _recoverFile; private CommandLineSwitch _showMeta; private CommandLineSwitch _showZeroSize; static void Main(string[] args) { Program program = new Program(); program.Run(args); } protected override ProgramBase.StandardSwitches DefineCommandLine(CommandLineParser parser) { _diskFiles = FileOrUriMultiParameter("disk", "The disks to inspect.", false); _recoverFile = new CommandLineSwitch("r", "recover", "file_index", "Tries to recover the file at MFT index file_index from the disk."); _showMeta = new CommandLineSwitch("M", "meta", null, "Don't hide files and directories that are part of the file system itself."); _showZeroSize = new CommandLineSwitch("Z", "empty", null, "Don't hide files shown as zero size."); parser.AddMultiParameter(_diskFiles); parser.AddSwitch(_recoverFile); parser.AddSwitch(_showMeta); parser.AddSwitch(_showZeroSize); return StandardSwitches.UserAndPassword | StandardSwitches.PartitionOrVolume; } protected override string[] HelpRemarks { get { return new string[] { "By default this utility shows the files that it may be possible to recover from an NTFS formatted virtual disk. Once a " + "candidate file is determined, use the '-r' option to attempt recovery of the file's contents." }; } } protected override void DoRun() { VolumeManager volMgr = new VolumeManager(); foreach (string disk in _diskFiles.Values) { volMgr.AddDisk(VirtualDisk.OpenDisk(disk, FileAccess.Read, UserName, Password)); } VolumeInfo volInfo = null; if (!string.IsNullOrEmpty(VolumeId)) { volInfo = volMgr.GetVolume(VolumeId); } else if (Partition >= 0) { volInfo = volMgr.GetPhysicalVolumes()[Partition]; } else { volInfo = volMgr.GetLogicalVolumes()[0]; } using (NtfsFileSystem fs = new NtfsFileSystem(volInfo.Open())) { MasterFileTable mft = fs.GetMasterFileTable(); if (_recoverFile.IsPresent) { MasterFileTableEntry entry = mft[long.Parse(_recoverFile.Value)]; IBuffer content = GetContent(entry); if (content == null) { Console.WriteLine("Sorry, unable to recover content"); Environment.Exit(1); } string outFile = _recoverFile.Value + "__recovered.bin"; if (File.Exists(outFile)) { Console.WriteLine("Sorry, the file already exists: " + outFile); Environment.Exit(1); } using (FileStream outFileStream = new FileStream(outFile, FileMode.CreateNew, FileAccess.Write)) { Pump(content, outFileStream); } Console.WriteLine("Possible file contents saved as: " + outFile); Console.WriteLine(); Console.WriteLine("Caution! It is rare for the file contents of deleted files to be intact - most"); Console.WriteLine("likely the contents recovered are corrupt as the space has been reused."); } else { foreach (var entry in mft.GetEntries(EntryStates.NotInUse)) { // Skip entries with no attributes, they've probably never been used. We're certainly // not going to manage to recover any useful data from them. if (entry.Attributes.Count == 0) continue; // Skip directories - any useful files inside will be found separately if ((entry.Flags & MasterFileTableEntryFlags.IsDirectory) != 0) continue; long size = GetSize(entry); string path = GetPath(mft, entry); if (!_showMeta.IsPresent && path.StartsWith(@"<root>\$Extend")) continue; if (!_showZeroSize.IsPresent && size == 0) continue; Console.WriteLine("Index: {0,-4} Size: {1,-8} Path: {2}", entry.Index, Utilities.ApproximateDiskSize(size), path); } } } } static IBuffer GetContent(MasterFileTableEntry entry) { foreach (var attr in entry.Attributes) { if (attr.AttributeType == AttributeType.Data) { return attr.Content; } } return null; } static long GetSize(MasterFileTableEntry entry) { foreach (var attr in entry.Attributes) { FileNameAttribute fna = attr as FileNameAttribute; if (fna != null) { return fna.RealSize; } } return 0; } static string GetPath(MasterFileTable mft, MasterFileTableEntry entry) { if (entry.SequenceNumber == MasterFileTable.RootDirectoryIndex) { return "<root>"; } FileNameAttribute fna = null; foreach (var attr in entry.Attributes) { FileNameAttribute thisFna = attr as FileNameAttribute; if (thisFna != null) { if (fna == null || thisFna.FileNameNamespace == NtfsNamespace.Win32 || thisFna.FileNameNamespace == NtfsNamespace.Win32AndDos) { fna = thisFna; } } } if (fna == null) { return "<unknown>"; } string parentPath = "<unknown>"; MasterFileTableEntry parentEntry = mft[fna.ParentDirectory.RecordIndex]; if (parentEntry != null) { if (parentEntry.SequenceNumber == fna.ParentDirectory.RecordSequenceNumber || parentEntry.SequenceNumber == fna.ParentDirectory.RecordSequenceNumber + 1) { parentPath = GetPath(mft, parentEntry); } } return parentPath + "\\" + fna.FileName; } private static void Pump(IBuffer inBuffer, Stream outStream) { long inPos = 0; byte[] buffer = new byte[4096]; int bytesRead = inBuffer.Read(inPos, buffer, 0, 4096); while (bytesRead != 0 && inPos < inBuffer.Capacity) { inPos += bytesRead; outStream.Write(buffer, 0, bytesRead); bytesRead = inBuffer.Read(inPos, buffer, 0, 4096); } } } }
using System; using System.Collections.Generic; using Android.Runtime; namespace Org.Webrtc { // Metadata.xml XPath class reference: path="/api/package[@name='org.webrtc']/class[@name='VideoRenderer']" [global::Android.Runtime.Register ("org/webrtc/VideoRenderer", DoNotGenerateAcw=true)] public partial class VideoRenderer : global::Java.Lang.Object { // Metadata.xml XPath interface reference: path="/api/package[@name='org.webrtc']/interface[@name='VideoRenderer.Callbacks']" [Register ("org/webrtc/VideoRenderer$Callbacks", "", "Org.Webrtc.VideoRenderer/ICallbacksInvoker")] public partial interface ICallbacks : IJavaObject { // Metadata.xml XPath method reference: path="/api/package[@name='org.webrtc']/interface[@name='VideoRenderer.Callbacks']/method[@name='canApplyRotation' and count(parameter)=0]" [Register ("canApplyRotation", "()Z", "GetCanApplyRotationHandler:Org.Webrtc.VideoRenderer/ICallbacksInvoker, WebRTCBindings")] bool CanApplyRotation (); // Metadata.xml XPath method reference: path="/api/package[@name='org.webrtc']/interface[@name='VideoRenderer.Callbacks']/method[@name='renderFrame' and count(parameter)=1 and parameter[1][@type='org.webrtc.VideoRenderer.I420Frame']]" [Register ("renderFrame", "(Lorg/webrtc/VideoRenderer$I420Frame;)V", "GetRenderFrame_Lorg_webrtc_VideoRenderer_I420Frame_Handler:Org.Webrtc.VideoRenderer/ICallbacksInvoker, WebRTCBindings")] void RenderFrame (global::Org.Webrtc.VideoRenderer.I420Frame p0); } [global::Android.Runtime.Register ("org/webrtc/VideoRenderer$Callbacks", DoNotGenerateAcw=true)] internal class ICallbacksInvoker : global::Java.Lang.Object, ICallbacks { static IntPtr java_class_ref = JNIEnv.FindClass ("org/webrtc/VideoRenderer$Callbacks"); IntPtr class_ref; public static ICallbacks GetObject (IntPtr handle, JniHandleOwnership transfer) { return global::Java.Lang.Object.GetObject<ICallbacks> (handle, transfer); } static IntPtr Validate (IntPtr handle) { if (!JNIEnv.IsInstanceOf (handle, java_class_ref)) throw new InvalidCastException (string.Format ("Unable to convert instance of type '{0}' to type '{1}'.", JNIEnv.GetClassNameFromInstance (handle), "org.webrtc.VideoRenderer.Callbacks")); return handle; } protected override void Dispose (bool disposing) { if (this.class_ref != IntPtr.Zero) JNIEnv.DeleteGlobalRef (this.class_ref); this.class_ref = IntPtr.Zero; base.Dispose (disposing); } public ICallbacksInvoker (IntPtr handle, JniHandleOwnership transfer) : base (Validate (handle), transfer) { IntPtr local_ref = JNIEnv.GetObjectClass (Handle); this.class_ref = JNIEnv.NewGlobalRef (local_ref); JNIEnv.DeleteLocalRef (local_ref); } protected override IntPtr ThresholdClass { get { return class_ref; } } protected override global::System.Type ThresholdType { get { return typeof (ICallbacksInvoker); } } static Delegate cb_canApplyRotation; #pragma warning disable 0169 static Delegate GetCanApplyRotationHandler () { if (cb_canApplyRotation == null) cb_canApplyRotation = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, bool>) n_CanApplyRotation); return cb_canApplyRotation; } static bool n_CanApplyRotation (IntPtr jnienv, IntPtr native__this) { global::Org.Webrtc.VideoRenderer.ICallbacks __this = global::Java.Lang.Object.GetObject<global::Org.Webrtc.VideoRenderer.ICallbacks> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); return __this.CanApplyRotation (); } #pragma warning restore 0169 IntPtr id_canApplyRotation; public unsafe bool CanApplyRotation () { if (id_canApplyRotation == IntPtr.Zero) id_canApplyRotation = JNIEnv.GetMethodID (class_ref, "canApplyRotation", "()Z"); return JNIEnv.CallBooleanMethod (Handle, id_canApplyRotation); } static Delegate cb_renderFrame_Lorg_webrtc_VideoRenderer_I420Frame_; #pragma warning disable 0169 static Delegate GetRenderFrame_Lorg_webrtc_VideoRenderer_I420Frame_Handler () { if (cb_renderFrame_Lorg_webrtc_VideoRenderer_I420Frame_ == null) cb_renderFrame_Lorg_webrtc_VideoRenderer_I420Frame_ = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, IntPtr>) n_RenderFrame_Lorg_webrtc_VideoRenderer_I420Frame_); return cb_renderFrame_Lorg_webrtc_VideoRenderer_I420Frame_; } static void n_RenderFrame_Lorg_webrtc_VideoRenderer_I420Frame_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0) { global::Org.Webrtc.VideoRenderer.ICallbacks __this = global::Java.Lang.Object.GetObject<global::Org.Webrtc.VideoRenderer.ICallbacks> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); global::Org.Webrtc.VideoRenderer.I420Frame p0 = global::Java.Lang.Object.GetObject<global::Org.Webrtc.VideoRenderer.I420Frame> (native_p0, JniHandleOwnership.DoNotTransfer); __this.RenderFrame (p0); } #pragma warning restore 0169 IntPtr id_renderFrame_Lorg_webrtc_VideoRenderer_I420Frame_; public unsafe void RenderFrame (global::Org.Webrtc.VideoRenderer.I420Frame p0) { if (id_renderFrame_Lorg_webrtc_VideoRenderer_I420Frame_ == IntPtr.Zero) id_renderFrame_Lorg_webrtc_VideoRenderer_I420Frame_ = JNIEnv.GetMethodID (class_ref, "renderFrame", "(Lorg/webrtc/VideoRenderer$I420Frame;)V"); JValue* __args = stackalloc JValue [1]; __args [0] = new JValue (p0); JNIEnv.CallVoidMethod (Handle, id_renderFrame_Lorg_webrtc_VideoRenderer_I420Frame_, __args); } } // Metadata.xml XPath class reference: path="/api/package[@name='org.webrtc']/class[@name='VideoRenderer.I420Frame']" [global::Android.Runtime.Register ("org/webrtc/VideoRenderer$I420Frame", DoNotGenerateAcw=true)] public partial class I420Frame : global::Java.Lang.Object { static IntPtr height_jfieldId; // Metadata.xml XPath field reference: path="/api/package[@name='org.webrtc']/class[@name='VideoRenderer.I420Frame']/field[@name='height']" [Register ("height")] public int Height { get { if (height_jfieldId == IntPtr.Zero) height_jfieldId = JNIEnv.GetFieldID (class_ref, "height", "I"); return JNIEnv.GetIntField (Handle, height_jfieldId); } set { if (height_jfieldId == IntPtr.Zero) height_jfieldId = JNIEnv.GetFieldID (class_ref, "height", "I"); try { JNIEnv.SetField (Handle, height_jfieldId, value); } finally { } } } static IntPtr rotationDegree_jfieldId; // Metadata.xml XPath field reference: path="/api/package[@name='org.webrtc']/class[@name='VideoRenderer.I420Frame']/field[@name='rotationDegree']" [Register ("rotationDegree")] public int RotationDegree { get { if (rotationDegree_jfieldId == IntPtr.Zero) rotationDegree_jfieldId = JNIEnv.GetFieldID (class_ref, "rotationDegree", "I"); return JNIEnv.GetIntField (Handle, rotationDegree_jfieldId); } set { if (rotationDegree_jfieldId == IntPtr.Zero) rotationDegree_jfieldId = JNIEnv.GetFieldID (class_ref, "rotationDegree", "I"); try { JNIEnv.SetField (Handle, rotationDegree_jfieldId, value); } finally { } } } static IntPtr textureId_jfieldId; // Metadata.xml XPath field reference: path="/api/package[@name='org.webrtc']/class[@name='VideoRenderer.I420Frame']/field[@name='textureId']" [Register ("textureId")] public int TextureId { get { if (textureId_jfieldId == IntPtr.Zero) textureId_jfieldId = JNIEnv.GetFieldID (class_ref, "textureId", "I"); return JNIEnv.GetIntField (Handle, textureId_jfieldId); } set { if (textureId_jfieldId == IntPtr.Zero) textureId_jfieldId = JNIEnv.GetFieldID (class_ref, "textureId", "I"); try { JNIEnv.SetField (Handle, textureId_jfieldId, value); } finally { } } } static IntPtr textureObject_jfieldId; // Metadata.xml XPath field reference: path="/api/package[@name='org.webrtc']/class[@name='VideoRenderer.I420Frame']/field[@name='textureObject']" [Register ("textureObject")] public global::Java.Lang.Object TextureObject { get { if (textureObject_jfieldId == IntPtr.Zero) textureObject_jfieldId = JNIEnv.GetFieldID (class_ref, "textureObject", "Ljava/lang/Object;"); IntPtr __ret = JNIEnv.GetObjectField (Handle, textureObject_jfieldId); return global::Java.Lang.Object.GetObject<global::Java.Lang.Object> (__ret, JniHandleOwnership.TransferLocalRef); } set { if (textureObject_jfieldId == IntPtr.Zero) textureObject_jfieldId = JNIEnv.GetFieldID (class_ref, "textureObject", "Ljava/lang/Object;"); IntPtr native_value = JNIEnv.ToLocalJniHandle (value); try { JNIEnv.SetField (Handle, textureObject_jfieldId, native_value); } finally { JNIEnv.DeleteLocalRef (native_value); } } } static IntPtr width_jfieldId; // Metadata.xml XPath field reference: path="/api/package[@name='org.webrtc']/class[@name='VideoRenderer.I420Frame']/field[@name='width']" [Register ("width")] public int Width { get { if (width_jfieldId == IntPtr.Zero) width_jfieldId = JNIEnv.GetFieldID (class_ref, "width", "I"); return JNIEnv.GetIntField (Handle, width_jfieldId); } set { if (width_jfieldId == IntPtr.Zero) width_jfieldId = JNIEnv.GetFieldID (class_ref, "width", "I"); try { JNIEnv.SetField (Handle, width_jfieldId, value); } finally { } } } static IntPtr yuvFrame_jfieldId; // Metadata.xml XPath field reference: path="/api/package[@name='org.webrtc']/class[@name='VideoRenderer.I420Frame']/field[@name='yuvFrame']" [Register ("yuvFrame")] public bool YuvFrame { get { if (yuvFrame_jfieldId == IntPtr.Zero) yuvFrame_jfieldId = JNIEnv.GetFieldID (class_ref, "yuvFrame", "Z"); return JNIEnv.GetBooleanField (Handle, yuvFrame_jfieldId); } set { if (yuvFrame_jfieldId == IntPtr.Zero) yuvFrame_jfieldId = JNIEnv.GetFieldID (class_ref, "yuvFrame", "Z"); try { JNIEnv.SetField (Handle, yuvFrame_jfieldId, value); } finally { } } } static IntPtr yuvPlanes_jfieldId; // Metadata.xml XPath field reference: path="/api/package[@name='org.webrtc']/class[@name='VideoRenderer.I420Frame']/field[@name='yuvPlanes']" [Register ("yuvPlanes")] public IList<Java.Nio.ByteBuffer> YuvPlanes { get { if (yuvPlanes_jfieldId == IntPtr.Zero) yuvPlanes_jfieldId = JNIEnv.GetFieldID (class_ref, "yuvPlanes", "[Ljava/nio/ByteBuffer;"); return JavaArray<global::Java.Nio.ByteBuffer>.FromJniHandle (JNIEnv.GetObjectField (Handle, yuvPlanes_jfieldId), JniHandleOwnership.TransferLocalRef); } set { if (yuvPlanes_jfieldId == IntPtr.Zero) yuvPlanes_jfieldId = JNIEnv.GetFieldID (class_ref, "yuvPlanes", "[Ljava/nio/ByteBuffer;"); IntPtr native_value = JavaArray<global::Java.Nio.ByteBuffer>.ToLocalJniHandle (value); try { JNIEnv.SetField (Handle, yuvPlanes_jfieldId, native_value); } finally { JNIEnv.DeleteLocalRef (native_value); } } } static IntPtr yuvStrides_jfieldId; // Metadata.xml XPath field reference: path="/api/package[@name='org.webrtc']/class[@name='VideoRenderer.I420Frame']/field[@name='yuvStrides']" [Register ("yuvStrides")] public IList<int> YuvStrides { get { if (yuvStrides_jfieldId == IntPtr.Zero) yuvStrides_jfieldId = JNIEnv.GetFieldID (class_ref, "yuvStrides", "[I"); return JavaArray<int>.FromJniHandle (JNIEnv.GetObjectField (Handle, yuvStrides_jfieldId), JniHandleOwnership.TransferLocalRef); } set { if (yuvStrides_jfieldId == IntPtr.Zero) yuvStrides_jfieldId = JNIEnv.GetFieldID (class_ref, "yuvStrides", "[I"); IntPtr native_value = JavaArray<int>.ToLocalJniHandle (value); try { JNIEnv.SetField (Handle, yuvStrides_jfieldId, native_value); } finally { JNIEnv.DeleteLocalRef (native_value); } } } internal static IntPtr java_class_handle; internal static IntPtr class_ref { get { return JNIEnv.FindClass ("org/webrtc/VideoRenderer$I420Frame", ref java_class_handle); } } protected override IntPtr ThresholdClass { get { return class_ref; } } protected override global::System.Type ThresholdType { get { return typeof (I420Frame); } } protected I420Frame (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {} static IntPtr id_ctor_IIIarrayIarrayLjava_nio_ByteBuffer_; // Metadata.xml XPath constructor reference: path="/api/package[@name='org.webrtc']/class[@name='VideoRenderer.I420Frame']/constructor[@name='VideoRenderer.I420Frame' and count(parameter)=5 and parameter[1][@type='int'] and parameter[2][@type='int'] and parameter[3][@type='int'] and parameter[4][@type='int[]'] and parameter[5][@type='java.nio.ByteBuffer[]']]" [Register (".ctor", "(III[I[Ljava/nio/ByteBuffer;)V", "")] public unsafe I420Frame (int p0, int p1, int p2, int[] p3, global::Java.Nio.ByteBuffer[] p4) : base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer) { if (Handle != IntPtr.Zero) return; IntPtr native_p3 = JNIEnv.NewArray (p3); IntPtr native_p4 = JNIEnv.NewArray (p4); try { JValue* __args = stackalloc JValue [5]; __args [0] = new JValue (p0); __args [1] = new JValue (p1); __args [2] = new JValue (p2); __args [3] = new JValue (native_p3); __args [4] = new JValue (native_p4); if (GetType () != typeof (I420Frame)) { SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (GetType (), "(III[I[Ljava/nio/ByteBuffer;)V", __args), JniHandleOwnership.TransferLocalRef); global::Android.Runtime.JNIEnv.FinishCreateInstance (Handle, "(III[I[Ljava/nio/ByteBuffer;)V", __args); return; } if (id_ctor_IIIarrayIarrayLjava_nio_ByteBuffer_ == IntPtr.Zero) id_ctor_IIIarrayIarrayLjava_nio_ByteBuffer_ = JNIEnv.GetMethodID (class_ref, "<init>", "(III[I[Ljava/nio/ByteBuffer;)V"); SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (class_ref, id_ctor_IIIarrayIarrayLjava_nio_ByteBuffer_, __args), JniHandleOwnership.TransferLocalRef); JNIEnv.FinishCreateInstance (Handle, class_ref, id_ctor_IIIarrayIarrayLjava_nio_ByteBuffer_, __args); } finally { if (p3 != null) { JNIEnv.CopyArray (native_p3, p3); JNIEnv.DeleteLocalRef (native_p3); } if (p4 != null) { JNIEnv.CopyArray (native_p4, p4); JNIEnv.DeleteLocalRef (native_p4); } } } static IntPtr id_ctor_IIILjava_lang_Object_I; // Metadata.xml XPath constructor reference: path="/api/package[@name='org.webrtc']/class[@name='VideoRenderer.I420Frame']/constructor[@name='VideoRenderer.I420Frame' and count(parameter)=5 and parameter[1][@type='int'] and parameter[2][@type='int'] and parameter[3][@type='int'] and parameter[4][@type='java.lang.Object'] and parameter[5][@type='int']]" [Register (".ctor", "(IIILjava/lang/Object;I)V", "")] public unsafe I420Frame (int p0, int p1, int p2, global::Java.Lang.Object p3, int p4) : base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer) { if (Handle != IntPtr.Zero) return; try { JValue* __args = stackalloc JValue [5]; __args [0] = new JValue (p0); __args [1] = new JValue (p1); __args [2] = new JValue (p2); __args [3] = new JValue (p3); __args [4] = new JValue (p4); if (GetType () != typeof (I420Frame)) { SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (GetType (), "(IIILjava/lang/Object;I)V", __args), JniHandleOwnership.TransferLocalRef); global::Android.Runtime.JNIEnv.FinishCreateInstance (Handle, "(IIILjava/lang/Object;I)V", __args); return; } if (id_ctor_IIILjava_lang_Object_I == IntPtr.Zero) id_ctor_IIILjava_lang_Object_I = JNIEnv.GetMethodID (class_ref, "<init>", "(IIILjava/lang/Object;I)V"); SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (class_ref, id_ctor_IIILjava_lang_Object_I, __args), JniHandleOwnership.TransferLocalRef); JNIEnv.FinishCreateInstance (Handle, class_ref, id_ctor_IIILjava_lang_Object_I, __args); } finally { } } static Delegate cb_copyFrom_arrayBI; #pragma warning disable 0169 static Delegate GetCopyFrom_arrayBIHandler () { if (cb_copyFrom_arrayBI == null) cb_copyFrom_arrayBI = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr, int, IntPtr>) n_CopyFrom_arrayBI); return cb_copyFrom_arrayBI; } static IntPtr n_CopyFrom_arrayBI (IntPtr jnienv, IntPtr native__this, IntPtr native_p0, int p1) { global::Org.Webrtc.VideoRenderer.I420Frame __this = global::Java.Lang.Object.GetObject<global::Org.Webrtc.VideoRenderer.I420Frame> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); byte[] p0 = (byte[]) JNIEnv.GetArray (native_p0, JniHandleOwnership.DoNotTransfer, typeof (byte)); IntPtr __ret = JNIEnv.ToLocalJniHandle (__this.CopyFrom (p0, p1)); if (p0 != null) JNIEnv.CopyArray (p0, native_p0); return __ret; } #pragma warning restore 0169 static IntPtr id_copyFrom_arrayBI; // Metadata.xml XPath method reference: path="/api/package[@name='org.webrtc']/class[@name='VideoRenderer.I420Frame']/method[@name='copyFrom' and count(parameter)=2 and parameter[1][@type='byte[]'] and parameter[2][@type='int']]" [Register ("copyFrom", "([BI)Lorg/webrtc/VideoRenderer$I420Frame;", "GetCopyFrom_arrayBIHandler")] public virtual unsafe global::Org.Webrtc.VideoRenderer.I420Frame CopyFrom (byte[] p0, int p1) { if (id_copyFrom_arrayBI == IntPtr.Zero) id_copyFrom_arrayBI = JNIEnv.GetMethodID (class_ref, "copyFrom", "([BI)Lorg/webrtc/VideoRenderer$I420Frame;"); IntPtr native_p0 = JNIEnv.NewArray (p0); try { JValue* __args = stackalloc JValue [2]; __args [0] = new JValue (native_p0); __args [1] = new JValue (p1); global::Org.Webrtc.VideoRenderer.I420Frame __ret; if (GetType () == ThresholdType) __ret = global::Java.Lang.Object.GetObject<global::Org.Webrtc.VideoRenderer.I420Frame> (JNIEnv.CallObjectMethod (Handle, id_copyFrom_arrayBI, __args), JniHandleOwnership.TransferLocalRef); else __ret = global::Java.Lang.Object.GetObject<global::Org.Webrtc.VideoRenderer.I420Frame> (JNIEnv.CallNonvirtualObjectMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "copyFrom", "([BI)Lorg/webrtc/VideoRenderer$I420Frame;"), __args), JniHandleOwnership.TransferLocalRef); return __ret; } finally { if (p0 != null) { JNIEnv.CopyArray (native_p0, p0); JNIEnv.DeleteLocalRef (native_p0); } } } static Delegate cb_copyFrom_Lorg_webrtc_VideoRenderer_I420Frame_; #pragma warning disable 0169 static Delegate GetCopyFrom_Lorg_webrtc_VideoRenderer_I420Frame_Handler () { if (cb_copyFrom_Lorg_webrtc_VideoRenderer_I420Frame_ == null) cb_copyFrom_Lorg_webrtc_VideoRenderer_I420Frame_ = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr, IntPtr>) n_CopyFrom_Lorg_webrtc_VideoRenderer_I420Frame_); return cb_copyFrom_Lorg_webrtc_VideoRenderer_I420Frame_; } static IntPtr n_CopyFrom_Lorg_webrtc_VideoRenderer_I420Frame_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0) { global::Org.Webrtc.VideoRenderer.I420Frame __this = global::Java.Lang.Object.GetObject<global::Org.Webrtc.VideoRenderer.I420Frame> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); global::Org.Webrtc.VideoRenderer.I420Frame p0 = global::Java.Lang.Object.GetObject<global::Org.Webrtc.VideoRenderer.I420Frame> (native_p0, JniHandleOwnership.DoNotTransfer); IntPtr __ret = JNIEnv.ToLocalJniHandle (__this.CopyFrom (p0)); return __ret; } #pragma warning restore 0169 static IntPtr id_copyFrom_Lorg_webrtc_VideoRenderer_I420Frame_; // Metadata.xml XPath method reference: path="/api/package[@name='org.webrtc']/class[@name='VideoRenderer.I420Frame']/method[@name='copyFrom' and count(parameter)=1 and parameter[1][@type='org.webrtc.VideoRenderer.I420Frame']]" [Register ("copyFrom", "(Lorg/webrtc/VideoRenderer$I420Frame;)Lorg/webrtc/VideoRenderer$I420Frame;", "GetCopyFrom_Lorg_webrtc_VideoRenderer_I420Frame_Handler")] public virtual unsafe global::Org.Webrtc.VideoRenderer.I420Frame CopyFrom (global::Org.Webrtc.VideoRenderer.I420Frame p0) { if (id_copyFrom_Lorg_webrtc_VideoRenderer_I420Frame_ == IntPtr.Zero) id_copyFrom_Lorg_webrtc_VideoRenderer_I420Frame_ = JNIEnv.GetMethodID (class_ref, "copyFrom", "(Lorg/webrtc/VideoRenderer$I420Frame;)Lorg/webrtc/VideoRenderer$I420Frame;"); try { JValue* __args = stackalloc JValue [1]; __args [0] = new JValue (p0); global::Org.Webrtc.VideoRenderer.I420Frame __ret; if (GetType () == ThresholdType) __ret = global::Java.Lang.Object.GetObject<global::Org.Webrtc.VideoRenderer.I420Frame> (JNIEnv.CallObjectMethod (Handle, id_copyFrom_Lorg_webrtc_VideoRenderer_I420Frame_, __args), JniHandleOwnership.TransferLocalRef); else __ret = global::Java.Lang.Object.GetObject<global::Org.Webrtc.VideoRenderer.I420Frame> (JNIEnv.CallNonvirtualObjectMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "copyFrom", "(Lorg/webrtc/VideoRenderer$I420Frame;)Lorg/webrtc/VideoRenderer$I420Frame;"), __args), JniHandleOwnership.TransferLocalRef); return __ret; } finally { } } static Delegate cb_rotatedHeight; #pragma warning disable 0169 static Delegate GetRotatedHeightHandler () { if (cb_rotatedHeight == null) cb_rotatedHeight = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, int>) n_RotatedHeight); return cb_rotatedHeight; } static int n_RotatedHeight (IntPtr jnienv, IntPtr native__this) { global::Org.Webrtc.VideoRenderer.I420Frame __this = global::Java.Lang.Object.GetObject<global::Org.Webrtc.VideoRenderer.I420Frame> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); return __this.RotatedHeight (); } #pragma warning restore 0169 static IntPtr id_rotatedHeight; // Metadata.xml XPath method reference: path="/api/package[@name='org.webrtc']/class[@name='VideoRenderer.I420Frame']/method[@name='rotatedHeight' and count(parameter)=0]" [Register ("rotatedHeight", "()I", "GetRotatedHeightHandler")] public virtual unsafe int RotatedHeight () { if (id_rotatedHeight == IntPtr.Zero) id_rotatedHeight = JNIEnv.GetMethodID (class_ref, "rotatedHeight", "()I"); try { if (GetType () == ThresholdType) return JNIEnv.CallIntMethod (Handle, id_rotatedHeight); else return JNIEnv.CallNonvirtualIntMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "rotatedHeight", "()I")); } finally { } } static Delegate cb_rotatedWidth; #pragma warning disable 0169 static Delegate GetRotatedWidthHandler () { if (cb_rotatedWidth == null) cb_rotatedWidth = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, int>) n_RotatedWidth); return cb_rotatedWidth; } static int n_RotatedWidth (IntPtr jnienv, IntPtr native__this) { global::Org.Webrtc.VideoRenderer.I420Frame __this = global::Java.Lang.Object.GetObject<global::Org.Webrtc.VideoRenderer.I420Frame> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); return __this.RotatedWidth (); } #pragma warning restore 0169 static IntPtr id_rotatedWidth; // Metadata.xml XPath method reference: path="/api/package[@name='org.webrtc']/class[@name='VideoRenderer.I420Frame']/method[@name='rotatedWidth' and count(parameter)=0]" [Register ("rotatedWidth", "()I", "GetRotatedWidthHandler")] public virtual unsafe int RotatedWidth () { if (id_rotatedWidth == IntPtr.Zero) id_rotatedWidth = JNIEnv.GetMethodID (class_ref, "rotatedWidth", "()I"); try { if (GetType () == ThresholdType) return JNIEnv.CallIntMethod (Handle, id_rotatedWidth); else return JNIEnv.CallNonvirtualIntMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "rotatedWidth", "()I")); } finally { } } } internal static IntPtr java_class_handle; internal static IntPtr class_ref { get { return JNIEnv.FindClass ("org/webrtc/VideoRenderer", ref java_class_handle); } } protected override IntPtr ThresholdClass { get { return class_ref; } } protected override global::System.Type ThresholdType { get { return typeof (VideoRenderer); } } protected VideoRenderer (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {} static IntPtr id_ctor_Lorg_webrtc_VideoRenderer_Callbacks_; // Metadata.xml XPath constructor reference: path="/api/package[@name='org.webrtc']/class[@name='VideoRenderer']/constructor[@name='VideoRenderer' and count(parameter)=1 and parameter[1][@type='org.webrtc.VideoRenderer.Callbacks']]" [Register (".ctor", "(Lorg/webrtc/VideoRenderer$Callbacks;)V", "")] public unsafe VideoRenderer (global::Org.Webrtc.VideoRenderer.ICallbacks p0) : base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer) { if (Handle != IntPtr.Zero) return; try { JValue* __args = stackalloc JValue [1]; __args [0] = new JValue (p0); if (GetType () != typeof (VideoRenderer)) { SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (GetType (), "(Lorg/webrtc/VideoRenderer$Callbacks;)V", __args), JniHandleOwnership.TransferLocalRef); global::Android.Runtime.JNIEnv.FinishCreateInstance (Handle, "(Lorg/webrtc/VideoRenderer$Callbacks;)V", __args); return; } if (id_ctor_Lorg_webrtc_VideoRenderer_Callbacks_ == IntPtr.Zero) id_ctor_Lorg_webrtc_VideoRenderer_Callbacks_ = JNIEnv.GetMethodID (class_ref, "<init>", "(Lorg/webrtc/VideoRenderer$Callbacks;)V"); SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (class_ref, id_ctor_Lorg_webrtc_VideoRenderer_Callbacks_, __args), JniHandleOwnership.TransferLocalRef); JNIEnv.FinishCreateInstance (Handle, class_ref, id_ctor_Lorg_webrtc_VideoRenderer_Callbacks_, __args); } finally { } } static IntPtr id_createGui_II; // Metadata.xml XPath method reference: path="/api/package[@name='org.webrtc']/class[@name='VideoRenderer']/method[@name='createGui' and count(parameter)=2 and parameter[1][@type='int'] and parameter[2][@type='int']]" [Register ("createGui", "(II)Lorg/webrtc/VideoRenderer;", "")] public static unsafe global::Org.Webrtc.VideoRenderer CreateGui (int p0, int p1) { if (id_createGui_II == IntPtr.Zero) id_createGui_II = JNIEnv.GetStaticMethodID (class_ref, "createGui", "(II)Lorg/webrtc/VideoRenderer;"); try { JValue* __args = stackalloc JValue [2]; __args [0] = new JValue (p0); __args [1] = new JValue (p1); return global::Java.Lang.Object.GetObject<global::Org.Webrtc.VideoRenderer> (JNIEnv.CallStaticObjectMethod (class_ref, id_createGui_II, __args), JniHandleOwnership.TransferLocalRef); } finally { } } static Delegate cb_dispose; #pragma warning disable 0169 static Delegate GetDisposeHandler () { if (cb_dispose == null) cb_dispose = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr>) n_Dispose); return cb_dispose; } static void n_Dispose (IntPtr jnienv, IntPtr native__this) { global::Org.Webrtc.VideoRenderer __this = global::Java.Lang.Object.GetObject<global::Org.Webrtc.VideoRenderer> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); __this.Dispose (); } #pragma warning restore 0169 static IntPtr id_dispose; // Metadata.xml XPath method reference: path="/api/package[@name='org.webrtc']/class[@name='VideoRenderer']/method[@name='dispose' and count(parameter)=0]" [Register ("dispose", "()V", "GetDisposeHandler")] public virtual unsafe void Dispose () { if (id_dispose == IntPtr.Zero) id_dispose = JNIEnv.GetMethodID (class_ref, "dispose", "()V"); try { if (GetType () == ThresholdType) JNIEnv.CallVoidMethod (Handle, id_dispose); else JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "dispose", "()V")); } finally { } } } }
/* * Copyright (c) Citrix Systems, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1) Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2) Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using Newtonsoft.Json; namespace XenAPI { /// <summary> /// A set of properties that describe one result element of SR.probe. Result elements and properties can change dynamically based on changes to the the SR.probe input-parameters or the target. /// </summary> public partial class Probe_result : XenObject<Probe_result> { #region Constructors public Probe_result() { } public Probe_result(Dictionary<string, string> configuration, bool complete, Sr_stat sr, Dictionary<string, string> extra_info) { this.configuration = configuration; this.complete = complete; this.sr = sr; this.extra_info = extra_info; } /// <summary> /// Creates a new Probe_result from a Hashtable. /// Note that the fields not contained in the Hashtable /// will be created with their default values. /// </summary> /// <param name="table"></param> public Probe_result(Hashtable table) : this() { UpdateFrom(table); } /// <summary> /// Creates a new Probe_result from a Proxy_Probe_result. /// </summary> /// <param name="proxy"></param> public Probe_result(Proxy_Probe_result proxy) { UpdateFrom(proxy); } #endregion /// <summary> /// Updates each field of this instance with the value of /// the corresponding field of a given Probe_result. /// </summary> public override void UpdateFrom(Probe_result update) { configuration = update.configuration; complete = update.complete; sr = update.sr; extra_info = update.extra_info; } internal void UpdateFrom(Proxy_Probe_result proxy) { configuration = proxy.configuration == null ? null : Maps.convert_from_proxy_string_string(proxy.configuration); complete = (bool)proxy.complete; sr = proxy.sr == null ? null : new Sr_stat(proxy.sr); extra_info = proxy.extra_info == null ? null : Maps.convert_from_proxy_string_string(proxy.extra_info); } public Proxy_Probe_result ToProxy() { Proxy_Probe_result result_ = new Proxy_Probe_result(); result_.configuration = Maps.convert_to_proxy_string_string(configuration); result_.complete = complete; result_.sr = sr == null ? null : sr.ToProxy(); result_.extra_info = Maps.convert_to_proxy_string_string(extra_info); return result_; } /// <summary> /// Given a Hashtable with field-value pairs, it updates the fields of this Probe_result /// with the values listed in the Hashtable. Note that only the fields contained /// in the Hashtable will be updated and the rest will remain the same. /// </summary> /// <param name="table"></param> public void UpdateFrom(Hashtable table) { if (table.ContainsKey("configuration")) configuration = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "configuration")); if (table.ContainsKey("complete")) complete = Marshalling.ParseBool(table, "complete"); if (table.ContainsKey("sr")) sr = (Sr_stat)Marshalling.convertStruct(typeof(Sr_stat), Marshalling.ParseHashTable(table, "sr"));; if (table.ContainsKey("extra_info")) extra_info = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "extra_info")); } public bool DeepEquals(Probe_result other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return Helper.AreEqual2(this._configuration, other._configuration) && Helper.AreEqual2(this._complete, other._complete) && Helper.AreEqual2(this._sr, other._sr) && Helper.AreEqual2(this._extra_info, other._extra_info); } internal static List<Probe_result> ProxyArrayToObjectList(Proxy_Probe_result[] input) { var result = new List<Probe_result>(); foreach (var item in input) result.Add(new Probe_result(item)); return result; } public override string SaveChanges(Session session, string opaqueRef, Probe_result server) { if (opaqueRef == null) { System.Diagnostics.Debug.Assert(false, "Cannot create instances of this type on the server"); return ""; } else { throw new InvalidOperationException("This type has no read/write properties"); } } /// <summary> /// Plugin-specific configuration which describes where and how to locate the storage repository. This may include the physical block device name, a remote NFS server and path or an RBD storage pool. /// Experimental. First published in XenServer 7.5. /// </summary> [JsonConverter(typeof(StringStringMapConverter))] public virtual Dictionary<string, string> configuration { get { return _configuration; } set { if (!Helper.AreEqual(value, _configuration)) { _configuration = value; NotifyPropertyChanged("configuration"); } } } private Dictionary<string, string> _configuration = new Dictionary<string, string>() {}; /// <summary> /// True if this configuration is complete and can be used to call SR.create. False if it requires further iterative calls to SR.probe, to potentially narrow down on a configuration that can be used. /// Experimental. First published in XenServer 7.5. /// </summary> public virtual bool complete { get { return _complete; } set { if (!Helper.AreEqual(value, _complete)) { _complete = value; NotifyPropertyChanged("complete"); } } } private bool _complete; /// <summary> /// Existing SR found for this configuration /// Experimental. First published in XenServer 7.5. /// </summary> public virtual Sr_stat sr { get { return _sr; } set { if (!Helper.AreEqual(value, _sr)) { _sr = value; NotifyPropertyChanged("sr"); } } } private Sr_stat _sr; /// <summary> /// Additional plugin-specific information about this configuration, that might be of use for an API user. This can for example include the LUN or the WWPN. /// Experimental. First published in XenServer 7.5. /// </summary> [JsonConverter(typeof(StringStringMapConverter))] public virtual Dictionary<string, string> extra_info { get { return _extra_info; } set { if (!Helper.AreEqual(value, _extra_info)) { _extra_info = value; NotifyPropertyChanged("extra_info"); } } } private Dictionary<string, string> _extra_info = new Dictionary<string, string>() {}; } }
//--------------------------------------------------------------------- // <copyright file="DataServiceClientFormat.cs" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information. // </copyright> //--------------------------------------------------------------------- namespace Microsoft.OData.Client { using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using Microsoft.OData.Core; using Microsoft.OData.Edm; /// <summary> /// Tracks the user-preferred format which the client should use when making requests. /// </summary> public sealed class DataServiceClientFormat { /// <summary>MIME type for ATOM bodies (http://www.iana.org/assignments/media-types/application/).</summary> private const string MimeApplicationAtom = "application/atom+xml"; /// <summary>MIME type for JSON bodies (implies light in V3, verbose otherwise) (http://www.iana.org/assignments/media-types/application/).</summary> private const string MimeApplicationJson = "application/json"; /// <summary>MIME type for JSON bodies in light mode (http://www.iana.org/assignments/media-types/application/).</summary> private const string MimeApplicationJsonODataLight = "application/json;odata.metadata=minimal"; /// <summary>MIME type for JSON bodies in light mode with all metadata.</summary> private const string MimeApplicationJsonODataLightWithAllMetadata = "application/json;odata.metadata=full"; /// <summary>MIME type for changeset multipart/mixed</summary> private const string MimeMultiPartMixed = "multipart/mixed"; /// <summary>MIME type for XML bodies.</summary> private const string MimeApplicationXml = "application/xml"; /// <summary>Combined accept header value for either 'application/atom+xml' or 'application/xml'.</summary> private const string MimeApplicationAtomOrXml = MimeApplicationAtom + "," + MimeApplicationXml; /// <summary>text for the utf8 encoding</summary> private const string Utf8Encoding = "UTF-8"; /// <summary>The character set the client wants the response to be in.</summary> private const string HttpAcceptCharset = "Accept-Charset"; /// <summary>The context this format instance is associated with.</summary> private readonly DataServiceContext context; /// <summary>The service edm model.</summary> private IEdmModel serviceModel; /// <summary> /// Initializes a new instance of the <see cref="DataServiceClientFormat"/> class. /// </summary> /// <param name="context">DataServiceContext instance associated with this format.</param> internal DataServiceClientFormat(DataServiceContext context) { Debug.Assert(context != null, "Context cannot be null for DataServiceClientFormat"); // On V6.0.2, we change the default format to be json for the client this.ODataFormat = ODataFormat.Json; this.context = context; } /// <summary> /// Gets the current format. Defaults to Atom if nothing else has been specified. /// </summary> public ODataFormat ODataFormat { get; private set; } /// <summary> /// Invoked when using the parameterless UseJson method in order to get the service model. /// </summary> public Func<IEdmModel> LoadServiceModel { get; set; } /// <summary> /// True if the format has been configured to use Atom, otherwise False. /// </summary> internal bool UsingAtom { get { #pragma warning disable 618 return this.ODataFormat == ODataFormat.Atom; #pragma warning restore 618 } } /// <summary> /// Gets the service model. /// </summary> internal IEdmModel ServiceModel { get { if (serviceModel == null && LoadServiceModel != null) { serviceModel = LoadServiceModel(); } return serviceModel; } private set { serviceModel = value; } } /// <summary> /// Indicates that the client should use the efficient JSON format. /// </summary> /// <param name="serviceModel">The model of the service.</param> public void UseJson(IEdmModel serviceModel) { Util.CheckArgumentNull(serviceModel, "serviceModel"); this.ODataFormat = ODataFormat.Json; this.serviceModel = serviceModel; } /// <summary> /// Indicates that the client should use the efficient JSON format. Will invoke the LoadServiceModel delegate property in order to get the required service model. /// </summary> public void UseJson() { if (this.ServiceModel == null) { throw new InvalidOperationException(Strings.DataServiceClientFormat_LoadServiceModelRequired); } this.ODataFormat = ODataFormat.Json; } /// <summary> /// Indicates that the client should use the Atom format. /// </summary> [Obsolete("ATOM support is obsolete.")] public void UseAtom() { this.ODataFormat = ODataFormat.Atom; this.ServiceModel = null; } /// <summary> /// Sets the value of the Accept header to the appropriate value for the current format. /// </summary> /// <param name="headers">The headers to modify.</param> internal void SetRequestAcceptHeader(HeaderCollection headers) { this.SetAcceptHeaderAndCharset(headers, this.ChooseMediaType(/*valueIfUsingAtom*/ MimeApplicationAtomOrXml, false)); } /// <summary> /// Sets the value of the Accept header for a query. /// </summary> /// <param name="headers">The headers to modify.</param> /// <param name="components">The query components for the request.</param> internal void SetRequestAcceptHeaderForQuery(HeaderCollection headers, QueryComponents components) { this.SetAcceptHeaderAndCharset(headers, this.ChooseMediaType(/*valueIfUsingAtom*/ MimeApplicationAtomOrXml, components.HasSelectQueryOption)); } /// <summary> /// Sets the value of the Accept header for a stream request (will set it to '*/*'). /// </summary> /// <param name="headers">The headers to modify.</param> internal void SetRequestAcceptHeaderForStream(HeaderCollection headers) { this.SetAcceptHeaderAndCharset(headers, XmlConstants.MimeAny); } #if !ASTORIA_LIGHT /// <summary> /// Sets the value of the Accept header for a count request (will set it to 'text/plain'). /// </summary> /// <param name="headers">The headers to modify.</param> internal void SetRequestAcceptHeaderForCount(HeaderCollection headers) { this.SetAcceptHeaderAndCharset(headers, XmlConstants.MimeTextPlain); } #endif /// <summary> /// Sets the value of the Accept header for a count request (will set it to 'multipart/mixed'). /// </summary> /// <param name="headers">The headers to modify.</param> internal void SetRequestAcceptHeaderForBatch(HeaderCollection headers) { this.SetAcceptHeaderAndCharset(headers, MimeMultiPartMixed); } /// <summary> /// Sets the value of the ContentType header on the specified entry request to the appropriate value for the current format. /// </summary> /// <param name="headers">Dictionary of request headers.</param> internal void SetRequestContentTypeForEntry(HeaderCollection headers) { this.SetRequestContentTypeHeader(headers, this.ChooseMediaType(/*valueIfUsingAtom*/ MimeApplicationAtom, false)); } /// <summary> /// Sets the value of the Content-Type header a request with operation parameters to the appropriate value for the current format. /// </summary> /// <param name="headers">Dictionary of request headers.</param> internal void SetRequestContentTypeForOperationParameters(HeaderCollection headers) { // Note: There has never been an atom or xml format for parameters. this.SetRequestContentTypeHeader(headers, MimeApplicationJsonODataLight); } /// <summary> /// Sets the value of the ContentType header on the specified links request to the appropriate value for the current format. /// </summary> /// <param name="headers">Dictionary of request headers.</param> internal void SetRequestContentTypeForLinks(HeaderCollection headers) { this.SetRequestContentTypeHeader(headers, this.ChooseMediaType(/*valueIfUsingAtom*/ MimeApplicationXml, false)); } /// <summary> /// Validates that we can write the request format. /// </summary> /// <param name="requestMessage">The request message to get the format from.</param> /// <param name="isParameterPayload">true if the writer is intended to for a parameter payload, false otherwise.</param> internal void ValidateCanWriteRequestFormat(IODataRequestMessage requestMessage, bool isParameterPayload) { string contentType = requestMessage.GetHeader(XmlConstants.HttpContentType); this.ValidateContentType(contentType, isParameterPayload, false /*isResponse*/); } /// <summary> /// Validates that we can read the response format. /// </summary> /// <param name="responseMessage">The response message to get the format from.</param> internal void ValidateCanReadResponseFormat(IODataResponseMessage responseMessage) { string contentType = responseMessage.GetHeader(XmlConstants.HttpContentType); this.ValidateContentType(contentType, false /*isParameterPayload*/, true /*isResponse*/); } /// <summary> /// Throws InvalidOperationException for JSON Light without a model. /// </summary> [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "DataServiceContext", Justification = "The spelling is correct.")] [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "UseJson", Justification = "The spelling is correct.")] private static void ThrowInvalidOperationExceptionForJsonLightWithoutModel() { throw new InvalidOperationException(Strings.DataServiceClientFormat_ValidServiceModelRequiredForJson); } /// <summary> /// Validates that we can read or write a message with the given content-type value. /// </summary> /// <param name="contentType">The content-type value in question.</param> /// <param name="isParameterPayload">true if the writer is intended to for a parameter payload, false otherwise.</param> /// <param name="isResponse">true if content-type header value is from response, false otherwise.</param> private void ValidateContentType(string contentType, bool isParameterPayload, bool isResponse) { if (string.IsNullOrEmpty(contentType)) { return; } // Ideally ODataLib should have a public API to get the ODataFormat from the content-type header. // Unfortunately since that's not available, we will process the content-type value to determine if the format is JSON Light. string mime; ContentTypeUtil.ReadContentType(contentType, out mime); if (MimeApplicationJson.Equals(mime, StringComparison.OrdinalIgnoreCase)) { if (isResponse && this.UsingAtom) { ThrowInvalidOperationExceptionForJsonLightWithoutModel(); } } } /// <summary> /// Sets the request's content type header. /// </summary> /// <param name="headers">Dictionary of request headers.</param> /// <param name="mediaType">content type</param> private void SetRequestContentTypeHeader(HeaderCollection headers, string mediaType) { if (mediaType == MimeApplicationJsonODataLight) { // set the request version to 4.0 headers.SetRequestVersion(Util.ODataVersion4, this.context.MaxProtocolVersionAsVersion); } headers.SetHeaderIfUnset(XmlConstants.HttpContentType, mediaType); } /// <summary> /// Sets the accept header to the given value and the charset to UTF-8. /// </summary> /// <param name="headers">The headers to update.</param> /// <param name="mediaType">The media type for the accept header.</param> [SuppressMessage("Microsoft.Performance", "CA1822", Justification = "If this becomes static, then so do its more visible callers, and we do not want to provide a mix of instance and static methods on this class.")] private void SetAcceptHeaderAndCharset(HeaderCollection headers, string mediaType) { // NOTE: we intentionally do NOT set the DSV header for 'accept' as content-negotiation // is primarily about determining how to respond and not how to interpret the request. // It is entirely valid to send a V1 request and get a V3 response. // (We do set the DSV to 3 for Content-Type above) headers.SetHeaderIfUnset(XmlConstants.HttpAccept, mediaType); headers.SetHeaderIfUnset(HttpAcceptCharset, Utf8Encoding); } /// <summary> /// Chooses between using JSON-Light and the context-dependent media type for when Atom is selected based on the user-selected format. /// </summary> /// <param name="valueIfUsingAtom">The value if using atom.</param> /// <param name="hasSelectQueryOption"> /// Whether or not the select query option is present in the request URI. /// If true, indicates that the client should ask the server to include all metadata in a JSON-Light response. /// </param> /// <returns>The media type to use (either JSON-Light or the provided value)</returns> private string ChooseMediaType(string valueIfUsingAtom, bool hasSelectQueryOption) { if (this.UsingAtom) { return valueIfUsingAtom; } if (hasSelectQueryOption) { return MimeApplicationJsonODataLightWithAllMetadata; } return MimeApplicationJsonODataLight; } } }
using J2N; using J2N.Text; using YAF.Lucene.Net.Support; using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using JCG = J2N.Collections.Generic; namespace YAF.Lucene.Net.Util.Fst { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /// <summary> /// Static helper methods. /// <para/> /// @lucene.experimental /// </summary> public sealed class Util // LUCENENET TODO: Fix naming conflict with containing namespace { private Util() { } /// <summary> /// Looks up the output for this input, or <c>null</c> if the /// input is not accepted. /// </summary> public static T Get<T>(FST<T> fst, Int32sRef input) { // TODO: would be nice not to alloc this on every lookup var arc = fst.GetFirstArc(new FST.Arc<T>()); var fstReader = fst.GetBytesReader(); // Accumulate output as we go T output = fst.Outputs.NoOutput; for (int i = 0; i < input.Length; i++) { if (fst.FindTargetArc(input.Int32s[input.Offset + i], arc, arc, fstReader) == null) { return default(T); } output = fst.Outputs.Add(output, arc.Output); } if (arc.IsFinal) { return fst.Outputs.Add(output, arc.NextFinalOutput); } else { return default(T); } } // TODO: maybe a CharsRef version for BYTE2 /// <summary> /// Looks up the output for this input, or <c>null</c> if the /// input is not accepted /// </summary> public static T Get<T>(FST<T> fst, BytesRef input) { Debug.Assert(fst.InputType == FST.INPUT_TYPE.BYTE1); var fstReader = fst.GetBytesReader(); // TODO: would be nice not to alloc this on every lookup var arc = fst.GetFirstArc(new FST.Arc<T>()); // Accumulate output as we go T output = fst.Outputs.NoOutput; for (int i = 0; i < input.Length; i++) { if (fst.FindTargetArc(input.Bytes[i + input.Offset] & 0xFF, arc, arc, fstReader) == null) { return default(T); } output = fst.Outputs.Add(output, arc.Output); } if (arc.IsFinal) { return fst.Outputs.Add(output, arc.NextFinalOutput); } else { return default(T); } } /// <summary> /// Reverse lookup (lookup by output instead of by input), /// in the special case when your FSTs outputs are /// strictly ascending. This locates the input/output /// pair where the output is equal to the target, and will /// return <c>null</c> if that output does not exist. /// /// <para/>NOTE: this only works with <see cref="T:FST{long?}"/>, only /// works when the outputs are ascending in order with /// the inputs. /// For example, simple ordinals (0, 1, /// 2, ...), or file offets (when appending to a file) /// fit this. /// </summary> public static Int32sRef GetByOutput(FST<long?> fst, long targetOutput) { var @in = fst.GetBytesReader(); // TODO: would be nice not to alloc this on every lookup FST.Arc<long?> arc = fst.GetFirstArc(new FST.Arc<long?>()); FST.Arc<long?> scratchArc = new FST.Arc<long?>(); Int32sRef result = new Int32sRef(); return GetByOutput(fst, targetOutput, @in, arc, scratchArc, result); } /// <summary> /// Expert: like <see cref="Util.GetByOutput(FST{long?}, long)"/> except reusing /// <see cref="FST.BytesReader"/>, initial and scratch Arc, and result. /// </summary> public static Int32sRef GetByOutput(FST<long?> fst, long targetOutput, FST.BytesReader @in, FST.Arc<long?> arc, FST.Arc<long?> scratchArc, Int32sRef result) { long output = arc.Output.Value; int upto = 0; //System.out.println("reverseLookup output=" + targetOutput); while (true) { //System.out.println("loop: output=" + output + " upto=" + upto + " arc=" + arc); if (arc.IsFinal) { long finalOutput = output + arc.NextFinalOutput.Value; //System.out.println(" isFinal finalOutput=" + finalOutput); if (finalOutput == targetOutput) { result.Length = upto; //System.out.println(" found!"); return result; } else if (finalOutput > targetOutput) { //System.out.println(" not found!"); return null; } } if (FST<long?>.TargetHasArcs(arc)) { //System.out.println(" targetHasArcs"); if (result.Int32s.Length == upto) { result.Grow(1 + upto); } fst.ReadFirstRealTargetArc(arc.Target, arc, @in); if (arc.BytesPerArc != 0) { int low = 0; int high = arc.NumArcs - 1; int mid = 0; //System.out.println("bsearch: numArcs=" + arc.numArcs + " target=" + targetOutput + " output=" + output); bool exact = false; while (low <= high) { mid = (int)((uint)(low + high) >> 1); @in.Position = arc.PosArcsStart; @in.SkipBytes(arc.BytesPerArc * mid); var flags = (sbyte)@in.ReadByte(); fst.ReadLabel(@in); long minArcOutput; if ((flags & FST.BIT_ARC_HAS_OUTPUT) != 0) { long arcOutput = fst.Outputs.Read(@in).Value; minArcOutput = output + arcOutput; } else { minArcOutput = output; } if (minArcOutput == targetOutput) { exact = true; break; } else if (minArcOutput < targetOutput) { low = mid + 1; } else { high = mid - 1; } } if (high == -1) { return null; } else if (exact) { arc.ArcIdx = mid - 1; } else { arc.ArcIdx = low - 2; } fst.ReadNextRealArc(arc, @in); result.Int32s[upto++] = arc.Label; output += arc.Output.Value; } else { FST.Arc<long?> prevArc = null; while (true) { //System.out.println(" cycle label=" + arc.label + " output=" + arc.output); // this is the min output we'd hit if we follow // this arc: long minArcOutput = output + arc.Output.Value; if (minArcOutput == targetOutput) { // Recurse on this arc: //System.out.println(" match! break"); output = minArcOutput; result.Int32s[upto++] = arc.Label; break; } else if (minArcOutput > targetOutput) { if (prevArc == null) { // Output doesn't exist return null; } else { // Recurse on previous arc: arc.CopyFrom(prevArc); result.Int32s[upto++] = arc.Label; output += arc.Output.Value; //System.out.println(" recurse prev label=" + (char) arc.label + " output=" + output); break; } } else if (arc.IsLast) { // Recurse on this arc: output = minArcOutput; //System.out.println(" recurse last label=" + (char) arc.label + " output=" + output); result.Int32s[upto++] = arc.Label; break; } else { // Read next arc in this node: prevArc = scratchArc; prevArc.CopyFrom(arc); //System.out.println(" after copy label=" + (char) prevArc.label + " vs " + (char) arc.label); fst.ReadNextRealArc(arc, @in); } } } } else { //System.out.println(" no target arcs; not found!"); return null; } } } /// <summary> /// Represents a path in TopNSearcher. /// <para/> /// @lucene.experimental /// </summary> public class FSTPath<T> { public FST.Arc<T> Arc { get; set; } public T Cost { get; set; } public Int32sRef Input { get; private set; } /// <summary> /// Sole constructor </summary> public FSTPath(T cost, FST.Arc<T> arc, Int32sRef input) { this.Arc = (new FST.Arc<T>()).CopyFrom(arc); this.Cost = cost; this.Input = input; } public override string ToString() { return "input=" + Input + " cost=" + Cost; } } /// <summary> /// Compares first by the provided comparer, and then /// tie breaks by <see cref="FSTPath{T}.Input"/>. /// </summary> private class TieBreakByInputComparer<T> : IComparer<FSTPath<T>> { internal readonly IComparer<T> comparer; public TieBreakByInputComparer(IComparer<T> comparer) { this.comparer = comparer; } public virtual int Compare(FSTPath<T> a, FSTPath<T> b) { int cmp = comparer.Compare(a.Cost, b.Cost); if (cmp == 0) { return a.Input.CompareTo(b.Input); } else { return cmp; } } } /// <summary> /// Utility class to find top N shortest paths from start /// point(s). /// </summary> public class TopNSearcher<T> { private readonly FST<T> fst; private readonly FST.BytesReader bytesReader; private readonly int topN; private readonly int maxQueueDepth; private readonly FST.Arc<T> scratchArc = new FST.Arc<T>(); internal readonly IComparer<T> comparer; internal JCG.SortedSet<FSTPath<T>> queue = null; private object syncLock = new object(); /// <summary> /// Creates an unbounded TopNSearcher </summary> /// <param name="fst"> the <see cref="Lucene.Net.Util.Fst.FST{T}"/> to search on </param> /// <param name="topN"> the number of top scoring entries to retrieve </param> /// <param name="maxQueueDepth"> the maximum size of the queue of possible top entries </param> /// <param name="comparer"> the comparer to select the top N </param> public TopNSearcher(FST<T> fst, int topN, int maxQueueDepth, IComparer<T> comparer) { this.fst = fst; this.bytesReader = fst.GetBytesReader(); this.topN = topN; this.maxQueueDepth = maxQueueDepth; this.comparer = comparer; queue = new JCG.SortedSet<FSTPath<T>>(new TieBreakByInputComparer<T>(comparer)); } /// <summary> /// If back plus this arc is competitive then add to queue: /// </summary> protected virtual void AddIfCompetitive(FSTPath<T> path) { Debug.Assert(queue != null); T cost = fst.Outputs.Add(path.Cost, path.Arc.Output); //System.out.println(" addIfCompetitive queue.size()=" + queue.size() + " path=" + path + " + label=" + path.arc.label); if (queue.Count == maxQueueDepth) { FSTPath<T> bottom = queue.Max; int comp = comparer.Compare(cost, bottom.Cost); if (comp > 0) { // Doesn't compete return; } else if (comp == 0) { // Tie break by alpha sort on the input: path.Input.Grow(path.Input.Length + 1); path.Input.Int32s[path.Input.Length++] = path.Arc.Label; int cmp = bottom.Input.CompareTo(path.Input); path.Input.Length--; // We should never see dups: Debug.Assert(cmp != 0); if (cmp < 0) { // Doesn't compete return; } } // Competes } else { // Queue isn't full yet, so any path we hit competes: } // copy over the current input to the new input // and add the arc.label to the end Int32sRef newInput = new Int32sRef(path.Input.Length + 1); Array.Copy(path.Input.Int32s, 0, newInput.Int32s, 0, path.Input.Length); newInput.Int32s[path.Input.Length] = path.Arc.Label; newInput.Length = path.Input.Length + 1; FSTPath<T> newPath = new FSTPath<T>(cost, path.Arc, newInput); queue.Add(newPath); if (queue.Count == maxQueueDepth + 1) { // LUCENENET NOTE: SortedSet doesn't have atomic operations, // so we need to add some thread safety just in case. // Perhaps it might make sense to wrap SortedSet into a type // that provides thread safety. lock (syncLock) { queue.Remove(queue.Max); } } } /// <summary> /// Adds all leaving arcs, including 'finished' arc, if /// the node is final, from this node into the queue. /// </summary> public virtual void AddStartPaths(FST.Arc<T> node, T startOutput, bool allowEmptyString, Int32sRef input) { // De-dup NO_OUTPUT since it must be a singleton: if (startOutput.Equals(fst.Outputs.NoOutput)) { startOutput = fst.Outputs.NoOutput; } FSTPath<T> path = new FSTPath<T>(startOutput, node, input); fst.ReadFirstTargetArc(node, path.Arc, bytesReader); //System.out.println("add start paths"); // Bootstrap: find the min starting arc while (true) { if (allowEmptyString || path.Arc.Label != FST.END_LABEL) { AddIfCompetitive(path); } if (path.Arc.IsLast) { break; } fst.ReadNextArc(path.Arc, bytesReader); } } public virtual TopResults<T> Search() { IList<Result<T>> results = new JCG.List<Result<T>>(); //System.out.println("search topN=" + topN); var fstReader = fst.GetBytesReader(); T NO_OUTPUT = fst.Outputs.NoOutput; // TODO: we could enable FST to sorting arcs by weight // as it freezes... can easily do this on first pass // (w/o requiring rewrite) // TODO: maybe we should make an FST.INPUT_TYPE.BYTE0.5!? // (nibbles) int rejectCount = 0; // For each top N path: while (results.Count < topN) { //System.out.println("\nfind next path: queue.size=" + queue.size()); FSTPath<T> path; if (queue == null) { // Ran out of paths //System.out.println(" break queue=null"); break; } // Remove top path since we are now going to // pursue it: // LUCENENET NOTE: SortedSet doesn't have atomic operations, // so we need to add some thread safety just in case. // Perhaps it might make sense to wrap SortedSet into a type // that provides thread safety. lock (syncLock) { path = queue.Min; if (path != null) { queue.Remove(path); } } if (path == null) { // There were less than topN paths available: //System.out.println(" break no more paths"); break; } if (path.Arc.Label == FST.END_LABEL) { //System.out.println(" empty string! cost=" + path.cost); // Empty string! path.Input.Length--; results.Add(new Result<T>(path.Input, path.Cost)); continue; } if (results.Count == topN - 1 && maxQueueDepth == topN) { // Last path -- don't bother w/ queue anymore: queue = null; } //System.out.println(" path: " + path); // We take path and find its "0 output completion", // ie, just keep traversing the first arc with // NO_OUTPUT that we can find, since this must lead // to the minimum path that completes from // path.arc. // For each input letter: while (true) { //System.out.println("\n cycle path: " + path); fst.ReadFirstTargetArc(path.Arc, path.Arc, fstReader); // For each arc leaving this node: bool foundZero = false; while (true) { //System.out.println(" arc=" + (char) path.arc.label + " cost=" + path.arc.output); // tricky: instead of comparing output == 0, we must // express it via the comparer compare(output, 0) == 0 if (comparer.Compare(NO_OUTPUT, path.Arc.Output) == 0) { if (queue == null) { foundZero = true; break; } else if (!foundZero) { scratchArc.CopyFrom(path.Arc); foundZero = true; } else { AddIfCompetitive(path); } } else if (queue != null) { AddIfCompetitive(path); } if (path.Arc.IsLast) { break; } fst.ReadNextArc(path.Arc, fstReader); } Debug.Assert(foundZero); if (queue != null) { // TODO: maybe we can save this copyFrom if we // are more clever above... eg on finding the // first NO_OUTPUT arc we'd switch to using // scratchArc path.Arc.CopyFrom(scratchArc); } if (path.Arc.Label == FST.END_LABEL) { // Add final output: //Debug.WriteLine(" done!: " + path); T finalOutput = fst.Outputs.Add(path.Cost, path.Arc.Output); if (AcceptResult(path.Input, finalOutput)) { //Debug.WriteLine(" add result: " + path); results.Add(new Result<T>(path.Input, finalOutput)); } else { rejectCount++; } break; } else { path.Input.Grow(1 + path.Input.Length); path.Input.Int32s[path.Input.Length] = path.Arc.Label; path.Input.Length++; path.Cost = fst.Outputs.Add(path.Cost, path.Arc.Output); } } } return new TopResults<T>(rejectCount + topN <= maxQueueDepth, results); } protected virtual bool AcceptResult(Int32sRef input, T output) { return true; } } /// <summary> /// Holds a single input (<see cref="Int32sRef"/>) + output, returned by /// <see cref="ShortestPaths"/>. /// </summary> public sealed class Result<T> { public Int32sRef Input { get; private set; } public T Output { get; private set; } public Result(Int32sRef input, T output) { this.Input = input; this.Output = output; } } /// <summary> /// Holds the results for a top N search using <see cref="TopNSearcher{T}"/> /// </summary> public sealed class TopResults<T> : IEnumerable<Result<T>> { /// <summary> /// <c>true</c> iff this is a complete result ie. if /// the specified queue size was large enough to find the complete list of results. this might /// be <c>false</c> if the <see cref="TopNSearcher{T}"/> rejected too many results. /// </summary> public bool IsComplete { get; private set; } /// <summary> /// The top results /// </summary> public IList<Result<T>> TopN { get; private set; } internal TopResults(bool isComplete, IList<Result<T>> topN) { this.TopN = topN; this.IsComplete = isComplete; } public IEnumerator<Result<T>> GetEnumerator() { return TopN.GetEnumerator(); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return GetEnumerator(); } } /// <summary> /// Starting from node, find the top N min cost /// completions to a final node. /// </summary> public static TopResults<T> ShortestPaths<T>(FST<T> fst, FST.Arc<T> fromNode, T startOutput, IComparer<T> comparer, int topN, bool allowEmptyString) { // All paths are kept, so we can pass topN for // maxQueueDepth and the pruning is admissible: TopNSearcher<T> searcher = new TopNSearcher<T>(fst, topN, topN, comparer); // since this search is initialized with a single start node // it is okay to start with an empty input path here searcher.AddStartPaths(fromNode, startOutput, allowEmptyString, new Int32sRef()); return searcher.Search(); } /// <summary> /// Dumps an <see cref="FST{T}"/> to a GraphViz's <c>dot</c> language description /// for visualization. Example of use: /// /// <code> /// using (TextWriter sw = new StreamWriter(&quot;out.dot&quot;)) /// { /// Util.ToDot(fst, sw, true, true); /// } /// </code> /// /// and then, from command line: /// /// <code> /// dot -Tpng -o out.png out.dot /// </code> /// /// <para/> /// Note: larger FSTs (a few thousand nodes) won't even /// render, don't bother. If the FST is &gt; 2.1 GB in size /// then this method will throw strange exceptions. /// <para/> /// See also <a href="http://www.graphviz.org/">http://www.graphviz.org/</a>. /// </summary> /// <param name="sameRank"> /// If <c>true</c>, the resulting <c>dot</c> file will try /// to order states in layers of breadth-first traversal. This may /// mess up arcs, but makes the output FST's structure a bit clearer. /// </param> /// <param name="labelStates"> /// If <c>true</c> states will have labels equal to their offsets in their /// binary format. Expands the graph considerably. /// </param> public static void ToDot<T>(FST<T> fst, TextWriter @out, bool sameRank, bool labelStates) { const string expandedNodeColor = "blue"; // this is the start arc in the automaton (from the epsilon state to the first state // with outgoing transitions. FST.Arc<T> startArc = fst.GetFirstArc(new FST.Arc<T>()); // A queue of transitions to consider for the next level. IList<FST.Arc<T>> thisLevelQueue = new JCG.List<FST.Arc<T>>(); // A queue of transitions to consider when processing the next level. IList<FST.Arc<T>> nextLevelQueue = new JCG.List<FST.Arc<T>>(); nextLevelQueue.Add(startArc); //System.out.println("toDot: startArc: " + startArc); // A list of states on the same level (for ranking). IList<int?> sameLevelStates = new JCG.List<int?>(); // A bitset of already seen states (target offset). BitArray seen = new BitArray(32); seen.SafeSet((int)startArc.Target, true); // Shape for states. const string stateShape = "circle"; const string finalStateShape = "doublecircle"; // Emit DOT prologue. @out.Write("digraph FST {\n"); @out.Write(" rankdir = LR; splines=true; concentrate=true; ordering=out; ranksep=2.5; \n"); if (!labelStates) { @out.Write(" node [shape=circle, width=.2, height=.2, style=filled]\n"); } EmitDotState(@out, "initial", "point", "white", ""); T NO_OUTPUT = fst.Outputs.NoOutput; var r = fst.GetBytesReader(); // final FST.Arc<T> scratchArc = new FST.Arc<>(); { string stateColor; if (fst.IsExpandedTarget(startArc, r)) { stateColor = expandedNodeColor; } else { stateColor = null; } bool isFinal; T finalOutput; if (startArc.IsFinal) { isFinal = true; finalOutput = startArc.NextFinalOutput.Equals(NO_OUTPUT) ? default(T) : startArc.NextFinalOutput; } else { isFinal = false; finalOutput = default(T); } EmitDotState(@out, Convert.ToString(startArc.Target), isFinal ? finalStateShape : stateShape, stateColor, finalOutput == null ? "" : fst.Outputs.OutputToString(finalOutput)); } @out.Write(" initial -> " + startArc.Target + "\n"); int level = 0; while (nextLevelQueue.Count > 0) { // we could double buffer here, but it doesn't matter probably. //System.out.println("next level=" + level); thisLevelQueue.AddRange(nextLevelQueue); nextLevelQueue.Clear(); level++; @out.Write("\n // Transitions and states at level: " + level + "\n"); while (thisLevelQueue.Count > 0) { FST.Arc<T> arc = thisLevelQueue[thisLevelQueue.Count - 1]; thisLevelQueue.RemoveAt(thisLevelQueue.Count - 1); //System.out.println(" pop: " + arc); if (FST<T>.TargetHasArcs(arc)) { // scan all target arcs //System.out.println(" readFirstTarget..."); long node = arc.Target; fst.ReadFirstRealTargetArc(arc.Target, arc, r); //System.out.println(" firstTarget: " + arc); while (true) { //System.out.println(" cycle arc=" + arc); // Emit the unseen state and add it to the queue for the next level. if (arc.Target >= 0 && !seen.SafeGet((int)arc.Target)) { /* boolean isFinal = false; T finalOutput = null; fst.readFirstTargetArc(arc, scratchArc); if (scratchArc.isFinal() && fst.targetHasArcs(scratchArc)) { // target is final isFinal = true; finalOutput = scratchArc.output == NO_OUTPUT ? null : scratchArc.output; System.out.println("dot hit final label=" + (char) scratchArc.label); } */ string stateColor; if (fst.IsExpandedTarget(arc, r)) { stateColor = expandedNodeColor; } else { stateColor = null; } string finalOutput; if (arc.NextFinalOutput != null && !arc.NextFinalOutput.Equals(NO_OUTPUT)) { finalOutput = fst.Outputs.OutputToString(arc.NextFinalOutput); } else { finalOutput = ""; } EmitDotState(@out, Convert.ToString(arc.Target), stateShape, stateColor, finalOutput); // To see the node address, use this instead: //emitDotState(out, Integer.toString(arc.target), stateShape, stateColor, String.valueOf(arc.target)); seen.SafeSet((int)arc.Target, true); nextLevelQueue.Add((new FST.Arc<T>()).CopyFrom(arc)); sameLevelStates.Add((int)arc.Target); } string outs; if (!arc.Output.Equals(NO_OUTPUT)) { outs = "/" + fst.Outputs.OutputToString(arc.Output); } else { outs = ""; } if (!FST<T>.TargetHasArcs(arc) && arc.IsFinal && !arc.NextFinalOutput.Equals(NO_OUTPUT)) { // Tricky special case: sometimes, due to // pruning, the builder can [sillily] produce // an FST with an arc into the final end state // (-1) but also with a next final output; in // this case we pull that output up onto this // arc outs = outs + "/[" + fst.Outputs.OutputToString(arc.NextFinalOutput) + "]"; } string arcColor; if (arc.Flag(FST.BIT_TARGET_NEXT)) { arcColor = "red"; } else { arcColor = "black"; } Debug.Assert(arc.Label != FST.END_LABEL); @out.Write(" " + node + " -> " + arc.Target + " [label=\"" + PrintableLabel(arc.Label) + outs + "\"" + (arc.IsFinal ? " style=\"bold\"" : "") + " color=\"" + arcColor + "\"]\n"); // Break the loop if we're on the last arc of this state. if (arc.IsLast) { //System.out.println(" break"); break; } fst.ReadNextRealArc(arc, r); } } } // Emit state ranking information. if (sameRank && sameLevelStates.Count > 1) { @out.Write(" {rank=same; "); foreach (int state in sameLevelStates) { @out.Write(state + "; "); } @out.Write(" }\n"); } sameLevelStates.Clear(); } // Emit terminating state (always there anyway). @out.Write(" -1 [style=filled, color=black, shape=doublecircle, label=\"\"]\n\n"); @out.Write(" {rank=sink; -1 }\n"); @out.Write("}\n"); @out.Flush(); } /// <summary> /// Emit a single state in the <c>dot</c> language. /// </summary> private static void EmitDotState(TextWriter @out, string name, string shape, string color, string label) { @out.Write(" " + name + " [" + (shape != null ? "shape=" + shape : "") + " " + (color != null ? "color=" + color : "") + " " + (label != null ? "label=\"" + label + "\"" : "label=\"\"") + " " + "]\n"); } /// <summary> /// Ensures an arc's label is indeed printable (dot uses US-ASCII). /// </summary> private static string PrintableLabel(int label) { // Any ordinary ascii character, except for " or \, are // printed as the character; else, as a hex string: if (label >= 0x20 && label <= 0x7d && label != 0x22 && label != 0x5c) // " OR \ { return char.ToString((char)label); } return "0x" + label.ToString("x", CultureInfo.InvariantCulture); } /// <summary> /// Just maps each UTF16 unit (char) to the <see cref="int"/>s in an /// <see cref="Int32sRef"/>. /// </summary> public static Int32sRef ToUTF16(string s, Int32sRef scratch) { int charLimit = s.Length; scratch.Offset = 0; scratch.Length = charLimit; scratch.Grow(charLimit); for (int idx = 0; idx < charLimit; idx++) { scratch.Int32s[idx] = (int)s[idx]; } return scratch; } /// <summary> /// Decodes the Unicode codepoints from the provided /// <see cref="ICharSequence"/> and places them in the provided scratch /// <see cref="Int32sRef"/>, which must not be <c>null</c>, returning it. /// </summary> public static Int32sRef ToUTF32(string s, Int32sRef scratch) { int charIdx = 0; int intIdx = 0; int charLimit = s.Length; while (charIdx < charLimit) { scratch.Grow(intIdx + 1); int utf32 = Character.CodePointAt(s, charIdx); scratch.Int32s[intIdx] = utf32; charIdx += Character.CharCount(utf32); intIdx++; } scratch.Length = intIdx; return scratch; } /// <summary> /// Decodes the Unicode codepoints from the provided /// <see cref="T:char[]"/> and places them in the provided scratch /// <see cref="Int32sRef"/>, which must not be <c>null</c>, returning it. /// </summary> public static Int32sRef ToUTF32(char[] s, int offset, int length, Int32sRef scratch) { int charIdx = offset; int intIdx = 0; int charLimit = offset + length; while (charIdx < charLimit) { scratch.Grow(intIdx + 1); int utf32 = Character.CodePointAt(s, charIdx, charLimit); scratch.Int32s[intIdx] = utf32; charIdx += Character.CharCount(utf32); intIdx++; } scratch.Length = intIdx; return scratch; } /// <summary> /// Just takes unsigned byte values from the <see cref="BytesRef"/> and /// converts into an <see cref="Int32sRef"/>. /// <para/> /// NOTE: This was toIntsRef() in Lucene /// </summary> public static Int32sRef ToInt32sRef(BytesRef input, Int32sRef scratch) { scratch.Grow(input.Length); for (int i = 0; i < input.Length; i++) { scratch.Int32s[i] = input.Bytes[i + input.Offset] & 0xFF; } scratch.Length = input.Length; return scratch; } /// <summary> /// Just converts <see cref="Int32sRef"/> to <see cref="BytesRef"/>; you must ensure the /// <see cref="int"/> values fit into a <see cref="byte"/>. /// </summary> public static BytesRef ToBytesRef(Int32sRef input, BytesRef scratch) { scratch.Grow(input.Length); for (int i = 0; i < input.Length; i++) { int value = input.Int32s[i + input.Offset]; // NOTE: we allow -128 to 255 Debug.Assert(value >= sbyte.MinValue && value <= 255, "value " + value + " doesn't fit into byte"); scratch.Bytes[i] = (byte)value; } scratch.Length = input.Length; return scratch; } // Uncomment for debugging: /* public static <T> void dotToFile(FST<T> fst, String filePath) throws IOException { Writer w = new OutputStreamWriter(new FileOutputStream(filePath)); toDot(fst, w, true, true); w.Dispose(); } */ /// <summary> /// Reads the first arc greater or equal that the given label into the provided /// arc in place and returns it iff found, otherwise return <c>null</c>. /// </summary> /// <param name="label"> the label to ceil on </param> /// <param name="fst"> the fst to operate on </param> /// <param name="follow"> the arc to follow reading the label from </param> /// <param name="arc"> the arc to read into in place </param> /// <param name="in"> the fst's <see cref="FST.BytesReader"/> </param> public static FST.Arc<T> ReadCeilArc<T>(int label, FST<T> fst, FST.Arc<T> follow, FST.Arc<T> arc, FST.BytesReader @in) { // TODO maybe this is a useful in the FST class - we could simplify some other code like FSTEnum? if (label == FST.END_LABEL) { if (follow.IsFinal) { if (follow.Target <= 0) { arc.Flags = (sbyte)FST.BIT_LAST_ARC; } else { arc.Flags = 0; // NOTE: nextArc is a node (not an address!) in this case: arc.NextArc = follow.Target; arc.Node = follow.Target; } arc.Output = follow.NextFinalOutput; arc.Label = FST.END_LABEL; return arc; } else { return null; } } if (!FST<T>.TargetHasArcs(follow)) { return null; } fst.ReadFirstTargetArc(follow, arc, @in); if (arc.BytesPerArc != 0 && arc.Label != FST.END_LABEL) { // Arcs are fixed array -- use binary search to find // the target. int low = arc.ArcIdx; int high = arc.NumArcs - 1; int mid = 0; // System.out.println("do arc array low=" + low + " high=" + high + // " targetLabel=" + targetLabel); while (low <= high) { mid = (int)((uint)(low + high) >> 1); @in.Position = arc.PosArcsStart; @in.SkipBytes(arc.BytesPerArc * mid + 1); int midLabel = fst.ReadLabel(@in); int cmp = midLabel - label; // System.out.println(" cycle low=" + low + " high=" + high + " mid=" + // mid + " midLabel=" + midLabel + " cmp=" + cmp); if (cmp < 0) { low = mid + 1; } else if (cmp > 0) { high = mid - 1; } else { arc.ArcIdx = mid - 1; return fst.ReadNextRealArc(arc, @in); } } if (low == arc.NumArcs) { // DEAD END! return null; } arc.ArcIdx = (low > high ? high : low); return fst.ReadNextRealArc(arc, @in); } // Linear scan fst.ReadFirstRealTargetArc(follow.Target, arc, @in); while (true) { // System.out.println(" non-bs cycle"); // TODO: we should fix this code to not have to create // object for the output of every arc we scan... only // for the matching arc, if found if (arc.Label >= label) { // System.out.println(" found!"); return arc; } else if (arc.IsLast) { return null; } else { fst.ReadNextRealArc(arc, @in); } } } } }
/* * 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; namespace SF.Snowball { public class SnowballProgram { /// <summary> Get the current string.</summary> virtual public System.String GetCurrent() { return current.ToString(); } protected internal SnowballProgram() { current = new System.Text.StringBuilder(); SetCurrent(""); } /// <summary> Set the current string.</summary> public virtual void SetCurrent(System.String value_Renamed) { //// current.Replace(current.ToString(0, current.Length - 0), value_Renamed, 0, current.Length - 0); current.Remove(0, current.Length); current.Append(value_Renamed); cursor = 0; limit = current.Length; limit_backward = 0; bra = cursor; ket = limit; } // current string protected internal System.Text.StringBuilder current; protected internal int cursor; protected internal int limit; protected internal int limit_backward; protected internal int bra; protected internal int ket; protected internal virtual void copy_from(SnowballProgram other) { current = other.current; cursor = other.cursor; limit = other.limit; limit_backward = other.limit_backward; bra = other.bra; ket = other.ket; } protected internal virtual bool in_grouping(char[] s, int min, int max) { if (cursor >= limit) return false; char ch = current[cursor]; if (ch > max || ch < min) return false; ch -= (char) (min); if ((s[ch >> 3] & (0x1 << (ch & 0x7))) == 0) return false; cursor++; return true; } protected internal virtual bool in_grouping_b(char[] s, int min, int max) { if (cursor <= limit_backward) return false; char ch = current[cursor - 1]; if (ch > max || ch < min) return false; ch -= (char) (min); if ((s[ch >> 3] & (0x1 << (ch & 0x7))) == 0) return false; cursor--; return true; } protected internal virtual bool out_grouping(char[] s, int min, int max) { if (cursor >= limit) return false; char ch = current[cursor]; if (ch > max || ch < min) { cursor++; return true; } ch -= (char) (min); if ((s[ch >> 3] & (0x1 << (ch & 0x7))) == 0) { cursor++; return true; } return false; } protected internal virtual bool out_grouping_b(char[] s, int min, int max) { if (cursor <= limit_backward) return false; char ch = current[cursor - 1]; if (ch > max || ch < min) { cursor--; return true; } ch -= (char) (min); if ((s[ch >> 3] & (0x1 << (ch & 0x7))) == 0) { cursor--; return true; } return false; } protected internal virtual bool in_range(int min, int max) { if (cursor >= limit) return false; char ch = current[cursor]; if (ch > max || ch < min) return false; cursor++; return true; } protected internal virtual bool in_range_b(int min, int max) { if (cursor <= limit_backward) return false; char ch = current[cursor - 1]; if (ch > max || ch < min) return false; cursor--; return true; } protected internal virtual bool out_range(int min, int max) { if (cursor >= limit) return false; char ch = current[cursor]; if (!(ch > max || ch < min)) return false; cursor++; return true; } protected internal virtual bool out_range_b(int min, int max) { if (cursor <= limit_backward) return false; char ch = current[cursor - 1]; if (!(ch > max || ch < min)) return false; cursor--; return true; } protected internal virtual bool eq_s(int s_size, System.String s) { if (limit - cursor < s_size) return false; int i; for (i = 0; i != s_size; i++) { if (current[cursor + i] != s[i]) return false; } cursor += s_size; return true; } protected internal virtual bool eq_s_b(int s_size, System.String s) { if (cursor - limit_backward < s_size) return false; int i; for (i = 0; i != s_size; i++) { if (current[cursor - s_size + i] != s[i]) return false; } cursor -= s_size; return true; } protected internal virtual bool eq_v(System.Text.StringBuilder s) { return eq_s(s.Length, s.ToString()); } protected internal virtual bool eq_v_b(System.Text.StringBuilder s) { return eq_s_b(s.Length, s.ToString()); } protected internal virtual int find_among(Among[] v, int v_size) { int i = 0; int j = v_size; int c = cursor; int l = limit; int common_i = 0; int common_j = 0; bool first_key_inspected = false; while (true) { int k = i + ((j - i) >> 1); int diff = 0; int common = common_i < common_j?common_i:common_j; // smaller Among w = v[k]; int i2; for (i2 = common; i2 < w.s_size; i2++) { if (c + common == l) { diff = - 1; break; } diff = current[c + common] - w.s[i2]; if (diff != 0) break; common++; } if (diff < 0) { j = k; common_j = common; } else { i = k; common_i = common; } if (j - i <= 1) { if (i > 0) break; // v->s has been inspected if (j == i) break; // only one item in v // - but now we need to go round once more to get // v->s inspected. This looks messy, but is actually // the optimal approach. if (first_key_inspected) break; first_key_inspected = true; } } while (true) { Among w = v[i]; if (common_i >= w.s_size) { cursor = c + w.s_size; if (w.method == null) return w.result; bool res; try { System.Object resobj = w.method.Invoke(w.methodobject, (System.Object[]) new System.Object[0]); // {{Aroush}} UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Object.toString' may return a different value. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1043_3"' res = resobj.ToString().Equals("true"); } catch (System.Reflection.TargetInvocationException e) { res = false; // FIXME - debug message } catch (System.UnauthorizedAccessException e) { res = false; // FIXME - debug message } cursor = c + w.s_size; if (res) return w.result; } i = w.substring_i; if (i < 0) return 0; } } // find_among_b is for backwards processing. Same comments apply protected internal virtual int find_among_b(Among[] v, int v_size) { int i = 0; int j = v_size; int c = cursor; int lb = limit_backward; int common_i = 0; int common_j = 0; bool first_key_inspected = false; while (true) { int k = i + ((j - i) >> 1); int diff = 0; int common = common_i < common_j?common_i:common_j; Among w = v[k]; int i2; for (i2 = w.s_size - 1 - common; i2 >= 0; i2--) { if (c - common == lb) { diff = - 1; break; } diff = current[c - 1 - common] - w.s[i2]; if (diff != 0) break; common++; } if (diff < 0) { j = k; common_j = common; } else { i = k; common_i = common; } if (j - i <= 1) { if (i > 0) break; if (j == i) break; if (first_key_inspected) break; first_key_inspected = true; } } while (true) { Among w = v[i]; if (common_i >= w.s_size) { cursor = c - w.s_size; if (w.method == null) return w.result; bool res; try { System.Object resobj = w.method.Invoke(w.methodobject, (System.Object[]) new System.Object[0]); // {{Aroush}} UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Object.toString' may return a different value. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1043_3"' res = resobj.ToString().Equals("true"); } catch (System.Reflection.TargetInvocationException e) { res = false; // FIXME - debug message } catch (System.UnauthorizedAccessException e) { res = false; // FIXME - debug message } cursor = c - w.s_size; if (res) return w.result; } i = w.substring_i; if (i < 0) return 0; } } /* to replace chars between c_bra and c_ket in current by the * chars in s. */ protected internal virtual int replace_s(int c_bra, int c_ket, System.String s) { int adjustment = s.Length - (c_ket - c_bra); if (current.Length > bra) current.Replace(current.ToString(bra, ket - bra), s, bra, ket - bra); else current.Append(s); limit += adjustment; if (cursor >= c_ket) cursor += adjustment; else if (cursor > c_bra) cursor = c_bra; return adjustment; } protected internal virtual void slice_check() { if (bra < 0 || bra > ket || ket > limit || limit > current.Length) // this line could be removed { System.Console.Error.WriteLine("faulty slice operation"); // FIXME: report error somehow. /* fprintf(stderr, "faulty slice operation:\n"); debug(z, -1, 0); exit(1); */ } } protected internal virtual void slice_from(System.String s) { slice_check(); replace_s(bra, ket, s); } protected internal virtual void slice_from(System.Text.StringBuilder s) { slice_from(s.ToString()); } protected internal virtual void slice_del() { slice_from(""); } protected internal virtual void insert(int c_bra, int c_ket, System.String s) { int adjustment = replace_s(c_bra, c_ket, s); if (c_bra <= bra) bra += adjustment; if (c_bra <= ket) ket += adjustment; } protected internal virtual void insert(int c_bra, int c_ket, System.Text.StringBuilder s) { insert(c_bra, c_ket, s.ToString()); } /* Copy the slice into the supplied StringBuffer */ protected internal virtual System.Text.StringBuilder slice_to(System.Text.StringBuilder s) { slice_check(); int len = ket - bra; //// s.Replace(s.ToString(0, s.Length - 0), current.ToString(bra, ket), 0, s.Length - 0); s.Remove(0, s.Length); s.Append(current.ToString(bra, ket)); return s; } protected internal virtual System.Text.StringBuilder assign_to(System.Text.StringBuilder s) { //// s.Replace(s.ToString(0, s.Length - 0), current.ToString(0, limit), 0, s.Length - 0); s.Remove(0, s.Length); s.Append(current.ToString(0, limit)); return s; } /* extern void debug(struct SN_env * z, int number, int line_count) { int i; int limit = SIZE(z->p); //if (number >= 0) printf("%3d (line %4d): '", number, line_count); if (number >= 0) printf("%3d (line %4d): [%d]'", number, line_count,limit); for (i = 0; i <= limit; i++) { if (z->lb == i) printf("{"); if (z->bra == i) printf("["); if (z->c == i) printf("|"); if (z->ket == i) printf("]"); if (z->l == i) printf("}"); if (i < limit) { int ch = z->p[i]; if (ch == 0) ch = '#'; printf("%c", ch); } } printf("'\n"); }*/ } }
// Copyright (c) 2007 James Newton-King // // 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; #if NET40 using System.Numerics; #endif using System.Text; using OpenGamingLibrary.Json.Converters; using Xunit; using OpenGamingLibrary.Json.Linq; using System.IO; using System.Linq; using OpenGamingLibrary.Json.Utilities; using OpenGamingLibrary.Xunit.Extensions; namespace OpenGamingLibrary.Json.Test.Linq { public class JTokenTests : TestFixtureBase { [Fact] public void ReadFrom() { JObject o = (JObject)JToken.ReadFrom(new JsonTextReader(new StringReader("{'pie':true}"))); Assert.Equal(true, (bool)o["pie"]); JArray a = (JArray)JToken.ReadFrom(new JsonTextReader(new StringReader("[1,2,3]"))); Assert.Equal(1, (int)a[0]); Assert.Equal(2, (int)a[1]); Assert.Equal(3, (int)a[2]); JsonReader reader = new JsonTextReader(new StringReader("{'pie':true}")); reader.Read(); reader.Read(); JProperty p = (JProperty)JToken.ReadFrom(reader); Assert.Equal("pie", p.Name); Assert.Equal(true, (bool)p.Value); JConstructor c = (JConstructor)JToken.ReadFrom(new JsonTextReader(new StringReader("new Date(1)"))); Assert.Equal("Date", c.Name); Assert.True(JToken.DeepEquals(new JValue(1), c.Values().ElementAt(0))); JValue v; v = (JValue)JToken.ReadFrom(new JsonTextReader(new StringReader(@"""stringvalue"""))); Assert.Equal("stringvalue", (string)v); v = (JValue)JToken.ReadFrom(new JsonTextReader(new StringReader(@"1"))); Assert.Equal(1, (int)v); v = (JValue)JToken.ReadFrom(new JsonTextReader(new StringReader(@"1.1"))); Assert.Equal(1.1, (double)v); #if !NET20 v = (JValue)JToken.ReadFrom(new JsonTextReader(new StringReader(@"""1970-01-01T00:00:00+12:31""")) { DateParseHandling = DateParseHandling.DateTimeOffset }); Assert.Equal(typeof(DateTimeOffset), v.Value.GetType()); Assert.Equal(new DateTimeOffset(DateTimeUtils.InitialJavaScriptDateTicks, new TimeSpan(12, 31, 0)), v.Value); #endif } [Fact] public void Load() { JObject o = (JObject)JToken.Load(new JsonTextReader(new StringReader("{'pie':true}"))); Assert.Equal(true, (bool)o["pie"]); } [Fact] public void Parse() { JObject o = (JObject)JToken.Parse("{'pie':true}"); Assert.Equal(true, (bool)o["pie"]); } [Fact] public void Parent() { JArray v = new JArray(new JConstructor("TestConstructor"), new JValue(new DateTime(2000, 12, 20))); Assert.Equal(null, v.Parent); JObject o = new JObject( new JProperty("Test1", v), new JProperty("Test2", "Test2Value"), new JProperty("Test3", "Test3Value"), new JProperty("Test4", null) ); Assert.Equal(o.Property("Test1"), v.Parent); JProperty p = new JProperty("NewProperty", v); // existing value should still have same parent Assert.Equal(o.Property("Test1"), v.Parent); // new value should be cloned Assert.NotSame(p.Value, v); Assert.Equal((DateTime)((JValue)p.Value[1]).Value, (DateTime)((JValue)v[1]).Value); Assert.Equal(v, o["Test1"]); Assert.Equal(null, o.Parent); JProperty o1 = new JProperty("O1", o); Assert.Equal(o, o1.Value); Assert.NotEqual(null, o.Parent); JProperty o2 = new JProperty("O2", o); Assert.NotSame(o1.Value, o2.Value); Assert.Equal(o1.Value.Children().Count(), o2.Value.Children().Count()); Assert.Equal(false, JToken.DeepEquals(o1, o2)); Assert.Equal(true, JToken.DeepEquals(o1.Value, o2.Value)); } [Fact] public void Next() { JArray a = new JArray( 5, 6, new JArray(7, 8), new JArray(9, 10) ); JToken next = a[0].Next; Assert.Equal(6, (int)next); next = next.Next; Assert.True(JToken.DeepEquals(new JArray(7, 8), next)); next = next.Next; Assert.True(JToken.DeepEquals(new JArray(9, 10), next)); next = next.Next; Assert.Null(next); } [Fact] public void Previous() { JArray a = new JArray( 5, 6, new JArray(7, 8), new JArray(9, 10) ); JToken previous = a[3].Previous; Assert.True(JToken.DeepEquals(new JArray(7, 8), previous)); previous = previous.Previous; Assert.Equal(6, (int)previous); previous = previous.Previous; Assert.Equal(5, (int)previous); previous = previous.Previous; Assert.Null(previous); } [Fact] public void Children() { JArray a = new JArray( 5, new JArray(1), new JArray(1, 2), new JArray(1, 2, 3) ); Assert.Equal(4, a.Count()); Assert.Equal(3, a.Children<JArray>().Count()); } [Fact] public void BeforeAfter() { JArray a = new JArray( 5, new JArray(1, 2, 3), new JArray(1, 2, 3), new JArray(1, 2, 3) ); Assert.Equal(5, (int)a[1].Previous); Assert.Equal(2, a[2].BeforeSelf().Count()); //Assert.Equal(2, a[2].AfterSelf().Count()); } [Fact] public void Casting() { Assert.Equal(1L, (long)(new JValue(1))); Assert.Equal(2L, (long)new JArray(1, 2, 3)[1]); Assert.Equal(new DateTime(2000, 12, 20), (DateTime)new JValue(new DateTime(2000, 12, 20))); #if !NET20 Assert.Equal(new DateTimeOffset(2000, 12, 20, 0, 0, 0, TimeSpan.Zero), (DateTimeOffset)new JValue(new DateTime(2000, 12, 20, 0, 0, 0, DateTimeKind.Utc))); Assert.Equal(new DateTimeOffset(2000, 12, 20, 23, 50, 10, TimeSpan.Zero), (DateTimeOffset)new JValue(new DateTimeOffset(2000, 12, 20, 23, 50, 10, TimeSpan.Zero))); Assert.Equal(null, (DateTimeOffset?)new JValue((DateTimeOffset?)null)); Assert.Equal(null, (DateTimeOffset?)(JValue)null); #endif Assert.Equal(true, (bool)new JValue(true)); Assert.Equal(true, (bool?)new JValue(true)); Assert.Equal(null, (bool?)((JValue)null)); Assert.Equal(null, (bool?)JValue.CreateNull()); Assert.Equal(10, (long)new JValue(10)); Assert.Equal(null, (long?)new JValue((long?)null)); Assert.Equal(null, (long?)(JValue)null); Assert.Equal(null, (int?)new JValue((int?)null)); Assert.Equal(null, (int?)(JValue)null); Assert.Equal(null, (DateTime?)new JValue((DateTime?)null)); Assert.Equal(null, (DateTime?)(JValue)null); Assert.Equal(null, (short?)new JValue((short?)null)); Assert.Equal(null, (short?)(JValue)null); Assert.Equal(null, (float?)new JValue((float?)null)); Assert.Equal(null, (float?)(JValue)null); Assert.Equal(null, (double?)new JValue((double?)null)); Assert.Equal(null, (double?)(JValue)null); Assert.Equal(null, (decimal?)new JValue((decimal?)null)); Assert.Equal(null, (decimal?)(JValue)null); Assert.Equal(null, (uint?)new JValue((uint?)null)); Assert.Equal(null, (uint?)(JValue)null); Assert.Equal(null, (sbyte?)new JValue((sbyte?)null)); Assert.Equal(null, (sbyte?)(JValue)null); Assert.Equal(null, (byte?)new JValue((byte?)null)); Assert.Equal(null, (byte?)(JValue)null); Assert.Equal(null, (ulong?)new JValue((ulong?)null)); Assert.Equal(null, (ulong?)(JValue)null); Assert.Equal(null, (uint?)new JValue((uint?)null)); Assert.Equal(null, (uint?)(JValue)null); Assert.Equal(11.1f, (float)new JValue(11.1)); Assert.Equal(float.MinValue, (float)new JValue(float.MinValue)); Assert.Equal(1.1, (double)new JValue(1.1)); Assert.Equal(uint.MaxValue, (uint)new JValue(uint.MaxValue)); Assert.Equal(ulong.MaxValue, (ulong)new JValue(ulong.MaxValue)); Assert.Equal(ulong.MaxValue, (ulong)new JProperty("Test", new JValue(ulong.MaxValue))); Assert.Equal(null, (string)new JValue((string)null)); Assert.Equal(5m, (decimal)(new JValue(5L))); Assert.Equal(5m, (decimal?)(new JValue(5L))); Assert.Equal(5f, (float)(new JValue(5L))); Assert.Equal(5f, (float)(new JValue(5m))); Assert.Equal(5f, (float?)(new JValue(5m))); Assert.Equal(5, (byte)(new JValue(5))); Assert.Equal(null, (sbyte?)JValue.CreateNull()); Assert.Equal("1", (string)(new JValue(1))); Assert.Equal("1", (string)(new JValue(1.0))); Assert.Equal("1.0", (string)(new JValue(1.0m))); Assert.Equal("True", (string)(new JValue(true))); Assert.Equal(null, (string)(JValue.CreateNull())); Assert.Equal(null, (string)(JValue)null); Assert.Equal("12/12/2000 12:12:12", (string)(new JValue(new DateTime(2000, 12, 12, 12, 12, 12, DateTimeKind.Utc)))); #if !NET20 Assert.Equal("12/12/2000 12:12:12 +00:00", (string)(new JValue(new DateTimeOffset(2000, 12, 12, 12, 12, 12, TimeSpan.Zero)))); #endif Assert.Equal(true, (bool)(new JValue(1))); Assert.Equal(true, (bool)(new JValue(1.0))); Assert.Equal(true, (bool)(new JValue("true"))); Assert.Equal(true, (bool)(new JValue(true))); Assert.Equal(1, (int)(new JValue(1))); Assert.Equal(1, (int)(new JValue(1.0))); Assert.Equal(1, (int)(new JValue("1"))); Assert.Equal(1, (int)(new JValue(true))); Assert.Equal(1m, (decimal)(new JValue(1))); Assert.Equal(1m, (decimal)(new JValue(1.0))); Assert.Equal(1m, (decimal)(new JValue("1"))); Assert.Equal(1m, (decimal)(new JValue(true))); Assert.Equal(TimeSpan.FromMinutes(1), (TimeSpan)(new JValue(TimeSpan.FromMinutes(1)))); Assert.Equal("00:01:00", (string)(new JValue(TimeSpan.FromMinutes(1)))); Assert.Equal(TimeSpan.FromMinutes(1), (TimeSpan)(new JValue("00:01:00"))); Assert.Equal("46efe013-b56a-4e83-99e4-4dce7678a5bc", (string)(new JValue(new Guid("46EFE013-B56A-4E83-99E4-4DCE7678A5BC")))); Assert.Equal("http://www.google.com/", (string)(new JValue(new Uri("http://www.google.com")))); Assert.Equal(new Guid("46EFE013-B56A-4E83-99E4-4DCE7678A5BC"), (Guid)(new JValue("46EFE013-B56A-4E83-99E4-4DCE7678A5BC"))); Assert.Equal(new Guid("46EFE013-B56A-4E83-99E4-4DCE7678A5BC"), (Guid)(new JValue(new Guid("46EFE013-B56A-4E83-99E4-4DCE7678A5BC")))); Assert.Equal(new Uri("http://www.google.com"), (Uri)(new JValue("http://www.google.com"))); Assert.Equal(new Uri("http://www.google.com"), (Uri)(new JValue(new Uri("http://www.google.com")))); Assert.Equal(null, (Uri)(JValue.CreateNull())); Assert.Equal(Convert.ToBase64String(Encoding.UTF8.GetBytes("hi")), (string)(new JValue(Encoding.UTF8.GetBytes("hi")))); Assert.Equal((byte[])Encoding.UTF8.GetBytes("hi"), (byte[])(new JValue(Convert.ToBase64String(Encoding.UTF8.GetBytes("hi"))))); Assert.Equal(new Guid("46EFE013-B56A-4E83-99E4-4DCE7678A5BC"), (Guid)(new JValue(new Guid("46EFE013-B56A-4E83-99E4-4DCE7678A5BC").ToByteArray()))); Assert.Equal(new Guid("46EFE013-B56A-4E83-99E4-4DCE7678A5BC"), (Guid?)(new JValue(new Guid("46EFE013-B56A-4E83-99E4-4DCE7678A5BC").ToByteArray()))); Assert.Equal((sbyte?)1, (sbyte?)(new JValue((short?)1))); Assert.Equal(null, (Uri)(JValue)null); Assert.Equal(null, (int?)(JValue)null); Assert.Equal(null, (uint?)(JValue)null); Assert.Equal(null, (Guid?)(JValue)null); Assert.Equal(null, (TimeSpan?)(JValue)null); Assert.Equal(null, (byte[])(JValue)null); Assert.Equal(null, (bool?)(JValue)null); Assert.Equal(null, (char?)(JValue)null); Assert.Equal(null, (DateTime?)(JValue)null); #if !NET20 Assert.Equal(null, (DateTimeOffset?)(JValue)null); #endif Assert.Equal(null, (short?)(JValue)null); Assert.Equal(null, (ushort?)(JValue)null); Assert.Equal(null, (byte?)(JValue)null); Assert.Equal(null, (byte?)(JValue)null); Assert.Equal(null, (sbyte?)(JValue)null); Assert.Equal(null, (sbyte?)(JValue)null); Assert.Equal(null, (long?)(JValue)null); Assert.Equal(null, (ulong?)(JValue)null); Assert.Equal(null, (double?)(JValue)null); Assert.Equal(null, (float?)(JValue)null); byte[] data = new byte[0]; Assert.Equal(data, (byte[])(new JValue(data))); Assert.Equal(5, (int)(new JValue(StringComparison.OrdinalIgnoreCase))); #if NET40 string bigIntegerText = "1234567899999999999999999999999999999999999999999999999999999999999990"; Assert.Equal(BigInteger.Parse(bigIntegerText), (new JValue(BigInteger.Parse(bigIntegerText))).Value); Assert.Equal(BigInteger.Parse(bigIntegerText), (new JValue(bigIntegerText)).ToObject<BigInteger>()); Assert.Equal(new BigInteger(long.MaxValue), (new JValue(long.MaxValue)).ToObject<BigInteger>()); Assert.Equal(new BigInteger(4.5d), (new JValue((4.5d))).ToObject<BigInteger>()); Assert.Equal(new BigInteger(4.5f), (new JValue((4.5f))).ToObject<BigInteger>()); Assert.Equal(new BigInteger(byte.MaxValue), (new JValue(byte.MaxValue)).ToObject<BigInteger>()); Assert.Equal(new BigInteger(123), (new JValue(123)).ToObject<BigInteger>()); Assert.Equal(new BigInteger(123), (new JValue(123)).ToObject<BigInteger>()); Assert.Equal(null, (JValue.CreateNull()).ToObject<BigInteger>()); byte[] intData = BigInteger.Parse(bigIntegerText).ToByteArray(); Assert.Equal(BigInteger.Parse(bigIntegerText), (new JValue(intData)).ToObject<BigInteger>()); Assert.Equal(4.0d, (double)(new JValue(new BigInteger(4.5d)))); Assert.Equal(true, (bool)(new JValue(new BigInteger(1)))); Assert.Equal(long.MaxValue, (long)(new JValue(new BigInteger(long.MaxValue)))); Assert.Equal(long.MaxValue, (long)(new JValue(new BigInteger(new byte[] { 255, 255, 255, 255, 255, 255, 255, 127 })))); Assert.Equal("9223372036854775807", (string)(new JValue(new BigInteger(long.MaxValue)))); intData = (byte[])(new JValue(new BigInteger(long.MaxValue))); Assert.Equal(new byte[] { 255, 255, 255, 255, 255, 255, 255, 127 }, intData); #endif } [Fact] public void FailedCasting() { AssertException.Throws<ArgumentException>(() => { var i = (DateTime)new JValue(true); }, "Can not convert Boolean to DateTime."); AssertException.Throws<ArgumentException>(() => { var i = (DateTime)new JValue(1); }, "Can not convert Integer to DateTime."); AssertException.Throws<ArgumentException>(() => { var i = (DateTime)new JValue(1.1); }, "Can not convert Float to DateTime."); AssertException.Throws<ArgumentException>(() => { var i = (DateTime)new JValue(1.1m); }, "Can not convert Float to DateTime."); AssertException.Throws<ArgumentException>(() => { var i = (DateTime)new JValue(TimeSpan.Zero); }, "Can not convert TimeSpan to DateTime."); AssertException.Throws<ArgumentException>(() => { var i = (DateTime)new JValue(new Uri("http://www.google.com")); }, "Can not convert Uri to DateTime."); AssertException.Throws<ArgumentException>(() => { var i = (DateTime)JValue.CreateNull(); }, "Can not convert Null to DateTime."); AssertException.Throws<ArgumentException>(() => { var i = (DateTime)new JValue(Guid.NewGuid()); }, "Can not convert Guid to DateTime."); AssertException.Throws<ArgumentException>(() => { var i = (Uri)new JValue(true); }, "Can not convert Boolean to Uri."); AssertException.Throws<ArgumentException>(() => { var i = (Uri)new JValue(1); }, "Can not convert Integer to Uri."); AssertException.Throws<ArgumentException>(() => { var i = (Uri)new JValue(1.1); }, "Can not convert Float to Uri."); AssertException.Throws<ArgumentException>(() => { var i = (Uri)new JValue(1.1m); }, "Can not convert Float to Uri."); AssertException.Throws<ArgumentException>(() => { var i = (Uri)new JValue(TimeSpan.Zero); }, "Can not convert TimeSpan to Uri."); AssertException.Throws<ArgumentException>(() => { var i = (Uri)new JValue(Guid.NewGuid()); }, "Can not convert Guid to Uri."); AssertException.Throws<ArgumentException>(() => { var i = (Uri)new JValue(DateTime.Now); }, "Can not convert Date to Uri."); #if !NET20 AssertException.Throws<ArgumentException>(() => { var i = (Uri)new JValue(DateTimeOffset.Now); }, "Can not convert Date to Uri."); #endif AssertException.Throws<ArgumentException>(() => { var i = (TimeSpan)new JValue(true); }, "Can not convert Boolean to TimeSpan."); AssertException.Throws<ArgumentException>(() => { var i = (TimeSpan)new JValue(1); }, "Can not convert Integer to TimeSpan."); AssertException.Throws<ArgumentException>(() => { var i = (TimeSpan)new JValue(1.1); }, "Can not convert Float to TimeSpan."); AssertException.Throws<ArgumentException>(() => { var i = (TimeSpan)new JValue(1.1m); }, "Can not convert Float to TimeSpan."); AssertException.Throws<ArgumentException>(() => { var i = (TimeSpan)JValue.CreateNull(); }, "Can not convert Null to TimeSpan."); AssertException.Throws<ArgumentException>(() => { var i = (TimeSpan)new JValue(Guid.NewGuid()); }, "Can not convert Guid to TimeSpan."); AssertException.Throws<ArgumentException>(() => { var i = (TimeSpan)new JValue(DateTime.Now); }, "Can not convert Date to TimeSpan."); #if !NET20 AssertException.Throws<ArgumentException>(() => { var i = (TimeSpan)new JValue(DateTimeOffset.Now); }, "Can not convert Date to TimeSpan."); #endif AssertException.Throws<ArgumentException>(() => { var i = (TimeSpan)new JValue(new Uri("http://www.google.com")); }, "Can not convert Uri to TimeSpan."); AssertException.Throws<ArgumentException>(() => { var i = (Guid)new JValue(true); }, "Can not convert Boolean to Guid."); AssertException.Throws<ArgumentException>(() => { var i = (Guid)new JValue(1); }, "Can not convert Integer to Guid."); AssertException.Throws<ArgumentException>(() => { var i = (Guid)new JValue(1.1); }, "Can not convert Float to Guid."); AssertException.Throws<ArgumentException>(() => { var i = (Guid)new JValue(1.1m); }, "Can not convert Float to Guid."); AssertException.Throws<ArgumentException>(() => { var i = (Guid)JValue.CreateNull(); }, "Can not convert Null to Guid."); AssertException.Throws<ArgumentException>(() => { var i = (Guid)new JValue(DateTime.Now); }, "Can not convert Date to Guid."); #if !NET20 AssertException.Throws<ArgumentException>(() => { var i = (Guid)new JValue(DateTimeOffset.Now); }, "Can not convert Date to Guid."); #endif AssertException.Throws<ArgumentException>(() => { var i = (Guid)new JValue(TimeSpan.FromMinutes(1)); }, "Can not convert TimeSpan to Guid."); AssertException.Throws<ArgumentException>(() => { var i = (Guid)new JValue(new Uri("http://www.google.com")); }, "Can not convert Uri to Guid."); #if !NET20 AssertException.Throws<ArgumentException>(() => { var i = (DateTimeOffset)new JValue(true); }, "Can not convert Boolean to DateTimeOffset."); #endif AssertException.Throws<ArgumentException>(() => { var i = (Uri)new JValue(true); }, "Can not convert Boolean to Uri."); #if NET40 AssertException.Throws<ArgumentException>(() => { var i = (new JValue(new Uri("http://www.google.com"))).ToObject<BigInteger>(); }, "Can not convert Uri to BigInteger."); AssertException.Throws<ArgumentException>(() => { var i = (JValue.CreateNull()).ToObject<BigInteger>(); }, "Can not convert Null to BigInteger."); AssertException.Throws<ArgumentException>(() => { var i = (new JValue(Guid.NewGuid())).ToObject<BigInteger>(); }, "Can not convert Guid to BigInteger."); AssertException.Throws<ArgumentException>(() => { var i = (new JValue(Guid.NewGuid())).ToObject<BigInteger>(); }, "Can not convert Guid to BigInteger."); #endif AssertException.Throws<ArgumentException>(() => { var i = (sbyte?)new JValue(DateTime.Now); }, "Can not convert Date to SByte."); AssertException.Throws<ArgumentException>(() => { var i = (sbyte)new JValue(DateTime.Now); }, "Can not convert Date to SByte."); AssertException.Throws<ArgumentException>(() => { var i = (new JValue("Ordinal1")).ToObject<StringComparison>(); }, "Could not convert 'Ordinal1' to StringComparison."); AssertException.Throws<ArgumentException>(() => { var i = (new JValue("Ordinal1")).ToObject<StringComparison?>(); }, "Could not convert 'Ordinal1' to StringComparison."); } [Fact] public void ToObject() { #if NET40 Assert.Equal((BigInteger)1, (new JValue(1).ToObject(typeof(BigInteger)))); Assert.Equal((BigInteger)1, (new JValue(1).ToObject(typeof(BigInteger)))); Assert.Equal((BigInteger)null, (JValue.CreateNull().ToObject(typeof(BigInteger)))); #endif Assert.Equal((ushort)1, (new JValue(1).ToObject(typeof(ushort)))); Assert.Equal((ushort)1, (new JValue(1).ToObject(typeof(ushort?)))); Assert.Equal((uint)1L, (new JValue(1).ToObject(typeof(uint)))); Assert.Equal((uint)1L, (new JValue(1).ToObject(typeof(uint?)))); Assert.Equal((ulong)1L, (new JValue(1).ToObject(typeof(ulong)))); Assert.Equal((ulong)1L, (new JValue(1).ToObject(typeof(ulong?)))); Assert.Equal((sbyte)1L, (new JValue(1).ToObject(typeof(sbyte)))); Assert.Equal((sbyte)1L, (new JValue(1).ToObject(typeof(sbyte?)))); Assert.Equal((byte)1L, (new JValue(1).ToObject(typeof(byte)))); Assert.Equal((byte)1L, (new JValue(1).ToObject(typeof(byte?)))); Assert.Equal((short)1L, (new JValue(1).ToObject(typeof(short)))); Assert.Equal((short)1L, (new JValue(1).ToObject(typeof(short?)))); Assert.Equal(1, (new JValue(1).ToObject(typeof(int)))); Assert.Equal(1, (new JValue(1).ToObject(typeof(int?)))); Assert.Equal(1L, (new JValue(1).ToObject(typeof(long)))); Assert.Equal(1L, (new JValue(1).ToObject(typeof(long?)))); Assert.Equal((float)1, (new JValue(1.0).ToObject(typeof(float)))); Assert.Equal((float)1, (new JValue(1.0).ToObject(typeof(float?)))); Assert.Equal((double)1, (new JValue(1.0).ToObject(typeof(double)))); Assert.Equal((double)1, (new JValue(1.0).ToObject(typeof(double?)))); Assert.Equal(1m, (new JValue(1).ToObject(typeof(decimal)))); Assert.Equal(1m, (new JValue(1).ToObject(typeof(decimal?)))); Assert.Equal(true, (new JValue(true).ToObject(typeof(bool)))); Assert.Equal(true, (new JValue(true).ToObject(typeof(bool?)))); Assert.Equal('b', (new JValue('b').ToObject(typeof(char)))); Assert.Equal('b', (new JValue('b').ToObject(typeof(char?)))); Assert.Equal(TimeSpan.MaxValue, (new JValue(TimeSpan.MaxValue).ToObject(typeof(TimeSpan)))); Assert.Equal(TimeSpan.MaxValue, (new JValue(TimeSpan.MaxValue).ToObject(typeof(TimeSpan?)))); Assert.Equal(DateTime.MaxValue, (new JValue(DateTime.MaxValue).ToObject(typeof(DateTime)))); Assert.Equal(DateTime.MaxValue, (new JValue(DateTime.MaxValue).ToObject(typeof(DateTime?)))); #if !NET20 Assert.Equal(DateTimeOffset.MaxValue, (new JValue(DateTimeOffset.MaxValue).ToObject(typeof(DateTimeOffset)))); Assert.Equal(DateTimeOffset.MaxValue, (new JValue(DateTimeOffset.MaxValue).ToObject(typeof(DateTimeOffset?)))); #endif Assert.Equal("b", (new JValue("b").ToObject(typeof(string)))); Assert.Equal(new Guid("A34B2080-B5F0-488E-834D-45D44ECB9E5C"), (new JValue(new Guid("A34B2080-B5F0-488E-834D-45D44ECB9E5C")).ToObject(typeof(Guid)))); Assert.Equal(new Guid("A34B2080-B5F0-488E-834D-45D44ECB9E5C"), (new JValue(new Guid("A34B2080-B5F0-488E-834D-45D44ECB9E5C")).ToObject(typeof(Guid?)))); Assert.Equal(new Uri("http://www.google.com/"), (new JValue(new Uri("http://www.google.com/")).ToObject(typeof(Uri)))); Assert.Equal(StringComparison.Ordinal, (new JValue("Ordinal").ToObject(typeof(StringComparison)))); Assert.Equal(StringComparison.Ordinal, (new JValue("Ordinal").ToObject(typeof(StringComparison?)))); Assert.Equal(null, (JValue.CreateNull().ToObject(typeof(StringComparison?)))); } [Fact] public void ImplicitCastingTo() { Assert.True(JToken.DeepEquals(new JValue(new DateTime(2000, 12, 20)), (JValue)new DateTime(2000, 12, 20))); Assert.True(JToken.DeepEquals(new JValue(new DateTimeOffset(2000, 12, 20, 23, 50, 10, TimeSpan.Zero)), (JValue)new DateTimeOffset(2000, 12, 20, 23, 50, 10, TimeSpan.Zero))); Assert.True(JToken.DeepEquals(new JValue((DateTimeOffset?)null), (JValue)(DateTimeOffset?)null)); #if NET40 // had to remove implicit casting to avoid user reference to System.Numerics.dll Assert.True(JToken.DeepEquals(new JValue(new BigInteger(1)), new JValue(new BigInteger(1)))); Assert.True(JToken.DeepEquals(new JValue((BigInteger)null), new JValue((BigInteger)null))); #endif Assert.True(JToken.DeepEquals(new JValue(true), (JValue)true)); Assert.True(JToken.DeepEquals(new JValue(true), (JValue)true)); Assert.True(JToken.DeepEquals(new JValue(true), (JValue)(bool?)true)); Assert.True(JToken.DeepEquals(new JValue((bool?)null), (JValue)(bool?)null)); Assert.True(JToken.DeepEquals(new JValue(10), (JValue)10)); Assert.True(JToken.DeepEquals(new JValue((long?)null), (JValue)(long?)null)); Assert.True(JToken.DeepEquals(new JValue((DateTime?)null), (JValue)(DateTime?)null)); Assert.True(JToken.DeepEquals(new JValue(long.MaxValue), (JValue)long.MaxValue)); Assert.True(JToken.DeepEquals(new JValue((int?)null), (JValue)(int?)null)); Assert.True(JToken.DeepEquals(new JValue((short?)null), (JValue)(short?)null)); Assert.True(JToken.DeepEquals(new JValue((double?)null), (JValue)(double?)null)); Assert.True(JToken.DeepEquals(new JValue((uint?)null), (JValue)(uint?)null)); Assert.True(JToken.DeepEquals(new JValue((decimal?)null), (JValue)(decimal?)null)); Assert.True(JToken.DeepEquals(new JValue((ulong?)null), (JValue)(ulong?)null)); Assert.True(JToken.DeepEquals(new JValue((sbyte?)null), (JValue)(sbyte?)null)); Assert.True(JToken.DeepEquals(new JValue((sbyte)1), (JValue)(sbyte)1)); Assert.True(JToken.DeepEquals(new JValue((byte?)null), (JValue)(byte?)null)); Assert.True(JToken.DeepEquals(new JValue((byte)1), (JValue)(byte)1)); Assert.True(JToken.DeepEquals(new JValue((ushort?)null), (JValue)(ushort?)null)); Assert.True(JToken.DeepEquals(new JValue(short.MaxValue), (JValue)short.MaxValue)); Assert.True(JToken.DeepEquals(new JValue(ushort.MaxValue), (JValue)ushort.MaxValue)); Assert.True(JToken.DeepEquals(new JValue(11.1f), (JValue)11.1f)); Assert.True(JToken.DeepEquals(new JValue(float.MinValue), (JValue)float.MinValue)); Assert.True(JToken.DeepEquals(new JValue(double.MinValue), (JValue)double.MinValue)); Assert.True(JToken.DeepEquals(new JValue(uint.MaxValue), (JValue)uint.MaxValue)); Assert.True(JToken.DeepEquals(new JValue(ulong.MaxValue), (JValue)ulong.MaxValue)); Assert.True(JToken.DeepEquals(new JValue(ulong.MinValue), (JValue)ulong.MinValue)); Assert.True(JToken.DeepEquals(new JValue((string)null), (JValue)(string)null)); Assert.True(JToken.DeepEquals(new JValue((DateTime?)null), (JValue)(DateTime?)null)); Assert.True(JToken.DeepEquals(new JValue(decimal.MaxValue), (JValue)decimal.MaxValue)); Assert.True(JToken.DeepEquals(new JValue(decimal.MaxValue), (JValue)(decimal?)decimal.MaxValue)); Assert.True(JToken.DeepEquals(new JValue(decimal.MinValue), (JValue)decimal.MinValue)); Assert.True(JToken.DeepEquals(new JValue(float.MaxValue), (JValue)(float?)float.MaxValue)); Assert.True(JToken.DeepEquals(new JValue(double.MaxValue), (JValue)(double?)double.MaxValue)); Assert.True(JToken.DeepEquals(JValue.CreateNull(), (JValue)(double?)null)); Assert.False(JToken.DeepEquals(new JValue(true), (JValue)(bool?)null)); Assert.False(JToken.DeepEquals(JValue.CreateNull(), (JValue)(object)null)); byte[] emptyData = new byte[0]; Assert.True(JToken.DeepEquals(new JValue(emptyData), (JValue)emptyData)); Assert.False(JToken.DeepEquals(new JValue(emptyData), (JValue)new byte[1])); Assert.True(JToken.DeepEquals(new JValue(Encoding.UTF8.GetBytes("Hi")), (JValue)Encoding.UTF8.GetBytes("Hi"))); Assert.True(JToken.DeepEquals(new JValue(TimeSpan.FromMinutes(1)), (JValue)TimeSpan.FromMinutes(1))); Assert.True(JToken.DeepEquals(JValue.CreateNull(), (JValue)(TimeSpan?)null)); Assert.True(JToken.DeepEquals(new JValue(TimeSpan.FromMinutes(1)), (JValue)(TimeSpan?)TimeSpan.FromMinutes(1))); Assert.True(JToken.DeepEquals(new JValue(new Guid("46EFE013-B56A-4E83-99E4-4DCE7678A5BC")), (JValue)new Guid("46EFE013-B56A-4E83-99E4-4DCE7678A5BC"))); Assert.True(JToken.DeepEquals(new JValue(new Uri("http://www.google.com")), (JValue)new Uri("http://www.google.com"))); Assert.True(JToken.DeepEquals(JValue.CreateNull(), (JValue)(Uri)null)); Assert.True(JToken.DeepEquals(JValue.CreateNull(), (JValue)(Guid?)null)); } [Fact] public void Root() { JArray a = new JArray( 5, 6, new JArray(7, 8), new JArray(9, 10) ); Assert.Equal(a, a.Root); Assert.Equal(a, a[0].Root); Assert.Equal(a, ((JArray)a[2])[0].Root); } [Fact] public void Remove() { JToken t; JArray a = new JArray( 5, 6, new JArray(7, 8), new JArray(9, 10) ); a[0].Remove(); Assert.Equal(6, (int)a[0]); a[1].Remove(); Assert.Equal(6, (int)a[0]); Assert.True(JToken.DeepEquals(new JArray(9, 10), a[1])); Assert.Equal(2, a.Count()); t = a[1]; t.Remove(); Assert.Equal(6, (int)a[0]); Assert.Null(t.Next); Assert.Null(t.Previous); Assert.Null(t.Parent); t = a[0]; t.Remove(); Assert.Equal(0, a.Count()); Assert.Null(t.Next); Assert.Null(t.Previous); Assert.Null(t.Parent); } [Fact] public void AfterSelf() { JArray a = new JArray( 5, new JArray(1), new JArray(1, 2), new JArray(1, 2, 3) ); JToken t = a[1]; List<JToken> afterTokens = t.AfterSelf().ToList(); Assert.Equal(2, afterTokens.Count); Assert.True(JToken.DeepEquals(new JArray(1, 2), afterTokens[0])); Assert.True(JToken.DeepEquals(new JArray(1, 2, 3), afterTokens[1])); } [Fact] public void BeforeSelf() { JArray a = new JArray( 5, new JArray(1), new JArray(1, 2), new JArray(1, 2, 3) ); JToken t = a[2]; List<JToken> beforeTokens = t.BeforeSelf().ToList(); Assert.Equal(2, beforeTokens.Count); Assert.True(JToken.DeepEquals(new JValue(5), beforeTokens[0])); Assert.True(JToken.DeepEquals(new JArray(1), beforeTokens[1])); } [Fact] public void HasValues() { JArray a = new JArray( 5, new JArray(1), new JArray(1, 2), new JArray(1, 2, 3) ); Assert.True(a.HasValues); } [Fact] public void Ancestors() { JArray a = new JArray( 5, new JArray(1), new JArray(1, 2), new JArray(1, 2, 3) ); JToken t = a[1][0]; List<JToken> ancestors = t.Ancestors().ToList(); Assert.Equal(2, ancestors.Count()); Assert.Equal(a[1], ancestors[0]); Assert.Equal(a, ancestors[1]); } [Fact] public void Descendants() { JArray a = new JArray( 5, new JArray(1), new JArray(1, 2), new JArray(1, 2, 3) ); List<JToken> descendants = a.Descendants().ToList(); Assert.Equal(10, descendants.Count()); Assert.Equal(5, (int)descendants[0]); Assert.True(JToken.DeepEquals(new JArray(1, 2, 3), descendants[descendants.Count - 4])); Assert.Equal(1, (int)descendants[descendants.Count - 3]); Assert.Equal(2, (int)descendants[descendants.Count - 2]); Assert.Equal(3, (int)descendants[descendants.Count - 1]); } [Fact] public void CreateWriter() { JArray a = new JArray( 5, new JArray(1), new JArray(1, 2), new JArray(1, 2, 3) ); JsonWriter writer = a.CreateWriter(); Assert.NotNull(writer); Assert.Equal(4, a.Count()); writer.WriteValue("String"); Assert.Equal(5, a.Count()); Assert.Equal("String", (string)a[4]); writer.WriteStartObject(); writer.WritePropertyName("Property"); writer.WriteValue("PropertyValue"); writer.WriteEnd(); Assert.Equal(6, a.Count()); Assert.True(JToken.DeepEquals(new JObject(new JProperty("Property", "PropertyValue")), a[5])); } [Fact] public void AddFirst() { JArray a = new JArray( 5, new JArray(1), new JArray(1, 2), new JArray(1, 2, 3) ); a.AddFirst("First"); Assert.Equal("First", (string)a[0]); Assert.Equal(a, a[0].Parent); Assert.Equal(a[1], a[0].Next); Assert.Equal(5, a.Count()); a.AddFirst("NewFirst"); Assert.Equal("NewFirst", (string)a[0]); Assert.Equal(a, a[0].Parent); Assert.Equal(a[1], a[0].Next); Assert.Equal(6, a.Count()); Assert.Equal(a[0], a[0].Next.Previous); } [Fact] public void RemoveAll() { JArray a = new JArray( 5, new JArray(1), new JArray(1, 2), new JArray(1, 2, 3) ); JToken first = a.First; Assert.Equal(5, (int)first); a.RemoveAll(); Assert.Equal(0, a.Count()); Assert.Null(first.Parent); Assert.Null(first.Next); } [Fact] public void AddPropertyToArray() { AssertException.Throws<ArgumentException>(() => { JArray a = new JArray(); a.Add(new JProperty("PropertyName")); }, "Can not add OpenGamingLibrary.Json.Linq.JProperty to OpenGamingLibrary.Json.Linq.JArray."); } [Fact] public void AddValueToObject() { AssertException.Throws<ArgumentException>(() => { JObject o = new JObject(); o.Add(5); }, "Can not add OpenGamingLibrary.Json.Linq.JValue to OpenGamingLibrary.Json.Linq.JObject."); } [Fact] public void Replace() { JArray a = new JArray( 5, new JArray(1), new JArray(1, 2), new JArray(1, 2, 3) ); a[0].Replace(new JValue(int.MaxValue)); Assert.Equal(int.MaxValue, (int)a[0]); Assert.Equal(4, a.Count()); a[1][0].Replace(new JValue("Test")); Assert.Equal("Test", (string)a[1][0]); a[2].Replace(new JValue(int.MaxValue)); Assert.Equal(int.MaxValue, (int)a[2]); Assert.Equal(4, a.Count()); Assert.True(JToken.DeepEquals(new JArray(int.MaxValue, new JArray("Test"), int.MaxValue, new JArray(1, 2, 3)), a)); } [Fact] public void ToStringWithConverters() { JArray a = new JArray( new JValue(new DateTime(2009, 2, 15, 0, 0, 0, DateTimeKind.Utc)) ); string json = a.ToString(Formatting.Indented, new IsoDateTimeConverter()); StringAssert.Equal(@"[ ""2009-02-15T00:00:00Z"" ]", json); json = JsonConvert.SerializeObject(a, new IsoDateTimeConverter()); Assert.Equal(@"[""2009-02-15T00:00:00Z""]", json); } [Fact] public void ToStringWithNoIndenting() { JArray a = new JArray( new JValue(new DateTime(2009, 2, 15, 0, 0, 0, DateTimeKind.Utc)) ); string json = a.ToString(Formatting.None, new IsoDateTimeConverter()); Assert.Equal(@"[""2009-02-15T00:00:00Z""]", json); } [Fact] public void AddAfterSelf() { JArray a = new JArray( 5, new JArray(1), new JArray(1, 2), new JArray(1, 2, 3) ); a[1].AddAfterSelf("pie"); Assert.Equal(5, (int)a[0]); Assert.Equal(1, a[1].Count()); Assert.Equal("pie", (string)a[2]); Assert.Equal(5, a.Count()); a[4].AddAfterSelf("lastpie"); Assert.Equal("lastpie", (string)a[5]); Assert.Equal("lastpie", (string)a.Last); } [Fact] public void AddBeforeSelf() { JArray a = new JArray( 5, new JArray(1), new JArray(1, 2), new JArray(1, 2, 3) ); a[1].AddBeforeSelf("pie"); Assert.Equal(5, (int)a[0]); Assert.Equal("pie", (string)a[1]); Assert.Equal(a, a[1].Parent); Assert.Equal(a[2], a[1].Next); Assert.Equal(5, a.Count()); a[0].AddBeforeSelf("firstpie"); Assert.Equal("firstpie", (string)a[0]); Assert.Equal(5, (int)a[1]); Assert.Equal("pie", (string)a[2]); Assert.Equal(a, a[0].Parent); Assert.Equal(a[1], a[0].Next); Assert.Equal(6, a.Count()); a.Last.AddBeforeSelf("secondlastpie"); Assert.Equal("secondlastpie", (string)a[5]); Assert.Equal(7, a.Count()); } [Fact] public void DeepClone() { JArray a = new JArray( 5, new JArray(1), new JArray(1, 2), new JArray(1, 2, 3), new JObject( new JProperty("First", new JValue(Encoding.UTF8.GetBytes("Hi"))), new JProperty("Second", 1), new JProperty("Third", null), new JProperty("Fourth", new JConstructor("Date", 12345)), new JProperty("Fifth", double.PositiveInfinity), new JProperty("Sixth", double.NaN) ) ); JArray a2 = (JArray)a.DeepClone(); Console.WriteLine(a2.ToString(Formatting.Indented)); Assert.True(a.DeepEquals(a2)); } #if !(NETFX_CORE || PORTABLE || ASPNETCORE50 || PORTABLE40) [Fact] public void Clone() { JArray a = new JArray( 5, new JArray(1), new JArray(1, 2), new JArray(1, 2, 3), new JObject( new JProperty("First", new JValue(Encoding.UTF8.GetBytes("Hi"))), new JProperty("Second", 1), new JProperty("Third", null), new JProperty("Fourth", new JConstructor("Date", 12345)), new JProperty("Fifth", double.PositiveInfinity), new JProperty("Sixth", double.NaN) ) ); ICloneable c = a; JArray a2 = (JArray)c.Clone(); Assert.True(a.DeepEquals(a2)); } #endif [Fact] public void DoubleDeepEquals() { JArray a = new JArray( double.NaN, double.PositiveInfinity, double.NegativeInfinity ); JArray a2 = (JArray)a.DeepClone(); Assert.True(a.DeepEquals(a2)); double d = 1 + 0.1 + 0.1 + 0.1; JValue v1 = new JValue(d); JValue v2 = new JValue(1.3); Assert.True(v1.DeepEquals(v2)); } [Fact] public void ParseAdditionalContent() { AssertException.Throws<JsonReaderException>(() => { string json = @"[ ""Small"", ""Medium"", ""Large"" ],"; JToken.Parse(json); }, "Additional text encountered after finished reading JSON content: ,. Path '', line 5, position 2."); } [Fact] public void Path() { JObject o = new JObject( new JProperty("Test1", new JArray(1, 2, 3)), new JProperty("Test2", "Test2Value"), new JProperty("Test3", new JObject(new JProperty("Test1", new JArray(1, new JObject(new JProperty("Test1", 1)), 3)))), new JProperty("Test4", new JConstructor("Date", new JArray(1, 2, 3))) ); JToken t = o.SelectToken("Test1[0]"); Assert.Equal("Test1[0]", t.Path); t = o.SelectToken("Test2"); Assert.Equal("Test2", t.Path); t = o.SelectToken(""); Assert.Equal("", t.Path); t = o.SelectToken("Test4[0][0]"); Assert.Equal("Test4[0][0]", t.Path); t = o.SelectToken("Test4[0]"); Assert.Equal("Test4[0]", t.Path); t = t.DeepClone(); Assert.Equal("", t.Path); t = o.SelectToken("Test3.Test1[1].Test1"); Assert.Equal("Test3.Test1[1].Test1", t.Path); JArray a = new JArray(1); Assert.Equal("", a.Path); Assert.Equal("[0]", a[0].Path); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Research.DataStructures; using System.Diagnostics.Contracts; namespace Microsoft.Research.CodeAnalysis { public struct Void { } abstract public class BoxedExpressionTransformer<ExtraInfo> { protected ExtraInfo Info { get; private set; } protected Func<object, FList<PathElement>> PathFetcher; virtual public BoxedExpression Visit(BoxedExpression exp, ExtraInfo info, Func<object, FList<PathElement>> PathFetcher = null) { Contract.Requires(exp != null); this.Info = info; this.PathFetcher = GetPathFetcher(PathFetcher); return this.Visit(exp); } protected virtual Func<object, FList<PathElement>> GetPathFetcher(Func<object, FList<PathElement>> PathFetcher) { return PathFetcher; } protected BoxedExpression Visit(BoxedExpression exp) { Contract.Requires(exp != null); if (exp.IsVariable) { return this.Variable(exp, exp.UnderlyingVariable, exp.AccessPath); } if (exp.IsNull) { return this.Null(exp); } if (exp.IsConstant) { return this.Constant(exp, exp.ConstantType, exp.Constant); } BinaryOperator bop; BoxedExpression left, right; if (exp.IsBinaryExpression(out bop, out left, out right)) { return this.Binary(exp, bop, left, right); } UnaryOperator uop; if (exp.IsUnaryExpression(out uop, out left)) { return this.Unary(exp, uop, left); } if (exp.IsSizeOf) { return this.SizeOf(exp); } object type; if (exp.IsIsInstExpression(out left, out type)) { return this.IsInst(exp, type, left); } BoxedExpression array, index; if (exp.IsArrayIndexExpression(out array, out index, out type)) { return this.ArrayIndex(exp, type, array, index); } if (exp.IsResult) { return this.Result(exp); } // exp.IsOld ?? // exp.IsValueAtReturn?? // exp.IsAssert ?? // exp.IsAssume ?? // exp.IsStatementSequence ?? bool isForAll; BoxedExpression boundedVar, low, upp, body; if (exp.IsQuantifiedExpression(out isForAll, out boundedVar, out low, out upp, out body)) { if (isForAll) { return this.ForAll(exp, boundedVar, low, upp, body); } else { return this.Exists(exp, boundedVar, low, upp, body); } } throw new NotImplementedException("Missing case !!!!"); } #region Virtual methods protected virtual BoxedExpression Null(BoxedExpression original) { return original; } protected virtual BoxedExpression Variable(BoxedExpression original, object var, PathElement[] path) { Contract.Requires(original != null); Contract.Requires(original.UnderlyingVariable == var); if (path != null || this.PathFetcher == null) { return original; } else { Contract.Assert(this.PathFetcher != null); var newPath = this.PathFetcher(original.UnderlyingVariable); return newPath != null ? BoxedExpression.Var(original.UnderlyingVariable, newPath) : null; } } protected virtual BoxedExpression Constant(BoxedExpression original, object type, object value) { return original; } protected virtual BoxedExpression Binary(BoxedExpression original, BinaryOperator binaryOperator, BoxedExpression left, BoxedExpression right) { Contract.Requires(original != null); Contract.Requires(left != null); Contract.Requires(right != null); var recLeft = this.Visit(left); if (recLeft == null) return recLeft; var recRight = this.Visit(right); if (recRight == null) return recRight; return BoxedExpression.Binary(binaryOperator, recLeft, recRight, original.UnderlyingVariable); } protected virtual BoxedExpression Unary(BoxedExpression original, UnaryOperator unaryOperator, BoxedExpression argument) { Contract.Requires(original != null); Contract.Requires(argument != null); var recArgument = this.Visit(argument); if (recArgument == null) return null; return BoxedExpression.Unary(unaryOperator, recArgument); } protected virtual BoxedExpression SizeOf(BoxedExpression original) { return original; } protected virtual BoxedExpression IsInst(BoxedExpression original, object type, BoxedExpression argument) { return original; } protected virtual BoxedExpression ArrayIndex<Typ>(BoxedExpression original, Typ type, BoxedExpression array, BoxedExpression index) { Contract.Requires(original != null); Contract.Requires(array != null); Contract.Requires(index != null); var arrayRec = this.Visit(array); if (arrayRec == null) return null; var indexRec = this.Visit(index); if (indexRec == null) return null; return BoxedExpression.ArrayIndex(arrayRec, indexRec, (Typ)type); } protected virtual BoxedExpression Result(BoxedExpression original) { return original; } protected virtual BoxedExpression ForAll(BoxedExpression original, BoxedExpression boundVariable, BoxedExpression lower, BoxedExpression upper, BoxedExpression body) { if (boundVariable == null || lower == null || upper == null || body == null) { return null; } var recboundVariable = this.Visit(boundVariable); if (recboundVariable == null) return null; var recLower = this.Visit(lower); if (recLower == null) return null; var recUpper = this.Visit(upper); if (recUpper == null) return null; var recBody = this.Visit(body); if (recBody == null) return null; return new ForAllIndexedExpression(null, recboundVariable, recLower, recUpper, recBody); } protected virtual BoxedExpression Exists(BoxedExpression original, BoxedExpression boundVariable, BoxedExpression lower, BoxedExpression upper, BoxedExpression body) { if (boundVariable == null || lower == null || upper == null || body == null) { return null; } var recboundVariable = this.Visit(boundVariable); if (recboundVariable == null) return null; var recLower = this.Visit(lower); if (recLower == null) return null; var recUpper = this.Visit(upper); if (recUpper == null) return null; var recBody = this.Visit(body); if (recBody == null) return null; return new ExistsIndexedExpression(null, recboundVariable, recLower, recUpper, recBody); } //abstract BoxedExpression Old(BoxedExpression original, object type, BoxedExpression expression); //abstract BoxedExpression ValueAtReturn(BoxedExpression original, object type, BoxedExpression expression); //abstract BoxedExpression Assert(BoxedExpression original, BoxedExpression condition); //abstract BoxedExpression Assume(BoxedExpression original, BoxedExpression condition); //abstract BoxedExpression StatementSequence(BoxedExpression original, IIndexable<BoxedExpression> statements); #endregion } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. #if POLYHEDRA using System; using System.Collections.Generic; using Microsoft.Boogie.AbstractInterpretation; using AI = Microsoft.AbstractInterpretationFramework; using Microsoft.Research.AbstractDomains.Expressions; using System.Collections; using Microsoft.Research.AbstractDomains; using Microsoft.Research.AbstractDomains.Numerical; using Microsoft.Research.DataStructures; namespace Microsoft.Research.AbstractDomains.Numerical { class UnknownType : AI.AIType { public UnknownType() { } } static class UnknownFunctionSymbol { private static AI.FunctionSymbol value; static UnknownFunctionSymbol() { value = new AI.FunctionSymbol(new UnknownType()); } static public AI.FunctionSymbol Value { get { return value; } } } class Converter { static public Exp<E> Box<E>(E exp, IExpressionDecoder<E> decoder) { if (decoder.IsVariable(exp)) return new Var<E>(exp, decoder); else { switch (decoder.OperatorFor(exp)) { case ExpressionOperator.ConvertToInt32: case ExpressionOperator.ConvertToUInt16: case ExpressionOperator.ConvertToUInt32: case ExpressionOperator.ConvertToUInt8: return Box(decoder.LeftExpressionFor(exp), decoder); } return new Exp<E>(exp, decoder); } } static public Var<E> BoxAsVariable<E>(E exp, IExpressionDecoder<E> decoder) { return new Var<E>(exp, decoder); } static public E Unbox<E>(AI.IExpr boxed) { return ((Exp<E>)boxed).InExp; } } class Exp<Expression> : AI.IFunApp { protected IExpressionDecoder<Variable, Expression> decoder; protected Expression exp; internal Expression InExp { get { return this.exp; } } public Exp(Expression exp, IExpressionDecoder<Variable, Expression> decoder) { this.exp = exp; this.decoder = decoder; } #region IFunApp Members public IList/*<AI.IExpr>*/ Arguments { get { IList result = new ArrayList(); if (this.decoder.IsUnaryExpression(exp)) { result.Add(Converter.Box(this.decoder.LeftExpressionFor(exp), this.decoder)); } else if (this.decoder.IsBinaryExpression(exp)) { result.Add(Converter.Box(this.decoder.LeftExpressionFor(exp), this.decoder)); result.Add(Converter.Box(this.decoder.RightExpressionFor(exp), this.decoder)); } return result; } } public AI.IFunApp CloneWithArguments(System.Collections.IList args) { return this; } public AI.IFunctionSymbol FunctionSymbol { get { if (this.decoder.IsConstant(this.exp)) { int val; if (this.decoder.TryValueOf<int>(this.exp, ExpressionType.Int32, out val)) { return AI.Int.Const(val); } else { return UnknownFunctionSymbol.Value; } } switch (this.decoder.OperatorFor(exp)) { case ExpressionOperator.Addition: return AI.Int.Add; case ExpressionOperator.And: return AI.Prop.And; case ExpressionOperator.Constant: return UnknownFunctionSymbol.Value; case ExpressionOperator.ConvertToInt32: case ExpressionOperator.ConvertToUInt16: case ExpressionOperator.ConvertToUInt32: case ExpressionOperator.ConvertToUInt8: return Converter.Box(this.decoder.LeftExpressionFor(exp), this.decoder).FunctionSymbol; case ExpressionOperator.Division: return AI.Int.Div; case ExpressionOperator.Equal: case ExpressionOperator.Equal_obj: return AI.Int.Eq; case ExpressionOperator.GreaterEqualThan_Un: case ExpressionOperator.GreaterEqualThan: return AI.Int.AtLeast; case ExpressionOperator.GreaterThan_Un: case ExpressionOperator.GreaterThan: return AI.Int.Greater; case ExpressionOperator.LessEqualThan_Un: case ExpressionOperator.LessEqualThan: return AI.Int.AtMost; case ExpressionOperator.LessThan_Un: case ExpressionOperator.LessThan: return AI.Int.Less; case ExpressionOperator.Modulus: return AI.Int.Mod; case ExpressionOperator.Multiplication: return AI.Int.Mul; case ExpressionOperator.Not: return AI.Prop.Not; case ExpressionOperator.NotEqual: return AI.Int.Neq; case ExpressionOperator.Or: return AI.Prop.Or; case ExpressionOperator.ShiftLeft: return UnknownFunctionSymbol.Value; case ExpressionOperator.ShiftRight: return UnknownFunctionSymbol.Value; case ExpressionOperator.SizeOf: return UnknownFunctionSymbol.Value; case ExpressionOperator.Subtraction: return AI.Int.Sub; case ExpressionOperator.UnaryMinus: return AI.Int.Negate; case ExpressionOperator.Unknown: return UnknownFunctionSymbol.Value; case ExpressionOperator.Variable: return new AI.NamedSymbol(ExpressionPrinter.ToString(this.exp, this.decoder), AI.Int.Type); case ExpressionOperator.WritableBytes: // to improve??? return UnknownFunctionSymbol.Value; default: return UnknownFunctionSymbol.Value; } } } #endregion #region IExpr Members public object DoVisit(AI.ExprVisitor visitor) { if (this.decoder.IsVariable(this.exp)) { return visitor.VisitVariable(Converter.BoxAsVariable(this.exp, this.decoder)); } else { return visitor.VisitFunApp(Converter.Box(this.exp, this.decoder)); } } #endregion public override string ToString() { return ExpressionPrinter.ToString(this.exp, this.decoder); } } class Var<Expression> : Exp<Expression>, AI.IVariable { public Var(Expression exp, IExpressionDecoder<Variable, Expression> decoder) : base(exp, decoder) { } #region IVariable Members public string Name { get { return ExpressionPrinter.ToString(this.exp, this.decoder); } } #endregion } class UninterestingFunctions : AI.IFunApp { #region IFunApp Members public IList Arguments { get { return new ArrayList(); } } public AI.IFunApp CloneWithArguments(IList args) { return this; } public AI.IFunctionSymbol FunctionSymbol { get { return UnknownFunctionSymbol.Value; } } #endregion #region IExpr Members public object DoVisit(AI.ExprVisitor visitor) { return visitor.Default(this); } #endregion } class PropFactory<Expression> : AI.IQuantPropExprFactory { internal static AI.IFunApp t = null; internal static AI.IFunApp f = null; IExpressionDecoder<Variable, Expression> decoder; IExpressionEncoder<Variable, Expression> encoder; public PropFactory(IExpressionDecoder<Variable, Expression> decoder, IExpressionEncoder<Variable, Expression> encoder) { this.decoder = decoder; this.encoder = encoder; } #region IQuantPropExprFactory Members public AI.IFunApp Exists(AI.AIType paramType, AI.FunctionBody body) { return new UninterestingFunctions(); } public AI.IFunApp Exists(AI.IFunction p) { return new UninterestingFunctions(); } public AI.IFunApp Forall(AI.AIType paramType, AI.FunctionBody body) { return new UninterestingFunctions(); } public AI.IFunApp Forall(AI.IFunction p) { return new UninterestingFunctions(); } #endregion #region IPropExprFactory Members public AI.IFunApp And(AI.IExpr p, AI.IExpr q) { Expression e1 = Converter.Unbox<Expression>(p); Expression e2 = Converter.Unbox<Expression>(q); return Converter.Box(encoder.CompoundExpressionFor(ExpressionType.Bool, ExpressionOperator.And, e1, e2), decoder); } public AI.IFunApp False { get { if (f == null) { Expression f1 = encoder.ConstantFor(false); f = Converter.Box(encoder.CompoundExpressionFor(ExpressionType.Bool, ExpressionOperator.Constant, f1), decoder); } return f; } } public AI.IFunApp Implies(AI.IExpr p, AI.IExpr q) { return new UninterestingFunctions(); } public AI.IFunApp Not(AI.IExpr p) { Expression e = Converter.Unbox<Expression>(p); return Converter.Box(encoder.CompoundExpressionFor(ExpressionType.Bool, ExpressionOperator.Not, e), decoder); } public AI.IFunApp Or(AI.IExpr p, AI.IExpr q) { Expression e1 = Converter.Unbox<Expression>(p); Expression e2 = Converter.Unbox<Expression>(q); return Converter.Box(encoder.CompoundExpressionFor(ExpressionType.Bool, ExpressionOperator.Or, e1, e2), decoder); } public AI.IFunApp True { get { if (t == null) { Expression t1 = encoder.ConstantFor(true); t = Converter.Box(encoder.CompoundExpressionFor(ExpressionType.Bool, ExpressionOperator.Constant, t1), decoder); } return t; } } #endregion } class LinearExpFactory<Expression> : AI.ILinearExprFactory { IExpressionDecoder<Variable, Expression> decoder; IExpressionEncoder<Variable, Expression> encoder; public LinearExpFactory(IExpressionDecoder<Variable, Expression> decoder, IExpressionEncoder<Variable, Expression> encoder) { this.decoder = decoder; this.encoder = encoder; } #region ILinearExprFactory Members public AI.IFunApp Add(AI.IExpr p, AI.IExpr q) { Expression e1 = Converter.Unbox<Expression>(p); Expression e2 = Converter.Unbox<Expression>(q); return Converter.Box(encoder.CompoundExpressionFor(ExpressionType.Int32, ExpressionOperator.Addition, e1, e2), decoder); } public AI.IFunApp And(AI.IExpr p, AI.IExpr q) { Expression e1 = Converter.Unbox<Expression>(p); Expression e2 = Converter.Unbox<Expression>(q); return Converter.Box(encoder.CompoundExpressionFor(ExpressionType.Bool, ExpressionOperator.And, e1, e2), decoder); } public AI.IFunApp AtMost(AI.IExpr p, AI.IExpr q) { Expression e1 = Converter.Unbox<Expression>(p); Expression e2 = Converter.Unbox<Expression>(q); return Converter.Box(encoder.CompoundExpressionFor(ExpressionType.Bool, ExpressionOperator.LessEqualThan, e1, e2), decoder); } public AI.IFunApp False { get { if (PropFactory<Expression>.f == null) { Expression f1 = encoder.ConstantFor(false); PropFactory<Expression>.f = Converter.Box(encoder.CompoundExpressionFor(ExpressionType.Bool, ExpressionOperator.Constant, f1), decoder); } return PropFactory<Expression>.f; } } public AI.IExpr Term(AI.Rational r, AI.IVariable var) { long up = r.Numerator; long down = r.Denominator; Expression upAsExp = encoder.ConstantFor(up); Expression downAsExp = encoder.ConstantFor(down); Expression asFrac = encoder.CompoundExpressionFor(ExpressionType.Int32, ExpressionOperator.Division, upAsExp, downAsExp); // We assume AI.IVariable being a Var<Exp> Var<Expression> v = var as Var<Expression>; if (v == null) throw new AbstractInterpretationException(); Expression newVar = Converter.Unbox<Expression>(v); return Converter.Box(encoder.CompoundExpressionFor(ExpressionType.Int32, ExpressionOperator.Multiplication, asFrac, newVar), decoder); } public AI.IFunApp True { get { if (PropFactory<Expression>.t == null) { Expression t1 = encoder.ConstantFor(false); PropFactory<Expression>.t = Converter.Box(t1, decoder); } return PropFactory<Expression>.t; } } #endregion #region IIntExprFactory Members public AI.IFunApp Const(int i) { return Converter.Box(encoder.ConstantFor(i), decoder); } #endregion #region IValueExprFactory Members public AI.IFunApp Eq(AI.IExpr p, AI.IExpr q) { Expression e1 = Converter.Unbox<Expression>(p); Expression e2 = Converter.Unbox<Expression>(q); return Converter.Box(encoder.CompoundExpressionFor(ExpressionType.Bool, ExpressionOperator.Equal, e1, e2), decoder); } public AI.IFunApp Neq(AI.IExpr p, AI.IExpr q) { Expression e1 = Converter.Unbox<Expression>(p); Expression e2 = Converter.Unbox<Expression>(q); return Converter.Box(encoder.CompoundExpressionFor(ExpressionType.Bool, ExpressionOperator.NotEqual, e1, e2), decoder); } #endregion } public class PolyhedraEnvironment<Expression> : INumericalAbstractDomain<Variable, Expression> { #region Statics static private AI.Lattice UnderlyingPolyhedra; static private LinearExpFactory<Expression> linearfactory; static private PropFactory<Expression> propfactory; public static void Init(IExpressionDecoder<Variable, Expression> decoder, IExpressionEncoder<Variable, Expression> encoder) { linearfactory = new LinearExpFactory<Expression>(decoder, encoder); propfactory = new PropFactory<Expression>(decoder, encoder); UnderlyingPolyhedra = new AI.PolyhedraLattice(linearfactory, propfactory); UnderlyingPolyhedra.Validate(); } #endregion #region Private State private AI.PolyhedraLattice.Element embedded; private IntervalEnvironment<Variable, Expression> intv; private IExpressionDecoder<Variable, Expression> decoder; private IExpressionEncoder<Variable, Expression> encoder; private PolyhedraTestTrueVisitor testTrueVisitor; private PolyhedraTestFalseVisitor testFalseVisitor; #endregion public PolyhedraEnvironment(IExpressionDecoder<Variable, Expression> decoder, IExpressionEncoder<Variable, Expression> encoder) { this.decoder = decoder; this.encoder = encoder; embedded = UnderlyingPolyhedra.Top; intv = new IntervalEnvironment<Variable, Expression>(decoder, encoder); testTrueVisitor = new PolyhedraEnvironment<Expression>.PolyhedraTestTrueVisitor(decoder); testFalseVisitor = new PolyhedraEnvironment<Expression>.PolyhedraTestFalseVisitor(decoder); testTrueVisitor.FalseVisitor = testFalseVisitor; testFalseVisitor.TrueVisitor = testTrueVisitor; } private PolyhedraEnvironment(PolyhedraEnvironment<Expression> pe, AI.PolyhedraLattice.Element value, IntervalEnvironment<Variable, Expression> intv) : this(pe.decoder, pe.encoder, value, intv) { testTrueVisitor = pe.testTrueVisitor; testFalseVisitor = pe.testFalseVisitor; } private PolyhedraEnvironment(IExpressionDecoder<Variable, Expression> decoder, IExpressionEncoder<Variable, Expression> encoder, AI.PolyhedraLattice.Element value, IntervalEnvironment<Variable, Expression> intv) { this.decoder = decoder; this.encoder = encoder; embedded = value; this.intv = intv; testTrueVisitor = new PolyhedraEnvironment<Expression>.PolyhedraTestTrueVisitor(decoder); testFalseVisitor = new PolyhedraEnvironment<Expression>.PolyhedraTestFalseVisitor(decoder); testTrueVisitor.FalseVisitor = testFalseVisitor; testFalseVisitor.TrueVisitor = testTrueVisitor; } #region INumericalAbstractDomain<Rational,Expression> Members /// <summary> /// Return top /// </summary> public Interval BoundsFor(Expression v) { return intv.BoundsFor(v); } // Does nothing for the moment public void AssignInterval(Expression x, Interval value) { this.AssignIntervalJustInPolyhedra(x, value); intv.AssignInterval(x, value); } private void AssignIntervalJustInPolyhedra(Expression x, Interval value) { if (!value.IsBottom) { if (!value.LowerBound.IsInfinity) { AI.IExpr lowerBound = linearfactory.AtMost(linearfactory.Const((Int32)value.LowerBound.PreviousInteger), Converter.BoxAsVariable(x, decoder)); embedded = UnderlyingPolyhedra.Constrain(embedded, lowerBound); } if (!value.UpperBound.IsInfinity) { AI.IExpr upperBound = linearfactory.AtMost(Converter.BoxAsVariable(x, decoder), linearfactory.Const((Int32)value.UpperBound.NextInteger)); embedded = UnderlyingPolyhedra.Constrain(embedded, upperBound); } } } public INumericalAbstractDomain<Variable, Expression> TestTrueGeqZero(Expression exp) { // 0 <= exp AI.IExpr toAssume = linearfactory.AtMost(linearfactory.Const(0), Converter.Box<Expression>(exp, decoder)); return Factory(UnderlyingPolyhedra.Constrain(embedded, toAssume), intv.TestTrueGeqZero(exp)); } public INumericalAbstractDomain<Variable, Expression> TestTrueLessThan(Expression exp1, Expression exp2) { // exp1 <= exp2 -1 AI.IExpr toAssume = linearfactory.AtMost(Converter.Box(exp1, decoder), linearfactory.Add(Converter.Box(exp2, decoder), linearfactory.Const(-1))); return Factory(UnderlyingPolyhedra.Constrain(embedded, toAssume), intv.TestTrueLessThan(exp1, exp2)); } public INumericalAbstractDomain<Variable, Expression> TestTrueLessEqualThan(Expression exp1, Expression exp2) { // exp1 <= exp2 AI.IExpr toAssume = linearfactory.AtMost(Converter.Box(exp1, decoder), Converter.Box(exp2, decoder)); return Factory(UnderlyingPolyhedra.Constrain(embedded, toAssume), intv.TestTrueLessEqualThan(exp1, exp2)); } public FlatAbstractDomain<bool> CheckIfGreaterEqualThanZero(Expression exp) { // exp >= 0 ? AI.IExpr toCheck = linearfactory.AtMost(linearfactory.Const(0), Converter.Box<Expression>(exp, decoder)); return ToFlatAbstractDomain(UnderlyingPolyhedra.CheckPredicate(embedded, toCheck)).Meet(intv.CheckIfGreaterEqualThanZero(exp)); } public FlatAbstractDomain<bool> CheckIfLessThan(Expression e1, Expression e2) { // exp1 <= exp2 -1 ? AI.IExpr toAssume = linearfactory.AtMost(Converter.Box(e1, decoder), linearfactory.Add(Converter.Box(e2, decoder), linearfactory.Const(-1))); return ToFlatAbstractDomain(UnderlyingPolyhedra.CheckPredicate(embedded, toAssume)).Meet(intv.CheckIfLessThan(e1, e2)); } public FlatAbstractDomain<bool> CheckIfLessEqualThan(Expression e1, Expression e2) { // exp1 <= exp2 ? AI.IExpr toAssume = linearfactory.AtMost(Converter.Box(e1, decoder), Converter.Box(e2, decoder)); return ToFlatAbstractDomain(UnderlyingPolyhedra.CheckPredicate(embedded, toAssume)).Meet(intv.CheckIfLessEqualThan(e1, e2)); } #endregion #region IAbstractDomain Members public bool IsBottom { get { return UnderlyingPolyhedra.IsBottom(embedded) || intv.IsBottom; } } public bool IsTop { get { return UnderlyingPolyhedra.IsTop(embedded) && intv.IsTop; } } bool IAbstractDomain.LessEqual(IAbstractDomain a) { return this.LessEqual((PolyhedraEnvironment<Expression>)a); } public bool LessEqual(PolyhedraEnvironment<Expression> right) { bool result; if (AbstractDomainsHelper.TryTrivialLessEqual(this, right, out result)) { return result; } else { return UnderlyingPolyhedra.LowerThan(embedded, right.embedded) && intv.LessEqual(right.intv); } } public IAbstractDomain Bottom { get { return Factory(UnderlyingPolyhedra.Bottom, (INumericalAbstractDomain<Variable, Expression>)intv.Bottom); } } public IAbstractDomain Top { get { return Factory(UnderlyingPolyhedra.Top, (INumericalAbstractDomain<Variable, Expression>)intv.Top); } } IAbstractDomain IAbstractDomain.Join(IAbstractDomain a) { return this.Join((PolyhedraEnvironment<Expression>)a); } public PolyhedraEnvironment<Expression> Join(PolyhedraEnvironment<Expression> right) { PolyhedraEnvironment<Expression> result; if (AbstractDomainsHelper.TryTrivialJoin(this, right, out result)) { return result; } else { return Factory(UnderlyingPolyhedra.Join(embedded, right.embedded), intv.Join(right.intv)); } } IAbstractDomain IAbstractDomain.Meet(IAbstractDomain a) { return this.Meet((PolyhedraEnvironment<Expression>)a); } public PolyhedraEnvironment<Expression> Meet(PolyhedraEnvironment<Expression> right) { PolyhedraEnvironment<Expression> result; if (AbstractDomainsHelper.TryTrivialMeet(this, right, out result)) { return result; } else { return Factory(UnderlyingPolyhedra.Meet(embedded, right.embedded), intv.Meet(right.intv)); } } IAbstractDomain IAbstractDomain.Widening(IAbstractDomain prev) { return this.Widening((PolyhedraEnvironment<Expression>)prev); } public PolyhedraEnvironment<Expression> Widening(PolyhedraEnvironment<Expression> prev) { PolyhedraEnvironment<Expression> result; if (AbstractDomainsHelper.TryTrivialJoin(this, prev, out result)) { return result; } else { // Boogie's polyhedra has it in the other order return Factory(UnderlyingPolyhedra.Widen(prev.embedded, embedded), intv.Widening(prev.intv)); } } public T To<T>(IFactory<T> factory) { return factory.Constant(true); } #endregion #region ICloneable Members public object Clone() { return Factory((AI.PolyhedraLattice.Element)embedded.Clone(), (IAbstractDomain)intv.Clone()); } #endregion #region IPureExpressionAssignments<Expression> Members public Set<Expression> Variables { get { Set<Expression> result = new Set<Expression>(); foreach (AI.IVariable var in embedded.FreeVariables()) { Exp<Expression> asExp = var as Exp<Expression>; result.Add(asExp.InExp); } return result.Union(intv.Variables); } } public void AddVariable(Expression var) { // Does nothing } public void Assign(Expression x, Expression exp) { this.Assign(x, exp, TopNumericalDomain<Variable, Expression>.Singleton); } public void Assign(Expression x, Expression exp, INumericalAbstractDomainQuery<Variable, Expression> preState) { embedded = UnderlyingPolyhedra.Constrain(embedded, Converter.Box(encoder.CompoundExpressionFor(ExpressionType.Bool, ExpressionOperator.Equal, x, exp), decoder)); } public void ProjectVariable(Expression var) { embedded = UnderlyingPolyhedra.Eliminate(embedded, Converter.BoxAsVariable<Expression>(var, decoder)); intv.ProjectVariable(var); } public void RemoveVariable(Expression var) { embedded = UnderlyingPolyhedra.Eliminate(embedded, Converter.BoxAsVariable<Expression>(var, decoder)); intv.RemoveVariable(var); } public void RenameVariable(Expression OldName, Expression NewName) { embedded = UnderlyingPolyhedra.Rename(embedded, Converter.BoxAsVariable<Expression>(OldName, decoder), Converter.BoxAsVariable<Expression>(NewName, decoder)); intv.RenameVariable(OldName, NewName); } #endregion #region IPureExpressionTest<Expression> Members IAbstractDomainForEnvironments<Variable, Expression> IPureExpressionTest<Expression>.TestTrue(Expression guard) { return this.TestTrue(guard); } PolyhedraEnvironment<Expression> TestTrue(Expression guard) { return testTrueVisitor.Visit(guard, this); } IAbstractDomainForEnvironments<Variable, Expression> IPureExpressionTest<Expression>.TestFalse(Expression guard) { return this.TestFalse(guard); } public IAbstractDomainForEnvironments<Variable, Expression> TestFalse(Expression guard) { return testFalseVisitor.Visit(guard, this); } public FlatAbstractDomain<bool> CheckIfNonZero(Expression exp) { return new FlatAbstractDomain<bool>(false).Top; } public FlatAbstractDomain<bool> CheckIfHolds(Expression exp) { // exp ? return ToFlatAbstractDomain(UnderlyingPolyhedra.CheckPredicate(embedded, Converter.Box(exp, decoder))).Meet(intv.CheckIfHolds(exp)); } #endregion #region IAssignInParallel<Expression> Members public void AssignInParallel(IDictionary<Expression, Microsoft.Research.DataStructures.FList<Expression>> sourcesToTargets) { intv.AssignInParallel(sourcesToTargets); // Do the renamings foreach (Expression source in sourcesToTargets.Keys) { { if (sourcesToTargets[source].Length() == 1) { // we want to just follow the renamings, all the rest is not interesting and we discard it Expression target = sourcesToTargets[source].Head; // source -> target , i.e. the new name for "source" is "target" ALog.Message(StringClosure.For("Renaming {0} to {1}", ExpressionPrinter.ToStringClosure(source, decoder), ExpressionPrinter.ToStringClosure(target, decoder))); embedded = UnderlyingPolyhedra.Rename(embedded, Converter.BoxAsVariable(source, decoder), Converter.BoxAsVariable(target, decoder)); } } } #if true || MOREPRECISE // else we want to keep track of constants foreach (Expression x in intv.Variables) { Interval value = intv.BoundsFor(x); { this.AssignIntervalJustInPolyhedra(x, value); } } #endif } #endregion #region Private Methods private PolyhedraEnvironment<Expression> Factory(AI.PolyhedraLattice.Element element, IAbstractDomain intv) { return new PolyhedraEnvironment<Expression>(decoder, encoder, element, (IntervalEnvironment<Variable, Expression>)intv); } private FlatAbstractDomain<bool> ToFlatAbstractDomain(AI.Answer answer) { switch (answer) { case AI.Answer.Maybe: return new FlatAbstractDomain<bool>(false).Top; case AI.Answer.No: return new FlatAbstractDomain<bool>(false); case AI.Answer.Yes: return new FlatAbstractDomain<bool>(true); } return null; // Should be unreachable } #endregion public override string ToString() { return embedded.ToString(); } public string ToString(Expression exp) { if (decoder != null) { return ExpressionPrinter.ToString(exp, decoder); } else { return "< missing expression decoder >"; } } class PolyhedraTestTrueVisitor : TestTrueVisitor<PolyhedraEnvironment<Expression>, Expression> { public PolyhedraTestTrueVisitor(IExpressionDecoder<Variable, Expression> decoder) : base(decoder) { } public override PolyhedraEnvironment<Expression> VisitEqual(Expression left, Expression right, PolyhedraEnvironment<Expression> data) { // left == right AI.IExpr notEq = linearfactory.Eq(Converter.Box(left, this.Decoder), Converter.Box(right, this.Decoder)); return data.Factory(UnderlyingPolyhedra.Constrain(data.embedded, notEq), data.intv); } public override PolyhedraEnvironment<Expression> VisitLessEqualThan(Expression left, Expression right, PolyhedraEnvironment<Expression> data) { return (PolyhedraEnvironment<Expression>)data.TestTrueLessEqualThan(left, right); } public override PolyhedraEnvironment<Expression> VisitLessThan(Expression left, Expression right, PolyhedraEnvironment<Expression> data) { return (PolyhedraEnvironment<Expression>)data.TestTrueLessThan(left, right); } public override PolyhedraEnvironment<Expression> VisitNotEqual(Expression left, Expression right, PolyhedraEnvironment<Expression> data) { // left != right AI.IExpr notEq = linearfactory.Neq(Converter.Box(left, this.Decoder), Converter.Box(right, this.Decoder)); return data.Factory(UnderlyingPolyhedra.Constrain(data.embedded, notEq), data.intv); } public override PolyhedraEnvironment<Expression> VisitVariable(Expression exp, object variable, PolyhedraEnvironment<Expression> data) { return data; } } class PolyhedraTestFalseVisitor : TestFalseVisitor<PolyhedraEnvironment<Expression>, Expression> { public PolyhedraTestFalseVisitor(IExpressionDecoder<Variable, Expression> decoder) : base(decoder) { } public override PolyhedraEnvironment<Expression> VisitVariable(Expression left, object variable, PolyhedraEnvironment<Expression> data) { return data; } } #region INumericalAbstractDomain<Rational,Expression> Members public INumericalAbstractDomain<Variable, Expression> RemoveRedundanciesWith(INumericalAbstractDomain<Variable, Expression> oracle) { return (INumericalAbstractDomain<Variable, Expression>)this.Clone(); } /// <returns> /// The empty set /// </returns> public IEnumerable<Expression> LowerBoundsFor(Expression v) { return new Set<Expression>(); } #endregion #region INumericalAbstractDomain<Rational,Expression> Members public IEnumerable<Expression> LowerBoundsFor(Expression v, bool strict) { return new Set<Expression>(); } #endregion #region INumericalAbstractDomain<Rational,Expression> Members public IEnumerable<Expression> UpperBoundsFor(Expression v, bool strict) { return new Set<Expression>(); } #endregion } public class PolyhedraException : Exception { } } #endif
using System; using System.Linq; using System.Threading.Tasks; using Baseline; using Marten.Events; using Marten.Testing.Events.Projections; using Marten.Testing.Harness; using Shouldly; using Weasel.Postgresql; using Xunit; namespace Marten.Testing.Events { [Collection("projections")] public class end_to_end_event_capture_and_fetching_the_stream_with_non_typed_streams_Tests : OneOffConfigurationsContext { public static TheoryData<DocumentTracking> SessionTypes = new TheoryData<DocumentTracking> { DocumentTracking.IdentityOnly, DocumentTracking.DirtyTracking }; public end_to_end_event_capture_and_fetching_the_stream_with_non_typed_streams_Tests() : base("projections") { } [Theory] [MemberData(nameof(SessionTypes))] public void capture_events_to_a_new_stream_and_fetch_the_events_back(DocumentTracking sessionType) { var store = InitStore(); using (var session = store.OpenSession(sessionType)) { #region sample_start-stream-with-aggregate-type var joined = new MembersJoined { Members = new[] { "Rand", "Matt", "Perrin", "Thom" } }; var departed = new MembersDeparted { Members = new[] { "Thom" } }; var id = session.Events.StartStream(joined, departed).Id; session.SaveChanges(); #endregion sample_start-stream-with-aggregate-type var streamEvents = session.Events.FetchStream(id); Enumerable.Count<IEvent>(streamEvents).ShouldBe(2); Enumerable.ElementAt<IEvent>(streamEvents, 0).Data.ShouldBeOfType<MembersJoined>(); Enumerable.ElementAt<IEvent>(streamEvents, 0).Version.ShouldBe(1); Enumerable.ElementAt<IEvent>(streamEvents, 1).Data.ShouldBeOfType<MembersDeparted>(); Enumerable.ElementAt<IEvent>(streamEvents, 1).Version.ShouldBe(2); GenericEnumerableExtensions.Each<IEvent>(streamEvents, e => ShouldBeTestExtensions.ShouldNotBe(e.Timestamp, default(DateTimeOffset))); } } [Theory] [MemberData(nameof(SessionTypes))] public async Task capture_events_to_a_new_stream_and_fetch_the_events_back_async(DocumentTracking sessionType) { var store = InitStore(); using (var session = store.OpenSession(sessionType)) { #region sample_start-stream-with-aggregate-type var joined = new MembersJoined { Members = new[] { "Rand", "Matt", "Perrin", "Thom" } }; var departed = new MembersDeparted { Members = new[] { "Thom" } }; var id = session.Events.StartStream(joined, departed).Id; await session.SaveChangesAsync(); #endregion sample_start-stream-with-aggregate-type var streamEvents = await session.Events.FetchStreamAsync(id); Enumerable.Count<IEvent>(streamEvents).ShouldBe(2); Enumerable.ElementAt<IEvent>(streamEvents, 0).Data.ShouldBeOfType<MembersJoined>(); Enumerable.ElementAt<IEvent>(streamEvents, 0).Version.ShouldBe(1); Enumerable.ElementAt<IEvent>(streamEvents, 1).Data.ShouldBeOfType<MembersDeparted>(); Enumerable.ElementAt<IEvent>(streamEvents, 1).Version.ShouldBe(2); GenericEnumerableExtensions.Each<IEvent>(streamEvents, e => ShouldBeTestExtensions.ShouldNotBe(e.Timestamp, default(DateTimeOffset))); } } [Theory] [MemberData(nameof(SessionTypes))] public async Task capture_events_to_a_new_stream_and_fetch_the_events_back_async_with_linq(DocumentTracking sessionType) { var store = InitStore(); using (var session = store.OpenSession(sessionType)) { #region sample_start-stream-with-aggregate-type var joined = new MembersJoined { Members = new[] { "Rand", "Matt", "Perrin", "Thom" } }; var departed = new MembersDeparted { Members = new[] { "Thom" } }; var id = session.Events.StartStream(joined, departed).Id; await session.SaveChangesAsync(); #endregion sample_start-stream-with-aggregate-type var streamEvents = await Queryable.Where<IEvent>(session.Events.QueryAllRawEvents(), x => x.StreamId == id).OrderBy(x => x.Version).ToListAsync(); streamEvents.Count().ShouldBe(2); streamEvents.ElementAt(0).Data.ShouldBeOfType<MembersJoined>(); streamEvents.ElementAt(0).Version.ShouldBe(1); streamEvents.ElementAt(1).Data.ShouldBeOfType<MembersDeparted>(); streamEvents.ElementAt(1).Version.ShouldBe(2); streamEvents.Each(e => e.Timestamp.ShouldNotBe(default(DateTimeOffset))); } } [Theory] [MemberData(nameof(SessionTypes))] public void capture_events_to_a_new_stream_and_fetch_the_events_back_sync_with_linq(DocumentTracking sessionType) { var store = InitStore(); using (var session = store.OpenSession(sessionType)) { #region sample_start-stream-with-aggregate-type var joined = new MembersJoined { Members = new[] { "Rand", "Matt", "Perrin", "Thom" } }; var departed = new MembersDeparted { Members = new[] { "Thom" } }; var id = session.Events.StartStream(joined, departed).Id; session.SaveChanges(); #endregion sample_start-stream-with-aggregate-type var streamEvents = Queryable.Where<IEvent>(session.Events.QueryAllRawEvents(), x => x.StreamId == id).OrderBy(x => x.Version).ToList(); streamEvents.Count().ShouldBe(2); streamEvents.ElementAt(0).Data.ShouldBeOfType<MembersJoined>(); streamEvents.ElementAt(0).Version.ShouldBe(1); streamEvents.ElementAt(1).Data.ShouldBeOfType<MembersDeparted>(); streamEvents.ElementAt(1).Version.ShouldBe(2); streamEvents.Each(e => e.Timestamp.ShouldNotBe(default(DateTimeOffset))); } } [Fact] public void live_aggregate_equals_inlined_aggregate_without_hidden_contracts() { var store = InitStore("event_store"); var questId = Guid.NewGuid(); using (var session = store.OpenSession()) { //Note Id = questId, is we remove it from first message then AggregateStream will return party.Id=default(Guid) that is not equals to Load<QuestParty> result var started = new QuestStarted { /*Id = questId,*/ Name = "Destroy the One Ring" }; var joined1 = new MembersJoined(1, "Hobbiton", "Frodo", "Merry"); session.Events.StartStream(questId, started, joined1); session.SaveChanges(); } using (var session = store.OpenSession()) { var liveAggregate = session.Events.AggregateStream<QuestParty>(questId); var inlinedAggregate = session.Load<QuestParty>(questId); liveAggregate.Id.ShouldBe(inlinedAggregate.Id); inlinedAggregate.ToString().ShouldBe(liveAggregate.ToString()); } } [Fact] public void open_persisted_stream_in_new_store_with_same_settings() { var store = InitStore("event_store"); var questId = Guid.NewGuid(); using (var session = store.OpenSession()) { //Note "Id = questId" @see live_aggregate_equals_inlined_aggregate... var started = new QuestStarted { Id = questId, Name = "Destroy the One Ring" }; var joined1 = new MembersJoined(1, "Hobbiton", "Frodo", "Merry"); session.Events.StartStream(questId, started, joined1); session.SaveChanges(); } // events-aggregate-on-the-fly - works with same store using (var session = store.OpenSession()) { // questId is the id of the stream var party = session.Events.AggregateStream<QuestParty>(questId); party.Id.ShouldBe(questId); SpecificationExtensions.ShouldNotBeNull(party); var party_at_version_3 = session.Events .AggregateStream<QuestParty>(questId, 3); SpecificationExtensions.ShouldNotBeNull(party_at_version_3); var party_yesterday = session.Events .AggregateStream<QuestParty>(questId, timestamp: DateTime.UtcNow.AddDays(-1)); party_yesterday.ShouldBeNull(); } using (var session = store.OpenSession()) { var party = session.Load<QuestParty>(questId); party.Id.ShouldBe(questId); } var newStore = InitStore("event_store", false); //Inline is working using (var session = store.OpenSession()) { var party = session.Load<QuestParty>(questId); SpecificationExtensions.ShouldNotBeNull(party); } //GetAll using (var session = store.OpenSession()) { var parties = session.Events.QueryRawEventDataOnly<QuestParty>().ToArray<QuestParty>(); foreach (var party in parties) { SpecificationExtensions.ShouldNotBeNull(party); } } //This AggregateStream fail with NPE using (var session = newStore.OpenSession()) { // questId is the id of the stream var party = session.Events.AggregateStream<QuestParty>(questId);//Here we get NPE party.Id.ShouldBe(questId); var party_at_version_3 = session.Events .AggregateStream<QuestParty>(questId, 3); party_at_version_3.Id.ShouldBe(questId); var party_yesterday = session.Events .AggregateStream<QuestParty>(questId, timestamp: DateTime.UtcNow.AddDays(-1)); party_yesterday.ShouldBeNull(); } } [Fact] public void query_before_saving() { var store = InitStore("event_store"); var questId = Guid.NewGuid(); using (var session = store.OpenSession()) { var parties = session.Query<QuestParty>().ToArray<QuestParty>(); parties.Length.ShouldBeLessThanOrEqualTo(0); } //This SaveChanges will fail with missing method (ro collection configured?) using (var session = store.OpenSession()) { var started = new QuestStarted { Name = "Destroy the One Ring" }; var joined1 = new MembersJoined(1, "Hobbiton", "Frodo", "Merry"); session.Events.StartStream(questId, started, joined1); session.SaveChanges(); var party = session.Events.AggregateStream<QuestParty>(questId); ShouldBeTestExtensions.ShouldBe(party.Id, questId); } } [Fact] public async Task aggregate_stream_async_has_the_id() { var store = InitStore("event_store"); var questId = Guid.NewGuid(); using (var session = store.OpenSession()) { var parties = await QueryableExtensions.ToListAsync<QuestParty>(session.Query<QuestParty>()); parties.Count.ShouldBeLessThanOrEqualTo(0); } //This SaveChanges will fail with missing method (ro collection configured?) using (var session = store.OpenSession()) { var started = new QuestStarted { Name = "Destroy the One Ring" }; var joined1 = new MembersJoined(1, "Hobbiton", "Frodo", "Merry"); session.Events.StartStream(questId, started, joined1); await session.SaveChangesAsync(); var party = await session.Events.AggregateStreamAsync<QuestParty>(questId); party.Id.ShouldBe(questId); } } [Theory] [MemberData(nameof(SessionTypes))] public void capture_events_to_a_new_stream_and_fetch_the_events_back_with_stream_id_provided( DocumentTracking sessionType) { var store = InitStore(); using (var session = store.OpenSession(sessionType)) { #region sample_start-stream-with-existing-guid var joined = new MembersJoined { Members = new[] { "Rand", "Matt", "Perrin", "Thom" } }; var departed = new MembersDeparted { Members = new[] { "Thom" } }; var id = Guid.NewGuid(); session.Events.StartStream(id, joined, departed); session.SaveChanges(); #endregion sample_start-stream-with-existing-guid var streamEvents = session.Events.FetchStream(id); Enumerable.Count<IEvent>(streamEvents).ShouldBe(2); Enumerable.ElementAt<IEvent>(streamEvents, 0).Data.ShouldBeOfType<MembersJoined>(); Enumerable.ElementAt<IEvent>(streamEvents, 0).Version.ShouldBe(1); Enumerable.ElementAt<IEvent>(streamEvents, 1).Data.ShouldBeOfType<MembersDeparted>(); Enumerable.ElementAt<IEvent>(streamEvents, 1).Version.ShouldBe(2); } } [Theory] [MemberData(nameof(SessionTypes))] public void capture_events_to_a_non_existing_stream_and_fetch_the_events_back(DocumentTracking sessionType) { var store = InitStore(); using (var session = store.OpenSession(sessionType)) { var joined = new MembersJoined { Members = new[] { "Rand", "Matt", "Perrin", "Thom" } }; var departed = new MembersDeparted { Members = new[] { "Thom" } }; var id = Guid.NewGuid(); session.Events.StartStream(id, joined); session.Events.Append(id, departed); session.SaveChanges(); var streamEvents = session.Events.FetchStream(id); streamEvents.Count<IEvent>().ShouldBe(2); streamEvents.ElementAt<IEvent>(0).Data.ShouldBeOfType<MembersJoined>(); streamEvents.ElementAt<IEvent>(0).Version.ShouldBe(1); streamEvents.ElementAt<IEvent>(1).Data.ShouldBeOfType<MembersDeparted>(); streamEvents.ElementAt<IEvent>(1).Version.ShouldBe(2); } } [Theory] [MemberData(nameof(SessionTypes))] public void capture_events_to_an_existing_stream_and_fetch_the_events_back(DocumentTracking sessionType) { var store = InitStore(); var id = Guid.NewGuid(); var started = new QuestStarted(); using (var session = store.OpenSession(sessionType)) { session.Events.StartStream(id, started); session.SaveChanges(); } using (var session = store.OpenSession(sessionType)) { var joined = new MembersJoined { Members = new[] { "Rand", "Matt", "Perrin", "Thom" } }; var departed = new MembersDeparted { Members = new[] { "Thom" } }; session.Events.Append(id, joined); session.Events.Append(id, departed); session.SaveChanges(); var streamEvents = session.Events.FetchStream(id); Enumerable.Count<IEvent>(streamEvents).ShouldBe(3); Enumerable.ElementAt<IEvent>(streamEvents, 0).Data.ShouldBeOfType<QuestStarted>(); Enumerable.ElementAt<IEvent>(streamEvents, 0).Version.ShouldBe(1); Enumerable.ElementAt<IEvent>(streamEvents, 1).Data.ShouldBeOfType<MembersJoined>(); Enumerable.ElementAt<IEvent>(streamEvents, 1).Version.ShouldBe(2); Enumerable.ElementAt<IEvent>(streamEvents, 2).Data.ShouldBeOfType<MembersDeparted>(); Enumerable.ElementAt<IEvent>(streamEvents, 2).Version.ShouldBe(3); } } [Theory] [MemberData(nameof(SessionTypes))] public void capture_events_to_a_new_stream_and_fetch_the_events_back_in_another_database_schema( DocumentTracking sessionType) { var store = InitStore("event_store"); using (var session = store.OpenSession(sessionType)) { var joined = new MembersJoined { Members = new[] { "Rand", "Matt", "Perrin", "Thom" } }; var departed = new MembersDeparted { Members = new[] { "Thom" } }; var id = session.Events.StartStream(joined, departed).Id; session.SaveChanges(); var streamEvents = session.Events.FetchStream(id); Enumerable.Count<IEvent>(streamEvents).ShouldBe(2); Enumerable.ElementAt<IEvent>(streamEvents, 0).Data.ShouldBeOfType<MembersJoined>(); Enumerable.ElementAt<IEvent>(streamEvents, 0).Version.ShouldBe(1); Enumerable.ElementAt<IEvent>(streamEvents, 1).Data.ShouldBeOfType<MembersDeparted>(); Enumerable.ElementAt<IEvent>(streamEvents, 1).Version.ShouldBe(2); } } [Theory] [MemberData(nameof(SessionTypes))] public void capture_events_to_a_new_stream_and_fetch_the_events_back_with_stream_id_provided_in_another_database_schema( DocumentTracking sessionType) { var store = InitStore("event_store"); using (var session = store.OpenSession(sessionType)) { var joined = new MembersJoined { Members = new[] { "Rand", "Matt", "Perrin", "Thom" } }; var departed = new MembersDeparted { Members = new[] { "Thom" } }; var id = Guid.NewGuid(); session.Events.StartStream(id, joined, departed); session.SaveChanges(); var streamEvents = session.Events.FetchStream(id); Enumerable.Count<IEvent>(streamEvents).ShouldBe(2); Enumerable.ElementAt<IEvent>(streamEvents, 0).Data.ShouldBeOfType<MembersJoined>(); Enumerable.ElementAt<IEvent>(streamEvents, 0).Version.ShouldBe(1); Enumerable.ElementAt<IEvent>(streamEvents, 1).Data.ShouldBeOfType<MembersDeparted>(); Enumerable.ElementAt<IEvent>(streamEvents, 1).Version.ShouldBe(2); GenericEnumerableExtensions.Each<IEvent>(streamEvents, x => SpecificationExtensions.ShouldBeGreaterThan(x.Sequence, 0L)); } } [Theory] [MemberData(nameof(SessionTypes))] public void capture_events_to_a_non_existing_stream_and_fetch_the_events_back_in_another_database_schema( DocumentTracking sessionType) { var store = InitStore("event_store"); using (var session = store.OpenSession(sessionType)) { var joined = new MembersJoined { Members = new[] { "Rand", "Matt", "Perrin", "Thom" } }; var departed = new MembersDeparted { Members = new[] { "Thom" } }; var id = Guid.NewGuid(); session.Events.StartStream(id, joined); session.Events.Append(id, departed); session.SaveChanges(); var streamEvents = session.Events.FetchStream(id); Enumerable.Count<IEvent>(streamEvents).ShouldBe(2); Enumerable.ElementAt<IEvent>(streamEvents, 0).Data.ShouldBeOfType<MembersJoined>(); Enumerable.ElementAt<IEvent>(streamEvents, 0).Version.ShouldBe(1); Enumerable.ElementAt<IEvent>(streamEvents, 1).Data.ShouldBeOfType<MembersDeparted>(); Enumerable.ElementAt<IEvent>(streamEvents, 1).Version.ShouldBe(2); } } [Theory] [MemberData(nameof(SessionTypes))] public void capture_events_to_an_existing_stream_and_fetch_the_events_back_in_another_database_schema( DocumentTracking sessionType) { var store = InitStore("event_store"); var id = Guid.NewGuid(); var started = new QuestStarted(); using (var session = store.OpenSession(sessionType)) { session.Events.StartStream(id, started); session.SaveChanges(); } using (var session = store.OpenSession(sessionType)) { #region sample_append-events var joined = new MembersJoined { Members = new[] { "Rand", "Matt", "Perrin", "Thom" } }; var departed = new MembersDeparted { Members = new[] { "Thom" } }; session.Events.Append(id, joined, departed); session.SaveChanges(); #endregion sample_append-events var streamEvents = session.Events.FetchStream(id); Enumerable.Count<IEvent>(streamEvents).ShouldBe(3); Enumerable.ElementAt<IEvent>(streamEvents, 0).Data.ShouldBeOfType<QuestStarted>(); Enumerable.ElementAt<IEvent>(streamEvents, 0).Version.ShouldBe(1); Enumerable.ElementAt<IEvent>(streamEvents, 1).Data.ShouldBeOfType<MembersJoined>(); Enumerable.ElementAt<IEvent>(streamEvents, 1).Version.ShouldBe(2); Enumerable.ElementAt<IEvent>(streamEvents, 2).Data.ShouldBeOfType<MembersDeparted>(); Enumerable.ElementAt<IEvent>(streamEvents, 2).Version.ShouldBe(3); } } [Theory] [MemberData(nameof(SessionTypes))] public void assert_on_max_event_id_on_event_stream_append( DocumentTracking sessionType) { var store = InitStore("event_store"); var id = Guid.NewGuid(); var started = new QuestStarted(); using (var session = store.OpenSession(sessionType)) { #region sample_append-events-assert-on-eventid session.Events.StartStream(id, started); session.SaveChanges(); var joined = new MembersJoined { Members = new[] { "Rand", "Matt", "Perrin", "Thom" } }; var departed = new MembersDeparted { Members = new[] { "Thom" } }; // Events are appended into the stream only if the maximum event id for the stream // would be 3 after the append operation. session.Events.Append(id, 3, joined, departed); session.SaveChanges(); #endregion sample_append-events-assert-on-eventid } } [Theory] [MemberData(nameof(SessionTypes))] public void capture_immutable_events(DocumentTracking sessionType) { var store = InitStore(); var id = Guid.NewGuid(); var immutableEvent = new ImmutableEvent(id, "some-name"); using (var session = store.OpenSession(sessionType)) { session.Events.Append(id, immutableEvent); session.SaveChanges(); } using (var session = store.OpenSession(sessionType)) { var streamEvents = session.Events.FetchStream(id); ShouldBeTestExtensions.ShouldBe(streamEvents.Count, 1); var @event = Enumerable.ElementAt<IEvent>(streamEvents, 0).Data.ShouldBeOfType<ImmutableEvent>(); @event.Id.ShouldBe(id); @event.Name.ShouldBe("some-name"); } } private DocumentStore InitStore(string databaseSchema = null, bool cleanSchema = true) { var store = StoreOptions(_ => { if (databaseSchema != null) { _.Events.DatabaseSchemaName = databaseSchema; } _.AutoCreateSchemaObjects = AutoCreate.All; _.Connection(ConnectionSource.ConnectionString); _.Events.Projections.SelfAggregate<QuestParty>(); _.Events.AddEventType(typeof(MembersJoined)); _.Events.AddEventType(typeof(MembersDeparted)); _.Events.AddEventType(typeof(QuestStarted)); }, cleanSchema); return store; } } }