public void Run(BuildTarget target, 
			NodeData node, 
			ConnectionPointData inputPoint,
			ConnectionData connectionToOutput, 
			Dictionary<string, List<Asset>> inputGroupAssets, 
			List<string> alreadyCached, 
			Action<ConnectionData, Dictionary<string, List<Asset>>, List<string>> Output)
        {
            var incomingAssets = inputGroupAssets.SelectMany(v => v.Value).ToList();

            var modifier = ModifierUtility.CreateModifier(node, target);
            UnityEngine.Assertions.Assert.IsNotNull(modifier);
            bool isAnyAssetModified = false;

            foreach(var asset in incomingAssets) {
                var loadedAsset = AssetDatabase.LoadAssetAtPath<UnityEngine.Object>(asset.importFrom);
                if(modifier.IsModified(loadedAsset)) {
                    modifier.Modify(loadedAsset);
                    isAnyAssetModified = true;
                }
            }

            if(isAnyAssetModified) {
                // apply asset setting changes to AssetDatabase.
                AssetDatabase.Refresh();
            }

            // Modifier does not add, filter or change structure of group, so just pass given group of assets
            Output(connectionToOutput, inputGroupAssets, null);
        }
Пример #2
0
 /// <summary>
 /// Detects which expressions in a <see cref="Grammar"/> are left-adjacent.
 /// </summary>
 /// <param name="grammar">The <see cref="Grammar"/> to inspect.</param>
 /// <returns>A <see cref="ILookup{Rule, Expression}"/> containing the left-adjacent rules.</returns>
 public static ILookup<Rule, Expression> Detect(Grammar grammar)
 {
     var leftAdjacent = new Dictionary<Rule, List<Expression>>();
     var zeroWidth = ZeroWidthEvaluator.Evaluate(grammar);
     new LeftRecursionExpressionTreeWalker(zeroWidth, leftAdjacent).WalkGrammar(grammar);
     return leftAdjacent.SelectMany(i => i.Value, (i, v) => new { i.Key, Value = v }).ToLookup(i => i.Key, i => i.Value);
 }
        public TagConverter(ISettingsProvider settingsProvider)
        {
            using (var reader = new StreamReader(settingsProvider.Get<string>(SettingsKeys.TagMappingFile)))
            {
                normalizedTags = reader
                    .ReadAllLines()
                    .Where(x => !string.IsNullOrWhiteSpace(x))
                    .Select(ParseTagDescription)
                    .ToDictionary(x => x.Name, x => x.RawTags);

                rawTagsMapping = normalizedTags
                    .SelectMany(normalizedTag => normalizedTag.Value.Select(rawTag => new { Normalized = normalizedTag.Key, Raw = rawTag }))
                    .ToDictionary(x => x.Raw, x => x.Normalized);
            }

            using (var reader = new StreamReader(settingsProvider.Get<string>(SettingsKeys.CorrectionsFile)))
            {
                correctionsByProblemUrl = reader
                    .ReadAllLines()
                    .Where(x => !string.IsNullOrWhiteSpace(x))
                    .SelectMany(ParseCorrections)
                    .GroupBy(x => x.ProblemUrl)
                    .ToDictionary(x => x.Key, x => x.ToArray());
            }
        }
Пример #4
0
        public static IEnumerable <Type> FindTypes <T>()
        {
            Type targetType = typeof(T);

            return(assemblyAndTypes?.SelectMany(kvp => kvp.Value)
                   .Where(type => targetType.IsAssignableFrom(type)));
        }
Пример #5
0
 private static IEnumerable<dynamic> LetterValuePairs(
 Dictionary<int, IList<string>> old)
 {
     return old.SelectMany(
       kvp => kvp.Value.Select(
     letter => new {Letter = letter.ToLower(), Value = kvp.Key}));
 }
Пример #6
0
 /// <summary>
 /// Initializes a new instance of the <see cref="FakeDataQueue"/> class to randomly emit data for each symbol
 /// </summary>
 public FakeDataQueue()
 {
     _ticks = new ConcurrentQueue<BaseData>();
     _symbols = new Dictionary<SecurityType, List<string>>();
     _timer = new Timer
     {
         AutoReset = true,
         Enabled = true
     };
     _timer.Elapsed += (sender, args) =>
     {
         _timer.Interval = _random.Next(15, 2500); // around each second
         foreach (var symbol in _symbols.SelectMany(x => x.Value))
         {
             // 50/50 repeating chance of emitting each symbol
             while (_random.NextDouble() > 0.75)
             {
                 _ticks.Enqueue(new Tick
                 {
                     Time = DateTime.Now,
                     Symbol = symbol,
                     Value = 10 + (decimal) Math.Abs(Math.Sin(DateTime.Now.TimeOfDay.TotalMinutes)),
                     TickType = TickType.Trade,
                     Quantity = _random.Next(10, (int) _timer.Interval)
                 });
             }
         }
     };
 }
        public void Given_30_New_Tweets_GetLatest_Returns_Tweets_In_Correct_Order()
        {
            var queryTweets = new Dictionary<string, IEnumerable<Item>>
            {
                { "#hashtag", BuildTweets(5) },
                { "@user", BuildTweets(10) },
                { "text", BuildTweets(15) }
            };
            var minDate = queryTweets.SelectMany(kv => kv.Value).Select(f => f.Published).Min();
            var maxDate = queryTweets.SelectMany(kv => kv.Value).Select(f => f.Published).Max();
            var twitterAggregator = BuildTwitterAggregator(queryTweets);

            var tweets = twitterAggregator.GetLatest(DateTime.MinValue).ToList();

            Assert.AreEqual(minDate, tweets.First().Published);
            Assert.AreEqual(maxDate, tweets.Last().Published);
        }
Пример #8
0
        public void Given_30_New_Feeds_GetLatest_Returns_Feeds_In_Correct_Order()
        {
            var urlFeeds = new Dictionary<string, IEnumerable<Item>>
            {
                { "http://atom1", BuildFeeds(5) },
                { "http://atom2", BuildFeeds(10) },
                { "http://atom3", BuildFeeds(15) }
            };
            var minDate = urlFeeds.SelectMany(kv => kv.Value).Select(f => f.Published).Min();
            var maxDate = urlFeeds.SelectMany(kv => kv.Value).Select(f => f.Published).Max();
            var rssAggregator = BuildRssAggregator(urlFeeds);

            var feeds = rssAggregator.GetLatest(DateTime.MinValue).ToList();

            Assert.AreEqual(minDate, feeds.First().Published);
            Assert.AreEqual(maxDate, feeds.Last().Published);
        }
Пример #9
0
        public IList GetAllErrors(string[] propertyNames = null)
        {
            if (propertyNames?.Any() == true)
            {
                return(_errors?.Where(error => propertyNames.Contains(error.Key)).SelectMany(error => error.Value).ToList());
            }

            return(_errors?.SelectMany(error => error.Value).ToList());
        }
 private string[] GetDistinctFieldCodes(Dictionary<TemplateModel, List<FieldCodeSummaryModel>> analysisData)
 {
     var distinctFieldCodes = new List<string>();
     foreach (var fieldCodeSummary in analysisData.SelectMany(i => i.Value.Where(fc => !distinctFieldCodes.Contains(fc.ColumnName))))
     {
         distinctFieldCodes.Add(fieldCodeSummary.ColumnName);
     }
     return distinctFieldCodes.OrderBy(fc => fc).ToArray();
 }
Пример #11
0
        public Job(string name, string rowScope, Dictionary<string, List<Column>> capturePathToColumns, TextWriter textWriter)
        {
            _rowScope = rowScope;
            _capturePathToColumn = capturePathToColumns;

            Name = name;
            List<string> columnNames = capturePathToColumns.SelectMany(x => x.Value.Select(y => y.Name)).ToList();
            Writer = new Writer(columnNames, textWriter);
        }
Пример #12
0
        public List<Fork> Search(Dictionary<SportType, Dictionary<GameInfo, List<Game>>> games)
        {
            if (games == null)
            {
                throw new ArgumentNullException(nameof(games));
            }

            return games.SelectMany(pair => this.GetForks(pair.Key, pair.Value)).ToList();
        }
Пример #13
0
        public IEnumerable<BlogPost> GetItems(int feedCount = 20, int pagenum = 0)
        {
            string json = File.ReadAllText("feeddata.json");
            var metadataEntries = json.FromJson<MetaData[]>();

            var syndicationFeeds = new Dictionary<string, SyndicationFeed>();

            foreach (var metadata in metadataEntries)
            {
                var reader = XmlReader.Create(metadata.FeedUrl);
                var feed = SyndicationFeed.Load(reader);

                reader.Close();
                if (feed != null)
                {
                    syndicationFeeds.Add(metadata.Id, feed);
                }
            }

            var data = syndicationFeeds
                .SelectMany(pair => pair.Value.Items, (pair, item) => new { Id = pair.Key, Item = item })
                .Where(x => x.Item.Categories.Any(y => y.Name.ToLower() == "nancy" || y.Name.ToLower() == "nancyfx"))
                .Select(x =>
                {
                    var rssauthor = x.Item.Authors.FirstOrDefault();
                    var metaauthor = metadataEntries.FirstOrDefault(y => y.Id == x.Id);
                    var authorname = string.Empty;
                    var authoremail = string.Empty;

                    if (metaauthor != null)
                    {
                        authorname = rssauthor == null ? metaauthor.Author : rssauthor.Name;
                        authoremail = rssauthor == null ? metaauthor.AuthorEmail : rssauthor.Email;
                    }

                    var link = x.Item.Links.FirstOrDefault();
                    var locallink = link == null ? string.Empty : link.Uri.PathAndQuery;
                    var originallink = link == null ? string.Empty : link.Uri.AbsoluteUri;

                    return new BlogPost
                    {
                        Title = x.Item.Title.Text,
                        Summary = x.Item.Summary.Text,
                        Author = authorname,
                        AuthorEmail = authoremail,
                        Localink = locallink,
                        OriginalLink = originallink
                    };

                })
                .Skip(feedCount * pagenum)
                .Take(feedCount)
                .OrderByDescending(x => x.PublishedDate)
                ;

            return data;
        }
Пример #14
0
        public FakeNewsServer(Dictionary<int, int[]> channelsByAccount)
        {
            var endDate = DateTime.Now.AddHours(-1);
            var startDate = endDate.AddDays(-40);

            this.channelsByAccount = channelsByAccount;
            var channels = channelsByAccount.SelectMany(ca => ca.Value).Distinct();
            newsByChannel = channels.ToDictionary(c => c,
                                                  c => NewsMaker.MakeSomeNews(c, startDate, endDate, 1,
                                                                              random.Next(100) < 50
                                                                                  ? random.Next(1, 10)
                                                                                  : random.Next(2, 1440)));
        }
Пример #15
0
 public static byte[] GetPJL(Dictionary<string, string> jobattribs, Dictionary<string, string> pjlsettings, string language)
 {
     return Encoding.ASCII.GetBytes(
         "\x1B%-12345X".ToArray()
         .Concat("@PJL JOB MODE=PRINTER\r\n")
         .Concat(jobattribs == null ? new char[] { } : jobattribs.SelectMany(kvp => "@PJL SET JOBATTR=\"@".ToArray().Concat(kvp.Key).Concat("=").Concat(kvp.Value).Concat("\"\r\n")))
         .Concat(pjlsettings == null ? new char[] { } : pjlsettings.SelectMany(kvp => "@PJL SET ".ToArray().Concat(kvp.Key).Concat("=").Concat(kvp.Value).Concat("\r\n")))
         .Concat("@PJL ENTER LANGUAGE=")
         .Concat(language)
         .Concat("\r\n")
         .ToArray()
     );
 }
Пример #16
0
        public void TestDetectionEngine()
        {
            Dictionary<string, IList<ISoundSignalReader>> learningWordSignals = new Dictionary<string, IList<ISoundSignalReader>>();
            Dictionary<string, IList<ISoundSignalReader>> testWordSignals = new Dictionary<string, IList<ISoundSignalReader>>();

            var learningDirectories = Directory.GetDirectories("Sounds\\Learning");
            var testDirectories = Directory.GetDirectories("Sounds\\test");

            foreach (var directory in learningDirectories.Where(item => !item.Contains("catalog")))
            {
                var word = new DirectoryInfo(directory).Name;
                learningWordSignals.Add(word, new List<ISoundSignalReader>());
                var wavFiles = Directory.GetFiles(directory).Select(item => new FileInfo(item)).Where(fItem => fItem.Extension.Contains("wav"));
                foreach (var file in wavFiles)
                {
                    learningWordSignals[word].Add(new WavSoundSignalReader(file.FullName));
                }
            }

            foreach (var directory in testDirectories)
            {
                var word = new DirectoryInfo(directory).Name;
                testWordSignals.Add(word, new List<ISoundSignalReader>());
                var wavFiles = Directory.GetFiles(directory).Select(item => new FileInfo(item)).Where(fItem => fItem.Extension.Contains("wav"));
                foreach (var file in wavFiles)
                {
                    testWordSignals[word].Add(new WavSoundSignalReader(file.FullName));
                }
            }

            var catalogSignals = new List<ISoundSignalReader>();
            catalogSignals.AddRange(learningWordSignals.SelectMany(item => item.Value));

            var codeBook = CodeBookFactory.FromWaves(catalogSignals, EngineParameters.Default);

            var recognitionEngine = new DetectionEngine(codeBook);
            var result = recognitionEngine.Train(learningWordSignals);

            foreach (var word in testWordSignals)
            {
                foreach (var signal in word.Value)
                {
                    string name;
                    var value = recognitionEngine.Recognize(signal, out name);
                    Assert.AreEqual(word.Key, name);

                }
            }
        }
        /// <summary>
        /// Process the content of Claim files and change to structure we want for Result file
        /// </summary>
        /// <param name="rows">content of claim file</param>
        /// <returns></returns>
        public ProcessClaimFileResult Process(Dictionary<string, Dictionary<int, List<BaseClaimRowMetaData>>> rows)
        {
            if (!rows.Any())
            {
                //We can throw Exception here too, depend on our policies
                return new ProcessClaimFileResult{Exception = new ProcessFileRowNotFoundException() };
            }

            var originYears = rows.SelectMany(r => r.Value.Select(v => v.Key)).Distinct().OrderBy(o => o).ToArray();
            _earliestOriginYear = originYears.First();
            _lastDevelopmentYear = originYears.Last();
            _numberOfDevelopment = _lastDevelopmentYear - _earliestOriginYear + 1;

            var accumulatedTriangle = CalculateAccumulatedTriangle(rows);

            return new ProcessClaimFileResult { EarliestOriginYear = _earliestOriginYear, NumberOfDevelopment = _numberOfDevelopment, AccumulatedTriangle = accumulatedTriangle };
        }
Пример #18
0
 private GameResult GetResults(TagInfo tag, PlayersRepo playersRepo, Dictionary<string, PlayerAnswers> playerAnswers)
 {
     IDictionary<string, int> wordStats = playerAnswers.SelectMany(ans => ans.Value.Answers).CountStatistics(word => word);
     return
         new GameResult
             {
                 Results = playerAnswers.Keys.Select(
                     k => new PlayerResult
                          	{
                          		Player = playersRepo.Find(k),
                                 WordsScores =
                          			playerAnswers[k].Answers.Select(ans => Tuple.Create(ans, wordStats[ans])).ToArray(),
                                 Score = playerAnswers[k].Answers.Sum(ans => wordStats[ans])
                          	}
                     ).OrderByDescending(p => p.Score).ToArray(),
                 Tag = tag,
                 WordsScores =
                     wordStats.OrderByDescending(kv => kv.Value).Select(kv => Tuple.Create(kv.Key, kv.Value)).ToArray()
             };
 }
Пример #19
0
        protected IEnumerable<BsaFolder> BuildBsaLayout(Dictionary<string, IList<FileRecord>> folderDict, IList<string> fileNames)
        {
            var pathedFiles = folderDict
                .SelectMany(kvp =>
                    kvp.Value.Select(record => new { path = kvp.Key, record }))
                .Zip(fileNames, (a, fn) => new { a.path, fn, a.record });

            var fileLookup = pathedFiles.ToLookup(a => a.path, a => new { a.fn, a.record });
            return
                from g in fileLookup
                let bsaFiles =
                    g.Select(a =>
                        new BsaFile(
                            g.Key,
                            a.fn,
                            Settings,
                            a.record,
                            (off, len) => _mmf.ToReader(a.record.offset + off, len)))
                select new BsaFolder(g.Key, bsaFiles);
        }
Пример #20
0
        private static void Main()
        {
            var configsList = new List<string>
            {
                "Name: Link, Level: 1, Hp: 20",
                "Name: Zelda, Level: 1, Hp: 20 ",
                "Name: Zelda, Hp: 30",
                "Name: Mario, Hp: 30"
            };
            var gamesDic = new Dictionary<string, Dictionary<string,string>>();

            foreach (var configs in configsList)
            {
                UpdateDictionary(configs, gamesDic);
            }

            foreach (var kvp in gamesDic.SelectMany(games => games.Value))
            {
                Console.WriteLine($"{kvp.Key}:{kvp.Value}");
            }

              Console.ReadKey();
        }
        public void EntityDiff_GetByRelationships()
        {
            // Arrange
            var dbEntities = new HashSet <Dummy>(AllEntities.Select(e => new Dummy {
                Id = e.Id
            }).ToList());
            DiffableEntityHashSet <Dummy> diffs = new DiffableEntityHashSet <Dummy>(AllEntities, dbEntities, Relationships, null);

            // Act
            Dictionary <RelationshipAttribute, HashSet <Dummy> > toOnes           = diffs.GetByRelationship <ToOne>();
            Dictionary <RelationshipAttribute, HashSet <Dummy> > toManies         = diffs.GetByRelationship <ToMany>();
            Dictionary <RelationshipAttribute, HashSet <Dummy> > notTargeted      = diffs.GetByRelationship <NotTargeted>();
            Dictionary <RelationshipAttribute, HashSet <Dummy> > allRelationships = diffs.AffectedRelationships;

            // Assert
            AssertRelationshipDictionaryGetters(allRelationships, toOnes, toManies, notTargeted);
            var allEntitiesWithAffectedRelationships = allRelationships.SelectMany(kvp => kvp.Value).ToList();

            NoRelationshipsEntities.ToList().ForEach(e =>
            {
                Assert.DoesNotContain(e, allEntitiesWithAffectedRelationships);
            });

            var requestEntitiesFromDiff = diffs;

            requestEntitiesFromDiff.ToList().ForEach(e =>
            {
                Assert.Contains(e, AllEntities);
            });
            var databaseEntitiesFromDiff = diffs.GetDiffs().Select(d => d.DatabaseValue);

            databaseEntitiesFromDiff.ToList().ForEach(e =>
            {
                Assert.Contains(e, dbEntities);
            });
        }
Пример #22
0
        /// <summary>
        /// Loads all the members from YAML metadata files, and group them by parent type.
        /// </summary>
        private static ILookup <string, Member> LoadMembersByType(string metadataDir)
        {
            var dictionary = new Dictionary <string, List <Member> >();

            // Urgh - there must be a nicer way of doing this.
            foreach (var file in Directory.GetFiles(metadataDir, "Google*.yml"))
            {
                using (var input = File.OpenText(file))
                {
                    var model = new Deserializer(namingConvention: new CamelCaseNamingConvention(), ignoreUnmatched: true).Deserialize <CodeModel>(input);
                    // Assume we only want classes and structs at the moment...
                    var type = model.Items.FirstOrDefault(x => x.Type == "Class" || x.Type == "Struct");
                    if (type == null)
                    {
                        continue;
                    }
                    var members = model.Items.Where(x => x.Parent == type.Uid).ToList();
                    dictionary[type.Uid] = members;
                }
            }
            return(dictionary
                   .SelectMany(pair => pair.Value.Select(m => new { pair.Key, Value = m }))
                   .ToLookup(pair => pair.Key, pair => pair.Value));
        }
Пример #23
0
        public SaveResult SaveChanges(JObject saveBundle)
        {
            var jsonSerializer = CreateJsonSerializer();

            var dynSaveBundle  = (dynamic)saveBundle;
            var entitiesArray  = (JArray)dynSaveBundle.entities;
            var dynSaveOptions = dynSaveBundle.saveOptions;

            SaveOptions = (SaveOptions)jsonSerializer.Deserialize(new JTokenReader(dynSaveOptions), typeof(SaveOptions));

            // SaveOptions = ExtractSaveOptions(saveBundle);
            EntitiesWithAutoGeneratedKeys = new List <EntityInfo>();

            var saveMap  = new Dictionary <Type, List <EntityInfo> >();
            var jObjects = entitiesArray.Select(jt => (dynamic)jt).ToList();
            var groups   = jObjects.GroupBy(jo => (String)jo.entityAspect.entityTypeName).ToList();

            groups.ForEach(g => {
                var entityType  = LookupEntityType(g.Key);
                var entityInfos = g.Select(jo => (EntityInfo)CreateEntityInfoFromJson(jo, entityType, jsonSerializer))
                                  .Where(BeforeSaveEntity)
                                  .ToList();
                EntitiesWithAutoGeneratedKeys.AddRange(entityInfos.Where(ei => ei.AutoGeneratedKey != null));
                saveMap.Add(entityType, entityInfos);
            });
            saveMap = BeforeSaveEntities(saveMap);

            var keyMappings = SaveChangesCore(saveMap);

            var entities = saveMap.SelectMany(kvp => kvp.Value.Select(entityInfo => entityInfo.Entity)).ToList();

            return(new SaveResult()
            {
                Entities = entities, KeyMappings = keyMappings
            });
        }
Пример #24
0
        public static void CreatePermutations(int maxDim = 10)
        {
            AllPermutations.Clear();
            maxDim = Math.Min(10, maxDim); // Maximum dimension is 10, and 10!=3,628,800 for complexity

            var permutations = new Dictionary <int, List <List <int> > >();

            permutations[1] = new List <List <int> >()
            {
                new List <int>()
                {
                    0
                }
            };
            for (int k = 1; k < maxDim; ++k)
            {
                permutations[k + 1] = AddDimension(permutations[k]);
            }

            AllPermutations = permutations.SelectMany(e => e.Value)
                              .Select(l => new Permutation(l))
                              .GroupBy(e => e.Dim)
                              .ToDictionary(a => a.Key, b => b.ToList());
        }
Пример #25
0
        private void OnMonitorNotification(MonitoredItem monitoreditem, MonitoredItemNotificationEventArgs e)
        {
            VariableNode varNode = (VariableNode)monitoreditem.Subscription.Session.ReadNode(monitoreditem.StartNodeId);

            foreach (var value in monitoreditem.DequeueValues())
            {
                Console.WriteLine("Got a value");
                var     typeManager = new DataTypeManager(monitoreditem.Subscription.Session);
                UaValue opcvalue    = typeManager.GetUaValue(varNode, value, false);

                dynamic monitorInfoPair;

                lock (_monitorPublishInfo)
                {
                    monitorInfoPair = _monitorPublishInfo
                                      .SelectMany(pair => pair.Value, (parent, child) => new { ServerUrl = parent.Key, Info = child })
                                      .First(couple => couple.Info.Subscription == monitoreditem.Subscription);
                }

                var message = $"[TOPIC: /*{monitorInfoPair.Info.Topic}]*/  \t ({monitoreditem.DisplayName}):{opcvalue.Value}";
                monitorInfoPair.Info.Forward(message);
                Console.WriteLine(message);
            }
        }
Пример #26
0
        protected override void OnClosed(EventArgs e)
        {
            if (Trader != null)
            {
                if (_initialized)
                {
                    Trader.MarketDepthsChanged -= TraderOnMarketDepthsChanged;
                }

                if (_scannerId != null)
                {
                    Trader.UnSubscribeScanner(_scannerId.Value);
                    _scannerId = null;
                }

                _reportSecurities.SelectMany(p => p.Value).ForEach(Trader.UnSubscribeFundamentalReport);
                _optionSecurities.ForEach(p => Trader.UnSubscribeOptionCalc(p.Value));

                _reportSecurities.Clear();
                _optionSecurities.Clear();
            }

            base.OnClosed(e);
        }
Пример #27
0
        private void Publish(Dictionary <Type, List <EntityInfo> > saveMap)
        {
            if (EventPublisher == null)
            {
                return;
            }
            foreach (var entity in saveMap.SelectMany(t => saveMap[t.Key]))
            {
                switch (entity.EntityState)
                {
                case EntityState.Added:
                    EventPublisher?.Publish(new EntityAdded(entity));
                    break;

                case EntityState.Deleted:
                    EventPublisher?.Publish(new EntityDeleted(entity));
                    break;

                case EntityState.Modified:
                    EventPublisher?.Publish(new EntityUpdated(entity));
                    break;
                }
            }
        }
Пример #28
0
        private MarginTradingAccount[] GetClientAccounts(string clientId)
        {
            _lockSlim.EnterReadLock();
            try
            {
                if (clientId != null)
                {
                    if (_accounts.ContainsKey(clientId))
                    {
                        return(_accounts[clientId]);
                    }

                    return(Array.Empty <MarginTradingAccount>());
                }
                else
                {
                    return(_accounts.SelectMany(a => a.Value).ToArray());
                }
            }
            finally
            {
                _lockSlim.ExitReadLock();
            }
        }
Пример #29
0
        public async Task <GroupAssignment> Assign(ClusterManager metadata, GroupSubscription groupSubscription)
        {
            Dictionary <string, Subscription> subscriptions = groupSubscription.groupSubscription();
            var allSubscribedTopics = new HashSet <string>();

            foreach (var topic in subscriptions.SelectMany(e => e.Value.Topics))
            {
                allSubscribedTopics.Add(topic);
            }

            var partitionsPerTopic = new Dictionary <string, int>();

            foreach (string topic in allSubscribedTopics)
            {
                int numPartitions = (await metadata.GetTopic(topic)).Partitions.Count;
                if (numPartitions > 0)
                {
                    partitionsPerTopic.Add(topic, numPartitions);
                }
                else
                {
                    log.debug("Skipping assignment for topic {} since no metadata is available", topic);
                }
            }

            Dictionary <string, List <TopicPartition> > rawAssignments = Assign(partitionsPerTopic, subscriptions);

            // this class maintains no user data, so just wrap the results
            var assignments = new Dictionary <string, Assignment>();

            foreach (var assignmentEntry in rawAssignments)
            {
                assignments.Add(assignmentEntry.Key, new Assignment(0, assignmentEntry.Value, null));
            }
            return(new GroupAssignment(assignments));
        }
Пример #30
0
        internal async static void ClearIdleConnections()
        {
            clearConenctions = true;
            while (clearConenctions)
            {
                await connectionAccessLock.WaitAsync();

                try
                {
                    var cutOff = DateTime.Now.AddMinutes(-1 * ProxyServer.ConnectionCacheTimeOutMinutes);

                    connectionCache
                    .SelectMany(x => x.Value)
                    .Where(x => x.LastAccess < cutOff)
                    .ToList()
                    .ForEach(x => x.TcpClient.Close());

                    connectionCache.ToList().ForEach(x => x.Value.RemoveAll(y => y.LastAccess < cutOff));
                }
                finally { connectionAccessLock.Release(); }

                await Task.Delay(1000 * 60 * 3).ConfigureAwait(false);
            }
        }
Пример #31
0
        public override void Render()
        {
            if (!Settings.Enable || !GameController.InGame || !Settings.ShowInTown && GameController.Area.CurrentArea.IsTown)
            {
                return;
            }

            RectangleF windowRectangle = GameController.Window.GetWindowRectangle();
            var        windowSize      = new Size2F(windowRectangle.Width / 2560, windowRectangle.Height / 1600);

            Camera camera = GameController.Game.IngameState.Camera;
            Func <HealthBar, bool> showHealthBar = x => x.IsShow(Settings.ShowEnemies);

            Parallel.ForEach(healthBars, x => x.Value.RemoveAll(hp => !(hp.Entity.IsValid && hp.Entity.IsAlive)));
            foreach (HealthBar healthBar in healthBars.SelectMany(x => x.Value).AsParallel().AsOrdered().Where(showHealthBar))
            {
                Vector3 worldCoords     = healthBar.Entity.Pos;
                Vector2 mobScreenCoords = camera.WorldToScreen(worldCoords.Translate(0, 0, -170), healthBar.Entity);
                if (mobScreenCoords != new Vector2())
                {
                    DrawHealthBar(healthBar, windowSize, mobScreenCoords);
                }
            }
        }
        private static void AssertFieldsAreSupported(
            IEnumerable <string> aggregationFields,
            Dictionary <string, AggregateQuery> aggregateQueries)
        {
            // First, get a distinct list of all the requested columns.
            string[] requestedFields = aggregateQueries
                                       .SelectMany(x => x.Value.DataFilters)
                                       .Select(x => x.Field)
                                       .Distinct()
                                       .ToArray();

            // Then, check if any columns been requested that are not
            // available.
            string[] unsupportedFields = requestedFields
                                         .Where(x => !aggregationFields.Any(y => y == x))
                                         .ToArray();

            if (unsupportedFields.Length > 0)
            {
                throw new UnsupportedAggregateColumnRequestException(
                          unsupportedFields,
                          aggregationFields);
            }
        }
        public bool IsGraphBipartite()
        {
            BFS(1);
            if (Nums.Count(element => element == 0) != 0)
            {
                return(false);
            }
            var even = new Dictionary <int, List <int> >();
            var odd  = new Dictionary <int, List <int> >();

            for (var i = 1; i < Nums.Length; i++)
            {
                TryAddValue(Nums[i] % 2 == 0 ? even : odd, Nums[i], i);
            }


            if (HasAdjacentNodesOfSameLevel(even) || HasAdjacentNodesOfSameLevel(odd))
            {
                return(false);
            }
            PartEven = even.SelectMany(x => x.Value).ToList();
            PartOdd  = odd.SelectMany(x => x.Value).ToList();
            return(true);
        }
Пример #34
0
        private async Task <List <ModDependencyInfo> > GetDependencies(CancellationToken cancellationToken)
        {
            ICollection <Mod> selectedMods = new List <Mod>(Mods.Where(mod => mod.IsSelected));

            if (selectedMods.Count == 0)
            {
                selectedMods = Mods;
            }

            var dict  = new Dictionary <string, Dictionary <Version, ModDependencyInfo> >();
            var infos = new Dictionary <string, ExtendedModInfo>();

            foreach (var mod in selectedMods)
            {
                if (cancellationToken.IsCancellationRequested)
                {
                    break;
                }

                await AddDependencies(dict, infos, mod, cancellationToken);
            }

            return(new List <ModDependencyInfo>(dict.SelectMany(kvp => kvp.Value.Values)));
        }
Пример #35
0
        private static Solution AddProjectReferences(
            Solution solution,
            string projectName,
            IEnumerable <string> projectReferences
            )
        {
            var referencesByTargetProject = new Dictionary <string, List <ProjectReference> >();

            foreach (var targetProject in projectReferences)
            {
                var references = referencesByTargetProject.GetOrAdd(
                    targetProject,
                    _ => new List <ProjectReference>()
                    );
                if (references.Count == 0)
                {
                    references.Add(
                        new ProjectReference(solution.GetProjectsByName(targetProject).Single().Id)
                        );
                }
                else
                {
                    references.Add(
                        new ProjectReference(
                            solution.GetProjectsByName(targetProject).Single().Id,
                            ImmutableArray.Create($"alias{references.Count}")
                            )
                        );
                }
            }

            return(solution.AddProjectReferences(
                       solution.GetProjectsByName(projectName).Single().Id,
                       referencesByTargetProject.SelectMany(pair => pair.Value)
                       ));
        }
Пример #36
0
        private async Task GenerateSelectionAsync()
        {
            ToggleUI(false);

            using (new Wait()) {
                Dictionary <Template, List <TemplateOutputDefinitionFilenameResult> > templateOutputs = (from li in outputsListView.CheckedItems.Cast <ListViewItem>()
                                                                                                         group(TemplateOutputDefinitionFilenameResult) li.Tag by(Template) li.Group.Tag into g
                                                                                                         select new {
                    Template = g.Key,
                    Outputs = g.ToList()
                }).ToDictionary(o => o.Template, o => o.Outputs);

                if (templateOutputs.IsNullOrEmpty())
                {
                    MessageBox.Show("You must select one or more template you wish to generate.", "Generate", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    ToggleUI(true);
                    return;
                }

                outputsListView.CheckedItems.Cast <ListViewItem>().ForEach(o => {
                    o.SubItems[statusColumn.Index].Text  = null;
                    o.SubItems[messageColumn.Index].Text = null;
                });

                progressBar.Value   = 0;
                progressBar.Maximum = templateOutputs.SelectMany(o => o.Value).Count();
                progressBar.Visible = true;

                this.Generator = new Generator(ProjectContext.Project, templateOutputs);
                this.Generator.GenerationStatus         += new Generator.GenerationStatusEventHandler(Generator_GenerationStatus);
                this.Generator.TemplateGenerationStatus += new Generator.TemplateGenerationStatusEventHandler(Generator_TemplateGenerationStatus);
                this.Generator.ItemGenerationStatus     += new Generator.ItemGenerationStatusEventHandler(Generator_ItemGenerationStatus);

                await this.Generator.GenerateAsync();
            }
        }
Пример #37
0
        private void SelectAddinForm_Load(object sender, EventArgs e)
        {
            this.Translate();

            lvAddins.Clear();
            lvAddins.Groups.Clear();

            ilLarge.Images.Clear();
            ilSmall.Images.Clear();

            var addins = new Dictionary <string, IAddin>[] { Host.Actions, Host.Effects };

            var addinList = addins.SelectMany(dict => dict)
                            .ToDictionary(pair => pair.Key, pair => pair.Value);

            AddinItems.Clear();
            foreach (var addin in addinList)
            {
                if (Host.CurrentFilter is IAddin && string.Equals(Host.CurrentFilter.Name, addin.Value.Name, StringComparison.CurrentCultureIgnoreCase))
                {
                    continue;
                }

                ilLarge.Images.Add(addin.Value.LargeIcon);
                ilSmall.Images.Add(addin.Value.SmallIcon);

                var lvi = new ListViewItem();
                lvi.Text       = addin.Value.DisplayName;
                lvi.Tag        = addin.Value;
                lvi.ImageIndex = ilLarge.Images.Count - 1;
                AddinItems.Add(lvi);
            }
            lvAddins.VirtualListSize = AddinItems.Count;

            btnGroupType.PerformClick();
        }
Пример #38
0
        /// <summary>
        /// Add new record to database
        /// </summary>
        /// <param name="backtraceData">Diagnostic data that should be stored in database</param>
        /// <returns>New instance of DatabaseRecordy</returns>
        public BacktraceDatabaseRecord Add(BacktraceData backtraceData)
        {
            if (backtraceData == null)
            {
                throw new NullReferenceException("backtraceData");
            }

            string hash = GetHash(backtraceData);

            if (!string.IsNullOrEmpty(hash))
            {
                var existRecord = BatchRetry.SelectMany(n => n.Value)
                                  .FirstOrDefault(n => n.Hash == hash);

                if (existRecord != null)
                {
                    existRecord.Locked = true;
                    existRecord.Increment();
                    TotalRecords++;
                    return(existRecord);
                }
            }
            //add built-in attachments
            var attachments = _attachmentManager.GetReportAttachments(backtraceData);

            foreach (var attachment in attachments)
            {
                if (!string.IsNullOrEmpty(attachment))
                {
                    backtraceData.Report.AttachmentPaths.Add(attachment);
                    backtraceData.Attachments.Add(attachment);
                }
            }

            var record = ConvertToRecord(backtraceData, hash);

            //add record to database context
            return(Add(record));
        }
        /// <summary>
        /// Add new record to database
        /// </summary>
        /// <param name="backtraceData">Diagnostic data that should be stored in database</param>
        /// <returns>New instance of DatabaseRecordy</returns>
        public virtual BacktraceDatabaseRecord Add(BacktraceData backtraceData, MiniDumpType miniDumpType = MiniDumpType.None)
        {
            if (backtraceData == null)
            {
                throw new NullReferenceException(nameof(backtraceData));
            }
            string hash = GetHash(backtraceData);

            if (!string.IsNullOrEmpty(hash))
            {
                var existRecord = BatchRetry.SelectMany(n => n.Value)
                                  .FirstOrDefault(n => n.Hash == hash);

                if (existRecord != null)
                {
                    existRecord.Locked = true;
                    existRecord.Increment();
                    TotalRecords++;
                    return(existRecord);
                }
            }

            string minidumpPath = GenerateMiniDump(backtraceData.Report, miniDumpType);

            backtraceData.Report.SetMinidumpPath(minidumpPath);
            backtraceData.Attachments.Add(minidumpPath);

            //create new record and save it on hard drive
            var record = new BacktraceDatabaseRecord(backtraceData, _path)
            {
                Hash = hash
            };

            record.Save();
            //add record to database context
            return(Add(record));
        }
        /// <summary>
        /// Add new record to database
        /// </summary>
        /// <param name="backtraceData">Diagnostic data that should be stored in database</param>
        /// <returns>New instance of DatabaseRecordy</returns>
        public BacktraceDatabaseRecord Add(BacktraceData backtraceData, MiniDumpType miniDumpType = MiniDumpType.None)
        {
            if (backtraceData == null)
            {
                throw new NullReferenceException("backtraceData");
            }

            string hash = GetHash(backtraceData);

            if (!string.IsNullOrEmpty(hash))
            {
                var existRecord = BatchRetry.SelectMany(n => n.Value)
                                  .FirstOrDefault(n => n.Hash == hash);

                if (existRecord != null)
                {
                    existRecord.Locked = true;
                    existRecord.Increment();
                    TotalRecords++;
                    return(existRecord);
                }
            }

            string minidumpPath = GenerateMiniDump(backtraceData.Report, miniDumpType);

            backtraceData.Report.SetMinidumpPath(minidumpPath);
            if (!string.IsNullOrEmpty(minidumpPath))
            {
                backtraceData.Attachments.Add(minidumpPath);
            }

            var record = ConvertToRecord(backtraceData, hash);

            //add record to database context
            return(Add(record));
        }
        private void Train()
        {
            Dictionary<string, IList<ISoundSignalReader>> learningWordSignals = new Dictionary<string, IList<ISoundSignalReader>>();

            List<string> learningDirectories = new List<string>();
            foreach (var folder in ConfigurationSettings.LearningsFolders)
            {
                learningDirectories.AddRange(Directory.GetDirectories(folder));
            }

            foreach (var directory in learningDirectories.Where(item => !item.Contains("catalog")))
            {
                var word = new DirectoryInfo(directory).Name;
                learningWordSignals.Add(word, new List<ISoundSignalReader>());
                var wavFiles = Directory.GetFiles(directory).Select(item => new FileInfo(item)).Where(fItem => fItem.Extension.Contains("wav"));
                foreach (var file in wavFiles)
                {
                    learningWordSignals[word].Add(new WavSoundSignalReader(file.FullName));
                }
            }

            var catalogSignals = new List<ISoundSignalReader>();
            catalogSignals.AddRange(learningWordSignals.SelectMany(item => item.Value));

            var codeBook = CodeBookFactory.FromWaves(catalogSignals, EngineParameters.Default);

            var recognitionEngine = new DetectionEngine(codeBook);
            var result = recognitionEngine.Train(learningWordSignals);
            //result.Hmm.Save("HMModels.dat");
            _models = result.Models;
            _codebook = result.Catalog;

            result.Save("SavedData", "model");
        }
Пример #42
0
 public static Dictionary <string, int> Transform(Dictionary <int, string[]> old)
 => old.SelectMany(kvp => kvp.Value, (kvp, c) => (c.ToLower(), kvp.Key)).ToDictionary(p => p.Item1, p => p.Item2);
Пример #43
0
 public void PostTraceReconciliation(Dictionary<Guid, List<ISerializable>> orphanedSerializables)
 {
     Assert.AreEqual(orphanedSerializables.SelectMany(kvp=>kvp.Value).Count(), ExpectedOrphanCount);
 }
        private static async Task<HashSet<SourceDependencyInfo>> GatherPackageDependencyInfo(ResolutionContext context,
            IEnumerable<string> primaryTargetIds,
            IEnumerable<string> allTargetIds,
            IEnumerable<PackageIdentity> primaryTargets,
            IEnumerable<PackageIdentity> allTargets,
            NuGetFramework targetFramework,
            IEnumerable<SourceRepository> primarySources,
            IEnumerable<SourceRepository> allSources,
            CancellationToken token)
        {
            // get a distinct set of packages from all repos
            var combinedResults = new HashSet<SourceDependencyInfo>(PackageIdentity.Comparer);

            // get the dependency info resources for each repo
            // primary and all may share the same resources
            var depResources = new Dictionary<SourceRepository, Task<DepedencyInfoResource>>();
            foreach (var source in allSources.Concat(primarySources))
            {
                if (!depResources.ContainsKey(source))
                {
                    depResources.Add(source, source.GetResourceAsync<DepedencyInfoResource>(token));
                }
            }

            // a resource may be null, if it is exclude this source from the gather
            var primaryDependencyResources = new List<Tuple<SourceRepository, DepedencyInfoResource>>();

            foreach (var source in primarySources)
            {
                var resource = await depResources[source];

                if (source != null)
                {
                    primaryDependencyResources.Add(new Tuple<SourceRepository, DepedencyInfoResource>(source, resource));
                }
            }

            var allDependencyResources = new List<Tuple<SourceRepository, DepedencyInfoResource>>();

            foreach (var source in allSources)
            {
                var resource = await depResources[source];

                if (source != null)
                {
                    allDependencyResources.Add(new Tuple<SourceRepository, DepedencyInfoResource>(source, resource));
                }
            }

            // track which sources have been searched for each package id
            Dictionary<SourceRepository, HashSet<string>> sourceToPackageIdsChecked = new Dictionary<SourceRepository, HashSet<string>>();

            UpdateSourceToPackageIdsChecked(sourceToPackageIdsChecked, primaryDependencyResources);
            UpdateSourceToPackageIdsChecked(sourceToPackageIdsChecked, allDependencyResources);
            
            if (primaryTargetIds != null && allTargetIds != null)
            {
                // First, check for primary targets alone against primary source repositories alone
                var primaryIdsAsAllDiscoveredIds = new HashSet<string>(primaryTargetIds);
                await ProcessMissingPackageIds(combinedResults, primaryIdsAsAllDiscoveredIds, sourceToPackageIdsChecked,
                    primaryDependencyResources, targetFramework, context, false, token);

                string missingPrimaryPackageId = primaryTargetIds.Where(p => !combinedResults.Any(c => c.Id.Equals(p, StringComparison.OrdinalIgnoreCase))).FirstOrDefault();
                if (!String.IsNullOrEmpty(missingPrimaryPackageId))
                {
                    throw new InvalidOperationException(String.Format(Strings.PackageNotFound, missingPrimaryPackageId));
                }

                var allIdsAsAllDiscoveredIds = new HashSet<string>(allTargetIds);
                await ProcessMissingPackageIds(combinedResults, allIdsAsAllDiscoveredIds, sourceToPackageIdsChecked,
                    primaryDependencyResources, targetFramework, context, false, token);
            }
            else
            {
                Debug.Assert(primaryTargets != null && allTargets != null);

                // First, check for primary targets alone against primary source repositories alone
                await ProcessMissingPackageIdentities(combinedResults, primaryTargets, sourceToPackageIdsChecked,
                    primaryDependencyResources, targetFramework, context, false, token);

                PackageIdentity missingPrimaryPackageIdentity = primaryTargets.Where(p => !combinedResults.Any(c => c.Equals(p))).FirstOrDefault();
                if (missingPrimaryPackageIdentity != null)
                {
                    throw new InvalidOperationException(String.Format(Strings.PackageNotFound, missingPrimaryPackageIdentity));
                }

                await ProcessMissingPackageIdentities(combinedResults, allTargets, sourceToPackageIdsChecked,
                    allDependencyResources, targetFramework, context, true, token);
            }

            // loop until we finish a full iteration with no new ids discovered
            bool complete = false;

            while (!complete)
            {
                HashSet<string> allDiscoveredIds = new HashSet<string>(sourceToPackageIdsChecked.SelectMany(e => e.Value), StringComparer.OrdinalIgnoreCase);
                complete = await ProcessMissingPackageIds(combinedResults, allDiscoveredIds, sourceToPackageIdsChecked, allDependencyResources, targetFramework, context, true, token);
            }

            return combinedResults;
        }
Пример #45
0
        public bool IsPlanar(Graph graphArgument)
        {
            var enableCudafy = Settings.EnableCudafy;

            Settings.EnableCudafy = true;

            if (WorkerLog != null)
            {
                WorkerLog("Начало гамма-алгоритма");
            }
            var graph = new Graph(graphArgument);

            Debug.Assert(
                graph.Children.All(pair => pair.Value
                                   .All(value => graph.Children.ContainsKey(value) &&
                                        graph.Children[value].Contains(pair.Key)))
                );

            if (WorkerBegin != null)
            {
                WorkerBegin();
            }
            // Шаг первый - удаляем все листья и узлы степени 2
            if (WorkerLog != null)
            {
                WorkerLog("Удаляем все листья и узлы степени 2");
            }

            // листья представляют собой дерево и нарисовать его плоскую укладку тривиально.
            graph.RemoveAllTrees();

            // Замечание. Если на ребра планарного графа нанести произвольное число вершин степени 2,
            // то он останется планарным; равным образом, если на ребра непланарного графа
            // нанести вершины степени 2, то он планарным не станет.
            graph.RemoveIntermedians();

            // Шаг второй - граф нужно укладывать отдельно по компонентам связности.
            if (WorkerLog != null)
            {
                WorkerLog("Находим ВСЕ пути в графе длины не более размера графа + 1");
            }
            Dictionary <int, PathDictionary> cachedAllGraphPaths = graph.GetAllGraphPaths();
            var queue = new StackListQueue <Context>
            {
                graph.GetAllSubGraphs().Select(subgraph =>
                                               new Context
                {
                    SubGraphQueue =
                        new StackListQueue <Graph>
                    {
                        subgraph
                    },
                    CachedSubGraphPathsQueue =
                        new StackListQueue <Dictionary <int, PathDictionary> >
                    {
                        Graph.GetSubgraphPaths(subgraph.Vertices, cachedAllGraphPaths)
                    },
                })
            };

            Debug.WriteLine("start ");

            foreach (Context context in queue)
            {
                while (context.SubGraphQueue.Any())
                {
                    Graph subGraph = context.SubGraphQueue.Dequeue();
                    if (WorkerLog != null)
                    {
                        WorkerLog("Проверка связанной компоненты " + subGraph);
                    }
                    Dictionary <int, PathDictionary> cachedSubGraphPaths =
                        context.CachedSubGraphPathsQueue.Dequeue();

                    // На вход подаются графы, обладающие следующими свойствами:
                    // граф связный;
                    // граф имеет хотя бы один цикл;
                    // граф не имеет мостиков, т. е. ребер, после удаления которых
                    // граф распадается на две компонеты связности.

                    if (WorkerLog != null)
                    {
                        WorkerLog(
                            "Находим мосты после удаления которых граф распадается на несколько компонет связности");
                    }

                    var vertices = new StackListQueue <Vertex>(subGraph.Vertices);
                    var bridges  = new StackListQueue <Vertex>();
                    for (int i = 0; i < vertices.Count; i++)
                    {
                        Vertex dequeue = vertices.Dequeue();
                        IEnumerable <Graph> subsubgraphs = subGraph.GetSubgraph(vertices).GetAllSubGraphs();
                        if (subsubgraphs.Count() > 1)
                        {
                            bridges.Add(dequeue);
                        }
                        vertices.Enqueue(dequeue);
                    }

                    Debug.Assert(bridges.Count != vertices.Count);

                    if (bridges.Any())
                    {
                        // Если в графе есть мосты, то их нужно разрезать, провести отдельно плоскую укладку
                        // каждой компоненты связности, а затем соединить их мостами.
                        // Здесь может возникнуть трудность: в процессе укладки концевые вершины моста могут
                        // оказаться внутри плоского графа. Нарисуем одну компоненту связности,
                        // и будем присоединять к ней другие последовательно.
                        // Каждую новую компоненту связности будем рисовать в той грани, в которой лежит
                        // концевая вершина соответствующего моста. Так как граф связности мостами компонент
                        // связности является деревом, мы сумеем получить плоскую укладку.
                        if (WorkerLog != null)
                        {
                            WorkerLog(
                                "В графе есть мосты, их нужно разрезать, провести отдельно плоскую укладку, а затем соединить их мостами.");
                        }
                        if (WorkerLog != null)
                        {
                            WorkerLog("Мосты: " + string.Join(",", bridges));
                        }

                        IEnumerable <Vertex> exceptBridges = vertices.Except(bridges);
                        IEnumerable <Graph>  subsubgraphs  = subGraph.GetSubgraph(exceptBridges).GetAllSubGraphs();
                        Debug.WriteLine("subsubgraphs = " + subsubgraphs.Count());
                        context.SubGraphQueue.Enqueue(
                            subsubgraphs.Select(subgraph => subGraph.GetSubgraph(subgraph.Vertices.Union(bridges))));
                        context.CachedSubGraphPathsQueue.Enqueue(
                            subsubgraphs.Select(
                                subgraph =>
                                Graph.GetSubgraphPaths(subgraph.Vertices.Union(bridges), cachedSubGraphPaths)));

                        continue;
                    }

                    if (WorkerLog != null)
                    {
                        WorkerLog("Находим ЛЮБОЙ МАКСИМАЛЬНОЙ ДЛИНЫ простой цикл в графе");
                    }
                    Circle circle = null;
                    for (int i = cachedSubGraphPaths.Keys.Max(); i > 3; i--)
                    {
                        foreach (var pair in cachedSubGraphPaths.Where(pair => pair.Key == i))
                        {
                            foreach (
                                var key in
                                subGraph.Vertices.Select(vertex => new KeyValuePair <Vertex, Vertex>(vertex, vertex))
                                )
                            {
                                if (pair.Value.ContainsKey(key) && pair.Value[key].Any())
                                {
                                    foreach (Path path in pair.Value[key])
                                    {
                                        circle = new Circle(path.GetRange(0, path.Count - 1));
                                        if (Circle.IsSimple(circle))
                                        {
                                            break;
                                        }
                                        circle = null;
                                    }
                                    if (circle != null)
                                    {
                                        break;
                                    }
                                }
                                if (circle != null)
                                {
                                    break;
                                }
                            }
                            if (circle != null)
                            {
                                break;
                            }
                        }
                        if (circle != null)
                        {
                            break;
                        }
                    }

                    if (circle == null && !context.Edges.Any())
                    {
                        // граф — дерево и нарисовать его плоскую укладку тривиально.
                        // Поскольку мы ещё не начинали рисовать, то значит всё проверено
                        continue;
                    }

                    // Инициализация алгоритма производится так: выбираем любой простой цикл;
                    // и получаем две грани: Γ1 — внешнюю и Γ2 — внутреннюю

                    if (circle != null && !context.Edges.Any())
                    {
                        context.Edges.Add(new Edge(circle));
                    }

                    if (circle != null)
                    {
                        context.Edges.Add(new Edge(circle));
                        context.Builded.Add(context.Edges.Last());
                    }
                    // Если циклов нет, то надо проверить, что данное дерево
                    // можно вписать в уже построенный граф

                    Debug.WriteLine("SubGraph " + subGraph);
                    Debug.WriteLine("builded " + context.Builded);
                    Debug.WriteLine("edges:" +
                                    string.Join(Environment.NewLine, context.Edges.Select(e => e.ToString())));


                    //// Каждый сегмент S относительно уже построенного графа G′ представляет собой одно из двух:
                    //// ребро, оба конца которого принадлежат G′, но само оно не принадлежит G′;
                    //// связную компоненту графа G – G′, дополненную всеми ребрами графа G,
                    //// один из концов которых принадлежит связной компоненте,
                    //// а второй из графа G′.

                    VertexSortedCollection           buildedVertices = context.Builded.Vertices;
                    Dictionary <int, PathDictionary> fromTo          = Graph.GetFromToPaths(buildedVertices,
                                                                                            buildedVertices,
                                                                                            cachedSubGraphPaths);
                    var paths =
                        new PathCollection(fromTo
                                           .SelectMany(pair => pair.Value)
                                           .SelectMany(pair => pair.Value)
                                           .Where(Path.IsNoVertix)
                                           .Where(Path.IsNoCircle)
                                           );
                    Debug.WriteLine("paths " + paths);

                    //var secondGraph = new Graph(subGraph.Except(context.Builded));

                    //if (secondGraph.Any())
                    //{
                    //    IEnumerable<Graph> collection = secondGraph.GetAllSubGraphs();
                    //    context.SubGraphQueue.Enqueue(collection);
                    //    context.CachedSubGraphPathsQueue.Enqueue(
                    //        collection.Select(subgraph => Graph.GetSubgraphPaths(subgraph.Vertices, cachedSubGraphPaths)));
                    //}



                    paths.ReplaceAll(paths.Distinct());
                    Debug.WriteLine("paths " + paths);
                    paths.RemoveAll(context.Builded.Contains);

                    Debug.WriteLine("paths " + paths);
                    Debug.WriteLine("builded " + context.Builded);
                    Debug.WriteLine("edges:" +
                                    string.Join(Environment.NewLine, context.Edges.Select(e => e.ToString())));

                    while (paths.Any())
                    {
                        paths.RemoveAll(context.Builded.Contains);
                        Debug.WriteLine("paths " + paths);
                        if (!paths.Any())
                        {
                            continue;
                        }
                        if (Settings.EnableCudafy)
                        {
                            try
                            {
                                while (paths.Any(Path.IsLong))
                                {
                                    // Находим для всех путей их перечечения с уже построенным графом
                                    // Разбиваем пути в найденных точках пересечения с уже построенным графом
                                    // Если точек пересечения не найдено, то выходим из цикла

                                    int[,] matrix;
                                    int[] indexes;
                                    lock (CudafySequencies.Semaphore)
                                    {
                                        CudafySequencies.SetSequencies(
                                            paths.Select(
                                                path =>
                                                path.GetRange(1, path.Count - 2)
                                                .Select(vertex => vertex.Id)
                                                .ToArray())
                                            .ToArray(),
                                            context.Builded.Vertices.Select(
                                                vertex => new StackListQueue <int>(vertex.Id).ToArray())
                                            .ToArray()
                                            );
                                        CudafySequencies.Execute("CountIntersections");
                                        // подсчитываем число пересечений
                                        matrix = CudafySequencies.GetMatrix();
                                    }
                                    lock (CudafyMatrix.Semaphore)
                                    {
                                        CudafyMatrix.SetMatrix(matrix);
                                        CudafyMatrix.ExecuteRepeatZeroIndexOfNonZero();
                                        // находим индексы ненулевых элементов в строках
                                        indexes = CudafyMatrix.GetIndexes();
                                    }
                                    Dictionary <int, int> dictionary = indexes.Select(
                                        (value, index) => new KeyValuePair <int, int>(index, value))
                                                                       .Where(pair => pair.Value >= 0)
                                                                       .ToDictionary(pair => pair.Key, pair => pair.Value);
                                    if (!dictionary.Any())
                                    {
                                        break;
                                    }
                                    Debug.Assert(dictionary.All(pair => pair.Key >= 0));
                                    Debug.Assert(dictionary.All(pair => pair.Value >= 0));
                                    Debug.Assert(dictionary.All(pair => pair.Key < paths.Count));
                                    Debug.Assert(dictionary.All(pair => pair.Value < context.Builded.Vertices.Count));
                                    var dictionary2 = new StackListQueue <KeyValuePair <Path, Vertex> >(
                                        dictionary.Select(
                                            pair =>
                                            new KeyValuePair <Path, Vertex>(new Path(paths[pair.Key]),
                                                                            new Vertex(context.Builded.Vertices[pair.Value])))
                                        );
                                    var list = new StackListQueue <int>(dictionary.Select(pair => pair.Key).Distinct());
                                    list.Sort();
                                    Debug.Assert(dictionary2.All(pair => pair.Key.Count > 1));
                                    for (int i = list.Count; i-- > 0;)
                                    {
                                        paths.RemoveAt(list[i]);
                                    }
                                    paths.AddRangeExcept(
                                        new PathCollection(
                                            dictionary2.SelectMany(pair => pair.Key.SplitBy(pair.Value)
                                                                   .Where(Path.IsNoVertix)
                                                                   .Where(Path.IsNoCircle))
                                            .Distinct()));
                                    paths.ReplaceAll(paths.Distinct());
                                    paths.RemoveAll(context.Builded.Contains);
                                }
                            }
                            catch (Exception ex)
                            {
                                if (WorkerLog != null)
                                {
                                    WorkerLog(ex.ToString());
                                }
                                paths.ReplaceAll(
                                    paths.SelectMany(context.Builded.Split)
                                    .Where(Path.IsNoVertix)
                                    .Where(Path.IsNoCircle)
                                    );
                                paths.ReplaceAll(paths.Distinct());
                                paths.RemoveAll(context.Builded.Contains);
                            }
                        }
Пример #46
0
        static SampleSpecsTestCaseData()
        {
            string specAssemblyPath   = TestConstants.SampleSpecsDllPath;
            string sourceCodeFilePath = TestUtils.FirstCharToLower(TestConstants.SampleSpecsSourcePath);

            ByClassMethodExampleName = new Dictionary <string, Dictionary <string, Dictionary <string, TestCase> > >()
            {
                {
                    "SampleSpecs.ParentSpec",
                    new Dictionary <string, Dictionary <string, TestCase> >()
                    {
                        {
                            "method_context_1",
                            new Dictionary <string, TestCase>()
                            {
                                {
                                    "parent example 1A",
                                    new TestCase(
                                        "nspec. ParentSpec. method context 1. parent example 1A.",
                                        Constants.ExecutorUri, specAssemblyPath)
                                    {
                                        DisplayName  = "ParentSpec › method context 1 › parent example 1A.",
                                        CodeFilePath = sourceCodeFilePath,
                                        LineNumber   = 19,
                                    }
                                },
                                {
                                    "parent example 1B",
                                    new TestCase(
                                        "nspec. ParentSpec. method context 1. parent example 1B.",
                                        Constants.ExecutorUri, specAssemblyPath)
                                    {
                                        DisplayName  = "ParentSpec › method context 1 › parent example 1B.",
                                        CodeFilePath = sourceCodeFilePath,
                                        LineNumber   = 21,
                                    }
                                },
                            }
                        },
                        {
                            "method_context_2",
                            new Dictionary <string, TestCase>()
                            {
                                {
                                    "parent example 2A",
                                    new TestCase(
                                        "nspec. ParentSpec. method context 2. parent example 2A.",
                                        Constants.ExecutorUri, specAssemblyPath)
                                    {
                                        DisplayName  = "ParentSpec › method context 2 › parent example 2A.",
                                        CodeFilePath = sourceCodeFilePath,
                                        LineNumber   = 26,
                                    }
                                },
                            }
                        },
                    }
                },
                {
                    "SampleSpecs.ChildSpec",
                    new Dictionary <string, Dictionary <string, TestCase> >()
                    {
                        {
                            "method_context_3",
                            new Dictionary <string, TestCase>()
                            {
                                {
                                    "child example 3A skipped",
                                    new TestCase(
                                        "nspec. ParentSpec. ChildSpec. method context 3. child example 3A skipped.",
                                        Constants.ExecutorUri, specAssemblyPath)
                                    {
                                        DisplayName = "ParentSpec › ChildSpec › method context 3 › child example 3A skipped.",
                                        // no source code info available for pending tests
                                        CodeFilePath = String.Empty,
                                        LineNumber   = 0,
                                    }
                                },
                            }
                        },
                        {
                            "method_context_4",
                            new Dictionary <string, TestCase>()
                            {
                                {
                                    "child example 4A",
                                    new TestCase(
                                        "nspec. ParentSpec. ChildSpec. method context 4. child example 4A.",
                                        Constants.ExecutorUri, specAssemblyPath)
                                    {
                                        DisplayName  = "ParentSpec › ChildSpec › method context 4 › child example 4A.",
                                        CodeFilePath = sourceCodeFilePath,
                                        LineNumber   = 42,
                                    }
                                },
                            }
                        },
                        {
                            "method_context_5. sub context 5-1",
                            new Dictionary <string, TestCase>()
                            {
                                {
                                    "child example 5-1A failing",
                                    new TestCase(
                                        "nspec. ParentSpec. ChildSpec. method context 5. sub context 5-1. child example 5-1A failing.",
                                        Constants.ExecutorUri, specAssemblyPath)
                                    {
                                        DisplayName  = "ParentSpec › ChildSpec › method context 5 › sub context 5-1 › child example 5-1A failing.",
                                        CodeFilePath = sourceCodeFilePath,
                                        LineNumber   = 49,
                                    }
                                },
                                {
                                    "child example 5-1B",
                                    new TestCase(
                                        "nspec. ParentSpec. ChildSpec. method context 5. sub context 5-1. child example 5-1B.",
                                        Constants.ExecutorUri, specAssemblyPath)
                                    {
                                        DisplayName  = "ParentSpec › ChildSpec › method context 5 › sub context 5-1 › child example 5-1B.",
                                        CodeFilePath = sourceCodeFilePath,
                                        LineNumber   = 51,
                                    }
                                },
                            }
                        },
                    }
                },
            };

            All = ByClassMethodExampleName
                  .SelectMany(byClassName => byClassName.Value)
                  .SelectMany(byMethodName => byMethodName.Value)
                  .Select(byExampleName => byExampleName.Value);

            ByTestCaseFullName = All.ToDictionary(tc => tc.FullyQualifiedName, tc => tc);

            // add implicit traits corresponding to class names
            // add explicit traits corresponding to tags

            All.Where(tc => tc.FullyQualifiedName.Contains("ParentSpec"))
            .Do(tc => tc.Traits.Add("ParentSpec", null));

            All.Where(tc => tc.FullyQualifiedName.Contains("method context 1"))
            .Do(tc =>
            {
                tc.Traits.Add("Tag-1A", null);
                tc.Traits.Add("Tag-1B", null);
            });

            All.Where(tc => tc.FullyQualifiedName.Contains("ChildSpec"))
            .Do(tc =>
            {
                tc.Traits.Add("ChildSpec", null);
                tc.Traits.Add("Tag-Child", null);
            });

            All.Where(tc => tc.FullyQualifiedName.Contains("method context 3"))
            .Do(tc => tc.Traits.Add("Tag-Child-example-skipped", null));

            All.Where(tc => tc.FullyQualifiedName.Contains("method context 4"))
            .Do(tc => tc.Traits.Add("Tag with underscores", null));
        }
Пример #47
0
        public void ToDot(string filename, Func <string, int, string> pathProcessor, List <HashSet <AbstractNode> > grouping)
        {
            using (var f = new StreamWriter(filename))
            {
                f.WriteLine("digraph \"extractedGraph\"{");;

                // Write all nodes
                var allNodes = new HashSet <AbstractNode>(AllRelationships.Select(n => n.Key).Concat(AllRelationships.SelectMany(n => n.Value)));
                var nodeIds  = new Dictionary <AbstractNode, int>();
                int nextId   = 0;
                int groupI   = 0;
                foreach (var group in grouping)
                {
                    groupI++;
                    f.WriteLine("subgraph cluster_" + groupI.ToString() + " {" + "style=filled; color = lightgrey; node[style = filled, shape=box; color = white]; ");
                    foreach (var node in group)
                    {
                        var removed = allNodes.Remove(node);
                        Debug.Assert(removed);
                        string path = "Unk/External";
                        if (node.Location != null && node.Location.SourceTree != null)
                        {
                            path = pathProcessor(node.Location.SourceTree.FilePath, node.Location.GetLineSpan().StartLinePosition.Line);
                        }
                        //f.WriteLine("n{0} [label=\"{1}\"];  //{2}", nextId, DotEscape(node.ToString()), path);
                        f.WriteLine("n{0} [label=\"{1}\"]; ", nextId, /*DotEscape(node.ToDotString())*/ node.ToDotString());
                        nodeIds[node] = nextId;
                        nextId++;
                    }
                    f.WriteLine("} //subgraph cluster_" + groupI.ToString());
                }


                foreach (var parentChildrenPair in AllRelationships)
                {
                    var parent = parentChildrenPair.Key;
                    foreach (var child in parentChildrenPair.Value)
                    {
                        if (nodeIds.ContainsKey(parent) && nodeIds.ContainsKey(child))
                        {
                            f.WriteLine("n{0}->n{1};", nodeIds[parent], nodeIds[child]);
                        }
                    }
                }

                f.WriteLine("}");
            }
        }
Пример #48
0
        public override void Weave(
            TypeDefinition typeDef,
            AssemblyDefinition assemblyDefinition,
            MapDefinition mapDefinition,
            Dictionary<string, List<MapDefinition>> assemblyMapDefinitions,
            Dictionary<string, AssemblyDefinition> assemblyDefinitions) {
            var boolTypeDef = typeDef.Module.Import(typeof(bool));
            foreach (var columnDef in
                mapDefinition.ColumnDefinitions.Where(
                    c => c.Relationship == RelationshipType.ManyToOne || c.Relationship == RelationshipType.OneToOne)) {
                // remember the property may be defined on a parent class
                var propDef = this.GetProperty(typeDef, columnDef.Name);

                // add a field with DbType and DbName 
                TypeReference fkTypeReference;
                var fkPkType = columnDef.DbType.GetCLRType();
                if (fkPkType.IsValueType) {
                    fkTypeReference = typeDef.Module.Import(typeof(Nullable<>).MakeGenericType(fkPkType));
                }
                else {
                    fkTypeReference = typeDef.Module.Import(fkPkType);
                }

                var fkField = new FieldDefinition(columnDef.DbName, FieldAttributes.Public, fkTypeReference);
                if (propDef.DeclaringType.Fields.Any(f => f.Name == columnDef.DbName)) {
                    continue; // already done something here!
                }

                this.MakeNotDebuggerBrowsable(typeDef.Module, fkField);
                propDef.DeclaringType.Fields.Add(fkField);

                // override the set method to set to null
                propDef.SetMethod.Body.Instructions.Insert(0, Instruction.Create(OpCodes.Initobj, fkTypeReference));
                propDef.SetMethod.Body.Instructions.Insert(0, Instruction.Create(OpCodes.Ldflda, fkField));
                propDef.SetMethod.Body.Instructions.Insert(0, Instruction.Create(OpCodes.Ldarg_0));

                // override the get method to access this field if null and create a new instance
                // TODO solve for non auto properties
                if (!propDef.GetMethod.Body.Variables.Any()) {
                    // Release code is different to debug code!
                    propDef.GetMethod.Body.Variables.Add(new VariableDefinition(propDef.PropertyType));
                }

                propDef.GetMethod.Body.Variables.Add(new VariableDefinition(propDef.PropertyType));
                propDef.GetMethod.Body.Variables.Add(new VariableDefinition(boolTypeDef));
                propDef.GetMethod.Body.InitLocals = true;
                //propDef.GetMethod.Body.Instructions.Clear();

                var backingField = this.GetBackingField(propDef);
                var il = propDef.GetMethod.Body.Instructions;
                var lastInstr = il[0];
                var index = 0;

                // first bit does the null/hasValue checks on the backing fields
                il.Insert(index++, Instruction.Create(OpCodes.Ldarg_0));
                il.Insert(index++, Instruction.Create(OpCodes.Ldfld, backingField));

                il.Insert(index++, Instruction.Create(OpCodes.Brtrue, lastInstr));

                if (fkPkType.IsValueType) {
                    il.Insert(index++, Instruction.Create(OpCodes.Ldarg_0));
                    il.Insert(index++, Instruction.Create(OpCodes.Ldflda, fkField));
                    il.Insert(
                        index++,
                        Instruction.Create(
                            OpCodes.Call,
                            MakeGeneric(
                                typeDef.Module.Import(fkTypeReference.Resolve().GetMethods().Single(m => m.Name == "get_HasValue")),
                                typeDef.Module.Import(fkPkType))));
                }
                else {
                    il.Insert(index++, Instruction.Create(OpCodes.Ldarg_0));
                    il.Insert(index++, Instruction.Create(OpCodes.Ldfld, fkField));
                }

                il.Insert(index++, Instruction.Create(OpCodes.Brfalse, lastInstr));

                // if we have a pk but no ref we create a new instance with the primary key set
                il.Insert(index++, Instruction.Create(OpCodes.Ldarg_0));
                il.Insert(
                    index++,
                    Instruction.Create(OpCodes.Newobj, typeDef.Module.Import(propDef.PropertyType.Resolve().GetConstructors().First())));
                il.Insert(index++, Instruction.Create(OpCodes.Stloc_0));
                il.Insert(index++, Instruction.Create(OpCodes.Ldloc_0));
                il.Insert(index++, Instruction.Create(OpCodes.Ldarg_0));

                if (fkPkType.IsValueType) {
                    il.Insert(index++, Instruction.Create(OpCodes.Ldflda, fkField));
                    il.Insert(
                        index++,
                        Instruction.Create(
                            OpCodes.Call,
                            typeDef.Module.Import(
                                MakeGeneric(
                                    fkField.FieldType.Resolve().GetMethods().Single(m => m.Name == "get_Value"),
                                    typeDef.Module.Import(fkPkType)))));
                    var fkMapDef = assemblyMapDefinitions.SelectMany(am => am.Value).First(m => m.TypeFullName == columnDef.TypeFullName);
                    var assemblyDef = assemblyDefinitions.Single(ad => ad.Value.FullName == fkMapDef.AssemblyFullName).Value;
                    var fkMapTypeRef = GetTypeDefFromFullName(columnDef.TypeFullName, assemblyDef);
                    il.Insert(
                        index++,
                        Instruction.Create(
                            OpCodes.Callvirt,
                            typeDef.Module.Import(
                                this.GetProperty(fkMapTypeRef, fkMapDef.ColumnDefinitions.Single(cd => cd.IsPrimaryKey).Name).SetMethod)));
                }
                else {
                    il.Insert(index++, Instruction.Create(OpCodes.Ldfld, fkField));
                    var fkMapDef = assemblyMapDefinitions.SelectMany(am => am.Value).First(m => m.TypeFullName == columnDef.TypeFullName);
                    var assemblyDef = assemblyDefinitions.Single(ad => ad.Value.FullName == fkMapDef.AssemblyFullName).Value;
                    var fkMapTypeRef = GetTypeDefFromFullName(columnDef.TypeFullName, assemblyDef);
                    il.Insert(
                        index++,
                        Instruction.Create(
                            OpCodes.Callvirt,
                            typeDef.Module.Import(
                                this.GetProperty(fkMapTypeRef, fkMapDef.ColumnDefinitions.Single(cd => cd.IsPrimaryKey).Name).SetMethod)));
                }

                il.Insert(index++, Instruction.Create(OpCodes.Ldloc_0));
                il.Insert(index, Instruction.Create(OpCodes.Stfld, backingField));
            }
        }
Пример #49
0
        public List<Tuple<GrainId, string, int>> GetGrainStatistics()
        {
            var counts = new Dictionary<string, Dictionary<GrainId, int>>();
            lock (activations)
            {
                foreach (var activation in activations)
                {
                    ActivationData data = activation.Value;
                    if (data == null || data.GrainInstance == null) continue;

                    // TODO: generic type expansion
                    var grainTypeName = TypeUtils.GetFullName(data.GrainInstanceType);
                    
                    Dictionary<GrainId, int> grains;
                    int n;
                    if (!counts.TryGetValue(grainTypeName, out grains))
                    {
                        counts.Add(grainTypeName, new Dictionary<GrainId, int> { { data.Grain, 1 } });
                    }
                    else if (!grains.TryGetValue(data.Grain, out n))
                        grains[data.Grain] = 1;
                    else
                        grains[data.Grain] = n + 1;
                }
            }
            return counts
                .SelectMany(p => p.Value.Select(p2 => Tuple.Create(p2.Key, p.Key, p2.Value)))
                .ToList();
        }
Пример #50
0
        private IEnumerable<DrugExposure> PrepareDrugExposures(IEnumerable<DrugExposure> drugExposures, Dictionary<long, VisitOccurrence> visitOccurrences)
        {
            var rxDrugs = new Dictionary<Guid, List<DrugExposure>>();
              var medicalDrugs = new Dictionary<Guid, List<DrugExposure>>();
              foreach (var drugExposure in drugExposures)
              {
             if (drugExposure.TypeConceptId == 38000175 || drugExposure.TypeConceptId == 38000176)
             {
                if (!rxDrugs.ContainsKey(drugExposure.SourceRecordGuid))
                   rxDrugs.Add(drugExposure.SourceRecordGuid, new List<DrugExposure>());

                rxDrugs[drugExposure.SourceRecordGuid].Add(drugExposure);
                continue;
             }

             if (!medicalDrugs.ContainsKey(drugExposure.SourceRecordGuid))
                medicalDrugs.Add(drugExposure.SourceRecordGuid, new List<DrugExposure>());

             medicalDrugs[drugExposure.SourceRecordGuid].Add(drugExposure);
              }

              foreach (var sourceRecordGuid in medicalDrugs.Keys)
              {
             //TypeConceptId == 0, ndc
             var ndcExists = medicalDrugs[sourceRecordGuid].Any(d => d.TypeConceptId == 0);

             foreach (var drugExposure in medicalDrugs[sourceRecordGuid])
             {
                //TypeConceptId == 4, proc_cd
                if (drugExposure.TypeConceptId == 4 && ndcExists)
                   continue;

                var visitOccurrence = GetVisitOccurrence(drugExposure);
                if (visitOccurrence == null)
                   continue;

                drugExposure.VisitOccurrenceId = visitOccurrence.Id;
                drugExposure.TypeConceptId = visitOccurrence.ConceptId == 9201 ? 38000180 : 38000179;

                yield return drugExposure;
             }
              }

              foreach (var similarDrugs in rxDrugs.SelectMany(drugs => drugs.Value.GroupBy(d => d.SourceValue.Length >= 9 ? d.SourceValue.Substring(0, 9) : d.SourceValue)))
              {
             if (similarDrugs.Count(d => d.ConceptId > 0) > 0)
             {
                yield return similarDrugs.Where(d => d.ConceptId > 0).OrderBy(d => d.SourceValue.Length).Last();
                continue;
             }

             yield return similarDrugs.OrderBy(d => d.SourceValue.Length).Last();
              }
        }
Пример #51
0
        private void ImplementITrackedEntityForTypeDefinition(TypeDefinition typeDef, MapDefinition mapDefinition, bool notInInheritance, Dictionary<string, AssemblyDefinition> assemblyDefinitions, Dictionary<string, List<MapDefinition>> assemblyMapDefinitions) {
            if (typeDef.Methods.Any(m => m.Name == "GetDirtyProperties")) {
                return; // type already woven
            }

            if (!this.ImplementsInterface(typeDef, typeof(ITrackedEntity))) {
                this.AddInterfaceToNonObjectAncestor(typeDef, typeof(ITrackedEntity));
            }

            // some common type definitions
            var boolTypeDef = typeDef.Module.Import(typeof(bool));
            var voidTypeDef = typeDef.Module.Import(typeof(void));
            var stringTypeDef = typeDef.Module.Import(typeof(string));
            var listStringTypeDef = typeDef.Module.Import(typeof(List<>)).MakeGenericInstanceType(stringTypeDef);
            var objectTypeDef = typeDef.Module.Import(typeof(object));

            // some column names
            const string isTrackingName = "__isTracking";

            // add isTracking field if base class
            if (this.IsBaseClass(typeDef)) {
                var _isTrackingField = new FieldDefinition(isTrackingName, FieldAttributes.Family, boolTypeDef);
                this.MakeNotDebuggerBrowsable(typeDef.Module, _isTrackingField);
                typeDef.Fields.Add(_isTrackingField);
            }

            // fields for tracking state of properties on this class only
            var nonPkCols = mapDefinition.ColumnDefinitions.Where(c => !c.IsPrimaryKey && c.Relationship != RelationshipType.OneToMany).ToList();
            foreach (var columnDefinition in nonPkCols) {
                if (this.HasPropertyInInheritanceChain(typeDef, columnDefinition.Name)) {
                    var propertyDefinition = this.GetProperty(typeDef, columnDefinition.Name);
                    if (propertyDefinition.DeclaringType.FullName == typeDef.FullName) {
                        var dirtyField = new FieldDefinition(
                            string.Format("__{0}_IsDirty", columnDefinition.Name),
                            FieldAttributes.Family,
                            boolTypeDef);
                        this.MakeNotDebuggerBrowsable(typeDef.Module, dirtyField);
                        typeDef.Fields.Add(dirtyField);

                        // handle other maps, strings, valuetype, valuetype?
                        var oldValuePropType = propertyDefinition.PropertyType;
                        if (columnDefinition.Relationship == RelationshipType.None && propertyDefinition.PropertyType.IsValueType
                            && propertyDefinition.PropertyType.Name != "Nullable`1") {
                            oldValuePropType = typeDef.Module.Import(typeof(Nullable<>)).MakeGenericInstanceType(oldValuePropType);
                            // use nullable value types
                        }

                        var oldValueField = new FieldDefinition(
                            string.Format("__{0}_OldValue", columnDefinition.Name),
                            FieldAttributes.Family,
                            oldValuePropType);
                        this.MakeNotDebuggerBrowsable(typeDef.Module, oldValueField);
                        typeDef.Fields.Add(oldValueField);
                    }
                }
            }

            // insert the instructions in to the setter
            var isTrackingField = this.GetField(typeDef, isTrackingName);
            foreach (var columnDefinition in nonPkCols) {
                if (this.HasPropertyInInheritanceChain(typeDef, columnDefinition.Name)) {
                    var propertyDefinition = this.GetProperty(typeDef, columnDefinition.Name);
                    if (propertyDefinition.DeclaringType.FullName == typeDef.FullName) {
                        var backingField = this.GetBackingField(propertyDefinition);
                        var setter = propertyDefinition.SetMethod;
                        setter.Body.Variables.Add(new VariableDefinition(boolTypeDef)); // we need a local bool
                        setter.Body.InitLocals = true;
                        var setIl = setter.Body.Instructions;
                        var setIntructions = new List<Instruction>();
                        setIntructions.Add(Instruction.Create(OpCodes.Nop));
                        setIntructions.Add(Instruction.Create(OpCodes.Ldarg_0));
                        setIntructions.Add(Instruction.Create(OpCodes.Ldfld, isTrackingField));
                        setIntructions.Add(Instruction.Create(OpCodes.Ldc_I4_0));
                        setIntructions.Add(Instruction.Create(OpCodes.Ceq));
                        setIntructions.Add(Instruction.Create(OpCodes.Stloc_0));
                        setIntructions.Add(Instruction.Create(OpCodes.Ldloc_0));
                        var endNopInstr = Instruction.Create(OpCodes.Nop);
                        var endLdArgInstr = setIl.First();
                        setIntructions.Add(Instruction.Create(OpCodes.Brtrue, endLdArgInstr));
                        setIntructions.Add(Instruction.Create(OpCodes.Nop));
                        setIntructions.Add(Instruction.Create(OpCodes.Ldarg_0));
                        setIntructions.Add(
                            Instruction.Create(
                                OpCodes.Ldfld,
                                typeDef.Fields.Single(f => f.Name == string.Format("__{0}_IsDirty", columnDefinition.Name))));
                        setIntructions.Add(Instruction.Create(OpCodes.Stloc_0));
                        setIntructions.Add(Instruction.Create(OpCodes.Ldloc_0));
                        setIntructions.Add(Instruction.Create(OpCodes.Brtrue, endNopInstr));
                        setIntructions.Add(Instruction.Create(OpCodes.Nop));
                        setIntructions.Add(Instruction.Create(OpCodes.Ldarg_0));

                        if (propertyDefinition.PropertyType.IsValueType) {
                            var isEnum = propertyDefinition.PropertyType.Resolve().IsEnum;
                            if (isEnum) {
                                setIntructions.Add(Instruction.Create(OpCodes.Ldfld, backingField));
                                setIntructions.Add(Instruction.Create(OpCodes.Box, propertyDefinition.PropertyType));
                            }
                            else {
                                setIntructions.Add(Instruction.Create(OpCodes.Ldflda, backingField));
                            }

                            setIntructions.Add(Instruction.Create(OpCodes.Ldarg_1));
                            if (isEnum) {
                                setIntructions.Add(Instruction.Create(OpCodes.Box, propertyDefinition.PropertyType));
                                setIntructions.Add(
                                    Instruction.Create(
                                        OpCodes.Callvirt,
                                        typeDef.Module.Import(
                                            objectTypeDef.Resolve()
                                                         .GetMethods()
                                                         .Single(
                                                             m =>
                                                             m.Name == "Equals" && m.Parameters.Count == 1
                                                             && m.Parameters.First().ParameterType.Name.ToLowerInvariant() == "object"))));
                            }
                            else if (propertyDefinition.PropertyType.Name == "Nullable`1") {
                                setIntructions.Add(Instruction.Create(OpCodes.Box, backingField.FieldType));
                                setIntructions.Add(Instruction.Create(OpCodes.Constrained, backingField.FieldType));
                                setIntructions.Add(
                                    Instruction.Create(
                                        OpCodes.Callvirt,
                                        typeDef.Module.Import(
                                            objectTypeDef.Resolve()
                                                         .GetMethods()
                                                         .Single(
                                                             m =>
                                                             m.Name == "Equals" && m.Parameters.Count == 1
                                                             && m.Parameters.First().ParameterType.Name.ToLowerInvariant() == "object"))));
                            }
                            else {
                                setIntructions.Add(
                                    Instruction.Create(
                                        OpCodes.Call,
                                        typeDef.Module.Import(
                                            propertyDefinition.PropertyType.Resolve()
                                                              .Methods.Single(
                                                                  m =>
                                                                  m.Name == "Equals" && m.Parameters.Count == 1
                                                                  && m.Parameters.First().ParameterType.Name.ToLowerInvariant() != "object"))));
                            }

                            setIntructions.Add(Instruction.Create(OpCodes.Stloc_0));
                            setIntructions.Add(Instruction.Create(OpCodes.Ldloc_0));
                            setIntructions.Add(Instruction.Create(OpCodes.Brtrue, endNopInstr));
                        }
                        else {
                            var fkPkType = columnDefinition.DbType.GetCLRType();
                            TypeReference fkTypeReference;
                            if (fkPkType.IsValueType) {
                                fkTypeReference = typeDef.Module.Import(typeof(Nullable<>).MakeGenericType(fkPkType));
                            }
                            else {
                                fkTypeReference = typeDef.Module.Import(fkPkType);
                            }

                            setIntructions.Add(Instruction.Create(OpCodes.Ldfld, backingField));
                            var hmmInstr = Instruction.Create(OpCodes.Ldc_I4_0);
                            var hmmInstr2 = Instruction.Create(OpCodes.Ldc_I4_1);

                            if (propertyDefinition.PropertyType.Name.ToLowerInvariant() == "string") {
                                var orInstr = Instruction.Create(OpCodes.Ldarg_0);
                                setIntructions.Add(Instruction.Create(OpCodes.Brtrue, orInstr));
                                setIntructions.Add(Instruction.Create(OpCodes.Ldarg_1));
                                setIntructions.Add(Instruction.Create(OpCodes.Brtrue, hmmInstr));
                                setIntructions.Add(orInstr);
                            }
                            else {
                                var orInstr = Instruction.Create(OpCodes.Ldarg_1);
                                var orInstr2 = Instruction.Create(OpCodes.Ldarg_0);
                                setIntructions.Add(Instruction.Create(OpCodes.Brtrue, orInstr));
                                setIntructions.Add(Instruction.Create(OpCodes.Ldarg_1));
                                setIntructions.Add(Instruction.Create(OpCodes.Brtrue, hmmInstr));
                                setIntructions.Add(orInstr);
                                setIntructions.Add(Instruction.Create(OpCodes.Brtrue, orInstr2));
                                setIntructions.Add(Instruction.Create(OpCodes.Ldarg_0));

                                if (fkPkType.IsValueType) {
                                    // need to call HasValue
                                    setIntructions.Add(Instruction.Create(OpCodes.Ldflda, typeDef.Fields.Single(f => f.Name == columnDefinition.DbName)));
                                    setIntructions.Add(Instruction.Create(
                                        OpCodes.Call,
                                        MakeGeneric(
                                            typeDef.Module.Import(fkTypeReference.Resolve().GetMethods().Single(m => m.Name == "get_HasValue")),
                                            typeDef.Module.Import(fkPkType))));
                                    setIntructions.Add(Instruction.Create(OpCodes.Brtrue, hmmInstr));
                                }
                                else {
                                    // check for null
                                    setIntructions.Add(Instruction.Create(OpCodes.Ldfld, typeDef.Fields.Single(f => f.Name == columnDefinition.DbName)));
                                    setIntructions.Add(Instruction.Create(OpCodes.Brtrue, hmmInstr));
                                }

                                setIntructions.Add(orInstr2);
                            }

                            setIntructions.Add(Instruction.Create(OpCodes.Ldfld, backingField));
                            setIntructions.Add(Instruction.Create(OpCodes.Brfalse, hmmInstr2));
                            setIntructions.Add(Instruction.Create(OpCodes.Ldarg_0));
                            setIntructions.Add(Instruction.Create(OpCodes.Ldfld, backingField));
                            setIntructions.Add(Instruction.Create(OpCodes.Ldarg_1));
                            if (propertyDefinition.PropertyType.Name.ToLowerInvariant() == "string") {
                                setIntructions.Add(
                                    Instruction.Create(
                                        OpCodes.Callvirt,
                                        typeDef.Module.Import(
                                            propertyDefinition.PropertyType.Resolve()
                                                              .GetMethods()
                                                              .Single(
                                                                  m =>
                                                                  m.Name == "Equals" && m.Parameters.Count == 1
                                                                  && m.Parameters.First().ParameterType.Name.ToLowerInvariant() == "string"))));
                            }
                            else {
                                setIntructions.Add(
                                    Instruction.Create(
                                        OpCodes.Callvirt,
                                        typeDef.Module.Import(
                                            objectTypeDef.Resolve()
                                                         .GetMethods()
                                                         .Single(
                                                             m =>
                                                             m.Name == "Equals" && m.Parameters.Count == 1
                                                             && m.Parameters.First().ParameterType.Name.ToLowerInvariant() == "object"))));
                            }

                            var nopInstr = Instruction.Create(OpCodes.Nop);
                            setIntructions.Add(Instruction.Create(OpCodes.Br, nopInstr));
                            setIntructions.Add(hmmInstr2);
                            setIntructions.Add(nopInstr);
                            var nopInstr2 = Instruction.Create(OpCodes.Nop);
                            setIntructions.Add(Instruction.Create(OpCodes.Br, nopInstr2));
                            setIntructions.Add(hmmInstr);
                            setIntructions.Add(nopInstr2);
                            setIntructions.Add(Instruction.Create(OpCodes.Stloc_0));
                            setIntructions.Add(Instruction.Create(OpCodes.Ldloc_0));
                            setIntructions.Add(Instruction.Create(OpCodes.Brtrue, endNopInstr));
                            setIntructions.Add(Instruction.Create(OpCodes.Nop));
                        }

                        // it's now dirty
                        setIntructions.Add(Instruction.Create(OpCodes.Nop));

                        var topOfSetIsDirtyInstr = Instruction.Create(OpCodes.Ldarg_0);
                        if (columnDefinition.Relationship == RelationshipType.ManyToOne || columnDefinition.Relationship == RelationshipType.OneToOne) {
                            // we need to check whether the foreign key backing field has a value
                            var setToBackingFieldInstr = Instruction.Create(OpCodes.Ldarg_0);
                            setIntructions.Add(Instruction.Create(OpCodes.Ldarg_0));
                            setIntructions.Add(Instruction.Create(OpCodes.Ldfld, backingField));
                            setIntructions.Add(Instruction.Create(OpCodes.Brtrue, setToBackingFieldInstr));
                            var fkPkType = columnDefinition.DbType.GetCLRType();
                            TypeReference fkTypeReference;
                            if (fkPkType.IsValueType) {
                                fkTypeReference = typeDef.Module.Import(typeof(Nullable<>).MakeGenericType(fkPkType));
                            }
                            else {
                                fkTypeReference = typeDef.Module.Import(fkPkType);
                            }

                            var fkField = typeDef.Fields.Single(f => f.Name == columnDefinition.DbName);
                            setIntructions.Add(Instruction.Create(OpCodes.Ldarg_0));
                            if (fkPkType.IsValueType) {
                                // need to call HasValue
                                setIntructions.Add(Instruction.Create(OpCodes.Ldflda, fkField));
                                setIntructions.Add(Instruction.Create(
                                    OpCodes.Call,
                                    MakeGeneric(
                                        typeDef.Module.Import(fkTypeReference.Resolve().GetMethods().Single(m => m.Name == "get_HasValue")),
                                        typeDef.Module.Import(fkPkType))));
                                setIntructions.Add(Instruction.Create(OpCodes.Brfalse, setToBackingFieldInstr));
                            }
                            else {
                                // check for null
                                setIntructions.Add(Instruction.Create(OpCodes.Ldfld, fkField));
                                setIntructions.Add(Instruction.Create(OpCodes.Brfalse, setToBackingFieldInstr));
                            }

                            // need to add a variable to hold the new obj
                            var fkGeneratedVariableDef = new VariableDefinition(propertyDefinition.PropertyType);
                            propertyDefinition.SetMethod.Body.Variables.Add(fkGeneratedVariableDef);

                            // if we get here then we have an FK value but null in this backing field so we need to create a new instance of the FK and set that as the old value
                            setIntructions.Add(Instruction.Create(OpCodes.Ldarg_0));
                            setIntructions.Add(Instruction.Create(OpCodes.Newobj, typeDef.Module.Import(propertyDefinition.PropertyType.Resolve().GetConstructors().First())));
                            setIntructions.Add(Instruction.Create(OpCodes.Stloc, fkGeneratedVariableDef));
                            setIntructions.Add(Instruction.Create(OpCodes.Ldloc, fkGeneratedVariableDef));
                            setIntructions.Add(Instruction.Create(OpCodes.Ldarg_0));
                            if (fkPkType.IsValueType) {
                                setIntructions.Add(Instruction.Create(OpCodes.Ldflda, typeDef.Fields.Single(f => f.Name == columnDefinition.DbName)));
                                setIntructions.Add(Instruction.Create(
                                        OpCodes.Call,
                                        typeDef.Module.Import(
                                            MakeGeneric(
                                                fkField.FieldType.Resolve().GetMethods().Single(m => m.Name == "get_Value"),
                                                typeDef.Module.Import(fkPkType)))));
                                var fkMapDef = assemblyMapDefinitions.SelectMany(am => am.Value).First(m => m.TypeFullName == columnDefinition.TypeFullName);
                                var assemblyDef = assemblyDefinitions.Single(ad => ad.Value.FullName == fkMapDef.AssemblyFullName).Value;
                                var fkMapTypeRef = GetTypeDefFromFullName(columnDefinition.TypeFullName, assemblyDef);
                                setIntructions.Add(
                                    Instruction.Create(
                                        OpCodes.Callvirt,
                                        typeDef.Module.Import(
                                            this.GetProperty(fkMapTypeRef, fkMapDef.ColumnDefinitions.Single(cd => cd.IsPrimaryKey).Name).SetMethod)));
                            }
                            else {
                                setIntructions.Add(Instruction.Create(OpCodes.Ldfld, fkField));
                                var fkMapDef = assemblyMapDefinitions.SelectMany(am => am.Value).First(m => m.TypeFullName == columnDefinition.TypeFullName);
                                var assemblyDef = assemblyDefinitions.Single(ad => ad.Value.FullName == fkMapDef.AssemblyFullName).Value;
                                var fkMapTypeRef = GetTypeDefFromFullName(columnDefinition.TypeFullName, assemblyDef);
                                setIntructions.Add(Instruction.Create(
                                        OpCodes.Callvirt,
                                        typeDef.Module.Import(
                                            this.GetProperty(fkMapTypeRef, fkMapDef.ColumnDefinitions.Single(cd => cd.IsPrimaryKey).Name).SetMethod)));
                            }

                            setIntructions.Add(Instruction.Create(OpCodes.Ldloc, fkGeneratedVariableDef));
                            setIntructions.Add(Instruction.Create(OpCodes.Stfld, typeDef.Fields.Single(f => f.Name == string.Format("__{0}_OldValue", columnDefinition.Name))));
                            setIntructions.Add(Instruction.Create(OpCodes.Br, topOfSetIsDirtyInstr));

                            // set using backing field
                            setIntructions.Add(setToBackingFieldInstr);
                            setIntructions.Add(Instruction.Create(OpCodes.Ldarg_0));
                            setIntructions.Add(Instruction.Create(OpCodes.Ldfld, backingField));
                            setIntructions.Add(
                                Instruction.Create(
                                    OpCodes.Stfld,
                                    typeDef.Fields.Single(f => f.Name == string.Format("__{0}_OldValue", columnDefinition.Name))));
                        }
                        else { 
                            setIntructions.Add(Instruction.Create(OpCodes.Ldarg_0));
                            setIntructions.Add(Instruction.Create(OpCodes.Ldarg_0));
                            setIntructions.Add(Instruction.Create(OpCodes.Ldfld, backingField));
                            if (columnDefinition.Relationship == RelationshipType.None && propertyDefinition.PropertyType.IsValueType
                                && propertyDefinition.PropertyType.Name != "Nullable`1") {
                                setIntructions.Add(
                                    Instruction.Create(
                                        OpCodes.Newobj,
                                        MakeGeneric(
                                            typeDef.Module.Import(
                                                typeDef.Fields.Single(f => f.Name == string.Format("__{0}_OldValue", columnDefinition.Name))
                                                       .FieldType.Resolve()
                                                       .GetConstructors()
                                                       .First()),
                                            propertyDefinition.PropertyType)));
                            }

                            setIntructions.Add(
                                Instruction.Create(
                                    OpCodes.Stfld,
                                    typeDef.Fields.Single(f => f.Name == string.Format("__{0}_OldValue", columnDefinition.Name))));
                        }

                        setIntructions.Add(topOfSetIsDirtyInstr);
                        setIntructions.Add(Instruction.Create(OpCodes.Ldc_I4_1));
                        setIntructions.Add(
                            Instruction.Create(
                                OpCodes.Stfld,
                                typeDef.Fields.Single(f => f.Name == string.Format("__{0}_IsDirty", columnDefinition.Name))));
                        setIntructions.Add(Instruction.Create(OpCodes.Nop));
                        setIntructions.Add(endNopInstr);
                        setIntructions.Reverse();
                        foreach (var instruction in setIntructions) {
                            setIl.Insert(0, instruction);
                        }
                    }
                }
            }

            // implement the ITrackedEntity methods
            // EnableTracking
            if (this.IsBaseClass(typeDef)) {
                var enableTracking = new MethodDefinition(
                    "EnableTracking",
                    MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.NewSlot | MethodAttributes.Virtual
                    | MethodAttributes.Final,
                    voidTypeDef);
                enableTracking.Body.Instructions.Add(Instruction.Create(OpCodes.Nop));
                enableTracking.Body.Instructions.Add(Instruction.Create(OpCodes.Ldarg_0));
                enableTracking.Body.Instructions.Add(Instruction.Create(OpCodes.Ldc_I4_1));
                enableTracking.Body.Instructions.Add(Instruction.Create(OpCodes.Stfld, typeDef.Fields.Single(f => f.Name == isTrackingName)));
                enableTracking.Body.Instructions.Add(Instruction.Create(OpCodes.Ret));
                typeDef.Methods.Add(enableTracking);
            }

            // DisableTracking
            var disableTrackingMethodAttrs = MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.Virtual;
            if (notInInheritance) {
                disableTrackingMethodAttrs = disableTrackingMethodAttrs | MethodAttributes.NewSlot | MethodAttributes.Final;
            }
            var disableTracking = new MethodDefinition("DisableTracking", disableTrackingMethodAttrs, voidTypeDef);
            var disableInstructions = disableTracking.Body.Instructions;
            disableInstructions.Add(Instruction.Create(OpCodes.Nop));
            disableInstructions.Add(Instruction.Create(OpCodes.Ldarg_0));
            disableInstructions.Add(Instruction.Create(OpCodes.Ldc_I4_0));
            disableInstructions.Add(Instruction.Create(OpCodes.Stfld, isTrackingField));
            foreach (var col in nonPkCols) {
                if (this.HasPropertyInInheritanceChain(typeDef, col.Name)) {
                    var propDef = this.GetProperty(typeDef, col.Name);

                    // reset isdirty
                    disableInstructions.Add(Instruction.Create(OpCodes.Ldarg_0));
                    disableInstructions.Add(Instruction.Create(OpCodes.Ldc_I4_0));
                    disableInstructions.Add(Instruction.Create(OpCodes.Stfld, this.GetField(typeDef, string.Format("__{0}_IsDirty", col.Name))));

                    // reset oldvalue
                    disableInstructions.Add(Instruction.Create(OpCodes.Ldarg_0));
                    var oldValueField = this.GetField(typeDef, string.Format("__{0}_OldValue", col.Name));
                    if (propDef.PropertyType.IsValueType) {
                        disableInstructions.Add(Instruction.Create(OpCodes.Ldflda, oldValueField));
                        disableInstructions.Add(Instruction.Create(OpCodes.Initobj, oldValueField.FieldType));
                    }
                    else {
                        disableInstructions.Add(Instruction.Create(OpCodes.Ldnull));
                        disableInstructions.Add(Instruction.Create(OpCodes.Stfld, oldValueField));
                    }
                }
            }

            disableInstructions.Add(Instruction.Create(OpCodes.Ret));
            typeDef.Methods.Add(disableTracking);

            // IsTrackingEnabled
            if (this.IsBaseClass(typeDef)) {
                var isTrackingEnabled = new MethodDefinition(
                    "IsTrackingEnabled",
                    MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.NewSlot | MethodAttributes.Virtual
                    | MethodAttributes.Final,
                    boolTypeDef);
                isTrackingEnabled.Body.Instructions.Add(Instruction.Create(OpCodes.Nop));
                isTrackingEnabled.Body.Instructions.Add(Instruction.Create(OpCodes.Ldarg_0));
                isTrackingEnabled.Body.Instructions.Add(Instruction.Create(OpCodes.Ldfld, typeDef.Fields.Single(f => f.Name == isTrackingName)));
                isTrackingEnabled.Body.Instructions.Add(Instruction.Create(OpCodes.Stloc_0));
                var loadInstr = Instruction.Create(OpCodes.Ldloc_0);
                isTrackingEnabled.Body.Instructions.Add(Instruction.Create(OpCodes.Br, loadInstr));
                isTrackingEnabled.Body.Instructions.Add(loadInstr);
                isTrackingEnabled.Body.Instructions.Add(Instruction.Create(OpCodes.Ret));
                isTrackingEnabled.Body.InitLocals = true;
                isTrackingEnabled.Body.Variables.Add(new VariableDefinition(boolTypeDef));
                typeDef.Methods.Add(isTrackingEnabled);
            }

            // GetDirtyProperties
            var getDirtyPropertiesMethodAttrs = MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.Virtual;
            if (notInInheritance) {
                getDirtyPropertiesMethodAttrs = getDirtyPropertiesMethodAttrs | MethodAttributes.NewSlot | MethodAttributes.Final;
            }
            var getDirtyProperties = new MethodDefinition(
                "GetDirtyProperties",
                getDirtyPropertiesMethodAttrs,
                typeDef.Module.Import(typeof(IEnumerable<>)).MakeGenericInstanceType(stringTypeDef));
            getDirtyProperties.Body.Variables.Add(new VariableDefinition("dirtyProps", listStringTypeDef));
            getDirtyProperties.Body.Variables.Add(
                new VariableDefinition(typeDef.Module.Import(typeof(IEnumerable<>)).MakeGenericInstanceType(stringTypeDef)));
            getDirtyProperties.Body.Variables.Add(new VariableDefinition(boolTypeDef));
            getDirtyProperties.Body.InitLocals = true;
            var instructions = getDirtyProperties.Body.Instructions;
            instructions.Add(Instruction.Create(OpCodes.Nop));
            var listStringContruictor =
                MakeGeneric(
                    typeDef.Module.Import(listStringTypeDef.Resolve().GetConstructors().First(c => !c.HasParameters && !c.IsStatic && c.IsPublic)),
                    stringTypeDef);
            instructions.Add(Instruction.Create(OpCodes.Newobj, listStringContruictor));
            instructions.Add(Instruction.Create(OpCodes.Stloc_0));

            var breakToInstruction = Instruction.Create(nonPkCols.Count == 1 ? OpCodes.Ldloc_0 : OpCodes.Ldarg_0);
            var addMethod = typeDef.Module.Import(listStringTypeDef.Resolve().Methods.Single(m => m.Name == "Add"));
            addMethod = MakeGeneric(addMethod, stringTypeDef);
            var visibleCols = nonPkCols.Where(c => this.HasPropertyInInheritanceChain(typeDef, c.Name)).ToList();
            for (var i = 0; i < visibleCols.Count; i++) {
                if (i == 0) {
                    instructions.Add(Instruction.Create(OpCodes.Ldarg_0));
                }

                instructions.Add(
                    Instruction.Create(OpCodes.Ldfld, this.GetField(typeDef, string.Format("__{0}_IsDirty", visibleCols.ElementAt(i).Name))));
                instructions.Add(Instruction.Create(OpCodes.Ldc_I4_0));
                instructions.Add(Instruction.Create(OpCodes.Ceq));
                instructions.Add(Instruction.Create(OpCodes.Stloc_2));
                instructions.Add(Instruction.Create(OpCodes.Ldloc_2));
                instructions.Add(Instruction.Create(OpCodes.Brtrue, breakToInstruction));
                instructions.Add(Instruction.Create(OpCodes.Nop));
                instructions.Add(Instruction.Create(OpCodes.Ldloc_0));
                instructions.Add(Instruction.Create(OpCodes.Ldstr, visibleCols.ElementAt(i).Name));
                instructions.Add(Instruction.Create(OpCodes.Callvirt, addMethod));
                instructions.Add(Instruction.Create(OpCodes.Nop));
                instructions.Add(Instruction.Create(OpCodes.Nop));
                instructions.Add(breakToInstruction);
                breakToInstruction = Instruction.Create(i == visibleCols.Count - 2 ? OpCodes.Ldloc_0 : OpCodes.Ldarg_0);
            }

            instructions.Add(Instruction.Create(OpCodes.Stloc_1));
            var retInstr = Instruction.Create(OpCodes.Ldloc_1);
            instructions.Add(Instruction.Create(OpCodes.Br, retInstr));
            instructions.Add(retInstr);
            instructions.Add(Instruction.Create(OpCodes.Ret));
            typeDef.Methods.Add(getDirtyProperties);

            // GetOldValue
            var getOldValueMethodAttrs = MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.Virtual;
            if (notInInheritance) {
                getOldValueMethodAttrs = getOldValueMethodAttrs | MethodAttributes.NewSlot | MethodAttributes.Final;
            }

            var getOldValue = new MethodDefinition("GetOldValue", getOldValueMethodAttrs, objectTypeDef);
            getOldValue.Parameters.Add(new ParameterDefinition("propertyName", ParameterAttributes.None, stringTypeDef));
            getOldValue.Body.Variables.Add(new VariableDefinition(objectTypeDef));
            getOldValue.Body.Variables.Add(new VariableDefinition(stringTypeDef));
            getOldValue.Body.Variables.Add(new VariableDefinition(boolTypeDef));
            getOldValue.Body.InitLocals = true;
            var getBodyInstructions = getOldValue.Body.Instructions;
            getBodyInstructions.Add(Instruction.Create(OpCodes.Nop));
            getBodyInstructions.Add(Instruction.Create(OpCodes.Ldarg_1));
            getBodyInstructions.Add(Instruction.Create(OpCodes.Stloc_1));
            getBodyInstructions.Add(Instruction.Create(OpCodes.Ldloc_1));

            var throwExceptionTarget = Instruction.Create(OpCodes.Ldstr, "propertyName");
            var returnTarget = Instruction.Create(OpCodes.Ldloc_0);
            getBodyInstructions.Add(Instruction.Create(OpCodes.Brfalse, throwExceptionTarget));

            var switchInstructions = new List<Instruction>();
            var opEqualityRef = typeDef.Module.Import(typeof(string).GetMethods().Single(m => m.Name == "op_Equality"));
            for (var i = 0; i < visibleCols.Count; i++) {
                // generate the switch bit
                getBodyInstructions.Add(Instruction.Create(OpCodes.Ldloc_1));
                getBodyInstructions.Add(Instruction.Create(OpCodes.Ldstr, visibleCols.ElementAt(i).Name));
                getBodyInstructions.Add(Instruction.Create(OpCodes.Call, opEqualityRef));

                // generate the if bit
                var targetInstr = Instruction.Create(OpCodes.Ldarg_0);
                getBodyInstructions.Add(Instruction.Create(OpCodes.Brtrue, targetInstr));
                switchInstructions.Add(targetInstr);
                switchInstructions.Add(
                    Instruction.Create(OpCodes.Ldfld, this.GetField(typeDef, String.Format("__{0}_IsDirty", visibleCols.ElementAt(i).Name))));
                switchInstructions.Add(Instruction.Create(OpCodes.Ldc_I4_0));
                switchInstructions.Add(Instruction.Create(OpCodes.Ceq));
                switchInstructions.Add(Instruction.Create(OpCodes.Stloc_2));
                switchInstructions.Add(Instruction.Create(OpCodes.Ldloc_2));

                // generate the return bit
                var breakInstruction = Instruction.Create(OpCodes.Br, throwExceptionTarget);
                switchInstructions.Add(Instruction.Create(OpCodes.Brtrue, breakInstruction));
                switchInstructions.Add(Instruction.Create(OpCodes.Nop));
                switchInstructions.Add(Instruction.Create(OpCodes.Ldarg_0));
                switchInstructions.Add(
                    Instruction.Create(OpCodes.Ldfld, this.GetField(typeDef, String.Format("__{0}_OldValue", visibleCols.ElementAt(i).Name))));
                if (this.GetProperty(typeDef, visibleCols.ElementAt(i).Name).PropertyType.IsValueType) {
                    switchInstructions.Add(
                        Instruction.Create(
                            OpCodes.Box,
                            this.GetField(typeDef, String.Format("__{0}_OldValue", visibleCols.ElementAt(i).Name)).FieldType));
                }

                switchInstructions.Add(Instruction.Create(OpCodes.Stloc_0));
                switchInstructions.Add(Instruction.Create(OpCodes.Br, returnTarget));
                switchInstructions.Add(breakInstruction);
            }

            // add a br
            getBodyInstructions.Add(Instruction.Create(OpCodes.Br, throwExceptionTarget));

            // run them
            foreach (var instruction in switchInstructions) {
                getBodyInstructions.Add(instruction);
            }

            // handle the exception
            getBodyInstructions.Add(Instruction.Create(OpCodes.Nop));
            getBodyInstructions.Add(throwExceptionTarget);
            getBodyInstructions.Add(
                Instruction.Create(OpCodes.Ldstr, "Either the property doesn't exist or it's not dirty. Consult GetDirtyProperties first"));
            getBodyInstructions.Add(
                Instruction.Create(
                    OpCodes.Newobj,
                    typeDef.Module.Import(
                        typeof(ArgumentOutOfRangeException).GetConstructors()
                                                           .First(
                                                               c =>
                                                               c.GetParameters().All(p => p.ParameterType == typeof(string))
                                                               && c.GetParameters().Count() == 2))));
            getBodyInstructions.Add(Instruction.Create(OpCodes.Throw));
            getBodyInstructions.Add(returnTarget);
            getBodyInstructions.Add(Instruction.Create(OpCodes.Ret));
            typeDef.Methods.Add(getOldValue);
        }
Пример #52
0
        public IList<TestataSollecitoDTO> GetSolleciti(int? idEsercizio, Dictionary<int, TipoIndirizzo> idCondomini, bool groupByPersone, DateTime? dataRate, DateTime? dataVersamenti, decimal? importoLimite, decimal? importoCompetenza, DateTime dataSollecito, bool stampaProprietario, int? idBanca, int idModelloLettera, string testoModelloLettera, DateTime? dataRegistrazioneContabile, int? idConto, int? idSottoConto, bool storico, bool sollecitaProprietarioConduzione)
        {
            try
            {
                var solleciti = new List<TestataSollecitoDTO>(idCondomini.Count);
                var listaSolleciti = new List<Sollecito>(idCondomini.Count);

                Esercizio esercizio = null;
                if (idEsercizio != null)
                    esercizio = _daoFactory.GetEsercizioDao().GetById(idEsercizio.Value, false);

                var dataFinale = new DateTime(DateTime.Today.Year, 12, 31);

                var modello = _daoFactory.GetModelloLetteraTestoDao().Find(idModelloLettera, false);

                // ==========================================================================================
                //  Leggo subito tutti i soggetti le rate e i versamenti
                // ==========================================================================================
                var idCondominiList = idCondomini.Select(item => item.Key).ToList();

                // rate
                var rateSoggetti = !groupByPersone ? _daoFactory.GetRataSoggettoDao().GetByEsercizioSoggetti(idEsercizio, null, idCondominiList, dataRate) : _daoFactory.GetRataSoggettoDao().GetByEsercizioPersone(idEsercizio, null, idCondominiList, dataRate);

                // soggetti
                IList<SoggettoCondominio> soggetti = null;
                IList<SoggettoCondominio> soggettiStampa = null;
                IList<Persona> persone = null;
                if (!groupByPersone)
                    soggetti = _daoFactory.GetSoggettoCondominioDao().GetAttiviByEsercizioSoggetti(esercizio, idCondominiList);
                else
                {
                    persone = _daoFactory.GetPersonaDao().GetAttiviByEsercizioSoggetti(esercizio, idCondominiList);
                    soggettiStampa = esercizio != null ? _daoFactory.GetSoggettoCondominioDao().GetAttiviByEsercizio(esercizio, dataFinale) : _daoFactory.GetSoggettoCondominioDao().GetAttiviByAzienda(modello.Azienda.ID);
                }

                // versamenti
                IList<VersamentoSoggetto> versamentiSoggetto;
                IList<VersamentiRate> versamentiRate;
                if (!groupByPersone)
                {
                    versamentiSoggetto = _daoFactory.GetVersamentoSoggettoDao().GetByEsercizioSoggetti(idEsercizio, idCondominiList);
                    versamentiRate = _daoFactory.GetVersamentiRateDao().GetByEsercizioSoggetti(idEsercizio, idCondominiList);
                }
                else
                {
                    versamentiSoggetto = _daoFactory.GetVersamentoSoggettoDao().GetByEsercizioPersone(idEsercizio, idCondominiList);
                    versamentiRate = _daoFactory.GetVersamentiRateDao().GetByEsercizioPersone(idEsercizio, idCondominiList);
                }

                DatiBancariCondomini bancaSollecito = null;
                if (idBanca != null)
                    bancaSollecito = _daoFactory.GetDatiBancariCondominiDao().Find(idBanca.Value, false);

                // ==========================================================================================
                //  Loop per i soggetti per generare i dati di stampa
                // ==========================================================================================
                foreach (var kvp in idCondomini)
                {
                    var id = kvp.Key;

                    try
                    {
                        SoggettoCondominio soggetto = null;
                        Persona persona = null;
                        if (soggetti != null)
                            soggetto = soggetti.FirstOrDefault(item => item.ID == kvp.Key) ?? _daoFactory.GetSoggettoCondominioDao().Find(id, false);
                        else if (persone != null)
                            persona = persone.FirstOrDefault(item => item.ID == kvp.Key) ?? _daoFactory.GetPersonaDao().Find(id, false);

                        if (persona == null && soggetto == null)
                        {
                            _log.ErrorFormat("Non trovata persona/soggetto - {0} - id:{1} - idCondomini:{2}", Utility.GetMethodDescription(), id, idEsercizio.GetValueOrDefault(), idCondomini != null ? string.Join(",", idCondomini.SelectMany(item => item.Key.ToString())) : "<NULL>");
                            continue;
                        }

                        var rateScadute = !groupByPersone ? rateSoggetti.Where(item => item.Soggetto.ID == kvp.Key).ToList() : rateSoggetti.Where(item => item.Soggetto.Persona.ID == kvp.Key).ToList();

                        // -----------------------------
                        // Calcolo importi
                        // -----------------------------
                        var importoScaduto = rateScadute.Sum(rata => rata.Importo);
                        var importoVersato = rateScadute.Sum(rata => rata.GetImportoVersato(dataVersamenti));

                        decimal importoVersatoSenzaRata;
                        IList<VersamentoSoggetto> altriVersamenti;
                        IList<VersamentiRate> altriVersamentiRate;
                        if (soggetto != null)
                        {
                            altriVersamenti = versamentiSoggetto.Where(item => item.Soggetto.ID == kvp.Key).ToList();
                            altriVersamentiRate = versamentiRate.Where(item => item.Versamento.Soggetto.ID == kvp.Key).ToList();
                            importoVersatoSenzaRata = altriVersamenti.Sum(versamento => versamento.Importo) - altriVersamentiRate.Sum(item => item.Importo);
                        }
                        else
                        {
                            altriVersamenti = versamentiSoggetto.Where(item => item.Soggetto.Persona.ID == kvp.Key).ToList();
                            altriVersamentiRate = versamentiRate.Where(item => item.Versamento.Soggetto.Persona.ID == kvp.Key).ToList();
                            importoVersatoSenzaRata = altriVersamenti.Sum(versamento => versamento.Importo) - altriVersamentiRate.Sum(item => item.Importo);
                        }

                        var importoDaSollecitare = importoScaduto - importoVersato - importoVersatoSenzaRata;

                        if (importoLimite == null || Math.Abs(importoDaSollecitare) >= importoLimite.Value)
                        {
                            if (persona == null)
                                persona = soggetto.Persona;
                            var condominio = soggetto != null ? soggetto.UnitaImmobiliare.GruppoStabileRiferimento.PalazzinaRiferimento.CondominioRiferimento : persona.SoggettiCondominio.Select(item => item.UnitaImmobiliare.GruppoStabileRiferimento.PalazzinaRiferimento.CondominioRiferimento).FirstOrDefault();

                            var recapito = _personaService.GetRecapito(persona, kvp.Value);

                            if (bancaSollecito == null)
                                bancaSollecito = condominio.DatiBancariPrincipale;

                            var testata = new TestataSollecitoDTO
                            {
                                Nominativo = getNominativoPresso(persona, soggetto, recapito),
                                Indirizzo = recapito != null ? recapito.GetIndirizzoCompleto() : string.Empty,
                                Cap = recapito.Cap,
                                Comune = recapito.ComuneDisplayName,
                                Titolo = Decodifica.Instance.GetElement("TitoloPersona", persona.Titolo).Descrizione,
                                ImportoCompetenza = importoCompetenza,
                                DataLettera = dataSollecito,
                                DataRate = dataRate.GetValueOrDefault(),
                                StampaProprietario = stampaProprietario,
                                GroupByPersona = groupByPersone,
                                OggettoLettera = string.IsNullOrEmpty(modello.Oggetto) ? string.Empty : modello.Oggetto.Trim(),
                                TestoLettera = formattaTestoLettera(condominio, bancaSollecito, string.IsNullOrEmpty(testoModelloLettera) ? modello.Testo : testoModelloLettera.Trim()),
                            };

                            if (soggetto != null)
                            {
                                testata.Id = soggetto.ID;
                                testata.IdSoggettoCondominio = soggetto.ID;
                                testata.IdPersona = soggetto.Persona.ID;
                                testata.IdUnitaImmobiliare = soggetto.UnitaImmobiliare.ID;
                                testata.Interno = soggetto.UnitaImmobiliare.InternoCompleto;
                                testata.Piano = soggetto.UnitaImmobiliare.Piano;
                                testata.Ordine = soggetto.UnitaImmobiliare.Ordine.GetValueOrDefault();
                                testata.DescrizioneUnitaImmobiliare = soggetto.UnitaImmobiliare.Descrizione;
                                testata.Subalterno = soggetto.UnitaImmobiliare.Subalterno;
                            }
                            else if (persona != null)
                            {
                                testata.Id = persona.ID;
                                testata.IdPersona = persona.ID;
                            }

                            var righeCondominio = condominio.IndirizzoCompleto.Split('&');
                            testata.DescrizioneCompletaCondominio = $"Condominio: {righeCondominio[0]}{Environment.NewLine}{righeCondominio[1]} - {righeCondominio[2]} - {righeCondominio[3]}";

                            // Se la stampa è per persona e viee richiesta la stampa per conoscenza al proprietario occorre leggere il soggettocondominio (soggettoStampa) bugid#8573
                            var soggettoStampa = soggetto;
                            if (soggettoStampa == null && persona != null)
                                soggettoStampa = soggettiStampa.Where(item => item.Persona.ID == persona.ID).OrderBy(item => item.UnitaImmobiliare.TipoUnitaImmobiliare.ID).FirstOrDefault();

                            if (stampaProprietario && soggettoStampa != null && soggettoStampa.Tipo == TipoSoggetto.Conduttore)
                            {
                                var proprietario = soggettoStampa.UnitaImmobiliare.GetProprietarioPrincipale(dataFinale) ??
                                                   soggettoStampa.UnitaImmobiliare.Proprietari.OrderByDescending(item => item.DataInizio.GetValueOrDefault()).FirstOrDefault();
                                if (proprietario != null)
                                    testata.NominativoProprietario = proprietario.DisplayName;

                                if (proprietario != null)
                                {
                                    var recapitoProprietario = _personaService.GetRecapito(proprietario.Persona, kvp.Value);
                                    if (recapitoProprietario != null)
                                    {
                                        testata.IndirizzoProprietario = recapitoProprietario.GetIndirizzoCompleto();
                                        testata.ComuneProprietario = recapitoProprietario.ComuneDisplayName;
                                        testata.CapProprietario = recapitoProprietario.Cap;
                                    }
                                }
                            }

                            if (recapito.Comune != null)
                                testata.Provincia = recapito.Comune.ProvinciaAppartenenza.Codice;

                            // ----------------------------------------------
                            //  Dettaglio Rate
                            // ----------------------------------------------
                            decimal importoTotaleDaVersare = 0;

                            // Rate con versamenti
                            foreach (var rata in rateScadute)
                            {
                                try
                                {
                                    var dettaglio = new DettaglioSollecitoDTO
                                    {
                                        Id = rata.ID,
                                        DataScadenza = rata.DataScadenza,
                                        IdTestataSollecito = testata.Id,
                                        ProgressivoRata = rata.PianoRatealeDettaglio?.Progressivo ?? rata.Progressivo,
                                        Importo = rata.Importo,
                                        ImportoPagato = rata.GetImportoVersato(dataVersamenti),
                                        CodiceRata = rata.ID,
                                        IdEsercizio = rata.Esercizio.ID,
                                        IdSoggetto = rata.Soggetto.ID,
                                        DescrizioneSoggetto = rata.Soggetto.DisplayName,
                                        DescrizioneEsercizio = rata.Esercizio.DisplayName
                                    };

                                    if (groupByPersone)
                                    {
                                        dettaglio.IdUnitaImmobiliare = rata.Soggetto.UnitaImmobiliare.ID;
                                        dettaglio.Interno = rata.Soggetto.UnitaImmobiliare.InternoCompleto;
                                        dettaglio.Piano = rata.Soggetto.UnitaImmobiliare.Piano;
                                        dettaglio.Ordine = rata.Soggetto.UnitaImmobiliare.Ordine.GetValueOrDefault();
                                        dettaglio.DescrizioneUnitaImmobiliare = rata.Soggetto.UnitaImmobiliare.TipoUnitaImmobiliare.Descrizione + " - " + rata.Soggetto.UnitaImmobiliare.Descrizione;
                                        dettaglio.Subalterno = rata.Soggetto.UnitaImmobiliare.Subalterno;
                                    }

                                    if (soggetto?.PercentualeRiferimento != null)
                                        dettaglio.PercentualePossesso = Convert.ToInt32(soggetto.PercentualeRiferimento.Value);
                                    dettaglio.ImportoDaVersare = dettaglio.Importo - dettaglio.ImportoPagato;

                                    if (rata.Versamenti.Count > 0)
                                        dettaglio.DataUltimoPagamento = IesiGenericCollections<VersamentiRate>.GetByIndex(rata.Versamenti, rata.Versamenti.Count - 1).Versamento.Data;

                                    testata.Dettagli.Add(dettaglio);
                                    importoTotaleDaVersare += dettaglio.ImportoDaVersare;
                                }
                                catch (Exception ex)
                                {
                                    _log.ErrorFormat("Errore inaspettato nel calcolo del sollecito per soggetto - DETTAGLIO RATE CON VERSAMENTI - {0} - soggetto:{1} - rata:{2}", ex, Utility.GetMethodDescription(), id, rata.ID);
                                    throw;
                                }
                            }

                            // Versamenti senza rate associate
                            // TODO: elaborare versamenti rate e versamentisoggetto per ottenere una lista dei versamenti fuori piano rateale
                            foreach (var versamento in altriVersamenti)
                            {
                                try
                                {
                                    var versamento1 = versamento;
                                    var importoPagato = versamento.Importo - altriVersamentiRate.Where(item => item.Versamento.ID == versamento1.ID).Sum(item => item.Importo);
                                    if (importoPagato > 0)
                                    {
                                        var dettaglio = new DettaglioSollecitoDTO
                                        {
                                            DataScadenza = DateTime.MaxValue,
                                            DataUltimoPagamento = versamento.Data,
                                            IdTestataSollecito = testata.Id,
                                            ImportoPagato = importoPagato,
                                            IdEsercizio = versamento.Esercizio.ID,
                                            IdSoggetto = versamento.Soggetto.ID,
                                            DescrizioneSoggetto = versamento.Soggetto.DisplayName,
                                            DescrizioneEsercizio = versamento.Esercizio.DisplayName,
                                            ImportoDaVersare = importoPagato * -1
                                        };

                                        if (groupByPersone)
                                        {
                                            dettaglio.IdUnitaImmobiliare = versamento.Soggetto.UnitaImmobiliare.ID;
                                            dettaglio.Interno = versamento.Soggetto.UnitaImmobiliare.InternoCompleto;
                                            dettaglio.Piano = versamento.Soggetto.UnitaImmobiliare.Piano;
                                            dettaglio.Ordine = versamento.Soggetto.UnitaImmobiliare.Ordine.GetValueOrDefault();
                                            dettaglio.DescrizioneUnitaImmobiliare = versamento.Soggetto.UnitaImmobiliare.TipoUnitaImmobiliare.Descrizione + " - " + versamento.Soggetto.UnitaImmobiliare.Descrizione;
                                            dettaglio.Subalterno = versamento.Soggetto.UnitaImmobiliare.Subalterno;
                                        }

                                        if (soggetto?.PercentualeRiferimento != null)
                                            dettaglio.PercentualePossesso = Convert.ToInt32(soggetto.PercentualeRiferimento.Value);

                                        testata.Dettagli.Add(dettaglio);
                                        importoTotaleDaVersare -= dettaglio.ImportoPagato;
                                    }
                                }
                                catch (Exception ex)
                                {
                                    _log.ErrorFormat("Errore inaspettato nel calcolo del sollecito per soggetto - VERSAMENTO SENZA RATE ASSOCIATE - {0} - Id:{1} - versamento:{2}", ex, Utility.GetMethodDescription(), id, versamento.ID);
                                    throw;
                                }
                            }

                            testata.ImportoTotaleDaVersare = importoTotaleDaVersare;
                            testata.TipoIndirizzo = kvp.Value;
                            solleciti.Add(testata);
                            
                            // ================================================================================
                            //  Se richiesto aggiungo per i proprietari le rate di conduzione
                            // ================================================================================
                            if (sollecitaProprietarioConduzione)
                            {
                                if (soggetto != null)
                                {
                                    var conduttori = soggetto.UnitaImmobiliare.Conduttori;
                                    if (conduttori.Count > 0)
                                    {
                                        var idConduttori = new List<int>(conduttori.Count);
                                        idConduttori.AddRange(conduttori.Select(soggettoCondominio => soggettoCondominio.ID));
                                        var rateConduttori = _rateService.GetRataByEsercizioSoggetti(idEsercizio, idConduttori, dataRate, false);
                                        var versamentiConduttori = _versamentiService.GetVersamentiByEsercizioSoggetti(idEsercizio, idConduttori);

                                        var importoCompetenzaConduzione = rateConduttori.Sum(item => item.Importo.GetValueOrDefault());
                                        var importoVersatoConduzione = versamentiConduttori.Sum(item => item.Importo);
                                        testata.ImportoCompetenza += importoCompetenzaConduzione;
                                        testata.ImportoTotaleDaVersare += (importoCompetenzaConduzione - importoVersatoConduzione);

                                        // Dettaglio rate
                                        IList<VersamentoSoggetto> versamentiElaborati = new List<VersamentoSoggetto>();
                                        foreach (var rataSoggettoDTO in rateConduttori)
                                        {
                                            var dettaglio = new DettaglioSollecitoDTO
                                            {
                                                Id = rataSoggettoDTO.ID,
                                                DataScadenza = rataSoggettoDTO.DataScadenza,
                                                IdTestataSollecito = testata.Id,
                                                ProgressivoRata = rataSoggettoDTO.Progressivo,
                                                Importo = rataSoggettoDTO.Importo.GetValueOrDefault(),
                                                ImportoPagato = rataSoggettoDTO.ImportoPagato.GetValueOrDefault(),
                                                CodiceRata = rataSoggettoDTO.ID,
                                                IdEsercizio = rataSoggettoDTO.IdEsercizio,
                                                IdSoggetto = rataSoggettoDTO.IdSoggettoCondominio,
                                                DescrizioneSoggetto = rataSoggettoDTO.DescrizioneSoggettoCondominio,
                                                DescrizioneEsercizio = rataSoggettoDTO.DescrizioneEsercizio
                                            };

                                            if (groupByPersone)
                                            {
                                                dettaglio.IdUnitaImmobiliare = rataSoggettoDTO.IdUnitaImmobiliare;
                                                dettaglio.Ordine = rataSoggettoDTO.OrdineUnitaImmobiliare;
                                                dettaglio.DescrizioneUnitaImmobiliare = rataSoggettoDTO.DescrizioneUnitaImmobiliare;
                                                dettaglio.Subalterno = rataSoggettoDTO.Subalterno;
                                            }

                                            if (soggetto?.PercentualeRiferimento != null)
                                                dettaglio.PercentualePossesso = Convert.ToInt32(soggetto.PercentualeRiferimento.Value);
                                            dettaglio.ImportoDaVersare = dettaglio.Importo - dettaglio.ImportoPagato;

                                            var rata = _daoFactory.GetRataSoggettoDao().Find(rataSoggettoDTO.ID, false);
                                            if (rata != null && rata.Versamenti.Count > 0)
                                            {
                                                foreach (var rateVersamenti in rata.Versamenti)
                                                    versamentiElaborati.Add(rateVersamenti.Versamento);

                                                dettaglio.DataUltimoPagamento = IesiGenericCollections<VersamentiRate>.GetByIndex(rata.Versamenti, rata.Versamenti.Count - 1).Versamento.Data;
                                            }

                                            testata.Dettagli.Add(dettaglio);
                                        }
                                        
                                        // Versamenti fuori piano rateale
                                        foreach (var versamentoSoggetto in versamentiConduttori)
                                        {
                                            if (!versamentiElaborati.Contains(versamentoSoggetto) && versamentoSoggetto.Importo > 0)
                                            {
                                                var dettaglioVersamento = new DettaglioSollecitoDTO
                                                {
                                                    DataScadenza = DateTime.MaxValue,
                                                    DataUltimoPagamento = versamentoSoggetto.Data,
                                                    IdTestataSollecito = testata.Id,
                                                    ImportoPagato = versamentoSoggetto.Importo,
                                                    IdEsercizio = versamentoSoggetto.Esercizio.ID,
                                                    IdSoggetto = versamentoSoggetto.Soggetto.ID,
                                                    DescrizioneSoggetto = versamentoSoggetto.Soggetto.DisplayName,
                                                    DescrizioneEsercizio = versamentoSoggetto.Esercizio.DisplayName,
                                                    ImportoDaVersare = versamentoSoggetto.Importo * -1
                                                };

                                                if (groupByPersone)
                                                {
                                                    dettaglioVersamento.IdUnitaImmobiliare = versamentoSoggetto.Soggetto.UnitaImmobiliare.ID;
                                                    dettaglioVersamento.Interno = versamentoSoggetto.Soggetto.UnitaImmobiliare.InternoCompleto;
                                                    dettaglioVersamento.Piano = versamentoSoggetto.Soggetto.UnitaImmobiliare.Piano;
                                                    dettaglioVersamento.Ordine = versamentoSoggetto.Soggetto.UnitaImmobiliare.Ordine.GetValueOrDefault();
                                                    dettaglioVersamento.DescrizioneUnitaImmobiliare = versamentoSoggetto.Soggetto.UnitaImmobiliare.TipoUnitaImmobiliare.Descrizione + " - " + versamentoSoggetto.Soggetto.UnitaImmobiliare.Descrizione;
                                                    dettaglioVersamento.Subalterno = versamentoSoggetto.Soggetto.UnitaImmobiliare.Subalterno;
                                                }

                                                testata.Dettagli.Add(dettaglioVersamento);
                                            }
                                        }
                                    }

                                }
                            }

                            // ================================================================
                            // Creo gli oggetti sollecito se richiesto
                            // ================================================================
                            if (storico)
                            {
                                var esercizioSollecito = (esercizio ?? _daoFactory.GetEsercizioDao().GetEsercizioCompetenza(condominio, DateTime.Today)) ?? _esercizioService.GetUltimoEsercizioOrdinario(condominio.ID);
                                if (esercizioSollecito != null)
                                {
                                    Sollecito sollecito;

                                    var testoLettera = testoModelloLettera;
                                    if (string.IsNullOrEmpty(testoLettera))
                                        testoLettera = modello.Testo;
                                    if (!string.IsNullOrEmpty(testoLettera))
                                        testoLettera = testoLettera.Trim();
                                    if (soggetto != null)
                                    {
                                        sollecito = new Sollecito(esercizioSollecito, soggetto, dataSollecito, dataRate.GetValueOrDefault(), importoLimite.GetValueOrDefault(), testata.ImportoTotaleDaVersare, bancaSollecito, modello.Oggetto, testoLettera)
                                        {
                                            ImportoCompetenza = importoCompetenza,
                                            TipoIndirizzo = kvp.Value,
                                            StampaProprietario = stampaProprietario,
                                            GroupByPersona = groupByPersone
                                        };
                                    }
                                    else
                                    {
                                        sollecito = new Sollecito(esercizioSollecito, persona, dataSollecito, dataRate.GetValueOrDefault(), importoLimite.GetValueOrDefault(), testata.ImportoTotaleDaVersare, bancaSollecito, modello.Oggetto, testoLettera)
                                        {
                                            ImportoCompetenza = importoCompetenza,
                                            TipoIndirizzo = kvp.Value,
                                            StampaProprietario = stampaProprietario,
                                            GroupByPersona = groupByPersone
                                        };
                                    }

                                    foreach (var dett in testata.Dettagli)
                                    {
                                        var dettaglio = new DettaglioSollecito(sollecito, dett.Importo, dett.ImportoDaVersare, dett.ImportoPagato)
                                        {
                                            DataUltimoPagamento = dett.DataUltimoPagamento
                                        };

                                        if (dett.DataScadenza != DateTime.MaxValue)
                                            dettaglio.DataScadenzaRata = dett.DataScadenza;

                                        if (dett.CodiceRata != null)
                                            dettaglio.Rata = rateSoggetti.FirstOrDefault(item => item.ID == dett.CodiceRata) ?? _daoFactory.GetRataSoggettoDao().GetById(dett.CodiceRata.Value, false);
                                    }
                                    listaSolleciti.Add(sollecito);
                                    _daoFactory.GetSollecitoDao().SaveOrUpdate(sollecito);
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        _log.ErrorFormat("Errore inaspettato nel calcolo del sollecito per soggetto - {0} - esercizio:{1} - soggetto:{2}", ex, Utility.GetMethodDescription(), idEsercizio, id);
                        throw;
                    }
                }

                // ================================================================================================================
                // Rimuovo eventuali dettagli con importo a 0
                // ================================================================================================================
                foreach (var testataSollecitoDTO in solleciti)
                {
                    var dettagliDaRimuovere = testataSollecitoDTO.Dettagli.Where(dettaglioSollecitoDTO => dettaglioSollecitoDTO.Importo == 0 && dettaglioSollecitoDTO.ImportoDaVersare == 0 && dettaglioSollecitoDTO.ImportoPagato == 0).ToList();

                    foreach (var dettaglioSollecitoDTO in dettagliDaRimuovere)
                        testataSollecitoDTO.Dettagli.Remove(dettaglioSollecitoDTO);
                }

                // ================================================================================================================
                // Creo i movimenti di addebito - una testata per ogni Esercizio (possibile solo se è stato richiesto lo STORICO)
                // ================================================================================================================
                try
                {
                    if (importoCompetenza > 0)
                    {
                        var sollecitiPerEsercizio = listaSolleciti.GroupBy(item => item.Esercizio);

                        foreach (var sollecitiEsercizio in sollecitiPerEsercizio)
                        {
                            var esercizioAddebito = sollecitiEsercizio.Key;
                            Conto contoAddebito = null;
                            SottoConto sottoContoAddebito = null;
                            if (idConto != null)
                            {
                                contoAddebito = _daoFactory.GetContoDao().Find(idConto.Value, false);
                                if (idSottoConto != null)
                                    sottoContoAddebito = _daoFactory.GetSottoContoDao().GetById(idSottoConto.Value, false);
                            }
                            if (contoAddebito == null)
                            {
                                sottoContoAddebito = _daoFactory.GetSottoContoDao().GetAddebitoCompetenzeByEsercizio(esercizioAddebito.ID, esercizioAddebito.CondominioRiferimento.ID);
                                if (sottoContoAddebito != null)
                                    contoAddebito = sottoContoAddebito.ContoRiferimento;
                            }

                            if (contoAddebito != null && esercizioAddebito != null)
                            {
                                var testata = _movimentiContabileService.SetMovimentiSollecito(esercizioAddebito, sollecitiEsercizio.ToList(), dataRegistrazioneContabile.GetValueOrDefault(), contoAddebito, sottoContoAddebito);

                                // -------------------------------------------
                                // Genero il protocollo di archiviazione
                                // -------------------------------------------
                                var progressivo = _protocolloService.GetProgressivo(TipoProtocollo.Fattura, testata.EsercizioRiferimento.DataApertura.GetValueOrDefault().Year, testata.EsercizioRiferimento.CondominioRiferimento);
                                if (progressivo.Progressivo != null)
                                {
                                    testata.NumeroProtocollo = progressivo.Progressivo.Value;
                                    testata.AnnoArchiviazioneOttica = testata.EsercizioRiferimento.DataApertura.GetValueOrDefault().Year;
                                }
                                else
                                {
                                    _log.ErrorFormat("Errore imprevisto nella generazione del protocollo di archiviazione - {0} - esercizio:{1} - testata:{2} - message:{3}", Utility.GetMethodDescription(), esercizioAddebito.ID, testata.ID, progressivo.Message);
                                }

                            }

                        }
                    }
                }
                catch (Exception ex)
                {
                    _log.ErrorFormat("Errore inaspettato nel calcolo del sollecito per soggetto - CREAZIONE MOVIMENTI CONTABILI - {0} - esercizio:{1}", ex, Utility.GetMethodDescription(), idEsercizio);
                    throw;
                }

                return solleciti;

            }
            catch (Exception ex)
            {
                _log.ErrorFormat("Errore inaspettato nel calcolo del sollecito per soggetto - CREAZIONE MOVIMENTI CONTABILI - {0} - esercizio:{1} - groupByPersone:{2} - dataRate:{3} - dataVersamenti:{4} - importoLimite:{5} - importoCompetenza:{6} - dataSollecito:{7} - stampaProprietario:{8} - idBanca:{9} - idModelloLettera:{10} - dataRegistrazioneContabile:{11} - idConto:{12} - idSottoConto:{13} - storico:{14} - esercizio:{15}", ex, Utility.GetMethodDescription(), idEsercizio.GetValueOrDefault(), groupByPersone, dataRate, dataVersamenti, importoLimite, importoCompetenza, dataSollecito, stampaProprietario, idBanca, idModelloLettera, dataRegistrazioneContabile, idConto, idSottoConto, storico, idEsercizio);
                throw;
            }

        }
Пример #53
0
        internal static Mapping <T> GetEntityMapping <T>(
            DbContext context,
            Type queryClass,
            Dictionary <Type, PropertyInfo[]> allowedPropertyMapping
            )
        {
            var allowedProperties = new HashSet <PropertyInfo>(
                allowedPropertyMapping.SelectMany(x => x.Value));

            var inParam        = Expression.Parameter(typeof(T), "x");
            var inMappingPairs = new List <Tuple <MemberInfo, Expression> >();

            var outParam        = Expression.Parameter(queryClass, "x");
            var outMappingPairs = new List <Tuple <MemberInfo, Expression> >();

            var usedProperties = new Dictionary <string, Func <T, object> >();
            var pkColumnName   = EFHelper.GetKeyProperty(context, queryClass);

            if (pkColumnName == null)
            {
                throw new NotSupportedException($"{queryClass.Name} should have PK set");
            }

            var columnNamesDict = EFHelper.GetColumnNames(context, queryClass);
            var members         = typeof(T).GetProperties().Cast <MemberInfo>().Union(typeof(T).GetFields());

            foreach (var member in members)
            {
                var memberType = member.MemberType == MemberTypes.Property ?
                                 ((PropertyInfo)member).PropertyType :
                                 ((FieldInfo)member).FieldType;

                var baseType = Nullable.GetUnderlyingType(memberType) ?? memberType;
                if (!allowedPropertyMapping.TryGetValue(baseType, out var allowedMappedProps))
                {
                    throw new NotSupportedException("Not supported property type");
                }

                var mapProperty = allowedMappedProps.FirstOrDefault(x => allowedProperties.Contains(x));
                if (mapProperty == null)
                {
                    throw new NotSupportedException("Too complex object");
                }

                Expression inExp = Expression.MakeMemberAccess(inParam, member);
                if (mapProperty.PropertyType != memberType)
                {
                    inExp = Expression.Convert(inExp, mapProperty.PropertyType);
                }

                inMappingPairs.Add(new Tuple <MemberInfo, Expression>(mapProperty, inExp));

                Expression outExp = Expression.MakeMemberAccess(outParam, mapProperty);
                if (mapProperty.PropertyType != memberType)
                {
                    outExp = Expression.Convert(outExp, memberType);
                }

                outMappingPairs.Add(new Tuple <MemberInfo, Expression>(member, outExp));

                allowedProperties.Remove(mapProperty);

                usedProperties.Add(
                    columnNamesDict[mapProperty],
                    (Func <T, object>)(Expression.Lambda(
                                           Expression.Convert(inExp, typeof(object)),
                                           inParam
                                           ).Compile()));
            }

            var inCtor = queryClass.GetConstructor(new Type[] { });
            var inNew  = Expression.New(inCtor);
            var inBind = Expression.MemberInit(inNew,
                                               inMappingPairs.Select(x => Expression.Bind(x.Item1, x.Item2)));
            // var inExpression = Expression.Lambda(inBind, inParam);

            var outCtor = typeof(T).GetConstructors(
                BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
            var        emptyCtor = outCtor.FirstOrDefault(x => x.GetParameters().Length == 0);
            Expression outExpression;

            if (emptyCtor != null)
            {
                var outNew  = Expression.New(emptyCtor);
                var outBind = Expression.MemberInit(outNew,
                                                    outMappingPairs.Select(x => Expression.Bind(x.Item1, x.Item2)));
                outExpression = Expression.Lambda(outBind, outParam);
            }
            else
            {
                var outNew = Expression.New(
                    outCtor.First(),
                    outMappingPairs.Select(x => x.Item2).ToArray(),
                    outMappingPairs.Select(x => x.Item1).ToArray());
                outExpression = Expression.Lambda(outNew, outParam);
            }

            return(new Mapping <T>()
            {
                UserProperties = usedProperties,
                OutExpression = outExpression,
                KeyColumnName = pkColumnName
            });
        }
Пример #54
0
 /// <summary>
 /// Find all ranges of the specified strings.
 /// </summary>
 /// <param name="words">Must be a dictionary of strings (keys) to search for and
 /// whether these strings represent whole words (true or false value).</param>
 /// <returns></returns>
 private IEnumerable<int[]> FindWordRanges(Dictionary<string, bool> words)
     => words.SelectMany(word => FindWordRanges(word.Key, word.Value));
Пример #55
0
 private bool _languageNamesExists(string languageName)
 {
     return(_languages.SelectMany(t => _languages).Any(languages => languages.Key == languageName));
 }
Пример #56
0
 public PivotedRows GroupAndTotal(TickCounter tickCounter, PivotedRows pivotedRows)
 {
     IDictionary<IList<Tuple<PropertyPath, PivotKey, object>>, List<GroupedRow>> allReportRows
         = new Dictionary<IList<Tuple<PropertyPath, PivotKey, object>>, List<GroupedRow>>();
     var groupColumns = ViewInfo.DisplayColumns
         .Where(col => TotalOperation.GroupBy == col.ColumnSpec.TotalOperation)
         .Select(col => col.ColumnDescriptor)
         .ToArray();
     var pivotOnColumns = ViewInfo.DisplayColumns
         .Where(col => TotalOperation.PivotKey == col.ColumnSpec.TotalOperation)
         .Select(col => col.ColumnDescriptor)
         .ToArray();
     var allInnerPivotKeys = new HashSet<PivotKey>();
     var allPivotKeys = new Dictionary<PivotKey, PivotKey>();
     foreach (var rowItem in pivotedRows.RowItems)
     {
         allInnerPivotKeys.UnionWith(rowItem.PivotKeys);
         IList<Tuple<PropertyPath, PivotKey, object>> groupKey = new List<Tuple<PropertyPath, PivotKey, object>>();
         foreach (var column in groupColumns)
         {
             var pivotColumn = GetPivotColumn(column);
             if (null == pivotColumn)
             {
                 groupKey.Add(new Tuple<PropertyPath, PivotKey, object>(column.PropertyPath, null,
                     column.GetPropertyValue(rowItem, null)));
             }
             else
             {
                 foreach (var pivotKey in GetPivotKeys(pivotColumn.PropertyPath, new []{rowItem}))
                 {
                     if (!pivotKey.Contains(pivotColumn.PropertyPath))
                     {
                         continue;
                     }
                     groupKey.Add(new Tuple<PropertyPath, PivotKey, object>(column.PropertyPath, pivotKey, column.GetPropertyValue(rowItem, pivotKey)));
                 }
             }
         }
         groupKey = ImmutableList.ValueOf(groupKey);
         var pivotOnKeyValues = new List<KeyValuePair<PropertyPath, object>>();
         foreach (var column in pivotOnColumns)
         {
             var pivotColumn = GetPivotColumn(column);
             if (null == pivotColumn)
             {
                 pivotOnKeyValues.Add(new KeyValuePair<PropertyPath, object>(column.PropertyPath,
                     column.GetPropertyValue(rowItem, null)));
             }
             else
             {
                 Trace.TraceWarning("Unable to pivot on column {0} because it is already pivoted.", pivotColumn.PropertyPath); // Not L10N
             }
         }
         var pivotOnKey = PivotKey.GetPivotKey(allPivotKeys, pivotOnKeyValues);
         List<GroupedRow> rowGroups;
         if (!allReportRows.TryGetValue(groupKey, out rowGroups))
         {
             rowGroups = new List<GroupedRow>();
             allReportRows.Add(groupKey, rowGroups);
         }
         var rowGroup = rowGroups.FirstOrDefault(rg => !rg.ContainsKey(pivotOnKey));
         if (null == rowGroup)
         {
             rowGroup = new GroupedRow();
             rowGroups.Add(rowGroup);
         }
         rowGroup.AddInnerRow(pivotOnKey, rowItem);
     }
     var outerPivotKeys = allPivotKeys.Keys.Where(key=>key.Length == pivotOnColumns.Length).ToArray();
     var pivotKeyComparer = PivotKey.GetComparer(ViewInfo.DataSchema);
     Array.Sort(outerPivotKeys, pivotKeyComparer);
     var innerPivotKeys = allInnerPivotKeys.ToArray();
     Array.Sort(innerPivotKeys, pivotKeyComparer);
     var reportItemProperties = new List<PropertyDescriptor>();
     var propertyNames = new HashSet<string>();
     foreach (var displayColumn in ViewInfo.DisplayColumns)
     {
         if (displayColumn.ColumnSpec.Hidden)
         {
             continue;
         }
         var totalOperation = displayColumn.ColumnSpec.TotalOperation;
         if (TotalOperation.GroupBy == totalOperation)
         {
             var pivotColumn = GetPivotColumn(displayColumn.ColumnDescriptor);
             if (null == pivotColumn)
             {
                 string propertyName = MakeUniqueName(propertyNames, displayColumn.PropertyPath);
                 reportItemProperties.Add(new GroupedPropertyDescriptor(propertyName, displayColumn, null));
             }
             else
             {
                 foreach (var innerPivotKey in innerPivotKeys)
                 {
                     string propertyName = MakeUniqueName(propertyNames, displayColumn.PropertyPath);
                     reportItemProperties.Add(new GroupedPropertyDescriptor(propertyName, displayColumn, innerPivotKey));
                 }
             }
         }
     }
     foreach (var outerPivotKey in outerPivotKeys)
     {
         foreach (var displayColumn in ViewInfo.DisplayColumns)
         {
             if (displayColumn.ColumnSpec.Hidden)
             {
                 continue;
             }
             if (TotalOperation.PivotValue == displayColumn.ColumnSpec.TotalOperation || TotalOperation.PivotKey == displayColumn.ColumnSpec.TotalOperation)
             {
                 var pivotColumn = GetPivotColumn(displayColumn.ColumnDescriptor);
                 if (null == pivotColumn)
                 {
                     string propertyName = MakeUniqueName(propertyNames, displayColumn.PropertyPath);
                     reportItemProperties.Add(new GroupedPropertyDescriptor(propertyName, outerPivotKey, displayColumn, null));
                 }
                 else
                 {
                     foreach (var innerPivotKey in allInnerPivotKeys)
                     {
                         string propertyName = MakeUniqueName(propertyNames, displayColumn.PropertyPath);
                         reportItemProperties.Add(new GroupedPropertyDescriptor(propertyName, outerPivotKey, displayColumn, innerPivotKey));
                     }
                 }
             }
         }
     }
     return new PivotedRows(allReportRows.SelectMany(entry=>entry.Value.Select(
         reportRow=>new RowItem(reportRow))), 
         new PropertyDescriptorCollection(reportItemProperties.ToArray()));
 }
        private Dictionary <long, FinalBuffs>[] GetBoonsForPlayers(List <Player> playerList, Player player)
        {
            Dictionary <long, FinalBuffs>[] uptimesByPhase =
                new Dictionary <long, FinalBuffs> [_statistics.Phases.Count];

            for (int phaseIndex = 0; phaseIndex < _statistics.Phases.Count; phaseIndex++)
            {
                PhaseData phase         = _statistics.Phases[phaseIndex];
                long      fightDuration = phase.End - phase.Start;

                Dictionary <Player, BoonDistribution> boonDistributions = new Dictionary <Player, BoonDistribution>();
                foreach (Player p in playerList)
                {
                    boonDistributions[p] = p.GetBoonDistribution(_log, phaseIndex);
                }

                HashSet <Boon> boonsToTrack = new HashSet <Boon>(boonDistributions.SelectMany(x => x.Value).Select(x => Boon.BoonsByIds[x.Key]));

                Dictionary <long, FinalBuffs> final =
                    new Dictionary <long, FinalBuffs>();

                foreach (Boon boon in boonsToTrack)
                {
                    long totalGeneration       = 0;
                    long totalOverstack        = 0;
                    long totalWasted           = 0;
                    long totalUnknownExtension = 0;
                    long totalExtension        = 0;
                    long totalExtended         = 0;
                    bool hasGeneration         = false;
                    foreach (BoonDistribution boons in boonDistributions.Values)
                    {
                        if (boons.ContainsKey(boon.ID))
                        {
                            hasGeneration          = hasGeneration || boons.HasSrc(boon.ID, player.AgentItem);
                            totalGeneration       += boons.GetGeneration(boon.ID, player.AgentItem);
                            totalOverstack        += boons.GetOverstack(boon.ID, player.AgentItem);
                            totalWasted           += boons.GetWaste(boon.ID, player.AgentItem);
                            totalUnknownExtension += boons.GetUnknownExtension(boon.ID, player.AgentItem);
                            totalExtension        += boons.GetExtension(boon.ID, player.AgentItem);
                            totalExtended         += boons.GetExtended(boon.ID, player.AgentItem);
                        }
                    }

                    if (hasGeneration)
                    {
                        FinalBuffs uptime = new FinalBuffs();
                        final[boon.ID] = uptime;
                        if (boon.Type == Boon.BoonType.Duration)
                        {
                            uptime.Generation      = Math.Round(100.0 * totalGeneration / fightDuration / playerList.Count, 2);
                            uptime.Overstack       = Math.Round(100.0 * (totalOverstack + totalGeneration) / fightDuration / playerList.Count, 2);
                            uptime.Wasted          = Math.Round(100.0 * (totalWasted) / fightDuration / playerList.Count, 2);
                            uptime.UnknownExtended = Math.Round(100.0 * (totalUnknownExtension) / fightDuration / playerList.Count, 2);
                            uptime.ByExtension     = Math.Round(100.0 * (totalExtension) / fightDuration / playerList.Count, 2);
                            uptime.Extended        = Math.Round(100.0 * (totalExtended) / fightDuration / playerList.Count, 2);
                        }
                        else if (boon.Type == Boon.BoonType.Intensity)
                        {
                            uptime.Generation      = Math.Round((double)totalGeneration / fightDuration / playerList.Count, 2);
                            uptime.Overstack       = Math.Round((double)(totalOverstack + totalGeneration) / fightDuration / playerList.Count, 2);
                            uptime.Wasted          = Math.Round((double)(totalWasted) / fightDuration / playerList.Count, 2);
                            uptime.UnknownExtended = Math.Round((double)(totalUnknownExtension) / fightDuration / playerList.Count, 2);
                            uptime.ByExtension     = Math.Round((double)(totalExtension) / fightDuration / playerList.Count, 2);
                            uptime.Extended        = Math.Round((double)(totalExtended) / fightDuration / playerList.Count, 2);
                        }
                    }
                }

                uptimesByPhase[phaseIndex] = final;
            }

            return(uptimesByPhase);
        }
Пример #58
0
        static void Main(string[] args)
        {
            var assemblyDictionary = new Dictionary<int, Assembly>()
            {
                { 1, Assembly.GetAssembly(typeof(Certification.Chapter1.Objective1_1.Threads.Listing_1_1)) },
                { 2 , Assembly.GetAssembly(typeof(Certification.Chapter2.Objective2_1.Listing_2_1)) },
                { 3, Assembly.GetAssembly(typeof(Chapter3.Objective1.Listing_3_6)) }
            };

            var typeDictionary = new Dictionary<int, IEnumerable<Type>>();
            foreach (var kvp in assemblyDictionary)
            {
                typeDictionary.Add(kvp.Key, kvp.Value.GetTypes()
                      .Where(type => type != typeof(IRunnable) && typeof(IRunnable).IsAssignableFrom(type)));
            }

            while (true)
            {
                Console.WriteLine("Enter the listing number:");
                var input = Console.ReadLine();

                bool isListing = Regex.IsMatch(input, listingRegExp);
                bool isChapter = Regex.IsMatch(input, chapterRegExp);

                if (isChapter)
                {
                    IEnumerable<Type> listings;
                    var chapterNumber = int.Parse(input);

                    if (typeDictionary.TryGetValue(chapterNumber, out listings))
                    {
                        Console.WriteLine("Available listing are:");
                        var listingNames = listings.Select(l => l.Name.Replace(typePrefix, string.Empty).Replace("_", "."));

                        foreach (var listing in listings.OrderBy(l => GetListingNumber(l)))
                        {
                            var displayName = listing.Name.Replace(typePrefix, string.Empty).Replace("_", ".");
                            var listingAttribute = (ListingAttribute)Attribute.GetCustomAttribute(listing, typeof(ListingAttribute));

                            if (listingAttribute != null)
                            {
                                displayName += " - " + listingAttribute.Description;
                            }

                            Console.WriteLine(displayName);
                        }
                    }
                    else
                    {
                        Console.WriteLine("Chapter " + input + " is unknown.");
                    }
                }
                else if (isListing)
                {
                    input = input.Replace('.', '_');

                    var type = typeDictionary.SelectMany(kvp => kvp.Value).FirstOrDefault(t => t.Name == typePrefix + input);

                    if (type == null)
                    {
                        Console.WriteLine("Unknown listing {0}", typePrefix + input);
                    }
                    else
                    {
                        var runnable = (IRunnable)(type.GetConstructor(new Type[0]).Invoke(new object[0]));
                        var listingAttribute = (ListingAttribute)Attribute.GetCustomAttribute(type, typeof(ListingAttribute));

                        if (listingAttribute != null)
                        {
                            Console.WriteLine("Running listing \"" + listingAttribute.Description + "\"");
                            Console.WriteLine();
                        }
                        runnable.Run();
                        Console.WriteLine("_______________________________________________________");
                    }
                }
                else if (input == "0" || input == String.Empty)
                {
                    Console.WriteLine("Bye bye pov' type");
                    Thread.Sleep(500);
                    return;
                }
            }
        }
Пример #59
0
 public void PostTraceReconciliation(Dictionary <Guid, List <ISerializable> > orphanedSerializables)
 {
     Assert.AreEqual(orphanedSerializables.SelectMany(kvp => kvp.Value).Count(), ExpectedOrphanCount);
 }
Пример #60
0
        public void NonSatisfiedImports()
        {
            var lockKey = new DatasetLockKey();
            var datasetLock = new Mock<ITrackDatasetLocks>();
            {
                datasetLock.Setup(d => d.LockForReading())
                    .Returns(lockKey)
                    .Verifiable();
                datasetLock.Setup(d => d.RemoveReadLock(It.IsAny<DatasetLockKey>()))
                    .Callback<DatasetLockKey>(key => Assert.AreSame(lockKey, key))
                    .Verifiable();
            }

            var groups = new Dictionary<GroupCompositionId, IEnumerable<GroupImportDefinition>>
                {
                    {
                        new GroupCompositionId(),
                        new List<GroupImportDefinition>
                            {
                                GroupImportDefinition.CreateDefinition(
                                    "a",
                                    new GroupRegistrationId("a"),
                                    null,
                                    Enumerable.Empty<ImportRegistrationId>()),
                                GroupImportDefinition.CreateDefinition(
                                    "b",
                                    new GroupRegistrationId("a"),
                                    null,
                                    Enumerable.Empty<ImportRegistrationId>()),
                            }
                    },
                    {
                        new GroupCompositionId(),
                        new List<GroupImportDefinition>
                            {
                                GroupImportDefinition.CreateDefinition(
                                    "c",
                                    new GroupRegistrationId("c"),
                                    null,
                                    Enumerable.Empty<ImportRegistrationId>()),
                                GroupImportDefinition.CreateDefinition(
                                    "d",
                                    new GroupRegistrationId("c"),
                                    null,
                                    Enumerable.Empty<ImportRegistrationId>()),
                            }
                    },
                };
            var storage = new Mock<IStoreGroupsAndConnections>();
            {
                storage.Setup(s => s.Groups())
                    .Returns(groups.Keys);
                storage.Setup(s => s.UnsatisfiedImports(It.IsAny<GroupCompositionId>()))
                    .Returns<GroupCompositionId>(id => groups[id]);
            }

            var commands = new CompositionCommands(datasetLock.Object, storage.Object);
            var task = commands.NonSatisfiedImports(false);
            var results = task.Result;
            Assert.That(
                results,
                Is.EquivalentTo(
                    groups.SelectMany(p => p.Value.Select(v => new Tuple<GroupCompositionId, GroupImportDefinition>(p.Key, v)))));

            datasetLock.Verify(d => d.LockForReading(), Times.Once());
            datasetLock.Verify(d => d.RemoveReadLock(It.IsAny<DatasetLockKey>()), Times.Once());
        }