本文整理汇总了C#中HashSet.GroupBy方法的典型用法代码示例。如果您正苦于以下问题:C# HashSet.GroupBy方法的具体用法?C# HashSet.GroupBy怎么用?C# HashSet.GroupBy使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类HashSet
的用法示例。
在下文中一共展示了HashSet.GroupBy方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: DeleteInDestination
private async Task DeleteInDestination(HashSet<Tuple<string, string, string>> src,
HashSet<Tuple<string, string, string>> dst)
{
dst.ExceptWith(src);
int n = 0;
// group by table + partition
foreach (var batch1 in dst.GroupBy(x => x.Item1 + x.Item2))
{
CloudTable dstTable = _dstClient.GetTableReference(batch1.First().Item1);
if (_token.IsCancellationRequested)
return;
foreach (var batch2 in batch1.Batch(100))
{
if (_token.IsCancellationRequested)
return;
var op = new TableBatchOperation();
foreach (var tuple in batch2)
{
op.Delete(new TableEntity(tuple.Item2, tuple.Item3) {ETag = "*"});
}
await dstTable.ExecuteBatchAsync(op, _token);
n += Math.Min(op.Count, 100);
Console.WriteLine("deleted {0} rows", n);
}
}
}
示例2: ExecuteTasks
public void ExecuteTasks(HashSet<EndRequestTask> tasks)
{
var tasksGroupedByType = tasks.GroupBy(task => task.GetType())
.ToDictionary(grouping => grouping.Key, grouping => grouping.ToHashSet());
foreach (var type in tasksGroupedByType.Keys.OrderByDescending(GetExecutionPriority))
{
if (OnRequestExecutionTypes.ContainsKey(type) && OnRequestExecutionTypes[type] != null)
{
var requestBase = _kernel.Get(OnRequestExecutionTypes[type]) as ExecuteEndRequestBase;
if (requestBase != null)
{
var data = tasksGroupedByType[type].Select(task => task.BaseData).ToHashSet();
requestBase.Execute(data);
continue;
}
}
CurrentRequestData.ErrorSignal.Raise(
new Exception(
string.Format(
"Could not process tasks of type {0}. Please create a valid executor for the type",
type.FullName)));
}
}
示例3: SomeFunction
public static void SomeFunction()
{
Dictionary<int, int> dict = new Dictionary<int, int>();
dict.Add(4, 3);
Console.WriteLine(dict[4]);
Console.WriteLine(dict.ContainsKey(8));
dict.Remove(4);
foreach(int key in dict.Keys)
Console.WriteLine(key);
foreach(int val in dict.Values)
Console.WriteLine(val);
foreach(var kv in dict)
Console.WriteLine(kv.Key + " " + kv.Value);
var dict2 = dict.ToDictionary(o => o.Key, o => o.Value);
var vals = dict.Values;
HashSet<int> hash = new HashSet<int>();
hash.Add(999);
Console.WriteLine(hash.Contains(999));
hash.Remove(999);
Console.WriteLine(hash.Contains(999));
foreach(int hashItem in hash)
Console.WriteLine(hashItem);
var z = hash.Select(o => 3).ToArray();
var g = hash.GroupBy(o => o).Select(o => o.Count()).Min();
}
示例4: PackageResolverContext
/// <summary>
/// Resolver context
/// </summary>
/// <param name="dependencyBehavior">behavior for non-target packages</param>
/// <param name="targetIds">packages to install or update</param>
/// <param name="requiredPackageIds">packages required in the solution</param>
/// <param name="packagesConfig">existing packages</param>
/// <param name="preferredVersions">preferred package versions or the installed version of a package</param>
/// <param name="availablePackages">all packages from the gather stage</param>
public PackageResolverContext(DependencyBehavior dependencyBehavior,
IEnumerable<string> targetIds,
IEnumerable<string> requiredPackageIds,
IEnumerable<Packaging.PackageReference> packagesConfig,
IEnumerable<PackageIdentity> preferredVersions,
IEnumerable<SourcePackageDependencyInfo> availablePackages)
{
if (targetIds == null)
{
throw new ArgumentNullException(nameof(targetIds));
}
if (requiredPackageIds == null)
{
throw new ArgumentNullException(nameof(requiredPackageIds));
}
if (packagesConfig == null)
{
throw new ArgumentNullException(nameof(packagesConfig));
}
if (preferredVersions == null)
{
throw new ArgumentNullException(nameof(preferredVersions));
}
if (availablePackages == null)
{
throw new ArgumentNullException(nameof(availablePackages));
}
DependencyBehavior = dependencyBehavior;
TargetIds = new HashSet<string>(targetIds, StringComparer.OrdinalIgnoreCase);
RequiredPackageIds = new HashSet<string>(requiredPackageIds, StringComparer.OrdinalIgnoreCase);
RequiredPackageIds.UnionWith(targetIds);
PackagesConfig = packagesConfig;
PreferredVersions = new HashSet<PackageIdentity>(preferredVersions, PackageIdentity.Comparer);
AvailablePackages = availablePackages;
Debug.Assert(PreferredVersions.GroupBy(p => p.Id, StringComparer.OrdinalIgnoreCase)
.All(group => group.Count() == 1), "duplicate preferred ids");
}
示例5: HiloCannotGoDown
public void HiloCannotGoDown()
{
using (var store = NewDocumentStore())
{
store.DatabaseCommands.Put(
"Raven/Hilo/Users", null,
new RavenJObject
{
{"Max", 32}
},
new RavenJObject());
var hiLoKeyGenerator = new HiLoKeyGenerator("Users", 32);
var ids = new HashSet<long> { hiLoKeyGenerator.NextId(store.DatabaseCommands) };
store.DatabaseCommands.Put(
"Raven/Hilo/Users", null,
new RavenJObject
{
{"Max", 12}
},
new RavenJObject());
for (int i = 0; i < 128; i++)
{
Assert.True(ids.Add(hiLoKeyGenerator.NextId(store.DatabaseCommands)), "Failed at " + i);
}
var list = ids.GroupBy(x => x).Select(g => new
{
g.Key,
Count = g.Count()
}).Where(x => x.Count > 1).ToList();
Assert.Empty(list);
}
}
示例6: GenerateForAssemblies
/// <summary>
/// Generates a syntax tree for the provided assemblies.
/// </summary>
/// <param name="assemblies">The assemblies to generate code for.</param>
/// <param name="runtime">Whether or not runtime code generation is being performed.</param>
/// <returns>The generated syntax tree.</returns>
private static GeneratedSyntax GenerateForAssemblies(List<Assembly> assemblies, bool runtime)
{
if (Logger.IsVerbose)
{
Logger.Verbose(
"Generating code for assemblies: {0}",
string.Join(", ", assemblies.Select(_ => _.FullName)));
}
Assembly targetAssembly;
HashSet<Type> ignoredTypes;
if (runtime)
{
// Ignore types which have already been accounted for.
ignoredTypes = GetTypesWithGeneratedSupportClasses();
targetAssembly = null;
}
else
{
ignoredTypes = new HashSet<Type>();
targetAssembly = assemblies.FirstOrDefault();
}
var members = new List<MemberDeclarationSyntax>();
// If any KnownAssemblies have been specified, include them during code generation.
var knownAssemblies =
assemblies.SelectMany(_ => _.GetCustomAttributes<KnownAssemblyAttribute>())
.Select(_ => _.Assembly)
.Distinct()
.ToSet();
if (knownAssemblies.Count > 0)
{
knownAssemblies.UnionWith(assemblies);
assemblies = knownAssemblies.ToList();
}
// Get types from assemblies which reference Orleans and are not generated assemblies.
var includedTypes = new HashSet<Type>();
for (var i = 0; i < assemblies.Count; i++)
{
var assembly = assemblies[i];
foreach (var attribute in assembly.GetCustomAttributes<KnownTypeAttribute>())
{
ConsiderType(attribute.Type, runtime, targetAssembly, includedTypes);
}
foreach (var type in assembly.DefinedTypes)
{
ConsiderType(type, runtime, targetAssembly, includedTypes);
}
}
includedTypes.RemoveWhere(_ => ignoredTypes.Contains(_));
// Group the types by namespace and generate the required code in each namespace.
foreach (var group in includedTypes.GroupBy(_ => CodeGeneratorCommon.GetGeneratedNamespace(_)))
{
var namespaceMembers = new List<MemberDeclarationSyntax>();
foreach (var type in group)
{
// The module containing the serializer.
var module = runtime ? null : type.Module;
// Every type which is encountered must be considered for serialization.
Action<Type> onEncounteredType = encounteredType =>
{
// If a type was encountered which can be accessed, process it for serialization.
SerializerGenerationManager.RecordTypeToGenerate(encounteredType, module, targetAssembly);
};
if (Logger.IsVerbose2)
{
Logger.Verbose2("Generating code for: {0}", type.GetParseableName());
}
if (GrainInterfaceData.IsGrainInterface(type))
{
if (Logger.IsVerbose2)
{
Logger.Verbose2(
"Generating GrainReference and MethodInvoker for {0}",
type.GetParseableName());
}
GrainInterfaceData.ValidateInterfaceRules(type);
namespaceMembers.Add(GrainReferenceGenerator.GenerateClass(type, onEncounteredType));
namespaceMembers.Add(GrainMethodInvokerGenerator.GenerateClass(type));
}
// Generate serializers.
var first = true;
Type toGen;
//.........这里部分代码省略.........
示例7: MarkMessages
private void MarkMessages()
{
HashSet<MarkRequest> hash;
using (_rwLock.GetReadLock())
hash = new HashSet<MarkRequest>(_requests);
foreach (var group in hash
.GroupBy(rq => rq.IsRead)
.Select(grp => new { IsRead = grp.Key, Ids = grp.SelectMany(rq => rq.MsgIds) }))
MarkMsgsRead(
_provider,
group.Ids,
group.IsRead);
using (_rwLock.GetWriteLock())
_requests.RemoveAll(hash.Contains);
foreach (var notificator in hash.Select(rq => rq.MarkFinished))
notificator();
}
示例8: GenerateForAssemblies
/// <summary>
/// Generates a syntax tree for the provided assemblies.
/// </summary>
/// <param name="assemblies">The assemblies to generate code for.</param>
/// <param name="runtime">Whether or not runtime code generation is being performed.</param>
/// <returns>The generated syntax tree.</returns>
private static GeneratedSyntax GenerateForAssemblies(List<Assembly> assemblies, bool runtime)
{
if (Logger.IsVerbose)
{
Logger.Verbose(
"Generating code for assemblies: {0}",
string.Join(", ", assemblies.Select(_ => _.FullName)));
}
Assembly targetAssembly;
HashSet<Type> ignoredTypes;
if (runtime)
{
// Ignore types which have already been accounted for.
ignoredTypes = CodeGeneratorCommon.GetTypesWithImplementations(
typeof(MethodInvokerAttribute),
typeof(GrainReferenceAttribute),
typeof(GrainStateAttribute),
typeof(SerializerAttribute));
targetAssembly = null;
}
else
{
ignoredTypes = new HashSet<Type>();
targetAssembly = assemblies.FirstOrDefault();
}
var members = new List<MemberDeclarationSyntax>();
// Get types from assemblies which reference Orleans and are not generated assemblies.
var includedTypes = new HashSet<Type>();
foreach (var type in assemblies.SelectMany(_ => _.DefinedTypes))
{
// The module containing the serializer.
var module = runtime ? null : type.Module;
var typeInfo = type.GetTypeInfo();
// Every type which is encountered must be considered for serialization.
if (!typeInfo.IsNested && !typeInfo.IsGenericParameter && typeInfo.IsSerializable)
{
// If a type was encountered which can be accessed, process it for serialization.
var isAccessibleForSerialization =
!TypeUtilities.IsTypeIsInaccessibleForSerialization(type, module, targetAssembly);
if (isAccessibleForSerialization)
{
includedTypes.Add(type);
SerializerGenerationManager.RecordTypeToGenerate(type);
}
}
// Collect the types which require code generation.
if (GrainInterfaceData.IsGrainInterface(type))
{
if (Logger.IsVerbose2)
{
Logger.Verbose2("Will generate code for: {0}", type.GetParseableName());
}
includedTypes.Add(type);
}
}
includedTypes.RemoveWhere(_ => ignoredTypes.Contains(_));
// Group the types by namespace and generate the required code in each namespace.
foreach (var group in includedTypes.GroupBy(_ => CodeGeneratorCommon.GetGeneratedNamespace(_)))
{
var namespaceMembers = new List<MemberDeclarationSyntax>();
foreach (var type in group)
{
// The module containing the serializer.
var module = runtime ? null : type.Module;
// Every type which is encountered must be considered for serialization.
Action<Type> onEncounteredType = encounteredType =>
{
// If a type was encountered which can be accessed, process it for serialization.
var isAccessibleForSerialization =
!TypeUtilities.IsTypeIsInaccessibleForSerialization(encounteredType, module, targetAssembly);
if (isAccessibleForSerialization)
{
SerializerGenerationManager.RecordTypeToGenerate(encounteredType);
}
};
if (Logger.IsVerbose2)
{
Logger.Verbose2("Generating code for: {0}", type.GetParseableName());
}
if (GrainInterfaceData.IsGrainInterface(type))
{
if (Logger.IsVerbose2)
{
//.........这里部分代码省略.........
示例9: Initialize
private void Initialize()
{
if (null == _consumingMethod)
throw new InvalidOperationException("Consuming method has not been defined");
if (!_assemblies.Any())
throw new InvalidOperationException("There are no assemblies to scan");
var types = _assemblies
.SelectMany(a => {
try
{
return a.GetExportedTypes();
} catch{}
return new Type[0];
}).Where(x=>x!=null)
.ToList();
var messageTypes = types.Where(x => !x.IsInterface && typeof(IMessage).IsAssignableFrom(x)).ToArray();
var consumerTypes = types.Where(x => typeof(IConsume).IsAssignableFrom(x)).ToArray();
var consumingDirectly = consumerTypes
.SelectMany(consumerType =>
GetConsumedMessages(consumerType)
.Select(messageType => new MessageMapping(consumerType, messageType, true)))
.ToArray();
var result = new HashSet<MessageMapping>();
foreach (var m in consumingDirectly)
{
result.Add(m);
}
var allMessages = result.Select(m => m.Message).ToList();
foreach (var messageType in messageTypes)
{
if (!allMessages.Contains(messageType))
{
allMessages.Add(messageType);
result.Add(new MessageMapping(typeof(MessageMapping.BusNull), messageType, true));
}
}
_consumerInfos = result
.GroupBy(x => x.Consumer)
.Select(x =>
{
var directs = x
.Where(m => m.Direct)
.Select(m => m.Message)
.Distinct();
var assignables = x
.Select(m => m.Message)
.Where(t => directs.Any(d => d.IsAssignableFrom(t)))
.Distinct();
return new ConsumerInfo(x.Key, assignables.ToArray());
}).ToList();
_messageInfos = result
.ToLookup(x => x.Message)
.Select(x =>
{
var domainConsumers = x
.Where(t => t.Consumer != typeof(MessageMapping.BusNull))
.ToArray();
return new MessageInfo
{
MessageType = x.Key,
AllConsumers = domainConsumers.Select(m => m.Consumer).Distinct().ToArray(),
DerivedConsumers = domainConsumers.Where(m => !m.Direct).Select(m => m.Consumer).Distinct().ToArray(),
DirectConsumers = domainConsumers.Where(m => m.Direct).Select(m => m.Consumer).Distinct().ToArray(),
};
}).ToList();
var includedTypes = _messageInfos
.Select(m => m.MessageType).ToList();
// message directory should still include all messages for the serializers
var orphanedMessages = result
.Where(m => !includedTypes.Contains(m.Message))
.Select(m => new MessageInfo
{
MessageType = m.Message,
AllConsumers = Type.EmptyTypes,
DerivedConsumers = Type.EmptyTypes,
DirectConsumers = Type.EmptyTypes
});
_messageInfos.AddRange(orphanedMessages);
}
示例10: Main
//.........这里部分代码省略.........
//Debug.WriteLine("Date: {0} - {1}", date, MethodInfo.TotalHits(dailyPages.Where(p => p.Timestamp == d.Date)));
}
topPages = filteredEntries.Where (p => filteredEntries.Count (q => q.Url == p.Url) > totalDays / 2);
AddChartFromSeries (startRow, startCol, "Daily Slow Pages - Response Time(Average) Trend", topPages, p => p.AvgResponseTime, d => d.ToString (DateTimeFormatInfo.CurrentInfo.ShortDatePattern));
SpreadCharts (reportSheet);
}
#endregion
#region Hourly analysis
if ( hourlyPages.Any () )
{
Console.WriteLine ("{0} Genrating Hourly Statistics", stopWatch.Elapsed.ToString (@"hh\:mm\:ss"));
reportSheet = reportSpreadsheet.Worksheets.Add (Type.Missing, reportSheet, 1);
reportSheet.Name = "Hourly Analysis";
startRow = 1;
startCol = 1;
filteredEntries.Clear ();
foreach ( var d in hourlyPages.Select (p => p.Timestamp).Distinct () )
{
filteredEntries.UnionWith (hourlyPages.Where (p => p.Timestamp == d.Date.AddHours (d.Hour))
.OrderByDescending (p => p.Hits).Take (topPagesPerDay));
//Debug.WriteLine("Date: {0} - {1}", date, MethodInfo.TotalHits(dailyPages.Where(p => p.Timestamp == d.Date)));
}
var totalHits = hourlyPages.Sum (p => p.Hits);
//filter out top pages which are there for 10% of time or 2% traffic
topPages = filteredEntries.Where (p => filteredEntries.Count (q => q.Url == p.Url) > totalHours / 10 || p.Hits > totalHits * 2 / 100);
startRow += AddChartFromSeries (startRow, startCol, "Hourly Top Pages Summary (By Hits)", topPages, p => p.Hits, d => d.ToString ());
excelApp.ActiveChart.Axes (XlAxisType.xlCategory).CategoryType = XlCategoryType.xlCategoryScale;
hourlyHits = hourlyPages.GroupBy (p => p.Timestamp, q => q);
peakHits = hourlyHits.Select (p => p.Sum (q => q.Hits)).OrderByDescending (p => p).Take (peakHoursCount).Min ();
peakHourPages = hourlyHits.Where (p => p.Sum (q => q.Hits) >= peakHits);
startRow += 10; startCol = 1;
startRow += AddChartFromSeries (startRow, startCol, "Peak Hour Top Pages Summary (By Hits)", peakHourPages.SelectMany (g => g.Where (p => p.Hits > peakHits * 2 / 100)), p => p.Hits, d => d.ToString ());
excelApp.ActiveChart.Axes (XlAxisType.xlCategory).CategoryType = XlCategoryType.xlCategoryScale;
CollectionToTable (peakHourPages.SelectMany (g => g), startRow + 10, 1, "Peak Hour Pages", true);
SpreadCharts (reportSheet);
}
#endregion
#region URL Param Hits Summary
if ( hitsPerURLParams.Any () )
{
Console.WriteLine ("{0} Genrating URL parameter statistics", stopWatch.Elapsed.ToString (@"hh\:mm\:ss"));
reportSheet = reportSpreadsheet.Worksheets.Add (Type.Missing, reportSheet, 1);
startRow = startCol = 1;
reportSheet.Name = "URL Parameters";
CollectionToTable (urlParamHits.Values, startRow, startCol, "URL Parameters Summary (for the period)");
}
#endregion
#region Summary
Console.WriteLine ("{0} Genrating Summary", stopWatch.Elapsed.ToString (@"hh\:mm\:ss"));
reportSheet = reportSpreadsheet.Worksheets.Add (reportSheet, Type.Missing, 1);
reportRow = reportCol = 1;
reportSheet.Name = "Summary";
reportSheet.Cells[reportRow, 1] = "Running From";
reportSheet.Cells[reportRow++, 2] = curerntPath;
示例11: GetMockableMethods
internal static ReadOnlyCollection<MethodMockableResult> GetMockableMethods(this Type @this, NameGenerator generator)
{
var objectMethods = @this.IsInterface ?
typeof(object).GetMethods().Where(_ => _.IsExtern() || _.IsVirtual).ToList() : new List<MethodInfo>();
var methods = new HashSet<MockableResult<MethodInfo>>(@this.GetMethods(ReflectionValues.PublicNonPublicInstance)
.Where(_ => !_.IsSpecialName && _.IsVirtual && !_.IsFinal &&
!objectMethods.Where(om => om.Match(_) == MethodMatch.Exact).Any() &&
_.DeclaringType.Assembly.CanBeSeenByMockAssembly(_.IsPublic, _.IsPrivate, _.IsFamily, _.IsFamilyOrAssembly, generator))
.Select(_ => new MockableResult<MethodInfo>(_, RequiresExplicitInterfaceImplementation.No)));
if (@this.IsInterface)
{
var namespaces = new SortedSet<string>();
foreach (var @interface in @this.GetInterfaces())
{
var interfaceMethods = @interface.GetMethods()
.Where(_ => !_.IsSpecialName && !objectMethods.Where(om => om.Match(_) == MethodMatch.Exact).Any());
foreach (var interfaceMethod in interfaceMethods)
{
if (interfaceMethod.CanBeSeenByMockAssembly(generator))
{
var matchMethodGroups = methods.GroupBy(_ => interfaceMethod.Match(_.Value)).ToDictionary(_ => _.Key);
if (!matchMethodGroups.ContainsKey(MethodMatch.Exact))
{
methods.Add(new MockableResult<MethodInfo>(
interfaceMethod, matchMethodGroups.ContainsKey(MethodMatch.DifferByReturnTypeOnly) ?
RequiresExplicitInterfaceImplementation.Yes : RequiresExplicitInterfaceImplementation.No));
}
}
}
}
}
var baseStaticMethods = @this.IsInterface ?
typeof(object).GetMethods().Where(_ => _.IsStatic).ToList() :
@this.GetMethods().Where(_ => _.IsStatic).ToList();
return methods.Select(_ => new MethodMockableResult(
_.Value, _.RequiresExplicitInterfaceImplementation,
baseStaticMethods.Where(osm => osm.Match(_.Value) == MethodMatch.Exact).Any() ?
RequiresIsNewImplementation.Yes : RequiresIsNewImplementation.No)).ToList().AsReadOnly();
}
示例12: GetMockableProperties
internal static ReadOnlyCollection<PropertyMockableResult> GetMockableProperties(this Type @this, NameGenerator generator)
{
var properties = new HashSet<PropertyMockableResult>(
from property in @this.GetProperties(ReflectionValues.PublicNonPublicInstance)
let canGet = property.CanRead && property.GetMethod.IsVirtual && !property.GetMethod.IsFinal &&
property.GetMethod.DeclaringType.Assembly.CanBeSeenByMockAssembly(
property.GetMethod.IsPublic, property.GetMethod.IsPrivate, property.GetMethod.IsFamily, property.GetMethod.IsFamilyOrAssembly, generator)
let canSet = property.CanWrite && property.SetMethod.IsVirtual && !property.SetMethod.IsFinal &&
property.SetMethod.DeclaringType.Assembly.CanBeSeenByMockAssembly(
property.SetMethod.IsPublic, property.SetMethod.IsPrivate, property.SetMethod.IsFamily, property.SetMethod.IsFamilyOrAssembly, generator)
where canGet || canSet
select new PropertyMockableResult(property, RequiresExplicitInterfaceImplementation.No,
(canGet && canSet ? PropertyAccessors.GetAndSet : (canGet ? PropertyAccessors.Get : PropertyAccessors.Set))));
if (@this.IsInterface)
{
var namespaces = new SortedSet<string>();
foreach (var @interface in @this.GetInterfaces())
{
foreach (var interfaceProperty in @interface.GetMockableProperties(generator))
{
if (interfaceProperty.Value.GetDefaultMethod().CanBeSeenByMockAssembly(generator))
{
var matchMethodGroups = properties.GroupBy(_ => interfaceProperty.Value.GetDefaultMethod().Match(_.Value.GetDefaultMethod())).ToDictionary(_ => _.Key);
if (!matchMethodGroups.ContainsKey(MethodMatch.Exact))
{
properties.Add(new PropertyMockableResult(interfaceProperty.Value,
matchMethodGroups.ContainsKey(MethodMatch.DifferByReturnTypeOnly) ?
RequiresExplicitInterfaceImplementation.Yes : RequiresExplicitInterfaceImplementation.No,
interfaceProperty.Accessors));
}
}
}
}
}
return properties.ToList().AsReadOnly();
}
示例13: CheckForConflictingVersions
/// <summary>
/// Check for conflicts of versions in the referenced assemblies of the workflow.
/// </summary>
/// <param name="referencedTypes">Referenced types in the project</param>
/// <param name="referencedAssemblies">Referenced assemblies in the project</param>
/// <param name="projectName">Name of the main type (workflow) of the project</param>
private static void CheckForConflictingVersions(HashSet<Type> referencedTypes, HashSet<Assembly> referencedAssemblies, string projectName)
{
// XamlBuildTask cannot support two different versions of the same dependency in XAML.
// As a workaround, we raise an error here if the workflow contains activities/variables/etc.
// from different versions of the same assembly.
var conflicts =
referencedAssemblies.GroupBy(asm => asm.GetName().Name).Where(grp => grp.Count() > 1).ToList();
if (conflicts.Any())
{
var conflict = conflicts.First();
Assembly asm1 = referencedAssemblies.First(item => item.GetName().Name == conflict.Key);
Assembly asm2 = referencedAssemblies.Last(item => item.GetName().Name == conflict.Key);
var type1 = referencedTypes.First(item => item.Assembly.GetName().Name == asm1.GetName().Name &&
item.Assembly.GetName().Version == asm1.GetName().Version);
var type2 = referencedTypes.First(item => item.Assembly.GetName().Name == asm2.GetName().Name &&
item.Assembly.GetName().Version == asm2.GetName().Version);
string message = string.Format(CompileMessages.MultipleVersionsUsed,
type1.Name, asm1.FullName, type2.Name, asm2.FullName, conflict.Key);
throw new CompileException(message);
}
// Check if the workflow contains a previous version of itself
var referencesToItself = new List<Assembly>(
from assemblies in referencedAssemblies
where assemblies.GetName().Name == projectName
select assemblies);
if (referencesToItself.Any())
{
string message = string.Format(CompileMessages.PreviousSelfVersion,
referencesToItself.First().GetName().Name,
referencesToItself.First().GetName().FullName);
throw new CompileException(message);
}
}