Beispiel #1
0
        public Dictionary<string, decimal> GetTotalFlowPerCategoriesForMonth(DateTime month)
        {
            Dictionary<string, decimal> categoryTotals = new Dictionary<string, decimal>
            {
                {"Total Expenses", GetTotalExpenseForMonth(month)}
            };

            categoryTotals.AddRange(_expenseService.GetAllCategoryTotals(month));

            categoryTotals.Add("Total Income", GetTotalIncomeForMonth(month));
            foreach (var totalIncomeByCategory in _incomeService.GetTotalIncomeByCategories(month))
            {
                if (categoryTotals.ContainsKey(totalIncomeByCategory.Key))
                {
                    var placeholder = categoryTotals[totalIncomeByCategory.Key];
                    categoryTotals.Remove(totalIncomeByCategory.Key);
            #warning Verify that part.. >.<
                    categoryTotals.Add(string.Format("{0} - Expense", totalIncomeByCategory.Key), placeholder);
                    categoryTotals.Add(string.Format("{0} - Income", totalIncomeByCategory.Key), placeholder);
                }
                else
                {
                    categoryTotals.Add(totalIncomeByCategory.Key, totalIncomeByCategory.Value);
                }
            }

            return categoryTotals;
        }
Beispiel #2
0
        public Dictionary<string, double> GetTotalsOfMonthByCategory()
        {
            Dictionary<string, double> categoryTotals = new Dictionary<string, double>();

            categoryTotals.Add("Total Expenses", GetMonthesExpenseTotal());
            categoryTotals.AddRange(ExpenseHandler.GetAllCategoryTotals(MonthRepresented));

            categoryTotals.Add("Total Income", GetMonthesIncomeTotal());
            foreach (KeyValuePair<string, double> curIncomeCatTotal in IncomeHandler.GetAllCategoryTotals(MonthRepresented))
            {
                if (categoryTotals.ContainsKey(curIncomeCatTotal.Key))
                {
                    double placeholder = categoryTotals[curIncomeCatTotal.Key];
                    categoryTotals.Remove(curIncomeCatTotal.Key);
                    categoryTotals.Add(string.Format("{0} - {1}", curIncomeCatTotal.Key, "Expense"), placeholder);
                    categoryTotals.Add(string.Format("{0} - {1}", curIncomeCatTotal.Key, "Income"), curIncomeCatTotal.Value);
                }
                else
                {
                    categoryTotals.Add(curIncomeCatTotal.Key, curIncomeCatTotal.Value);
                }
            }

            return categoryTotals;
        }
Beispiel #3
0
 public object Clone()
 {
     BeanConfig bc = null;
     try
     {
         bc = (BeanConfig) Activator.CreateInstance(GetType());
     }
     catch (TargetInvocationException e)
     {
         throw new ConfigException(e);
     }
     catch (MemberAccessException e)
     {
         throw new ConfigException(e);
     }
     if (bc == null)
     {
         return null;
     }
     bc.ClassName = ClassName;
     bc.Name = Name;
     var @params = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
     @params.AddRange(@params);
     bc.@params = @params;
     return bc;
 }
Beispiel #4
0
        /// <summary>
        /// Deserialization constructor.
        /// </summary>
        /// <param name="group">Market Group the Blueprint will be a member of.</param>
        /// <param name="src">Source serializable blueprint.</param>
        internal Blueprint(MarketGroup group, SerializableBlueprint src)
            : base(group, src)
        {
            RunsPerCopy = src.MaxProductionLimit;
            ProducesItem = StaticItems.GetItemByID(src.ProduceItemID);
            ProductionTime = src.ProductionTime;
            ResearchCopyTime = src.ResearchCopyTime;
            ResearchMaterialTime = src.ResearchMaterialTime;
            ResearchProductivityTime = src.ResearchProductivityTime;
            ResearchInventionTime = src.InventionTime;
            ReverseEngineeringTime = src.ReverseEngineeringTime;

            // Invented blueprints
            m_inventBlueprints = new Dictionary<int, double>(src.InventionTypeIDs?.Count ?? 0);
            if (src.InventionTypeIDs != null && src.InventionTypeIDs.Any())
            {
                m_inventBlueprints.AddRange(src.InventionTypeIDs);
            }

            // Materials prerequisites
            m_materialRequirements =
                new FastList<StaticRequiredMaterial>(src.ReqMaterial?.Count ?? 0);
            if (src.ReqMaterial == null)
                return;

            foreach (SerializableRequiredMaterial prereq in src.ReqMaterial)
            {
                m_materialRequirements.Add(new StaticRequiredMaterial(prereq));
            }
        }
        private static Dictionary<string, string> Translate(HashSet<string> toTranslate, string fromCulture, string toCulture)
        {
            var translated = Translation.TranslationClient.Translator.TranslateBatch(toTranslate.ToList(), fromCulture, toCulture);

            Dictionary<string, string> dic = new Dictionary<string, string>();
            dic.AddRange(toTranslate.ToList(), translated);
            return dic;
        }
Beispiel #6
0
 public static void Redirect()
 {
     redirects = new Dictionary<MethodInfo, RedirectCallsState>();
     foreach (var type in Assembly.GetExecutingAssembly().GetTypes())
     {
         redirects.AddRange(RedirectionUtil.RedirectType(type));
     }
 }
 public IDictionary<Number640, Data> Evaluate2(IDictionary<PeerAddress, IDictionary<Number640, Data>> rawData)
 {
     var result = new Dictionary<Number640, Data>();
     foreach (var dictionary in rawData.Values)
     {
         result.AddRange(dictionary);
     }
     return result;
 }
 public ICollection<Number640> Evaluate6(IDictionary<PeerAddress, IDictionary<Number640, byte>> rawKeys)
 {
     var result = new Dictionary<Number640, byte>();
     foreach (var dictionary in rawKeys.Values)
     {
         result.AddRange(dictionary);
     }
     return result.Keys;
 }
        // say, we have a type Type<(1) T1, (2) T2> with the method of the following signature:
        // T3[,][] Meth<(3) T3>(T1 o1, Func<T1, T3> o2) that has the following public type points:
        //
        // ReturnValue = T3 (a)[,][]
        // Args = T1 (b), Func<T1 (c), T3 (d)>
        // 
        // to be perfectly fine we need the following typelinks to be built:
        // (3) <-> (a), (1) <-> (b), (1) <-> (c), (3) <-> (d)
        // 
        // after some analysis we build the following mapping:
        // (key <- value)
        // a0 <- t[0]
        // a1[0] <- t[0]
        // a1[1] <- m[0]
        // ret[0][0] <- m[0]

        public static Dictionary<String, String> GetGenericArgsMapping(this MethodInfo method)
        {
            if (method == null)
            {
                return null;
            }
            else
            {
                var pattern = (MethodInfo)method.Module.ResolveMethod(method.MetadataToken);
                var methodGenericArgs = pattern.XGetGenericArguments();
                var typeGenericArgs = pattern.DeclaringType.XGetGenericArguments();

                var mapping = new Dictionary<String, String>();
                mapping.AddRange(AppendMethodMapping(pattern, methodGenericArgs, "m"));
                mapping.AddRange(AppendMethodMapping(pattern, typeGenericArgs, "t"));
                return mapping;
            }
        }
        public IDictionary<BetSheet, IList<BetOrder>> BuildOrder(User user, LotterySpecies specie,
            IEnumerable<AutoBetItem> betList, IDictionary<string, object> parameters)
        {
            this._betResult = new BetResult();
            BetResult returnResult = new Models.BetResult();
            var todayLotteryCompany = TodayLotteryCompany.Instance.GetTodayCompany();       //获取今日开奖公司
            var memberComm = CommManager.GetMemberCommissionInSession(user, specie);        //获取会员的佣金
            IDictionary<BetSheet, IList<BetOrder>> betSheetDic = new Dictionary<BetSheet, IList<BetOrder>>();
            IDictionary<BetSheet, IList<BetOrder>> resultDic = new Dictionary<BetSheet, IList<BetOrder>>();
            foreach (var betOrder in betList)
            {
                int[] nums;
                switch (betOrder.BetType)
                {
                    case AutoBetType.TwelveZodiac: nums = LotterySystem.Current.TwelveZodiac; break;
                    case AutoBetType.EvenEven: nums = LotterySystem.Current.EvenEven; break;
                    case AutoBetType.EvenOdd: nums = LotterySystem.Current.EvenOdd; break;
                    case AutoBetType.OddEven: nums = LotterySystem.Current.OddEven; break;
                    case AutoBetType.OddOdd: nums = LotterySystem.Current.OddOdd; break;
                    case AutoBetType.Small: nums = LotterySystem.Current.Small; break;
                    case AutoBetType.Big: nums = LotterySystem.Current.Big; break;
                    default: throw new InvalidDataException("不可到达,数据异常!");
                }
                var sheet = BuildAutoElectionCodeOrder(user, specie, betOrder.CompanyList, betOrder.WagerList, nums);
                betSheetDic.AddRange(sheet);
                returnResult.Append(this.BetResult);

                List<BetOrder> orderList = new List<BetOrder>();
                foreach (var item in betSheetDic)
                    orderList.AddRange(item.Value);
                StringBuilder companySb = new StringBuilder();
                foreach (var companyId in betOrder.CompanyList)
                {
                    var company = todayLotteryCompany.Find(it => it.CompanyId == companyId);
                    if (company == null)
                        throw new InvalidDataException("CompanyId:" + companyId);
                    companySb.AppendFormat("{0} ", company.Abbreviation);
                }
                BetSheet orderSheet = new BetSheet
                {
                    Num = betOrder.BetType.ToString(),
                    Turnover = orderList.Sum(it => it.Turnover),
                    NetAmount = orderList.Sum(it => it.NetAmount),
                    Commission = orderList.Sum(it => it.Commission),
                    UserId = user.UserId,
                    Status = BetStatus.Valid,
                    IPAddress = IPHelper.IPAddress,
                    BetCompany = companySb.ToString(),
                    BetAmount = JoinSheetBetAmount(sheet.Keys)
                };
                resultDic.Add(orderSheet, orderList);
                betSheetDic.Clear();
            }
            this._betResult = returnResult;
            return resultDic;
        }
Beispiel #11
0
 public Dictionary<string, List<string>> Update()
 {
     Dictionary<string, List<string>> updateChanges = new Dictionary<string, List<string>>();
     foreach (GameData gameData in Games)
     {
         var gameUpdateChanges = gameData.Update();
         updateChanges.AddRange(gameUpdateChanges.Select
             (e => new KeyValuePair<string, List<string>>(e.Key, e.Value)) );
     }
     return updateChanges;
 }
        public void then_range_added_to_existing_dictionary_adds_correctly()
        {
            Dictionary<string, string> stuff = new Dictionary<string, string> {{"ONE", "one"}};

            stuff.AddRange(s => s.ToUpperInvariant(), new[] { "two", "three" });

            Assert.AreEqual(3, stuff.Count);
            Assert.IsTrue(stuff.ContainsKey("TWO"));
            Assert.AreEqual("two", stuff["TWO"]);
            Assert.IsTrue(stuff.ContainsKey("THREE"));
            Assert.AreEqual("three", stuff["THREE"]);
        }
        public override Task ExecuteBindingAsync(ModelMetadataProvider metadataProvider, HttpActionContext actionContext, CancellationToken cancellationToken) {
            var binding = actionContext.ActionDescriptor.ActionBinding;

            var parameterBinding = binding.ParameterBindings.FirstOrDefault(b => b.Descriptor.ParameterBinderAttribute is QueryStringParametersAttribute);
            if (parameterBinding == null || !(typeof(IDictionary<string, string>).IsAssignableFrom(parameterBinding.Descriptor.ParameterType)))
                return Task.FromResult(0);

            var parameters = new Dictionary<string, string>();
            parameters.AddRange(actionContext.Request.GetQueryNameValuePairs().Where(kvp => !kvp.Key.Equals("access_token", StringComparison.OrdinalIgnoreCase)));
            SetValue(actionContext, parameters);

            return Task.FromResult(0);
        }
        public AssemblyInfoViewModel(AssemblyInfo assemblyInfo)
        {
            this.assemblyInfo = assemblyInfo;
            NewGuidCommand = new RelayCommand(() => Guid = System.Guid.NewGuid());

            var cultures = CultureInfo.GetCultures(CultureTypes.AllCultures);

            Languages = new Dictionary<string, string>();
            Languages.Add(
                NONE_LANGUAGE_CODE,
                string.Format("({0})", StringParser.Parse("${res:Dialog.ProjectOptions.AssemblyInfo.None}")));

            Languages.AddRange(cultures.ToDictionary(x => x.Name, x => x.DisplayName).Distinct().OrderBy(x => x.Value));
        }
        public void then_range_added_to_empty_dictionary_adds_correctly()
        {
            Dictionary<string, string> stuff = new Dictionary<string, string>();

            stuff.AddRange(s => s.ToUpperInvariant().Remove(2), new[]{"one", "two", "three"});

            Assert.AreEqual(3, stuff.Count);
            Assert.IsTrue(stuff.ContainsKey("ON"));
            Assert.AreEqual("one", stuff["ON"]);
            Assert.IsTrue(stuff.ContainsKey("TW"));
            Assert.AreEqual("two", stuff["TW"]);
            Assert.IsTrue(stuff.ContainsKey("TH"));
            Assert.AreEqual("three", stuff["TH"]);
        }
        public static void AddRange_KeyValuePair_Test()
        {
            var dictionary = new Dictionary<int, string>();

            var collection2 = new List<KeyValuePair<int, string>>
            {
                new KeyValuePair<int, string>(1, "test")
            };

            dictionary.AddRange(collection2);

            Assert.That(dictionary.ContainsKey(1));
            Assert.That(dictionary.ContainsValue("test"));
        }
 public void AddRangeTest()
 {
     Dictionary<string, string> dict = new Dictionary<string, string>();
     dict.Add("Key 1", "Value 1");
     dict.Add("Key 2", "Value 2");
     dict.Add("Key 3", "Value 3");
     IEnumerable<KeyValuePair<string, string>> range = kvp("Key 4", "Value 4");
     dict.AddRange(range);
     Dictionary<string, string> dictCopy = new Dictionary<string, string>();
     dictCopy.Add("Key 1", "Value 1");
     dictCopy.Add("Key 2", "Value 2");
     dictCopy.Add("Key 3", "Value 3");
     dictCopy.Add("Key 4", "Value 4");
     Assert.AreEqual(dictCopy, dict);
 }
Beispiel #18
0
        /// <summary>
        /// Method to compute the NGram.  
        /// 
        /// </summary>
        /// <param name="input">Input String</param>
        /// <param name="mvalue">Requested Length of NGrams to compute</param>
        /// <returns>A Dictionary containing the NGram (key) and count (value) of occurences</returns>
        public static Dictionary<string, int> ComputeNGram(string input, int mvalue)
        {
            // Initialize dictionary of results
            var result = new Dictionary<string, int>();

            // Split input string based on spaces.  
            // ASSUMPTION: This assumes that each word in the input is delineated by the space character.  Punctuation is not factored in and may need to be removed for future usage
            var inputArray = input.Split(' ');

            // start computing ngrams beginning with an ngram length of 1 (single words), and looping up to the length defined by the mvalue
            for (int i = 1; i <= mvalue; i++)
            {
                result.AddRange(ComputeNGramForMValue(inputArray, i));
            }

            return result;
        }
        public override void RunStarted(object automationObject, Dictionary<string, string> replacementsDictionary, WizardRunKind runKind, object[] customParams)
        {
            base.RunStarted(automationObject, replacementsDictionary, runKind, customParams);

            if (UnfoldScope.IsActive)
            {
                replacementsDictionary.AddRange(
                    ProductElementDictionaryConverter.Convert(UnfoldScope.Current.Automation.Owner)
                    .ToDictionary(e => string.Format(CultureInfo.InvariantCulture, @"${0}$", e.Key), e => e.Value));

                tracer.Verbose(Resources.ElementReplacementWizard_TracerTitle);
                foreach (var item in replacementsDictionary)
                {
                    tracer.Verbose(@"	{0}:'{1}'", item.Key, item.Value);
                }
            }
        }
            public HttpTriggerBinding(HttpTriggerAttribute attribute, ParameterInfo parameter, bool isUserTypeBinding)
            {
                _parameter = parameter;
                _isUserTypeBinding = isUserTypeBinding;

                Dictionary<string, Type> aggregateDataContract = new Dictionary<string, Type>(StringComparer.OrdinalIgnoreCase);
                if (_isUserTypeBinding)
                {
                    // Create the BindingDataProvider from the user Type. The BindingDataProvider
                    // is used to define the binding parameters that the binding exposes to other
                    // bindings (i.e. the properties of the POCO can be bound to by other bindings).
                    // It is also used to extract the binding data from an instance of the Type.
                    _bindingDataProvider = BindingDataProvider.FromType(parameter.ParameterType);
                    if (_bindingDataProvider.Contract != null)
                    {
                        aggregateDataContract.AddRange(_bindingDataProvider.Contract);
                    }
                }

                // add any route parameters to the contract
                if (!string.IsNullOrEmpty(attribute.RouteTemplate))
                {
                    var routeParameters = _httpRouteFactory.GetRouteParameters(attribute.RouteTemplate);
                    var parameters = ((MethodInfo)parameter.Member).GetParameters().ToDictionary(p => p.Name, p => p.ParameterType, StringComparer.OrdinalIgnoreCase);
                    foreach (string parameterName in routeParameters)
                    {
                        // don't override if the contract already includes a name
                        if (!aggregateDataContract.ContainsKey(parameterName))
                        {
                            // if there is a method parameter mapped to this parameter
                            // derive the Type from that
                            Type type;
                            if (!parameters.TryGetValue(parameterName, out type))
                            {
                                type = typeof(string);
                            }
                            aggregateDataContract[parameterName] = type;
                        }
                    }
                }

                _bindingDataContract = aggregateDataContract;
            }
        public void AddRangeTestCase()
        {
            var dictionary = new Dictionary<String, String>
            {
                { RandomValueEx.GetRandomString(), RandomValueEx.GetRandomString() },
                { RandomValueEx.GetRandomString(), RandomValueEx.GetRandomString() }
            };

            var otherDictionary = new Dictionary<String, String>
            {
                { RandomValueEx.GetRandomString(), RandomValueEx.GetRandomString() },
                { RandomValueEx.GetRandomString(), RandomValueEx.GetRandomString() }
            };

            Assert.AreEqual( 2, dictionary.Count );

            dictionary.AddRange( otherDictionary );
            Assert.AreEqual( 4, dictionary.Count );
            Assert.IsTrue( dictionary.ContainsAll( otherDictionary ) );
        }
        private void Deployment_BackgroundThread(object sender, DoWorkEventArgs e)
        {
            var referencedFiles = ModBeingDeployed.GetAllRelativeReferences();

            string archivePath = e.Argument as string;
            //Key is in-archive path, value is on disk path
            var archiveMapping             = new Dictionary <string, string>();
            SortedSet <string> directories = new SortedSet <string>();

            foreach (var file in referencedFiles)
            {
                var path      = Path.Combine(ModBeingDeployed.ModPath, file);
                var directory = Directory.GetParent(path).FullName;
                if (directory.Length <= ModBeingDeployed.ModPath.Length)
                {
                    continue;                                                      //root file or directory.
                }
                directory = directory.Substring(ModBeingDeployed.ModPath.Length + 1);

                //nested folders with no folders
                var    relativeFolders    = directory.Split('\\');
                string buildingFolderList = "";
                foreach (var relativeFolder in relativeFolders)
                {
                    if (buildingFolderList != "")
                    {
                        buildingFolderList += "\\";
                    }
                    buildingFolderList += relativeFolder;
                    if (directories.Add(buildingFolderList))
                    {
                        Debug.WriteLine("7z folder: " + buildingFolderList);
                        archiveMapping[buildingFolderList] = null;
                    }
                }
            }

            archiveMapping.AddRange(referencedFiles.ToDictionary(x => x, x => Path.Combine(ModBeingDeployed.ModPath, x)));

            var compressor = new SevenZip.SevenZipCompressor();

            //compressor.CompressionLevel = CompressionLevel.Ultra;
            compressor.CustomParameters.Add("s", "on");
            if (!MultithreadedCompression)
            {
                compressor.CustomParameters.Add("mt", "off");
            }
            compressor.CustomParameters.Add("yx", "9");
            //compressor.CustomParameters.Add("x", "9");
            compressor.CustomParameters.Add("d", "28");
            string currentDeploymentStep = "Mod";

            compressor.Progressing += (a, b) =>
            {
                //Debug.WriteLine(b.AmountCompleted + "/" + b.TotalAmount);
                ProgressMax   = b.TotalAmount;
                ProgressValue = b.AmountCompleted;
                var now = DateTime.Now;
                if ((now - lastPercentUpdateTime).Milliseconds > ModInstaller.PERCENT_REFRESH_COOLDOWN)
                {
                    //Don't update UI too often. Once per second is enough.
                    string percent = (ProgressValue * 100.0 / ProgressMax).ToString("0.00");
                    OperationText         = $"[{currentDeploymentStep}] Deployment in progress... {percent}%";
                    lastPercentUpdateTime = now;
                }
                //Debug.WriteLine(ProgressValue + "/" + ProgressMax);
            };
            compressor.FileCompressionStarted += (a, b) => { Debug.WriteLine(b.FileName); };
            compressor.CompressFileDictionary(archiveMapping, archivePath);
            Debug.WriteLine("Now compressing moddesc.ini...");
            compressor.CustomParameters.Clear(); //remove custom params as it seems to force LZMA
            compressor.CompressionMode  = CompressionMode.Append;
            compressor.CompressionLevel = CompressionLevel.None;
            currentDeploymentStep       = "moddesc.ini";
            compressor.CompressFiles(archivePath, new string[]
            {
                Path.Combine(ModBeingDeployed.ModPath, "moddesc.ini")
            });
            OperationText = "Deployment succeeded";
            Utilities.HighlightInExplorer(archivePath);
        }
Beispiel #23
0
        public override void Added(Scene scene)
        {
            base.Added(scene);

            // read the matching texture
            if (string.IsNullOrEmpty(overrideTexture))
            {
                overrideTexture = AreaData.Get(scene).WoodPlatform;
            }
            MTexture platformTexture = GFX.Game["objects/woodPlatform/" + overrideTexture];

            textures = new MTexture[platformTexture.Width / 8];
            for (int i = 0; i < textures.Length; i++)
            {
                textures[i] = platformTexture.GetSubtexture(i * 8, 0, 8, 8);
            }

            // draw lines between all nodes
            if (Visible || forcedTrackOffset != null)
            {
                Vector2 lineOffset = forcedTrackOffset ?? new Vector2(Width, Height + 4f) / 2f;
                scene.Add(new MovingPlatformLine(nodes[0] + lineOffset, nodes[1] + lineOffset));
                if (nodes.Length > 2)
                {
                    for (int i = 1; i < nodes.Length - 1; i++)
                    {
                        scene.Add(new MovingPlatformLine(nodes[i] + lineOffset, nodes[i + 1] + lineOffset));
                    }

                    if (mode == Mode.Loop || mode == Mode.LoopNoPause)
                    {
                        scene.Add(new MovingPlatformLine(nodes[nodes.Length - 1] + lineOffset, nodes[0] + lineOffset));
                    }
                }
            }

            // if count > 1, spawn other platforms to simulate multiple evenly spread platforms.
            for (int i = 1; i < amount; i++)
            {
                // each platform has 1 / amount of offset more than the previous.
                float newOffset = startingOffset;
                newOffset += (1f / amount) * i;
                if (newOffset >= 1f)
                {
                    newOffset -= 1f;
                }

                // copy the entity data and inject the new offset in it.
                Dictionary <string, object> newEntityProperties = new Dictionary <string, object>();
                newEntityProperties.AddRange(entityProperties);
                newEntityProperties["offset"] = newOffset;

                // force-set the amount to 1 because the spawned platform should definitely not spawn platforms!
                newEntityProperties["amount"] = 1;

                // assemble everything into a new EntityData and build a new platform with it.
                EntityData data = new EntityData {
                    Position = entityPosition,
                    Nodes    = entityNodes,
                    Width    = entityWidth,
                    Values   = newEntityProperties
                };
                Scene.Add(new MultiNodeMovingPlatform(data, entityOffset, callbackOnAdded)
                {
                    Visible = Visible
                });
            }

            callbackOnAdded?.Invoke(this);

            if (startingOffsetIsNotZero && !moveLater)
            {
                updatePosition();
            }
        }
        public void Transform(MethodBody body)
        {
            if (this.result == null)
            {
                throw new InvalidOperationException("Analysis result not available.");
            }

            foreach (var node in this.cfg.Nodes)
            {
                var node_result = this.result[node.Id];
                var copies      = new Dictionary <IVariable, IVariable>();

                if (node_result.Input != null)
                {
                    copies.AddRange(node_result.Input);
                }

                for (var i = 0; i < node.Instructions.Count; ++i)
                {
                    var instruction = node.Instructions[i];

                    foreach (var variable in instruction.UsedVariables)
                    {
                        // Only replace temporal variables
                        if (variable.IsTemporal() &&
                            copies.ContainsKey(variable))
                        {
                            var operand = copies[variable];

                            instruction.Replace(variable, operand);
                        }
                    }

                    var isTemporalCopy = this.Flow(instruction, copies);

                    // Only replace temporal variables
                    if (isTemporalCopy)
                    {
                        // Remove the copy instruction
                        if (i == 0)
                        {
                            // The copy is the first instruction of the basic block
                            // Replace the copy instruction with a nop to preserve branch targets
                            var nop   = new NopInstruction(instruction.Offset);
                            var index = body.Instructions.IndexOf(instruction);
                            body.Instructions[index] = nop;
                            node.Instructions[i]     = nop;
                        }
                        else
                        {
                            // The copy is not the first instruction of the basic block
                            body.Instructions.Remove(instruction);
                            node.Instructions.RemoveAt(i);
                            --i;
                        }
                    }
                }
            }

            body.UpdateVariables();
        }
        /// <summary>
        /// Override the do tests function, since it has the default get request behavior.Executes the tests.
        /// </summary>
        /// <seealso cref="M:BackScatterScannerLib.Engine.TestBase.DoTests()"/>
        public override void DoTests()
        {
            BrowserAbstract browser      = null;
            var             postElements = this.inspectPostPage.Inspect(this.TestTarget, ref browser).ToArray();

            // a container representing the id of the element and the element itself
            var webElementsToBeTested = new Dictionary <string, IWebElement>();

            foreach (var postElement in postElements)
            {
                string elementUniqueIdentification = GetElementIdentification(postElement);

                webElementsToBeTested[elementUniqueIdentification] = postElement;
            }

            try
            {
                // test all user interaction controls
                while (webElementsToBeTested.Count > 0)
                {
                    // if we found a vulnerability then exit, the page is already compromised
                    if (this.vulnerabilityFound)
                    {
                        break;
                    }

                    // take the first element and start testing
                    KeyValuePair <string, IWebElement> postElement = webElementsToBeTested.First();

                    // for each test case
                    foreach (var testCase in this.TestCases)
                    {
                        // if we found a vulnerability then exit, the page is already compromised
                        if (this.vulnerabilityFound)
                        {
                            break;
                        }

                        if (string.IsNullOrEmpty(postElement.Key))
                        {
                            break;
                        }

                        // for each payload in the test case
                        foreach (var payload in testCase.InjectionString)
                        {
                            // if we found a vulnerability then exit, the page is already compromised
                            if (this.vulnerabilityFound)
                            {
                                break;
                            }

                            try
                            {
                                this.SendPayload(postElement.Value, payload, browser, testCase);
                            }
                            catch (StaleElementReferenceException ex)
                            {
                                // before re-inspecting the page check for vulnerabilities
                                this.CheckForVulnerabilities(browser, testCase, payload);

                                // the web elements had become stale the refresh them, re- inspect the elements and continue testing
                                postElements = this.inspectPostPage.Inspect(this.TestTarget, ref browser).ToArray();

                                // update the new reflected elements
                                var newWebElements = this.UpdateWebElementsToBeTested(
                                    webElementsToBeTested,
                                    postElements);

                                webElementsToBeTested.Clear();
                                webElementsToBeTested.AddRange(newWebElements);

                                postElement =
                                    webElementsToBeTested.SingleOrDefault(
                                        e => e.Key.Equals(postElement.Key, StringComparison.InvariantCultureIgnoreCase));

                                if (string.IsNullOrEmpty(postElement.Key))
                                {
                                    break;
                                }

                                Logger.WriteWarning(ex);
                            }
                            catch (UnhandledAlertException ex)
                            {
                                this.CheckForVulnerabilities(browser, testCase, payload);
                                Logger.WriteError(ex);
                            }
                            catch (Exception ex)
                            {
                                Logger.WriteError(ex);
                            }
                        }
                    }

                    if (!string.IsNullOrEmpty(postElement.Key))
                    {
                        // after the testing is done remove it from container
                        webElementsToBeTested.Remove(postElement.Key);
                    }
                }
            }
            finally
            {
                Context.ReleaseBrowser(browser);
            }
        }
Beispiel #26
0
        public bool Refresh()
        {
            this.DictColumnInfo      = new IgCaseDictionary <ColumnInfo>();
            this.TableNames          = new List <string>();
            this.TableInfoDict       = new IgCaseDictionary <TableInfo>();
            this.TableColumnNameDict = new IgCaseDictionary <List <string> >();
            this.TableColumnInfoDict = new IgCaseDictionary <List <ColumnInfo> >();
            this.TableColumnComments = new IgCaseDictionary <NameValueCollection>();

            string dbSql  = "select datname from pg_database where  datistemplate=false  order by oid desc";
            string strSql = @"select a.*,cast(obj_description(relfilenode,'pg_class') as varchar) as value from (
select b.oid as schid, a.table_schema as scName,a.table_name as Name from information_schema.tables  a
left join pg_namespace b on b.nspname = a.table_schema
where a.table_schema not in ('pg_catalog','information_schema') and a.table_type='BASE TABLE'
) a inner join pg_class b on a.name = b.relname and a.schid = b.relnamespace
order by schid asc";

            string viewSql = "SELECT viewname,definition FROM pg_views where schemaname='public' order by viewname asc";
            string procSql = "select proname,prosrc from  pg_proc where pronamespace=(SELECT pg_namespace.oid FROM pg_namespace WHERE nspname = 'public') order by proname asc";

            try
            {
                this.DBNames = Db.ReadList <string>(dbSql);

                this.Version = Db.Scalar("select version()", string.Empty);

                var data = Db.GetDataTable(strSql);

                var dictGp = new Dictionary <string, List <string> >();

                foreach (DataRow dr in data.Rows)
                {
                    this.TableComments[dr["name"].ToString()] = dr["value"].ToString();
                    this.TableSchemas[dr["name"].ToString()]  = dr["scname"].ToString();

                    dictGp.AddRange(dr["scname"].ToString(), dr["name"].ToString());
                }

                foreach (var item in dictGp)
                {
                    this.TableNames.AddRange(item.Value.OrderBy(t => t));
                }

                this.Views = Db.ReadNameValues(viewSql);

                this.Procs = Db.ReadNameValues(procSql);

                if (this.TableComments != null && this.TableComments.Count > 0)
                {
                    List <Task> lstTask = new List <Task>();

                    foreach (var tableName in this.TableNames)
                    {
                        Task task = Task.Run(() =>
                        {
                            TableInfo tabInfo  = new TableInfo();
                            tabInfo.TableName  = tableName;
                            tabInfo.TabComment = TableComments[tableName];

                            strSql = @"set search_path to " + TableSchemas[tableName] + @";select ordinal_position as Colorder,column_name as ColumnName,data_type as TypeName,
coalesce(character_maximum_length,numeric_precision,-1) as Length,numeric_scale as Scale,
case is_nullable when 'NO' then 0 else 1 end as CanNull,column_default as DefaultVal,
case  when position('nextval' in column_default)>0 then 1 else 0 end as IsIdentity, 
case when b.pk_name is null then 0 else 1 end as IsPK,c.DeText
from information_schema.columns 
left join (
	select pg_attr.attname as colname,pg_constraint.conname as pk_name from pg_constraint  
	inner join pg_class on pg_constraint.conrelid = pg_class.oid 
	inner join pg_attribute pg_attr on pg_attr.attrelid = pg_class.oid and  pg_attr.attnum = pg_constraint.conkey[1] 
	inner join pg_type on pg_type.oid = pg_attr.atttypid
	where pg_class.relname =:tableName and pg_constraint.contype='p' 
) b on b.colname = information_schema.columns.column_name
left join (
	select attname,description as DeText from pg_class
	left join pg_attribute pg_attr on pg_attr.attrelid= pg_class.oid
	left join pg_description pg_desc on pg_desc.objoid = pg_attr.attrelid and pg_desc.objsubid=pg_attr.attnum
	where pg_attr.attnum>0 and pg_attr.attrelid=pg_class.oid and pg_class.relname=:tableName
)c on c.attname = information_schema.columns.column_name
where table_schema not in ('pg_catalog','information_schema') and table_name=:tableName order by ordinal_position asc";
                            try
                            {
                                tabInfo.Colnumns                 = Db.GetDataTable(strSql, new { tableName = tableName }).ConvertToListObject <ColumnInfo>();
                                List <string> lstColName         = new List <string>();
                                NameValueCollection nvcColDeText = new NameValueCollection();
                                foreach (ColumnInfo colInfo in tabInfo.Colnumns)
                                {
                                    lstColName.Add(colInfo.ColumnName);
                                    nvcColDeText.Add(colInfo.ColumnName, colInfo.DeText);

                                    var strKey = (tableName + "@" + colInfo.ColumnName);
                                    this.DictColumnInfo.Add(strKey, colInfo);
                                    if (colInfo.IsIdentity)
                                    {
                                        this.Dict_Table_Identity_Column[tableName] = colInfo.ColumnName;
                                    }

                                    if (colInfo.IsPK)
                                    {
                                        tabInfo.PriKeyColName = colInfo.ColumnName;
                                        if (colInfo.IsIdentity)
                                        {
                                            tabInfo.PriKeyType = PrimaryKeyType.AUTO;
                                        }
                                        else
                                        {
                                            tabInfo.PriKeyType = PrimaryKeyType.SET;
                                        }
                                    }

                                    Global.Dict_PostgreSql_DbType.TryGetValue(colInfo.TypeName, out DbType type);
                                    colInfo.DbType = type;
                                }

                                this.TableInfoDict.Add(tableName, tabInfo);
                                this.TableColumnNameDict.Add(tableName, lstColName);
                                this.TableColumnInfoDict.Add(tableName, tabInfo.Colnumns);
                                this.TableColumnComments.Add(tableName, nvcColDeText);
                            }
                            catch (Exception ex)
                            {
                                LogUtils.LogError("DB", Developer.SysDefault, ex);
                            }
                        });
                        lstTask.Add(task);
                        if (lstTask.Count(t => t.Status != TaskStatus.RanToCompletion) >= 50)
                        {
                            Task.WaitAny(lstTask.ToArray());
                            lstTask = lstTask.Where(t => t.Status != TaskStatus.RanToCompletion).ToList();
                        }
                    }
                    Task.WaitAll(lstTask.ToArray());
                }
            }
            catch (Exception ex)
            {
                LogUtils.LogError("DB", Developer.SysDefault, ex);
                return(false);
            }
            return(this.TableComments.Count == this.TableInfoDict.Count);
        }
        public void AddRangeThrowsArgumentNullExceptionIfAnyOfTheArgumentsIsNull()
        {
            Dictionary <int, string> dic1 = null, dic2 = null;

            // ReSharper disable once AccessToModifiedClosure
            Func <ArgumentNullException> getException = () => TestUtils.ExpectException <ArgumentNullException>(() => dic1.AddRange(dic2));

            Assert.AreEqual("originalDictionary", getException().ParamName);

            dic1 = new Dictionary <int, string>();
            Assert.AreEqual("additionalElements", getException().ParamName);
        }
Beispiel #28
0
 private static void PrintJson(List<CryptoHashInput> inputs)
 {
     Object obj = inputs;
     if (_map)
     {
         var map = new Dictionary<string, CryptoHashInput>();
         map.AddRange(inputs.Select(input => new KeyValuePair<string, CryptoHashInput>(input.Name, input)));
         obj = map;
     }
     Console.WriteLine(JsonConvert.SerializeObject(obj, Formatting.Indented));
 }
Beispiel #29
0
        public static Statement CreateStatement(Select select, IEntityMapping mapping, IEnumerable <string> projectionOverride = null, bool noLock = false)
        {
            var sql        = new SqlWriter();
            var parameters = new Dictionary <string, object>();

            var projection    = projectionOverride ?? BuildProjection(select, mapping, parameters);
            var whereClause   = BuildWhereClause(select, mapping, parameters);
            var orderByClause = select.HasOrderBy ? BuildOrderBy(select.OrderBy, mapping, parameters) : null;

            Action <SqlWriter> writeProjection = x => x.Do(projection != null, y => y.FieldList(z => z.Comma.Flush(), projection), y => y.Wildcard.Flush());

            if (select.Any)
            {
                sql.Select.Cast().Trim().OpenBlock.Trim().Case.When.Exists.OpenBlock.Trim();
            }

            if (select.From.IsTable || select.HasConditions)
            {
                sql.Select.Flush();

                if (select.First || select.FirstOrDefault)
                {
                    sql.Top(1);
                }
                else if (select.Single)
                {
                    sql.Top(2);
                }
                else if (select.HasTop && !select.HasStart)
                {
                    sql.Do(select.TopType == Select.TopValueType.Count, x => x.Top(select.Top), x => x.TopPercent(select.Top));
                }

                if (select.Count)
                {
                    sql.CountWildcard.Flush();
                }
                else
                {
                    sql.Do(writeProjection);
                }

                sql.From.Flush();

                if (select.HasStart)
                {
                    sql.OpenBlock.Trim().Select.Do(writeProjection).Trim().Comma.
                    RowNumber().Over.OpenBlock.Trim().OrderBy.
                    Do(select.HasOrderBy, x => x.Write(orderByClause), x => x.Do(projection != null, writeProjection, y => y.QuotedName(mapping.Key.GetColumnName()))).Trim().
                    CloseBlock.As.RowNumberAlias.From.Flush();
                }

                if (select.HasDuplicates)
                {
                    var duplicateProjection = BuildProjection(select.Duplicates.Distinct, mapping, parameters);
                    sql.OpenBlock.Trim().Select.Do(writeProjection).Trim().Comma.
                    RowNumber().Over.OpenBlock.Trim().Partition.By.Write(duplicateProjection).OrderBy.Write(BuildOrderBy(select.Duplicates.OrderBy, mapping, parameters)).
                    Trim().CloseBlock.As.PartitionAlias.From.Flush();
                }
                else if (select.HasDistinct)
                {
                    var distinctProjection = BuildProjections(select.Distinct.Select(x => x.Projection), mapping, parameters);
                    sql.OpenBlock.Trim().Select.Do(writeProjection).Trim().Comma.
                    RowNumber().Over.OpenBlock.Trim().Partition.By.ExpressionList(z => z.Comma.Flush(), distinctProjection).OrderBy.
                    Write(BuildOrderBy(select.Distinct.Any(x => x.HasOrder) ? select.Distinct.Where(x => x.HasOrder).Select(x => x.Order) :
                                       select.Distinct.Select(x => new OrderBy {
                        Type       = OrderBy.SourceType.Projection,
                        Projection = x.Projection,
                        Order      = Order.Ascending
                    }), mapping, parameters)).Trim().
                    CloseBlock.As.PartitionAlias.From.Flush();
                }
            }

            switch (select.From.Type)
            {
            case Data.DataType.Table:
                sql.QuotedName(select.From.Table.Name).Write(select.From.Alias);
                if (noLock)
                {
                    sql.With(x => x.NoLock.Flush());
                }
                break;

            case Data.DataType.Query:
                var first = true;
                if (select.HasConditions)
                {
                    sql.OpenBlock.Trim().Flush();
                }
                foreach (var subQuery in select.From.Queries.Select(x => CreateStatement(x, mapping, projection, noLock)))
                {
                    sql.Do(!first, x => x.Union.Flush()).Write(subQuery.Text).Flush();
                    parameters.AddRange(subQuery.Parameters);
                    first = false;
                }
                if (select.HasConditions)
                {
                    sql.Trim().CloseBlock.As.Write(select.From.Alias).Flush();
                }
                break;
            }

            if (select.From.IsTable || select.HasConditions)
            {
                if (select.HasWhere || select.HasSetOperations)
                {
                    sql.Where.Write(whereClause).Flush();
                }

                if (select.Randomize)
                {
                    sql.OrderBy.NewId();
                }
                // The reason why we dont do an order by if there is a start is because the order by is
                // already specified in the row number definition. So we dont need to specify it again.
                else if (select.HasOrderBy && !select.HasStart && !select.HasDistinct)
                {
                    sql.OrderBy.Write(orderByClause);
                }

                if (select.HasDuplicates)
                {
                    sql.Trim().CloseBlock.As.Write(select.From.Alias).Where.PartitionAlias.GreaterThan.Value(1, SqlDbType.Int).Flush();
                }
                else if (select.HasDistinct)
                {
                    sql.Trim().CloseBlock.As.Write(select.From.Alias).Where.PartitionAlias.Equal.Value(1, SqlDbType.Int).Flush();
                }

                if (select.HasStart)
                {
                    sql.Trim().CloseBlock.As.Write(select.From.Alias).Where.RowNumberAlias.Flush();
                    if (select.HasTop && select.HasStart)
                    {
                        sql.Between(select.Start, select.Start + (select.Top - 1));
                    }
                    else
                    {
                        sql.GreaterThanOrEqual.Value(select.Start, SqlDbType.Int);
                    }
                }
            }

            if (select.Any)
            {
                sql.Trim().CloseBlock.Then.Value(1, SqlDbType.Bit).Else.Value(0, SqlDbType.Bit).End.As.Write(DataTypes.Bit.SqlName).Trim().CloseBlock.Flush();
            }

            return(new Statement(sql.ToString(), Statement.StatementType.Text, GetResultType(select), parameters));
        }
        /// <summary>
        /// This is the update method which will change some <paramref name="myDBObjects"/> an behalf of the <paramref name="myListOfUpdates"/>
        /// </summary>
        /// <param name="myDBObjects">Some dbobjects</param>
        /// <param name="myListOfUpdates">The list of update tasks (assign, delete, etc)</param>
        /// <param name="dbObjectCache"></param>
        /// <returns></returns>
        public QueryResult Update(IEnumerable<Exceptional<DBObjectStream>> myDBObjects, IEnumerable<AAttributeAssignOrUpdateOrRemove> myListOfUpdates, DBContext myDBContext, GraphDBType myGraphDBType)
        {
            #region Data

            var queryResultContent = new List<Vertex>();
            var queryResult = new QueryResult();
            Warning_UndefinedAttribute undefAttrWarning = null;

            #endregion

            #region check for undefined attributes setting

            var undefAttrSetting = myDBContext.DBSettingsManager.GetSetting(SettingUndefAttrBehaviour.UUID, myDBContext, TypesSettingScope.DB);

            if (!undefAttrSetting.Success())
            {
                return new QueryResult(undefAttrSetting);
            }

            var undefSettingVal = ((SettingUndefAttrBehaviour)undefAttrSetting.Value).Behaviour;

            #endregion

            #region Validate attributes

            foreach (var updateOrAssign in myListOfUpdates)
            {
                System.Diagnostics.Debug.Assert(updateOrAssign != null);
                if (updateOrAssign is AAttributeAssignOrUpdateOrRemove && !(updateOrAssign is AttributeRemove))
                {
                    var result = (updateOrAssign as AAttributeAssignOrUpdateOrRemove).AttributeIDChain.Validate(myDBContext, true);

                    if (updateOrAssign.IsUndefinedAttributeAssign)
                    {
                        switch (undefSettingVal)
                        {
                            case UndefAttributeBehaviour.disallow:
                                return new QueryResult(new Error_UndefinedAttributes());

                            case UndefAttributeBehaviour.warn:
                                if (undefAttrWarning == null)
                                {
                                    undefAttrWarning = new Warning_UndefinedAttribute();
                                }

                                queryResult.PushIWarning(undefAttrWarning);
                                break;
                        }
                    }

                    if (result.Failed())
                    {
                        return new QueryResult(result);
                    }
                }
            }

            //var undefinedAttributeAssignments = myListOfUpdates.Where(a => a.IsUndefinedAttributeAssign);
            var definedAttributeAssignments = myListOfUpdates.Where(a => !a.IsUndefinedAttributeAssign);

            #endregion

            #region check unique constraint - refactor!!

            if (definedAttributeAssignments.CountIsGreater(0))
            {

                Exceptional<Boolean> CheckConstraint = null;

                IEnumerable<GraphDBType> parentTypes = myDBContext.DBTypeManager.GetAllParentTypes(myGraphDBType, true, false);
                Dictionary<AttributeUUID, IObject> ChkForUnique = new Dictionary<AttributeUUID, IObject>();

                foreach (var entry in myDBObjects)
                {
                    //all attributes, that are going to be changed
                    var attrsToCheck = entry.Value.GetAttributes().Where(item => definedAttributeAssignments.Select(updAttrs => GetAttributesToCheckForUnique(updAttrs)).Contains(item.Key));

                    foreach (var attrValue in attrsToCheck)
                    {
                        if (!ChkForUnique.ContainsKey(attrValue.Key))
                            ChkForUnique.Add(attrValue.Key, attrValue.Value);
                    }

                    CheckConstraint = myDBContext.DBIndexManager.CheckUniqueConstraint(myGraphDBType, parentTypes, ChkForUnique);
                    ChkForUnique.Clear();

                    if (CheckConstraint.Failed())
                        return new QueryResult(CheckConstraint.IErrors);

                }
            }

            #endregion

            #region regular update

            foreach (var aDBO in myDBObjects)
            {
                //key: attribute name
                //value: TypeAttribute, NewValue
                Dictionary<String, Tuple<TypeAttribute, IObject>> attrsForResult = new Dictionary<String, Tuple<TypeAttribute, IObject>>();

                if (aDBO.Failed())
                {
                    return new QueryResult(aDBO);
                }

                #region data

                Boolean sthChanged = false;

                #endregion

                #region iterate tasks

                //Exceptional<Boolean> partialResult;

                foreach (var attributeUpdateOrAssign in myListOfUpdates)
                {

                    var updateResult = attributeUpdateOrAssign.Update(myDBContext, aDBO.Value, myGraphDBType);
                    if (updateResult.Failed())
                    {
                        return new QueryResult(updateResult);
                    }

                    if (updateResult.Value.Count > 0)
                    {
                        sthChanged = true;
                        attrsForResult.AddRange(updateResult.Value);
                    }

                }

                #endregion

                if (sthChanged)
                {
                    var definedAttributes = ExtractDefinedAttributes(attrsForResult, myDBContext.DBTypeManager);

                    #region update Idx

                    foreach (var _AttributeIndex in myGraphDBType.GetAllAttributeIndices())
                    {
                        if(definedAttributes.Exists(item => _AttributeIndex.IndexKeyDefinition.IndexKeyAttributeUUIDs.Contains(item.Key.Definition.UUID)))
                        {
                            //execute update
                            _AttributeIndex.Update(aDBO.Value, myGraphDBType, myDBContext);
                        }
                    }

                    #endregion

                    #region update dbobjects on fs

                    var flushResult = myDBContext.DBObjectManager.FlushDBObject(aDBO.Value);
                    if (!flushResult.Success())
                    {
                        return new QueryResult(flushResult);
                    }

                    #endregion

                    var resultSet = GetManipulationResultSet(myDBContext, aDBO, myGraphDBType, undefinedAttributes: ExtractUndefindedAttributes(attrsForResult), attributes: definedAttributes);
                    if (!resultSet.Success())
                    {
                        /*
                          what should happen now
                          this should not break the update
                        */
                    }

                    queryResultContent.Add(resultSet.Value);
                }
            }

            #endregion

            #region Return all affected dbObjectUUIDs

            queryResult.Vertices = queryResultContent;

            return queryResult;

            #endregion
        }
Beispiel #31
0
        public async Task <IActionResult> Upload(
            [FromBody] DataCheck data
            )
        {
            if (data == null || data.Activities == null)
            {
                return(BadRequest());
            }
            Logger.LogInformation("Received query on {0} activity slices, last check {1}",
                                  data.Activities.Length, data.LastCheckTimestamp);

            if (!ApiConf.Value.PerformTimestampFiltering)
            {
                Logger.LogDebug("Timestamp filtering disabled");
            }
            if (ApiConf.Value.PerformTimestampFiltering && !data.LastCheckTimestamp.HasValue)
            {
                Logger.LogDebug("No last check, checking from min value");
                data.LastCheckTimestamp = DateTime.MinValue;
            }

            var ctas = new Dictionary <ObjectId, DataModels.CallToAction>();

            foreach (var activity in data.Activities)
            {
                var matchCtas = await Mongo.MatchFilter(activity.Date, activity.Hashes,
                                                        ApiConf.Value.PerformTimestampFiltering?data.LastCheckTimestamp.Value : DateTime.MinValue);

                Logger.LogInformation("Geohashes {0} on {1} matches {2} calls ({3})",
                                      string.Join(", ", activity.Hashes),
                                      activity.Date.ToShortDateString(),
                                      matchCtas.Count,
                                      string.Join(", ", from id in matchCtas select id.Id.ToString()));

                ctas.AddRange(matchCtas, cta => cta.Id);
            }

            Logger.LogInformation("Loading filters for {0} unique call to actions", ctas.Count);
            var filters = await Mongo.GetCallToActionFilters(ctas.Keys);

            var filterMap = filters.GroupBy(f => f.CallToActionId)
                            .ToDictionary(g => g.Key, g => g.Select(cta => cta));

            Logger.LogInformation("Found {0} call to actions ({1}) with {2} filters ({3})",
                                  ctas.Count, string.Join(", ", from ctaId in ctas.Keys select ctaId.ToString()),
                                  filters.Count, string.Join(", ", from filter in filters select filter.Id.ToString())
                                  );

            return(Ok(new CallToActionMatch {
                HasMatch = ctas.Count > 0,
                Calls = (from cta in ctas.Values
                         select new CallToActionMatch.CallToAction {
                    Id = cta.Id.ToString(),
                    Description = cta.Description,
                    Url = string.IsNullOrEmpty(cta.Url)
                                 ? GenerateActionLink(nameof(CallToActionController.Show), "CallToAction", new { id = cta.Id.ToString() })
                                 : cta.Url,
                    Source = cta.SourceKey,
                    SourceName = cta.SourceName,
                    SourceDescription = cta.SourceDescription,
                    ExposureSeconds = cta.ExposureSeconds,
                    Queries = (from filter in filterMap[cta.Id]
                               select new CallToActionMatch.CallToActionQuery {
                        From = filter.TimeBegin,
                        To = filter.TimeEnd,
                        LastUpdate = filter.AddedOn,
                        Geometry = new CallToActionMatch.GeoJsonGeometry {
                            Type = "Polygon",
                            Coordinates = filter.Geometry.ToPolygonArray()
                        }
                    }).ToArray()
                }).ToArray()
            }));
        }
        private static Dictionary<string, string> AskForReplacementsWithMemory(HashSet<string> newNames, HashSet<string> oldNames, Dictionary<string, string> memory, string replacementKey)
        {
            Dictionary<string, string> result = new Dictionary<string, string>();

            foreach (var kvp in memory)
            {
                if (oldNames.Contains(kvp.Key) && kvp.Value == null)
                {
                    oldNames.Remove(kvp.Key);
                }
                else if (oldNames.Contains(kvp.Key) && newNames.Contains(kvp.Value))
                {
                    oldNames.Remove(kvp.Key);
                    newNames.Remove(kvp.Value);
                    result.Add(kvp.Key, kvp.Value);
                }
            }

            Replacements rep = new Replacements();

            rep.AskForReplacements(oldNames, newNames, replacementKey);

            var answers = rep.TryGetC(replacementKey);
            if (answers != null)
            {
                result.AddRange(answers);
                memory.SetRange(answers);
            }

            var toDelete = oldNames.Except(newNames);
            if(answers != null)
                toDelete = toDelete.Except(answers.Keys);

            memory.SetRange(toDelete.Select(n => KVP.Create(n, (string)null)));

            return result;
        }
Beispiel #33
0
        private static Dictionary <Type, TypeMetadata> ConstructTypesMetadata(Type type, string baseEntityName = null)
        {
            var           typesMetadata = new Dictionary <Type, TypeMetadata>();
            Func <object> constructor;

            var inheritedEntityTypeAttribute = type.GetCustomAttribute <InheritedEntityTypeAttribute>();

            if (inheritedEntityTypeAttribute != null)
            {
                var inheritedTypes = type.Assembly.GetTypes().Where(a => a.IsSubclassOf(type));
                foreach (var t in inheritedTypes)
                {
                    var innerMetadata = ConstructTypesMetadata(t, inheritedEntityTypeAttribute.Type);
                    typesMetadata.AddRange(innerMetadata);
                }
            }

            if ((constructor = BuildEmptyConstructorAccessor(type)) == null)
            {
                return(typesMetadata);
            }

            TypeMetadata typeMetadata;

            if (typeof(ICollection).IsAssignableFrom(type))
            {
                if (!type.GetGenericArguments().Any())
                {
                    //TODO: Add Warn log
                    return(typesMetadata);
                }

                typeMetadata = new ListMetadata
                {
                    Constructor = constructor,
                    ItemsType   = type.GetGenericArguments()[0],
                    AddItem     = BuildMethodAccessorWithOneParameter(type.GetMethod("Add")),
                    GetItem     = BuildMethodAccessorWithOneParameterAndReturnValue(type.GetMethod("get_Item"))
                };
            }
            else
            {
                typeMetadata = new TypeMetadata
                {
                    Constructor        = constructor,
                    PropertiesInfo     = GetPropertiesAccessors(type),
                    InheritedClassType = GetInheritedType(inheritedEntityTypeAttribute, baseEntityName)
                };
            }
            typesMetadata.Add(type, typeMetadata);

            //Traverse all the entity properties
            var properties = type.GetProperties();

            foreach (var property in properties)
            {
                var innerMetadata = ConstructTypesMetadata(property.PropertyType);
                typesMetadata.AddRange(innerMetadata);
            }

            return(typesMetadata);
        }
Beispiel #34
0
        public void Transform(MethodBody body)
        {
            if (this.result == null)
            {
                throw new InvalidOperationException("Analysis result not available.");
            }
            var copiesToRemove = new Dictionary <IVariable, InstructionLocation>();
            var sorted_nodes   = cfg.ForwardOrder;

            foreach (var node in sorted_nodes)
            {
                var node_result = this.result[node.Id];
                var copies      = new Dictionary <IVariable, IVariable>();

                if (node_result.Input != null)
                {
                    copies.AddRange(node_result.Input);
                }

                for (var i = 0; i < node.Instructions.Count; ++i)
                {
                    var instruction = node.Instructions[i];

                    foreach (var variable in instruction.UsedVariables)
                    {
                        // If the variable definition is marked to be removed
                        // but it is not a copy reaching this instruction,
                        // then we cannot remove the definition because the
                        // variable cannot be replaced with a copy.
                        if (copiesToRemove.ContainsKey(variable) &&
                            !copies.ContainsKey(variable))
                        {
                            copiesToRemove.Remove(variable);
                        }
                        // Only replace temporal variables
                        else if (variable.IsTemporal() &&
                                 copies.ContainsKey(variable))
                        {
                            var operand = copies[variable];

                            instruction.Replace(variable, operand);
                        }
                    }

                    var isTemporalCopy = this.Flow(instruction, copies);

                    // Only replace temporal variables
                    if (isTemporalCopy)
                    {
                        var definition = instruction as DefinitionInstruction;

                        // Mark the copy instruction to be removed later
                        var location = new InstructionLocation()
                        {
                            CFGNode     = node,
                            Instruction = instruction
                        };

                        // TODO: Check this, not sure if this is the right fix.
                        if (!copiesToRemove.ContainsKey(definition.Result))
                        {
                            copiesToRemove.Add(definition.Result, location);
                        }
                    }
                }
            }

            // Remove unnecessary copy instructions
            foreach (var location in copiesToRemove.Values)
            {
                var bodyIndex = body.Instructions.IndexOf(location.Instruction);
                var nodeIndex = location.CFGNode.Instructions.IndexOf(location.Instruction);

                if (nodeIndex == 0)
                {
                    // The copy is the first instruction of the basic block
                    // Replace the copy instruction with a nop to preserve branch targets
                    var nop = new NopInstruction(location.Instruction.Offset);
                    body.Instructions[bodyIndex]             = nop;
                    location.CFGNode.Instructions[nodeIndex] = nop;
                }
                else
                {
                    // The copy is not the first instruction of the basic block
                    body.Instructions.RemoveAt(bodyIndex);
                    location.CFGNode.Instructions.RemoveAt(nodeIndex);
                }
            }

            body.UpdateVariables();
        }
Beispiel #35
0
        private void LoadReportData(ReportPackage report, Dictionary <String, String> parameters, XElement reportDef, ServiceBuilder sb)
        {
            try
            {
                var reportParams = ReportViewer1.LocalReport.GetParameters();
                sb.SendTimeout = TimeSpan.FromMinutes(30);
                var dlSvc     = sb.DataLinkV2();
                var newParams = new Dictionary <String, String>();
                var xmlns     = reportDef.GetDefaultNamespace().ToString();
                var rd        = reportDef.GetNamespaceOfPrefix("rd").ToString();

                var dataSets = reportDef.Descendants(XName.Get("DataSet", xmlns));
                if (dataSets == null)
                {
                    throw new Exception("DataSet not found in report"); //We control writing this, so we should never see this occur.
                }
                foreach (var dataSet in dataSets)
                {
                    var dsName = dataSet.SafeAttributeValue <String>("Name", Constants.ECLIPSE_DATASOURCE);
                    var rds    = report.ReportDataSets.FirstOrDefault(r => r.Name == dsName);
                    var dlSR   = dlSvc.GetReportData(new GetReportDataArgs {
                        Parameters = parameters, QueryDefinition = rds.QueryDefinition
                    });
                    ExceptionsML.Check(dlSR.Error);
                    newParams.AddRange(dlSR.Result.Parameters);
                    var dt     = new DataTable(dsName);
                    var fields = dataSet.Descendants(XName.Get("Field", xmlns));
                    if (fields != null)
                    {
                        foreach (var field in fields)
                        {
                            var fieldName = field.Element(XName.Get("DataField", xmlns)).Value;
                            var fieldType = field.Element(XName.Get("TypeName", rd)).Value;
                            dt.Columns.Add(new DataColumn(fieldName, Converter.GetType(fieldType)));
                        }
                        if (dlSR.Result != null)
                        {
                            dlSR.Result.FillDataTable(dt);
                        }
                    }
                    var rptData = new ReportDataSource(dsName, dt);
                    ReportViewer1.LocalReport.DataSources.Add(rptData);
                }
                // Set the parameters for the report
                var length     = reportParams == null ? 0 : reportParams.Count;
                var setParams  = new ReportParameter[length];
                var eclipseURL = String.Format("{0}://{1}:{2}{3}",
                                               Request.IsSecureConnection ? "https" : "http",
                                               Request.ServerVariables["SERVER_NAME"],
                                               Request.ServerVariables["SERVER_PORT"],
                                               Request.ApplicationPath);
                var idx = 0;
                foreach (var param in reportParams)
                {
                    // Add a hardcoded EclipseURL parameter so the report can use it to navigate documents
                    var name          = param.Name;
                    var newParamsName = "@" + name;
                    if (name == Constants.REPORTS_ECLIPSE_URL)
                    {
                        setParams[idx] = new ReportParameter(name, eclipseURL);
                    }
                    else if (newParams.ContainsKey(newParamsName)) // newParams names begin with "@", where as name does not
                    {
                        setParams[idx] = new ReportParameter(name, newParams[newParamsName]);
                    }
                    else
                    {
                        setParams[idx] = new ReportParameter(name);
                    }
                    idx++;
                }
                setParams = setParams.RemoveNulls();    // Prevents setting null parameters (ones' that have been deleted)
                ReportViewer1.LocalReport.SetParameters(setParams);
            }
            catch (LocalProcessingException lex)
            {
                ErrorHandler(lex.InnerMost());
            }
            catch (Exception ex)
            {
                ErrorHandler(ex);
            }
        }
		private void PopulateProductExportConfiguration(Dictionary<string, Func<CatalogProduct, string>> configuration, IEnumerable<CatalogProduct> products)
		{

			configuration.Add("Sku", (product) =>
			{
				return product.Code;
			});

			configuration.Add("ParentSku", (product) =>
			{
				return product.MainProduct != null ? product.MainProduct.Code : String.Empty;
			});

			//Category
			configuration.Add("Category", (product) =>
			{
				if(product.CategoryId != null)
				{
					var category = _categoryService.GetById(product.CategoryId);
					var path = String.Join("/", category.Parents.Select(x => x.Name).Concat(new string[] { category.Name }));
					return path;
				}
				return String.Empty;
			});


			//Scalar Properties
			var exportScalarFields = ReflectionUtility.GetPropertyNames<CatalogProduct>(x=>x.Id, x=>x.MainProductId, x=>x.CategoryId, x => x.Name, x => x.IsActive, x => x.IsBuyable, x => x.TrackInventory,
																							  x => x.ManufacturerPartNumber, x => x.Gtin, x => x.MeasureUnit, x => x.WeightUnit, x => x.Weight,
																							  x => x.Height, x => x.Length, x => x.Width, x => x.TaxType,  x => x.ShippingType,
																							  x => x.ProductType, x => x.Vendor, x => x.DownloadType, x => x.DownloadExpiration, x => x.HasUserAgreement);
			configuration.AddRange(exportScalarFields.Select(x => new KeyValuePair<string, Func<CatalogProduct, string>>(x, null)));

			configuration.Add("PrimaryImage", (product) =>
			{
				if (product.Images != null && product.Images.Any())
				{
					return _blobUrlResolver.GetAbsoluteUrl(product.Images.First().Url);
				}
				return String.Empty;
			});

			configuration.Add("AltImage", (product) =>
			{
				if (product.Images != null)
				{
					var image = product.Images.Skip(1).FirstOrDefault();
					if (image != null)
					{
						return _blobUrlResolver.GetAbsoluteUrl(image.Url);
					}
				}
				return String.Empty;
			});

			configuration.Add("Review", (product) =>
			{
				if (product.Reviews != null)
				{
					var review = product.Reviews.FirstOrDefault();
					if (review != null)
					{
						return review.Content ?? String.Empty;
					}
				}
				return String.Empty;
			});

			configuration.Add("SeoUrl", (product) =>
			{
				if (product.SeoInfos != null)
				{
					var seoInfo = product.SeoInfos.FirstOrDefault();
					if (seoInfo != null)
					{
						return seoInfo.SemanticUrl ?? String.Empty;
					}
				}
				return String.Empty;
			});
			configuration.Add("SeoTitle", (product) =>
			{
				if (product.SeoInfos != null)
				{
					var seoInfo = product.SeoInfos.FirstOrDefault();
					if (seoInfo != null)
					{
						return seoInfo.PageTitle ?? String.Empty;
					}
				}
				return String.Empty;
			});
			configuration.Add("SeoDescription", (product) =>
			{
				if (product.SeoInfos != null)
				{
					var seoInfo = product.SeoInfos.FirstOrDefault();
					if (seoInfo != null)
					{
						return seoInfo.MetaDescription ?? String.Empty;
					}
				}
				return String.Empty;
			});

			//Prices
			configuration.Add("PriceId", (product) =>
			{
				var bestPrice = product.Prices.Any() ? product.Prices.FirstOrDefault() : null;
				return bestPrice != null ? bestPrice.Id : String.Empty;
			});
			configuration.Add("SalePrice", (product) =>
				{
					var bestPrice = product.Prices.Any() ? product.Prices.FirstOrDefault() : null;
					return bestPrice != null ? (bestPrice.Sale != null ? bestPrice.Sale.Value.ToString(CultureInfo.InvariantCulture) : String.Empty) : String.Empty;
				});
			configuration.Add("Price", (product) =>
			{
				var bestPrice = product.Prices.Any() ? product.Prices.FirstOrDefault() : null;
				return bestPrice != null ? bestPrice.List.ToString(CultureInfo.InvariantCulture) : String.Empty;
			});
			configuration.Add("Currency", (product) =>
			{
				var bestPrice = product.Prices.Any() ? product.Prices.FirstOrDefault() : null;
				return bestPrice != null ? bestPrice.Currency.ToString() : String.Empty;
			});
		
			//Inventories
			configuration.Add("FulfilmentCenterId", (product) =>
			{
				var inventory = product.Inventories.Any() ? product.Inventories.FirstOrDefault() : null;
				return inventory != null ? inventory.FulfillmentCenterId : String.Empty;
			});
			configuration.Add("AllowBackorder", (product) =>
			{
				var inventory = product.Inventories.Any() ? product.Inventories.FirstOrDefault() : null;
				return inventory != null ? inventory.AllowBackorder.ToString() : String.Empty;
			});
			configuration.Add("Quantity", (product) =>
			{
				var inventory = product.Inventories.Any() ? product.Inventories.FirstOrDefault() : null;
				return inventory != null ? inventory.InStockQuantity.ToString() : String.Empty;
			});
		
			//Properties
			foreach (var propertyName in products.SelectMany(x => x.PropertyValues).Select(x => x.PropertyName).Distinct())
			{
				if (!configuration.ContainsKey(propertyName))
				{
					configuration.Add(propertyName, (product) =>
					{
						var propertyValue = product.PropertyValues.FirstOrDefault(x => x.PropertyName == propertyName);
						if (propertyValue != null)
						{
							return propertyValue.Value != null ? propertyValue.Value.ToString() : String.Empty;
						}
						return String.Empty;
					});
				}
			}
	
		}
 /// <summary>
 /// Adds the given list to the dictionary, provided a function that will extract the key for each value
 /// </summary>
 /// <typeparam name="Key"></typeparam>
 /// <typeparam name="Value"></typeparam>
 /// <param name="dictionary"></param>
 /// <param name="values"></param>
 /// <param name="keyFunction"></param>
 public static void AddRange <Key, Value>(this Dictionary <Key, Value> dictionary, Func <Value, Key> keyFunction, params Value[] values)
 {
     dictionary.AddRange(keyFunction, (IEnumerable <Value>)values);
 }
        /// <summary>
        /// Реализация метода обновления коллекций ресурсов библиотеки
        /// </summary>
        /// <param name="parResManager">Менеджер ресурсов приложения</param>
        /// <param name="outDataSprites">Выходная коллекция спрайтов</param>
        /// <param name="outDataAnimations">Выходная коллекция анимаций</param>
        /// <param name="outDataFonts">Выходная коллекция шрифтов</param>
        public void UpdateCollectionLibrary(ResourceManager parResManager,
                                            out Dictionary <string, SubassetDataSprite> outDataSprites,
                                            out Dictionary <string, SubassetDataAnimation> outDataAnimations,
                                            out Dictionary <string, SubassetDataFont> outDataFonts)
        {
            outDataSprites    = new Dictionary <string, SubassetDataSprite>();
            outDataAnimations = new Dictionary <string, SubassetDataAnimation>();
            outDataFonts      = new Dictionary <string, SubassetDataFont>();

            var loadedContent = parResManager.GetLoadedAssetPackContent(AssetPackName);

            while (!OpenGlCommandsInternalHandler.AreAllActionsPerformed())
            {
            }

            foreach (var assetContentElementKeyValuePair in loadedContent)
            {
                Console.WriteLine($"Processing {assetContentElementKeyValuePair.Value.ActualAssetMetadata.FilePath}");
                if (assetContentElementKeyValuePair.Value is AssetDataOpenTkTexture workingWithTexture)
                {
                    Console.WriteLine("Texture detected!");
                    string textureName = Path.GetFileName(workingWithTexture.ActualAssetMetadata.FilePath);

                    parResManager.GetAssetInfo(workingWithTexture.ActualAssetMetadata, out string assetPack,
                                               out string assetName);
                    string possibleMetadataAssetName = $"{assetName}.meta.json";

                    Console.WriteLine($"Checking for metadata {possibleMetadataAssetName}");

                    //проверим, что имеются метаданные
                    if (loadedContent.ContainsKey(
                            possibleMetadataAssetName))
                    {
                        AssetDataText metadataAsset = (AssetDataText)loadedContent[possibleMetadataAssetName];
                        string        jsonFullText  = string.Join(" ",
                                                                  metadataAsset.TextData);
                        Dictionary <string, object> jsonData =
                            JsonConvert.DeserializeObject <Dictionary <string, object> >(jsonFullText);

                        string metadataType = (string)jsonData[METADATATYPE_KEY];

                        if (metadataType == METADATATYPE_ANIM_SHEET)
                        {
                            //поделим текстуру на спрайты и создадим анимации
                            int width  = (int)(long)jsonData[METADATA_ANIM_WIDTH];
                            int height = (int)(long)jsonData[METADATA_ANIM_HEIGHT];

                            Dictionary <string, SubassetDataSprite> spritesInAnim =
                                new Dictionary <string, SubassetDataSprite>();

                            // TODO be carefull with x'es and y'es

                            int currentX = 1;
                            int currentY = 1;

                            int animCounter = 0;

                            int framesCountConstraint = int.MaxValue;

                            if (jsonData.ContainsKey(METADATA_ANIM_FRAMESCOUNT))
                            {
                                framesCountConstraint = (int)(long)jsonData[METADATA_ANIM_FRAMESCOUNT];
                            }

                            while (currentY < workingWithTexture.Height && animCounter < framesCountConstraint)
                            {
                                currentX = 1;
                                while (currentX < workingWithTexture.Width && animCounter < framesCountConstraint)
                                {
                                    spritesInAnim.Add($"{assetName}{ANIMATION_POSTFIX}{animCounter}",
                                                      new SubassetDataSprite(workingWithTexture,
                                                                             new Rectangle(currentX - 1, currentY - 1, width, height)));

                                    animCounter++;
                                    currentX += width;
                                }

                                currentY += height;
                            }

                            Console.WriteLine(
                                $"Animation sprite sheet processed, name {assetName} frames {animCounter}");

                            //создание анимации и объединение спрайтов
                            SubassetDataAnimation animation =
                                new SubassetDataAnimation(new List <SubassetDataSprite>(spritesInAnim.Values));

                            outDataAnimations.Add(assetName, animation);
                            outDataSprites.AddRange(spritesInAnim);
                        }
                        else if (metadataType == METADATATYPE_SPRITE_SHEET)
                        {
                            SpriteSheetDataTuple deserializedActualJsonData =
                                JsonConvert.DeserializeObject <SpriteSheetDataTuple>(jsonFullText);

                            foreach (var sprite in deserializedActualJsonData.Sprites)
                            {
                                outDataSprites.Add($"{assetName}/{sprite.SpriteName}",
                                                   new SubassetDataSprite(workingWithTexture,
                                                                          new Rectangle(sprite.X - 1, sprite.Y - 1, sprite.Width, sprite.Height)));
                                Console.WriteLine(
                                    $"Subasset sprite in sheet processed, name {assetName}/{sprite.SpriteName}");
                            }
                        }
                        else if (metadataType == METADATATYPE_FONT_SPRITE_SHEET)
                        {
                            SpriteSheetDataTuple deserializedActualJsonData =
                                JsonConvert.DeserializeObject <SpriteSheetDataTuple>(jsonFullText);

                            Dictionary <string, SubassetDataSprite> fontSymbolsToSprites =
                                new Dictionary <string, SubassetDataSprite>();


                            foreach (var sprite in deserializedActualJsonData.Sprites)
                            {
                                SubassetDataSprite createdSprite = new SubassetDataSprite(workingWithTexture,
                                                                                          new Rectangle(sprite.X - 1, sprite.Y - 1, sprite.Width, sprite.Height));

                                outDataSprites.Add($"{assetName}/{sprite.SpriteName}",
                                                   createdSprite);

                                string fontSymbolNameOnly =
                                    sprite.SpriteName.Replace(
                                        AssetDataRelatedConsts.FONT_ASSET_SYMBOL_DEFINITION_PREFIX, "");

                                if (fontSymbolNameOnly == ViewBehaviourConsts.SPECIAL_SYMBOL_SPACE)
                                {
                                    fontSymbolNameOnly = " ";
                                }

                                fontSymbolsToSprites.Add(fontSymbolNameOnly, createdSprite);

                                Console.WriteLine(
                                    $"Font sprite in sheet processed, name {assetName}/{sprite.SpriteName} symbol {fontSymbolNameOnly}");
                            }

                            outDataFonts.Add(assetName, new SubassetDataFont(fontSymbolsToSprites));
                        }
                    }
                    else
                    {
                        outDataSprites.Add($"{assetName}",
                                           new SubassetDataSprite(workingWithTexture,
                                                                  new Rectangle(0, 0, workingWithTexture.Width, workingWithTexture.Height)));
                        Console.WriteLine($"Sprite without metadata added {assetName}");
                    }
                }
            }
        }
Beispiel #39
0
        public bool Refresh()
        {
            this.DictColumnInfo      = new IgCaseDictionary <ColumnInfo>();
            this.TableNames          = new List <string>();
            this.TableInfoDict       = new IgCaseDictionary <TableInfo>();
            this.TableColumnNameDict = new IgCaseDictionary <List <string> >();
            this.TableColumnInfoDict = new IgCaseDictionary <List <ColumnInfo> >();
            this.TableColumnComments = new IgCaseDictionary <NameValueCollection>();

            string dbSql  = "select name from sys.sysdatabases Order By name asc";
            string strSql = "SELECT * FROM (SELECT '[' + (Select Top 1 c.name From sys.schemas c Where c.schema_id = a.schema_id) + '].[' + a.Name + ']' as Name,(SELECT TOP 1 Value FROM sys.extended_properties b WHERE b.major_id=a.object_id and b.minor_id=0) AS value,(Select top 1 c.name From sys.schemas c Where c.schema_id = a.schema_id) scName From sys.objects a WHERE a.type = 'U' AND a.name <> 'sysdiagrams' AND a.name <> 'dtproperties' )K WHERE K.scName <> 'cdc' ORDER BY K.name ASC;";

            string viewSql = "SELECT TABLE_NAME,VIEW_DEFINITION FROM INFORMATION_SCHEMA.VIEWS Order By TABLE_NAME asc";
            string procSql = "select name,[definition] from sys.objects a Left Join sys.sql_modules b On a.[object_id]=b.[object_id] Where a.type='P' And a.is_ms_shipped=0 And b.execute_as_principal_id Is Null And name !='sp_upgraddiagrams' Order By a.name asc";

            try
            {
                this.DBNames = Db.ReadList <string>(dbSql);

                this.Version = Db.Scalar("select @@version", string.Empty)?.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries)?[0];

                var data = Db.GetDataTable(strSql);

                var dictGp = new Dictionary <string, List <string> >();

                foreach (DataRow dr in data.Rows)
                {
                    this.TableComments[dr["name"].ToString()] = dr["value"].ToString();
                    this.TableSchemas[dr["name"].ToString()]  = dr["scname"].ToString();

                    dictGp.AddRange(dr["scname"].ToString(), dr["name"].ToString());
                }

                foreach (var item in dictGp)
                {
                    this.TableNames.AddRange(item.Value.OrderBy(t => t));
                }

                this.Views = Db.ReadNameValues(viewSql);
                this.Procs = Db.ReadNameValues(procSql);

                if (this.TableComments != null && this.TableComments.Count > 0)
                {
                    List <Task> lstTask = new List <Task>();
                    foreach (var tableName in this.TableNames)
                    {
                        Task task = Task.Run(() =>
                        {
                            TableInfo tabInfo  = new TableInfo();
                            tabInfo.TableName  = tableName;
                            tabInfo.TabComment = TableComments[tableName];

                            strSql = @"select s.* FROM (SELECT a.colorder Colorder,a.name ColumnName,b.name TypeName,row_number() over (partition by a.name order by b.name) as group_idx,(case when (SELECT count(*) FROM sysobjects  WHERE (name in (SELECT name FROM sysindexes  WHERE (id = a.id) AND (indid in  (SELECT indid FROM sysindexkeys  WHERE (id = a.id) AND (colid in  (SELECT colid FROM syscolumns WHERE (id = a.id) AND (name = a.name)))))))  AND (xtype = 'PK'))>0 then 1 else 0 end) IsPK,(case when COLUMNPROPERTY( a.id,a.name,'IsIdentity')=1 then 1 else 0 end) IsIdentity,  CASE When b.name ='uniqueidentifier' Then 36  WHEN (charindex('int',b.name)>0) OR (charindex('time',b.name)>0) THEN NULL ELSE  COLUMNPROPERTY(a.id,a.name,'PRECISION') end as [Length], CASE WHEN ((charindex('int',b.name)>0) OR (charindex('time',b.name)>0)) THEN NULL ELSE isnull(COLUMNPROPERTY(a.id,a.name,'Scale'),null) end as Scale,(case when a.isnullable=1 then 1 else 0 end) CanNull,Replace(Replace(IsNull(e.text,''),'(',''),')','') DefaultVal,isnull(g.[value], ' ') AS DeText FROM  syscolumns a left join systypes b on a.xtype=b.xusertype inner join sysobjects d on a.id=d.id and d.xtype='U' and d.name<>'dtproperties' left join syscomments e on a.cdefault=e.id left join sys.extended_properties g on a.id=g.major_id AND a.colid=g.minor_id  And g.class=1 left join sys.extended_properties f on d.id=f.class and f.minor_id=0 left join sys.schemas c on d.uid = c.schema_id where b.name is not NULL and '[' + c.name + '].[' + d.name + ']'=@tableName ) s WHERE s.group_idx = 1 order by s.colorder";

                            try
                            {
                                tabInfo.Colnumns                 = Db.GetDataTable(strSql, new { tableName = tableName }).ConvertToListObject <ColumnInfo>();
                                List <string> lstColName         = new List <string>();
                                NameValueCollection nvcColDeText = new NameValueCollection();
                                foreach (ColumnInfo colInfo in tabInfo.Colnumns)
                                {
                                    lstColName.Add(colInfo.ColumnName);
                                    nvcColDeText.Add(colInfo.ColumnName, colInfo.DeText);

                                    var strKey = (tableName + "@" + colInfo.ColumnName);
                                    this.DictColumnInfo.Add(strKey, colInfo);

                                    if (colInfo.IsPK)
                                    {
                                        tabInfo.PriKeyColName = colInfo.ColumnName;
                                        if (colInfo.IsIdentity)
                                        {
                                            tabInfo.PriKeyType = PrimaryKeyType.AUTO;
                                        }
                                        else
                                        {
                                            tabInfo.PriKeyType = PrimaryKeyType.SET;
                                        }
                                    }

                                    Global.Dict_SqlServer_DbType.TryGetValue(colInfo.TypeName, out DbType type);
                                    colInfo.DbType = type;
                                }
                                this.TableInfoDict.Add(tableName, tabInfo);
                                this.TableColumnNameDict.Add(tableName, lstColName);
                                this.TableColumnInfoDict.Add(tableName, tabInfo.Colnumns);
                                this.TableColumnComments.Add(tableName, nvcColDeText);
                            }
                            catch (Exception ex)
                            {
                                LogUtils.LogError("DB", Developer.SysDefault, ex, "查询过程出现失败,账号的权限可能不足!!!");
                            }
                        });
                        lstTask.Add(task);
                        if (lstTask.Count(t => t.Status != TaskStatus.RanToCompletion) >= 50)
                        {
                            Task.WaitAny(lstTask.ToArray());
                            lstTask = lstTask.Where(t => t.Status != TaskStatus.RanToCompletion).ToList();
                        }
                    }
                    Task.WaitAll(lstTask.ToArray());
                }
            }
            catch (Exception ex)
            {
                LogUtils.LogError("DB", Developer.SysDefault, ex, "查询过程出现失败,账号的权限可能不足!!!");
                return(false);
            }
            return(this.TableComments.Count == this.TableInfoDict.Count);
        }
 void MergeWith(InterfaceFamily f)
 {
     Debug.Assert(_interfaces.Intersect(f._interfaces).Any() == false);
     _interfaces.UnionWith(f._interfaces);
     _classes.AddRange(f._classes);
 }
Beispiel #41
0
        public HelpForm()
        {
            topics = new Dictionary <string, string>();
            topics.AddRange(
                #region Topics
                "What is KShootMania?",
                "KShootMania is a rhythm game that consists of notes along numerous lanes of a track that the player must hit when they reach the bottom of the track.\n" +
                "There are four lanes which white (BT) object travel down. Orange (FX) objects also travel down either the two lefthand or two righthand lanes and cause a distortion to the song when successfully hit.\n" +
                "Laser objects will also travel down the screen, moving left and right in various patterns, to which the player must move indicators to line up with them.\n" +
                @"KShootMania can be downloaded at \L[http://www.kshootmania.com]http://www.kshootmania.com/\/L",

                "What is KShootMania Skin Manager",
                "KShootMania Skin Manager is a utility that automates replacement of textures and audio files or \"skins\" for KShootMania.\n",

                "Installation",
                "You must already have KShootMania installed on your computer and have the zip file for KShootMania. If you deleted it, you'll have to redownload them again.\n" +
                "To install KShootMania Skin Manager, create a folder you would like to install KShootMania Skin Manager to and put \"KShootMania Skin Manager.exe\" in the folder.\n" +
                "Afterwards, run KShootMania Skin Manager.exe and go through the installation process.\n" +
                "NOTE: If you want to move the installation location, you must uninstall KShootMania Skin Manager first. To do so, see \"Uninstallation\".",

                "How to use KShootMania Skin Manager",
                "After installing KShootMania Skin Manager, while KShootMania is running, a button labelled \"Change skin\" will appear in the top-right corner. Clicking on it will open KShootMania Skin Manager.\n" +
                "From there, you'll two lists of skins, one of the left and one on the right. The one on the left is your complete list of skins you have installed and the one on the right is the list of skins you have loaded.\n" +
                "Your loaded skins all have different \"priorities\" and are ordered from lowest to highest priority. You can reorder the skin priorities with the increase and decrease higherarchy buttons.\n" +
                "Once you're done configuring your skin(s) to how you like them, click the \"Save\" button and KShootMania Skin Manager will replace the skin elements and reopen KShootMania.",

                "Skin hierarchy",
                "KShootMania Skin Manager works by loading multiple skins at once. These skins most likely will contains some of the same assets as each other. For this reason, your loaded skins will be organised in a heirarchy. If two skins share the same kind of asset, the asset from the skin higher in the heirarchy is used.\n" +
                "To avoid any issues with missing assets, it is recommended that you always have the default skin loaded at the bottom of the heirarchy.",

                "Moving KShootMania after installation",
                "If you want to move KShootMania after installing KShootMania Skin Manager, you must do a little more than just moving the folder.\n" +
                "It is recommended that you screenshot or write these instructions down as the process will prevent you from accessing this help while moving KShootMania.\n" +
                "First, right click your taskbar or press CTRL+ALT+Delete and select \"Task Manager\". From there, find the process named \"KShootMania Skin Manager (32 bit)\", right click it and select \"End task\".\n" +
                "Then, move KShootMania to where you want to put it.\n" +
                "Afterwards, go into KShootMania Skin Manager, open the file \"settings.ini\" and find the line starting with \"KSMDir\". Replace the directory listed after the '=' with the new directory you put KShootMania in.\n" +
                "Now, restart your computer and KShootMania Skin Manager should work with the new directory.",

                "Uninstalling KShootMania Skin Manager",
                "It is recommended that you screenshot or write these instructions down as the process will prevent you from accessing this help during and after uninstallation.\n" +
                "First, right click your taskbar or press CTRL+ALT+Delete and select \"Task Manager\". From there, find the process named \"KShootMania Skin Manager (32 bit)\", right click it and select \"End task\".\n" +
                @"Afterwards, if you installed KShootMania Skin Manager for your specific account, go to ""C:\Users\" + Environment.UserName + @"\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup"", or if you installed to all users, ""C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp"". Within the folder, you will find a shortcut to KShootMania Skin Manager. Delete it." + "\n" +
                "After that, delete the KShootMania Skin Manager folder. KShootMania Skin Manager is now fully uninstalled.",

                "Moving KShootMania Skin Manager after installation",
                "KShootMania Skin Manager can't be moved directly, but there are two hypothetical ways to move the program's install location.\n" +
                "It is recommended that you screenshot or write your perfered method's instructions down as both processes will prevent you from accessing this help during while moving KShooMania Skin Manager.\n" +
                "\n" +
                "METHOD 1:\n" +
                "Firstly, go into KShootMania Skin Manager's directory and back up the skins folder and settings.ini.\n" +
                "After that, uninstall KShootMania Skin Manager and reinstall it to the new location.\n" +
                "Then, go into Task Manager and end the KShootMania Skin Manager process like you did during the uninstallation.\n" +
                "Copy the skins folder and settings.ini file from the backup into the new installation of KShootMania Skin Manager.\n" +
                "Now, restart your computer and KShootMania Skin Manager should now work from within the new directory.\n" +
                "\n" +
                "METHOD 2:\n" +
                "First, right click your taskbar or press CTRL + ALT + Delete and select \"Task Manager\". From there, find the process named \"KShootMania Skin Manager (32 bit)\", right click it and select \"End task\".\n" +
                @"Afterwards, if you installed KShootMania Skin Manager for your specific account, go to ""C:\Users\" + Environment.UserName + @"\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup"", or if you installed to all users, ""C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp"". Within the folder, you will find a shortcut to KShootMania Skin Manager. Delete it, but leave the window open for later." + "\n" +
                "After that, move the KShootMania Skin Manager folder, right click \"KShootMania Skin Manager.exe\", mouse down to \"Send to\" and select \"Desktop (create shortcut)\".\n" +
                "Finally, copy the shortcut into the folder you left open and restart your computer. KShootMania Skin Manager should now work from within the new directory.",

                "Installing additional skins",
                "To install more skins to KShootMania Skin Manager, go to where you installed KShootMania Skin manager and extract the skin to the skins folder.\n" +
                "Keep in mind that the skin's file structure needs to be organised a certain way. See the default skin KShootMania Skin Manager generates for reference.",

                "Settings",
                "There are some settings in KShootMania Skin Manager that you can alter. There are two ways you can do this.\n" +
                "The standard way to edit settings is to open up the change skin window and click the settings button. From there, you can edit a good number of the settings in this window, but it's not guaranteed that you'll be able to edit every setting from within the settings window.\n" +
                "The other way is to edit the settings.ini file directly. To edit it, go into KShootMania Skin Manager's directory and open the settings.ini file. In there, you can change all of the settings that KShootMania allows you to change.",

                "Settings.ini breakdown",
                "A breakdown of each setting of the settings.ini file\n" +
                "KSMDir: The location of where the user has KShootMania. Don't change this outside of moving KShootMania. See \"Moving KShootMania after installation\" for how to do that.\n" +
                "TopPriorityOnTop: The way skins in the current skin configuration are organised in the change skin window. If this is \"true\", skins higher in the hierarchy will appear higher in the list. If this is \"false\", skins lower in the hierarchy will appear higher in the list.\n" +
                "ChangeSkinButtonPosition: The corner the change skin button will appear in when KShootMania is running. 0: Top-left corner. 1: Top-right corner. 2: Bottom-left corner. 3: Bottom-right corner."
                #endregion
                );
            InitializeComponent();
        }
Beispiel #42
0
 public static void AddRangeTo <TKey, TValue>(this IEnumerable <KeyValuePair <TKey, TValue> > toAdd, Dictionary <TKey, TValue> dict) where TKey : notnull =>
 dict.AddRange(toAdd);
            private Dictionary <MemberPath, ODataExpression> ParseProjectionBody(Expression body)
            {
                var isAnonymousTypeProjection     = body.NodeType == ExpressionType.New && body.Type.IsAnonymous();
                var isObjectInitializerProjection = body.NodeType == ExpressionType.MemberInit;

                if (isAnonymousTypeProjection || isObjectInitializerProjection)
                {
                    Dictionary <MemberPath, Expression> pathToLinqMapping;
                    if (isAnonymousTypeProjection) // anonymous, like a => new { x = a.B }
                    {
                        // anonymous type creation is actually a new using a constructor whose arguments match the anonymous properties
                        var @new = (NewExpression)body;
                        pathToLinqMapping = @new.Constructor.GetParameters()
                                            .Select((v, i) => new { Value = v, Index = i })
                                            .ToDictionary(
                            t => @new.Type.GetMember(t.Value.Name).As <MemberPath>(),
                            t => @new.Arguments[t.Index]
                            );
                    }
                    else
                    {
                        // initializer, like a => new X { Foo = a.B }
                        var memberInit = (MemberInitExpression)body;
                        if (memberInit.NewExpression.Arguments.Count > 0)
                        {
                            throw new ODataCompileException("Only parameterless constructors are supported with object initializers in OData. Found: " + memberInit);
                        }
                        if (memberInit.Bindings.Any(mb => mb.BindingType != MemberBindingType.Assignment))
                        {
                            throw new ODataCompileException("Only member assignment initializers are supported in OData. Found: " + memberInit);
                        }

                        pathToLinqMapping = memberInit.Bindings.Cast <MemberAssignment>()
                                            .ToDictionary(
                            mb => new[] { mb.Member }.As <MemberPath>(),
                            mb => mb.Expression
                            );
                    }

                    // for anonymous and initializer projections, we support nested projections such as
                    // a => new { b = new { c = a.x } } }
                    // To do this, for each property mapping (a.b in the example above), we simply recurse
                    // on the value expression and then add the property prefix to the resulting paths
                    var result = new Dictionary <MemberPath, ODataExpression>(MemberPathComparer);
                    foreach (var kvp in pathToLinqMapping)
                    {
                        var parsed = this.ParseProjectionBody(kvp.Value);
                        result.AddRange(parsed.Select(p => KeyValuePair.Create(kvp.Key.Concat(p.Key).ToArray().As <MemberPath>(), p.Value)));
                    }

                    return(result);
                }

                // if we have a path stack and we find a parameter, then we can just copy over all paths from
                // that parameters mapping to the new mapping
                if (this._pathStack.Count > 0 && body.NodeType == ExpressionType.Parameter)
                {
                    // add all paths for the last parameter
                    var result = new Dictionary <MemberPath, ODataExpression>(this._pathStack.Peek(), MemberPathComparer);
                    return(result);
                }

                // a member path, where the path stack is non-empty and thus the path won't translate directly
                // for example: a => a.b.x, where a is not the root query parameter
                if (this._pathStack.Count > 0 && body.NodeType == ExpressionType.MemberAccess)
                {
                    // pull out the member path as going back to a parameter (similar to what we do when translating a member)
                    var reverseMemberPath = Traverse.Along((MemberExpression)body, me => me.Expression as MemberExpression)
                                            .ToArray();
                    if (reverseMemberPath[reverseMemberPath.Length - 1].Expression.NodeType != ExpressionType.Parameter)
                    {
                        throw new ODataCompileException("Expression '" + reverseMemberPath.Last().Expression + "' could not be compiled to OData as part of a projection");
                    }

                    // find all paths for the current parameter which are prefixes of this path
                    var memberPath = reverseMemberPath.Reverse().Select(me => me.Member).ToArray();
                    var result     = this._pathStack.Peek().Where(kvp => StartsWith(kvp.Key, prefix: memberPath))
                                     .ToDictionary(
                        // the new mapping has the same path, but without the prefix of the current parameter
                        kvp => kvp.Key.Skip(memberPath.Length).ToArray(),
                        kvp => kvp.Value,
                        MemberPathComparer
                        );
                    // if we didn't find any such paths, then this should be directly translatable. For example:
                    // q.Select(a => a.B).Select(b => b.Id), then no path starts with b.Id. Thus, we fall through to
                    // just translating b.Id
                    if (result.Count > 0)
                    {
                        return(result);
                    }
                }

                // finally, if the projection doesn't match any special patterns, then we simply try
                // to translate the projected value directly (e. g. a => a.Id + 2)
                var simpleResult = new Dictionary <MemberPath, ODataExpression>(MemberPathComparer)
                {
                    { Empty <MemberInfo> .Array, this._translator.TranslateInternal(body) },
                };

                return(simpleResult);
            }
Beispiel #44
0
            /// <summary>
            /// Calculates the required reason codes given the source type.
            /// </summary>
            /// <param name="request">The request.</param>
            /// <param name="requiredReasonCodes">The collection to which required reason codes are added.</param>
            /// <param name="transactionRequiredReasonCodeIds">The identifiers of reason codes required at transaction level.</param>
            /// <param name="reasonCodeRequirements">The collection of reason code requirements.</param>
            private static void CalculateRequiredReasonCodesBySourceType(
                CalculateRequiredReasonCodesServiceRequest request,
                Dictionary <string, ReasonCode> requiredReasonCodes,
                HashSet <string> transactionRequiredReasonCodeIds,
                HashSet <ReasonCodeRequirement> reasonCodeRequirements)
            {
                // Look up operation level reason codes if available.
                if (request.SourceType != ReasonCodeSourceType.None)
                {
                    ReasonCodeSettings settingsDictionary = GetReasonCodeSettings(request.RequestContext);
                    string             reasonCodeId       = settingsDictionary[request.SourceType];

                    if (!string.IsNullOrWhiteSpace(reasonCodeId))
                    {
                        GetReasonCodesDataRequest getReasonCodeRequest = new GetReasonCodesDataRequest(QueryResultSettings.AllRecords, new string[] { reasonCodeId });
                        IEnumerable <ReasonCode>  reasonCodes          = request.RequestContext.Execute <EntityDataServiceResponse <ReasonCode> >(getReasonCodeRequest).PagedEntityCollection.Results;

                        foreach (var reasonCode in reasonCodes)
                        {
                            if (IsTransactionSourceType(request.SourceType) &&
                                ShouldReasonCodeBeApplied(reasonCode, request.SalesTransaction))
                            {
                                if (!ContainsReasonCode(request.SalesTransaction.ReasonCodeLines, reasonCode.ReasonCodeId))
                                {
                                    requiredReasonCodes[reasonCode.ReasonCodeId] = reasonCode;
                                    transactionRequiredReasonCodeIds.Add(reasonCode.ReasonCodeId);
                                }

                                var triggeredReasonCodes = CalculateTriggeredReasonCodes(
                                    new ReasonCode[] { reasonCode }, request.SalesTransaction.ReasonCodeLines, request.RequestContext);

                                if (triggeredReasonCodes.Any())
                                {
                                    requiredReasonCodes.AddRange(triggeredReasonCodes.ToDictionary(rc => rc.ReasonCodeId, rc => rc));
                                    transactionRequiredReasonCodeIds.AddRange(triggeredReasonCodes.Select(rc => rc.ReasonCodeId));
                                }
                            }
                            else
                            {
                                foreach (var salesLine in request.SalesLines)
                                {
                                    if (ShouldReasonCodeBeApplied(reasonCode, request.SalesTransaction))
                                    {
                                        if (!ContainsReasonCode(salesLine.ReasonCodeLines, reasonCode.ReasonCodeId))
                                        {
                                            var reasonCodeRequirement = new ReasonCodeRequirement()
                                            {
                                                ReasonCodeId      = reasonCode.ReasonCodeId,
                                                SourceId          = salesLine.ProductId.ToString(CultureInfo.InvariantCulture),
                                                TableRefTypeValue = (int)ReasonCodeTableRefType.Item,
                                            };

                                            reasonCodeRequirements.Add(reasonCodeRequirement);
                                            requiredReasonCodes[reasonCode.ReasonCodeId] = reasonCode;
                                        }

                                        var triggeredReasonCodes = CalculateTriggeredReasonCodes(
                                            new ReasonCode[] { reasonCode }, salesLine.ReasonCodeLines, request.RequestContext);

                                        if (triggeredReasonCodes.Any())
                                        {
                                            requiredReasonCodes.AddRange(triggeredReasonCodes.ToDictionary(rc => rc.ReasonCodeId, rc => rc));
                                            reasonCodeRequirements.AddRange(triggeredReasonCodes.Select(rc => new ReasonCodeRequirement()
                                            {
                                                ReasonCodeId      = rc.ReasonCodeId,
                                                SourceId          = salesLine.ProductId.ToString(CultureInfo.InvariantCulture),
                                                TableRefTypeValue = (int)ReasonCodeTableRefType.Item,
                                            }));
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
 public void SetMessageSendingFlags(Dictionary <Type, MessageSendingFlags> flags)
 {
     _messageSendingFlags.AddRange(flags);
 }
Beispiel #46
0
        private async Task RefreshFundingStream(Reference fundingStream,
                                                SpecificationSummary specification,
                                                IDictionary <string, Provider> scopedProviders,
                                                IDictionary <string, ProviderCalculationResult> allCalculationResults,
                                                string jobId, Reference author,
                                                string correlationId,
                                                IEnumerable <PublishedProvider> existingPublishedProviders,
                                                string fundingPeriodId)
        {
            TemplateMetadataContents templateMetadataContents = await _policiesService.GetTemplateMetadataContents(fundingStream.Id, specification.FundingPeriod.Id, specification.TemplateIds[fundingStream.Id]);

            if (templateMetadataContents == null)
            {
                _logger.Information($"Unable to locate template meta data contents for funding stream:'{fundingStream.Id}' and template id:'{specification.TemplateIds[fundingStream.Id]}'");
                return;
            }

            IEnumerable <ProfileVariationPointer> variationPointers = await _specificationService.GetProfileVariationPointers(specification.Id) ?? ArraySegment <ProfileVariationPointer> .Empty;

            Dictionary <string, PublishedProvider> publishedProviders = new Dictionary <string, PublishedProvider>();

            foreach (PublishedProvider publishedProvider in existingPublishedProviders)
            {
                if (publishedProvider.Current.FundingStreamId == fundingStream.Id)
                {
                    publishedProviders.Add(publishedProvider.Current.ProviderId, publishedProvider);
                }
            }

            // Create PublishedProvider for providers which don't already have a record (eg ProviderID-FundingStreamId-FundingPeriodId)
            IDictionary <string, PublishedProvider> newProviders = _providerService.GenerateMissingPublishedProviders(scopedProviders.Values, specification, fundingStream, publishedProviders);

            publishedProviders.AddRange(newProviders);

            // Get TemplateMapping for calcs from Calcs API client nuget
            ApiResponse <Common.ApiClient.Calcs.Models.TemplateMapping> calculationMappingResult = await _calculationsApiClientPolicy.ExecuteAsync(() => _calculationsApiClient.GetTemplateMapping(specification.Id, fundingStream.Id));

            if (calculationMappingResult == null)
            {
                throw new Exception($"calculationMappingResult returned null for funding stream {fundingStream.Id}");
            }

            Common.ApiClient.Calcs.Models.TemplateMapping templateMapping = calculationMappingResult.Content;

            _logger.Information("Generating PublishedProviders for refresh");

            // Generate populated data for each provider in this funding line
            IDictionary <string, GeneratedProviderResult> generatedPublishedProviderData;

            try
            {
                generatedPublishedProviderData = _publishedProviderDataGenerator.Generate(templateMetadataContents, templateMapping, scopedProviders.Values, allCalculationResults);
            }
            catch (Exception ex)
            {
                _logger.Error(ex, "Exception during generating provider data");
                throw;
            }
            _logger.Information("Populated PublishedProviders for refresh");

            Dictionary <string, PublishedProvider> publishedProvidersToUpdate = new Dictionary <string, PublishedProvider>();

            Dictionary <string, PublishedProvider> existingPublishedProvidersToUpdate = new Dictionary <string, PublishedProvider>();

            FundingLine[] flattenedTemplateFundingLines = templateMetadataContents.RootFundingLines.Flatten(_ => _.FundingLines).ToArray();

            _logger.Information("Profiling providers for refresh");

            try
            {
                await ProfileProviders(publishedProviders, newProviders, generatedPublishedProviderData);
            }
            catch (Exception ex)
            {
                _logger.Error(ex, "Exception during generating provider profiling");

                if (ex is NonRetriableException)
                {
                    await _jobManagement.UpdateJobStatus(jobId, 0, 0, false, "Refresh job failed during generating provider profiling.");
                }

                throw;
            }

            _logger.Information("Finished profiling providers for refresh");

            _logger.Information("Start snapshots for published provider variations");
            // snapshot the current published providers so any changes aren't reflected when we detect variations later
            _variationService.SnapShot(publishedProviders, fundingStream.Id);
            _logger.Information("Finished snapshots for published provider variations");

            //we need enumerate a readonly cut of this as we add to it in some variations now (for missing providers not in scope)
            Dictionary <string, PublishedProvider> publishedProvidersReadonlyDictionary = publishedProviders.ToDictionary(_ => _.Key, _ => _.Value);

            _logger.Information($"Start getting funding configuration for funding stream '{fundingStream.Id}'");
            // set up the published providers context for error detection laterawait
            FundingConfiguration fundingConfiguration = await _policiesService.GetFundingConfiguration(fundingStream.Id, specification.FundingPeriod.Id);

            _logger.Information($"Retrieved funding stream configuration for '{fundingStream.Id}'");

            PublishedProvidersContext publishedProvidersContext = new PublishedProvidersContext
            {
                ScopedProviders         = scopedProviders.Values,
                SpecificationId         = specification.Id,
                ProviderVersionId       = specification.ProviderVersionId,
                CurrentPublishedFunding = (await _publishingResiliencePolicy.ExecuteAsync(() => _publishedFundingDataService.GetCurrentPublishedFunding(specification.Id, GroupingReason.Payment)))
                                          .Where(x => x.Current.GroupingReason == CalculateFunding.Models.Publishing.GroupingReason.Payment),
                OrganisationGroupResultsData = new Dictionary <string, HashSet <string> >(),
                FundingConfiguration         = fundingConfiguration
            };

            _logger.Information("Starting to process providers for variations and exclusions");

            foreach (KeyValuePair <string, PublishedProvider> publishedProvider in publishedProvidersReadonlyDictionary)
            {
                PublishedProviderVersion publishedProviderVersion = publishedProvider.Value.Current;

                string providerId = publishedProviderVersion.ProviderId;

                // this could be a retry and the key may not exist as the provider has been created as a successor so we need to skip
                if (!generatedPublishedProviderData.ContainsKey(publishedProvider.Key))
                {
                    continue;
                }

                GeneratedProviderResult generatedProviderResult = generatedPublishedProviderData[publishedProvider.Key];

                PublishedProviderExclusionCheckResult exclusionCheckResult =
                    _providerExclusionCheck.ShouldBeExcluded(generatedProviderResult, flattenedTemplateFundingLines);

                if (exclusionCheckResult.ShouldBeExcluded)
                {
                    if (newProviders.ContainsKey(publishedProvider.Key))
                    {
                        newProviders.Remove(publishedProvider.Key);
                        continue;
                    }

                    if (!_fundingLineValueOverride.TryOverridePreviousFundingLineValues(publishedProviderVersion, generatedProviderResult))
                    {
                        //there are no none null payment funding line values and we didn't have to override any previous
                        //version funding lines with a zero amount now they are all null so skip this published provider
                        //the updates check

                        continue;
                    }
                }

                bool publishedProviderUpdated = _publishedProviderDataPopulator.UpdatePublishedProvider(publishedProviderVersion,
                                                                                                        generatedProviderResult,
                                                                                                        scopedProviders[providerId],
                                                                                                        specification.TemplateIds[fundingStream.Id],
                                                                                                        newProviders.ContainsKey(publishedProvider.Key));

                _logger.Verbose($"Published provider '{publishedProvider.Key}' updated: '{publishedProviderUpdated}'");

                //reapply any custom profiles this provider has and internally check for errors
                _reApplyCustomProfiles.ProcessPublishedProvider(publishedProviderVersion);

                // process published provider and detect errors
                await _detection.ProcessPublishedProvider(publishedProvider.Value, publishedProvidersContext);

                if (publishedProviderUpdated && existingPublishedProviders.AnyWithNullCheck())
                {
                    IDictionary <string, PublishedProvider> newPublishedProviders = await _variationService.PrepareVariedProviders(generatedProviderResult.TotalFunding,
                                                                                                                                   publishedProviders,
                                                                                                                                   publishedProvider.Value,
                                                                                                                                   scopedProviders[providerId],
                                                                                                                                   fundingConfiguration?.Variations,
                                                                                                                                   variationPointers,
                                                                                                                                   fundingStream.Id,
                                                                                                                                   specification.ProviderVersionId);

                    if (!newPublishedProviders.IsNullOrEmpty())
                    {
                        newProviders.AddRange(newPublishedProviders);
                    }
                }

                if (!publishedProviderUpdated)
                {
                    continue;
                }

                if (!newProviders.ContainsKey(publishedProvider.Key))
                {
                    existingPublishedProvidersToUpdate.Add(publishedProvider.Key, publishedProvider.Value);
                }

                publishedProvidersToUpdate.Add(publishedProvider.Key, publishedProvider.Value);
            }

            _logger.Information("Finished processing providers for variations and exclusions");

            _logger.Information("Adding additional variation reasons");
            AddInitialPublishVariationReasons(newProviders.Values);
            _logger.Information("Finished adding additional variation reasons");

            _logger.Information("Starting to apply variations");

            if (!(await _variationService.ApplyVariations(publishedProvidersToUpdate, newProviders, specification.Id, jobId)))
            {
                await _jobManagement.UpdateJobStatus(jobId, 0, 0, false, "Refresh job failed with variations errors.");

                throw new NonRetriableException($"Unable to refresh funding. Variations generated {_variationService.ErrorCount} errors. Check log for details");
            }

            _logger.Information("Finished applying variations");

            _logger.Information($"Updating a total of {publishedProvidersToUpdate.Count} published providers");

            if (publishedProvidersToUpdate.Count > 0)
            {
                if (existingPublishedProvidersToUpdate.Count > 0 || newProviders.Count > 0)
                {
                    using (Transaction transaction = _transactionFactory.NewTransaction <RefreshService>())
                    {
                        try
                        {
                            // if any error occurs while updating or indexing then we need to re-index all published providers for consistency
                            transaction.Enroll(async() =>
                            {
                                await _publishedProviderVersionService.CreateReIndexJob(author, correlationId, specification.Id, jobId);
                            });

                            // Save updated PublishedProviders to cosmos and increment version status
                            if (existingPublishedProvidersToUpdate.Count > 0)
                            {
                                _logger.Information($"Saving updates to existing published providers. Total={existingPublishedProvidersToUpdate.Count}");
                                await _publishedProviderStatusUpdateService.UpdatePublishedProviderStatus(existingPublishedProvidersToUpdate.Values, author, PublishedProviderStatus.Updated, jobId, correlationId);

                                _logger.Information("Indexing existing PublishedProviders");
                                await _publishedProviderIndexerService.IndexPublishedProviders(existingPublishedProvidersToUpdate.Values.Select(_ => _.Current));
                            }

                            if (newProviders.Count > 0)
                            {
                                _logger.Information($"Saving new published providers. Total={newProviders.Count}");
                                await _publishedProviderStatusUpdateService.UpdatePublishedProviderStatus(newProviders.Values, author, PublishedProviderStatus.Draft, jobId, correlationId);

                                _logger.Information("Indexing newly added PublishedProviders");
                                await _publishedProviderIndexerService.IndexPublishedProviders(newProviders.Values.Select(_ => _.Current));
                            }

                            transaction.Complete();
                        }
                        catch (Exception ex)
                        {
                            await transaction.Compensate();

                            throw;
                        }
                    }

                    _logger.Information("Creating generate Csv jobs");

                    IGeneratePublishedFundingCsvJobsCreation generateCsvJobs = _generateCsvJobsLocator
                                                                               .GetService(GeneratePublishingCsvJobsCreationAction.Refresh);
                    IEnumerable <string> fundingLineCodes = await _publishedFundingDataService.GetPublishedProviderFundingLines(specification.Id);

                    IEnumerable <string>           fundingStreamIds = Array.Empty <string>();
                    PublishedFundingCsvJobsRequest publishedFundingCsvJobsRequest = new PublishedFundingCsvJobsRequest
                    {
                        SpecificationId  = specification.Id,
                        CorrelationId    = correlationId,
                        User             = author,
                        FundingLineCodes = fundingLineCodes,
                        FundingStreamIds = fundingStreamIds,
                        FundingPeriodId  = fundingPeriodId
                    };
                    await generateCsvJobs.CreateJobs(publishedFundingCsvJobsRequest);
                }
            }
        }
Beispiel #47
0
        //TODO with the rollback information that's now being stored, rollback could be down without needing the block
        private void RollbackUtxo(Block block)
        {
            //TODO currently a MissingDataException will get thrown if the rollback information is missing
            //TODO rollback is still possible if any resurrecting transactions can be found
            //TODO the network does not allow arbitrary transaction lookup, but if the transactions can be retrieved then this code should allow it
            //TODO this should be handled by a distinct worker that rebuilds rollback information

            var spentTransactions = new Dictionary <UInt256, SpentTx>();

            spentTransactions.AddRange(this.spentTransactionsCache[block.Hash]);

            var spentOutputs = new Dictionary <TxOutputKey, TxOutput>();

            spentOutputs.AddRange(this.spentOutputsCache[block.Hash]);

            for (var txIndex = block.Transactions.Count - 1; txIndex >= 1; txIndex--)
            {
                var tx = block.Transactions[txIndex];

                // MONITOR: BeforeRemoveTransaction
                if (this.chainStateMonitor != null)
                {
                    this.chainStateMonitor.BeforeRemoveTransaction(ChainPosition.Fake(), tx);
                }

                // remove outputs
                this.Unmint(tx, this.LastBlock, isCoinbase: false);

                // remove inputs in reverse order
                for (var inputIndex = tx.Inputs.Count - 1; inputIndex >= 0; inputIndex--)
                {
                    var input = tx.Inputs[inputIndex];
                    this.Unspend(input, this.LastBlock, spentTransactions, spentOutputs);
                }

                // MONITOR: AfterRemoveTransaction
                if (this.chainStateMonitor != null)
                {
                    this.chainStateMonitor.AfterRemoveTransaction(ChainPosition.Fake(), tx);
                }
            }

            var coinbaseTx = block.Transactions[0];

            // MONITOR: BeforeRemoveTransaction
            if (this.chainStateMonitor != null)
            {
                this.chainStateMonitor.BeforeRemoveTransaction(ChainPosition.Fake(), coinbaseTx);
            }

            // remove coinbase outputs
            this.Unmint(coinbaseTx, this.LastBlock, isCoinbase: true);

            for (var inputIndex = coinbaseTx.Inputs.Count - 1; inputIndex >= 0; inputIndex--)
            {
                // MONITOR: UnCoinbaseInput
                if (this.chainStateMonitor != null)
                {
                    this.chainStateMonitor.UnCoinbaseInput(ChainPosition.Fake(), coinbaseTx.Inputs[inputIndex]);
                }
            }

            // MONITOR: AfterRemoveTransaction
            if (this.chainStateMonitor != null)
            {
                this.chainStateMonitor.AfterRemoveTransaction(ChainPosition.Fake(), coinbaseTx);
            }
        }
        /// <summary>
        /// Converts <see cref="Type"/> to <see cref="OpenApiSchema"/>.
        /// </summary>
        /// <param name="type"><see cref="Type"/> instance.</param>
        /// <param name="namingStrategy"><see cref="NamingStrategy"/> instance to create the JSON schema from .NET Types.</param>
        /// <param name="attribute"><see cref="OpenApiSchemaVisibilityAttribute"/> instance. Default is <c>null</c>.</param>
        /// <param name="returnSingleSchema">Value indicating whether to return single schema or not.</param>
        /// <param name="depth">Recurring depth.</param>
        /// <returns>Returns <see cref="Dictionary{String, OpenApiSchema}"/> instance.</returns>
        public static Dictionary <string, OpenApiSchema> ToOpenApiSchemas(this Type type, NamingStrategy namingStrategy, OpenApiSchemaVisibilityAttribute attribute = null, bool returnSingleSchema = false, int depth = 0)
        {
            type.ThrowIfNullOrDefault();

            var schema     = (OpenApiSchema)null;
            var schemeName = type.GetOpenApiTypeName(namingStrategy);

            if (depth == 8)
            {
                schema = new OpenApiSchema()
                {
                    Type   = type.ToDataType(),
                    Format = type.ToDataFormat()
                };

                return(new Dictionary <string, OpenApiSchema>()
                {
                    { schemeName, schema }
                });
            }

            depth++;

            if (type.IsJObjectType())
            {
                schema = typeof(object).ToOpenApiSchemas(namingStrategy, null, true, depth).Single().Value;

                return(new Dictionary <string, OpenApiSchema>()
                {
                    { schemeName, schema }
                });
            }

            if (type.IsOpenApiNullable(out var unwrappedValueType))
            {
                schema          = unwrappedValueType.ToOpenApiSchemas(namingStrategy, null, true, depth).Single().Value;
                schema.Nullable = true;

                return(new Dictionary <string, OpenApiSchema>()
                {
                    { schemeName, schema }
                });
            }

            schema = new OpenApiSchema()
            {
                Type   = type.ToDataType(),
                Format = type.ToDataFormat()
            };

            if (!attribute.IsNullOrDefault())
            {
                var visibility = new OpenApiString(attribute.Visibility.ToDisplayName());

                schema.Extensions.Add("x-ms-visibility", visibility);
            }

            if (type.IsUnflaggedEnumType())
            {
                var converterAttribute = type.GetCustomAttribute <JsonConverterAttribute>();
                if (!converterAttribute.IsNullOrDefault() &&
                    typeof(StringEnumConverter).IsAssignableFrom(converterAttribute.ConverterType))
                {
                    var enums = type.ToOpenApiStringCollection(namingStrategy);

                    schema.Type    = "string";
                    schema.Format  = null;
                    schema.Enum    = enums;
                    schema.Default = enums.First();
                }
                else
                {
                    var enums = type.ToOpenApiIntegerCollection();

                    schema.Enum    = enums;
                    schema.Default = enums.First();
                }
            }

            if (type.IsSimpleType())
            {
                return(new Dictionary <string, OpenApiSchema>()
                {
                    { schemeName, schema }
                });
            }

            if (type.IsOpenApiDictionary())
            {
                schema.AdditionalProperties = type.GetGenericArguments()[1].ToOpenApiSchemas(namingStrategy, null, true, depth).Single().Value;

                return(new Dictionary <string, OpenApiSchema>()
                {
                    { schemeName, schema }
                });
            }

            if (type.IsOpenApiArray())
            {
                schema.Type  = "array";
                schema.Items = (type.GetElementType() ?? type.GetGenericArguments()[0]).ToOpenApiSchemas(namingStrategy, null, true, depth).Single().Value;

                return(new Dictionary <string, OpenApiSchema>()
                {
                    { schemeName, schema }
                });
            }

            var allProperties = type.IsInterface
                                    ? new[] { type }.Concat(type.GetInterfaces()).SelectMany(i => i.GetProperties())
                                    : type.GetProperties();
            var properties = allProperties.Where(p => !p.ExistsCustomAttribute <JsonIgnoreAttribute>());

            var retVal = new Dictionary <string, OpenApiSchema>();

            foreach (var property in properties)
            {
                var visibility   = property.GetCustomAttribute <OpenApiSchemaVisibilityAttribute>(inherit: false);
                var propertyName = property.GetJsonPropertyName(namingStrategy);

                var ts = property.DeclaringType.GetGenericArguments();
                if (!ts.Any())
                {
                    if (property.PropertyType.IsUnflaggedEnumType() && !returnSingleSchema)
                    {
                        var recur1 = property.PropertyType.ToOpenApiSchemas(namingStrategy, visibility, false, depth);
                        retVal.AddRange(recur1);

                        var enumReference = new OpenApiReference()
                        {
                            Type = ReferenceType.Schema,
                            Id   = property.PropertyType.GetOpenApiReferenceId(false, false)
                        };

                        var schema1 = new OpenApiSchema()
                        {
                            Reference = enumReference
                        };
                        schema.Properties[namingStrategy.GetPropertyName(propertyName, false)] = schema1;
                    }
                    else if (property.PropertyType.IsSimpleType() || Nullable.GetUnderlyingType(property.PropertyType) != null || returnSingleSchema)
                    {
                        schema.Properties[namingStrategy.GetPropertyName(propertyName, false)] = property.PropertyType.ToOpenApiSchemas(namingStrategy, visibility, true, depth).Single().Value;
                    }
                    else if (property.PropertyType.IsOpenApiDictionary())
                    {
                        var elementType = property.PropertyType.GetGenericArguments()[1];
                        if (elementType.IsSimpleType() || elementType.IsOpenApiDictionary() || elementType.IsOpenApiArray())
                        {
                            schema.Properties[namingStrategy.GetPropertyName(propertyName, false)] = property.PropertyType.ToOpenApiSchemas(namingStrategy, visibility, true, depth).Single().Value;
                        }
                        else
                        {
                            var recur1 = elementType.ToOpenApiSchemas(namingStrategy, visibility, false, depth);
                            retVal.AddRange(recur1);

                            var elementReference = new OpenApiReference()
                            {
                                Type = ReferenceType.Schema,
                                Id   = elementType.GetOpenApiReferenceId(false, false)
                            };

                            var dictionarySchema = new OpenApiSchema()
                            {
                                Type = "object",
                                AdditionalProperties = new OpenApiSchema()
                                {
                                    Reference = elementReference
                                }
                            };

                            schema.Properties[namingStrategy.GetPropertyName(propertyName, false)] = dictionarySchema;
                        }
                    }
                    else if (property.PropertyType.IsOpenApiArray())
                    {
                        var elementType = property.PropertyType.GetElementType() ?? property.PropertyType.GetGenericArguments()[0];
                        if (elementType.IsSimpleType() || elementType.IsOpenApiDictionary() || elementType.IsOpenApiArray())
                        {
                            schema.Properties[namingStrategy.GetPropertyName(propertyName, false)] = property.PropertyType.ToOpenApiSchemas(namingStrategy, visibility, true, depth).Single().Value;
                        }
                        else
                        {
                            var elementReference = elementType.ToOpenApiSchemas(namingStrategy, visibility, false, depth);
                            retVal.AddRange(elementReference);

                            var reference1 = new OpenApiReference()
                            {
                                Type = ReferenceType.Schema,
                                Id   = elementType.GetOpenApiReferenceId(false, false)
                            };
                            var arraySchema = new OpenApiSchema()
                            {
                                Type  = "array",
                                Items = new OpenApiSchema()
                                {
                                    Reference = reference1
                                }
                            };

                            schema.Properties[namingStrategy.GetPropertyName(propertyName, false)] = arraySchema;
                        }
                    }
                    else
                    {
                        var recur1 = property.PropertyType.ToOpenApiSchemas(namingStrategy, visibility, false, depth);
                        retVal.AddRange(recur1);

                        var reference1 = new OpenApiReference()
                        {
                            Type = ReferenceType.Schema,
                            Id   = property.PropertyType.GetOpenApiReferenceId(false, false)
                        };

                        var schema1 = new OpenApiSchema()
                        {
                            Reference = reference1
                        };

                        schema.Properties[namingStrategy.GetPropertyName(propertyName, false)] = schema1;
                    }

                    continue;
                }

                var reference = new OpenApiReference()
                {
                    Type = ReferenceType.Schema,
                    Id   = property.PropertyType.GetOpenApiRootReferenceId()
                };

                var referenceSchema = new OpenApiSchema()
                {
                    Reference = reference
                };

                if (!ts.Contains(property.PropertyType))
                {
                    if (property.PropertyType.IsOpenApiDictionary())
                    {
                        reference.Id = property.PropertyType.GetOpenApiReferenceId(true, false);
                        var dictionarySchema = new OpenApiSchema()
                        {
                            Type = "object",
                            AdditionalProperties = referenceSchema
                        };

                        schema.Properties[namingStrategy.GetPropertyName(propertyName, false)] = dictionarySchema;

                        continue;
                    }

                    if (property.PropertyType.IsOpenApiArray())
                    {
                        reference.Id = property.PropertyType.GetOpenApiReferenceId(false, true);
                        var arraySchema = new OpenApiSchema()
                        {
                            Type  = "array",
                            Items = referenceSchema
                        };

                        schema.Properties[namingStrategy.GetPropertyName(propertyName, false)] = arraySchema;

                        continue;
                    }

                    schema.Properties[namingStrategy.GetPropertyName(propertyName, false)] = property.PropertyType.ToOpenApiSchemas(namingStrategy, visibility, true, depth).Single().Value;

                    continue;
                }

                schema.Properties[namingStrategy.GetPropertyName(propertyName, false)] = referenceSchema;
            }

            retVal[schemeName] = schema;

            return(retVal);
        }
Beispiel #49
0
 public static void ReplaceContents <T, S>(this Dictionary <T, S> source, Dictionary <T, S> collection)
 {
     source.Clear();
     source.AddRange(collection);
 }
Beispiel #50
0
    public Dictionary <string, string> Configure(ISynapseDalConfig conifg)
    {
        ComponentizedDalConfig cdc = null;

        if (conifg != null)
        {
            string s = YamlHelpers.Serialize(conifg.Config);
            cdc = YamlHelpers.Deserialize <ComponentizedDalConfig>(s);
        }
        else
        {
            cdc = (ComponentizedDalConfig)GetDefaultConfig();
        }

        Dictionary <string, string> secProps = new Dictionary <string, string>();
        ComponentizedDalItem        cdi      = cdc.DalComponents.SingleOrDefault(r => r.Key.Equals(cdc.SecurityProviderKey, StringComparison.OrdinalIgnoreCase));

        if (cdi != null)
        {
            _planSecurityProvider = AssemblyLoader.Load <IPlanSecurityProvider>(cdi.Type, string.Empty);
            secProps = _planSecurityProvider.Configure(new ConfigWrapper {
                Config = cdi.Config, Type = cdi.Type
            });
        }
        else
        {
            throw new TypeLoadException($"Could not load {cdi.Key}/{cdi.Type} for {nameof( IPlanSecurityProvider )}");
        }

        Dictionary <string, string> execProps = new Dictionary <string, string>();

        cdi = cdc.DalComponents.SingleOrDefault(r => r.Key.Equals(cdc.ExecuteReaderKey, StringComparison.OrdinalIgnoreCase));
        if (cdi != null)
        {
            _planExecuteReader = AssemblyLoader.Load <IPlanExecuteReader>(cdi.Type, string.Empty);
            execProps          = _planExecuteReader.Configure(new ConfigWrapper {
                Config = cdi.Config, Type = cdi.Type
            });
        }
        else
        {
            throw new TypeLoadException($"Could not load {cdi.Key}/{cdi.Type} for {nameof( IPlanExecuteReader )}");
        }

        Dictionary <string, string> histProps = new Dictionary <string, string>();

        cdi = cdc.DalComponents.SingleOrDefault(r => r.Key.Equals(cdc.HistoryWriterKey, StringComparison.OrdinalIgnoreCase));
        if (cdi != null)
        {
            _planHistoryWriter = AssemblyLoader.Load <IPlanHistoryWriter>(cdi.Type, string.Empty);
            histProps          = _planHistoryWriter.Configure(new ConfigWrapper {
                Config = cdi.Config, Type = cdi.Type
            });
        }
        else
        {
            throw new TypeLoadException($"Could not load {cdi.Key}/{cdi.Type} for {nameof( IPlanHistoryWriter )}");
        }


        string name = nameof(ComponentizedDal);
        Dictionary <string, string> props = new Dictionary <string, string>
        {
            { $"{name} ExecuteReaderKey", cdc.ExecuteReaderKey },
            { $"{name} HistoryWriterKey", cdc.HistoryWriterKey },
            { $"{name} SecurityProviderKey", cdc.SecurityProviderKey }
        };

        props.AddRange(execProps);
        props.AddRange(histProps);
        props.AddRange(secProps);
        return(props);
    }
Beispiel #51
0
    static Parser() {
      Registers8 = new Dictionary<string, Register>(){
        {"AL", AL },
        {"AH", AH },
        {"BL", BL },
        {"BH", BH },
        {"CL", CL },
        {"CH", CH },
        {"DL", DL },
        {"DH", DH },
                 };

      Registers16 = new Dictionary<string, Register>()
                    {
        {"AX", AX },
        {"BX", BX },
        {"CX", CX },
        {"DX", DX },
                    };

      Registers32 = new Dictionary<string, Register>()
                    {
        {"EAX", EAX },
        {"EBX", EBX },
        {"ECX", ECX },
        {"EDX", EDX },
                    };

      RegistersIdx = new Dictionary<string, Register>()
                    {
        {"ESI", ESI },
        {"EDI", EDI },
        {"ESP", ESP },
        {"EBP", EBP },
                    };

      var xRegisters = new Dictionary<string, Register>();
      xRegisters.AddRange(Registers8);
      xRegisters.AddRange(Registers16);
      xRegisters.AddRange(Registers32);
      xRegisters.AddRange(RegistersIdx);
      Registers = xRegisters;

      var xRegistersAddr = new Dictionary<string, Register>();
      xRegistersAddr.AddRange(Registers32);
      xRegistersAddr.AddRange(RegistersIdx);
      RegistersAddr = xRegistersAddr;
    }
        /// <summary>
        /// Retrieve a <see cref="IAsyncEnumerator{T}"/> using a SOQL query. Batches will be retrieved asynchronously.
        /// <para>When using the iterator, the initial result batch will be returned as soon as it is received. The additional result batches will be retrieved only as needed.</para>
        /// </summary>
        /// <param name="queryString">SOQL query string, without any URL escaping/encoding</param>
        /// <param name="queryAll">Optional. True if deleted records are to be included.await Defaults to false.</param>
        /// <param name="batchSize">Optional. Size of result batches between 200 and 2000</param>
        /// <returns><see cref="IAsyncEnumerator{T}"/> of results</returns>
        public IAsyncEnumerator <T> QueryAsyncEnumerator <T>(string queryString, bool queryAll = false, int?batchSize = null)
        {
            Dictionary <string, string> headers = new Dictionary <string, string>();

            //Add call options
            Dictionary <string, string> callOptions = HeaderFormatter.SforceCallOptions(ClientName);

            headers.AddRange(callOptions);

            //Add query options headers if batch size specified
            if (batchSize.HasValue)
            {
                Dictionary <string, string> queryOptions = HeaderFormatter.SforceQueryOptions(batchSize.Value);
                headers.AddRange(queryOptions);
            }

            var jsonClient = new JsonClient(AccessToken, _httpClient);

            // Enumerator on the current batch items
            IEnumerator <T> currentBatchEnumerator = null;
            var             done           = false;
            var             nextRecordsUri = UriFormatter.Query(InstanceUrl, ApiVersion, queryString, queryAll);

            return(AsyncEnumerable.CreateEnumerator(MoveNextAsync, Current, Dispose));

            async Task <bool> MoveNextAsync(CancellationToken token)
            {
                if (token.IsCancellationRequested)
                {
                    return(false);
                }

                // If items remain in the current Batch enumerator, go to next item
                if (currentBatchEnumerator?.MoveNext() == true)
                {
                    return(true);
                }

                // if done, no more items.
                if (done)
                {
                    return(false);
                }

                // else : no enumerator or currentBatchEnumerator ended
                // so get the next batch
                var qr = await jsonClient.HttpGetAsync <QueryResult <T> >(nextRecordsUri, headers);

#if DEBUG
                Debug.WriteLine($"Got query resuts, {qr.TotalSize} totalSize, {qr.Records.Count} in this batch, final batch: {qr.Done}");
#endif

                currentBatchEnumerator = qr.Records.GetEnumerator();

                if (!string.IsNullOrEmpty(qr.NextRecordsUrl))
                {
                    nextRecordsUri = new Uri(new Uri(InstanceUrl), qr.NextRecordsUrl);
                    done           = false;
                }
                else
                {
                    //Normally if query has remaining batches, NextRecordsUrl will have a value, and Done will be false.
                    //In case of some unforseen error, flag the result as done if we're missing the NextRecordsURL
                    done = true;
                }

                return(currentBatchEnumerator.MoveNext());
            }

            T Current()
            {
                return(currentBatchEnumerator == null ? default(T) : currentBatchEnumerator.Current);
            }

            void Dispose()
            {
                currentBatchEnumerator?.Dispose();
                jsonClient.Dispose();
            }
        }
		internal Task<bool> RunBuildAsync(CancellationToken cancellationToken)
		{
			Dictionary<string, string> globalProperties = new Dictionary<string, string>();
			globalProperties.AddRange(SD.MSBuildEngine.GlobalBuildProperties);
			
			foreach (KeyValuePair<string, string> pair in options.Properties) {
				LoggingService.Debug("Setting property " + pair.Key + " to '" + pair.Value + "'");
				globalProperties[pair.Key] = pair.Value;
			}
			globalProperties["Configuration"] = options.Configuration;
			if (options.Platform == "Any CPU")
				globalProperties["Platform"] = "AnyCPU";
			else
				globalProperties["Platform"] = options.Platform;
			
			InterestingTasks.AddRange(parentBuildEngine.CompileTaskNames);
			
			loggers.Add(new SharpDevelopLogger(this));
			if (options.BuildOutputVerbosity == BuildOutputVerbosity.Diagnostic) {
				this.ReportMessageEvents = true;
				this.ReportAllTaskFinishedEvents = true;
				this.ReportAllTaskStartedEvents = true;
				this.ReportTargetFinishedEvents = true;
				this.ReportTargetStartedEvents = true;
				this.ReportUnknownEvents = true;
				loggers.Add(new SDConsoleLogger(feedbackSink, LoggerVerbosity.Diagnostic));
				globalProperties["MSBuildTargetsVerbose"] = "true";
			}
			//loggers.Add(new BuildLogFileLogger(project.FileName + ".log", LoggerVerbosity.Diagnostic));
			foreach (IMSBuildAdditionalLogger loggerProvider in parentBuildEngine.AdditionalMSBuildLoggers) {
				loggers.Add(loggerProvider.CreateLogger(this));
			}
			
			loggerChain = new EndOfChain(this);
			foreach (IMSBuildLoggerFilter loggerFilter in parentBuildEngine.MSBuildLoggerFilters) {
				loggerChain = loggerFilter.CreateFilter(this, loggerChain) ?? loggerChain;
			}
			
			WriteAdditionalTargetsToTempFile(globalProperties);
			
			BuildJob job = new BuildJob();
			job.ProjectFileName = projectFileName;
			job.Target = options.Target.TargetName;
			
			// First remove the flags for the controllable events.
			job.EventMask = EventTypes.All & ~ControllableEvents;
			// Add back active controllable events.
			if (ReportMessageEvents)
				job.EventMask |= EventTypes.Message;
			if (ReportTargetStartedEvents)
				job.EventMask |= EventTypes.TargetStarted;
			if (ReportTargetFinishedEvents)
				job.EventMask |= EventTypes.TargetFinished;
			if (ReportAllTaskStartedEvents)
				job.EventMask |= EventTypes.TaskStarted;
			if (ReportAllTaskFinishedEvents)
				job.EventMask |= EventTypes.TaskFinished;
			if (ReportUnknownEvents)
				job.EventMask |= EventTypes.Unknown;
			
			if (!(ReportAllTaskStartedEvents && ReportAllTaskFinishedEvents)) {
				// just some TaskStarted & TaskFinished events should be reported
				job.InterestingTaskNames.AddRange(InterestingTasks);
			}
			foreach (var pair in globalProperties) {
				job.Properties.Add(pair.Key, pair.Value);
			}
			
			foreach (ILogger logger in loggers) {
				logger.Initialize(eventSource);
			}
			
			tcs = new TaskCompletionSource<bool>();
			if (projectMinimumSolutionVersion <= SolutionFormatVersion.VS2008) {
				if (DotnetDetection.IsDotnet35SP1Installed()) {
					BuildWorkerManager.MSBuild35.RunBuildJob(job, loggerChain, OnDone, cancellationToken);
				} else {
					loggerChain.HandleError(new BuildError(job.ProjectFileName, ".NET 3.5 SP1 is required to build this project."));
					tcs.SetResult(false);
				}
			} else {
				BuildWorkerManager.MSBuild40.RunBuildJob(job, loggerChain, OnDone, cancellationToken);
			}
			return tcs.Task;
		}
        internal Task <bool> RunBuildAsync(CancellationToken cancellationToken)
        {
            Dictionary <string, string> globalProperties = new Dictionary <string, string>();

            globalProperties.AddRange(SD.MSBuildEngine.GlobalBuildProperties);

            foreach (KeyValuePair <string, string> pair in options.Properties)
            {
                LoggingService.Debug("Setting property " + pair.Key + " to '" + pair.Value + "'");
                globalProperties[pair.Key] = pair.Value;
            }
            globalProperties["Configuration"] = options.Configuration;
            if (options.Platform == "Any CPU")
            {
                globalProperties["Platform"] = "AnyCPU";
            }
            else
            {
                globalProperties["Platform"] = options.Platform;
            }

            InterestingTasks.AddRange(parentBuildEngine.CompileTaskNames);

            loggers.Add(new SharpDevelopLogger(this));
            if (options.BuildOutputVerbosity == BuildOutputVerbosity.Diagnostic)
            {
                this.ReportMessageEvents         = true;
                this.ReportAllTaskFinishedEvents = true;
                this.ReportAllTaskStartedEvents  = true;
                this.ReportTargetFinishedEvents  = true;
                this.ReportTargetStartedEvents   = true;
                this.ReportUnknownEvents         = true;
                loggers.Add(new SDConsoleLogger(feedbackSink, LoggerVerbosity.Diagnostic));
                globalProperties["MSBuildTargetsVerbose"] = "true";
            }
            //loggers.Add(new BuildLogFileLogger(project.FileName + ".log", LoggerVerbosity.Diagnostic));
            foreach (IMSBuildAdditionalLogger loggerProvider in parentBuildEngine.AdditionalMSBuildLoggers)
            {
                loggers.Add(loggerProvider.CreateLogger(this));
            }

            loggerChain = new EndOfChain(this);
            foreach (IMSBuildLoggerFilter loggerFilter in parentBuildEngine.MSBuildLoggerFilters)
            {
                loggerChain = loggerFilter.CreateFilter(this, loggerChain) ?? loggerChain;
            }

            WriteAdditionalTargetsToTempFile(globalProperties);

            BuildJob job = new BuildJob();

            job.ProjectFileName = projectFileName;
            job.Target          = options.Target.TargetName;

            // First remove the flags for the controllable events.
            job.EventMask = EventTypes.All & ~ControllableEvents;
            // Add back active controllable events.
            if (ReportMessageEvents)
            {
                job.EventMask |= EventTypes.Message;
            }
            if (ReportTargetStartedEvents)
            {
                job.EventMask |= EventTypes.TargetStarted;
            }
            if (ReportTargetFinishedEvents)
            {
                job.EventMask |= EventTypes.TargetFinished;
            }
            if (ReportAllTaskStartedEvents)
            {
                job.EventMask |= EventTypes.TaskStarted;
            }
            if (ReportAllTaskFinishedEvents)
            {
                job.EventMask |= EventTypes.TaskFinished;
            }
            if (ReportUnknownEvents)
            {
                job.EventMask |= EventTypes.Unknown;
            }

            if (!(ReportAllTaskStartedEvents && ReportAllTaskFinishedEvents))
            {
                // just some TaskStarted & TaskFinished events should be reported
                job.InterestingTaskNames.AddRange(InterestingTasks);
            }
            foreach (var pair in globalProperties)
            {
                job.Properties.Add(pair.Key, pair.Value);
            }

            foreach (ILogger logger in loggers)
            {
                logger.Initialize(eventSource);
            }

            tcs = new TaskCompletionSource <bool>();
            if (projectMinimumSolutionVersion <= SolutionFormatVersion.VS2008)
            {
                if (DotnetDetection.IsDotnet35SP1Installed())
                {
                    BuildWorkerManager.MSBuild35.RunBuildJob(job, loggerChain, OnDone, cancellationToken);
                }
                else
                {
                    loggerChain.HandleError(new BuildError(job.ProjectFileName, ".NET 3.5 SP1 is required to build this project."));
                    tcs.SetResult(false);
                }
            }
            else
            {
                if (DotnetDetection.IsBuildTools2013Installed())
                {
                    BuildWorkerManager.MSBuild120.RunBuildJob(job, loggerChain, OnDone, cancellationToken);
                }
                else
                {
                    BuildWorkerManager.MSBuild40.RunBuildJob(job, loggerChain, OnDone, cancellationToken);
                }
            }
            return(tcs.Task);
        }
 private async Task BuildFlagAsync()
 {
     await this.dataCenter.FlagManager.Source.CursorAsync(z =>
     {
         var type = (int)z.Type;
         var dest = this.flagRefs.GetOrCreateValue(type);
         if (string.IsNullOrEmpty(z.Value) || z.Id != JryFlag.BuildFlagId(z.Type, z.Value))
         {
             if (Debugger.IsAttached) Debugger.Break();
             Debug.Assert(false);
         }
         dest.Add(z.Value, z.Count);
     });
     foreach (var dictPair in this.flagRefs)
     {
         var d = new Dictionary<string, int>(dictPair.Value.Count);
         d.AddRange(dictPair.Value.ToList());
         this.originFlagRefs[dictPair.Key] = d;
     }
 }
Beispiel #56
0
        private void PopulateProductExportConfiguration(Dictionary <string, Func <CatalogProduct, string> > configuration, IEnumerable <CatalogProduct> products)
        {
            configuration.Add("Sku", (product) =>
            {
                return(product.Code);
            });

            configuration.Add("ParentSku", (product) =>
            {
                return(product.MainProduct != null ? product.MainProduct.Code : String.Empty);
            });

            //Category
            configuration.Add("Category", (product) =>
            {
                if (product.CategoryId != null)
                {
                    var category = _categoryService.GetById(product.CategoryId);
                    var path     = String.Join("/", category.Parents.Select(x => x.Name).Concat(new string[] { category.Name }));
                    return(path);
                }
                return(String.Empty);
            });


            //Scalar Properties
            var exportScalarFields = ReflectionUtility.GetPropertyNames <CatalogProduct>(x => x.Id, x => x.MainProductId, x => x.CategoryId, x => x.Name, x => x.IsActive, x => x.IsBuyable, x => x.TrackInventory,
                                                                                         x => x.ManufacturerPartNumber, x => x.Gtin, x => x.MeasureUnit, x => x.WeightUnit, x => x.Weight,
                                                                                         x => x.Height, x => x.Length, x => x.Width, x => x.TaxType, x => x.ShippingType,
                                                                                         x => x.ProductType, x => x.Vendor, x => x.DownloadType, x => x.DownloadExpiration, x => x.HasUserAgreement);

            configuration.AddRange(exportScalarFields.Select(x => new KeyValuePair <string, Func <CatalogProduct, string> >(x, null)));

            configuration.Add("PrimaryImage", (product) =>
            {
                if (product.Assets != null)
                {
                    var image = product.Assets.Where(x => x.Type == ItemAssetType.Image && x.Group == "primaryimage").FirstOrDefault();
                    if (image != null)
                    {
                        return(_blobUrlResolver.GetAbsoluteUrl(image.Url));
                    }
                }
                return(String.Empty);
            });

            configuration.Add("AltImage", (product) =>
            {
                if (product.Assets != null)
                {
                    var image = product.Assets.Where(x => x.Type == ItemAssetType.Image && x.Group != "primaryimage").FirstOrDefault();
                    if (image != null)
                    {
                        return(_blobUrlResolver.GetAbsoluteUrl(image.Url));
                    }
                }
                return(String.Empty);
            });

            configuration.Add("Review", (product) =>
            {
                if (product.Reviews != null)
                {
                    var review = product.Reviews.FirstOrDefault();
                    if (review != null)
                    {
                        return(review.Content ?? String.Empty);
                    }
                }
                return(String.Empty);
            });

            configuration.Add("SeoUrl", (product) =>
            {
                if (product.SeoInfos != null)
                {
                    var seoInfo = product.SeoInfos.FirstOrDefault();
                    if (seoInfo != null)
                    {
                        return(seoInfo.SemanticUrl ?? String.Empty);
                    }
                }
                return(String.Empty);
            });
            configuration.Add("SeoTitle", (product) =>
            {
                if (product.SeoInfos != null)
                {
                    var seoInfo = product.SeoInfos.FirstOrDefault();
                    if (seoInfo != null)
                    {
                        return(seoInfo.PageTitle ?? String.Empty);
                    }
                }
                return(String.Empty);
            });
            configuration.Add("SeoDescription", (product) =>
            {
                if (product.SeoInfos != null)
                {
                    var seoInfo = product.SeoInfos.FirstOrDefault();
                    if (seoInfo != null)
                    {
                        return(seoInfo.MetaDescription ?? String.Empty);
                    }
                }
                return(String.Empty);
            });

            //Prices
            configuration.Add("PriceId", (product) =>
            {
                var bestPrice = product.Prices.Any() ? product.Prices.FirstOrDefault() : null;
                return(bestPrice != null ? bestPrice.Id : String.Empty);
            });
            configuration.Add("SalePrice", (product) =>
            {
                var bestPrice = product.Prices.Any() ? product.Prices.FirstOrDefault() : null;
                return(bestPrice != null ? (bestPrice.Sale != null ? bestPrice.Sale.Value.ToString(CultureInfo.InvariantCulture) : String.Empty) : String.Empty);
            });
            configuration.Add("Price", (product) =>
            {
                var bestPrice = product.Prices.Any() ? product.Prices.FirstOrDefault() : null;
                return(bestPrice != null ? bestPrice.List.ToString(CultureInfo.InvariantCulture) : String.Empty);
            });
            configuration.Add("Currency", (product) =>
            {
                var bestPrice = product.Prices.Any() ? product.Prices.FirstOrDefault() : null;
                return(bestPrice != null ? bestPrice.Currency.ToString() : String.Empty);
            });

            //Inventories
            configuration.Add("FulfilmentCenterId", (product) =>
            {
                var inventory = product.Inventories.Any() ? product.Inventories.FirstOrDefault() : null;
                return(inventory != null ? inventory.FulfillmentCenterId : String.Empty);
            });
            configuration.Add("AllowBackorder", (product) =>
            {
                var inventory = product.Inventories.Any() ? product.Inventories.FirstOrDefault() : null;
                return(inventory != null ? inventory.AllowBackorder.ToString() : String.Empty);
            });
            configuration.Add("Quantity", (product) =>
            {
                var inventory = product.Inventories.Any() ? product.Inventories.FirstOrDefault() : null;
                return(inventory != null ? inventory.InStockQuantity.ToString() : String.Empty);
            });

            //Properties
            foreach (var propertyName in products.SelectMany(x => x.PropertyValues).Select(x => x.PropertyName).Distinct())
            {
                if (!configuration.ContainsKey(propertyName))
                {
                    configuration.Add(propertyName, (product) =>
                    {
                        var propertyValue = product.PropertyValues.FirstOrDefault(x => x.PropertyName == propertyName);
                        if (propertyValue != null)
                        {
                            return(propertyValue.Value != null ? propertyValue.Value.ToString() : String.Empty);
                        }
                        return(String.Empty);
                    });
                }
            }
        }
        private void ProcessProjectChange(Solution solution, ProjectId projectId)
        {
            this.AssertIsForeground();

            // Remove anything we have associated with this project.
            Dictionary<string, string> installedPackages;
            _projectToInstalledPackageAndVersion.TryRemove(projectId, out installedPackages);

            if (!solution.ContainsProject(projectId))
            {
                // Project was removed.  Nothing needs to be done.
                return;
            }

            // Project was changed in some way.  Let's go find the set of installed packages for it.
            var dteProject = _workspace.TryGetDTEProject(projectId);
            if (dteProject == null)
            {
                // Don't have a DTE project for this project ID.  not something we can query nuget for.
                return;
            }

            installedPackages = new Dictionary<string, string>();

            // Calling into nuget.  Assume they may fail for any reason.
            try
            {
                var installedPackageMetadata = _packageInstallerServices.GetInstalledPackages(dteProject);
                installedPackages.AddRange(installedPackageMetadata.Select(m => new KeyValuePair<string, string>(m.Id, m.VersionString)));
            }
            catch (Exception e) when (FatalError.ReportWithoutCrash(e))
            {
            }

            _projectToInstalledPackageAndVersion.AddOrUpdate(projectId, installedPackages, (_1, _2) => installedPackages);
        }
Beispiel #58
0
        /// <summary>
        /// Gets the lists by category.
        /// </summary>
        /// <param name="category">The category.</param>
        /// <returns></returns>
        private List <Group> GetListsByCategory(Category category)
        {
            int communicationListGroupTypeId            = GroupTypeCache.Get(Rock.SystemGuid.GroupType.GROUPTYPE_COMMUNICATIONLIST.AsGuid()).Id;
            int?communicationListGroupTypeDefaultRoleId = GroupTypeCache.Get(communicationListGroupTypeId).DefaultGroupRoleId;

            var rockContext = new RockContext();

            var memberOfList = new GroupMemberService(rockContext).GetByPersonId(CurrentPersonId.Value).AsNoTracking().Select(a => a.GroupId).ToList();

            // Get a list of syncs for the communication list groups where the default role is sync'd AND the current person is NOT a member of
            // This is used to filter out the list of communication lists.
            var commGroupSyncsForDefaultRole = new GroupSyncService(rockContext)
                                               .Queryable()
                                               .Where(a => a.Group.GroupTypeId == communicationListGroupTypeId)
                                               .Where(a => a.GroupTypeRoleId == communicationListGroupTypeDefaultRoleId)
                                               .Where(a => !memberOfList.Contains(a.GroupId))
                                               .Select(a => a.GroupId)
                                               .ToList();

            var communicationLists = new GroupService(rockContext)
                                     .Queryable()
                                     .Where(a => a.GroupTypeId == communicationListGroupTypeId && !commGroupSyncsForDefaultRole.Contains(a.Id))
                                     .IsActive()
                                     .ToList();

            var categoryGuids = new List <Guid>();

            categoryGuids.Add(category.Guid);
            var viewableCommunicationLists = new List <Group>();

            foreach (var communicationList in communicationLists)
            {
                communicationList.LoadAttributes(rockContext);
                if (!categoryGuids.Any())
                {
                    // if no categories where specified, only show lists that the person has VIEW auth
                    if (communicationList.IsAuthorized(Rock.Security.Authorization.VIEW, this.CurrentPerson))
                    {
                        viewableCommunicationLists.Add(communicationList);
                    }
                }
                else
                {
                    Guid?categoryGuid = communicationList.GetAttributeValue("Category").AsGuidOrNull();
                    if (categoryGuid.HasValue && categoryGuids.Contains(categoryGuid.Value))
                    {
                        viewableCommunicationLists.Add(communicationList);
                    }
                }
            }

            viewableCommunicationLists = viewableCommunicationLists.OrderBy(a =>
            {
                var name = a.GetAttributeValue("PublicName");
                if (name.IsNullOrWhiteSpace())
                {
                    name = a.Name;
                }

                return(name);
            }).ToList();

            var groupIds = viewableCommunicationLists.Select(a => a.Id).ToList();
            var personId = this.CurrentPersonId.Value;

            showMediumPreference = this.GetAttributeValue(AttributeKey.ShowMediumPreference).AsBoolean();

            var localPersonCommunicationListsMember = new GroupMemberService(rockContext)
                                                      .Queryable()
                                                      .AsNoTracking()
                                                      .Where(a => groupIds.Contains(a.GroupId) && a.PersonId == personId)
                                                      .GroupBy(a => a.GroupId)
                                                      .ToList()
                                                      .ToDictionary(k => k.Key, v => v.FirstOrDefault());

            if (localPersonCommunicationListsMember != null)
            {
                personCommunicationListsMember.AddRange(localPersonCommunicationListsMember);
            }

            nbNoCommunicationLists.Visible      = !viewableCommunicationLists.Any();
            pnlCommunicationPreferences.Visible = viewableCommunicationLists.Any();

            return(viewableCommunicationLists.OrderBy(l => l.Order).ThenBy(l => l.Name).ToList());
        }
 private static Dictionary<IFieldSymbol, VariableDeclaratorSyntax> GetCandidateVariables(SemanticModel semanticModel, IEnumerable<FieldDeclarationSyntax> fieldDeclarations)
 {
     var variablesToMakeReadonly = new Dictionary<IFieldSymbol, VariableDeclaratorSyntax>();
     foreach (var fieldDeclaration in fieldDeclarations)
         variablesToMakeReadonly.AddRange(GetCandidateVariables(semanticModel, fieldDeclaration));
     return variablesToMakeReadonly;
 }
        public void Transform(MethodBody body)
        {
            if (this.result == null)
            {
                throw new InvalidOperationException("Analysis result not available.");
            }

            // TODO: Not sure if we need to process the cfg nodes in backward order
            // since there is no global information used, the order shouldn't matter.
            //var sorted_nodes = cfg.BackwardOrder;
            //
            //foreach (var node in sorted_nodes)
            foreach (var node in this.cfg.Nodes)
            {
                var node_result = this.result[node.Id];
                var copies      = new Dictionary <IVariable, IVariable>();

                if (node_result.Output != null)
                {
                    copies.AddRange(node_result.Output);
                }

                for (var i = node.Instructions.Count - 1; i >= 0; --i)
                {
                    var instruction = node.Instructions[i];

                    foreach (var variable in instruction.ModifiedVariables)
                    {
                        // Only replace temporal variables
                        if (variable.IsTemporal() &&
                            copies.ContainsKey(variable))
                        {
                            var operand = copies[variable];

                            instruction.Replace(variable, operand);
                        }
                    }

                    var isTemporalCopy = this.Flow(instruction, copies);

                    foreach (var variable in instruction.UsedVariables)
                    {
                        // Only replace temporal variables
                        if (variable.IsTemporal() &&
                            copies.ContainsKey(variable))
                        {
                            var operand = copies[variable];
                            instruction.Replace(variable, operand);
                        }
                    }

                    // Only replace temporal variables
                    if (isTemporalCopy)
                    {
                        // Remove the copy instruction
                        if (i == 0)
                        {
                            // The copy is the first instruction of the basic block
                            // Replace the copy instruction with a nop to preserve branch targets
                            var nop   = new NopInstruction(instruction.Offset);
                            var index = body.Instructions.IndexOf(instruction);
                            body.Instructions[index] = nop;
                            node.Instructions[i]     = nop;
                        }
                        else
                        {
                            // The copy is not the first instruction of the basic block
                            body.Instructions.Remove(instruction);
                            node.Instructions.RemoveAt(i);
                        }
                    }
                }
            }

            body.UpdateVariables();
        }