Esempio n. 1
0
            private static string CreateProject(string scriptFile, string tempDir, ProcessSourceFile fileHandler, bool copyLocalAsm)
            {
                string srcProjDir = @"Lib\Debug\VS10.0"; //relative to CSSCRIPT_DIR
                string scHomeDir = VS100IDE.GetEnvironmentVariable("CSSCRIPT_DIR");
                string scriptShortName = Path.GetFileName(scriptFile);
                string projFile = Path.Combine(tempDir, "DebugScript.csproj");
                string solutionFile = Path.Combine(tempDir, "DebugScript.sln");

                //copy project template
                if (!Directory.Exists(tempDir))
                    Directory.CreateDirectory(tempDir);

                foreach (string file in Directory.GetFiles(Path.Combine(scHomeDir, srcProjDir)))
                {
                    if (Path.GetExtension(file) != ".resx")
                    {
                        if (string.Compare(Path.GetFileName(file), "AssemblyInfo.cs", true) == 0)
                        {
                            using (StreamReader sr = new StreamReader(file))
                            using (StreamWriter sw = new StreamWriter(Path.Combine(tempDir, Path.GetFileName(file))))
                            {
                                string code = sr.ReadToEnd().Replace("ScriptDebugger", Path.GetFileNameWithoutExtension(scriptFile));
                                sw.Write(code);
                            }
                        }
                        else
                        {
                            File.Copy(file, Path.Combine(tempDir, Path.GetFileName(file)), true);
                        }
                    }
                }

                //update project template with script specific data
                VS100IDE ide = new VS100IDE();

                ScriptParser parser = new ScriptParser(scriptFile, Script.SearchDirs, VS100IDE.isolating);
                AssemblyResolver asmResolver = new AssemblyResolver();

                foreach (string dir in parser.SearchDirs)
                    AddSearchDir(dir);

                string resxSrcFile = Path.Combine(Path.Combine(scHomeDir, srcProjDir), "Form1.resx");
                bool XAML = false;
                bool WWF = false;

                ArrayList importerdScripts = new ArrayList();
                ArrayList precompilibleScripts = new ArrayList();
                importerdScripts.AddRange(parser.SaveImportedScripts());

                string srcFile = fileHandler(scriptFile, tempDir);
                XAML = srcFile.ToLower().EndsWith(".xaml");

                string associatedXml = FindAssociatedXml(srcFile, (string[])importerdScripts.ToArray(typeof(string)));

                string precompiler = "";
                if (UsesPreprocessor(srcFile, out precompiler))
                    precompilibleScripts.Add(new string[] { srcFile, precompiler });

                if (VS100IDE.IsResxRequired(srcFile) && associatedXml == "")
                    ide.InsertFile(srcFile, projFile, resxSrcFile, "");
                else
                {
                    if (associatedXml != "")
                        ide.InsertXamlCSFile(srcFile, projFile, associatedXml);
                    else
                        ide.InsertFile(srcFile, projFile, "", "");
                }

                foreach (string file in importerdScripts)
                {
                    if (UsesPreprocessor(file, out precompiler))
                        precompilibleScripts.Add(new string[] { file, precompiler });

                    srcFile = fileHandler(file, tempDir);
                    associatedXml = FindAssociatedXml(srcFile, (string[])importerdScripts.ToArray(typeof(string)));
                    XAML = srcFile.ToLower().EndsWith(".xaml");
                    if (!Path.GetFileName(srcFile).StartsWith("i_") && VS100IDE.IsResxRequired(srcFile) && associatedXml == "")
                    {
                        ide.InsertFile(srcFile, projFile, resxSrcFile, "");
                    }
                    else
                    {
                        if (associatedXml != "")
                            ide.InsertXamlCSFile(srcFile, projFile, associatedXml);
                        else
                            ide.InsertFile(srcFile, projFile, "", "");
                    }
                }

                if (XAML)
                    ide.InsertImport(@"$(MSBuildBinPath)\Microsoft.WinFX.targets", projFile);

                ArrayList referencedNamespaces = new ArrayList(parser.ReferencedNamespaces);

                string[] defaultAsms = (CSScript.GlobalSettings.DefaultRefAssemblies ?? "")
                                        .Replace(" ", "")
                                        .Split(";,".ToCharArray());
                referencedNamespaces.AddRange(defaultAsms);

                if (precompilibleScripts.Count > 0)
                {
                    referencedNamespaces.Add("CSScriptLibrary");

                    Hashtable ht = new Hashtable();
                    foreach (string[] info in precompilibleScripts)
                    {
                        if (!ht.ContainsKey(info[1])) //to avoid duplication
                        {
                            ht[info[1]] = true;
                            string t = Path.GetDirectoryName(scriptFile);

                            ide.InsertFile(Path.Combine(Path.GetDirectoryName(scriptFile), info[1]), projFile, "", "");
                        }
                    }

                    string commands = "";
                    foreach (string[] info in precompilibleScripts)
                        commands += "cscs.exe \"" + Path.Combine(Path.GetDirectoryName(scriptFile), info[1]) + "\" \"" + info[0] + "\" \"/primary:" + scriptFile + "\"" + "\r\n";

                    string firstPrecompiler = (precompilibleScripts[0] as string[])[1];
                    ide.InsertFile(Path.Combine(scHomeDir, "Lib\\precompile.part.cs"), projFile, "", firstPrecompiler);
                    ide.InsertPreBuildEvent(commands, projFile);
                    //<PropertyGroup>
                    //<PreBuildEvent>cscs.exe "C:\cs-script\Dev\Macros C#\precompile.cs" "C:\cs-script\Dev\Macros C#\code.cs"</PreBuildEvent>
                    //</PropertyGroup>
                }

                foreach (string name in referencedNamespaces)
                {
                    bool ignore = false;
                    foreach (string ignoreName in parser.IgnoreNamespaces)
                        if (ignore = (name == ignoreName))
                            break;

                    if (ignore)
                        continue;

                    string[] asmFiles = AssemblyResolver.FindAssembly(name, SearchDirs);
                    foreach (string file in asmFiles)
                    {
                        if (!WWF && file.ToLower().IndexOf("system.workflow.runtime") != -1)
                            WWF = true;

                        if (!copyLocalAsm || file.IndexOf("assembly\\GAC") != -1 || file.IndexOf("assembly/GAC") != -1)
                            ide.InsertReference(file, projFile);
                        else
                        {
                            string asmCopy = Path.Combine(tempDir, Path.GetFileName(file));
                            File.Copy(file, asmCopy, true);

                            ide.InsertReference(Path.GetFileName(asmCopy), projFile);
                        }
                    }
                }

                foreach (string asm in parser.ReferencedAssemblies) //some assemblies were referenced from code
                {
                    foreach (string file in AssemblyResolver.FindAssembly(asm, SearchDirs))
                    {
                        if (!WWF && file.ToLower().IndexOf("system.workflow.runtime") != -1)
                            WWF = true;

                        if (!copyLocalAsm || file.IndexOf("assembly\\GAC") != -1 || file.IndexOf("assembly\\GAC") != -1)
                            ide.InsertReference(file, projFile);
                        else
                        {
                            string asmCopy = Path.Combine(tempDir, Path.GetFileName(file));
                            if (Path.IsPathRooted(file) || File.Exists(file))
                                File.Copy(file, asmCopy, true);
                            ide.InsertReference(Path.GetFileName(asmCopy), projFile);
                        }
                    }
                }

                //adjust project settings
                if (WWF)
                {
                    ide.InsertProjectTypeGuids("{14822709-B5A1-4724-98CA-57A101D1B079};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}", projFile);
                    ide.InsertImport(@"$(MSBuildExtensionsPath)\Microsoft\Windows Workflow Foundation\v3.0\Workflow.Targets", projFile);

                    foreach (string file in importerdScripts)
                        if (file.ToLower().IndexOf("designer.cs") != -1)
                        {
                            string className = Path.GetFileNameWithoutExtension(file.ToLower()).Replace(".designer", "");
                            string template = Path.Combine(tempDir, "wwf.layout");
                            string layoutFile = file.Replace("designer.cs", "layout");

                            if (copyLocalAsm) //isolating
                                layoutFile = Path.Combine(Path.GetDirectoryName(projFile), Path.GetFileName(layoutFile));

                            File.Copy(template, layoutFile, true);
                            ReplaceInFile(layoutFile, "WFInitialState", className + "InitialState");

                            ide.InsertResource(layoutFile, projFile);
                        }
                }

                CSharpParser fileParser = new CSharpParser(scriptFile, true, new string[] { "//css_dbg", "//css_args", "//css_co" });

                //foreach (string statement in fileParser.CustomDirectives["//css_dbg"] as List<string>)//should be  reenabled when CS-Script is compiled for  .NET 2.0
                foreach (string statement in fileParser.CustomDirectives["//css_dbg"] as IEnumerable)
                    foreach (string directive in statement.Split(','))
                    {
                        string d = directive.Trim();
                        if (d.StartsWith("/t:"))
                            ide.SetOutputType(d.Substring("/t:".Length), projFile);
                        else if (d.StartsWith("/platform:"))
                            ide.SetPlatformType(d.Substring("/platform:".Length), projFile, solutionFile);
                        else if (d.Trim().StartsWith("/args:"))
                            ide.SetArguments(d.Substring("/args:".Length), projFile + ".user");
                    }

                //foreach (string statement in fileParser.CustomDirectives["//css_args"] as List<string>) //should be  reenabled when CS-Script is compiled for  .NET 2.0
                foreach (string statement in fileParser.CustomDirectives["//css_args"] as IEnumerable)
                    foreach (string directive in statement.Split(','))
                    {
                        string d = directive.Trim();
                        if (d.StartsWith("/co"))
                        {
                            string[] compilerOptions = d.Substring(4).Split(',');
                            foreach (string option in compilerOptions)
                            {
                                string o = option.Trim();
                                if (o.StartsWith("/unsafe"))
                                    ide.SetAllowUnsafe(projFile);
                                else if (o.StartsWith("/platform:"))
                                    ide.SetPlatformType(o.Substring("/platform:".Length), projFile, solutionFile);
                            }
                        }
                    }

                foreach (string statement in fileParser.CustomDirectives["//css_co"] as IEnumerable)
                    foreach (string directive in statement.Split(','))
                    {
                        string d = directive.Trim();
                        if (d.StartsWith("/platform:"))
                            ide.SetPlatformType(d.Substring("/platform:".Length), projFile, solutionFile);
                    }

                Settings settings = GetSystemWideSettings();
                if (settings != null)
                    ide.SetTargetFramework(settings.TargetFramework, projFile);

                ide.SetWorkingDir(Path.GetDirectoryName(scriptFile), projFile + ".user");

                if (!VS100IDE.isolating)
                    ide.RemoveFile("AssemblyInfo.cs", projFile);

                string appConfigFile = "";

                if (File.Exists(Path.ChangeExtension(scriptFile, ".cs.config")))
                    appConfigFile = Path.ChangeExtension(scriptFile, ".cs.config");
                else if (File.Exists(Path.ChangeExtension(scriptFile, ".exe.config")))
                    appConfigFile = Path.ChangeExtension(scriptFile, ".exe.config");

                if (appConfigFile != "")
                    ide.InsertAppConfig(appConfigFile, projFile);

                ///////////////////////////////////
                //rename project files
                string newSolutionFile = Path.Combine(tempDir, Path.GetFileNameWithoutExtension(scriptFile) + " (script).sln");
                string newProjectFile = Path.Combine(tempDir, Path.GetFileNameWithoutExtension(newSolutionFile) + ".csproj");

                FileMove(solutionFile, newSolutionFile);
                FileMove(projFile, newProjectFile);
                FileMove(projFile + ".user", newProjectFile + ".user");

                ReplaceInFile(newSolutionFile, Path.GetFileNameWithoutExtension(projFile), Path.GetFileNameWithoutExtension(newProjectFile));
                ReplaceInFile(newProjectFile, "DebugScript", Path.GetFileNameWithoutExtension(scriptFile));

                //remove xmlns=""
                VSProjectDoc.FixFile(newProjectFile);
                VSProjectDoc.FixFile(newProjectFile + ".user");

                ///////////////////////
                return newSolutionFile;
            }
Esempio n. 2
0
        public static void Main(string[] args)
        {
            SetEnvironmentVariable("CSScriptDebugging", "VS10.0");
            if (args.Length == 0 || (args.Length == 1 && (args[0] == "?" || args[0] == "/?" || args[0] == "-?" || args[0].ToLower() == "help")))
            {
                Console.WriteLine(usage);
            }
            else if (args[0].Trim().ToLower() == "/prj")
            {
                scriptFile = ResolveScriptFile(args[1]);
                try
                {
                    VS100IDE.IsolateProject(scriptFile, Path.Combine(Path.GetDirectoryName(scriptFile), Path.GetFileNameWithoutExtension(scriptFile)));
                }
                catch (Exception e)
                {
                    MessageBox.Show("Specified file could not be linked to the temp project:\n" + e.Message);
                }
            }
            else if (args[0].Trim().ToLower() == "/r")
            {
                string projFile = args[1];
                try
                {
                    VS100IDE.RefreshProject(projFile);
                }
                catch (Exception e)
                {
                    MessageBox.Show("Specified file could not be linked to the temp project:\n" + e.Message);
                }
            }
            else if (args[0].Trim().ToLower() == "/print")
            {
                try
                {
                    // Note "/print" is to be only invoked from VSX, which  can only be hosted by full VS. Thus "/print" and "/e" cannot come together.
                    scriptFile = args[1];

                    ScriptParser parser = new ScriptParser(scriptFile, Script.SearchDirs, false);

                    foreach (string dir in parser.SearchDirs)
                        AddSearchDir(dir);

                    Console.WriteLine("Src:{0}", scriptFile);

                    foreach (string file in parser.SaveImportedScripts())
                        Console.WriteLine("Src:{0}", file);

                    string[] defaultAsms = (CSScript.GlobalSettings.DefaultRefAssemblies ?? "")
                                            .Replace(" ", "")
                                            .Split(";,".ToCharArray());

                    List<string> referencedAssemblies = new List<string>();

                    List<string> referencedNamespaces = new List<string>();
                    referencedNamespaces.AddRange(parser.ReferencedNamespaces);
                    referencedNamespaces.AddRange(defaultAsms);

                    foreach (string name in referencedNamespaces)
                        if (!parser.IgnoreNamespaces.Contains(name))
                            referencedAssemblies.AddRange(AssemblyResolver.FindAssembly(name, SearchDirs));

                    foreach (string asm in parser.ReferencedAssemblies) //some assemblies were referenced from code
                        referencedAssemblies.AddRange(AssemblyResolver.FindAssembly(asm, SearchDirs));

                    foreach (string file in referencedAssemblies.Distinct())
                        Console.WriteLine("Asm:{0}", file);
                }
                catch (Exception e)
                {
                    MessageBox.Show("Specified file could not be linked to the temp project:\n" + e.Message);
                }
            }
            else
            {
                try
                {
                    bool doNotOpenIDE = false;

                    IDEEditions edition = IDEEditions.normal;
                    scriptFile = args[0];

                    if (args[0].Trim().ToLower() == "/e")
                    {
                        edition = IDEEditions.express;
                        scriptFile = args[1];
                    }

                    // Note "/noide" is to be only invoked from VSX, which  can only be hosted by full VS. Thus "/noide" and "/e" cannot come together.
                    if (args[0].Trim().ToLower() == "/noide")
                    {
                        doNotOpenIDE = true;
                        scriptFile = args[1];
                    }

                    scriptFile = ResolveScriptFile(scriptFile);
                    RunPreScripts(scriptFile);
                    string tempDir = Path.Combine(GetTempCSSDir(), Environment.TickCount.ToString());
                    string solutionFile = VS100IDE.CreateProject(scriptFile, tempDir);
                    string projFile = Path.ChangeExtension(solutionFile, ".csproj");

                    //"lock" the directory to indicate that it is in use
                    File.WriteAllText(Path.Combine(tempDir, "host.pid"), Process.GetCurrentProcess().Id.ToString());

                    //open project
                    Environment.CurrentDirectory = Path.GetDirectoryName(scriptFile);

                    Process myProcess = new Process();
                    myProcess.StartInfo.FileName = VS100IDE.GetIDEFile(edition);

                    if (myProcess.StartInfo.FileName == "<not defined>")
                    {
                        if (edition == IDEEditions.express)
                            myProcess.StartInfo.FileName = VS100IDE.GetIDEFile(IDEEditions.normal);
                        else
                            myProcess.StartInfo.FileName = VS100IDE.GetIDEFile(IDEEditions.express);
                    }

                    AddToRecentScripts(scriptFile);

                    if (!doNotOpenIDE)
                    {
                        myProcess.StartInfo.Arguments = "\"" + solutionFile + "\" " + " /command Edit.OpenFile " + "\"" + scriptFile + "\"";
                        //MessageBox.Show("About to start the VS2010");
                        myProcess.Start();
                        myProcess.WaitForExit();
                    }
                    else
                    {
                        Console.WriteLine("Solution File: " + solutionFile);
                    }

                    if (doNotOpenIDE)
                    {
                        //calling party is responsible for cleanup
                    }
                    else
                    {
                        //do clean up
                        foreach (string file in VS100IDE.GetImportedScripts(projFile))
                        {
                            DeleteSatelliteFiles(file);
                            if (Path.GetFileName(file).StartsWith("i_")) //imported modified files have name "i_file_XXXXXX.cs>"
                            {
                                DeleteSatelliteFiles(file);
                                File.SetAttributes(file, FileAttributes.Normal);
                                File.Delete(file);
                            }
                        }

                        try
                        {
                            Directory.Delete(tempDir, true);
                        }
                        catch { }

                        RunPostScripts(scriptFile);
                    }
                }
                catch (Exception e)
                {
                    MessageBox.Show("Specified file could not be linked to the temp project:\n" + e);
                }
            }
        }
		static public void Main(string[] args)
		{
			if (args.Length == 0 || (args.Length == 1 && (args[0] == "?" || args[0] == "/?" || args[0] == "-?" || args[0].ToLower() == "help")))
			{
				Console.WriteLine(usage);
			}
			else if (args[0].Trim().ToLower() == "/i")
			{
				SharpDevelopIDE.InstallShellExtension();
			}
			else if (args[0].Trim().ToLower() == "/u")
			{
				SharpDevelopIDE.UninstallShellExtension();
			}
			else
			{
				try
				{
					FileInfo info = new FileInfo(args[0]);
					scriptFile = info.FullName;
					string srcProjDir = @"Lib\Debug\#D1.1"; //relative to CSSCRIPT_DIR
					string scHomeDir = SharpDevelopIDE.GetEnvironmentVariable("CSSCRIPT_DIR");
					string tempDir = Path.Combine(Path.Combine(Path.GetTempPath(), "CSSCRIPT"), Environment.TickCount.ToString());

					string projFile = Path.Combine(tempDir, "DebugScript.prjx");
					string solutionFile = Path.Combine(tempDir, "DebugScript.cmbx");


					//copy project template
					Directory.CreateDirectory(tempDir);

					foreach (string file in Directory.GetFiles(Path.Combine(scHomeDir, srcProjDir)))
						File.Copy(file, Path.Combine(tempDir, Path.GetFileName(file)), true);

					//update project template with script specific data
					SharpDevelopIDE ide = new SharpDevelopIDE();
					ScriptParser parser = new ScriptParser(scriptFile, SearchDirs);
					AssemblyResolver asmResolver = new AssemblyResolver();

					ide.InsertFile(scriptFile, projFile);

					string[] importerdScripts = parser.SaveImportedScripts();
					foreach (string file in importerdScripts)
						ide.InsertFile(file, projFile);
					
					System.Diagnostics.Debug.Assert(false);
					foreach (string name in parser.ReferencedNamespaces)
					{
                        bool ignore = false;
                        foreach (string ignoreName in parser.IgnoreNamespaces)
                            if (ignore = (name == ignoreName))
                                break;

                        if (ignore)
                            continue;

						string[] asmFiles = AssemblyResolver.FindAssembly(name, SearchDirs);
						
						foreach (string file in asmFiles)
						{
							ide.InsertReference(file, projFile);
						}
					}

					foreach (string asmName in parser.ReferencedAssemblies) //some assemblies were referenced from code
					{
						string[] asmFiles = AssemblyResolver.FindAssembly(asmName, SearchDirs);
						foreach (string file in asmFiles)
							ide.InsertReference(file, projFile);
					}

					//open project
					Environment.CurrentDirectory = Path.GetDirectoryName(scriptFile);

					Process myProcess = new Process();
					myProcess.StartInfo.FileName = SharpDevelopIDE.GetIDEFile();
					myProcess.StartInfo.Arguments = "\"" + solutionFile + "\" ";
					myProcess.Start();
					myProcess.WaitForExit();

					//do clean up
					Directory.Delete(tempDir, true);
					foreach (string file in importerdScripts)
					{
						if (Path.GetFileName(file).StartsWith("i_")) //imported modified files have name "i_file_XXXXXX.cs>"
						{
							File.SetAttributes(file, FileAttributes.Normal);
							File.Delete(file);
						}
					}
				}
				catch (Exception e)
				{
					MessageBox.Show("Specified file could not be linked to the temp project:\n" + e.Message);
				}
			}
		}