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); [email protected] = @params; return bc; }
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; }
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; }
/// <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; }
public static void Redirect() { redirects = new Dictionary<MethodInfo, RedirectCallsState>(); foreach (var type in Assembly.GetExecutingAssembly().GetTypes()) { redirects.AddRange(RedirectionUtil.RedirectType(type)); } }
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<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 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; }
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 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 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 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 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); }
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); } } }
/// <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 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 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; }
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; }); } } }
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); }
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)); }
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; } }
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; }
/// <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 }
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; }
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; }