public ValidationPattern(ITaskItem item, TaskLoggingHelper log)
            {
                string idRegex = item.GetMetadata("IdentityRegex");
                if (string.IsNullOrEmpty(idRegex))
                {
                    // Temporarily support reading the regex from the Include/ItemSpec for backwards compatibility
                    // when the IdentityRegex isn't specified. This can be removed once all consumers are using IdentityRegex.
                    idRegex = item.ItemSpec;
                }

                _idPattern = new Regex(idRegex);
                _expectedVersion = item.GetMetadata("ExpectedVersion");
                _expectedPrerelease = item.GetMetadata("ExpectedPrerelease");
                _log = log;

                if (string.IsNullOrWhiteSpace(_expectedVersion))
                {
                    if (string.IsNullOrWhiteSpace(_expectedPrerelease))
                    {
                        _log.LogError(
                            "Can't find ExpectedVersion or ExpectedPrerelease metadata on item {0}",
                            item.ItemSpec);
                    }
                }
                else if (!string.IsNullOrWhiteSpace(_expectedPrerelease))
                {
                    _log.LogError(
                        "Both ExpectedVersion and ExpectedPrerelease metadata found on item {0}, but only one permitted",
                        item.ItemSpec);
                }
            }
Пример #2
0
        public bool Parse(string antBuildPath, string antBuildType, TaskLoggingHelper log, bool outputInQuotes)
        {
            // Ant build directory check
            if (Directory.Exists(antBuildPath) == false)
            {
                log.LogError("Ant Build Path '" + antBuildPath + "' does not exist");
                return false;
            }

            // Check that the build.xml exists
            string buildXml = Path.GetFullPath(antBuildPath + "\\build.xml");
            if (File.Exists(buildXml) == false)
            {
                log.LogError("build.xml '" + buildXml + "' does not exist");
                return false;
            }

            // Check that the AndroidManifest.xml exists
            string manifestXml = Path.GetFullPath(antBuildPath + "\\AndroidManifest.xml");
            if (File.Exists(manifestXml) == false)
            {
                log.LogError("AndroidManifest.xml '" + manifestXml + "' does not exist");
                return false;
            }

            // Parse the xml to grab the finished apk path
            if (ParseBuildXml(buildXml))
            {
                if (antBuildType.ToLower() == "debug")
                {
                    OutputFile = Path.GetFullPath(antBuildPath + "\\" + BUILD_BIN_PATH + "\\" + ApkName + "-debug.apk");
                }
                else
                {
                    OutputFile = Path.GetFullPath(antBuildPath + "\\" + BUILD_BIN_PATH + "\\" + ApkName + "-release.apk");
                }

                if ( outputInQuotes )
                {
                    OutputFile = "\"" + OutputFile + "\"";
                }
            }
            else
            {
                // Parse failed, oh dear.
                log.LogError("Failed parsing '" + buildXml + "'");
                return false;
            }

            if (ParseAndroidManifestXml(manifestXml) == false)
            {
                // Parse failed, oh dear.
                log.LogError("Failed parsing '" + manifestXml + "'");
                return false;
            }

            return true;
        }
Пример #3
0
        public async Task <bool> PushToFeed(IEnumerable <string> items, bool allowOverwrite = false)
        {
            if (IsSanityChecked(items))
            {
                if (CancellationToken.IsCancellationRequested)
                {
                    Log.LogError("Task PushToFeed cancelled");
                    CancellationToken.ThrowIfCancellationRequested();
                }

                await PushItemsToFeedAsync(items, allowOverwrite);
            }

            return(!Log.HasLoggedErrors);
        }
Пример #4
0
        public IEnumerable<string> GetAppBuildOrder(string sourceDirectory, string startAppPath, string uniqueSourceDirectoryPath, TaskLoggingHelper log)
        {
            _log = log;
            _uniqueSourceDirectoryPath = uniqueSourceDirectoryPath;
            var sourceDirectoryPath = sourceDirectory.Trim('\'', '"');
            var appList = GetAppListWithReferences(sourceDirectoryPath);

            var appPath = startAppPath.Trim('\'', '"');
            var startApps = appPath.Split('|').ToList();
            foreach (var app in startApps)
            {
                if (!string.IsNullOrEmpty(app))
                {
                    _log.LogMessage("Application path: {0}", app);
                    var startApp = appList[Path.GetFullPath(app.ToUpper().Replace(sourceDirectoryPath.ToUpper(), _uniqueSourceDirectoryPath)).ToUpper()];
                    if (startApp == null)
                    {
                        log.LogError("Application {0} could not be found.", app);
                    }
                    else
                    {
                        _orderedAppList.Add(Path.GetFullPath(app.ToUpper().Replace(sourceDirectoryPath.ToUpper(), _uniqueSourceDirectoryPath)).ToUpper());
                        LoopReferences(startApp, appList);
                    }
                }
            }

            _orderedAppList.ForEach(a => _log.LogMessage(a));

            return _orderedAppList;
        }
Пример #5
0
        private void Log(ILogMessage message, LogLevel level)
        {
            switch (level)
            {
            case LogLevel.Error:
                _log.LogError(message.Message);
                break;

            case LogLevel.Warning:
                _log.LogWarning(message.Message);
                break;

            case LogLevel.Minimal:
                _log.LogMessage(MessageImportance.Low, message.Message);
                break;

            case LogLevel.Information:
                _log.LogMessage(MessageImportance.Normal, message.Message);
                break;

            case LogLevel.Debug:
            case LogLevel.Verbose:
            default:
                _log.LogMessage(MessageImportance.High, message.Message);
                break;
            }

            return;
        }
Пример #6
0
        public async Task <bool> PushToFeed(IEnumerable <string> items, string relativePath, bool allowOverwrite = false)
        {
            if (feed.IsSanityChecked(items))
            {
                if (CancellationToken.IsCancellationRequested)
                {
                    Log.LogError("Task PushToFeed cancelled");
                    CancellationToken.ThrowIfCancellationRequested();
                }

                using (var clientThrottle = new SemaphoreSlim(this.MaxClients, this.MaxClients))
                {
                    await Task.WhenAll(items.Select(item => PushItemToFeed(item, relativePath, clientThrottle, allowOverwrite)));
                }
            }

            return(!Log.HasLoggedErrors);
        }
Пример #7
0
        void Fault(object sender, ExceptionEventArgs e)
        {
            log.LogError("Confuser", "CR003", "Confuser",
                         0, 0, 0, 0, string.Format(@"***************
ERROR IN CONFUSER!!
Message : {0}
Stack Trace : {1}
***************", e.Exception.Message, e.Exception.StackTrace));
            ReturnValue = false;
        }
            public ValidationPattern(ITaskItem item, TaskLoggingHelper log)
            {
                _idPattern = new Regex(item.ItemSpec);
                _expectedVersion = item.GetMetadata("ExpectedVersion");
                _expectedPrerelease = item.GetMetadata("ExpectedPrerelease");
                _log = log;

                if (string.IsNullOrWhiteSpace(_expectedVersion))
                {
                    if (string.IsNullOrWhiteSpace(_expectedPrerelease))
                    {
                        _log.LogError(
                            "Can't find ExpectedVersion or ExpectedPrerelease metadata on item {0}",
                            item.ItemSpec);
                    }
                }
                else if (!string.IsNullOrWhiteSpace(_expectedPrerelease))
                {
                    _log.LogError(
                        "Both ExpectedVersion and ExpectedPrerelease metadata found on item {0}, but only one permitted",
                        item.ItemSpec);
                }
            }
Пример #9
0
		private static bool HandleIntegerList(dynamic scTask, IList<int> targetCollection, string value, string itemName, TaskLoggingHelper log) {
			if (!string.IsNullOrEmpty(value)) {
				foreach (var s in value.Split(new[] { ';', ',' }).Select(s => s.Trim()).Where(s => s != "")) {
					int w;
					if (!int.TryParse(s, NumberStyles.Integer, CultureInfo.InvariantCulture, out w)) {
						log.LogError("Invalid number " + s + " in " + itemName);
						return false;
					}
					if (!targetCollection.Contains(w))
						targetCollection.Add(w);
				}
			}
			return true;
		}
Пример #10
0
        public bool IsSanityChecked(IEnumerable <string> items)
        {
            Log.LogMessage(MessageImportance.Low, $"START checking sanitized items for feed");
            foreach (var item in items)
            {
                if (items.Any(s => Path.GetExtension(item) != ".nupkg"))
                {
                    Log.LogError($"{item} is not a nupkg");
                    return(false);
                }
            }
            List <string> duplicates = items.GroupBy(x => x)
                                       .Where(group => group.Count() > 1)
                                       .Select(group => group.Key).ToList();

            if (duplicates.Count > 0)
            {
                Log.LogError($"Duplicates found: {duplicates}");
                return(false);
            }
            Log.LogMessage(MessageImportance.Low, $"DONE checking for sanitized items for feed");
            return(true);
        }
Пример #11
0
		public CollectTargets(TaskLoggingHelper log)
		{
			Log = log;
			// Get the parent directory of the running program.  We assume that
			// this is the root of the FieldWorks repository tree.
			var fwrt = BuildUtils.GetAssemblyFolder();
			while (!Directory.Exists(Path.Combine(fwrt, "Build")) || !Directory.Exists(Path.Combine(fwrt, "Src")))
			{
				fwrt = Path.GetDirectoryName(fwrt);
				if (fwrt == null)
				{
					Log.LogError("Error pulling the working folder from the running assembly.");
					break;
				}
			}
			m_fwroot = fwrt;
		}
Пример #12
0
 public static bool InstallPackages(string packagesDirectory, string packagesConfigPath, string nugetExePath, TaskLoggingHelper log)
 {
     var nugetArguments = @"install -o " + packagesDirectory + " -Prerelease -NonInteractive " + packagesConfigPath;
     log.LogMessage("Installing: " + nugetExePath + " " + nugetArguments);
     ProcessStartInfo psi = new ProcessStartInfo();
     psi.UseShellExecute = false;
     psi.FileName = nugetExePath;
     psi.Arguments = nugetArguments;
     psi.CreateNoWindow = true;
     var process = Process.Start(psi);
     if (!process.WaitForExit(20000))
     {
         log.LogError("Packages installation timed out.");
         return false;
     }
     return true;
 }
Пример #13
0
 public static bool CreateJavaSources(TaskLoggingHelper log, IEnumerable<TypeDefinition> javaTypes, string outputPath, bool useSharedRuntime, bool generateOnCreateOverrides, bool hasExportReference)
 {
     bool ok = true;
     foreach (var t in javaTypes) {
         try {
             GenerateJavaSource (log, t, outputPath, useSharedRuntime, generateOnCreateOverrides, hasExportReference);
         } catch (XamarinAndroidException xae) {
             ok = false;
             log.LogError (
                     subcategory:      "",
                     errorCode:        "XA" + xae.Code,
                     helpKeyword:      string.Empty,
                     file:             xae.SourceFile,
                     lineNumber:       xae.SourceLine,
                     columnNumber:     0,
                     endLineNumber:    0,
                     endColumnNumber:  0,
                     message:          xae.MessageWithoutCode,
                     messageArgs:      new object [0]
             );
         }
     }
     return ok;
 }
Пример #14
0
    public bool Initialize(string taskName, IDictionary<string, TaskPropertyInfo> parameterGroup, string taskBody, IBuildEngine taskFactoryLoggingHost)
    {
      TaskLoggingHelper log = new TaskLoggingHelper(taskFactoryLoggingHost, taskName);
        
      // We use the property group for the declaration
      taskProperties = (from c in parameterGroup select c.Value).ToArray();

      // Compile chunk
      try
      {
        log.LogMessage("Compile script.");
        task = lua.CompileChunk(taskBody, taskName, LuaDeskop.StackTraceCompileOptions, 
          new KeyValuePair<string, Type>("engine", typeof(IBuildEngine)), 
          new KeyValuePair<string, Type>("log", typeof(TaskLoggingHelper))
        );
        
        return true;
      }
      catch (LuaParseException e)
      {
        log.LogError("{0} (at line {1},{2})", e.Message, taskName, e.Line);
        return false;
      }
    } // func Initialize
Пример #15
0
        public async Task <bool> CheckIfBlobExistsAsync(string blobPath)
        {
            string url = $"{FeedContainerUrl}/{blobPath}?comp=metadata";

            using (HttpClient client = new HttpClient())
            {
                const int MaxAttempts = 15;
                // add a bit of randomness to the retry delay.
                var rng        = new Random();
                int retryCount = MaxAttempts;

                // Used to make sure TaskCancelledException comes from timeouts.
                CancellationTokenSource cancelTokenSource = new CancellationTokenSource();

                while (true)
                {
                    try
                    {
                        client.DefaultRequestHeaders.Clear();
                        var request = AzureHelper.RequestMessage("GET", url, AccountName, AccountKey).Invoke();
                        using (HttpResponseMessage response = await client.SendAsync(request, cancelTokenSource.Token))
                        {
                            if (response.IsSuccessStatusCode)
                            {
                                Log.LogMessage(
                                    MessageImportance.Low,
                                    $"Blob {blobPath} exists for {AccountName}: Status Code:{response.StatusCode} Status Desc: {await response.Content.ReadAsStringAsync()}");
                            }
                            else
                            {
                                Log.LogMessage(
                                    MessageImportance.Low,
                                    $"Blob {blobPath} does not exist for {AccountName}: Status Code:{response.StatusCode} Status Desc: {await response.Content.ReadAsStringAsync()}");
                            }
                            return(response.IsSuccessStatusCode);
                        }
                    }
                    catch (HttpRequestException toLog)
                    {
                        if (retryCount <= 0)
                        {
                            Log.LogError($"Unable to check for existence of blob {blobPath} in {AccountName} after {MaxAttempts} retries.");
                            throw;
                        }
                        else
                        {
                            Log.LogWarning("Exception thrown while trying to detect if blob already exists in feed:");
                            Log.LogWarningFromException(toLog, true);
                        }
                    }
                    catch (TaskCanceledException possibleTimeoutToLog)
                    {
                        // Detect timeout.
                        if (possibleTimeoutToLog.CancellationToken != cancelTokenSource.Token)
                        {
                            if (retryCount <= 0)
                            {
                                Log.LogError($"Unable to check for existence of blob {blobPath} in {AccountName} after {MaxAttempts} retries.");
                                throw;
                            }
                            else
                            {
                                Log.LogWarning("Exception thrown while trying to detect if blob already exists in feed:");
                                Log.LogWarningFromException(possibleTimeoutToLog, true);
                            }
                        }
                        else
                        {
                            throw;
                        }
                    }
                    --retryCount;
                    Log.LogWarning($"Failed to check for existence of blob {blobPath}. {retryCount} attempts remaining");
                    int delay = (MaxAttempts - retryCount) * rng.Next(1, 7);
                    await Task.Delay(delay * 1000);
                }
            }
        }
Пример #16
0
        public static bool Bind(TaskLoggingHelper log, XmlReader modelReader, XmlReader viewModelReader, XmlWriter viewWriter, Action<object, XsltMessageEncounteredEventArgs> messageAction = null)
        {
            XmlDocument viewModelDocument = new XmlDocument();
            try
            {
                viewModelDocument.Load(viewModelReader);
            }
            catch (Exception x)
            {
                log.LogError("View Model: {0}", x.Message);
                return false;
            }

            XmlDocument modelDocument = new XmlDocument();

            try
            {
                modelDocument.Load(modelReader);
            }
            catch (Exception x)
            {
                log.LogError("Model: {0}", x.Message);
                return false;
            }

            using (StringReader dummyReader = new StringReader("<dummy/>"))
            {
                XslTransforms.BindTransform.Apply(
                    XmlReader.Create(dummyReader),
                    viewWriter,
                    messageAction: messageAction,
                    parameters: new[] {
                    new XslTransforms.Parameter("ViewModel", "", viewModelDocument),
                    new XslTransforms.Parameter("Model", "", modelDocument)});
            }
            return true;
        }
Пример #17
0
        /// <summary>
        /// Executes a tool, logs standard error and a nonzero exit code as errors, returns the output and optionally logs that
        /// as well.
        /// </summary>
        /// <param name="log">used for logging</param>
        /// <param name="executable">the name of the executable</param>
        /// <param name="args">the command line arguments</param>
        /// <param name="logOutput">should we log the output in real time</param>
        /// <returns>the output of the tool</returns>
        public static string ExecuteWithLogging(TaskLoggingHelper log, string executable, string args, bool logOutput)
        {
            if (log == null)
            {
                throw new ArgumentNullException("log");
            }

            log.LogMessage(MessageImportance.Low, "Executing tool: {0} {1}", executable, args);

            var exec = new ShellWrapper(executable, args);

            // stderr is logged as errors
            exec.ErrorDataReceived += (sender, e) =>
            {
                if (e.Data != null)
                {
                    log.LogError(e.Data);
                }
            };

            // stdout is logged normally if requested
            if (logOutput)
            {
                exec.OutputDataReceived += (sender, e) =>
                {
                    if (e.Data != null)
                    {
                        log.LogMessage(MessageImportance.Normal, e.Data);
                    }
                };
            }

            // execute the process
            exec.Execute();

            // check the exit code
            if (exec.ExitCode != 0)
            {
                log.LogError("The tool {0} exited with error code {1}", executable, exec.ExitCode);
            }

            return exec.StandardOutput;
        }
Пример #18
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Dynamically invokes <paramref name="methodName"/> in dll <paramref name="fileName"/>.
		/// </summary>
		/// <param name="log">Log helper</param>
		/// <param name="fileName">Name of the dll.</param>
		/// <param name="delegateSignatureType">Signature of the method.</param>
		/// <param name="methodName">Name of the method</param>
		/// <param name="args">Arguments to pass to <paramref name="methodName"/>.</param>
		/// ------------------------------------------------------------------------------------
		private static void ApiInvoke(TaskLoggingHelper log, string fileName,
			Type delegateSignatureType, string methodName, params object[] args)
		{
			if (!File.Exists(fileName))
				return;
			fileName = Path.GetFullPath(fileName);
			IntPtr hModule = LoadLibrary(fileName);
			if (hModule == IntPtr.Zero)
			{
				var errorCode = Marshal.GetLastWin32Error();
				log.LogError("Failed to load library {0} for {1} with error code {2}", fileName, methodName,
					errorCode);
				return;
			}

			try
			{
				IntPtr method = GetProcAddress(hModule, methodName);
				if (method == IntPtr.Zero)
					return;

				Marshal.GetDelegateForFunctionPointer(method, delegateSignatureType).DynamicInvoke(args);
			}
			catch (Exception e)
			{
				log.LogError("RegHelper.ApiInvoke failed getting function pointer for {0}: {1}",
					methodName, e);
			}
			finally
			{
				FreeLibrary(hModule);
			}
		}
Пример #19
0
    private bool ValidNonNull(string name, object value, TaskLoggingHelper log)
    {
      Contract.Requires(name != null);
      Contract.Ensures(!Contract.Result<bool>() || (value != null));
      Contract.Ensures(Contract.Result<bool>() || (value == null));

      if (value == null)
      {
        if (log != null)
        {
          log.LogError("Parameter '{0}' must be non-empty", name);
        }
        return false;
      }
      return true;
    }
Пример #20
0
		private static CompilerOptions GetOptions(dynamic taskOptions, TaskLoggingHelper log) {
			var result = new CompilerOptions();

			result.KeyContainer          =  taskOptions.KeyContainer;
			result.KeyFile               =  taskOptions.KeyFile;
			result.MinimizeScript        = !taskOptions.EmitDebugInformation;
			result.DocumentationFile     =  taskOptions.DocumentationFile;
			result.OutputAssemblyPath    =  taskOptions.OutputAssembly;
			result.OutputScriptPath      =  taskOptions.OutputScript;
			result.TreatWarningsAsErrors =  taskOptions.TreatWarningsAsErrors;
			result.WarningLevel          =  taskOptions.WarningLevel;
			result.AlreadyCompiled       =  taskOptions.AlreadyCompiled;

			result.EntryPointClass = taskOptions.MainEntryPoint;
			if (!string.IsNullOrEmpty(taskOptions.TargetType)) {
				switch ((string)taskOptions.TargetType.ToLowerInvariant()) {
					case "exe":
					case "winexe":
						result.HasEntryPoint = true;
						break;
					case "library":
					case "module":
						result.HasEntryPoint = false;
						break;
					default:
						log.LogError("Invalid target type (must be exe, winexe, library or module).");
						return null;
				}
			}
			else {
				result.HasEntryPoint = false;
			}

			if (taskOptions.WarningLevel < 0 || taskOptions.WarningLevel > 4) {
				log.LogError("Warning level must be between 0 and 4.");
				return null;
			}

			if (taskOptions.AdditionalLibPaths != null)
				result.AdditionalLibPaths.AddRange(taskOptions.AdditionalLibPaths);

			if (taskOptions.DefineConstants != null)
				result.DefineConstants.AddRange(((string)taskOptions.DefineConstants).Split(';').Select(s => s.Trim()).Where(s => s != ""));

			if (!HandleIntegerList(taskOptions, result.DisabledWarnings, taskOptions.DisabledWarnings, "DisabledWarnings", log))
				return null;
			if (!HandleIntegerList(taskOptions, result.WarningsAsErrors, taskOptions.WarningsAsErrors, "WarningsAsErrors", log))
				return null;
			if (!HandleIntegerList(taskOptions, result.WarningsNotAsErrors, taskOptions.WarningsNotAsErrors, "WarningsNotAsErrors", log))
				return null;

			if (taskOptions.References != null) {
				foreach (ITaskItem r in taskOptions.References) {
					string alias = r.GetMetadata("Aliases");
					result.References.Add(new Reference(r.ItemSpec, !string.IsNullOrWhiteSpace(alias) ? alias : null));
				}
			}

			if (taskOptions.Sources != null) {
				foreach (ITaskItem s in taskOptions.Sources) {
					result.SourceFiles.Add(s.ItemSpec);
				}
			}

			if (taskOptions.Resources != null) {
				foreach (ITaskItem r in taskOptions.Resources) {
					string name = r.GetMetadata("LogicalName");
					string access = r.GetMetadata("Access");
					result.EmbeddedResources.Add(new EmbeddedResource(r.ItemSpec, !string.IsNullOrWhiteSpace(name) ? name : Path.GetFileName(r.ItemSpec), !string.Equals(access, "private", StringComparison.OrdinalIgnoreCase)));
				}
			}

			return result;
		}
Пример #21
0
        /// <summary>
        /// Append each of the define constants to the command line.
        /// </summary>
        /// <param name="commandLine">Command line builder.</param>
        internal static void AppendExtensions(CommandLineBuilder commandLine, ITaskItem[] extensions, TaskLoggingHelper log)
        {
            if (extensions == null)
            {
                // No items
                return;
            }

            for (int i = 0; i < extensions.Length; i++)
            {
                string className = extensions[i].GetMetadata("Class");
                if (String.IsNullOrEmpty(className))
                {
                    log.LogError(String.Format("Missing the required property 'Class' for the extension {0}", extensions[i].ItemSpec));
                }

                commandLine.AppendSwitchUnquotedIfNotNull("-ext ", String.Concat(className, ",", extensions[i].ItemSpec));
            }
        }
 /// <summary>
 /// 
 /// </summary>
 /// <param name="fileName">The file name of the dependent (usually a .resx)</param>
 /// <param name="binaryStream">File contents binary stream, may be null</param>
 /// <param name="log">Task's TaskLoggingHelper, for logging warnings or errors</param>
 /// <returns></returns>
 private static ExtractedClassName GetFirstClassNameFullyQualified(string fileName, Stream binaryStream,TaskLoggingHelper log)
 {
     Match m = null;
     string currentNamespace = "";
     ExtractedClassName name = new ExtractedClassName();
     int conditionalDepth = 0;
     StreamReader reader = new StreamReader(binaryStream, true); // let the reader determine the encoding
     var namespaces = new Stack<string>();
     while (! reader.EndOfStream)
     {
         var line = reader.ReadLine();
         // Does the line contain "CLASS"
         m = classRx.Match(line);
         if (m.Success)
         {
             name.Name = currentNamespace + m.Groups[1].Value;
             name.IsInsideConditionalBlock = conditionalDepth > 0;
             return name;
         }
         // Does the line contain "BEGIN NAMESPACE"
         m = namespaceBeginRx.Match(line);
         if (m.Success)
         {
             namespaces.Push(currentNamespace);
             currentNamespace = currentNamespace + (m.Groups[1].Value + ".");
         }
         // Does the line contain "END NAMESPACE"
         else if (namespaceEndRx.Match(line).Success)
         {
             if (namespaces.Count > 0)
             {
                 currentNamespace = namespaces.Pop();
             }
             else
             {
                 object[] messageArgs = new object[] { fileName };
                 log.LogError("CreateXSharpManifestResourceName: found 'END NAMESPACE' with no matching 'BEGIN NAMESPACE' in '{0}'", messageArgs);
             }
         }
         // Does the line contain "#IFDEF"
         else if (ifdefRx.Match(line).Success)
         {
             conditionalDepth++;
         }
         // Does the line contain "#ENDIF"
         else if (endifRx.Match(line).Success)
         {
             conditionalDepth--;
         }
     }
     return name;
 }
Пример #23
0
		public static bool GenerateFile (CodeDomProvider provider, string app_name,
		                                       string xaml_file, string xaml_path_in_project, string out_file, TaskLoggingHelper log)
		{
			XmlDocument xmldoc = new XmlDocument ();
			xmldoc.Load (xaml_file);

			XmlNamespaceManager nsmgr = new XmlNamespaceManager (xmldoc.NameTable);
			nsmgr.AddNamespace("x", "http://schemas.microsoft.com/winfx/2006/xaml");

			XmlNode root = xmldoc.SelectSingleNode ("/*", nsmgr);
			if (root == null) {
				log.LogError ("{0}: No root node found.", xaml_file);
				return false;
			}

			XmlAttribute root_class = root.Attributes ["x:Class"];
			if (root_class == null) {
				File.WriteAllText (out_file, "");
				return true;
			}

			bool is_application = root.LocalName == "Application";
			string root_ns;
			string root_type;
			string root_asm;

			ParseXmlns (root_class.Value, out root_type, out root_ns, out root_asm);

			Hashtable names_and_types = GetNamesAndTypes (root, nsmgr);
//			Hashtable keys_and_types = GetKeysAndTypes (root, nsmgr);

			CodeCompileUnit ccu = new CodeCompileUnit ();
			CodeNamespace decl_ns = new CodeNamespace (root_ns);
			ccu.Namespaces.Add (decl_ns);

			decl_ns.Imports.Add (new CodeNamespaceImport ("System"));
			decl_ns.Imports.Add (new CodeNamespaceImport ("System.Windows"));
			decl_ns.Imports.Add (new CodeNamespaceImport ("System.Windows.Controls"));
			decl_ns.Imports.Add (new CodeNamespaceImport ("System.Windows.Documents"));
			decl_ns.Imports.Add (new CodeNamespaceImport ("System.Windows.Input"));
			decl_ns.Imports.Add (new CodeNamespaceImport ("System.Windows.Media"));
			decl_ns.Imports.Add (new CodeNamespaceImport ("System.Windows.Media.Animation"));
			decl_ns.Imports.Add (new CodeNamespaceImport ("System.Windows.Shapes"));
			decl_ns.Imports.Add (new CodeNamespaceImport ("System.Windows.Controls.Primitives"));

			CodeTypeDeclaration decl_type = new CodeTypeDeclaration (root_type);
			decl_type.IsPartial = true;

			decl_ns.Types.Add (decl_type);

			CodeMemberMethod initcomp = new CodeMemberMethod ();
			initcomp.Name = "InitializeComponent";
			decl_type.Members.Add (initcomp);

			if (sl2) {
				CodeMemberField field = new CodeMemberField ();
				field.Name = "_contentLoaded";
				field.Type = new CodeTypeReference (typeof (bool));

				decl_type.Members.Add (field);

				CodeConditionStatement is_content_loaded = new CodeConditionStatement (new CodeVariableReferenceExpression ("_contentLoaded"),
						new CodeStatement [] { new CodeMethodReturnStatement () });
				initcomp.Statements.Add (is_content_loaded);

				CodeAssignStatement set_content_loaded = new CodeAssignStatement (new CodeVariableReferenceExpression ("_contentLoaded"),
						new CodePrimitiveExpression (true));

				initcomp.Statements.Add (set_content_loaded);

				string component_path = String.Format ("/{0};component/{1}", app_name, xaml_path_in_project);
				CodeMethodInvokeExpression load_component = new CodeMethodInvokeExpression (
					new CodeTypeReferenceExpression ("System.Windows.Application"), "LoadComponent",
					new CodeExpression [] { new CodeThisReferenceExpression (),
								new CodeObjectCreateExpression (new CodeTypeReference ("System.Uri"), new CodeExpression [] {
									new CodePrimitiveExpression (component_path),
									new CodeFieldReferenceExpression (new CodeTypeReferenceExpression ("System.UriKind"), "Relative") })
					});
				initcomp.Statements.Add (load_component);
			}

			if (!is_application) {
				foreach (DictionaryEntry entry  in names_and_types) {
					string name = (string) entry.Key;
					CodeTypeReference type = (CodeTypeReference) entry.Value;

					CodeMemberField field = new CodeMemberField ();

					if (sl2)
						field.Attributes = MemberAttributes.Assembly;

					field.Name = name;
					field.Type = type;

					decl_type.Members.Add (field);

					CodeMethodInvokeExpression find_invoke = new CodeMethodInvokeExpression (
						new CodeThisReferenceExpression(), "FindName",
						new CodeExpression[] { new CodePrimitiveExpression (name) } );

					CodeCastExpression cast = new CodeCastExpression (type, find_invoke);

					CodeAssignStatement assign = new CodeAssignStatement (
						new CodeVariableReferenceExpression (name), cast);

					initcomp.Statements.Add (assign);
				}
			}


			using (StreamWriter writer = new StreamWriter (out_file)) {
				provider.GenerateCodeFromCompileUnit (ccu, writer, new CodeGeneratorOptions ());
			}

			return true;
		}