internal static void InternalCompileFromDomBatch(string[] files, string[] codeFiles, WorkflowCompilerParameters parameters, WorkflowCompilerResults results, string localAssemblyPath)
        {
            foreach (string str in parameters.LibraryPaths)
            {
                if (!CheckPathName(str))
                {
                    int num5 = 0x160;
                    WorkflowCompilerError error = new WorkflowCompilerError(string.Empty, 0, 0, num5.ToString(CultureInfo.InvariantCulture), string.Format(CultureInfo.CurrentCulture, SR.GetString("LibraryPathIsInvalid"), new object[] { str }))
                    {
                        IsWarning = true
                    };
                    results.Errors.Add(error);
                }
            }
            IList <AuthorizedType> authorizedTypes = null;

            if (parameters.CheckTypes)
            {
                authorizedTypes = WorkflowCompilationContext.Current.GetAuthorizedTypes();
                if (authorizedTypes == null)
                {
                    ValidationError error2 = new ValidationError(SR.GetString("Error_ConfigFileMissingOrInvalid"), 0x178);
                    results.Errors.Add(CreateXomlCompilerError(error2, parameters));
                    return;
                }
            }
            ITypeProvider service = WorkflowCompilationContext.Current.ServiceProvider.GetService(typeof(ITypeProvider)) as ITypeProvider;
            ArrayList     list2   = new ArrayList();

            using (PDBReader reader = new PDBReader(localAssemblyPath))
            {
                foreach (Type type in service.LocalAssembly.GetTypes())
                {
                    if (TypeProvider.IsAssignable(typeof(Activity), type) && !type.IsAbstract)
                    {
                        string fileLocation = string.Empty;
                        WorkflowMarkupSourceAttribute[] customAttributes = (WorkflowMarkupSourceAttribute[])type.GetCustomAttributes(typeof(WorkflowMarkupSourceAttribute), false);
                        if ((customAttributes != null) && (customAttributes.Length > 0))
                        {
                            fileLocation = customAttributes[0].FileName;
                        }
                        else
                        {
                            ConstructorInfo constructor = type.GetConstructor(Type.EmptyTypes);
                            if (constructor != null)
                            {
                                try
                                {
                                    uint line   = 0;
                                    uint column = 0;
                                    reader.GetSourceLocationForOffset((uint)constructor.MetadataToken, 0, out fileLocation, out line, out column);
                                }
                                catch
                                {
                                }
                            }
                            if (string.IsNullOrEmpty(fileLocation))
                            {
                                MethodInfo info2 = type.GetMethod("InitializeComponent", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance, null, Type.EmptyTypes, null);
                                if (info2 != null)
                                {
                                    try
                                    {
                                        uint num3 = 0;
                                        uint num4 = 0;
                                        reader.GetSourceLocationForOffset((uint)info2.MetadataToken, 0, out fileLocation, out num3, out num4);
                                        if (!string.IsNullOrEmpty(fileLocation))
                                        {
                                            if (fileLocation.EndsWith(".designer.cs", StringComparison.OrdinalIgnoreCase))
                                            {
                                                fileLocation = fileLocation.Substring(0, fileLocation.Length - ".designer.cs".Length) + ".cs";
                                            }
                                            else if (fileLocation.EndsWith(".designer.vb", StringComparison.OrdinalIgnoreCase))
                                            {
                                                fileLocation = fileLocation.Substring(0, fileLocation.Length - ".designer.vb".Length) + ".vb";
                                            }
                                        }
                                    }
                                    catch
                                    {
                                    }
                                }
                            }
                        }
                        Activity activity = null;
                        try
                        {
                            try
                            {
                                Activity.ActivityType = type;
                                activity = Activator.CreateInstance(type) as Activity;
                            }
                            finally
                            {
                                Activity.ActivityType = null;
                            }
                            activity.UserData[UserDataKeys.CustomActivity] = false;
                            if (activity is CompositeActivity)
                            {
                                CompositeActivity activity2 = activity as CompositeActivity;
                                if (activity2.CanModifyActivities)
                                {
                                    results.Errors.Add(CreateXomlCompilerError(new ValidationError(SR.GetString("Error_Missing_CanModifyProperties_False", new object[] { activity.GetType().FullName }), 0x117), parameters));
                                }
                            }
                            if (customAttributes.Length > 0)
                            {
                                DesignerSerializationManager manager = new DesignerSerializationManager(WorkflowCompilationContext.Current.ServiceProvider);
                                Activity activity3 = null;
                                using (manager.CreateSession())
                                {
                                    WorkflowMarkupSerializationManager serializationManager = new WorkflowMarkupSerializationManager(manager)
                                    {
                                        LocalAssembly = parameters.LocalAssembly
                                    };
                                    using (XmlReader reader2 = XmlReader.Create(customAttributes[0].FileName))
                                    {
                                        activity3 = new WorkflowMarkupSerializer().Deserialize(serializationManager, reader2) as Activity;
                                    }
                                }
                                if (activity3 is CompositeActivity)
                                {
                                    ActivityMarkupSerializer.ReplaceChildActivities(activity as CompositeActivity, activity3 as CompositeActivity);
                                }
                            }
                        }
                        catch (TargetInvocationException exception)
                        {
                            if ((exception.InnerException is TypeInitializationException) && (exception.InnerException.InnerException != null))
                            {
                                results.Errors.Add(CreateXomlCompilerError(new ValidationError(SR.GetString("Error_CustomActivityCantCreate", new object[] { type.FullName, exception.InnerException.InnerException.ToString() }), 0x117), parameters));
                            }
                            else if (exception.InnerException.InnerException != null)
                            {
                                results.Errors.Add(CreateXomlCompilerError(new ValidationError(exception.InnerException.InnerException.ToString(), 0x117), parameters));
                            }
                            else
                            {
                                results.Errors.Add(CreateXomlCompilerError(new ValidationError(SR.GetString("Error_CustomActivityCantCreate", new object[] { type.FullName, exception.InnerException.ToString() }), 0x117), parameters));
                            }
                            continue;
                        }
                        catch (Exception exception2)
                        {
                            results.Errors.Add(CreateXomlCompilerError(new ValidationError(SR.GetString("Error_CustomActivityCantCreate", new object[] { type.FullName, exception2.ToString() }), 0x117), parameters));
                            continue;
                        }
                        activity.SetValue(ActivityCodeDomSerializer.MarkupFileNameProperty, fileLocation);
                        activity.SetValue(WorkflowMarkupSerializer.XClassProperty, type.FullName);
                        ValidateActivity(activity, parameters, results);
                        list2.Add(activity);
                    }
                }
            }
            foreach (KeyValuePair <object, Exception> pair in service.TypeLoadErrors)
            {
                int num7 = 0x161;
                WorkflowCompilerError error3 = new WorkflowCompilerError(string.Empty, 0, 0, num7.ToString(CultureInfo.InvariantCulture), pair.Value.Message)
                {
                    IsWarning = true
                };
                results.Errors.Add(error3);
            }
            results.CompiledUnit = WorkflowCompilerInternal.GenerateCodeFromFileBatch(files, parameters, results);
            WorkflowCompilationContext current = WorkflowCompilationContext.Current;

            if (current == null)
            {
                throw new Exception(SR.GetString("Error_MissingCompilationContext"));
            }
            WorkflowMarkupSerializationHelpers.ReapplyRootNamespace(results.CompiledUnit.Namespaces, current.RootNamespace, CompilerHelpers.GetSupportedLanguage(current.Language));
            WorkflowMarkupSerializationHelpers.FixStandardNamespacesAndRootNamespace(results.CompiledUnit.Namespaces, current.RootNamespace, CompilerHelpers.GetSupportedLanguage(current.Language));
            if (!results.Errors.HasErrors)
            {
                CodeGenerationManager manager3 = new CodeGenerationManager(WorkflowCompilationContext.Current.ServiceProvider);
                manager3.Context.Push(results.CompiledUnit.Namespaces);
                foreach (Activity activity4 in list2)
                {
                    if (activity4.Parent == null)
                    {
                        foreach (ActivityCodeGenerator generator in manager3.GetCodeGenerators(activity4.GetType()))
                        {
                            generator.GenerateCode(manager3, activity4);
                        }
                    }
                }
                if (!parameters.GenerateCodeCompileUnitOnly || parameters.CheckTypes)
                {
                    CodeDomProvider codeDomProvider = CompilerHelpers.GetCodeDomProvider(CompilerHelpers.GetSupportedLanguage(parameters.LanguageToUse), parameters.CompilerVersion);
                    ArrayList       list3           = new ArrayList((ICollection)parameters.UserCodeCompileUnits);
                    list3.Add(results.CompiledUnit);
                    ArrayList list4 = new ArrayList();
                    list4.AddRange(codeFiles);
                    list4.AddRange(GenerateFiles(codeDomProvider, parameters, (CodeCompileUnit[])list3.ToArray(typeof(CodeCompileUnit))));
                    CompilerResults results2 = codeDomProvider.CompileAssemblyFromFile(parameters, (string[])list4.ToArray(typeof(string)));
                    results.AddCompilerErrorsFromCompilerResults(results2);
                    results.PathToAssembly            = results2.PathToAssembly;
                    results.NativeCompilerReturnValue = results2.NativeCompilerReturnValue;
                    if (!results.Errors.HasErrors && parameters.CheckTypes)
                    {
                        foreach (string str3 in MetaDataReader.GetTypeRefNames(results2.CompiledAssembly.Location))
                        {
                            bool flag = false;
                            foreach (AuthorizedType type2 in authorizedTypes)
                            {
                                if (type2.RegularExpression.IsMatch(str3))
                                {
                                    flag = string.Compare(bool.TrueString, type2.Authorized, StringComparison.OrdinalIgnoreCase) == 0;
                                    if (!flag)
                                    {
                                        break;
                                    }
                                }
                            }
                            if (!flag)
                            {
                                ValidationError error4 = new ValidationError(SR.GetString("Error_TypeNotAuthorized", new object[] { str3 }), 0x16b);
                                results.Errors.Add(CreateXomlCompilerError(error4, parameters));
                            }
                        }
                    }
                    if (((!results.Errors.HasErrors && !parameters.GenerateCodeCompileUnitOnly) && parameters.GenerateInMemory) && (string.IsNullOrEmpty(parameters.CompilerOptions) || !parameters.CompilerOptions.ToLower(CultureInfo.InvariantCulture).Contains("/delaysign")))
                    {
                        results.CompiledAssembly = results2.CompiledAssembly;
                    }
                }
            }
        }
Ejemplo n.º 2
0
        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);
        }
Ejemplo n.º 3
0
        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);
        }
        public object GetArgumentValueAs(IServiceProvider serviceProvider, int argumentIndex, Type requestedType)
        {
            if ((argumentIndex >= this.ArgumentValues.Count) || (argumentIndex < 0))
            {
                throw new ArgumentException(SR.GetString("Error_InvalidArgumentIndex"), "argumentIndex");
            }
            if (requestedType == null)
            {
                throw new ArgumentNullException("requestedType");
            }
            SupportedLanguages supportedLanguage = CompilerHelpers.GetSupportedLanguage(serviceProvider);

            if (requestedType == typeof(string))
            {
                string str = this.ArgumentValues[argumentIndex] as string;
                if (str != null)
                {
                    try
                    {
                        str = Regex.Unescape(str);
                    }
                    catch
                    {
                    }
                }
                if (str != null)
                {
                    if (str.EndsWith("\"", StringComparison.Ordinal))
                    {
                        str = str.Substring(0, str.Length - 1);
                    }
                    if ((supportedLanguage == SupportedLanguages.CSharp) && str.StartsWith("@\"", StringComparison.Ordinal))
                    {
                        return(str.Substring(2, str.Length - 2));
                    }
                    if (str.StartsWith("\"", StringComparison.Ordinal))
                    {
                        str = str.Substring(1, str.Length - 1);
                    }
                }
                return(str);
            }
            if (requestedType.IsEnum)
            {
                string str2 = "";
                bool   flag = true;
                foreach (string str3 in (this.ArgumentValues[argumentIndex] as string).Split(new string[] { (supportedLanguage == SupportedLanguages.CSharp) ? "|" : "Or" }, StringSplitOptions.RemoveEmptyEntries))
                {
                    if (!flag)
                    {
                        str2 = str2 + ",";
                    }
                    int num = str3.LastIndexOf('.');
                    if (num != -1)
                    {
                        str2 = str2 + str3.Substring(num + 1);
                    }
                    else
                    {
                        str2 = str2 + str3;
                    }
                    flag = false;
                }
                return(Enum.Parse(requestedType, str2));
            }
            if (requestedType == typeof(bool))
            {
                return(Convert.ToBoolean(this.ArgumentValues[argumentIndex], CultureInfo.InvariantCulture));
            }
            if (!(requestedType == typeof(Type)))
            {
                return(null);
            }
            string typeName = "";

            if (this.ArgumentValues[argumentIndex] is CodeTypeOfExpression)
            {
                typeName = DesignTimeType.GetTypeNameFromCodeTypeReference((this.ArgumentValues[argumentIndex] as CodeTypeOfExpression).Type, null);
            }
            ITypeProvider service = serviceProvider.GetService(typeof(ITypeProvider)) as ITypeProvider;

            if (service == null)
            {
                throw new Exception(SR.GetString("General_MissingService", new object[] { typeof(ITypeProvider).ToString() }));
            }
            Type type = ParseHelpers.ParseTypeName(service, supportedLanguage, typeName);

            if (type != null)
            {
                return(type);
            }
            string[] parameters       = null;
            string   str5             = string.Empty;
            string   elemantDecorator = string.Empty;

            if ((!ParseHelpers.ParseTypeName(typeName, (supportedLanguage == SupportedLanguages.CSharp) ? ParseHelpers.ParseTypeNameLanguage.CSharp : ParseHelpers.ParseTypeNameLanguage.VB, out str5, out parameters, out elemantDecorator) || (str5 == null)) || (parameters == null))
            {
                return(type);
            }
            string str7 = str5 + "`" + parameters.Length.ToString(CultureInfo.InvariantCulture) + "[";

            foreach (string str8 in parameters)
            {
                if (str8 != parameters[0])
                {
                    str7 = str7 + ",";
                }
                Type type2 = ParseHelpers.ParseTypeName(service, supportedLanguage, str8);
                if (type2 != null)
                {
                    str7 = str7 + "[" + type2.FullName + "]";
                }
                else
                {
                    str7 = str7 + "[" + str8 + "]";
                }
            }
            str7 = str7 + "]";
            return(ParseHelpers.ParseTypeName(service, supportedLanguage, str7));
        }
Ejemplo n.º 5
0
        internal static void InternalCompileFromDomBatch(string[] files, string[] codeFiles, WorkflowCompilerParameters parameters, WorkflowCompilerResults results, string localAssemblyPath)
        {
            // Check all the library paths are valid.
            foreach (string libraryPath in parameters.LibraryPaths)
            {
                if (!XomlCompilerHelper.CheckPathName(libraryPath))
                {
                    WorkflowCompilerError libPathError =
                        new WorkflowCompilerError(string.Empty, 0, 0, ErrorNumbers.Error_LibraryPath.ToString(CultureInfo.InvariantCulture), string.Format(CultureInfo.CurrentCulture, SR.GetString(SR.LibraryPathIsInvalid), libraryPath));
                    libPathError.IsWarning = true;
                    results.Errors.Add(libPathError);
                }
            }

            IList <AuthorizedType> authorizedTypes = null;

            if (parameters.CheckTypes)
            {
                //If we dont find the list of authorized types then return.
                authorizedTypes = WorkflowCompilationContext.Current.GetAuthorizedTypes();
                if (authorizedTypes == null)
                {
                    ValidationError error = new ValidationError(SR.GetString(SR.Error_ConfigFileMissingOrInvalid), ErrorNumbers.Error_ConfigFileMissingOrInvalid);
                    results.Errors.Add(CreateXomlCompilerError(error, parameters));
                    return;
                }
            }

            ITypeProvider typeProvider = WorkflowCompilationContext.Current.ServiceProvider.GetService(typeof(ITypeProvider)) as ITypeProvider;
            ArrayList     activities   = new ArrayList();

            using (PDBReader pdbReader = new PDBReader(localAssemblyPath))
            {
                // Validate all the compiled activities in the assembly.
                foreach (Type type in typeProvider.LocalAssembly.GetTypes())
                {
                    if (!TypeProvider.IsAssignable(typeof(Activity), type) || type.IsAbstract)
                    {
                        continue;
                    }

                    // Fetch file name.
                    string fileName = string.Empty;
                    WorkflowMarkupSourceAttribute[] sourceAttrs = (WorkflowMarkupSourceAttribute[])type.GetCustomAttributes(typeof(WorkflowMarkupSourceAttribute), false);
                    if (sourceAttrs != null && sourceAttrs.Length > 0)
                    {
                        fileName = sourceAttrs[0].FileName;
                    }
                    else
                    {
                        ConstructorInfo ctorMethod = type.GetConstructor(Type.EmptyTypes);
                        if (ctorMethod != null)
                        {
                            try
                            {
                                uint line = 0, column = 0;
                                pdbReader.GetSourceLocationForOffset((uint)ctorMethod.MetadataToken, 0, out fileName, out line, out column);
                            }
                            catch
                            {
                                // We don't want errors if the user has written their own custom
                                // activity and simply inherited the constructor
                            }
                        }

                        // In case of VB, if the ctor is autogenerated the PDB will not have symbol
                        // information. Use InitializeComponent method as the fallback.
                        if (String.IsNullOrEmpty(fileName))
                        {
                            MethodInfo initializeComponent = type.GetMethod("InitializeComponent", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, Type.EmptyTypes, null);
                            if (initializeComponent != null)
                            {
                                try
                                {
                                    uint line = 0, column = 0;
                                    pdbReader.GetSourceLocationForOffset((uint)initializeComponent.MetadataToken, 0, out fileName, out line, out column);

                                    if (!String.IsNullOrEmpty(fileName))
                                    {
                                        if (fileName.EndsWith(".designer.cs", StringComparison.OrdinalIgnoreCase))
                                        {
                                            fileName = fileName.Substring(0, fileName.Length - ".designer.cs".Length) + ".cs";
                                        }
                                        else if (fileName.EndsWith(".designer.vb", StringComparison.OrdinalIgnoreCase))
                                        {
                                            fileName = fileName.Substring(0, fileName.Length - ".designer.vb".Length) + ".vb";
                                        }
                                    }
                                }
                                catch
                                {
                                }
                            }
                        }
                    }

                    // Create the activity.
                    Activity activity = null;
                    try
                    {
                        try
                        {
                            Activity.ActivityType = type;
                            activity = Activator.CreateInstance(type) as Activity;
                        }
                        finally
                        {
                            Activity.ActivityType = null;
                        }
                        activity.UserData[UserDataKeys.CustomActivity] = false;
                        if (activity is CompositeActivity)
                        {
                            CompositeActivity compositeActivity = activity as CompositeActivity;
                            if (compositeActivity.CanModifyActivities)
                            {
                                results.Errors.Add(CreateXomlCompilerError(new ValidationError(SR.GetString(SR.Error_Missing_CanModifyProperties_False, activity.GetType().FullName), ErrorNumbers.Error_CustomActivityCantCreate), parameters));
                            }
                        }
                        if (sourceAttrs.Length > 0)
                        {
                            DesignerSerializationManager manager = new DesignerSerializationManager(WorkflowCompilationContext.Current.ServiceProvider);
                            Activity instance2 = null;
                            using (manager.CreateSession())
                            {
                                WorkflowMarkupSerializationManager xomlSerializationManager = new WorkflowMarkupSerializationManager(manager);
                                xomlSerializationManager.LocalAssembly = parameters.LocalAssembly;
                                using (XmlReader reader = XmlReader.Create((sourceAttrs[0].FileName)))
                                    instance2 = new WorkflowMarkupSerializer().Deserialize(xomlSerializationManager, reader) as Activity;
                            }
                            if (instance2 is CompositeActivity)
                            {
                                ActivityMarkupSerializer.ReplaceChildActivities(activity as CompositeActivity, instance2 as CompositeActivity);
                            }
                        }
                    }
                    catch (TargetInvocationException tie)
                    {
                        // For TypeInitializationException, the message is available at the inner Exception
                        if (tie.InnerException is TypeInitializationException && tie.InnerException.InnerException != null)
                        {
                            results.Errors.Add(CreateXomlCompilerError(new ValidationError(SR.GetString(SR.Error_CustomActivityCantCreate, type.FullName, tie.InnerException.InnerException.ToString()), ErrorNumbers.Error_CustomActivityCantCreate), parameters));
                        }
                        else if (tie.InnerException.InnerException != null)
                        {
                            results.Errors.Add(CreateXomlCompilerError(new ValidationError(tie.InnerException.InnerException.ToString(), ErrorNumbers.Error_CustomActivityCantCreate), parameters));
                        }
                        else
                        {
                            results.Errors.Add(CreateXomlCompilerError(new ValidationError(SR.GetString(SR.Error_CustomActivityCantCreate, type.FullName, tie.InnerException.ToString()), ErrorNumbers.Error_CustomActivityCantCreate), parameters));
                        }
                        continue;
                    }
                    catch (Exception e)
                    {
                        results.Errors.Add(CreateXomlCompilerError(new ValidationError(SR.GetString(SR.Error_CustomActivityCantCreate, type.FullName, e.ToString()), ErrorNumbers.Error_CustomActivityCantCreate), parameters));
                        continue;
                    }

                    // Work around : another set of work arounds.
                    activity.SetValue(ActivityCodeDomSerializer.MarkupFileNameProperty, fileName);
                    activity.SetValue(WorkflowMarkupSerializer.XClassProperty, type.FullName);

                    // Run the validators.
                    ValidateActivity(activity, parameters, results);
                    activities.Add(activity);
                }
            }

            // Add all type load errors to compiler results.
            foreach (KeyValuePair <object, Exception> entry in typeProvider.TypeLoadErrors)
            {
                WorkflowCompilerError compilerError = new WorkflowCompilerError(string.Empty, 0, 0, ErrorNumbers.Error_TypeLoad.ToString(CultureInfo.InvariantCulture), entry.Value.Message);
                compilerError.IsWarning = true;
                results.Errors.Add(compilerError);
            }
            results.CompiledUnit = WorkflowCompilerInternal.GenerateCodeFromFileBatch(files, parameters, results);

            WorkflowCompilationContext context = WorkflowCompilationContext.Current;

            if (context == null)
            {
                throw new Exception(SR.GetString(SR.Error_MissingCompilationContext));
            }
            // Fix standard namespaces and root namespace.
            WorkflowMarkupSerializationHelpers.ReapplyRootNamespace(results.CompiledUnit.Namespaces, context.RootNamespace, CompilerHelpers.GetSupportedLanguage(context.Language));
            WorkflowMarkupSerializationHelpers.FixStandardNamespacesAndRootNamespace(results.CompiledUnit.Namespaces, context.RootNamespace, CompilerHelpers.GetSupportedLanguage(context.Language));
            if (!results.Errors.HasErrors)
            {
                // ask activities to generate code for themselves
                CodeGenerationManager codeGenerationManager = new CodeGenerationManager(WorkflowCompilationContext.Current.ServiceProvider);
                codeGenerationManager.Context.Push(results.CompiledUnit.Namespaces);
                foreach (Activity activity in activities)
                {
                    // Need to call code generators associated with the root activity.
                    if (activity.Parent == null)
                    {
                        foreach (System.Workflow.ComponentModel.Compiler.ActivityCodeGenerator codeGenerator in codeGenerationManager.GetCodeGenerators(activity.GetType()))
                        {
                            codeGenerator.GenerateCode(codeGenerationManager, activity);
                        }
                    }
                }

                // If only ccu needed then return.
                if (!parameters.GenerateCodeCompileUnitOnly || parameters.CheckTypes)
                {
                    // Convert all compile units to source files.
                    SupportedLanguages language        = CompilerHelpers.GetSupportedLanguage(parameters.LanguageToUse);
                    CodeDomProvider    codeDomProvider = CompilerHelpers.GetCodeDomProvider(language, parameters.CompilerVersion);
                    ArrayList          ccus            = new ArrayList((ICollection)parameters.UserCodeCompileUnits);
                    ccus.Add(results.CompiledUnit);

                    ArrayList sourceFilePaths = new ArrayList();
                    sourceFilePaths.AddRange(codeFiles);
                    sourceFilePaths.AddRange(XomlCompilerHelper.GenerateFiles(codeDomProvider, parameters, (CodeCompileUnit[])ccus.ToArray(typeof(CodeCompileUnit))));

                    // Finally give it to Code Compiler.
                    CompilerResults results2 = codeDomProvider.CompileAssemblyFromFile(parameters, (string[])sourceFilePaths.ToArray(typeof(string)));
                    results.AddCompilerErrorsFromCompilerResults(results2);
                    results.PathToAssembly            = results2.PathToAssembly;
                    results.NativeCompilerReturnValue = results2.NativeCompilerReturnValue;

                    if (!results.Errors.HasErrors && parameters.CheckTypes)
                    {
                        foreach (string referenceType in MetaDataReader.GetTypeRefNames(results2.CompiledAssembly.Location))
                        {
                            bool authorized = false;
                            foreach (AuthorizedType authorizedType in authorizedTypes)
                            {
                                if (authorizedType.RegularExpression.IsMatch(referenceType))
                                {
                                    authorized = (String.Compare(bool.TrueString, authorizedType.Authorized, StringComparison.OrdinalIgnoreCase) == 0);
                                    if (!authorized)
                                    {
                                        break;
                                    }
                                }
                            }
                            if (!authorized)
                            {
                                ValidationError error = new ValidationError(SR.GetString(SR.Error_TypeNotAuthorized, referenceType), ErrorNumbers.Error_TypeNotAuthorized);
                                results.Errors.Add(CreateXomlCompilerError(error, parameters));
                            }
                        }
                    }
                    //this line was throwing for the delay sign case. besides, copying PathToAssembly should do the same...
                    if (!results.Errors.HasErrors && !parameters.GenerateCodeCompileUnitOnly && parameters.GenerateInMemory &&
                        (string.IsNullOrEmpty(parameters.CompilerOptions) || !parameters.CompilerOptions.ToLower(CultureInfo.InvariantCulture).Contains("/delaysign")))
                    {
                        results.CompiledAssembly = results2.CompiledAssembly;
                    }
                }
            }
        }
Ejemplo n.º 6
0
 internal static CodeDomProvider GetCodeDomProvider(SupportedLanguages language)
 {
     return(CompilerHelpers.GetCodeDomProvider(language, string.Empty));
 }
        public override bool Execute()
        {
            CompilerOptionsBuilder builder;

            if (!this.ValidateParameters())
            {
                return(false);
            }
            if (this.WorkflowMarkupFiles == null)
            {
                base.Log.LogMessageFromResources(MessageImportance.Normal, "NoXomlFiles", new object[0]);
            }
            if ((this.ReferenceFiles == null) || (this.ReferenceFiles.Length == 0))
            {
                base.Log.LogMessageFromResources(MessageImportance.Normal, "NoReferenceFiles", new object[0]);
            }
            if ((this.SourceCodeFiles == null) || (this.SourceCodeFiles.Length == 0))
            {
                base.Log.LogMessageFromResources(MessageImportance.Normal, "NoSourceCodeFiles", new object[0]);
            }
            if (((this.HostObject == null) || ((this.HostObject is IWorkflowBuildHostProperties) && ((IWorkflowBuildHostProperties)this.HostObject).SkipWorkflowCompilation)) && (string.Compare(Process.GetCurrentProcess().ProcessName, "devenv", StringComparison.OrdinalIgnoreCase) == 0))
            {
                return(true);
            }
            int num  = 0;
            int num2 = 0;
            WorkflowCompilerParameters   parameters = new WorkflowCompilerParameters();
            IWorkflowCompilerErrorLogger service    = null;
            IServiceProvider             provider   = null;

            if (this.HostObject is IOleServiceProvider)
            {
                provider = new ServiceProvider(this.HostObject as IOleServiceProvider);
                service  = provider.GetService(typeof(IWorkflowCompilerErrorLogger)) as IWorkflowCompilerErrorLogger;
            }
            string[] strArray = GetFiles(this.SourceCodeFiles, this.ProjectDirectory);
            foreach (ITaskItem item in this.ReferenceFiles)
            {
                parameters.ReferencedAssemblies.Add(item.ItemSpec);
            }
            if (!string.IsNullOrEmpty(this.targetFramework))
            {
                parameters.MultiTargetingInformation = new MultiTargetingInfo(this.targetFramework);
            }
            if (this.ProjectType != SupportedLanguages.VB)
            {
                builder = new CompilerOptionsBuilder();
            }
            else
            {
                string compilerVersion = parameters.CompilerVersion;
                if (compilerVersion != null)
                {
                    if (!(compilerVersion == "v2.0"))
                    {
                        if (compilerVersion == "v3.5")
                        {
                            builder = new OrcasVBCompilerOptionsBuilder();
                            goto Label_01BE;
                        }
                    }
                    else
                    {
                        builder = new WhidbeyVBCompilerOptionsBuilder();
                        goto Label_01BE;
                    }
                }
                builder = new CompilerOptionsBuilder();
            }
Label_01BE:
            parameters.CompilerOptions             = this.PrepareCompilerOptions(builder);
            parameters.GenerateCodeCompileUnitOnly = true;
            parameters.LanguageToUse       = this.ProjectType.ToString();
            parameters.TempFiles.KeepFiles = this.ShouldKeepTempFiles();
            parameters.OutputAssembly      = this.AssemblyName;
            if (!string.IsNullOrEmpty(this.assemblyName))
            {
                string str = parameters.GenerateExecutable ? ".exe" : ".dll";
                parameters.OutputAssembly = parameters.OutputAssembly + str;
            }
            CodeDomProvider provider2 = null;

            if (this.ProjectType == SupportedLanguages.VB)
            {
                provider2 = CompilerHelpers.CreateCodeProviderInstance(typeof(VBCodeProvider), parameters.CompilerVersion);
            }
            else
            {
                provider2 = CompilerHelpers.CreateCodeProviderInstance(typeof(CSharpCodeProvider), parameters.CompilerVersion);
            }
            using (TempFileCollection files = new TempFileCollection(Environment.GetEnvironmentVariable("temp", EnvironmentVariableTarget.User), true))
            {
                string[] strArray2;
                this.outputFiles = new TaskItem[1];
                if (this.WorkflowMarkupFiles != null)
                {
                    strArray2 = new string[this.WorkflowMarkupFiles.GetLength(0) + strArray.Length];
                    int index = 0;
                    while (index < this.WorkflowMarkupFiles.GetLength(0))
                    {
                        strArray2[index] = Path.Combine(this.ProjectDirectory, this.WorkflowMarkupFiles[index].ItemSpec);
                        index++;
                    }
                    strArray.CopyTo(strArray2, index);
                }
                else
                {
                    strArray2 = new string[strArray.Length];
                    strArray.CopyTo(strArray2, 0);
                }
                WorkflowCompilerResults results = new CompilerWrapper().Compile(parameters, strArray2);
                foreach (WorkflowCompilerError error in results.Errors)
                {
                    if (error.IsWarning)
                    {
                        num2++;
                        if (service != null)
                        {
                            error.FileName = Path.Combine(this.ProjectDirectory, error.FileName);
                            service.LogError(error);
                            service.LogMessage(error.ToString() + "\n");
                        }
                        else
                        {
                            base.Log.LogWarning(error.ErrorText, new object[] { error.ErrorNumber, error.FileName, error.Line, error.Column });
                        }
                    }
                    else
                    {
                        num++;
                        if (service != null)
                        {
                            error.FileName = Path.Combine(this.ProjectDirectory, error.FileName);
                            service.LogError(error);
                            service.LogMessage(error.ToString() + "\n");
                        }
                        else
                        {
                            base.Log.LogError(error.ErrorText, new object[] { error.ErrorNumber, error.FileName, error.Line, error.Column });
                        }
                    }
                }
                if (!results.Errors.HasErrors)
                {
                    CodeCompileUnit compiledUnit = results.CompiledUnit;
                    if (compiledUnit != null)
                    {
                        WorkflowMarkupSerializationHelpers.FixStandardNamespacesAndRootNamespace(compiledUnit.Namespaces, this.RootNamespace, CompilerHelpers.GetSupportedLanguage(this.ProjectType.ToString()));
                        string path = files.AddExtension(provider2.FileExtension);
                        using (StreamWriter writer = new StreamWriter(new FileStream(path, FileMode.Create, FileAccess.Write), Encoding.UTF8))
                        {
                            CodeGeneratorOptions options = new CodeGeneratorOptions {
                                BracingStyle = "C"
                            };
                            provider2.GenerateCodeFromCompileUnit(compiledUnit, writer, options);
                        }
                        this.outputFiles[0] = new TaskItem(path);
                        this.temporaryFiles.Add(path);
                        base.Log.LogMessageFromResources(MessageImportance.Normal, "TempCodeFile", new object[] { path });
                    }
                }
            }
            if (((num > 0) || (num2 > 0)) && (service != null))
            {
                service.LogMessage(string.Format(CultureInfo.CurrentCulture, "\nCompile complete -- {0} errors, {1} warnings \n", new object[] { num, num2 }));
            }
            base.Log.LogMessageFromResources(MessageImportance.Normal, "XomlValidationCompleted", new object[] { num, num2 });
            return(num == 0);
        }
        public object GetArgumentValueAs(IServiceProvider serviceProvider, int argumentIndex, Type requestedType)
        {
            if (argumentIndex >= this.ArgumentValues.Count || argumentIndex < 0)
            {
                throw new ArgumentException(SR.GetString(SR.Error_InvalidArgumentIndex), "argumentIndex");
            }

            if (requestedType == null)
            {
                throw new ArgumentNullException("requestedType");
            }

            SupportedLanguages language = CompilerHelpers.GetSupportedLanguage(serviceProvider);

            if (requestedType == typeof(string))
            {
                string returnValue = this.ArgumentValues[argumentIndex] as string;

                // string values read by the code-dom parser are double escaped, so
                // remove the 2nd escaping (we need to leave the escaping in at parse time)
                // in case the attribute argument is never processed and emitted as
                // the code snippet
                if (returnValue != null)
                {
                    try
                    {
                        returnValue = Regex.Unescape(returnValue);
                    }
                    catch
                    {
                    }
                }

                if (returnValue != null)
                {
                    if (returnValue.EndsWith("\"", StringComparison.Ordinal))
                    {
                        returnValue = returnValue.Substring(0, returnValue.Length - 1);
                    }

                    if (language == SupportedLanguages.CSharp && returnValue.StartsWith("@\"", StringComparison.Ordinal))
                    {
                        returnValue = returnValue.Substring(2, returnValue.Length - 2);
                    }
                    else if (returnValue.StartsWith("\"", StringComparison.Ordinal))
                    {
                        returnValue = returnValue.Substring(1, returnValue.Length - 1);
                    }
                }

                return(returnValue);
            }
            else if (requestedType.IsEnum)
            {
                string parseableValue = "";
                bool   firstValue     = true;
                foreach (string enumValue in (this.ArgumentValues[argumentIndex] as string).Split(new string[] { language == SupportedLanguages.CSharp ? "|" : "Or" }, StringSplitOptions.RemoveEmptyEntries))
                {
                    if (!firstValue)
                    {
                        parseableValue += ",";
                    }

                    int valueSep = enumValue.LastIndexOf('.');
                    if (valueSep != -1)
                    {
                        parseableValue += enumValue.Substring(valueSep + 1);
                    }
                    else
                    {
                        parseableValue += enumValue;
                    }

                    firstValue = false;
                }

                return(Enum.Parse(requestedType, parseableValue));
            }
            else if (requestedType == typeof(bool))
            {
                return(System.Convert.ToBoolean(this.ArgumentValues[argumentIndex], CultureInfo.InvariantCulture));
            }
            else if (requestedType == typeof(Type))
            {
                string typeName = "";
                if (this.ArgumentValues[argumentIndex] is CodeTypeOfExpression)
                {
                    typeName = DesignTimeType.GetTypeNameFromCodeTypeReference((this.ArgumentValues[argumentIndex] as CodeTypeOfExpression).Type, null);
                }

                ITypeProvider typeProvider = serviceProvider.GetService(typeof(ITypeProvider)) as ITypeProvider;
                if (typeProvider == null)
                {
                    throw new Exception(SR.GetString(SR.General_MissingService, typeof(ITypeProvider).ToString()));
                }

                Type returnType = ParseHelpers.ParseTypeName(typeProvider, language, typeName);
                if (returnType == null)
                {
                    // Try to parse the attribute value manually
                    string[] genericParamTypeNames = null;
                    string   baseTypeName          = string.Empty;
                    string   elementDecorators     = string.Empty;
                    if (ParseHelpers.ParseTypeName(typeName, language == SupportedLanguages.CSharp ? ParseHelpers.ParseTypeNameLanguage.CSharp : ParseHelpers.ParseTypeNameLanguage.VB, out baseTypeName, out genericParamTypeNames, out elementDecorators))
                    {
                        if (baseTypeName != null && genericParamTypeNames != null)
                        {
                            string parsedTypeName = baseTypeName + "`" + genericParamTypeNames.Length.ToString(CultureInfo.InvariantCulture) + "[";
                            foreach (string genericArg in genericParamTypeNames)
                            {
                                if (genericArg != genericParamTypeNames[0])
                                {
                                    parsedTypeName += ",";
                                }

                                Type genericArgType = ParseHelpers.ParseTypeName(typeProvider, language, genericArg);
                                if (genericArgType != null)
                                {
                                    parsedTypeName += "[" + genericArgType.FullName + "]";
                                }
                                else
                                {
                                    parsedTypeName += "[" + genericArg + "]";
                                }
                            }
                            parsedTypeName += "]";

                            returnType = ParseHelpers.ParseTypeName(typeProvider, language, parsedTypeName);
                        }
                    }
                }

                return(returnType);
            }

            return(null);
        }