Programmatically Compile WebSite
Hi all!!
I have come across a situation where I need to compile the website using my code.
This is the code I have used to compile my website:
//Namespace you need to include
using System.Diagnostics;
//Code snippet
public string compileProject() {
System.IO.StreamWriter strWriter;
string runBatch = "\"c:/Program Files/Microsoft Visual Studio 8/SDK/v2.0/Bin/sdkvars.bat\"";
string runASPNet = "aspnet_compiler -p d:/mahindracomposites/mahindracomposites -v /mahindracomposites d:/New";
string sOutput;
Process p = new Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.FileName = "cmd.exe"; //File name to pass to process
p.StartInfo.Arguments = "/c " + runBatch + " && " + runASPNet;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.RedirectStandardInput = true;
p.Start();//This will start executing the process
p.WaitForExit();
string output = p.StandardOutput.ReadToEnd();//After completion we will get
string erroutput = p.StandardError.ReadToEnd();
if (output.Contains("error"))
{
//output contains all error details
sOutput = "Contains Error " + output;
}
else
{
sOutput = "Compile Success!! " + output;
}
return sOutput;
}
Here I have used Process class. Process class provides access to local and remote processes and enables you to start
and stop local system processes.
Process p = new Process();
For compiling Dot Net code we need to initialize environment variables by executing following bat file available with the Dot Net SDK.
string runBatch = "\"c:/Program Files/Microsoft Visual Studio 8/SDK/v2.0/Bin/sdkvars.bat\"";
I am using aspnet_compiler command for compiling asp code.
Command syntax is: aspnet_compiler [-p physicalDir] [-v virtualPath] [targetDir]
string runASPNet = "aspnet_compiler -p d:/mahindracomposites/mahindracomposites -v /mahindracomposites d:/New";
[RedirectStandardOutput ] - This will allow standard output to be redirected to System.Diagnostics.StandardOutput Stream
p.StartInfo.RedirectStandardOutput = true;
[RedirectStandardError ] - This will allow standard error stream to be redirected to System.Diagnostics.StandardError Stream
p.StartInfo.RedirectStandardOutput = true;
Here whatever we get from standard output of Process is the output of our command.
If command executed and web site compiles correctly we get Success or the error description from command.
This is the way I managed to compile my website programmatically.
Please respond if you have any comments.
Coding IS Like Designing Your Own World !!