コード例 #1
0
        private void ProcessTodayPayments()
        {
            var todayPayments = _paymentSvc.GetTodayPayments(_expenseController.CurrentSessionData).ToList();
            var nextPayments = _paymentSvc.GetComingPayments(_expenseController.CurrentSessionData).ToList();
            var latePayments = _paymentSvc.GetLatePayments(_expenseController.CurrentSessionData).ToList();

            var form = new FormPendingExpensesViewModel(todayPayments, nextPayments, latePayments);
            form.ShowDialog();

            //when the form is closed, read the modified data and notify the worksheet.
            var processedPayments = new List<BaseTransaction>();
            processedPayments.AddRange(EditPendingExpenseDto.ToList(form.TodayPayments, w => w.IsOk == true));
            processedPayments.AddRange(EditPendingExpenseDto.ToList(form.LatePayments, w => w.IsOk == true));
            processedPayments.AddRange(EditPendingExpenseDto.ToList(form.NextPayments, w => w.IsOk == true));

            var processedExpenses = processedPayments.OfType<Expense>();
            var processedIncomes = processedPayments.OfType<Income>();
            _expenseController.AcceptDataCollection(processedExpenses, true);
            _incomeController.AcceptDataCollection(processedIncomes, true);

            CommandHandler.Run<ConfigureSidePanelCommand>(new SidePanelCommandArgs
                                                              {
                                                                  WpfControl = new MainSidePanel(),
                                                                  Transactions = CurrentSession.ValidTransactions,
                                                                  Accounts = CurrentSession.Accounts
                                                              });
        }
コード例 #2
0
        static void Main()
        {
            List<Person> SULSdata = new List<Person>()
            {
                new SeniorTrainer("Spiro", "Spirov", 33),
                new JuniorTrainer("Kiro", "Kirov", 22),
                new GraduateStudent("Pesho", "Peshov", 77, 000001, 3.33),
                new GraduateStudent("Gosho", "Goshev", 77, 000002, 4.23),
                new DropoutStudent("Baba", "Yaga", 88, 000003, 6.00, "To fly more."),
                new DropoutStudent("Ivan", "Petrov", 18, 000006, 2.00, "No reason."),
                new OnsiteStudent("Yan", "Hon", 31, 000013, 3.50, "OOP", 2),
                new OnsiteStudent("Tzun", "Gvan", 19, 000019, 4.41, "OOP", 0),
                new OnlineStudent("Maria", "Georgieva", 21, 000119, 2.90, "OOP"),
                new OnlineStudent("Smilen", "Svilenov", 45, 000231, 3.80, "OOP"),
            };

            SULSdata.OfType<CurrentStudent>()
                .OrderBy(s => s.AverageGrade)
                .ToList()
                .ForEach(Console.WriteLine);

            Console.WriteLine();

            SULSdata.OfType<DropoutStudent>()
                .ToList()
                .ForEach(s => s.ReApply());
        }
コード例 #3
0
ファイル: Verify.cs プロジェクト: kevin-montrose/More
        public static List<Block> Task(List<Block> blocks)
        {
            var media = blocks.OfType<MediaBlock>().Select(t => t.MediaQuery);
            var import = blocks.OfType<Model.Import>().Select(t => t.MediaQuery);
            var @using = blocks.OfType<Model.Using>().Select(t => t.MediaQuery);

            var toVerify = media.Union(import).Union(@using).ToList();

            toVerify.Each(v => VerifyQuery(v));

            var allProps =
                blocks.OfType<SelectorAndBlock>().SelectMany(s => s.Properties)
                .Union(
                    blocks.OfType<MediaBlock>().Select(m => m.Blocks).OfType<SelectorAndBlock>().SelectMany(s => s.Properties)
                );

            var values = allProps.OfType<NameValueProperty>().Select(s => s.Value).ToList();

            VerifyCycle(values);
            VerifySteps(values);
            VerifyCubicBezier(values);
            VerifyLinearGradient(values);

            return blocks;
        }
コード例 #4
0
        public void ExploreAssembly(IProject project, IMetadataAssembly assembly, UnitTestElementConsumer consumer, ManualResetEvent exitEvent)
        {
            var envoy = ProjectModelElementEnvoy.Create(project);
            if (assembly.ReferencedAssembliesNames.Any(n => n.Name == SilverlightMsTestAssemblyName))
            {
                var allElements = new List<IUnitTestElement>();
                var mappedElements = new Dictionary<IUnitTestElement, IUnitTestElement>();

                new mstestlegacy::JetBrains.ReSharper.UnitTestProvider.MSTest.MsTestMetadataExplorer(msTestElementFactory, msTestAttributesProvider, project, shellLocks, allElements.Add)
                    .ExploreAssembly(assembly);

                foreach (var classElement in allElements.OfType<mstest10::JetBrains.ReSharper.UnitTestProvider.MSTest10.MsTestTestClassElement>())
                    mappedElements.Add(classElement, elementFactory.GetOrCreateClassElement(classElement.TypeName, project, envoy));

                foreach (var methodElement in allElements.OfType<mstest10::JetBrains.ReSharper.UnitTestProvider.MSTest10.MsTestTestMethodElement>())
                    mappedElements.Add(methodElement, elementFactory.GetOrCreateMethodElement(methodElement.Id, project, (mstestlegacy::JetBrains.ReSharper.UnitTestProvider.MSTest.MsTestTestClassElementBase)mappedElements[methodElement.Parent], envoy, methodElement.TypeName));

                foreach (var rowElement in allElements.OfType<mstest10::JetBrains.ReSharper.UnitTestProvider.MSTest10.MsTestTestRowElement>())
                    mappedElements.Add(rowElement, elementFactory.GetOrCreateRowElement(rowElement.Id, project, (mstestlegacy::JetBrains.ReSharper.UnitTestProvider.MSTest.MsTestTestMethodElementBase)mappedElements[rowElement.Parent], envoy));

                foreach (var element in allElements)
                {
                    IUnitTestElement mappedElement;
                    if (mappedElements.TryGetValue(element, out mappedElement))
                        consumer(mappedElements[element]);
                    else
                        consumer(element);
                }

            }
        }
コード例 #5
0
        //public static List<FileAction> PerformRollup(List<USNChangeRange> range)
        //{
        //    var deletedFiles = range.Where(e=>  e.Entry)
        //}
        public static List<FileAction> PerformRollup(List<FileAction> toReturn)
        {
            var deletedFiles = toReturn.OfType<DeleteAction>().ToList();

            foreach (var deletedFile in deletedFiles)
            {
                if (toReturn.OfType<UpdateAction>().Select(f => f.RelativePath).Contains(deletedFile.RelativePath))
                {
                    toReturn.Remove(deletedFile);
                }

                toReturn.RemoveAll(f => f.RelativePath == deletedFile.RelativePath && f.USN < deletedFile.USN);
            }

            var fileActions = toReturn.Select(e => e.RelativePath).Distinct().Select(f => toReturn.FirstOrDefault(a => a.RelativePath == f)).ToList();

            foreach (var source in fileActions.OfType<RenameAction>().ToList())
            {
                if (fileActions.Any(f => f.RawPath == source.RenameFrom))
                {
                    fileActions.RemoveAll(f => f.RawPath == source.RenameFrom);
                    fileActions.Remove(source);
                    fileActions.Add(new RenameAction()
                    {
                        RelativePath = source.RelativePath,
                        RawPath = source.RawPath,
                        USN = source.USN,
                        IsDirectory = source.IsDirectory,
                        Mountpoint = source.Mountpoint
                    });
                }
            }

            return fileActions;
        }
コード例 #6
0
ファイル: OpenIdChannel.cs プロジェクト: rafek/dotnetopenid
		/// <summary>
		/// Initializes a new instance of the <see cref="OpenIdChannel"/> class.
		/// </summary>
		/// <param name="messageTypeProvider">A class prepared to analyze incoming messages and indicate what concrete
		/// message types can deserialize from it.</param>
		/// <param name="bindingElements">The binding elements to use in sending and receiving messages.</param>
		protected OpenIdChannel(IMessageFactory messageTypeProvider, IChannelBindingElement[] bindingElements)
			: base(messageTypeProvider, bindingElements) {
			Requires.NotNull(messageTypeProvider, "messageTypeProvider");

			// Customize the binding element order, since we play some tricks for higher
			// security and backward compatibility with older OpenID versions.
			var outgoingBindingElements = new List<IChannelBindingElement>(bindingElements);
			var incomingBindingElements = new List<IChannelBindingElement>(bindingElements);
			incomingBindingElements.Reverse();

			// Customize the order of the incoming elements by moving the return_to elements in front.
			var backwardCompatibility = incomingBindingElements.OfType<BackwardCompatibilityBindingElement>().SingleOrDefault();
			var returnToSign = incomingBindingElements.OfType<ReturnToSignatureBindingElement>().SingleOrDefault();
			if (backwardCompatibility != null) {
				incomingBindingElements.MoveTo(0, backwardCompatibility);
			}
			if (returnToSign != null) {
				// Yes, this is intentionally, shifting the backward compatibility
				// binding element to second position.
				incomingBindingElements.MoveTo(0, returnToSign);
			}

			this.CustomizeBindingElementOrder(outgoingBindingElements, incomingBindingElements);

			// Change out the standard web request handler to reflect the standard
			// OpenID pattern that outgoing web requests are to unknown and untrusted
			// servers on the Internet.
			this.WebRequestHandler = new UntrustedWebRequestHandler();
		}
コード例 #7
0
        public SpatialRecord Map(ISOSpatialRow isoSpatialRow, List<WorkingData> meters)
        {
            var spatialRecord = new SpatialRecord();

            foreach (var meter in meters.OfType<NumericWorkingData>())
            {
                SetNumericMeterValue(isoSpatialRow, meter, spatialRecord);
            }

            foreach (var meter in meters.OfType<EnumeratedWorkingData>())
            {
                SetEnumeratedMeterValue(isoSpatialRow, meter, spatialRecord);
            }

            spatialRecord.Geometry = new ApplicationDataModel.Shapes.Point
            {
                X = Convert.ToDouble(isoSpatialRow.EastPosition * CoordinateMultiplier),
                Y = Convert.ToDouble(isoSpatialRow.NorthPosition * CoordinateMultiplier),
                Z = isoSpatialRow.Elevation
            };

            spatialRecord.Timestamp = isoSpatialRow.TimeStart;

            return spatialRecord;
        }
コード例 #8
0
        private static dynamic ReadJsonArray(JsonReader reader)
        {
            List<dynamic> vals = new List<dynamic>();

            while (reader.Read())
            {
                if (reader.TokenType == JsonToken.EndArray)
                {
                    break;
                }
                else
                {
                    vals.Add(ReadJsonValue(reader, true));
                }
            }

            if (vals.Count != 0 && vals.All(v => v is IDictionary<string, object>))
            {
                if (vals.OfType<IDictionary<string, object>>().All(v => v.ContainsKey("Key") && v.ContainsKey("Value")))
                {
                    ExpandoObject obj = new ExpandoObject();

                    foreach (IDictionary<string, object> dict in vals.OfType<IDictionary<string, object>>())
                    {
                        ((IDictionary<string, object>)obj).Add(dict["Key"].ToString(), dict["Value"]);
                    }

                    return obj;
                }
            }

            return vals;
        }
コード例 #9
0
ファイル: Ship.cs プロジェクト: elodea/Wormhole-2.0
        //////////////////////
        // MOVEMENT API
        //////////////////////
        /// <summary>
        /// Ask ship engines to thrust ship along a passed in vector direction
        /// magnitude of vector direction determines thrust scaling
        /// </summary>
        public void Thrust(Vector vDir)
        {
            vDir = vDir.Rotate(Dir.Angle * (Math.PI / 180));

            foreach (Engine e in componentList?.OfType <Engine>())
            {
                Vel = e.ApplyForce(vDir, Vel, Mass);
                componentList.SetVel(Vel);
            }
        }
コード例 #10
0
ファイル: VmfProvider.cs プロジェクト: KonstantinUb/sledge
        public static GenericStructure CreateCopyStream(List<MapObject> objects)
        {
            var stream = new GenericStructure("clipboard");

            var entitySolids = objects.OfType<Entity>().SelectMany(x => x.Find(y => y is Solid)).ToList();
            stream.Children.AddRange(objects.OfType<Solid>().Where(x => !x.IsCodeHidden && !x.IsVisgroupHidden && !entitySolids.Contains(x)).Select(WriteSolid));
            stream.Children.AddRange(objects.OfType<Group>().Select(WriteGroup));
            stream.Children.AddRange(objects.OfType<Entity>().Select(WriteEntity));

            return stream;
        }
コード例 #11
0
ファイル: Verify.cs プロジェクト: repos-css/More
        public static List<Block> Task(List<Block> blocks)
        {
            var media = blocks.OfType<MediaBlock>().Select(t => t.MediaQuery);
            var import = blocks.OfType<Model.Import>().Select(t => t.MediaQuery);
            var @using = blocks.OfType<Model.Using>().Select(t => t.MediaQuery);

            var toVerify = media.Union(import).Union(@using).ToList();

            toVerify.Each(v => VerifyQuery(v));

            return blocks;
        }
コード例 #12
0
ファイル: ResetIncludes.cs プロジェクト: kevin-montrose/More
        public static List<Block> Task(List<Block> blocks)
        {
            var resets = blocks.OfType<SelectorAndBlock>().Where(w => w.IsReset).ToList();

            var ret = new List<Block>();
            ret.AddRange(blocks.Where(w => !(w is SelectorAndBlock || w is MediaBlock)));
            ret.AddRange(blocks.OfType<SelectorAndBlock>().Where(w => w.IsReset));

            var remaining = blocks.Where(w => !ret.Contains(w)).ToList();

            foreach (var block in remaining)
            {
                var selBlock = block as SelectorAndBlock;
                if (selBlock != null)
                {
                    var props = new List<Property>();

                    var resetProps = selBlock.Properties.OfType<ResetProperty>();
                    var selfResetProps = selBlock.Properties.OfType<ResetSelfProperty>();

                    props.AddRange(selBlock.Properties.Where(w => !(resetProps.Contains(w) || selfResetProps.Contains(w))));

                    var copySels = resetProps.Select(x => x.Selector).Union(selfResetProps.Select(x => x.EffectiveSelector)).ToList();

                    foreach (var sel in copySels)
                    {
                        var newProps = FindMatches(sel, resets);

                        foreach (var p in newProps)
                        {
                            // reset properties never override
                            if (props.Any(a => a is NameValueProperty && ((NameValueProperty)a).Name.Equals(p.Name, StringComparison.InvariantCultureIgnoreCase))) continue;

                            props.Add(p);
                        }
                    }

                    ret.Add(new SelectorAndBlock(selBlock.Selector, props, null, selBlock.Start, selBlock.Stop, selBlock.FilePath));
                }

                var media = block as MediaBlock;
                if (media != null)
                {
                    var subBlocks = Task(media.Blocks.ToList());

                    ret.Add(new MediaBlock(media.MediaQuery, subBlocks, media.Start, media.Start, media.FilePath));
                }
            }

            return ret;
        }
コード例 #13
0
        private string GetFirstAvailableProcessName()
        {
            _lastProcess += 1;

            string result = $"{GetIdentityTypeName(typeof(Process))} {_lastProcess}";

            var process = _entities?.OfType <IProcess>().FirstOrDefault(x => string.CompareOrdinal(result, x.Name) == 0);

            if (process != null)
            {
                result = GetFirstAvailableProcessName();
            }

            return(result);
        }
コード例 #14
0
        private void RegisterHandles()
        {
            UIResizeOperationHandleConnector = new UIResizeOperationHandleConnector(CanvasItem, FrameOfReference,
                SnappingEngine);


            var thumbContainer = (UIElement) FindName("PART_ThumbContainer");

            Debug.Assert(thumbContainer != null, "ThumbContainer part not found!");

            var visualChildren = new List<DependencyObject>();
            for (var i = 0; i < VisualTreeHelper.GetChildrenCount(thumbContainer); i++)
            {
                visualChildren.Add(VisualTreeHelper.GetChild(thumbContainer, i));
            }

            var logicalChildren = visualChildren.OfType<FrameworkElement>();
            foreach (var logicalChild in logicalChildren)
            {


                var childRect = this.GetRectRelativeToParent(logicalChild);

                var parentRect = CanvasItem.Rect();

                var handlePoint = childRect.GetHandlePoint(parentRect.Size);

                UIResizeOperationHandleConnector.RegisterHandle(new UIElementAdapter(logicalChild), handlePoint);                
            }
        }
コード例 #15
0
ファイル: MapMenu.cs プロジェクト: Riock/Legends-Viewer
 public void AddOptions(List<Object> addOptions)
 {
     Options.Clear();
     addOptions = addOptions.GroupBy(optionObject => optionObject).Select(test => test.Key).ToList(); //remove duplicates
     foreach (Entity civ in addOptions.OfType<Entity>())
         Options.Add(new MapMenuOption(this, civ));
     foreach (Site site in addOptions.OfType<Site>())
         Options.Add(new MapMenuOption(this, site));
     foreach (Battle battle in addOptions.OfType<Battle>())
         Options.Add(new MapMenuOption(this, battle));
     foreach (List<Battle> battles in addOptions.OfType<List<Battle>>())
         Options.Add(new MapMenuOption(this, battles));
     foreach (string text in addOptions.OfType<string>())
         Options.Add(new MapMenuOption(this, text));
     CalculateSize();
 }
コード例 #16
0
ファイル: APIIndex.cs プロジェクト: Tigrouzen/UnrealEngine-4
        public APIIndex(List<DoxygenModule> InModules)
            : base(null, "API")
        {
            // Build a mapping of module names to modules
            Dictionary<string, DoxygenModule> NameToModuleMap = new Dictionary<string,DoxygenModule>();
            foreach(DoxygenModule Module in InModules)
            {
                NameToModuleMap.Add(Module.Name, Module);
            }

            // Create a module category tree
            APIModuleCategory RootCategory = new APIModuleCategory(null);
            RootCategory.AddModules(InModules.Select(x => new KeyValuePair<string, string>(x.Name, x.BaseSrcDir)).ToArray());
            Debug.Assert(RootCategory.MinorModules.Count == 0 && RootCategory.MajorModules.Count == 0);

            // Create all the index pages
            foreach (APIModuleCategory Category in RootCategory.Categories)
            {
                if (!Category.IsEmpty)
                {
                    APIModuleIndex ModuleIndex = new APIModuleIndex(this, Category, InModules);
                    ModuleIndexes.Add(ModuleIndex);
                }
            }
            Pages.AddRange(ModuleIndexes);

            // Get all the members that were created as part of building the modules. After this point we'll only create index pages.
            List<APIMember> AllMembers = new List<APIMember>(GatherPages().OfType<APIMember>().OrderBy(x => x.FullName));
            foreach (APIMember Member in AllMembers)
            {
                Member.Link();
            }
            foreach (APIMember Member in AllMembers)
            {
                Member.PostLink();
            }

            // Create an index of all the constants
            ConstantIndex = new APIConstantIndex(this, AllMembers);
            Pages.Add(ConstantIndex);

            // Create an index of all the functions
            FunctionIndex = new APIFunctionIndex(this, AllMembers.OfType<APIFunction>().Where(x => !(x.ScopeParent is APIRecord)));
            Pages.Add(FunctionIndex);

            // Create an index of all the types
            TypeIndex = new APITypeIndex(this, AllMembers);
            Pages.Add(TypeIndex);

            // Create an index of all the classes
            RecordHierarchy = APIHierarchy.Build(this, AllMembers.OfType<APIRecord>());
            Pages.Add(RecordHierarchy);

            // Create all the quick links
            foreach (string QuickLinkPath in QuickLinkPaths)
            {
                APIMember Member = AllMembers.FirstOrDefault(x => x.LinkPath == QuickLinkPath);
                if (Member != null) QuickLinks.Add(Member);
            }
        }
コード例 #17
0
ファイル: AphidMacro.cs プロジェクト: robocoder/aphid
 public static AphidMacro[] Parse(List<AphidExpression> ast)
 {
     return ast
         .OfType<BinaryOperatorExpression>()
         .Select(x => new
         {
             Id = x.LeftOperand as IdentifierExpression,
             Call = x.RightOperand as CallExpression,
             Original = x,
         })
         .Where(x => x.Id != null && x.Call != null && x.Call.Args.Count() == 1)
         .Select(x => new
         {
             Name = x.Id.Identifier,
             CallName = x.Call.FunctionExpression as IdentifierExpression,
             Func = x.Call.Args.Single() as FunctionExpression,
             x.Original,
         })
         .Where(x =>
             x.CallName != null &&
             x.CallName.Identifier == "macro" &&
             x.Func != null)
         .Select(x => new AphidMacro(x.Name, x.Func, x.Original))
         .ToArray();
 }
コード例 #18
0
ファイル: UsageGraph.cs プロジェクト: nieve/fubucore
        public UsageGraph(string appName, Type commandType)
        {
            _appName = appName;
            _commandType = commandType;
            _inputType = commandType.FindInterfaceThatCloses(typeof (IFubuCommand<>)).GetGenericArguments().First();

            _commandName = CommandFactory.CommandNameFor(commandType);
            _commandType.ForAttribute<CommandDescriptionAttribute>(att => { _description = att.Description; });

            if (_description == null) _description = _commandType.Name;

            _handlers = InputParser.GetHandlers(_inputType);

            _commandType.ForAttribute<UsageAttribute>(att =>
            {
                _usages.Add(buildUsage(att));
            });

            if (!_usages.Any())
            {
                var usage = new CommandUsage()
                {
                    AppName = _appName,
                    CommandName = _commandName,
                    UsageKey = "default",
                    Description = _description,
                    Arguments = _handlers.OfType<Argument>(),
                    ValidFlags = _handlers.Where(x => !(x is Argument))
                };

                _usages.Add(usage);
            }
        }
コード例 #19
0
ファイル: Machine.cs プロジェクト: CadeLaRen/BizHawk
		public Machine(byte[] appleIIe, byte[] diskIIRom)
		{
			Events = new MachineEvents();

			Cpu = new Cpu(this);
			Memory = new Memory(this, appleIIe);
			Keyboard = new Keyboard(this);
			GamePort = new GamePort(this);
			Cassette = new Cassette(this);
			Speaker = new Speaker(this);
			Video = new Video(this);
			NoSlotClock = new NoSlotClock(this);

			var emptySlot = new PeripheralCard(this);
			Slot1 = emptySlot;
			Slot2 = emptySlot;
			Slot3 = emptySlot;
			Slot4 = emptySlot;
			Slot5 = emptySlot;
			Slot6 = new DiskIIController(this, diskIIRom);
			Slot7 = emptySlot;

			Slots = new List<PeripheralCard> { null, Slot1, Slot2, Slot3, Slot4, Slot5, Slot6, Slot7 };
			Components = new List<MachineComponent> { Cpu, Memory, Keyboard, GamePort, Cassette, Speaker, Video, NoSlotClock, Slot1, Slot2, Slot3, Slot4, Slot5, Slot6, Slot7 };

			BootDiskII = Slots.OfType<DiskIIController>().Last();
		}
コード例 #20
0
ファイル: Charsets.cs プロジェクト: repos-css/More
        public static List<Block> Task(List<Block> blocks)
        {
            var charsets = blocks.OfType<CssCharset>();

            if (charsets.Count() == 0) return blocks;

            var ret = new List<Block>(blocks.Count);
            ret.AddRange(blocks.Where(w => !(w is CssCharset)));

            var charsetStrings = charsets.Select(s => s.Charset.Value).Distinct();

            if (charsetStrings.Count() != 1)
            {
                foreach (var c in charsets)
                {
                    var others = string.Join(", ", charsetStrings.Where(s => s != c.Charset.Value));

                    Current.RecordError(ErrorType.Compiler, c, "@charset conflicts with " + others + ", defined elsewhere.");
                }

                return null;
            }

            ret.Insert(0, new CssCharset(new QuotedStringValue(charsetStrings.Single()), -1, -1));

            return ret;
        }
コード例 #21
0
        public override void Synchronize(ref List <Declaration> updated)
        {
            if (Declaration is null ||
                !(updated?.OfType <ProjectDeclaration>()
                  .FirstOrDefault(declaration => declaration.ProjectId.Equals(Declaration.ProjectId)) is ProjectDeclaration match))
            {
                Declaration = null;
                return;
            }

            Declaration = match;

            var children = ExtractTrackedDeclarationsForProject(Declaration, ref updated);

            updated = updated.Except(children.Union(new[] { Declaration })).ToList();

            // Reference synchronization is deferred to AddNewChildren for 2 reasons. First, it doesn't make sense to sling around a List of
            // declaration for something that doesn't need it. Second (and more importantly), the priority can't be set without calling
            // GetProjectReferenceModels, which hits the VBE COM interfaces. So, we only want to do that once. The bonus 3rd reason is that it
            // can be called from the ctor this way.

            SynchronizeChildren(ref children);

            // Have to do this again - the project might have been saved or otherwise had the ProjectDisplayName changed.
            SetName();
        }
コード例 #22
0
ファイル: Program.cs プロジェクト: nyctef/irclogsparser
 private static void ListKicks(List<LogMessage> messages)
 {
     foreach (var kick in messages.OfType<KickedMessage>())
     {
         Console.WriteLine(kick);
     }
 }
コード例 #23
0
        protected override ModelMetadata CreateMetadata(IEnumerable<Attribute> attributes, Type containerType, Func<object> modelAccessor, Type modelType, string propertyName)
        {
            //不希望覆寫太多東西,所以大部分還是用base的CreateMetadata方法
            ModelMetadata metadata = base.CreateMetadata(attributes,
                                                          containerType,
                                                          modelAccessor,
                                                          modelType,
                                                          propertyName);

            List<Attribute> attributeList = new List<Attribute>(attributes);

            IEnumerable<UIHintAttribute> uiHintAttributes = attributeList.OfType<UIHintAttribute>();
            UIHintAttribute uiHintAttribute = uiHintAttributes.FirstOrDefault(a => String.Equals(a.PresentationLayer, "MVC", StringComparison.OrdinalIgnoreCase))
                                            ?? uiHintAttributes.FirstOrDefault(a => String.IsNullOrEmpty(a.PresentationLayer));

            //如果有UIHint屬性,就將他的參數塞到ModelMetadata.AdditionalValues裡面
            //Key是UIHintTemplateControlParameters
            if (uiHintAttribute != null)
            {
                if (metadata.AdditionalValues.ContainsKey("UIHintTemplateControlParameters"))
                    throw new ArgumentException("Metadate.AdditionalValues已存在 \"UIHintTemplateControlParameters\"這個Key,請更換擴充UIHintAttribute的Key值。");

                metadata.AdditionalValues.Add("UIHintTemplateControlParameters", uiHintAttribute.ControlParameters);
            }
            return metadata;
        }
コード例 #24
0
        public CollectionQuerySimplification(List<object> coll)
        {
            var x = coll.Select(element => element as object).Any(element => element != null);  // Noncompliant use OfType
            x = coll.Select((element) => ((element as object))).Any(element => (element != null) && CheckCondition(element) && true);  // Noncompliant use OfType
            var y = coll.Where(element => element is object).Select(element => element as object); // Noncompliant use OfType
            var y = coll.Where(element => element is object).Select(element => element as object[]);
            y = coll.Where(element => element is object).Select(element => (object)element); // Noncompliant use OfType
            x = coll.Where(element => element == null).Any();  // Noncompliant use Any([expression])
            var z = coll.Where(element => element == null).Count();  // Noncompliant use Count([expression])
            z = Enumerable.Count(coll.Where(element => element == null));  // Noncompliant
            z = Enumerable.Count(Enumerable.Where(coll, element => element == null));  // Noncompliant
            y = coll.Select(element => element as object);
            y = coll.ToList().Select(element => element as object); // Noncompliant
            y = coll
                .ToList()  // Noncompliant
                .ToArray() // Noncompliant
                .Select(element => element as object);

            var z = coll
                .Select(element => element as object)
                .ToList();

            var c = coll.Count(); //Noncompliant
            c = coll.OfType<object>().Count();

            x = Enumerable.Select(coll, element => element as object).Any(element => element != null); //Noncompliant
            x = Enumerable.Any(Enumerable.Select(coll, element => element as object), element => element != null); //Noncompliant
        }
コード例 #25
0
        public override void BeginInit()
        {
            SetValue(FocusManager.IsFocusScopeProperty, true);
            _modifierKeys = new List<ModifierKeyBase>();
            _allLogicalKeys = new List<ILogicalKey>();
            _allOnScreenKeys = new List<OnScreenKey>();

            _sections = new ObservableCollection<OnScreenKeyboardSection>();

            var mainSection = new OnScreenKeyboardSection();
            var mainKeys = GetMainKeys();

            mainSection.Keys = mainKeys;
            mainSection.SetValue(ColumnProperty, 0);
            _sections.Add(mainSection);
            ColumnDefinitions.Add(new ColumnDefinition {Width = new GridLength(3, GridUnitType.Star)});
            Children.Add(mainSection);

            _allLogicalKeys.AddRange(mainKeys.Select(x => x.Key));
            _allOnScreenKeys.AddRange(mainSection.Keys);

            _modifierKeys.AddRange(_allLogicalKeys.OfType<ModifierKeyBase>());
            _allOnScreenKeys.ForEach(x => x.OnScreenKeyPress += OnScreenKeyPress);

            SynchroniseModifierKeyState();

            base.BeginInit();
        }
コード例 #26
0
ファイル: Zone.cs プロジェクト: McLeanBH/XbimExchange
        protected internal override List<CobieObject> MergeDuplicates(List<CobieObject> objects, TextWriter log)
        {
            var candidates = objects.OfType<Zone>().ToList();
            if (!candidates.Any()) return new List<CobieObject>();

            var categoryStrings = (Categories ?? new List<Category>()).Select(c => c.CategoryString);
            var duplicates =
                candidates.Where(
                    s => s.Name == Name)
                    .ToList();
            duplicates.Remove(this);
            if (!duplicates.Any()) return new List<CobieObject>();

            //get all components into this one
            foreach (var duplicate in duplicates)
            {
                if (duplicate.Spaces == null) continue;
                Spaces.AddRange(duplicate.Spaces);

                //check if the category is the same. It doesn't have to be according to COBie specification as it is a compound
                //key but it would make any attached attributes ambiguous
                var categoryDif = duplicate.Categories.Where(c => !categoryStrings.Contains(c.CategoryString)).ToList();
                if (categoryDif.Any())
                    log.WriteLine(
                        "There are multiple systems with the same name but different category. This is a legal in COBie sheet but will make any attributes related to this object ambiguous. Object: {0}, different category: {1}",
                        duplicate.Name, String.Join("; ", categoryDif.Select(c => c.CategoryString)));
            }

            return duplicates.Cast<CobieObject>().ToList();
        }
コード例 #27
0
        /// <summary>
        /// Initializes a new instance of the <see cref="AnalysisResultCell"/> class.
        /// </summary>
        /// <param name="values">Values</param>
        /// <param name="row">Row</param>
        /// <param name="column">Column</param>
        public AnalysisResultCell(List <object> values, AnalysisRow row, AnalysisColumn column)
        {
            Row    = row;
            Column = column;
            var result = 0.0;

            if (column.IsTextColumn || values?.Any() == false)
            {
                Value       = 0;
                StringValue = string.Empty;
            }

            var collection      = values?.OfType <AnalysisProcessingResultColumnValue>();
            var lstAnalysis     = collection?.ToList();
            var aggregationType = column.ResultColumn.AggregationType;

            if (lstAnalysis?.Any() == true)
            {
                result = GetAggregatedResult(aggregationType, lstAnalysis);
            }

            Value       = result;
            StringValue = column.ResultColumn.DisplayStringFromNumber(Value);
            var xCategoryValues = column.XCategoryValues;

            if (xCategoryValues?.Any() == true)
            {
                XResultCells = GetAnalysisXResultCells(lstAnalysis, aggregationType, column);
            }
        }
コード例 #28
0
        protected virtual void SubAreaControl_Leaving(object sender, WPFUserControl.AutoCompleteTextBoxControlEventArgs e)
        {
            if (SubjectLocationControl.ListBoxReadOnly)
            {
                // get the country / area / subarea names from UI
                var countryName = CountryControl.GetCurrentText();
                var areaName    = AreaControl.GetCurrentText();
                var subAreaName = SubAreaControl.GetCurrentText();

                // get country object from UI
                if (CountryControl.GetCurrentObject() is Country country)
                {
                    // find the corresponding subject location (need to match country, area and subarea)
                    var subjectLocations = country.SubjectLocations.Where(c => c.Country.Name == countryName && c.Area.Name == areaName && c.SubArea.Name == subAreaName).ToList();

                    // valid subject Locations
                    if (subjectLocations != null)
                    {
                        // refresh control
                        RefreshControl(subjectLocations?.OfType <Location>().ToList(), SubjectLocationControl);
                    }
                }
            }
            else
            {
                RefreshControl(_allSubjectLocations?.OfType <Location>().ToList(), SubjectLocationControl);
            }

            // take subarea name from subarea object (if in database) or from UI text
            SetSubAreaDisplayItem(e.Object is SubArea subArea ? subArea.Name : SubAreaControl.GetCurrentText());

            SubjectLocationControl.SetFocus();
        }
コード例 #29
0
ファイル: Sprites.cs プロジェクト: kevin-montrose/More
        public static List<Block> Task(List<Block> blocks)
        {
            var inputFile = Current.InitialFilePath;

            var spriteDecls = blocks.OfType<SpriteBlock>().ToList();
            if (spriteDecls.Count == 0)
            {
                return blocks;
            }

            var ret = blocks.Where(w => w.GetType() != typeof(SpriteBlock)).ToList();

            foreach (var sprite in spriteDecls)
            {
                var output = sprite.OutputFile.Value.RebaseFile(inputFile);

                var input = sprite.Sprites.ToDictionary(k => k.MixinName, v => v.SpriteFilePath.Value.RebaseFile(inputFile));

                var export = SpriteExport.Create(output, inputFile, input);
                Current.SpritePending(export);

                ret.AddRange(export.MixinEquivalents());

                Current.Dependecies.SpritesResolved(sprite);
            }

            return ret;
        }
コード例 #30
0
        public RequestMetadata GetRequestMetadata(RequestLog source)
        {
            var entries = new List<object>(source.LogTable.Rows.Count);

            foreach (DataRow row in source.LogTable.Rows)
            {
                try
                {
                    object entry = mEntryFactory.CreateEntry(row);
                    if (entry != null)
                    {
                        entries.Add(entry);
                    }
                }
                catch (ArgumentException exception)
                {
                    Trace.TraceWarning(exception.Message);
                }
            }

            var commandEntries = entries.OfType<CommandEntry>();

            return new RequestMetadata
            {
                Entries = entries,
                Statistics = new RequestMetadataStatistics
                {
                    TotalCommands = commandEntries.LongCount(),
                    TotalDuration = commandEntries.Aggregate(TimeSpan.Zero, (value, entry) => value + entry.Duration),
                    TotalBytesReceived = commandEntries.Sum(x => x.BytesReceived),
                    TotalBytesSent = commandEntries.Sum(x => x.BytesSent),
                    TotalDuplicateCommands = commandEntries.LongCount(x => x.IsDuplicate)
                }
            };
        }
コード例 #31
0
		private bool ValidateVersion(List<Plan> folders)
		{
			bool result = true;
			foreach (var plan in folders.OfType<Plan>())
				result &= ValidateVersion(plan);
			return result;
		}
コード例 #32
0
ファイル: AppConfig.cs プロジェクト: mibbio/PoE-Helper
		public AppConfig( string configFile ) {
			this.saveFile = configFile;
			this.configState = ConfigState.Loading;
			this.currencies = new List<Currency>(24);
			try {
				config = Configuration.LoadFromFile(configFile, Encoding.UTF8);
				foreach (Section sec in config) {
					Currency c = sec.CreateObject<Currency>();
					if (sec["Name"].StringValue.Contains("Chaos")) { c.Value = 1; }
					this.currencies.Add(c);
				}
			}
			catch (Exception) {
				InitializeCurrency();
				config = new Configuration();
				byte id = 0;
				var currencyData = currencies.OfType<Currency>().OrderBy(item => item.Name).GetEnumerator();
				while (currencyData.MoveNext()) {
					config.Add(Section.FromObject(SECTION_CURRENCY + id, currencyData.Current));
					id++;
				}
				config.SaveToFile(configFile, Encoding.UTF8);
			}
			configState = ConfigState.Clean;
		}
コード例 #33
0
ファイル: World.cs プロジェクト: JaakkoLipsanen/WVVW
        private Portal _stagePortal; // Can be null

        #endregion Fields

        #region Constructors

        protected World(WorldMap worldMap, List<GameObject> gameObjects, List<DoorGroup> doorGroups)
        {
            _worldMap = worldMap;
            _timeBonuses = gameObjects.OfType<TimeBonus>().ToList();
            _springs = gameObjects.OfType<Spring>().ToList();
            _keys = gameObjects.OfType<Key>().ToList();
            _cannons = gameObjects.OfType<Cannon>().ToList();
            _doors = gameObjects.OfType<Door>().ToList();
            _doorGroups = doorGroups;

            _readOnlyTimeBonuses = new ReadOnlyCollection<TimeBonus>(_timeBonuses);
            _readOnlySprings = new ReadOnlyCollection<Spring>(_springs);
            _readOnlyKeys = new ReadOnlyCollection<Key>(_keys);
            _readOnlyCannons = new ReadOnlyCollection<Cannon>(_cannons);
            _readOnlyDoors = new ReadOnlyCollection<Door>(_doors);
        }
コード例 #34
0
        private static void EnsureLoaded()
        {
            if (itemDefinitions == null)
            {
                // Items sammeln
                itemDefinitions = new List<IItemDefinition>();
                itemDefinitions.AddRange(ExtensionManager.GetInstances<IItemDefinition>());

                // Ressourcen sammeln
                resourceDefinitions = new List<IResourceDefinition>();
                resourceDefinitions.AddRange(itemDefinitions.OfType<IResourceDefinition>());

                // Blöcke sammeln
                blockDefinitions = itemDefinitions.OfType<IBlockDefinition>().ToArray();
            }
        }
コード例 #35
0
ファイル: FilterForm.cs プロジェクト: nodia/scut
 public void SetFilters(List<IFilter> filters)
 {
     foreach (var filter in filters.OfType<ContainsTextFilter>())
     {
         filterPanel.Controls.Add(new ContainsTextFilterControl { Filter = filter });
     }
 }
コード例 #36
0
        private ConsoleMenuItem Next(bool firstChildWhenExpanded)
        {
            if (firstChildWhenExpanded && IsExpanded && HasChildren)
            {
                return(items?.OfType <ConsoleMenuItem>().FirstOrDefault());
            }

            if (Parent == null || ((ConsoleMenuItem)Parent).items == null)
            {
                return(null);
            }

            var currentIndex = ((ConsoleMenuItem)Parent).items.IndexOf(this);
            var nextIndex    = currentIndex + 1;

            while (nextIndex < ((ConsoleMenuItem)Parent).items.Count)
            {
                var item = ((ConsoleMenuItem)Parent).items[nextIndex] as ConsoleMenuItem;
                if (item != null)
                {
                    return(item);
                }

                nextIndex++;
            }

            return(((ConsoleMenuItem)Parent).Next(false));
        }
コード例 #37
0
 private static void BeforeQueuedEvents_PauseBase(List <IGeoCharacterContainer> ____justRestedContainer, GeoLevelController ____level)
 {
     try {
         if (____justRestedContainer?.OfType <GeoSite>().Any() != true)
         {
             return;
         }
         Info("Crew in a base are rested. Pausing.");
         ____level.View.RequestGamePause();
     } catch (Exception ex) { Error(ex); }
 }
コード例 #38
0
 private static void BeforeQueuedEvents_CentreBase(List <IGeoCharacterContainer> ____justRestedContainer, GeoLevelController ____level)
 {
     try {
         var pxbase = ____justRestedContainer?.OfType <GeoSite>().FirstOrDefault();
         if (pxbase == null)
         {
             return;
         }
         Info("Crew in base {0} are rested. Centering.", pxbase.Name);
         ____level.View.ChaseTarget(pxbase, false);
     } catch (Exception ex) { Error(ex); }
 }
コード例 #39
0
        public DataClass GetInventoryData(List <ConfigObject> profileVars)
        {
            var innerData =
                profileVars?.OfType <GeneralClass>().FirstOrDefault(item => item.ClassName == ProfileVariablesString);
            var inventoryClass =
                innerData?.Content.OfType <ItemClass>().FirstOrDefault(item => item.Name == InventoryDataString);

            if (inventoryClass != null)
            {
                return(inventoryClass.Data);
            }
            throw new ArgumentException("No inventory data found in config variables.");
        }
コード例 #40
0
        private string GetFirstAvailableTrustBoundaryName()
        {
            _lastTrustBoundary += 1;

            string result = $"{GetIdentityTypeName(typeof(TrustBoundary))} {_lastTrustBoundary}";

            var trustBoundary = _groups?.OfType <ITrustBoundary>().FirstOrDefault(x => string.CompareOrdinal(result, x.Name) == 0);

            if (trustBoundary != null)
            {
                result = GetFirstAvailableTrustBoundaryName();
            }

            return(result);
        }
コード例 #41
0
ファイル: Broker.cs プロジェクト: 7studios/silverback
        protected virtual void Dispose(bool disposing)
        {
            if (!disposing)
            {
                return;
            }

            Disconnect();

            _consumers?.OfType <IDisposable>().ForEach(o => o.Dispose());
            _consumers = null;

            _producers?.Values.OfType <IDisposable>().ForEach(o => o.Dispose());
            _producers = null;
        }
コード例 #42
0
 private static void BeforeQueuedEvents_CentreVehicle(List <IGeoCharacterContainer> ____justRestedContainer, GeoLevelController ____level)
 {
     try {
         var vehicle = ____justRestedContainer?.OfType <GeoVehicle>().FirstOrDefault();
         if (vehicle == null)
         {
             return;
         }
         GeoscapeViewState state = ____level.View.CurrentViewState;
         Info("Crew on {0} are rested. ViewState is {1}.", vehicle.Name, state);
         if (state is UIStateVehicleSelected)
         {
             typeof(UIStateVehicleSelected).GetMethod("SelectVehicle", NonPublic | Instance).Invoke(state, new object[] { vehicle, true });
         }
     } catch (Exception ex) { Error(ex); }
 }
コード例 #43
0
ファイル: IndexNode.cs プロジェクト: shupoval/json-everything
        protected override IEnumerable <PathMatch> ProcessMatch(PathMatch match)
        {
            switch (match.Value.ValueKind)
            {
            case JsonValueKind.Array:
                var array = match.Value.EnumerateArray().ToArray();
                IEnumerable <int> indices;
                indices = _ranges?.OfType <IArrayIndexExpression>()
                          .SelectMany(r => r.GetIndices(match.Value))
                          .OrderBy(i => i)
                          .Where(i => 0 <= i && i < array.Length)
                          .Distinct() ??
                          Enumerable.Range(0, array.Length);
                foreach (var index in indices)
                {
                    yield return(new PathMatch(array[index], match.Location.Combine(PointerSegment.Create(index.ToString()))));
                }
                break;

            case JsonValueKind.Object:
                if (_ranges != null)
                {
                    var props = _ranges.OfType <IObjectIndexExpression>()
                                .SelectMany(r => r.GetProperties(match.Value))
                                .Distinct();
                    foreach (var prop in props)
                    {
                        if (!match.Value.TryGetProperty(prop, out var value))
                        {
                            continue;
                        }
                        yield return(new PathMatch(value, match.Location.Combine(PointerSegment.Create(prop))));
                    }
                }
                else
                {
                    foreach (var prop in match.Value.EnumerateObject())
                    {
                        yield return(new PathMatch(prop.Value, match.Location.Combine(PointerSegment.Create(prop.Name))));
                    }
                }
                break;
            }
        }
コード例 #44
0
 public IEnumerable <ValidationError> GetErrors()
 {
     return(Messages.OfType <ValidationError>());
 }
コード例 #45
0
 private void RefreshParkingLocationControl()
 {
     RefreshControl(_allParkingLocations?.OfType <Location>()?.ToList(), Window.ParkingLocationControl);
 }
コード例 #46
0
        /// <summary>
        /// Просит переразметить файл
        /// </summary>
        /// <param name="ifChanged">Только изменившийся</param>
        /// <param name="safe">Нужна ли синхронизация</param>
        public void Remap(bool ifChanged)
        {
            var path = FullPath;
            var fi   = new FileInfo(path);

            if (ifChanged && LastUpdate == fi.LastWriteTime && LastSize == fi.Length)
            {
                return;
            }
            LastUpdate = fi.LastWriteTime;
            LastSize   = fi.Length;
            try
            {
                _Items = null;
                if (!System.IO.File.Exists(path))
                {
                    return;
                }
                var mapper = Core.Mappers.FindMapper(Ext);
                if (mapper != null)
                {
                    try
                    {
                        Action tryGet = () =>
                        {
                            _Items = mapper.GetMap(Text, Ext, MapMethods ? MapperOptions.MapMethods : MapperOptions.None).OrderBy(it => it.Start).ToList();
                            foreach (var item in _Items?.OfType <IMapUnitEntry>())
                            {
                                item.Data = this;
                                item.Path = FullPath;
                            }
                        };
                        try
                        {
                            tryGet();
                        }
                        catch (MapperFixableException e)
                        {
                            if (!FixingEnabled)
                            {
                                throw;
                            }
                            //попытка пофиксить
                            Helpers.ConsoleWrite($"{path}\r\n{e.ToString()}", ConsoleColor.DarkRed);
                            mapper.TryFix(path, Helpers.GetEncoding(path, Helpers.Encoding));
                            tryGet();
                            if (ShowMappingErrors)
                            {
                                MessageBox.Show(string.Format("Произошла ошибка во время обработки файла, файл был исправлен:\r\n{0}\r\n\r\n{1}", path, e));
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        Helpers.ConsoleWrite($"{path}\r\n{e.ToString()}", ConsoleColor.Red);
                        _Items = new List <IMapRangeItem>();
                        if (ShowMappingErrors)
                        {
                            MessageBox.Show(string.Format("Произошла ошибка во время обработки файла:\r\n{0}\r\n\r\n{1}", path, e));
                        }
                    }
                }
            }
            finally
            {
                if (Items == null)
                {
                    _StringsCount    = _CyrilicCount = 0;
                    _ContainsLiteral = false;
                }
                else
                {
                    var mapValItems = Items.OfType <IMapValueItem>();
                    _StringsCount    = mapValItems.Count();
                    _CyrilicCount    = mapValItems.Where(it => cyrRegex.IsMatch(it.Value)).Count();
                    _ContainsLiteral = mapValItems.Any(it => it.Value.Any(c => char.IsLetter(c)));
                }
                if (!IsUpdating)
                {
                    NotifyPropertiesChanged(nameof(CyrilicCount), nameof(StringsCount), nameof(Items), nameof(ShowingItems));
                }
            }
        }
コード例 #47
0
 public object AppImplementationOfType(Type typeToAssignTo)
 {
     return(MengeKomponente?.OfType <IInterfaceKomponenteImplementationOfType>()?.Select((IInterfaceKomponenteImplementationOfType komponente) => komponente?.Implementation(typeToAssignTo))?.WhereNotDefault()?.FirstOrDefault());
 }
コード例 #48
0
 public T Find <T>(Func <T, bool> match)
 {
     return(_list.OfType <T>().FirstOrDefault(match));
 }
コード例 #49
0
        private object IEnumerableToExcel(IEnumerable rowEnumerable, Match toExcelMatch, List <object> args = null)
        {
            ExcelPackage pack4Book = new ExcelPackage();

            IDictionary <string, object> config = args?.OfType <IDictionary <string, object> >().FirstOrDefault();

            string sheetName = config?.FirstOrDefault(kvp => Regex.IsMatch(kvp.Key, "^s(heet)?_?n(ame)?$", RegexOptions.IgnoreCase)).Value?.ToString();

            ExcelWorksheet sheet = pack4Book.Workbook.Worksheets.Add(string.Format(sheetName ?? Config.Instance.ExcelDefaultSheetName, pack4Book.Workbook.Worksheets.Count + 1));

            dynamic preDo = config?.FirstOrDefault(kvp => Regex.IsMatch(kvp.Key, "^((pre_?((do)|(execute)))|(before_?((do)|(execute)))|(((do)|(execute))_?((before)|(at_?(the_?)?((start)|(begining))))))$", RegexOptions.IgnoreCase)).Value;

            if (preDo != null)
            {
                MethodInfo method = preDo.Method as MethodInfo;
                method?.Invoke(preDo.Target, new object[] { new object[] { sheet } });
            }

            List <object> rowList = rowEnumerable.Cast <object>().ToList();

            Dictionary <string, int> headersColumns = new Dictionary <string, int>();

            var headersConfig = (config?.FirstOrDefault(kvp => Regex.IsMatch(kvp.Key, "^(headers?(_?names?)?)|(col(umns?)?(_?names?)?)$", RegexOptions.IgnoreCase) && !(kvp.Value is string) && kvp.Value is IEnumerable).Value as IEnumerable)?.OfType <string>()?.ToList();

            List <string> headers = headersConfig
                                    ?? args?
                                    .Where(a => !(a is string) && !(a is IDictionary <string, object>))
                                    .OfType <IEnumerable>()
                                    .FirstOrDefault()?
                                    .OfType <string>()?
                                    .ToList()
                                    ?? new List <string>();

            for (int r = 0; r < rowList.Count; r++)
            {
                if (rowList[r] is IDictionary <string, object> dict)
                {
                    dict.Keys.ToList().ForEach(name =>
                    {
                        if (!headersColumns.ContainsKey(name))
                        {
                            headers.Add(name);
                            headersColumns[name] = headers.Count;
                        }

                        if (dict[name] is DateTime dateTime)
                        {
                            sheet.SetValue(r + 1, headersColumns[name], dateTime);
                            sheet.Cells[r + 1, headersColumns[name]].Style.Numberformat.Format = Config.Instance.ExcelDateTimeDefaultFormat;
                        }
                        else if (dict[name].GetType().IsValueType)
                        {
                            sheet.SetValue(r + 1, headersColumns[name], dict[name]);
                        }
                        else
                        {
                            sheet.SetValue(r + 1, headersColumns[name], dict[name].ToString());
                        }
                    });
                }
                else if (rowList[r] is IEnumerable columnEnumerable)
                {
                    List <object> columnList = columnEnumerable.Cast <object>().ToList();

                    for (int c = 0; c < columnList.Count; c++)
                    {
                        sheet.SetValue(r + 1, c + 1, columnList[c].ToString());
                    }
                }
                else if (rowList[r] is DateTime dateTime)
                {
                    sheet.SetValue(r + 1, 1, dateTime);
                    sheet.Cells[r + 1, 1].Style.Numberformat.Format = Config.Instance.ExcelDateTimeDefaultFormat;
                }
                else if (rowList[r].GetType().IsValueType)
                {
                    sheet.SetValue(r + 1, 1, rowList[r]);
                }
            }

            if (headers.Count > 0 &&
                !toExcelMatch.Groups["noheader"].Success &&
                !(config?.FirstOrDefault(kvp => Regex.IsMatch(kvp.Key, "^no?_?h(ead(er)?)?$", RegexOptions.IgnoreCase)).Value as bool?).GetValueOrDefault())
            {
                sheet.InsertRow(1, 1);

                for (int c = 0; c < headers.Count; c++)
                {
                    sheet.SetValue(1, c + 1, headers[c]);
                }
            }

            if (toExcelMatch.Groups["fatheader"].Success ||
                (config?.FirstOrDefault(kvp => Regex.IsMatch(kvp.Key, "^(f(at)?|b(old)?)_?h(ead(er)?)?$", RegexOptions.IgnoreCase)).Value as bool?).GetValueOrDefault())
            {
                sheet.Cells[1, 1, 1, sheet.Dimension.Columns].Style.Font.Bold = true;
            }

            if (toExcelMatch.Groups["autofilter"].Success ||
                (config?.FirstOrDefault(kvp => Regex.IsMatch(kvp.Key, "^(a(uto)?)_?f(ilter)?$", RegexOptions.IgnoreCase)).Value as bool?).GetValueOrDefault())
            {
                sheet.Cells[1, 1, sheet.Dimension.Rows, sheet.Dimension.Columns].AutoFilter = true;
            }

            if (toExcelMatch.Groups["freeze"].Success)
            {
                int row    = int.Parse(toExcelMatch.Groups["freezerow"].Value);
                int column = int.Parse(toExcelMatch.Groups["freezecolumn"].Value);

                sheet.View.FreezePanes(row, column);
            }
            else if (config?.FirstOrDefault(kvp => Regex.IsMatch(kvp.Key, "^fr(eeze)?$", RegexOptions.IgnoreCase)).Value is object freezeObject)
            {
                int row    = 1;
                int column = 1;

                if (freezeObject is int freezeInt)
                {
                    row = freezeInt;
                }
                else if (freezeObject is Dictionary <string, object> freezeDictionary)
                {
                    if (freezeDictionary.FirstOrDefault(kvp => Regex.IsMatch(kvp.Key, "^(r(ows?)?)|y$", RegexOptions.IgnoreCase)).Value is int freezeRow)
                    {
                        row = freezeRow;
                    }
                    if (freezeDictionary.FirstOrDefault(kvp => Regex.IsMatch(kvp.Key, "^(c(ol(umn)?s?)?)|y$", RegexOptions.IgnoreCase)).Value is int freezeColumn)
                    {
                        column = freezeColumn;
                    }
                }
                else if (freezeObject is IEnumerable freezeEnum)
                {
                    var values = freezeEnum.OfType <int>().ToList();
                    if (values.Count > 0)
                    {
                        row = values[0];
                    }
                    if (values.Count > 1)
                    {
                        column = values[1];
                    }
                }

                sheet.View.FreezePanes(row, column);
            }
            if (toExcelMatch.Groups["columnautosize"].Success ||
                (config?.FirstOrDefault(kvp => Regex.IsMatch(kvp.Key, "^(c(ol(umn)?)?)_?(a(uto)?)_?s(ize)?$", RegexOptions.IgnoreCase)).Value as bool?).GetValueOrDefault())
            {
                sheet.Cells[sheet.Dimension.Address].AutoFitColumns();
            }

            dynamic postDo = config?.FirstOrDefault(kvp => Regex.IsMatch(kvp.Key, "^((post_?((do)|(execute)))|(after_?((do)|(execute)))|(((do)|(execute))_?((after)|(at_?(the_?)?end))))$", RegexOptions.IgnoreCase)).Value;

            if (postDo != null)
            {
                MethodInfo method = postDo.Method as MethodInfo;
                method?.Invoke(postDo.Target, new object[] { new object[] { sheet } });
            }

            return(pack4Book);
        }
コード例 #50
0
 /// <summary>
 /// Gets the storage mechanism.
 /// </summary>
 /// <typeparam name="T">The type of storage mechanism to get.</typeparam>
 /// <returns>The storage mechanism.</returns>
 public T GetStorageMechanism<T>() where T : IStorageMechanism {
     return storageMechanisms.OfType<T>().FirstOrDefault();
 }
コード例 #51
0
ファイル: CarePlanService.cs プロジェクト: lulzzz/openizdc
        public Bundle CreatePlan([RestMessage(RestMessageFormat.SimpleJson)] Patient p)
        {
            // Additional instructions?
            this.m_tracer.TraceInfo(">>>> CALCULATING CARE PLAN ");

            var search    = NameValueCollection.ParseQueryString(MiniImsServer.CurrentContext.Request.Url.Query);
            var predicate = QueryExpressionParser.BuildLinqExpression <Act>(search);

            if (search.ContainsKey("_patientId"))
            {
                var patientSvc = ApplicationContext.Current.GetService <IPatientRepositoryService>();
                p = patientSvc.Get(Guid.Parse(search["_patientId"][0]), Guid.Empty)?.Clone() as Patient;
                //p.Participations = new List<ActParticipation>();
            }

            if (p == null)
            {
                throw new FileNotFoundException();
            }

            //        if(p.Participations.Count == 0)
            //        {
            //            var actService = ApplicationContext.Current.GetService<IActRepositoryService>();
            //            int tr = 0;
            //            IEnumerable<Act> acts = null;
            //            Guid searchState = Guid.Empty;

            //if (actService is IPersistableQueryProvider && search.ContainsKey("_state") && Guid.TryParse(search["_state"][0], out searchState))
            //	acts = (actService as IPersistableQueryProvider).Query<Act>(o => o.Participations.Any(guard => guard.ParticipationRole.Mnemonic == "RecordTarget" && guard.PlayerEntityKey == p.Key), 0, 200, out tr, searchState);
            //else
            //	acts = actService.Find<Act>(o => o.Participations.Any(guard => guard.ParticipationRole.Mnemonic == "RecordTarget" && guard.PlayerEntityKey == p.Key), 0, 200, out tr);

            //            p.Participations = acts.Select(a => new ActParticipation(ActParticipationKey.RecordTarget, p)
            //            {
            //             Act = a,
            //	ParticipationRole = new Concept { Mnemonic = "RecordTarget" },
            //	SourceEntity = actService.Get<Act>(a.Key.Value, Guid.Empty)
            //            }).ToList();
            //        }

            // As appointments
            bool asAppointments = search.ContainsKey("_appointments") && search["_appointments"][0] == "true";

            var       protocolService = ApplicationContext.Current.GetService <ICarePlanService>();
            Stopwatch sw = new Stopwatch();

            sw.Start();

            List <Act> plan = null;

            if (search.ContainsKey("_protocolId"))
            {
                plan = protocolService.CreateCarePlan(p, asAppointments, null, search["_protocolId"].Select(o => Guid.Parse(o)).ToArray()).Action;
            }
            else
            {
                plan = protocolService.CreateCarePlan(p, asAppointments).Action; // All protocols
            }
            sw.Stop();
            this.m_tracer.TraceInfo(">>>> CARE PLAN CONSTRUCTED IN {0}", sw.Elapsed);


            // Assign location to all
            var sdlKey = (AuthenticationContext.Current.Session.UserEntity.Relationships.FirstOrDefault(o => o.RelationshipTypeKey == EntityRelationshipTypeKeys.DedicatedServiceDeliveryLocation || o.RelationshipType?.Mnemonic == "DedicatedServiceDeliveryLocation") ??
                          p.Relationships.FirstOrDefault(o => o.RelationshipTypeKey == EntityRelationshipTypeKeys.DedicatedServiceDeliveryLocation || o.RelationshipType?.Mnemonic == "DedicatedServiceDeliveryLocation"))?.TargetEntityKey;

            if (sdlKey.HasValue)
            {
                foreach (var itm in plan)
                {
                    if (!itm.Participations.Any(o => o.ParticipationRoleKey == ActParticipationKey.Location || o.ParticipationRole?.Mnemonic == "Location"))
                    {
                        itm.Participations.Add(new ActParticipation(ActParticipationKey.Location, sdlKey));
                    }
                }
            }

            // Instructions?
            if (search.Count > 0)
            {
                var pred = predicate.Compile();
                plan.RemoveAll(o => !pred(o));
            }

            return(new Bundle()
            {
                Item = plan.OfType <IdentifiedData>().ToList()
            });
            //return plan;
        }
コード例 #52
0
        internal void PopulateEditorList(AchievementScriptInterpreter interpreter)
        {
            var editors = new List <GeneratedItemViewModelBase>();

            if (Script != null)
            {
                editors.Add(Script);
            }

            if (interpreter != null)
            {
                GeneratedAchievementCount = interpreter.Achievements.Count();
                editors.Capacity         += GeneratedAchievementCount;

                if (!String.IsNullOrEmpty(interpreter.RichPresence))
                {
                    var richPresenceViewModel = new RichPresenceViewModel(this, interpreter.RichPresence);
                    if (richPresenceViewModel.Lines.Any())
                    {
                        richPresenceViewModel.SourceLine = interpreter.RichPresenceLine;
                        editors.Add(richPresenceViewModel);
                    }
                }

                foreach (var achievement in interpreter.Achievements)
                {
                    var achievementViewModel = new GeneratedAchievementViewModel(this, achievement);
                    editors.Add(achievementViewModel);
                }

                foreach (var leaderboard in interpreter.Leaderboards)
                {
                    editors.Add(new LeaderboardViewModel(this, leaderboard));
                }
            }
            else
            {
                GeneratedAchievementCount = 0;
            }

            if (!String.IsNullOrEmpty(RACacheDirectory))
            {
                if (_isN64)
                {
                    MergePublishedN64(GameId, editors);
                }
                else
                {
                    MergePublished(GameId, editors);
                }

                MergeLocal(GameId, editors);
            }

            int nextLocalId = 111000001;

            foreach (var achievement in editors.OfType <GeneratedAchievementViewModel>())
            {
                if (achievement.Local != null && achievement.Local.Id >= nextLocalId)
                {
                    nextLocalId = achievement.Local.Id + 1;
                }
            }

            foreach (var achievement in editors.OfType <GeneratedAchievementViewModel>())
            {
                if (achievement.Local != null && achievement.Local.Id == 0)
                {
                    achievement.Local.Id = nextLocalId++;
                }

                achievement.UpdateCommonProperties(this);
            }

            Editors = editors;
        }
コード例 #53
0
 public IEnumerable <TFactory> QueryDataSourceFactories <TFactory>()
     where TFactory : ConfiguredDataSourceFactory
 {
     return(_dataSourceFactories?.OfType <TFactory>() ?? Enumerable <TFactory> .Empty);
 }
コード例 #54
0
 private List <IInstallable> GetInstallableItems()
 {
     return(_configItems.OfType <IInstallable>().ToList());
 }
 protected bool CanAcceptDrop(List <IGraphElementModel> draggedObjects)
 {
     return(draggedObjects?.OfType <IVariableDeclarationModel>().Any(ContainsVariable) ?? false);
 }
コード例 #56
0
        static List <CodeAction> GetActions(CodeRefactoringProvider action, string input, out CSharpDiagnosticTestBase.TestWorkspace workspace, out Document doc, CSharpParseOptions parseOptions = null)
        {
            TextSpan selectedSpan;
            TextSpan markedSpan;
            string   text = ParseText(input, out selectedSpan, out markedSpan);

            workspace = new CSharpDiagnosticTestBase.TestWorkspace();
            var projectId  = ProjectId.CreateNewId();
            var documentId = DocumentId.CreateNewId(projectId);

            if (parseOptions == null)
            {
                parseOptions = new CSharpParseOptions(
                    LanguageVersion.CSharp6,
                    DocumentationMode.Diagnose | DocumentationMode.Parse,
                    SourceCodeKind.Regular,
                    ImmutableArray.Create("DEBUG", "TEST")
                    );
            }
            workspace.Options = workspace.Options
                                .WithChangedOption(CSharpFormattingOptions.NewLinesForBracesInControlBlocks, true);
            workspace.Open(ProjectInfo.Create(
                               projectId,
                               VersionStamp.Create(),
                               "TestProject",
                               "TestProject",
                               LanguageNames.CSharp,
                               null,
                               null,
                               new CSharpCompilationOptions(
                                   OutputKind.DynamicallyLinkedLibrary,
                                   false,
                                   "",
                                   "",
                                   "Script",
                                   null,
                                   OptimizationLevel.Debug,
                                   false,
                                   true
                                   ),
                               parseOptions,
                               new[] {
                DocumentInfo.Create(
                    documentId,
                    "a.cs",
                    null,
                    SourceCodeKind.Regular,
                    TextLoader.From(TextAndVersion.Create(SourceText.From(text), VersionStamp.Create()))
                    )
            },
                               null,
                               DiagnosticTestBase.DefaultMetadataReferences
                               )
                           );
            doc = workspace.CurrentSolution.GetProject(projectId).GetDocument(documentId);
            var actions = new List <CodeAction>();
            var context = new CodeRefactoringContext(doc, selectedSpan, actions.Add, default(CancellationToken));

            action.ComputeRefactoringsAsync(context).Wait();
            if (markedSpan.Start > 0)
            {
                foreach (var nra in actions.OfType <NRefactoryCodeAction>())
                {
                    Assert.AreEqual(markedSpan, nra.TextSpan, "Activation span does not match.");
                }
            }
            return(actions);
        }
コード例 #57
0
 private IEnumerable <ScriptListenKey> GetScriptListenKeyScripts()
 {
     return(_scripts?.OfType <ScriptListenKey>());
 }
コード例 #58
0
 public Mock <T> Mock <T>() where T : class => mocks.OfType <Mock <T> >().First();
コード例 #59
0
ファイル: Network.cs プロジェクト: JPsychotic/SWP16
 /// <summary>
 /// Gets all workstations.
 /// </summary>
 /// <returns>all Workstations</returns>
 public List <Workstation> GetAllWorkstations()
 {
     return(nodes.OfType <Workstation>().ToList());
 }
コード例 #60
0
 private void RefreshShootLocationControl()
 {
     RefreshControl(_allShootingLocations?.OfType <Location>()?.ToList(), Window.ShootingLocationControl);
 }