Wednesday, July 30, 2014

Automated Build CSharp code using CodeDomProvider and .csproj file

Here is the code snippet from the code I used for automated compilation of CSharp code....
 string _projectName = Path.GetFileNameWithoutExtension(projectFilePath);  
 XmlDocument _project = new XmlDocument();  
 _project.Load(projectFilePath);  
 XmlNamespaceManager ns = new XmlNamespaceManager(_project.NameTable);  
 ns.AddNamespace("msbld", "http://schemas.microsoft.com/developer/msbuild/2003");  
 XmlNode _settings = _project.SelectSingleNode("//msbld:Project/msbld:PropertyGroup/msbld:AssemblyName", ns);  
 string _asmName = _settings.InnerText;  
 XmlNodeList _files = _project.SelectNodes("//msbld:Project/msbld:ItemGroup/msbld:Compile", ns);  
 ArrayList _sourceNames = new ArrayList();  
 // Add compilable files  
 foreach (XmlNode _file in _files)  
 {  
   string _codeFilename = _file.Attributes["Include"].Value.ToLower();  
  if ( _codeFilename != "assemblyinfo.cs"      && !_codeFilename.EndsWith("vsa.cs") )       
      {  
                          // Read the source code  
           int _idx = _sourceNames.Add(_file.Attributes["Include"].Value);  
      }  
 }  
 XmlNodeList _reference = _project.SelectNodes("//msbld:Project/msbld:ItemGroup/msbld:Reference", ns);  
  foreach (XmlNode _asmRef in _reference)  
 {  
         // Try to use the AssemblyName attribute if it exists  
         string _refAsmName;  
         if (_asmRef.Attributes["AssemblyName"] != null)  
           _refAsmName = _asmRef.Attributes["AssemblyName"].Value;  
         else if (_asmRef.Attributes["Name"] != null)  
           _refAsmName = _asmRef.Attributes["Name"].Value;  
         else  
         {  
           _refAsmName = _asmRef.Attributes["Include"].Value;  
           if (_refAsmName.IndexOf(",") > 0)  
             _refAsmName = _refAsmName.Substring(0, _refAsmName.IndexOf(","));  
         }  
        cp.ReferencedAssemblies.Add(_refAsmName + ".dll");  
  }  
       cp.GenerateExecutable = false;   // result is a .DLL  
       cp.IncludeDebugInformation = true;  
       String[] _sourcefiles = (String[])_sourceNames.ToArray(typeof(string));  
       CompilerResults cr = provider.CompileAssemblyFromFile(cp, _sourcefiles);  
       if (cr.Errors.Count > 0) //if (_compErrs.Length > 0)  
                {  
                     bool _error = false;  
         foreach (CompilerError _err in cr.Errors)  
                     {                           
                          // Error or warning?  
                          if (!_err.IsWarning)//( _err.ErrorLevel != Microsoft.CSharp.ErrorLevel.Warning )  
                               _error = true;  
                          if(_error)                           
                               swrLog.WriteLine("CompileAndDeploy:CompileComponentAssemblies: Error compiling " + _projectName + ".\nPlease rectify then redeloy.");  
                          else  
                               swrLog.WriteLine("CompileAndDeploy:CompileComponentAssemblies: Warning compiling " + _projectName + ".\nPlease rectify then redeloy.");  
                          swrLog.WriteLine( _err.ErrorText);  
                     }  
                     if (_error)  
                     {  
                          swrLog.WriteLine("Compile errors occurred. Rectify first.");  
                          throw new Exception ("Compile errors occurred. Rectify first." );  
                     }  
                }  
method 2: msbuild

                           //string projectFileName = @"C:\Temp\E4SE\src\SMEC\Epicor.SMEC.IInterfaces.csproj";
                            BuildManager manager = BuildManager.DefaultBuildManager;

                            ProjectInstance projectInstance = new ProjectInstance(path);
                            var result = manager.Build(new BuildParameters()
                            {
                                DetailedSummary = true
                            },
                                new BuildRequestData(projectInstance, new string[] { "Build" }));
                            var buildResult = result.ResultsByTarget["Build"];
                            var buildResultItems = buildResult.Items;
                            mswrLog.WriteLine("Building: " + path + " Result: " + buildResult.ResultCode);