1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035
|
namespace System.Workflow.ComponentModel.Compiler
{
#region Imports
using System;
using System.Collections;
using System.Collections.Specialized;
using System.Collections.Generic;
using System.CodeDom;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.CodeDom.Compiler;
using System.Reflection;
using System.ComponentModel.Design.Serialization;
using System.Xml;
using System.Globalization;
using System.IO;
using System.Text;
using System.Diagnostics;
using System.Text.RegularExpressions;
using Microsoft.CSharp;
using Microsoft.VisualBasic;
using System.Workflow.ComponentModel.Design;
using System.Workflow.ComponentModel.Serialization;
using System.Security.Policy;
using System.Runtime.Versioning;
using System.Configuration;
using System.Collections.ObjectModel;
#endregion
#region WorkflowMarkupSourceAttribute Class
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
[Obsolete("The System.Workflow.* types are deprecated. Instead, please use the new types from System.Activities.*")]
public sealed class WorkflowMarkupSourceAttribute : Attribute
{
private string fileName;
private string md5Digest;
public WorkflowMarkupSourceAttribute(string fileName, string md5Digest)
{
this.fileName = fileName;
this.md5Digest = md5Digest;
}
public string FileName
{
get
{
return this.fileName;
}
}
public string MD5Digest
{
get
{
return this.md5Digest;
}
}
}
#endregion
#region Interface IWorkflowCompilerOptionsService
[Obsolete("The System.Workflow.* types are deprecated. Instead, please use the new types from System.Activities.*")]
public interface IWorkflowCompilerOptionsService
{
string RootNamespace { get; }
string Language { get; }
bool CheckTypes { get; }
}
[Obsolete("The System.Workflow.* types are deprecated. Instead, please use the new types from System.Activities.*")]
public class WorkflowCompilerOptionsService : IWorkflowCompilerOptionsService
{
internal const string DefaultLanguage = "CSharp";
public virtual string RootNamespace
{
get
{
return string.Empty;
}
}
public virtual string Language
{
get
{
return WorkflowCompilerOptionsService.DefaultLanguage;
}
}
public virtual bool CheckTypes
{
get
{
return false;
}
}
public virtual string TargetFrameworkMoniker
{
get
{
return string.Empty;
}
}
}
#endregion
#region WorkflowCompilationContext
[Obsolete("The System.Workflow.* types are deprecated. Instead, please use the new types from System.Activities.*")]
public sealed class WorkflowCompilationContext
{
[ThreadStatic]
static WorkflowCompilationContext current = null;
ContextScope scope;
ReadOnlyCollection<AuthorizedType> authorizedTypes;
WorkflowCompilationContext(ContextScope scope)
{
this.scope = scope;
}
public static WorkflowCompilationContext Current
{
get
{
return WorkflowCompilationContext.current;
}
private set
{
WorkflowCompilationContext.current = value;
}
}
public string RootNamespace
{
get
{
return this.scope.RootNamespace;
}
}
public string Language
{
get
{
return this.scope.Language;
}
}
public bool CheckTypes
{
get
{
return this.scope.CheckTypes;
}
}
internal FrameworkName TargetFramework
{
get
{
return this.scope.TargetFramework;
}
}
internal Version TargetFrameworkVersion
{
get
{
FrameworkName fx = this.scope.TargetFramework;
if (fx != null)
{
return fx.Version;
}
else
{
return MultiTargetingInfo.DefaultTargetFramework;
}
}
}
internal IServiceProvider ServiceProvider
{
get
{
return this.scope;
}
}
public static IDisposable CreateScope(IServiceProvider serviceProvider)
{
if (serviceProvider == null)
{
throw new ArgumentNullException("serviceProvider");
}
IWorkflowCompilerOptionsService optionsService = serviceProvider.GetService(typeof(IWorkflowCompilerOptionsService)) as IWorkflowCompilerOptionsService;
if (optionsService != null)
{
return CreateScope(serviceProvider, optionsService);
}
else
{
return new DefaultContextScope(serviceProvider);
}
}
public IList<AuthorizedType> GetAuthorizedTypes()
{
if (this.authorizedTypes == null)
{
try
{
IList<AuthorizedType> authorizedTypes;
IDictionary<string, IList<AuthorizedType>> authorizedTypesDictionary =
ConfigurationManager.GetSection("System.Workflow.ComponentModel.WorkflowCompiler/authorizedTypes") as IDictionary<string, IList<AuthorizedType>>;
Version targetVersion = null;
FrameworkName framework = this.scope.TargetFramework;
if (framework != null)
{
targetVersion = framework.Version;
}
else
{
targetVersion = MultiTargetingInfo.DefaultTargetFramework;
}
string normalizedVersionString = string.Format(CultureInfo.InvariantCulture, "v{0}.{1}", targetVersion.Major, targetVersion.Minor);
if (authorizedTypesDictionary.TryGetValue(normalizedVersionString, out authorizedTypes))
{
this.authorizedTypes = new ReadOnlyCollection<AuthorizedType>(authorizedTypes);
}
}
catch
{
}
}
return this.authorizedTypes;
}
internal static IDisposable CreateScope(IServiceProvider serviceProvider, WorkflowCompilerParameters parameters)
{
return new ParametersContextScope(serviceProvider, parameters);
}
static IDisposable CreateScope(IServiceProvider serviceProvider, IWorkflowCompilerOptionsService optionsService)
{
WorkflowCompilerOptionsService standardService = optionsService as WorkflowCompilerOptionsService;
if (standardService != null)
{
return new StandardContextScope(serviceProvider, standardService);
}
else
{
return new InterfaceContextScope(serviceProvider, optionsService);
}
}
abstract class ContextScope : IDisposable, IServiceProvider
{
IServiceProvider serviceProvider;
WorkflowCompilationContext currentContext;
bool disposed;
protected ContextScope(IServiceProvider serviceProvider)
{
this.serviceProvider = serviceProvider;
this.currentContext = WorkflowCompilationContext.Current;
WorkflowCompilationContext.Current = new WorkflowCompilationContext(this);
}
~ContextScope()
{
DisposeImpl();
}
public abstract string RootNamespace { get; }
public abstract string Language { get; }
public abstract bool CheckTypes { get; }
public abstract FrameworkName TargetFramework { get; }
public void Dispose()
{
DisposeImpl();
GC.SuppressFinalize(this);
}
public object GetService(Type serviceType)
{
return this.serviceProvider.GetService(serviceType);
}
void DisposeImpl()
{
if (!this.disposed)
{
WorkflowCompilationContext.Current = this.currentContext;
this.disposed = true;
}
}
}
class InterfaceContextScope : ContextScope
{
IWorkflowCompilerOptionsService service;
public InterfaceContextScope(IServiceProvider serviceProvider, IWorkflowCompilerOptionsService service)
: base(serviceProvider)
{
this.service = service;
}
public override string RootNamespace
{
get
{
return this.service.RootNamespace;
}
}
public override string Language
{
get
{
return this.service.Language;
}
}
public override bool CheckTypes
{
get
{
return this.service.CheckTypes;
}
}
public override FrameworkName TargetFramework
{
get
{
return null;
}
}
}
class StandardContextScope : ContextScope
{
WorkflowCompilerOptionsService service;
FrameworkName fxName;
public StandardContextScope(IServiceProvider serviceProvider, WorkflowCompilerOptionsService service)
: base(serviceProvider)
{
this.service = service;
}
public override string RootNamespace
{
get
{
return this.service.RootNamespace;
}
}
public override string Language
{
get
{
return this.service.Language;
}
}
public override bool CheckTypes
{
get
{
return this.service.CheckTypes;
}
}
public override FrameworkName TargetFramework
{
get
{
if (this.fxName == null)
{
string fxName = this.service.TargetFrameworkMoniker;
if (!string.IsNullOrEmpty(fxName))
{
this.fxName = new FrameworkName(fxName);
}
}
return this.fxName;
}
}
}
class ParametersContextScope : ContextScope
{
WorkflowCompilerParameters parameters;
public ParametersContextScope(IServiceProvider serviceProvider, WorkflowCompilerParameters parameters)
: base(serviceProvider)
{
this.parameters = parameters;
}
public override string RootNamespace
{
get
{
return WorkflowCompilerParameters.ExtractRootNamespace(this.parameters);
}
}
public override string Language
{
get
{
return this.parameters.LanguageToUse;
}
}
public override bool CheckTypes
{
get
{
return this.parameters.CheckTypes;
}
}
public override FrameworkName TargetFramework
{
get
{
if (this.parameters.MultiTargetingInformation != null)
{
return this.parameters.MultiTargetingInformation.TargetFramework;
}
else
{
return null;
}
}
}
}
class DefaultContextScope : ContextScope
{
public DefaultContextScope(IServiceProvider serviceProvider)
: base(serviceProvider)
{
}
public override string RootNamespace
{
get
{
return string.Empty;
}
}
public override string Language
{
get
{
return WorkflowCompilerOptionsService.DefaultLanguage;
}
}
public override bool CheckTypes
{
get
{
return false;
}
}
public override FrameworkName TargetFramework
{
get
{
return null;
}
}
}
}
#endregion
#region Class WorkflowCompiler
[Obsolete("The System.Workflow.* types are deprecated. Instead, please use the new types from System.Activities.*")]
public sealed class WorkflowCompiler
{
public WorkflowCompilerResults Compile(WorkflowCompilerParameters parameters, params string[] files)
{
if (parameters == null)
throw new ArgumentNullException("parameters");
if (files == null)
throw new ArgumentNullException("files");
string createdDirectoryName = null;
string createdTempFileName = null;
AppDomainSetup setup = AppDomain.CurrentDomain.SetupInformation;
setup.LoaderOptimization = LoaderOptimization.MultiDomainHost;
AppDomain compilerDomain = AppDomain.CreateDomain("CompilerDomain", null, setup);
bool generateInMemory = false;
string originalOutputAssembly = parameters.OutputAssembly;
try
{
if (parameters.GenerateInMemory)
{
generateInMemory = true;
parameters.GenerateInMemory = false;
if (string.IsNullOrEmpty(parameters.OutputAssembly))
{
// We need to remember the filename generated by Path.GetTempFileName so we can clean it up.
createdTempFileName = Path.GetTempFileName();
parameters.OutputAssembly = createdTempFileName + ".dll";
}
else
{
int tries = 0;
while (true)
{
try
{
tries++;
createdDirectoryName = Path.GetTempPath() + "\\" + Guid.NewGuid();
DirectoryInfo info = Directory.CreateDirectory(createdDirectoryName);
parameters.OutputAssembly = info.FullName + "\\" + parameters.OutputAssembly;
break;
}
catch
{
// If we have tried 10 times without success, give up. Something must be wrong
// with what gets returned by GetTempPath or we have exceeded max_path by appending
// the GUID.
if (tries >= 10)
{
throw;
}
}
}
}
}
WorkflowCompilerInternal compiler = (WorkflowCompilerInternal)compilerDomain.CreateInstanceAndUnwrap(Assembly.GetExecutingAssembly().FullName, typeof(WorkflowCompilerInternal).FullName);
WorkflowCompilerResults results = compiler.Compile(parameters, files);
if (generateInMemory && !results.Errors.HasErrors)
{
results.CompiledAssembly = Assembly.Load(File.ReadAllBytes(results.PathToAssembly));
results.PathToAssembly = null;
}
return results;
}
finally
{
string outputAssembly = parameters.OutputAssembly;
if (generateInMemory)
{
parameters.GenerateInMemory = true;
parameters.OutputAssembly = originalOutputAssembly;
}
AppDomain.Unload(compilerDomain);
// The temp file must be deleted after the app domain is unloaded, or else it will
// be "busy", causing the delete to throw an access exception.
if (generateInMemory)
{
try
{
// There will always be an outputAssemblyName to delete.
File.Delete(outputAssembly);
// If we created a temp file name with Path.GetTempFileName, we need to delete it here.
if (createdTempFileName != null)
{
File.Delete(createdTempFileName);
}
// If we created a directory, delete it.
if (createdDirectoryName != null)
{
Directory.Delete(createdDirectoryName, true);
}
}
catch
{ }
}
}
}
}
#endregion
#region Class WorkflowCompilerInternal
internal sealed class WorkflowCompilerInternal : MarshalByRefObject
{
#region Lifetime service
public override object InitializeLifetimeService()
{
return null;
}
#endregion
#region File based compilation
public WorkflowCompilerResults Compile(WorkflowCompilerParameters parameters, string[] allFiles)
{
WorkflowCompilerResults results = new WorkflowCompilerResults(parameters.TempFiles);
// Split the xoml files from cs/vb files.
StringCollection xomlFiles = new StringCollection();
StringCollection userCodeFiles = new StringCollection();
foreach (string file in allFiles)
{
if (file.EndsWith(".xoml", StringComparison.OrdinalIgnoreCase))
xomlFiles.Add(file);
else
userCodeFiles.Add(file);
}
string[] files = new string[xomlFiles.Count];
xomlFiles.CopyTo(files, 0);
string[] codeFiles = new string[userCodeFiles.Count];
userCodeFiles.CopyTo(codeFiles, 0);
string mscorlibPath = typeof(object).Assembly.Location;
ServiceContainer serviceContainer = new ServiceContainer();
MultiTargetingInfo mtInfo = parameters.MultiTargetingInformation;
if (mtInfo == null)
{
XomlCompilerHelper.FixReferencedAssemblies(parameters, results, parameters.LibraryPaths);
}
string mscorlibName = Path.GetFileName(mscorlibPath);
// Add assembly resolver.
ReferencedAssemblyResolver resolver = new ReferencedAssemblyResolver(parameters.ReferencedAssemblies, parameters.LocalAssembly);
AppDomain.CurrentDomain.AssemblyResolve += resolver.ResolveEventHandler;
// prepare service container
TypeProvider typeProvider = new TypeProvider(new ServiceContainer());
int mscorlibIndex = -1;
if ((parameters.ReferencedAssemblies != null) && (parameters.ReferencedAssemblies.Count > 0))
{
for (int i = 0; i < parameters.ReferencedAssemblies.Count; i++)
{
string assemblyPath = parameters.ReferencedAssemblies[i];
if ((mscorlibIndex == -1) && (string.Compare(mscorlibName, Path.GetFileName(assemblyPath), StringComparison.OrdinalIgnoreCase) == 0))
{
mscorlibIndex = i;
mscorlibPath = assemblyPath;
}
typeProvider.AddAssemblyReference(assemblyPath);
}
}
// a note about references to mscorlib:
// If we found mscorlib in the list of reference assemblies, we should remove it prior to sending it to the CodeDOM compiler.
// The CodeDOM compiler would add the right mscorlib [based on the version of the provider we use] and the duplication would
// cause a compilation error.
// If we didn't found a reference to mscorlib we need to add it to the type-provider, though, so we will support exposing
// those known types.
if (mscorlibIndex != -1)
{
parameters.ReferencedAssemblies.RemoveAt(mscorlibIndex);
if (string.IsNullOrEmpty(parameters.CoreAssemblyFileName))
{
parameters.CoreAssemblyFileName = mscorlibPath;
}
}
else
{
typeProvider.AddAssemblyReference(mscorlibPath);
}
serviceContainer.AddService(typeof(ITypeProvider), typeProvider);
TempFileCollection intermediateTempFiles = null;
string localAssemblyPath = string.Empty;
string createdDirectoryName = null;
try
{
using (WorkflowCompilationContext.CreateScope(serviceContainer, parameters))
{
parameters.LocalAssembly = GenerateLocalAssembly(files, codeFiles, parameters, results, out intermediateTempFiles, out localAssemblyPath, out createdDirectoryName);
if (parameters.LocalAssembly != null)
{
// WinOE Bug 17591: we must set the local assembly here,
// otherwise, the resolver won't be able to resolve custom types correctly.
resolver.SetLocalAssembly(parameters.LocalAssembly);
// Work around HERE!!!
// prepare type provider
typeProvider.SetLocalAssembly(parameters.LocalAssembly);
typeProvider.AddAssembly(parameters.LocalAssembly);
results.Errors.Clear();
XomlCompilerHelper.InternalCompileFromDomBatch(files, codeFiles, parameters, results, localAssemblyPath);
}
}
}
catch (Exception e)
{
results.Errors.Add(new WorkflowCompilerError(String.Empty, -1, -1, ErrorNumbers.Error_UnknownCompilerException.ToString(CultureInfo.InvariantCulture), SR.GetString(SR.Error_CompilationFailed, e.Message)));
}
finally
{
// Delate the temp files.
if (intermediateTempFiles != null && parameters.TempFiles.KeepFiles == false)
{
foreach (string file in intermediateTempFiles)
{
try
{
System.IO.File.Delete(file);
}
catch
{
}
}
try
{
// GenerateLocalAssembly may have created a directory, so let's try to delete it
// We can't just delete Path.GetDirectoryName(localAssemblyPath) because it might be the Temp directory.
if (createdDirectoryName != null)
{
Directory.Delete(createdDirectoryName, true);
}
}
catch
{
}
}
}
return results;
}
#endregion
#region Code for Generating Local Assembly
private static ValidationErrorCollection ValidateIdentifiers(IServiceProvider serviceProvider, Activity activity)
{
ValidationErrorCollection validationErrors = new ValidationErrorCollection();
Dictionary<string, int> names = new Dictionary<string, int>();
Walker walker = new Walker();
walker.FoundActivity += delegate(Walker walker2, WalkerEventArgs e)
{
Activity currentActivity = e.CurrentActivity;
if (!currentActivity.Enabled)
{
e.Action = WalkerAction.Skip;
return;
}
ValidationError identifierError = null;
if (names.ContainsKey(currentActivity.QualifiedName))
{
if (names[currentActivity.QualifiedName] != 1)
{
identifierError = new ValidationError(SR.GetString(SR.Error_DuplicatedActivityID, currentActivity.QualifiedName), ErrorNumbers.Error_DuplicatedActivityID, false, "Name");
identifierError.UserData[typeof(Activity)] = currentActivity;
validationErrors.Add(identifierError);
names[currentActivity.QualifiedName] = 1;
}
return;
}
// Undone: AkashS - remove this check when we allow root activities to not have a name.
if (!string.IsNullOrEmpty(currentActivity.Name))
{
names[currentActivity.Name] = 0;
identifierError = ValidationHelpers.ValidateIdentifier("Name", serviceProvider, currentActivity.Name);
if (identifierError != null)
{
identifierError.UserData[typeof(Activity)] = currentActivity;
validationErrors.Add(identifierError);
}
}
};
walker.Walk(activity as Activity);
return validationErrors;
}
private Assembly GenerateLocalAssembly(string[] files, string[] codeFiles, WorkflowCompilerParameters parameters, WorkflowCompilerResults results, out TempFileCollection tempFiles2, out string localAssemblyPath, out string createdDirectoryName)
{
localAssemblyPath = string.Empty;
createdDirectoryName = null;
tempFiles2 = null;
// Generate code for the markup files.
CodeCompileUnit markupCompileUnit = GenerateCodeFromFileBatch(files, parameters, results);
if (results.Errors.HasErrors)
return null;
SupportedLanguages language = CompilerHelpers.GetSupportedLanguage(parameters.LanguageToUse);
// Convert all compile units to source files.
CodeDomProvider codeDomProvider = CompilerHelpers.GetCodeDomProvider(language, parameters.CompilerVersion);
// Clone the parameters.
CompilerParameters clonedParams = XomlCompilerHelper.CloneCompilerParameters(parameters);
clonedParams.TempFiles.KeepFiles = true;
tempFiles2 = clonedParams.TempFiles;
clonedParams.GenerateInMemory = true;
if (string.IsNullOrEmpty(parameters.OutputAssembly))
localAssemblyPath = clonedParams.OutputAssembly = clonedParams.TempFiles.AddExtension("dll");
else
{
string tempAssemblyDirectory = clonedParams.TempFiles.BasePath;
int postfix = 0;
while (true)
{
try
{
if (Directory.Exists(tempAssemblyDirectory))
{
break;
}
Directory.CreateDirectory(tempAssemblyDirectory);
createdDirectoryName = tempAssemblyDirectory;
break;
}
catch
{
// If we have tried 10 times without success, give up. Something must be wrong
// with what gets returned by TempFiles.BasePath
if (postfix >= 10)
{
throw;
}
tempAssemblyDirectory = clonedParams.TempFiles.BasePath + postfix++;
}
}
localAssemblyPath = clonedParams.OutputAssembly = tempAssemblyDirectory + "\\" + Path.GetFileName(clonedParams.OutputAssembly);
clonedParams.TempFiles.AddFile(localAssemblyPath, true);
// Working around the fact that when the OutputAssembly is specified, the
// codeDomProvider.CompileAssemblyFromFile call below does NOT add the pdb file
// to the clonedParams.TempFiles collection. Instead, it looks as though it
// does a clonedParams.TempFiles.BasePath.AddExtension("pdb"), which is a file
// that doesn't actually get created.
// We need to add the pdb file to the clonedParameters.TempFiles collection so that
// it gets deleted, even in the case where we didn't end up creating the tempAssemblyDirectory above.
string pdbFilename = Path.GetFileNameWithoutExtension(localAssemblyPath) + ".pdb";
clonedParams.TempFiles.AddFile(Path.GetDirectoryName(localAssemblyPath) + "\\" + pdbFilename, true);
}
// Explictily ignore warnings (in case the user set this property in the project options).
clonedParams.TreatWarningsAsErrors = false;
if (clonedParams.CompilerOptions != null && clonedParams.CompilerOptions.Length > 0)
{
// Need to remove /delaysign option together with the /keyfile or /keycontainer
// the temp assembly should not be signed or we'll have problems loading it.
// Custom splitting: need to take strings like '"one two"' into account
// even though it has a space inside, it should not be split.
string source = clonedParams.CompilerOptions;
ArrayList optionsList = new ArrayList();
int begin = 0;
int end = 0;
bool insideString = false;
while (end < source.Length)
{
int currentLength = end - begin;
if (source[end] == '"')
{
insideString = !insideString;
}
else if (source[end] == ' ' && !insideString)
{
// Split only if not inside string like in "inside some string".
// Split here. Ignore multiple spaces.
if (begin == end)
{
begin++; // end will get incremented in the end of the loop.
}
else
{
string substring = source.Substring(begin, end - begin);
optionsList.Add(substring);
begin = end + 1; // end will get incremented in the end of the loop
}
}
end++;
}
// The remaining sub-string.
if (begin != end)
{
string substring = source.Substring(begin, end - begin);
optionsList.Add(substring);
}
string[] options = optionsList.ToArray(typeof(string)) as string[];
clonedParams.CompilerOptions = string.Empty;
foreach (string option in options)
{
if (option.Length > 0 &&
!option.StartsWith("/delaysign", StringComparison.OrdinalIgnoreCase) &&
!option.StartsWith("/keyfile", StringComparison.OrdinalIgnoreCase) &&
!option.StartsWith("/keycontainer", StringComparison.OrdinalIgnoreCase))
{
clonedParams.CompilerOptions += " " + option;
}
}
}
// Disable compiler optimizations, but include debug information.
clonedParams.CompilerOptions = (clonedParams.CompilerOptions == null) ? "/optimize-" : clonedParams.CompilerOptions + " /optimize-";
clonedParams.IncludeDebugInformation = true;
if (language == SupportedLanguages.CSharp)
clonedParams.CompilerOptions += " /unsafe";
// Add files.
ArrayList ccus = new ArrayList((ICollection)parameters.UserCodeCompileUnits);
ccus.Add(markupCompileUnit);
ArrayList userCodeFiles = new ArrayList();
userCodeFiles.AddRange(codeFiles);
userCodeFiles.AddRange(XomlCompilerHelper.GenerateFiles(codeDomProvider, clonedParams, (CodeCompileUnit[])ccus.ToArray(typeof(CodeCompileUnit))));
// Generate the temporary assembly.
CompilerResults results2 = codeDomProvider.CompileAssemblyFromFile(clonedParams, (string[])userCodeFiles.ToArray(typeof(string)));
if (results2.Errors.HasErrors)
{
results.AddCompilerErrorsFromCompilerResults(results2);
return null;
}
return results2.CompiledAssembly;
}
internal static CodeCompileUnit GenerateCodeFromFileBatch(string[] files, WorkflowCompilerParameters parameters, WorkflowCompilerResults results)
{
WorkflowCompilationContext context = WorkflowCompilationContext.Current;
if (context == null)
throw new Exception(SR.GetString(SR.Error_MissingCompilationContext));
CodeCompileUnit codeCompileUnit = new CodeCompileUnit();
foreach (string fileName in files)
{
Activity rootActivity = null;
try
{
DesignerSerializationManager manager = new DesignerSerializationManager(context.ServiceProvider);
using (manager.CreateSession())
{
WorkflowMarkupSerializationManager xomlSerializationManager = new WorkflowMarkupSerializationManager(manager);
xomlSerializationManager.WorkflowMarkupStack.Push(parameters);
xomlSerializationManager.LocalAssembly = parameters.LocalAssembly;
using (XmlReader reader = XmlReader.Create(fileName))
rootActivity = WorkflowMarkupSerializationHelpers.LoadXomlDocument(xomlSerializationManager, reader, fileName);
if (parameters.LocalAssembly != null)
{
foreach (object error in manager.Errors)
{
if (error is WorkflowMarkupSerializationException)
{
results.Errors.Add(new WorkflowCompilerError(fileName, (WorkflowMarkupSerializationException)error));
}
else
{
results.Errors.Add(new WorkflowCompilerError(fileName, -1, -1, ErrorNumbers.Error_SerializationError.ToString(CultureInfo.InvariantCulture), error.ToString()));
}
}
}
}
}
catch (WorkflowMarkupSerializationException xomlSerializationException)
{
results.Errors.Add(new WorkflowCompilerError(fileName, xomlSerializationException));
continue;
}
catch (Exception e)
{
results.Errors.Add(new WorkflowCompilerError(fileName, -1, -1, ErrorNumbers.Error_SerializationError.ToString(CultureInfo.InvariantCulture), SR.GetString(SR.Error_CompilationFailed, e.Message)));
continue;
}
if (rootActivity == null)
{
results.Errors.Add(new WorkflowCompilerError(fileName, 1, 1, ErrorNumbers.Error_SerializationError.ToString(CultureInfo.InvariantCulture), SR.GetString(SR.Error_RootActivityTypeInvalid)));
continue;
}
bool createNewClass = (!string.IsNullOrEmpty(rootActivity.GetValue(WorkflowMarkupSerializer.XClassProperty) as string));
if (!createNewClass)
{
results.Errors.Add(new WorkflowCompilerError(fileName, 1, 1, ErrorNumbers.Error_SerializationError.ToString(CultureInfo.InvariantCulture), SR.GetString(SR.Error_CannotCompile_No_XClass)));
continue;
}
//NOTE: CompileWithNoCode is meaningless now. It means no x:Code in a XOML file. It exists until the FP migration is done
//Ideally FP should just use XOML files w/o X:Class and run them w/o ever compiling them
if ((parameters.CompileWithNoCode) && XomlCompilerHelper.HasCodeWithin(rootActivity))
{
ValidationError error = new ValidationError(SR.GetString(SR.Error_CodeWithinNotAllowed), ErrorNumbers.Error_CodeWithinNotAllowed);
error.UserData[typeof(Activity)] = rootActivity;
results.Errors.Add(XomlCompilerHelper.CreateXomlCompilerError(error, parameters));
}
ValidationErrorCollection errors = new ValidationErrorCollection();
errors = ValidateIdentifiers(context.ServiceProvider, rootActivity);
foreach (ValidationError error in errors)
results.Errors.Add(XomlCompilerHelper.CreateXomlCompilerError(error, parameters));
if (results.Errors.HasErrors)
continue;
codeCompileUnit.Namespaces.AddRange(WorkflowMarkupSerializationHelpers.GenerateCodeFromXomlDocument(rootActivity, fileName, context.RootNamespace, CompilerHelpers.GetSupportedLanguage(context.Language), context.ServiceProvider));
}
WorkflowMarkupSerializationHelpers.FixStandardNamespacesAndRootNamespace(codeCompileUnit.Namespaces, context.RootNamespace, CompilerHelpers.GetSupportedLanguage(context.Language));
return codeCompileUnit;
}
#endregion
}
#endregion
}
|