コード例 #1
1
        // Varant 2
        private static IList<int> CalculateMembers(int firstMember, int sequenceLength, IList<Func<int, int>> pattern)
        {
            var queue = new Queue<int>(50);
            var result = new List<int>(50);

            // The queue stores members for calculation.
            queue.Enqueue(firstMember);

            // The list stores the result.
            result.Add(firstMember);

            int patternLeadElement = new int();

            for (int counter = 0; counter < sequenceLength; counter += 1)
            {
                var patternIndex = counter % pattern.Count;

                // If a new pattern cycle begun, get new element for calculation.
                if (patternIndex == 0)
                {
                    patternLeadElement = queue.Dequeue();
                }

                // Calculate next member via current pattern method.
                var patternElement = pattern[patternIndex](patternLeadElement);

                queue.Enqueue(patternElement);
                result.Add(patternElement);
            }

            return result.GetRange(0, sequenceLength);
        }
コード例 #2
1
        public async Task AssignBatchActionResultsAsync(IODataClient client,
            ODataResponse batchResponse, IList<Func<IODataClient, Task>> actions, IList<int> responseIndexes)
        {
            var exceptions = new List<Exception>();
            for (var actionIndex = 0; actionIndex < actions.Count && !exceptions.Any(); actionIndex++)
            {
                var responseIndex = responseIndexes[actionIndex];
                if (responseIndex >= 0 && responseIndex < batchResponse.Batch.Count)
                {
                    var actionResponse = batchResponse.Batch[responseIndex];
                    if (actionResponse.Exception != null)
                    {
                        exceptions.Add(actionResponse.Exception);
                    }
                    else if (actionResponse.StatusCode >= (int)HttpStatusCode.BadRequest)
                    {
                        exceptions.Add(WebRequestException.CreateFromStatusCode((HttpStatusCode)actionResponse.StatusCode));
                    }
                    else
                    {
                        await actions[actionIndex](new ODataClient(client as ODataClient, actionResponse));
                    }
                }
            }

            if (exceptions.Any())
            {
                throw exceptions.First();
            }
        }
コード例 #3
1
        public void Execute(IList<Action> operations, Action<IEnumerable<Action>> remaining)
        {
            for (int i = 0; i < operations.Count; i++)
            {
                if (_stopping)
                    break;

                operations[i]();
            }
        }
コード例 #4
1
ファイル: ChaosHelper.cs プロジェクト: zybermark/ChaosDotNet
 public static void DoChaos(Func<bool> doInjectFault, IList<Action> faults)
 {
     if (faults!=null
     && faults.Count>0
     && doInjectFault()
     )
      {
     Trace.WriteLine("CHAOSMONKEY STRIKES AGAIN!!!!");
     faults[_rnd.Next(faults.Count)]();
      }
 }
コード例 #5
1
ファイル: BasicExecutor.cs プロジェクト: helios-io/helios
        public virtual void Execute(IList<Action> ops, Action<IEnumerable<Action>> remainingOps)
        {
            for (var i = 0; i < ops.Count; i++)
            {
                if (!AcceptingJobs)
                {
                    remainingOps.NotNull(obj => remainingOps(ops.Skip(i + 1)));
                    break;
                }

                ops[i]();
            }
        }
コード例 #6
1
ファイル: EmitExtensions.cs プロジェクト: virmitio/coapp
        /// <summary>
        ///   Emits an array.
        /// </summary>
        /// <param name="generator"> The generator. </param>
        /// <param name="arrayType"> Type of the array. </param>
        /// <param name="emitElements"> The emit elements. </param>
        public static void EmitArray(this ILGenerator generator, Type arrayType, IList<Action<ILGenerator>> emitElements)
        {
            var tLocal = generator.DeclareLocal(arrayType.MakeArrayType());
            generator.Emit(OpCodes.Ldc_I4, emitElements.Count);
            generator.Emit(OpCodes.Newarr, arrayType);
            generator.EmitStoreLocation(tLocal.LocalIndex);

            for (var i = 0; i < emitElements.Count; i++) {
                generator.EmitLoadLocation(tLocal.LocalIndex);
                generator.Emit(OpCodes.Ldc_I4, i);
                emitElements[i](generator);
                generator.Emit(OpCodes.Stelem_Ref);
            }
            generator.EmitLoadLocation(tLocal.LocalIndex);
        }
コード例 #7
1
        public DefaultRequestDispatcherFixture()
        {
            this.responseProcessors = new List<IResponseProcessor>();
            this.routeResolver = A.Fake<IRouteResolver>();
            this.routeInvoker = A.Fake<IRouteInvoker>();
            this.negotiator = A.Fake<IResponseNegotiator>();

            A.CallTo(() => this.routeInvoker.Invoke(A<Route>._, A<CancellationToken>._, A<DynamicDictionary>._, A<NancyContext>._))
                .ReturnsLazily(async arg =>
                {
                    var routeResult = ((Route)arg.Arguments[0]).Invoke((DynamicDictionary)arg.Arguments[2], new CancellationToken()).ConfigureAwait(false);
                    var x = await routeResult;

                    return (Response)x;
                });

            this.requestDispatcher =
                new DefaultRequestDispatcher(this.routeResolver, this.responseProcessors, this.routeInvoker, this.negotiator);

            var resolvedRoute = new ResolveResult
            {
                Route = new FakeRoute(),
                Parameters = DynamicDictionary.Empty,
                Before = null,
                After = null,
                OnError = null
            };

            A.CallTo(() => this.routeResolver.Resolve(A<NancyContext>._)).Returns(resolvedRoute);
        }
コード例 #8
1
        public void SetCurrent(UiEncodingWindowSource source, IList<int> mainIndices, IList<int> additionalIndices)
        {
            CurrentSource = source;
            CurrentMainIndices = mainIndices;
            CurrentAdditionalIndices = additionalIndices;

            for (int i = mainIndices.Count; i < _mainControls.Count; i++)
                _mainControls[i].Visibility = Visibility.Collapsed;
            for (int i = additionalIndices.Count; i < _additionalControls.Count; i++)
                _additionalControls[i].Visibility = Visibility.Collapsed;

            if (CurrentSource == null)
                return;

            for (int i = 0; i < mainIndices.Count; i++)
            {
                _mainControls[i].Load(source, mainIndices[i]);
                _mainControls[i].Visibility = Visibility.Visible;
            }

            for (int i = 0; i < additionalIndices.Count; i++)
            {
                _additionalControls[i].Load(source, additionalIndices[i]);
                _additionalControls[i].Visibility = Visibility.Visible;
            }

            _drawEvent.NullSafeSet();
        }
コード例 #9
1
        public void should_parse_objects_symbols_and_properties_when_parsing_more_complex_xml_content()
        {
            Lexemes = Parser.Parse(ComplexXml);

            Lexemes.Count.ShouldBe(136);
            Lexemes.Count(lx => lx.Type == LexemType.Comment).ShouldBe(6);
        }
コード例 #10
1
        public override void Draw(
			IList<Point> points,
			double thickness,
			int miterLimit,
			ILogicalToScreenMapper logicalToScreenMapper)
        {
            // First define the geometric shape
            var streamGeometry = new StreamGeometry();
            using (var gc = streamGeometry.Open())
            {
                gc.BeginFigure(points[0], _fillAndClose, _fillAndClose);
                points.RemoveAt(0);

                gc.PolyLineTo(points, true, true);
            }

            using (var dc = RenderOpen())
                dc.DrawGeometry(
                    _fillAndClose ? Brushes.White : null,
                    new Pen(
                        Brushes.White,
                        thickness == 1 ? 0.25 : thickness)
                        {
                            MiterLimit = miterLimit
                        },
                    streamGeometry);
        }
コード例 #11
1
 public static void Require(IList<string> errors, string fieldValue, string error)
 {
     if (String.IsNullOrEmpty(fieldValue))
     {
         errors.Add(error);
     }
 }
コード例 #12
1
 public static void AddRoleClaims(IEnumerable<string> roles, IList<Claim> claims)
 {
     foreach (string role in roles)
     {
         claims.Add(new Claim(RoleClaimType, role, ClaimsIssuer));
     }
 }
コード例 #13
1
ファイル: ControllerHelper.cs プロジェクト: jzinedine/Cedar
 public static void GetLocationSelectedListItem(IList<Location> locations, out MultiSelectList allLocation, out List<SelectListItem> selectListItems)
 {
     var multiSelectList = new MultiSelectList(locations, "LocationId", "Province", locations);
     allLocation = multiSelectList;
     selectListItems =
         locations.Select(o => new SelectListItem { Text = o.Province, Value = o.Province }).ToList();
 }
コード例 #14
1
ファイル: EpiphanyAbility.cs プロジェクト: mynew4/DAoC
 public override void AddEffectsInfo(IList<string> list)
 {
     list.Add("25% Group power refresh.");
     list.Add("");
     list.Add("Target: Group");
     list.Add("Casting time: instant");
 }
コード例 #15
1
 public EnumerationSignature (string serviceName, string enumName, IList<EnumerationValueSignature> values, string documentation)
 {
     Name = enumName;
     FullyQualifiedName = serviceName + "." + Name;
     Values = values;
     Documentation = DocumentationUtils.ResolveCrefs (documentation);
 }
コード例 #16
1
        public ICLS_Expression Compiler(IList<Token> tlist, ICLS_Environment content)
        {
            ICLS_Expression value;

            int expbegin = 0;
            int expend = FindCodeBlock(tlist, expbegin);
            if (expend != tlist.Count - 1)
            {
                LogError(tlist, "CodeBlock 识别问题,异常结尾", expbegin, expend);
                return null;
            }
            bool succ = Compiler_Expression_Block(tlist, content, expbegin, expend, out value);
            if (succ)
            {
                if (value == null)
                {
                    logger.Log_Warn("编译为null:");
                }
                return value;

            }
            else
            {
                LogError(tlist, "编译失败:", expbegin, expend);
                return null;
            }



        }
コード例 #17
1
ファイル: SiteMapService.cs プロジェクト: HRINY/HRI-Umbraco
 /// <summary>
 /// Recursive menu builder
 /// </summary>
 /// <param name="flatList">Original flat menu items list</param>
 /// <param name="parentId">Parent node ID</param>
 /// <returns>Hierarchical list</returns>
 private IList<SiteMapItem> BuildTree(IList<SiteMapItem> flatList, int parentId)
 {
     var list = new List<SiteMapItem>();
     EnumerableExtensions.ForEach(flatList.Where(x => x.ParentId == parentId), list.Add);
     list.ForEach(x => x.Children = BuildTree(flatList, x.Id));
     return list;
 }
コード例 #18
1
ファイル: World.cs プロジェクト: maconbot/c4g
		public void Initialise()
		{
			_primitives = new List<Cube>();
			var random = new Random();
			for (int i = 0; i < Constants.CubeCount; i++)
			{
				_primitives.Add(new Cube
					{
						Color = Color.Red,
						Position = new Vector3(random.Next(100) - 50, random.Next(100) - 50, -random.Next(100)),
						Radius = random.Next(100),
						Rotation = Vector3.Zero
					});
			}
            //How to create a kernel and a channel?
//			_kernel = 
//		    _channel = 

			

			_colour = Color.Beige;
			
			_kernel.Factory.NewCoroutine(ChangePosition);
			_kernel.Factory.NewCoroutine(ChangeColour);
		    
		}
コード例 #19
1
ファイル: SmugglerApi.cs プロジェクト: robashton/ravendb
		public SmugglerApi(SmugglerOptions smugglerOptions, IAsyncDatabaseCommands commands, Action<string> output)
			: base(smugglerOptions)
		{
			this.commands = commands;
			this.output = output;
			batch = new List<RavenJObject>();
		}
コード例 #20
1
        /// <summary>
        /// Replaces the intrinsic call site
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="typeSystem">The type system.</param>
        void IIntrinsicPlatformMethod.ReplaceIntrinsicCall(Context context, ITypeSystem typeSystem, IList<RuntimeParameter> parameters)
        {
            var result = context.Result;
            var op1 = context.Operand1;
            var op2 = context.Operand2;
            var constant = Operand.CreateConstant(BuiltInSigType.IntPtr, parameters.Count * 4);

            var eax = Operand.CreateCPURegister(BuiltInSigType.IntPtr, GeneralPurposeRegister.EAX); // FIXME - need access to virtual register allocator
            var edx = Operand.CreateCPURegister(BuiltInSigType.IntPtr, GeneralPurposeRegister.EDX); // FIXME - need access to virtual register allocator
            var esp = Operand.CreateCPURegister(BuiltInSigType.IntPtr, GeneralPurposeRegister.ESP); // FIXME - need access to virtual register allocator
            var ebp = Operand.CreateCPURegister(BuiltInSigType.IntPtr, GeneralPurposeRegister.EBP); // FIXME - need access to virtual register allocator
            context.SetInstruction(X86.Sub, esp, constant);
            context.AppendInstruction(X86.Mov, edx, esp);

            var size = parameters.Count * 4 + 4;
            foreach (var parameter in parameters)
            {
                context.AppendInstruction(X86.Mov, Operand.CreateMemoryAddress(BuiltInSigType.IntPtr, edx, new IntPtr(size - 4)), Operand.CreateMemoryAddress(BuiltInSigType.IntPtr, ebp, new IntPtr(size + 4)));
                size -= 4;
            }
            context.AppendInstruction(X86.Mov, Operand.CreateMemoryAddress(BuiltInSigType.IntPtr, edx, new IntPtr(size - 4)), op1);

            context.AppendInstruction(X86.Mov, eax, op2);
            context.AppendInstruction(X86.Call, null, eax);
            context.AppendInstruction(X86.Add, esp, constant);
            context.AppendInstruction(X86.Mov, result, Operand.CreateCPURegister(result.Type, GeneralPurposeRegister.EAX)); // FIXME - need access to virtual register allocator
        }
コード例 #21
1
 private ParametriAggiuntiviCompilazioneLettera(TipoModelloLetteraEnum tipoLettera = TipoModelloLetteraEnum.Messaggistica, string bodyFormat = "PLAIN", List<TipoMessaggio> tipiMessaggioConsentiti = null, TipoMessaggio tipoMessaggioPredefinito = TipoMessaggio.Manuale)
 {
     TipoLettera = tipoLettera;
     BodyFormat = bodyFormat;
     TipiMessaggioConsentiti = tipiMessaggioConsentiti;
     TipoMessaggioPredefinito = tipoMessaggioPredefinito;
 }
コード例 #22
1
ファイル: Command.cs プロジェクト: damy90/Telerik-all
        private void TranslateInput(string input)
        {
            var indexOfFirstSeparator = input.IndexOf(SplitCommandSymbol);

            this.Name = input.Substring(0, indexOfFirstSeparator);
            this.Parameters = input.Substring(indexOfFirstSeparator + 1).Split(new[] { SplitCommandSymbol }, StringSplitOptions.RemoveEmptyEntries);
        }
コード例 #23
1
ファイル: Messenger.cs プロジェクト: yonglehou/sharpsnmplib
        /// <summary>
        /// Gets a list of variable binds.
        /// </summary>
        /// <param name="version">Protocol version.</param>
        /// <param name="endpoint">Endpoint.</param>
        /// <param name="community">Community name.</param>
        /// <param name="variables">Variable binds.</param>
        /// <param name="timeout">The time-out value, in milliseconds. The default value is 0, which indicates an infinite time-out period. Specifying -1 also indicates an infinite time-out period.</param>
        /// <returns></returns>
        public static IList<Variable> Get(VersionCode version, IPEndPoint endpoint, OctetString community, IList<Variable> variables, int timeout)
        {
            if (endpoint == null)
            {
                throw new ArgumentNullException("endpoint");
            }

            if (community == null)
            {
                throw new ArgumentNullException("community");
            }

            if (variables == null)
            {
                throw new ArgumentNullException("variables");
            }

            if (version == VersionCode.V3)
            {
                throw new NotSupportedException("SNMP v3 is not supported");
            }

            var message = new GetRequestMessage(RequestCounter.NextId, version, community, variables);
            var response = message.GetResponse(timeout, endpoint);
            var pdu = response.Pdu();
            if (pdu.ErrorStatus.ToInt32() != 0)
            {
                throw ErrorException.Create(
                    "error in response",
                    endpoint.Address,
                    response);
            }

            return pdu.Variables;
        }
コード例 #24
1
 public static IList<QueryReference> DiscoverQueryReferences(this SqlExpression expression, ref int level, IList<QueryReference> list)
 {
     var visitor = new QueryReferencesVisitor(list, level);
     visitor.Visit(expression);
     level = visitor.Level;
     return visitor.References;
 }
コード例 #25
1
        public void GivenANewHostedGameWithPlayers(int playerCount)
        {
            var gameBinding = Binding<GameStateBindings>();
            gameBinding.GivenANewGameWithPlayers(playerCount);

            _gameHost = new LockingGameHost(gameBinding.Game);           

            _clients = new List<GameClient>();
            _notifications = new Dictionary<GameClient, int>();

            foreach(var player in gameBinding.Game.Players)
            {
                var client = new GameClient(player.Id, player.Name);
                _gameHost.RegisterGameClient(client, player);
                _clients.Add(client);
                _notifications[client] = 0;
                client.GameStateUpdates.Subscribe( _ =>
                                                       {                                                           
                                                           _notifications[client] += 1;
                                                       });
            }

            

        }
コード例 #26
1
 private double GetHeightFromChildren(IList<ICanvasItem> children)
 {
     children.SwapCoordinates();
     var maxBottom = GetMaxRightFromChildren(children);
     children.SwapCoordinates();
     return maxBottom - Top;
 }
コード例 #27
1
ファイル: ErrorsHelper.cs プロジェクト: omederos/TigerNET
 private static void CheckIfReturnsSpecifiedType(ExpressionNode expression, IList<Error> errors, TigerType type)
 {
     if (!(expression.ReturnType == type)) {
         errors.Add(new UnexpectedTypeError(expression.Line, expression.Column, expression.ReturnType,
                                            IntegerType.Create()));
     }
 }
        public void AugmentCompletionSession(ICompletionSession session, IList<CompletionSet> completionSets)
        {
            int position = session.TextView.Caret.Position.BufferPosition.Position;
            var line = _buffer.CurrentSnapshot.Lines.SingleOrDefault(l => l.Start <= position && l.End >= position);
            if (line == null) return;

            int linePos = position - line.Start.Position;

            var info = NodeModuleCompletionUtils.FindCompletionInfo(line.GetText(), linePos);
            if (info == null) return;

            var callingFilename = _buffer.GetFileName();
            var baseFolder = Path.GetDirectoryName(callingFilename);

            IEnumerable<Completion> results;
            if (String.IsNullOrWhiteSpace(info.Item1))
                results = GetRootCompletions(baseFolder);
            else
                results = GetRelativeCompletions(NodeModuleService.ResolvePath(baseFolder, info.Item1));

            var trackingSpan = _buffer.CurrentSnapshot.CreateTrackingSpan(info.Item2.Start + line.Start, info.Item2.Length, SpanTrackingMode.EdgeInclusive);
            completionSets.Add(new CompletionSet(
                "Node.js Modules",
                "Node.js Modules",
                trackingSpan,
                results,
                null
            ));
        }
コード例 #29
0
        //public IList<MergeField> AnnexMergeFields { get; private set; }

        public CustomsOfficeBlock(IList<MergeField> mergeFields, TransportRoute transportRoute)
        {
            CorrespondingMergeFields = MergeFieldLocator.GetCorrespondingFieldsForBlock(mergeFields, TypeName);
            data = new CustomsOfficeViewModel(transportRoute);

            AnnexMergeFields = MergeFieldLocator.GetAnnexMergeFields(mergeFields, TypeName);
        }
コード例 #30
0
        public RecordsetGroup(IBinaryDataListEntry sourceEntry, IList<IDev2Definition> definitions, Func<IDev2Definition, string> inputExpressionExtractor, Func<IDev2Definition, string> outputExpressionExtractor)
        {
            if(sourceEntry == null)
            {
                throw new ArgumentNullException("sourceEntry");
            }

            if(definitions == null)
            {
                throw new ArgumentNullException("definitions");
            }
            if(inputExpressionExtractor == null)
            {
                throw new ArgumentNullException("inputExpressionExtractor");
            }
            if(outputExpressionExtractor == null)
            {
                throw new ArgumentNullException("outputExpressionExtractor");
            }

            SourceEntry = sourceEntry;
            Definitions = definitions;
            InputExpressionExtractor = inputExpressionExtractor;
            OutputExpressionExtractor = outputExpressionExtractor;
        }
        public static IServiceCollection AddCustomizedMvc(this IServiceCollection services, IList<ModuleInfo> modules,
            IConfiguration configuration, IHostingEnvironment hostingEnvironment)
        {
            var mvcBuilder = services
                .AddMvc()
                .AddJsonOptions(
                    options => options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
                )
                .SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
                .AddRazorOptions(o =>
                {
                    foreach (var module in modules)
                    {
                        o.AdditionalCompilationReferences.Add(
                            MetadataReference.CreateFromFile(module.Assembly.Location));
                    }
                });

            foreach (var module in modules)
            {
                // Register controller from modules to main web host
                mvcBuilder.AddApplicationPart(module.Assembly);

                // Register dependency in modules
                var moduleInitializerType =
                    module.Assembly.GetTypes().FirstOrDefault(x => typeof(IModuleInitializer).IsAssignableFrom(x));
                if ((moduleInitializerType != null) && (moduleInitializerType != typeof(IModuleInitializer)))
                {
                    var moduleInitializer = (IModuleInitializer)Activator.CreateInstance(moduleInitializerType);
                    moduleInitializer.Init(services);
                }
            }

            var builder = new ContainerBuilder();
            foreach (var module in GlobalConfiguration.Modules)
            {
                builder.RegisterAssemblyTypes(module.Assembly).AsImplementedInterfaces();
            }

            builder.RegisterInstance(configuration);
            builder.RegisterInstance(hostingEnvironment);
            builder.Populate(services);

            var container = builder.Build();
            container.Resolve<IServiceProvider>();

            return services;
        }
コード例 #32
0
ファイル: Tags.cs プロジェクト: PeterAfN/ClipboardHelperRegEx
        /// <summary>
        ///     Transforms tags for presentation for the user. There are five places where presentation occurs: In the settings,
        ///     in the program main form, when pasting to another program, when clicking on a item (opens url in web browser) or
        ///     in tags inside tags (nested tags).
        /// </summary>
        public async void TransformLines(
            int navigationPosition,
            int id,
            PresenterMainSplContPanelUpTabs.LineChangeType lineChangeType,
            int tabIndex,
            List <string> lines,
            List <TagType> tags,
            Action <int, int, PresenterMainSplContPanelUpTabs.LineChangeType, int, IList <string>, bool, string, int> action,
            string clipboard          = "",
            bool changedContentEdited = false,
            string changedContent     = "")
        {
            Cancel();
            Action                = action;
            Lines                 = lines;
            TokenSource           = new CancellationTokenSource();
            _cancellationToken    = TokenSource.Token;
            _changedContent       = changedContent;
            _changedContentEdited = changedContentEdited;
            if (Lines == null)
            {
                return;
            }
            var linesWithIndex = CreateLinesWithIndex(Lines);

            var linesFast = GetFastLines(linesWithIndex);

            LinesOut = new List <string>(lines);
            foreach (var line in linesFast)
            {
                LinesOut[line.Key] = TransformLine(line.Value, UsedIn.MainDisplay, tags, clipboard);
            }

            //Set fast lines
            if (Action == null)
            {
                return;
            }
            {
                Action(navigationPosition, id, lineChangeType, tabIndex, LinesOut, changedContentEdited,
                       _changeableContent, -1);

                var linesSlow = GetSlowLines(linesWithIndex);
                var stripped  = StripOutEverythingExceptLineNumberingAndInfoTag(linesSlow);
                foreach (var line in stripped)
                {
                    LinesOut[line.Key] = TransformLine(line.Value, UsedIn.MainDisplay, tags, clipboard);
                }

                //Set slow lines
                Action(navigationPosition, id, lineChangeType, tabIndex, LinesOut, changedContentEdited,
                       _changeableContent, -1);

                //Set slow lines async
                if (linesSlow.Count != 0)
                {
                    await Task.Run(() => SetLinesAsync(navigationPosition, id, lineChangeType, tabIndex,
                                                       linesSlow, tags, Action, _cancellationToken, clipboard, changedContentEdited),
                                   _cancellationToken).ConfigureAwait(true); //parse delayed Tags
                }
            }
        }
コード例 #33
0
        public void Attach(EventType parentEventType, StatementContext statementContext, ViewFactory optionalParentFactory, IList <ViewFactory> parentViewFactories)
        {
            _eventType = parentEventType;

            // define built-in fields
            var builtinTypeDef = ExpressionViewOAFieldEnumExtensions.AsMapOfTypes(_eventType);

            _builtinMapType = statementContext.EventAdapterService.CreateAnonymousObjectArrayType(
                statementContext.StatementId + "_exprview", builtinTypeDef);

            StreamTypeService streamTypeService = new StreamTypeServiceImpl(new EventType[] { _eventType, _builtinMapType }, new String[2], new bool[2], statementContext.EngineURI, false);

            // validate expression
            ExpiryExpression = ViewFactorySupport.ValidateExpr(ViewName, statementContext, ExpiryExpression, streamTypeService, 0);

            var summaryVisitor = new ExprNodeSummaryVisitor();

            ExpiryExpression.Accept(summaryVisitor);
            if (summaryVisitor.HasSubselect || summaryVisitor.HasStreamSelect || summaryVisitor.HasPreviousPrior)
            {
                throw new ViewParameterException("Invalid expiry expression: Sub-select, previous or prior functions are not supported in this context");
            }

            var returnType = ExpiryExpression.ExprEvaluator.ReturnType;

            if (returnType.GetBoxedType() != typeof(bool?))
            {
                throw new ViewParameterException("Invalid return value for expiry expression, expected a bool return value but received " + returnType.GetParameterAsString());
            }

            // determine variables used, if any
            var visitor = new ExprNodeVariableVisitor();

            ExpiryExpression.Accept(visitor);
            VariableNames = visitor.VariableNames;

            // determine aggregation nodes, if any
            var aggregateNodes = new List <ExprAggregateNode>();

            ExprAggregateNodeUtil.GetAggregatesBottomUp(ExpiryExpression, aggregateNodes);
            if (aggregateNodes.IsNotEmpty())
            {
                try {
                    AggregationServiceFactoryDesc = AggregationServiceFactoryFactory.GetService(
                        Collections.GetEmptyList <ExprAggregateNode>(),
                        Collections.GetEmptyMap <ExprNode, String>(),
                        Collections.GetEmptyList <ExprDeclaredNode>(),
                        null, aggregateNodes,
                        Collections.GetEmptyList <ExprAggregateNode>(),
                        Collections.GetEmptyList <ExprAggregateNodeGroupKey>(), false,
                        statementContext.Annotations,
                        statementContext.VariableService, false, false, null, null,
                        statementContext.AggregationServiceFactoryService,
                        streamTypeService.EventTypes,
                        statementContext.MethodResolutionService, null,
                        statementContext.ContextName,
                        null, null, false, false, false);
                }
                catch (ExprValidationException ex) {
                    throw new ViewParameterException(ex.Message, ex);
                }
            }
        }
コード例 #34
0
 public PersonService()
 {
     _data = GeneratePeople();
 }
コード例 #35
0
 public CardItemsAdapter(Activity context, int height, int spacing, IList<CardItem> values)
 {
     _gen = new CardsViewMaker(context, height, spacing, values);
     _values = values;
 }
コード例 #36
0
        public bool HidePaymentMethod(IList<ShoppingCartItem> cart)
        {
            var match = _klarnaCheckout.GetSupportedLocale();

            return match == null;
        }
コード例 #37
0
ファイル: Indexable.cs プロジェクト: slozier/ironpython3
 public UsePythonListAsList(IList <int> list)
 {
     this.list = list;
 }
コード例 #38
0
 private static IEnumerable <string> GetSelect(IList <SelectElement> elements)
 {
     return(elements.Select((e) => GetString(e)).Distinct());
 }
コード例 #39
0
 /// <summary>
 /// Initializes a new instance of the NotificationIdList class.
 /// </summary>
 /// <param name="values">List of notification Ids.</param>
 public NotificationIdList(IList<string> values)
 {
     Values = values;
     CustomInit();
 }
コード例 #40
0
ファイル: Game.cs プロジェクト: holmak/minimalist-rpg-demo
 static T Choose<T>(Random random, IList<T> list)
 {
     return list[random.Next(list.Count)];
 }
コード例 #41
0
        /// <summary>
        /// Excludes the file and folder items from their corresponding maps if they are part of the build.
        /// </summary>
        /// <param name="project">The project to modify.</param>
        /// <param name="fileList">List containing relative files paths.</param>
        /// <param name="folderList">List containing relative folder paths.</param>
        private static void ExcludeProjectBuildItems(ProjectNode project, IList<string> fileList, IList<string> folderList)
        {
            BuildItemGroup projectItems = project.BuildProject.EvaluatedItems;

            if (projectItems == null)
                return; // do nothig, just ignore it.
                        
            if (fileList == null && folderList == null)
                throw new ArgumentNullException("folderList");
            
            // we need these maps becuase we need to have both lowercase and actual case path information.
            // we use lower case paths for case-insesitive search of file entries and actual paths for 
            // creating hierarchy node. if we don't do that, we will end up with duplicate nodes when the
            // case of path in .wixproj file doesn't match with the actual file path on the disk.
            IDictionary<string, string> folderMap = null;
            IDictionary<string, string> fileMap = null;

            if (folderList != null)
            {
                folderMap = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
                foreach (string folder in folderList)
                    folderMap.Add(folder, folder);
            }

            if (fileList != null)
            {
                fileMap = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
                foreach (string file in fileList)
                    fileMap.Add(file, file);
            }

            foreach (BuildItem buildItem in projectItems)
            {
                if (folderMap != null &&
                    folderMap.Count > 0 &&
                    String.Equals(buildItem.Name, ProjectFileConstants.Folder, StringComparison.OrdinalIgnoreCase))
                {
                    string relativePath = buildItem.FinalItemSpec;
                    if (Path.IsPathRooted(relativePath)) // if not the relative path, make it relative
                        relativePath = Utils.GetRelativePath(project.ProjectFolder, relativePath);
                    
                    if (folderMap.ContainsKey(relativePath))
                    {
                        folderList.Remove(folderMap[relativePath]); // remove it from the actual list.
                        folderMap.Remove(relativePath);
                    }
                }
                else if (fileMap != null &&
                    fileMap.Count > 0 &&
                    IsNemerleFileItem(buildItem))
                {
                    string relativePath = buildItem.FinalItemSpec;
                    if (Path.IsPathRooted(relativePath)) // if not the relative path, make it relative
                    {
                        relativePath = Utils.GetRelativePath(project.ProjectFolder, relativePath);
                    }

                    if (fileMap.ContainsKey(relativePath))
                    {
                        fileList.Remove(fileMap[relativePath]); // remove it from the actual list.
                        fileMap.Remove(relativePath);
                    }
                }
            }
        }
コード例 #42
0
        public static void CountryBreadcrumb(this IList<BreadcrumbViewModel> breadcrumbViewModels, CountryV countryV, DateTime viewDate)
        {
            breadcrumbViewModels.OrganisationBreadcrumb(countryV.Organisation.GetApprovedVersion<OrganisationV>(viewDate), viewDate);

            breadcrumbViewModels.Add(AreaType.Cnt, countryV.HeaderKey, countryV.CountryName, string.Empty);
        }
コード例 #43
0
        public static void MatchBreadcrumb(this IList<BreadcrumbViewModel> breadcrumbViewModels, MatchV matchV, DateTime viewDate)
        {
            breadcrumbViewModels.CompetitionBreadcrumb(matchV.CampaignStage.Campaign.Competition.GetApprovedVersion<CompetitionV>(viewDate), viewDate);

            breadcrumbViewModels.Add(AreaType.Mtc, matchV.HeaderKey, matchV.ToViewModel(viewDate).ToString(), string.Empty);
        }
コード例 #44
0
        /// <summary>
        /// Finds all linked uris of a resource and filters the resources deleted by the current save process.
        /// This implies all uris found in the repo resource but no longer found in the current resource.
        /// </summary>
        /// <param name="resource"></param>
        /// <param name="repoResource"></param>
        /// <returns></returns>
        private IList<string> GetLinkedPidUris(Resource resource, Entity repoResource, IList<MetadataProperty> metadataProperties)
        {
            var linkedPidUris = GetLinkedPidUris(resource, metadataProperties);

            var repoLinkedPidUris = GetLinkedPidUris(repoResource, metadataProperties);

            return repoLinkedPidUris.Except(linkedPidUris).ToList();
        }
コード例 #45
0
        /// <summary>
        /// Delete resource and update all linked resources.
        ///
        /// Outbound -> RegistrationService
        /// Inbound -> RegistrationService
        /// Versions -> Update one of the versioned resources in the crawler
        ///
        /// Crawler check if resource is published
        /// </summary>
        /// <param name="resource">Resource to be deleted</param>
        public void SendResourceDeleted(Resource resource, IList<string> inboundProperties, IList<MetadataProperty> metadataProperties)
        {
            SendResourceDeleted(resource.PidUri.ToString());

            var oneVersionedResource = resource.Versions.FirstOrDefault(t => t.PidUri != resource.PidUri.OriginalString)?.PidUri;

            // TODO: try catch and Log error
            // TODO: Concat or Addrange check
            var linkedPidURis = GetLinkedPidUris(resource, metadataProperties).Concat(inboundProperties).Distinct();

            linkedPidURis.Append(oneVersionedResource);

            foreach (var pidUri in linkedPidURis)
            {
                SendResourcePublished(pidUri);
            }
        }
コード例 #46
0
        public void Calculate( IList<CalculationPointDLE> points )
        {
            // главный цикл по лучам
            for ( var iteration = 0; iteration < NRays; iteration++ )
            {
                // определяем источник
                var light = this.RouletteLight();

                // розыгрыш луча от источника
                var ray = light.RandomRay();


                // DEBUG
                // [0,000 ms] - Ray.From = x = 0,06968741, y = 0,1730685, z = 4,9, Ray.To = x = -2,499, y = 0,1456028, z = 2,175853
                // [0,000 ms] - Ray.From = x = 0,7848736, y = -2,312128, z = 0,0009999275, Ray.To = x = 0,785834, y = -0,3403686, z = 1,224729
                //ray = new LightRay(ray.From, new Vector( -0.1f, -0.25f, -1, true ), ray.Illuminance );
                //ray.To = new Point3D()


                var wMinFact = ray.Illuminance.ValueMax * WMin;

                // основной блуждания луча
                int rayIteration = 0;
                while ( ray.Illuminance.ValueMax > wMinFact && rayIteration < 8 )
                {
                    rayIteration++;

                    // ищем пересечение с элементом сцены
                    var intersection = this.RayTracer.Trace( ray.From, ray.Direction, Constants.Epsilon );
                    while ( intersection != null && intersection.Face.Material.Reflectance == null )
                    {
                        if ( intersection.Face.Material.Mirror != null )
                        {
                            var mirrorRay = Vector.Reflect( ray.Direction, intersection.Face.Normal );
                            mirrorRay.Normalize();
                            ray.From = intersection.Point;
                            ray.Direction = mirrorRay;
                            intersection = this.RayTracer.Trace( ray.From, ray.Direction, Constants.Epsilon );
                        }
                        else
                            throw new NotImplementedException();
                    }
                    if ( intersection == null )
                        break;

                    //RayDebugStaticCollection.Add( new Ray( ray.From, intersection.Point ), Color.Blue );
                    //this.Log.Message( string.Format( "Ray.From = {0}, Ray.To = {1}", ray.From, intersection.Point ) );

                    var intersectionNormal = intersection.Face.Normal;
                    var intesectionPointOcclude = intersection.Point + intersectionNormal * Constants.Epsilon;

                    // для всех расчетных точек производимы вычисления
                    foreach ( var point in points )
                    {
                        var renderPointNormal = point.Face.Normal;


                        //if (point.Obj.Name == "Box2")
                        //{
                        //    point.Illuminance = new Spectrum(1f, 0, 0);
                        //    continue;
                        //}

                        if ( Vector.Dot( intersectionNormal, renderPointNormal ) > Constants.Epsilon )
                        {
                            point.CounterVisibleNormals++;
                            continue;
                        }


                        var pointOcclude = point.Position;

                        // направление от точки до точки рендеринга
                        var r2 = Point3D.LenghtSquared( intesectionPointOcclude, pointOcclude );

                        var coreDirection = new Vector( intesectionPointOcclude, pointOcclude, true );
                        //var occludeRayLength = (float)Math.Sqrt( r2 ) - Constants.Epsilon;

                        //r2 = Point3D.LenghtSquared(intesectionPointOcclude, point.Position );
                        var occludeRayLength = (float)Math.Sqrt( r2 ) - Constants.Epsilon;


                        if ( this.RayTracer.Occluded( intesectionPointOcclude, coreDirection, 0, occludeRayLength ) )
                        {
                            point.CounterOccluded++;
                            continue;
                        }



                        //if ( this.RayTracer.Occluded( intersection.Point, coreDirection, Constants.Epsilon, occludeRayLength ) )
                        //    continue;

                        var cos1 = ( Vector.Dot( coreDirection, intersectionNormal ) );
                        var cos2 = Math.Abs( Vector.Dot( coreDirection, renderPointNormal ) );

                        if ( cos1 < Constants.Epsilon2 )
                            point.CounterRaysCos1Zero++;
                        if ( cos2 < Constants.Epsilon )
                            point.CounterRaysCos2Zero++;

                        cos1 = Math.Abs( cos1 );
                        cos2 = Math.Abs( cos2 );

                        var sigma1 = intersection.Face.Material.Reflectance.BRDF( ray.Direction, intersectionNormal,
                            coreDirection );

                        var kernel1 = sigma1 * cos1 * cos2 / r2;
                        //var kernel1 = intersection.Face.Material.BRDF( ray.Direction, intersection.Face.Normal,
                        //    core1Direction );

                        //var kernel1 = new Spectrum( sigma1 );

                        //kernel1.Multiplication( cos1 * cos2 / r2 );

                        // Ядро 2. Переход из суб. точки в искомое направление
                        var sigma2 = point.Face.Material.Reflectance.BRDF( coreDirection, renderPointNormal,
                            point.Direction );

                        var kernel2 = sigma2;

                        point.Illuminance += ray.Illuminance * kernel1 * kernel2;

                    }

                    var newDirection = intersection.Face.Material.Reflectance.RandomReflectedDirection( ray.Direction,
                            intersectionNormal );
                    var brdf = intersection.Face.Material.Reflectance.BRDF( ray.Direction, intersectionNormal, newDirection );

                    ray = new LightRay( intersection.Point, newDirection, ray.Illuminance * brdf );

                    /*
                    if (rayIteration == 1)
                        ray = new LightRay(ray.From, new Vector(1f, 0, 1f), ray.Illuminance);
                    else if ( rayIteration == 2 )
                        ray = new LightRay( ray.From, new Vector( -0.85f, 1.5f, 1.5f, true ), ray.Illuminance );
                    
                     * */
                }

                if ( iteration % 100 == 0 )
                    this.Log.Message( string.Format( "Render {0} rays", iteration ), 1 );

            }


            const float norm = 4 * Constants.PI;
            foreach ( var point in points )
            {
                point.Illuminance *= ( norm / ( NRays * Constants.PI * Constants.PI ) );
            }
        }
コード例 #47
0
 public decimal GetAdditionalHandlingFee(IList<ShoppingCartItem> cart)
 {
     return 0m;
 }
コード例 #48
0
ファイル: Ticket.cs プロジェクト: savasl/SambaPOS-3
 public void SetLogs(IList <TicketLogValue> logs)
 {
     TicketLogs       = JsonHelper.Serialize(logs);
     _ticketLogValues = null;
 }
コード例 #49
0
        public static async Task <bool> ExtractFromTagsAsync(ILocalFsResourceAccessor folderOrFileLfsra, MovieInfo movieInfo)
        {
            // Calling EnsureLocalFileSystemAccess not necessary; only string operation
            string extensionLower = StringUtils.TrimToEmpty(Path.GetExtension(folderOrFileLfsra.LocalFileSystemPath)).ToLower();

            if (!MatroskaConsts.MATROSKA_VIDEO_EXTENSIONS.Contains(extensionLower))
            {
                return(false);
            }

            // Try to get extended information out of matroska files)
            MatroskaBinaryReader mkvReader = new MatroskaBinaryReader(folderOrFileLfsra);
            // Add keys to be extracted to tags dictionary, matching results will returned as value
            Dictionary <string, IList <string> > tagsToExtract = MatroskaConsts.DefaultVideoTags;
            await mkvReader.ReadTagsAsync(tagsToExtract).ConfigureAwait(false);

            // Read plot
            IList <string> tags = tagsToExtract[MatroskaConsts.TAG_EPISODE_SUMMARY];
            string         plot = tags != null?tags.FirstOrDefault() : string.Empty;

            if (!string.IsNullOrEmpty(plot))
            {
                movieInfo.HasChanged |= MetadataUpdater.SetOrUpdateString(ref movieInfo.Summary, plot, true);
            }

            // Read genre
            tags = tagsToExtract[MatroskaConsts.TAG_SERIES_GENRE];
            if (tags != null)
            {
                List <GenreInfo> genreList = tags.Where(s => !string.IsNullOrEmpty(s?.Trim())).Select(s => new GenreInfo {
                    Name = s.Trim()
                }).ToList();
                movieInfo.HasChanged |= MetadataUpdater.SetOrUpdateList(movieInfo.Genres, genreList, movieInfo.Genres.Count == 0);
            }

            // Read actors
            tags = tagsToExtract[MatroskaConsts.TAG_ACTORS];
            if (tags != null)
            {
                movieInfo.HasChanged |= MetadataUpdater.SetOrUpdateList(movieInfo.Actors,
                                                                        tags.Select(t => new PersonInfo()
                {
                    Name = t, Occupation = PersonAspect.OCCUPATION_ACTOR, MediaName = movieInfo.MovieName.Text
                }).ToList(), false);
            }

            tags = tagsToExtract[MatroskaConsts.TAG_DIRECTORS];
            if (tags != null)
            {
                movieInfo.HasChanged |= MetadataUpdater.SetOrUpdateList(movieInfo.Directors,
                                                                        tags.Select(t => new PersonInfo()
                {
                    Name = t, Occupation = PersonAspect.OCCUPATION_DIRECTOR, MediaName = movieInfo.MovieName.Text
                }).ToList(), false);
            }

            tags = tagsToExtract[MatroskaConsts.TAG_WRITTEN_BY];
            if (tags != null)
            {
                movieInfo.HasChanged |= MetadataUpdater.SetOrUpdateList(movieInfo.Writers,
                                                                        tags.Select(t => new PersonInfo()
                {
                    Name = t, Occupation = PersonAspect.OCCUPATION_WRITER, MediaName = movieInfo.MovieName.Text
                }).ToList(), false);
            }

            if (tagsToExtract[MatroskaConsts.TAG_MOVIE_IMDB_ID] != null)
            {
                string imdbId;
                foreach (string candidate in tagsToExtract[MatroskaConsts.TAG_MOVIE_IMDB_ID])
                {
                    if (ImdbIdMatcher.TryMatchImdbId(candidate, out imdbId))
                    {
                        movieInfo.HasChanged |= MetadataUpdater.SetOrUpdateId(ref movieInfo.ImdbId, imdbId);
                        break;
                    }
                }
            }
            if (tagsToExtract[MatroskaConsts.TAG_MOVIE_TMDB_ID] != null)
            {
                int tmp;
                foreach (string candidate in tagsToExtract[MatroskaConsts.TAG_MOVIE_TMDB_ID])
                {
                    if (int.TryParse(candidate, out tmp) == true)
                    {
                        movieInfo.HasChanged |= MetadataUpdater.SetOrUpdateId(ref movieInfo.MovieDbId, tmp);
                        break;
                    }
                }
            }

            return(true);
        }
コード例 #50
0
ファイル: Ticket.cs プロジェクト: savasl/SambaPOS-3
        public Order AddOrder(AccountTransactionType template, Department department, string userName, MenuItem menuItem, IList <TaxTemplate> taxTemplates, MenuItemPortion portion, string priceTag, ProductTimer timer)
        {
            UnLock();
            var order = OrderBuilder.Create()
                        .WithDepartment(department)
                        .ForMenuItem(menuItem)
                        .WithUserName(userName)
                        .WithTaxTemplates(taxTemplates)
                        .WithPortion(portion)
                        .WithPriceTag(priceTag)
                        .WithAccountTransactionType(template)
                        .WithProductTimer(timer)
                        .Build();

            AddOrder(order, taxTemplates, template, userName);
            return(order);
        }
コード例 #51
0
 public CardItemsAdapter(Activity context, IList<CardItem> values)
 {
     _gen = new CardsViewMaker(context, values);
     _values = values;
 }
コード例 #52
0
 public void TestOnCompilerMessageReceived(IList <ICompileMessageTO> messages)
 {
     OnCompilerMessageReceived(messages);
 }
コード例 #53
0
ファイル: PathAnnotation.cs プロジェクト: am1752/StudyCSharpp
        /// <summary>
        /// Renders the annotation on the specified context.
        /// </summary>
        /// <param name="rc">The render context.</param>
        public override void Render(IRenderContext rc)
        {
            base.Render(rc);

            this.CalculateActualMinimumsMaximums();

            this.screenPoints = this.GetScreenPoints();

            var clippingRectangle = this.GetClippingRect();

            const double MinimumSegmentLength = 4;

            var clippedPoints = new List <ScreenPoint>();
            var dashArray     = this.LineStyle.GetDashArray();

            if (this.StrokeThickness > 0 && this.LineStyle != LineStyle.None)
            {
                rc.DrawClippedLine(
                    clippingRectangle,
                    this.screenPoints,
                    MinimumSegmentLength * MinimumSegmentLength,
                    this.GetSelectableColor(this.Color),
                    this.StrokeThickness,
                    this.EdgeRenderingMode,
                    dashArray,
                    this.LineJoin,
                    null,
                    clippedPoints.AddRange);
            }

            var margin = this.TextMargin;

            this.GetActualTextAlignment(out var ha, out var va);

            if (ha == HorizontalAlignment.Center)
            {
                margin = 0;
            }
            else
            {
                margin *= this.TextLinePosition < 0.5 ? 1 : -1;
            }

            if (GetPointAtRelativeDistance(clippedPoints, this.TextLinePosition, margin, out var position, out var angle))
            {
                if (angle < -90)
                {
                    angle += 180;
                }

                if (angle > 90)
                {
                    angle -= 180;
                }

                switch (this.TextOrientation)
                {
                case AnnotationTextOrientation.Horizontal:
                    angle = 0;
                    break;

                case AnnotationTextOrientation.Vertical:
                    angle = -90;
                    break;
                }

                // Apply 'padding' to the position
                var angleInRadians = angle / 180 * Math.PI;
                var f = 1;

                if (ha == HorizontalAlignment.Right)
                {
                    f = -1;
                }

                if (ha == HorizontalAlignment.Center)
                {
                    f = 0;
                }

                position += new ScreenVector(f * this.TextPadding * Math.Cos(angleInRadians), f * this.TextPadding * Math.Sin(angleInRadians));

                if (!string.IsNullOrEmpty(this.Text))
                {
                    var textPosition = this.GetActualTextPosition(() => position);

                    if (this.TextPosition.IsDefined())
                    {
                        angle = this.TextRotation;
                    }

                    if (this.ClipText)
                    {
                        var cs = new CohenSutherlandClipping(clippingRectangle);
                        if (cs.IsInside(position))
                        {
                            rc.DrawClippedText(
                                clippingRectangle,
                                textPosition,
                                this.Text,
                                this.ActualTextColor,
                                this.ActualFont,
                                this.ActualFontSize,
                                this.ActualFontWeight,
                                angle,
                                this.TextHorizontalAlignment,
                                this.TextVerticalAlignment);
                        }
                    }
                    else
                    {
                        rc.DrawText(
                            textPosition,
                            this.Text,
                            this.ActualTextColor,
                            this.ActualFont,
                            this.ActualFontSize,
                            this.ActualFontWeight,
                            angle,
                            ha,
                            va);
                    }
                }
            }
        }
コード例 #54
0
ファイル: BlogService.cs プロジェクト: henrique16/repository
 public bool UpdateListObject(IList <object> pListObject)
 {
     throw new NotImplementedException();
 }
コード例 #55
0
 public abstract void SetViewParameters(ViewFactoryContext viewFactoryContext, IList <ExprNode> viewParameters);
コード例 #56
0
ファイル: BlogService.cs プロジェクト: henrique16/repository
 public bool InsertListObject(IList <object> pListObj)
 {
     throw new NotImplementedException();
 }
コード例 #57
0
 private static void HandleBindingCollection(IDeviceReport report, IList <bool> prevStates, IList <bool> newStates, IDictionary <int, IBinding> bindings)
 {
     for (int i = 0; i < newStates.Count; i++)
     {
         if (bindings.TryGetValue(i, out IBinding binding) && binding != null)
         {
             InvokeBinding(report, binding, prevStates[i], newStates[i]);
         }
         prevStates[i] = newStates[i];
     }
 }
コード例 #58
0
        public static void VenueBreadcrumb(this IList<BreadcrumbViewModel> breadcrumbViewModels, VenueV venueV, DateTime viewDate)
        {
            breadcrumbViewModels.CountryBreadcrumb(venueV.Country.GetApprovedVersion<CountryV>(viewDate), viewDate);

            breadcrumbViewModels.Add(AreaType.Ven, venueV.PrimaryKey, venueV.VenueName, string.Empty);
        }
コード例 #59
0
 protected internal Asn1Set(
     int capacity)
 {
     _set = Platform.CreateArrayList(capacity);
 }
        /// <summary>
        /// Get bpf_adoxio_application_adoxio_applicationcrsbpfv4 from
        /// adoxio_applications
        /// </summary>
        /// <param name='adoxioApplicationid'>
        /// key: adoxio_applicationid of adoxio_application
        /// </param>
        /// <param name='top'>
        /// </param>
        /// <param name='skip'>
        /// </param>
        /// <param name='search'>
        /// </param>
        /// <param name='filter'>
        /// </param>
        /// <param name='count'>
        /// </param>
        /// <param name='orderby'>
        /// Order items by property values
        /// </param>
        /// <param name='select'>
        /// Select properties to be returned
        /// </param>
        /// <param name='expand'>
        /// Expand related entities
        /// </param>
        /// <param name='customHeaders'>
        /// Headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="HttpOperationException">
        /// 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<HttpOperationResponse<MicrosoftDynamicsCRMadoxioApplicationcrsbpfv4Collection>> GetWithHttpMessagesAsync(string adoxioApplicationid, int? top = default(int?), int? skip = default(int?), string search = default(string), string filter = default(string), bool? count = default(bool?), IList<string> orderby = default(IList<string>), IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (adoxioApplicationid == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "adoxioApplicationid");
            }
            // Tracing
            bool _shouldTrace = ServiceClientTracing.IsEnabled;
            string _invocationId = null;
            if (_shouldTrace)
            {
                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
                tracingParameters.Add("adoxioApplicationid", adoxioApplicationid);
                tracingParameters.Add("top", top);
                tracingParameters.Add("skip", skip);
                tracingParameters.Add("search", search);
                tracingParameters.Add("filter", filter);
                tracingParameters.Add("count", count);
                tracingParameters.Add("orderby", orderby);
                tracingParameters.Add("select", select);
                tracingParameters.Add("expand", expand);
                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("/") ? "" : "/")), "adoxio_applications({adoxio_applicationid})/bpf_adoxio_application_adoxio_applicationcrsbpfv4").ToString();
            _url = _url.Replace("{adoxio_applicationid}", System.Uri.EscapeDataString(adoxioApplicationid));
            List<string> _queryParameters = new List<string>();
            if (top != null)
            {
                _queryParameters.Add(string.Format("$top={0}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(top, Client.SerializationSettings).Trim('"'))));
            }
            if (skip != null)
            {
                _queryParameters.Add(string.Format("$skip={0}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(skip, Client.SerializationSettings).Trim('"'))));
            }
            if (search != null)
            {
                _queryParameters.Add(string.Format("$search={0}", System.Uri.EscapeDataString(search)));
            }
            if (filter != null)
            {
                _queryParameters.Add(string.Format("$filter={0}", System.Uri.EscapeDataString(filter)));
            }
            if (count != null)
            {
                _queryParameters.Add(string.Format("$count={0}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(count, Client.SerializationSettings).Trim('"'))));
            }
            if (orderby != null)
            {
                _queryParameters.Add(string.Format("$orderby={0}", System.Uri.EscapeDataString(string.Join(",", orderby))));
            }
            if (select != null)
            {
                _queryParameters.Add(string.Format("$select={0}", System.Uri.EscapeDataString(string.Join(",", select))));
            }
            if (expand != null)
            {
                _queryParameters.Add(string.Format("$expand={0}", System.Uri.EscapeDataString(string.Join(",", expand))));
            }
            if (_queryParameters.Count > 0)
            {
                _url += "?" + 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 (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 HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                if (_httpResponse.Content != null) {
                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
                }
                else {
                    _responseContent = string.Empty;
                }
                ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
                ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
                if (_shouldTrace)
                {
                    ServiceClientTracing.Error(_invocationId, ex);
                }
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw ex;
            }
            // Create Result
            var _result = new HttpOperationResponse<MicrosoftDynamicsCRMadoxioApplicationcrsbpfv4Collection>();
            _result.Request = _httpRequest;
            _result.Response = _httpResponse;
            // Deserialize Response
            if ((int)_statusCode == 200)
            {
                _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
                try
                {
                    _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<MicrosoftDynamicsCRMadoxioApplicationcrsbpfv4Collection>(_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;
        }