public void Process(SolutionFile solutionFile)
		{
			foreach (var command in underlying)
			{
				command.Process(solutionFile);
			}
		}
		public void Process(SolutionFile solutionFile)
		{
			var basePath = solutionFile.FullPath.Parent;
			var relativePath = absolutePath.PathFrom(basePath);
			var project = new SolutionProject(relativePath, basePath, SolutionProject.CsProjProject, fileSystem);
			// It would be nicer if we could figure out the type by reading the destination file.
			solutionFile.Add(project);
		}
        public static void WriteConditionalCompilation(this SolutionProjectLanguage Language, SolutionFile File, PseudoIfExpression If, SolutionBuilder Context)
        {
            File.WriteSpace(PreprocessorDirectives.@if);
            Language.WritePseudoExpression(File, If.Expression, Context);
            File.WriteLine();

            Language.WriteMethodBody(File, If.TrueCase, Context);

            if (If.FalseCase != null)
            {
                File.WriteLine(PreprocessorDirectives.@else);
                Language.WriteMethodBody(File, If.FalseCase, Context);
            }

            File.WriteLine(PreprocessorDirectives.@endif);
        }
        public FilteredSolutionWatcher(
                    AcceptDifferencesHandler handler,
                    FilterFile filterFile,
                    SolutionFile filteredSolution)
        {
            r_acceptDifferencesHandler = handler;
            r_filterFile = filterFile;
            m_filteredSolution = filteredSolution;

            r_watcher = new FileSystemWatcher
                {
                    NotifyFilter = NotifyFilters.LastWrite,
                    Path = Path.GetDirectoryName(m_filteredSolution.SolutionFullPath),
                    Filter = Path.GetFileName(m_filteredSolution.SolutionFullPath)
                };
            r_watcher.Changed += OnChanged;
        }
        public override void WriteMethod(SolutionFile File, SolutionProjectLanguageMethod Method, SolutionBuilder Context)
        {
            var m = Method;

            if (!m.IsLambda)
            {
                this.WriteSummary(File, m.Summary, m.Parameters.ToArray());
            }


            File.Region(
                delegate
            {
                if (m.IsLambda)
                {
                    if (Method.IsFunction)
                    {
                        File.WriteSpace(Keywords.Function);
                    }
                    else
                    {
                        File.WriteSpace(Keywords.Sub);
                    }
                }
                else
                {
                    File.WriteIndent();

                    if (m.IsProtected)
                    {
                        File.WriteSpace(Keywords.Protected);
                    }
                    else
                    {
                        File.WriteSpace(Keywords.Public);
                    }

                    if (m.IsStatic)
                    {
                        var IsModule = false;

                        if (m.DeclaringType != null)
                        {
                            if (m.DeclaringType.IsStatic)
                            {
                                IsModule = true;
                            }
                        }

                        if (IsModule)
                        {
                        }
                        else
                        {
                            File.WriteSpace(Keywords.Shared);
                        }
                    }

                    if (m.IsOverride)
                    {
                        File.WriteSpace(Keywords.Overrides);
                    }

                    if (Method.IsFunction)
                    {
                        File.WriteSpace(Keywords.Function);
                    }
                    else
                    {
                        File.WriteSpace(Keywords.Sub);
                    }

                    if (m.IsConstructor)
                    {
                        File.Write(Keywords.New);
                    }
                    else
                    {
                        File.Write(m.Name);
                    }
                }

                File.Write("(");

                #region Parameters
                var Parameters = m.Parameters.ToArray();

                for (int i = 0; i < Parameters.Length; i++)
                {
                    if (i > 0)
                    {
                        File.WriteSpace(",");
                    }


                    File.Write(Parameters[i].Name);

                    if (Method.Code.IsLambdaExpression)
                    {
                        // omit type ? :)
                    }
                    else
                    {
                        Parameters[i].Type.With(
                            ParameterType =>
                        {
                            File.WriteSpaces(Keywords.As);

                            this.WriteTypeName(File, ParameterType);
                        }
                            );
                    }
                }
                #endregion

                File.Write(")");

                if (Method.Code.IsLambdaExpression)
                {
                    File.WriteSpace();
                    this.WriteMethodBody(File, m.Code, Context);
                }
                else
                {
                    File.WriteLine();

                    this.WriteMethodBody(File, m.Code, Context);

                    File.WriteIndent();

                    File.WriteSpace(Keywords.End);
                    if (Method.IsFunction)
                    {
                        File.WriteSpace(Keywords.Function);
                    }
                    else
                    {
                        File.WriteSpace(Keywords.Sub);
                    }
                }
                File.WriteLine();
            }
                );
        }
        public override void WritePseudoCallExpression(SolutionFile File, PseudoCallExpression Lambda, SolutionBuilder Context)
        {
            if (Lambda.Method.Name == SolutionProjectLanguageMethod.op_Implicit)
            {
                WritePseudoExpression(File, Lambda.ParameterExpressions[0], Context);
                return;
            }

            if (Lambda.Method.OperatorName != null)
            {
                if (Lambda.ParameterExpressions.Length == 2)
                {
                    WritePseudoExpression(File, Lambda.ParameterExpressions[0], Context);
                    File.WriteSpaces(Lambda.Method.OperatorName);
                    WritePseudoExpression(File, Lambda.ParameterExpressions[1], Context);

                    return;
                }
            }

            if (Lambda.Method.IsConstructor)
            {
                File.Write(Keywords.New);
                File.WriteSpace();
                WriteTypeName(File, Lambda.Method.DeclaringType);
                InternalWriteParameterList(File, Lambda, Context);
                return;
            }

            if (Lambda.Method.IsEvent)
            {
                if (Lambda.Method.Name.StartsWith("add_"))
                {
                    File.WriteSpace(Keywords.AddHandler);
                }
            }

            var Objectless = true;

            if (IsExtensionMethod(Lambda))
            {
                WritePseudoExpression(File, Lambda.ParameterExpressions[0], Context);
                Objectless = false;
            }
            else
            {
                if (Lambda.Method.IsStatic)
                {
                    if (Lambda.Method.DeclaringType != null)
                    {
                        WriteTypeName(File, Lambda.Method.DeclaringType);
                        Objectless = false;
                    }
                }
                else
                {
                    if (Lambda.Object != null)
                    {
                        WritePseudoExpression(File, Lambda.Object, Context);
                        Objectless = false;
                    }
                }
            }


            if (Lambda.Method.Name == "Invoke")
            {
                // in c# we can omit the .Invoke on a delegate
            }
            else
            {
                var Target = Lambda.Method.Name;

                if (Lambda.Method.IsProperty)
                {
                    Target = Target.SkipUntilIfAny("set_").SkipUntilIfAny("get_");
                }
                else if (Lambda.Method.IsEvent)
                {
                    Target = Target.SkipUntilIfAny("add_").SkipUntilIfAny("remove_");
                }

                if (!Objectless)
                {
                    File.Write(".");
                }

                File.Write(
                    new SolutionFileWriteArguments
                    {
                        Fragment = SolutionFileTextFragment.None,
                        Text = Target,
                        Tag = Lambda.Method
                    }
                );
            }

            if (Lambda.Method.IsEvent)
            {
                if (Lambda.Method.Name.StartsWith("add_"))
                {
                    File.WriteSpace(",");
                    WritePseudoExpression(File, Lambda.ParameterExpressions[0], Context);
                }
            }
            else if (Lambda.Method.IsProperty)
            {

                if (Lambda.ParameterExpressions.Length == 1)
                {
                    File.WriteSpace();

                    if (Lambda.IsAttributeContext)
                    {
                        File.Write(":=");
                    }
                    else
                    {
                        File.Write("=");
                    }

                    File.WriteSpace();
                    WritePseudoExpression(File, Lambda.ParameterExpressions[0], Context);
                }

            }
            else
            {

                InternalWriteParameterList(File, Lambda, Context);
            }


        }
        public override void WriteType(SolutionFile File, SolutionProjectLanguageType Type, SolutionBuilder Context)
        {
            File.Write(this, Context, Type.Comments);



            // should the namespaces be clickable?


            File.WriteUsingNamespaceList(this, Type);

            File.WriteLine();

            File.Region(
                delegate
            {
                WriteNamespace(File, Type.Namespace,
                               delegate
                {
                    this.WriteSummary(
                        File,

                        Type.Summary
                        );


                    File.Region(
                        delegate
                    {
                        File.WriteIndent();

                        if (Type.IsPartial)
                        {
                            File.WriteSpace(Keywords.Partial);
                        }

                        File.WriteSpace(Keywords.Public);

                        if (Type.IsSealed)
                        {
                            File.WriteSpace(Keywords.NotInheritable);
                        }

                        if (!Type.IsStatic)
                        {
                            File.WriteSpace(Keywords.Class);
                        }
                        else
                        {
                            File.WriteSpace(Keywords.Module);
                        }

                        File.Write(Type);
                        File.WriteLine();

                        File.Indent(this,
                                    delegate
                        {
                            Type.BaseType.With(
                                BaseType =>
                            {
                                File.WriteIndent().WriteSpace(Keywords.Inherits);
                                WriteTypeName(File, BaseType);
                                File.WriteLine();
                            }
                                );

                            #region Fields
                            Type.Fields.WithEach(
                                Field =>
                            {
                                this.WriteSummary(File, Field.Summary);

                                File.WriteIndent();

                                if (Field.IsPrivate)
                                {
                                    File.WriteSpace(Keywords.Private);
                                }
                                else
                                {
                                    File.WriteSpace(Keywords.Public);
                                }

                                if (Field.IsReadOnly)
                                {
                                    File.WriteSpace(Keywords.ReadOnly);
                                }

                                File.WriteSpace(Field.Name);
                                File.WriteSpace(Keywords.As);

                                if (Field.FieldConstructor == null)
                                {
                                    WriteTypeName(File, Field.FieldType);
                                }
                                else
                                {
                                    WritePseudoCallExpression(File, Field.FieldConstructor, Context);
                                }

                                File.WriteLine();

                                File.WriteLine();
                            }
                                );


                            #endregion

                            #region Methods
                            foreach (var item in Type.Methods.ToArray())
                            {
                                if (item.DeclaringType == null)
                                {
                                    item.DeclaringType = Type;
                                }

                                this.WriteMethod(
                                    File,
                                    item,
                                    Context
                                    );


                                File.WriteLine();
                            }
                            #endregion



                            File.WriteLine();
                        }
                                    );

                        File.WriteIndent();
                        File.Write(Keywords.End);
                        File.WriteSpace();
                        if (!Type.IsStatic)
                        {
                            File.Write(Keywords.Class);
                        }
                        else
                        {
                            File.Write(Keywords.Module);
                        }
                    }
                        );
                    File.WriteLine();
                }
                               );
            }
                );
            File.WriteLine();
        }
Exemple #8
0
        private static void ProcessSolutionFile(CommandLine commandLine)
        {
            if (commandLine.Clean)
            {
                Log.Info("Removing .NET 3.5 VS solutions and project files ");
            }
            else
            {
                Log.Info("Converting VS solution and projects to target .NET 3.5");
            }
            if (commandLine.NoChanges)
            {
                Log.Info("PREVIEW MODE: NO CHANGES WILL BE MADE");
            }
            var solutionFile = new SolutionFile(commandLine.ProjectFile);
            using (CurrentDirectory.ChangeTo(Path.GetDirectoryName(commandLine.ProjectFile)))
            {
                foreach (var project in solutionFile.Projects)
                {
                    if (project.ProjectType == ProjectType.SolutionFolder)
                    {
                        project.ShouldTransform = true;
                    }
                    else if (project.ProjectType == ProjectType.CSharp)
                    {
                        var projectFile = new ProjectFile(project.RelativePath);
                        if (projectFile.ShouldTransformToNet35())
                        {
                            project.ShouldTransform = true;
                        }
                        else
                        {
                            project.ShouldTransform = false;
                        }
                    }
                }

                foreach (var project in solutionFile.Projects)
                {
                    if (project.ShouldTransform && project.ProjectType == ProjectType.CSharp)
                    {
                        var projectFile = new ProjectFile(project.RelativePath);
                        projectFile.ProjectGuid = project.NewProjectGuid;
                        projectFile.TransformToNet35();
                        foreach (var referenceProject in solutionFile.Projects)
                        {
                            if (referenceProject == project
                                || referenceProject.ProjectType != ProjectType.CSharp
                                || !referenceProject.ShouldTransform)
                            {
                                continue;
                            }

                            projectFile.ChangeProjectReference(referenceProject);
                        }
                        if (commandLine.Clean)
                        {
                            PromptToRemoveFile(projectFile.Net35FilePath);
                        }
                        else
                        {
                            Log.InfoFormat("{0} -> {1}", projectFile.FilePath, projectFile.Net35FilePath);
                            if (!commandLine.NoChanges)
                            {
                                projectFile.SaveTo(projectFile.Net35FilePath);
                            }
                        }
                    }
                }
            }
            if (commandLine.Clean)
            {
                PromptToRemoveFile(commandLine.OutputFile);
            }
            else
            {
                Log.InfoFormat("{0} -> {1}", commandLine.ProjectFile, commandLine.OutputFile);
                if (!commandLine.NoChanges)
                {
                    solutionFile.SaveTo(commandLine.OutputFile);
                }
            }
        }
        private void OnChanged(object source, FileSystemEventArgs e)
        {
            lock (r_watcher)
            {
                try
                {
                    WaitForFileToBeReleased(e.FullPath);

                    var newFilteredSolution = SolutionFile.FromFile(m_filteredSolution.SolutionFullPath);
                    var difference = newFilteredSolution.CompareTo(m_filteredSolution);
                    if (difference != null)
                    {
                        difference.Remove(diff => diff.Identifier.Name.Contains("SccProjectTopLevelParentUniqueName"));
                        if (difference.Subdifferences.Count > 0)
                        {
                            if (r_acceptDifferencesHandler(difference))
                            {
                                var newOriginalSolution = SolutionFile.FromElement((NodeElement)r_filterFile.SourceSolution.ToElement().Apply(difference));
                                newOriginalSolution.Save();
                                m_filteredSolution = newFilteredSolution;
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Trace.WriteLine("OnChanged handler: " + ex.ToString());
                }
            }
        }
Exemple #10
0
        public void GetProjectsFromSolution_ValidArguments(SolutionFile solution, IEnumerable <string> expected)
        {
            IEnumerable <string> actual = SolutionUtilities.GetProjectsFromSolution(solution);

            Assert.That(actual, Is.EquivalentTo(expected));
        }
        internal static IEnumerable <string> GetProjectsFromSolution(string solutionPath)
        {
            var sln = SolutionFile.Parse(solutionPath);

            return(sln.ProjectsInOrder.Select(p => p.AbsolutePath));
        }
 public override void WriteUsingNamespace(SolutionFile File, string item)
 {
     File.WriteIndent().WriteSpace(Keywords.@using).Write(item).WriteLine(";");
 }
 public override void WriteAssemblyAttributeNamespace(SolutionFile File, string Namespace, Action Body)
 {
     Body();
 }
        public override void WriteNamespace(SolutionFile File, string Namespace, Action Body)
        {
            File.Write(Keywords.@namespace);
            File.WriteSpace();
            File.Write(Namespace);
            File.WriteLine();
            File.WriteLine("{");
            File.Indent(this, Body);

            File.WriteLine("}");

        }
        public override void WriteType(SolutionFile File, SolutionProjectLanguageType Type, SolutionBuilder Context)
        {
            File.Write(this, Context, Type.Comments);

            File.WriteUsingNamespaceList(this, Type);


            File.WriteLine();

            File.Region(
                delegate
                {
                    WriteNamespace(File, Type.Namespace,
                        delegate
                        {

                            if (Type.Summary != null)
                                this.WriteSummary(
                                    File,
                                    Type.Summary
                                );

                            File.Region(
                                delegate
                                {
                                    File.WriteIndent();

                                    if (Type.IsInternal)
                                    {
                                        File.WriteSpace(Keywords.@internal);
                                    }
                                    else
                                    {
                                        File.WriteSpace(Keywords.@public);
                                    }

                                    if (Type.IsStatic)
                                    {
                                        File.WriteSpace(Keywords.@static);
                                    }


                                    if (Type.IsSealed)
                                    {
                                        File.WriteSpace(Keywords.@sealed);
                                    }

                                    if (Type.IsPartial)
                                    {
                                        File.WriteSpace(Keywords.@partial);
                                    }


                                    if (Type.IsInterface)
                                    {
                                        File.WriteSpace(Keywords.@interface);
                                    }
                                    else
                                    {
                                        File.WriteSpace(Keywords.@class);
                                    }

                                    File.Write(Type);

                                    if (Type.BaseType != null)
                                    {
                                        File.WriteSpaces(":");
                                        WriteTypeName(File, Type.BaseType);
                                    }

                                    File.WriteLine();

                                    File.WriteIndent();
                                    File.WriteLine("{");
                                    File.Indent(this,
                                        delegate
                                        {
                                            #region Fields
                                            Type.Fields.WithEach(
                                                Field =>
                                                {
                                                    this.WriteSummary(File, Field.Summary);

                                                    File.WriteIndent();

                                                    if (Field.IsPrivate)
                                                    {
                                                        File.WriteSpace(Keywords.@private);
                                                    }
                                                    else
                                                    {
                                                        File.WriteSpace(Keywords.@public);
                                                    }

                                                    if (Field.IsReadOnly)
                                                    {
                                                        File.WriteSpace(Keywords.@readonly);
                                                    }

                                                    WriteTypeName(File, Field.FieldType);
                                                    File.WriteSpace().Write(Field.Name);

                                                    if (Field.FieldConstructor != null)
                                                    {
                                                        File.WriteSpaces("=");
                                                        this.WritePseudoCallExpression(File, Field.FieldConstructor, Context);
                                                    }

                                                    File.WriteLine(";");

                                                    File.WriteLine();
                                                }
                                            );


                                            #endregion


                                            #region Properties
                                            foreach (var m in Type.Properties.ToArray())
                                            {
                                                File.WriteIndent();

                                                if (Type.IsInterface)
                                                {

                                                }
                                                else
                                                {
                                                    File.Write(Keywords.@public);
                                                    File.WriteSpace();

                                                    if (m.IsStatic)
                                                    {
                                                        File.Write(Keywords.@static);
                                                        File.WriteSpace();
                                                    }
                                                }

                                                WriteTypeName(File, m.PropertyType);
                                                File.WriteSpace();
                                                File.Write(m.Name);

                                                if (m.IsAutoProperty)
                                                {
                                                    File.WriteSpace();
                                                    File.Write("{");
                                                }
                                                else
                                                {
                                                    File.WriteLine();
                                                    File.WriteIndent();
                                                    File.WriteLine("{");
                                                }


                                                Action<SolutionProjectLanguageMethod, Keyword> Property = (mm, kk) =>
                                                {
                                                    if (mm != null)
                                                    {
                                                        if (m.IsAutoProperty)
                                                        {
                                                            File.WriteSpace();
                                                        }
                                                        else
                                                        {
                                                            File.WriteIndent();
                                                        }
                                                        File.Write(kk);
                                                        if (mm.Code == null)
                                                        {
                                                            File.Write(";");
                                                            if (m.IsAutoProperty)
                                                            {
                                                            }
                                                            else
                                                            {
                                                                File.WriteLine();
                                                            }
                                                        }
                                                        else
                                                        {
                                                            File.WriteLine();
                                                            this.WriteMethodBody(File, mm.Code, Context);
                                                        }
                                                    }
                                                };

                                                Action PropertyBody = delegate
                                                {
                                                    Property(m.GetMethod, Keywords.get);
                                                    Property(m.SetMethod, Keywords.set);
                                                };

                                                Action<Action> PropertyIndent = Body => File.Indent(this, Body);

                                                if (m.IsAutoProperty)
                                                {
                                                    PropertyBody();
                                                    File.WriteSpace();
                                                }
                                                else
                                                {
                                                    File.Indent(this, PropertyBody);
                                                    File.WriteIndent();
                                                }


                                                File.WriteLine("}");
                                            }
                                            #endregion

                                            if (Type.Properties.Any())
                                                File.WriteLine();

                                            foreach (var item in Type.Methods.ToArray())
                                            {
                                                if (item.DeclaringType == null)
                                                    item.DeclaringType = Type;

                                                this.WriteMethod(
                                                    File,
                                                    item,
                                                    Context
                                                );

                                                File.WriteLine();
                                            }


                                        }
                                    );

                                    File.WriteIndent().WriteLine("}");
                                }
                            );
                        }
                    );


                }
            );

        }
        public override void WriteTypeName(SolutionFile File, SolutionProjectLanguageType Type)
        {
            if (Type is KnownStockTypes.System.Boolean)
            {
                File.Write(Keywords.@bool);
                return;
            }

            if (Type is KnownStockTypes.System.String)
            {
                File.Write(Keywords.@string);
                return;
            }

            if (Type.DeclaringType != null)
            {
                WriteTypeName(File, Type.DeclaringType);
                File.Write(".");
            }

            if (Type.ElementType != null)
            {
                WriteTypeName(File, Type.ElementType);
                File.Write("[]");

                return;
            }

            File.Write(Type);

            if (Type.Arguments.Count > 0)
            {
                File.Write("<");

                var Arguments = Type.Arguments.ToArray();

                for (int i = 0; i < Arguments.Length; i++)
                {
                    if (i > 0)
                    {
                        File.Write(",");
                        File.WriteSpace();
                    }

                    this.WriteTypeName(File, Arguments[i].Type);
                }

                File.Write(">");

            }
        }
        public override void WriteMethod(SolutionFile File, SolutionProjectLanguageMethod m, SolutionBuilder Context)
        {
            if (!m.IsLambda)
                if (m.Summary != null)
                    this.WriteSummary(File, m.Summary, m.Parameters.ToArray());

            File.Region(
                delegate
                {
                    if (m.IsLambda)
                    {
                        var Parameters = m.Parameters.ToArray();

                        if (Parameters.Length != 1)
                            File.Write("(");


                        for (int i = 0; i < Parameters.Length; i++)
                        {
                            if (i > 0)
                            {
                                File.WriteSpace(",");
                            }

                            File.Write(Parameters[i].Name);
                        }

                        if (Parameters.Length != 1)
                            File.WriteSpace(")");
                        else
                            File.WriteSpace();

                        File.WriteSpace("=>");

                        if (m.Code.History.Count != 1)
                            File.WriteLine();

                        this.WriteMethodBody(File, m.Code, Context);

                        return;

                    }
                    #region not lambda
                    File.WriteIndent();

                    if (m.IsPrivate)
                    {
                        File.Write(Keywords.@private);
                    }
                    else if (m.IsProtected)
                    {
                        File.Write(Keywords.@protected);
                    }
                    else
                    {
                        File.Write(Keywords.@public);
                    }
                    File.WriteSpace();

                    if (m.IsOverride)
                    {
                        File.WriteSpace(Keywords.@override);
                    }


                    if (m.IsStatic)
                    {
                        File.WriteSpace(Keywords.@static);
                    }

                    if (m.IsConstructor)
                    {
                        WriteTypeName(File, m.DeclaringType);
                    }
                    else
                    {
                        File.WriteSpace(Keywords.@void).Write(m.Name);
                    }
                    #endregion

                    {

                        var Parameters = m.Parameters.ToArray();


                        File.Write("(");


                        for (int i = 0; i < Parameters.Length; i++)
                        {
                            if (i > 0)
                            {
                                File.WriteSpace(",");
                            }

                            this.WriteTypeName(File, Parameters[i].Type);

                            File.WriteSpace();
                            File.Write(Parameters[i].Name);
                        }


                        File.Write(")");
                    }

                    if (m.Code == null)
                    {
                        File.WriteLine(";");
                    }
                    else
                    {
                        File.WriteLine();

                        this.WriteMethodBody(File, m.Code, Context);

                        if (!m.IsLambda)
                        {
                            File.WriteLine();
                        }
                    }
                }
            );
        }
        public override void WriteXMLCommentLine(SolutionFile File, string Text)
        {
            // http://msdn.microsoft.com/en-us/library/aa288481(VS.71).aspx

            File.WriteLine(SolutionFileTextFragment.Comment, "/// " + Text);
        }
 public override void WriteUsingNamespace(SolutionFile File, string item)
 {
     File.WriteIndent().WriteSpace(Keywords.@Imports).WriteLine(item);
 }
        public override void WriteAssemblyAttribute(SolutionFile File, SolutionProjectLanguageAttribute Attribute, SolutionBuilder Context)
        {
            File.Write("[");
            File.Write(Keywords.assembly);
            File.Write(": ");

            this.WriteTypeName(File, Attribute.Type);
            File.Write("(");

            var args = new List<Action>();

            if (Attribute.Parameters != null)
            {
                args.AddRange(
                    from item in Attribute.Parameters
                    select (Action)delegate
                    {
                        this.WritePseudoExpression(File, item, Context);
                    }
                );
            }


            if (Attribute.Properties != null)
            {
                args.AddRange(
                    from item in Attribute.Properties.ToArray()
                    select (Action)delegate
                    {
                        this.WritePseudoCallExpression(File,
                            new PseudoCallExpression
                            {
                                Method = item.Key,
                                ParameterExpressions = new[] {
										item.Value
									}
                            }, Context
                        );
                    }
                );

            }

            Action Separator = delegate
            {
                File.Write(", ");
            };

            var BeforeSeparator = args.ToArray();
            var AfterSeparator = BeforeSeparator.SelectWithSeparator(Separator).ToArray();

            AfterSeparator.Invoke();

            File.Write(")");
            File.Write("]");

            File.WriteLine();
        }
 public override void WriteSingleIndent(SolutionFile File)
 {
     File.Write(SolutionFileTextFragment.Indent, "\t");
 }
 public override void WriteSingleIndent(SolutionFile File)
 {
     File.Write(SolutionFileTextFragment.Indent, "\t");
 }
        public virtual void Initalize(IConfiguration configuration)
        {
            if (_context.AlreadyInitialised)
            {
                // When the Protobuild project system imports projects, we
                // don't want the raw non-Protobuild MSBuild import to occur.
                // To avoid this, the Protobuild project system sets
                // AlreadyInitialised to true after it finishes running (if
                // it has detected projects), and to false again before it starts.
                return;
            }

            _options = new MSBuildOptions();
            OptionsServices.ReadProperties(_options, configuration);

            var solutionFilePath = _env.SolutionFilePath;

            if (string.IsNullOrEmpty(solutionFilePath))
            {
                var solutions = Directory.GetFiles(_env.Path, "*.sln");
                var result    = SolutionPicker.ChooseSolution(_env.Path, solutions);

                if (result.Message != null)
                {
                    _logger.LogInformation(result.Message);
                }

                if (result.Solution == null)
                {
                    return;
                }

                solutionFilePath = result.Solution;
            }

            SolutionFile solutionFile = null;

            _context.SolutionPath = solutionFilePath;

            using (var stream = File.OpenRead(solutionFilePath))
            {
                using (var reader = new StreamReader(stream))
                {
                    solutionFile = SolutionFile.Parse(reader);
                }
            }
            _logger.LogInformation($"Detecting projects in '{solutionFilePath}'.");

            foreach (var block in solutionFile.ProjectBlocks)
            {
                if (!_supportsProjectTypes.Contains(block.ProjectTypeGuid))
                {
                    if (UnityTypeGuid(block.ProjectName) != block.ProjectTypeGuid)
                    {
                        _logger.LogWarning("Skipped unsupported project type '{0}'", block.ProjectPath);
                        continue;
                    }
                }

                if (_context.ProjectGuidToWorkspaceMapping.ContainsKey(block.ProjectGuid))
                {
                    continue;
                }

                var projectFilePath = Path.GetFullPath(Path.GetFullPath(Path.Combine(_env.Path, block.ProjectPath.Replace('\\', Path.DirectorySeparatorChar))));

                _logger.LogInformation($"Loading project from '{projectFilePath}'.");

                var projectFileInfo = CreateProject(projectFilePath);

                if (projectFileInfo == null)
                {
                    continue;
                }

                var compilationOptions = new CSharpCompilationOptions(projectFileInfo.OutputKind);
#if DNX451
                compilationOptions = compilationOptions.WithAssemblyIdentityComparer(DesktopAssemblyIdentityComparer.Default);
#endif

                if (projectFileInfo.AllowUnsafe)
                {
                    compilationOptions = compilationOptions.WithAllowUnsafe(true);
                }

                var projectInfo = ProjectInfo.Create(ProjectId.CreateNewId(projectFileInfo.Name),
                                                     VersionStamp.Create(),
                                                     projectFileInfo.Name,
                                                     projectFileInfo.AssemblyName,
                                                     LanguageNames.CSharp,
                                                     projectFileInfo.ProjectFilePath,
                                                     compilationOptions: compilationOptions);

                _workspace.AddProject(projectInfo);

                projectFileInfo.WorkspaceId = projectInfo.Id;

                _context.Projects[projectFileInfo.ProjectFilePath]        = projectFileInfo;
                _context.ProjectGuidToWorkspaceMapping[block.ProjectGuid] = projectInfo.Id;

                _watcher.Watch(projectFilePath, OnProjectChanged);
            }

            foreach (var projectFileInfo in _context.Projects.Values)
            {
                UpdateProject(projectFileInfo);
            }
        }
Exemple #24
0
        protected override IEnumerable <string> GetSolutionCompletionResults(InvokeMSBuildParameters parameters)
        {
            var solution = SolutionFile.Parse(parameters.Project);

            return(solution.SolutionConfigurations.Select(x => x.ConfigurationName).Distinct());
        }
Exemple #25
0
        public void CustomConfigurationAndPlatforms()
        {
            SlnProject projectA = new SlnProject
            {
                Configurations  = new[] { "Debug", "Release" },
                FullPath        = GetTempFileName(),
                IsMainProject   = true,
                Name            = "ProjectA",
                Platforms       = new[] { "AnyCPU", "x64", "x86" },
                ProjectGuid     = Guid.NewGuid(),
                ProjectTypeGuid = Guid.NewGuid(),
            };

            SlnProject projectB = new SlnProject
            {
                Configurations  = new[] { "Debug", "Release" },
                FullPath        = GetTempFileName(),
                IsMainProject   = true,
                Name            = "ProjectB",
                Platforms       = new[] { "x64", "x86" },
                ProjectGuid     = Guid.NewGuid(),
                ProjectTypeGuid = Guid.NewGuid(),
            };

            SlnProject projectC = new SlnProject
            {
                Configurations  = new[] { "Debug", "Release" },
                FullPath        = GetTempFileName(),
                IsMainProject   = true,
                Name            = "ProjectC",
                Platforms       = new[] { "amd64" },
                ProjectGuid     = Guid.NewGuid(),
                ProjectTypeGuid = Guid.NewGuid(),
            };

            SlnProject projectD = new SlnProject
            {
                Configurations  = new[] { "Debug", "Release" },
                FullPath        = GetTempFileName(),
                IsMainProject   = true,
                Name            = "ProjectD",
                Platforms       = new[] { "Razzle" },
                ProjectGuid     = Guid.NewGuid(),
                ProjectTypeGuid = Guid.NewGuid(),
            };

            SlnProject projectE = new SlnProject
            {
                Configurations  = new[] { "Release" },
                FullPath        = GetTempFileName(),
                IsMainProject   = true,
                Name            = "ProjectE",
                Platforms       = new[] { "AnyCPU" },
                ProjectGuid     = Guid.NewGuid(),
                ProjectTypeGuid = Guid.NewGuid(),
            };

            SlnFile slnFile = new SlnFile()
            {
                Configurations = new[] { "Debug" },
                Platforms      = new[] { "Any CPU" },
            };

            slnFile.AddProjects(new[] { projectA, projectB, projectC, projectD, projectE });

            string solutionFilePath = GetTempFileName();

            slnFile.Save(solutionFilePath, useFolders: false);

            SolutionFile solutionFile = SolutionFile.Parse(solutionFilePath);

            ValidateSolutionPlatformAndConfiguration(projectA, solutionFile, "Debug", "AnyCPU");

            ValidateSolutionPlatformAndConfiguration(projectB, solutionFile, "Debug", "x64");

            ValidateSolutionPlatformAndConfiguration(projectC, solutionFile, "Debug", "amd64");

            ValidateSolutionPlatformAndConfiguration(projectD, solutionFile, "Debug", "Razzle", expectedIncludeInBuild: false);

            ValidateSolutionPlatformAndConfiguration(projectE, solutionFile, "Release", "AnyCPU", expectedIncludeInBuild: true);
        }
Exemple #26
0
        /// <summary>
        /// This is a javascript application.
        /// </summary>
        /// <param name="page">HTML document rendered by the web server which can now be enhanced.</param>
        public Application(IDefaultPage page)
        {
            new JSCSolutionsNETImage().ToBackground(page.Item1.style, false);
            new JSCSolutionsNETImage().ToBackground(page.Item2.style, false);


            // Update document title
            // http://do.jsc-solutions.net/Update-document-title

            @"Hello world".ToDocumentTitle();
            // Send xml to server
            // http://do.jsc-solutions.net/Send-xml-to-server

            var v = new SolutionFileView();

            var f = new SolutionFile();

            f.WriteHTMLElement(StockPageDefault.Element);

            v.File = f;

            var Container = new IHTMLDiv();

            Container.style.position = IStyle.PositionEnum.relative;
            Container.style.display  = IStyle.DisplayEnum.inline_block;
            Container.style.width    = "600px";
            Container.style.height   = "400px";
            Container.style.border   = "1px solid gray";

            var ToolbarHeight = "1.3em";
            var Content       = new IHTMLDiv().AttachTo(Container);

            Content.style.position = IStyle.PositionEnum.absolute;
            Content.style.left     = "0px";
            Content.style.top      = "0px";
            Content.style.right    = "0px";
            Content.style.bottom   = ToolbarHeight;


            var Toolbar = new IHTMLDiv().AttachTo(Container);

            Toolbar.style.backgroundColor = Color.FromGray(0xef);
            Toolbar.style.position        = IStyle.PositionEnum.absolute;
            Toolbar.style.left            = "0px";
            Toolbar.style.height          = ToolbarHeight;
            Toolbar.style.right           = "0px";
            Toolbar.style.bottom          = "0px";

            Action <IHTMLImage, string, Action> AddToolbarButton =
                (img, text, handler) =>
            {
                var span = new IHTMLSpan {
                    innerText = text
                };

                span.style.paddingLeft  = "1.5em";
                span.style.paddingRight = "0.3em";

                var a = new IHTMLAnchor
                {
                    img, span
                };

                img.style.verticalAlign = "middle";
                img.border         = 0;
                img.style.position = IStyle.PositionEnum.absolute;

                a.style.backgroundColor = Color.FromGray(0xef);
                a.style.color           = Color.Black;
                a.style.textDecoration  = "none";
                a.style.fontFamily      = IStyle.FontFamilyEnum.Tahoma;

                a.href     = "javascript: void(0);";
                a.onclick +=
                    delegate
                {
                    handler();
                };
                a.style.display = IStyle.DisplayEnum.inline_block;
                a.style.height  = "100%";


                a.onmousemove +=
                    delegate
                {
                    a.style.backgroundColor = Color.FromGray(0xff);
                };

                a.onmouseout +=
                    delegate
                {
                    a.style.backgroundColor = Color.FromGray(0xef);
                };

                Toolbar.Add(a);
            };


            v.Container.style.height = "100%";
            v.Container.AttachTo(Content);


            Content.Add(v.Container);

            var i = CreateEditor();

            i.AttachTo(Content);



            var ii = new IHTMLPre().AttachTo(Content);

            ii.style.position   = IStyle.PositionEnum.absolute;
            ii.style.left       = "0px";
            ii.style.top        = "0px";
            ii.style.right      = "0px";
            ii.style.bottom     = "0px";
            ii.style.overflow   = IStyle.OverflowEnum.auto;
            ii.style.padding    = "0px";
            ii.style.margin     = "0px";
            ii.style.whiteSpace = IStyle.WhiteSpaceEnum.normal;

            v.Container.style.display = IStyle.DisplayEnum.none;
            i.style.display           = IStyle.DisplayEnum.empty;
            ii.style.display          = IStyle.DisplayEnum.none;

            AddToolbarButton(new RTA_mode_design(), "Design",
                             delegate
            {
                v.Container.style.display = IStyle.DisplayEnum.none;
                ii.style.display          = IStyle.DisplayEnum.none;
                i.style.display           = IStyle.DisplayEnum.empty;
            }
                             );

            AddToolbarButton(new RTA_mode_html(), "Source",
                             delegate
            {
                v.Container.style.display = IStyle.DisplayEnum.empty;
                ii.style.display          = IStyle.DisplayEnum.none;
                i.style.display           = IStyle.DisplayEnum.none;

                f.Clear();

                i.WhenContentReady(
                    body =>
                {
                    f.WriteHTMLElement(body.AsXElement());

                    // update
                    v.File = f;
                }
                    );
            }
                             );

            AddToolbarButton(new RTA_mode_html(), "Source raw",
                             delegate
            {
                v.Container.style.display = IStyle.DisplayEnum.none;
                ii.style.display          = IStyle.DisplayEnum.empty;
                i.style.display           = IStyle.DisplayEnum.none;



                i.WhenContentReady(
                    body =>
                {
                    ii.innerText = body.AsXElement().ToString();
                }
                    );
            }
                             );

            page.PageContainer.Add(Container);

            new ApplicationWebService().WebMethod2(
                new XElement(@"Document",
                             new object[] {
                new XElement(@"Data",
                             new object[] {
                    @"Hello world"
                }
                             ),
                new XElement(@"Client",
                             new object[] {
                    @"Unchanged text"
                }
                             )
            }
                             ),
                delegate(XElement doc)
            {
                // Show server message as document title
                // http://do.jsc-solutions.net/Show-server-message-as-document-title

                doc.Element(@"Data").Value.ToDocumentTitle();
            }
                );
        }
Exemple #27
0
        public SolutionFile ApplyOn(SolutionFile original)
        {
            var includedProjects = new List<Project>();
            foreach (var projectFullName in this.ProjectsToKeep)
            {
                var projectToKeep = original.Projects.FindByFullName(projectFullName);
                if (projectToKeep != null)
                {
                    AddRecursiveDependenciesToList(includedProjects, projectToKeep);
                    foreach (var descendant in projectToKeep.AllDescendants)
                    {
                        AddRecursiveDependenciesToList(includedProjects, descendant);
                    }
                }
                else
                {
                    // TODO MessageBox Found project X in filter but doesn't exist in original solution
                }
            }

            return new SolutionFile(
                        this.DestinationSolutionFullPath,
                        original.Headers,
                        includedProjects,
                        original.GlobalSections);
        }
 public override void WriteLinkCommentLine(SolutionFile File, Uri Link)
 {
     File.Write(SolutionFileTextFragment.Comment, "// ").WriteLine(Link);
 }
 public override void WriteCommentLine(SolutionFile File, string Text)
 {
     File.WriteLine(SolutionFileTextFragment.Comment, "// " + Text);
 }
Exemple #30
0
        static int Main(string[] args)
        {
            if (args.Length == 0 || args.Length > 2)
            {
                ShowHelp();
                return(1);
            }
            else if (args.Length == 1 && new[] { "-?", "-h", "-help" }.Contains(args[0]))
            {
                ShowHelp();
                return(1);
            }

            System.IO.FileInfo fi = new System.IO.FileInfo(args[0]);

            if (!fi.Exists)
            {
                throw new System.IO.FileNotFoundException("Unable to find file given as first argument", args[0]);
            }

            bool write = true;

            if (args.Length == 2 && args[1] == "-test")
            {
                write = false;
            }


            SolutionFile sf = SolutionFile.Parse(fi.FullName);

            foreach (var proj in sf.ProjectsInOrder)
            {
                Console.WriteLine("Starting " + proj.ProjectName);

                if (!
                    (
                        proj.AbsolutePath.EndsWith(".csproj")
                        ||
                        proj.AbsolutePath.EndsWith(".vbproj")
                    )
                    )
                {
                    Console.WriteLine("Unsupported project type, bailing");
                    break;
                }

                XmlDocument xd = new XmlDocument();
                xd.Load(proj.AbsolutePath);

                XmlNamespaceManager nsmgr = new XmlNamespaceManager(
                    xd.NameTable);
                nsmgr.AddNamespace("ms", "http://schemas.microsoft.com/developer/msbuild/2003");

                var nodes = xd.SelectNodes("/ms:Project/ms:ItemGroup/ms:Reference/ms:HintPath", nsmgr);
                foreach (XmlNode node in nodes)
                {
                    string projectPath  = node.InnerText;
                    string relativePath = RefTransformer.MakeRefRelative(projectPath);
                    Console.WriteLine($"{proj.ProjectName}: {projectPath} -> {relativePath}");
                    node.InnerText = relativePath;
                }

                if (write)
                {
                    xd.Save(proj.AbsolutePath);
                    Console.WriteLine("Written");
                }
                else
                {
                    Console.WriteLine("Not written");
                }
            }

            return(0);
        }
 public override void WriteLinkCommentLine(SolutionFile File, Uri Link)
 {
     File.Write(SolutionFileTextFragment.Comment, "' ");
     File.Write(Link);
     File.WriteLine();
 }
        static void Main(string[] args)
        {
            Parser parser = new Parser();

            if (!parser.ParseArguments(args, CommandLineOptions))
            {
                Console.WriteLine(CommandLineOptions.GetUsage());
                return;
            }
            if (string.IsNullOrEmpty(CommandLineOptions.Solution) && string.IsNullOrEmpty(CommandLineOptions.Project))
            {
                Console.WriteLine("No solution or project provided!");
                Console.WriteLine(CommandLineOptions.GetUsage());
                return;
            }

            if (CommandLineOptions.VisualStudioVersion == "vs2019")
            {
                Compiler = WindowsCompiler.VisualStudio2019;
            }
            else if (CommandLineOptions.VisualStudioVersion == "vs2017")
            {
                Compiler = WindowsCompiler.VisualStudio2017;
            }
            else
            {
                Console.WriteLine("Unsupport Complier!");
                Console.WriteLine(CommandLineOptions.GetUsage());
                return;
            }


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

            if (!string.IsNullOrEmpty(CommandLineOptions.Solution) && File.Exists(CommandLineOptions.Solution))
            {
                try
                {
                    if (string.IsNullOrEmpty(CommandLineOptions.Project))
                    {
                        List <ProjectInSolution> SolutionProjects = SolutionFile.Parse(Path.GetFullPath(CommandLineOptions.Solution)).ProjectsInOrder.Where(el => el.ProjectType == SolutionProjectType.KnownToBeMSBuildFormat).ToList();
                        SolutionProjects.Sort((x, y) =>                         //Very dubious sort.
                        {
                            if (x.Dependencies.Contains(y.ProjectGuid))
                            {
                                return(1);
                            }
                            if (y.Dependencies.Contains(x.ProjectGuid))
                            {
                                return(-1);
                            }
                            return(0);
                        });
                        ProjectsToBuild = SolutionProjects.ConvertAll(el => el.AbsolutePath);
                    }
                    else
                    {
                        ProjectsToBuild.Add(Path.GetFullPath(CommandLineOptions.Project));
                    }

                    SolutionDir = Path.GetDirectoryName(Path.GetFullPath(CommandLineOptions.Solution));
                    SolutionDir = SolutionDir.Replace(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
                    if (SolutionDir.Last() != Path.AltDirectorySeparatorChar)
                    {
                        SolutionDir += Path.AltDirectorySeparatorChar;
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine("Failed to parse solution file " + CommandLineOptions.Solution + "!");
                    Console.WriteLine("Exception: " + e.ToString());
                    return;
                }
            }
            else if (!string.IsNullOrEmpty(CommandLineOptions.Project))
            {
                ProjectsToBuild.Add(Path.GetFullPath(CommandLineOptions.Project));
            }

            List <MSFBProject> EvaluatedProjects = new List <MSFBProject>();

            for (int i = 0; i < ProjectsToBuild.Count; ++i)
            {
                EvaluateProjectReferences(ProjectsToBuild[i], EvaluatedProjects, null);
            }

            int ProjectsBuilt = 0;

            foreach (MSFBProject project in EvaluatedProjects)
            {
                CurrentProject = project;

                string VCTargetsPath = CurrentProject.Proj.GetPropertyValue("VCTargetsPathEffective");
                if (string.IsNullOrEmpty(VCTargetsPath))
                {
                    VCTargetsPath = CurrentProject.Proj.GetPropertyValue("VCTargetsPath");
                }
                if (string.IsNullOrEmpty(VCTargetsPath))
                {
                    Console.WriteLine("Failed to evaluate VCTargetsPath variable on " + Path.GetFileName(CurrentProject.Proj.FullPath) + "!");
                    continue;
                }

                bool   useBuiltinDll = true;
                string BuildDllName  = "Microsoft.Build.CPPTasks.Common.dll";
                string BuildDllPath  = VCTargetsPath + BuildDllName;
                if (File.Exists(BuildDllPath))
                {
                    CPPTasksAssembly = Assembly.LoadFrom(BuildDllPath);
                    if (CPPTasksAssembly.GetType("Microsoft.Build.CPPTasks.CL") != null &&
                        CPPTasksAssembly.GetType("Microsoft.Build.CPPTasks.RC") != null &&
                        CPPTasksAssembly.GetType("Microsoft.Build.CPPTasks.Link") != null &&
                        CPPTasksAssembly.GetType("Microsoft.Build.CPPTasks.LIB") != null)
                    {
                        useBuiltinDll = false;
                    }
                }
                if (useBuiltinDll)
                {
                    CPPTasksAssembly = Assembly.LoadFrom(AppDomain.CurrentDomain.BaseDirectory + BuildDllName);
                }

                BFFOutputFilePath = Path.GetDirectoryName(CurrentProject.Proj.FullPath) + "\\" + Path.GetFileName(CurrentProject.Proj.FullPath) + "_" + CommandLineOptions.Config.Replace(" ", "") + "_" + CommandLineOptions.Platform.Replace(" ", "") + ".bff";
                GenerateBffFromVcxproj(CommandLineOptions.Config, CommandLineOptions.Platform);
                Console.WriteLine("BFF: {0}\r\n", BFFOutputFilePath);
                if (!CommandLineOptions.GenerateOnly)
                {
                    if (HasCompileActions && !ExecuteBffFile(CurrentProject.Proj.FullPath))
                    {
                        break;
                    }
                    else
                    {
                        ProjectsBuilt++;
                    }
                }
            }

            Console.WriteLine(ProjectsBuilt + "/" + EvaluatedProjects.Count + " built.");
        }
 public override void WriteXMLCommentLine(SolutionFile File, string Text)
 {
     File.WriteLine(SolutionFileTextFragment.Comment, "''' " + Text);
 }
Exemple #34
0
        public void Find()
        {
            var sln = SolutionFile.Find("Gu.Roslyn.Asserts.sln");

            Assert.AreEqual("Gu.Roslyn.Asserts.sln", sln.Name);
        }
 public override void WriteAssemblyAttributeNamespace(SolutionFile File, string Namespace, Action Body)
 {
     Body();
 }
        public StockUltraApplicationBuilder(
                Action<SolutionFile> AddFile,
                SolutionBuilder Context,
                XElement ItemGroupForCompile,
                Action<SolutionProjectLanguageType> NotifyStartupType)
        {
            Context.Interactive.Initialize();

            Func<string, string> ToProjectFile =
                f => Context.Name + "/" + Context.Name + "/" + f;

            #region AddProjectFile
            Func<string, string, SolutionFile> AddProjectFile =
                (f, t) =>
                {
                    var r = new SolutionFile
                    {
                        Name = ToProjectFile(f),
                        Content = t,
                        Context = Context
                    };

                    AddFile(
                        r
                    );

                    return r;
                };
            #endregion

            #region AssemblyInfo

            AssemblyInfoFolder = "Properties";

            if (Context.Language == KnownLanguages.VisualBasic)
                AssemblyInfoFolder = "My Project";

            var AssemblyInfo =
                new SolutionFile
                {
                    Name = ToProjectFile(AssemblyInfoFolder + "/AssemblyInfo" + Context.Language.CodeFileExtension),
                };


            {
                AssemblyInfo.Write(Context.Language, Context, new[] { Context.Interactive.FileHeader });

                AssemblyInfo.WriteLine();

                Context.Language.WriteAssemblyAttributeNamespace(AssemblyInfo, Context.Name,
                    delegate
                    {
                        Context.Language.WriteUsingNamespace(AssemblyInfo, "System.Reflection");

                        AssemblyInfo.WriteLine();

                        // language write assembly attribute

                        Action<string, string> WriteGeneralInformation =
                            (TypeName, Constant) =>
                            {
                                Context.Language.WriteAssemblyAttribute(
                                    AssemblyInfo,
                                    new StockAttributeGeneralInformation(
                                        new SolutionProjectLanguageType { Name = TypeName, Namespace = "System.Reflection" },
                                        Constant
                                    ),
                                    Context
                                );
                            };

                        Context.Language.WriteIndentedComment(AssemblyInfo,
@"General Information about an assembly is controlled through the following 
set of attributes. Change these attribute values to modify the information
associated with an assembly."
                        );

                        //[assembly: AssemblyTitle("Ultra Application")]
                        //[assembly: AssemblyDescription("Ultra Application. Write javascript, flash and java applets within a C# project. http://jsc-solutions.net")]
                        //[assembly: AssemblyConfiguration("")]
                        //[assembly: AssemblyCompany("jsc-solutions.net")]
                        //[assembly: AssemblyProduct("UltraApplication")]
                        //[assembly: AssemblyCopyright("Copyright © jsc-solutions.net 2010")]

                        WriteGeneralInformation("AssemblyTitle", Context.Name);
                        WriteGeneralInformation("AssemblyDescription", Context.Description);
                        WriteGeneralInformation("AssemblyCompany", Context.Company);


                        WriteGeneralInformation("AssemblyProduct", Context.Name.Replace(" ", ""));
                        WriteGeneralInformation("AssemblyCopyright", "Copyright © " + Context.Company + " " + DateTime.Now.Year);
                        WriteGeneralInformation("AssemblyVersion", "1.0.0.0");
                        WriteGeneralInformation("AssemblyFileVersion", "1.0.0.0");

                        Context.Language.WriteAssemblyAttribute(
                            AssemblyInfo,
                            new StockAttributeObfuscation(),
                            Context
                        );
                    }
                );

            }

            ItemGroupForCompile.Add(
                new XElement("Compile",
                    new XAttribute("Include",
                        AssemblyInfoFolder + @"\AssemblyInfo" + Context.Language.CodeFileExtension
                    )
                )
            );


            AddFile(AssemblyInfo);
            #endregion




            #region Design/App.css
            var DesignStyle =
               new SolutionFile
               {
                   Name = ToProjectFile("Design/App.css"),
                   Content = "h1 { color: blue; }"
               };

            ItemGroupForCompile.Add(
                new XElement("Content",
                    new XAttribute("Include",
                        @"Design\App.css"
                    )
                )
            );

            AddFile(DesignStyle);

            #endregion

            #region Design/App.htm
            var DefaultPageElement =
                new XElement("html",
                    new XElement("head",
                // visual studio does
                        new XElement("title", "App")
                    ),
                    Context.ApplicationPage
                );

            var DefaultPage =
                new SolutionFile
                {
                    Name = ToProjectFile("Design/App.htm"),
                };

            DefaultPage.WriteHTMLElement(DefaultPageElement);


            ItemGroupForCompile.Add(
                new XElement("Content",
                    new XAttribute("Include",
                        @"Design\App.htm"
                    )
                )
            );

            AddFile(DefaultPage);

            #endregion


            #region RaiseGenerateHTMLFiles
            Context.Interactive.RaiseGenerateHTMLFiles(
                item =>
                {
                    var f =
                        new SolutionFile
                        {
                            Name = ToProjectFile(item.Name),
                            DependentUpon = DefaultPage
                        };

                    f.WriteHTMLElement(item.Content);

                    ItemGroupForCompile.Add(
                        new XElement("Content",
                            new XAttribute("Include",
                                item.Name.Replace("/", "\\")
                            ),
                            new XElement("DependentUpon", DefaultPage.Name.SkipUntilLastIfAny("/"))

                        )
                    );

                    AddFile(f);

                }
            );
            #endregion

            var AddTypeFiles = new Dictionary<SolutionProjectLanguageType, SolutionFile>();

            #region AddTypeWithoutMerge
            Action<SolutionProjectLanguageType, string> AddTypeWithoutMerge =
                (SourceType, IncludeName) =>
                {
                    var Folder = SourceType.Namespace.SkipUntilIfAny(Context.Name + ".");
                    var Include = "";

                    if (Folder != "")
                        if (Folder != Context.Name)
                            Include += Folder.Replace(".", "/") + "/";

                    Include += IncludeName + Context.Language.CodeFileExtension;

                    var SourceFile =
                        new SolutionFile
                        {
                            Name = ToProjectFile(Include),
                            ContextType = SourceType
                        };

                    AddTypeFiles[SourceType] = SourceFile;

                    Context.Language.WriteType(SourceFile, SourceType, Context);

                    var Compile =
                        new XElement("Compile",
                            new XAttribute("Include",
                                Include.Replace("/", "\\")
                            )
                        );

                    if (SourceType.BaseType != null)
                    {
                        if (SourceType.BaseType is KnownStockTypes.System.Windows.Forms.UserControl)
                            Compile.Add(
                                new XElement("SubType", SourceType.BaseType.Name)
                            );

                        if (SourceType.BaseType is KnownStockTypes.System.ComponentModel.Component)
                            Compile.Add(
                                new XElement("SubType", SourceType.BaseType.Name)
                            );
                    }


                    if (SourceType.DependentUpon != null)
                    {
                        SourceFile.DependentUpon = AddTypeFiles[SourceType.DependentUpon];

                        if (Context.Language.SupportsDependentUpon())
                        {
                            // F# does not?

                            Compile.Add(
                                new XElement("DependentUpon", SourceFile.DependentUpon.Name.SkipUntilLastIfAny("/"))
                            );
                        }
                    }

                    ItemGroupForCompile.Add(Compile);
                    AddFile(SourceFile);
                };
            #endregion

            #region AddType
            Action<SolutionProjectLanguageType> AddType =
                SourceType =>
                {
                    // if partial is not supported then
                    // we need to merge the types
                    // later we may need to have an identity object? :)

                    if (!Context.Language.SupportsPartialTypes())
                    {
                        SourceType.DependentPartialTypes.WithEach(
                              PartialType =>
                              {
                                  SourceType.Fields.AddRange(PartialType.Type.Fields);
                                  SourceType.Methods.AddRange(PartialType.Type.Methods);
                              }
                        );

                        SourceType.DependentPartialTypes = null;
                    }

                    AddTypeWithoutMerge(
                        SourceType,
                        SourceType.Name
                    );

                    SourceType.DependentPartialTypes.WithEach(
                        PartialType =>
                        {
                            PartialType.Type.DependentUpon = SourceType;

                            AddTypeWithoutMerge(
                                PartialType.Type,
                                PartialType.Name
                            );
                        }
                    );
                };
            #endregion



            Context.Interactive.RaiseGenerateTypes(AddType);


            // http://thevalerios.net/matt/2009/01/assembly-information-for-f-console-applications/

            #region ApplicationWebService

            var ApplicationWebServiceType = Context.Interactive.ApplicationWebServiceType;

            ApplicationWebServiceType.Namespace = Context.Name;

            AddType(ApplicationWebServiceType);

            #endregion




            #region Application

            var ApplicationType = Context.Interactive.ApplicationType;

            ApplicationType.Namespace = Context.Name;

            ApplicationType.UsingNamespaces.Add("System");
            ApplicationType.UsingNamespaces.Add("System.Text");
            ApplicationType.UsingNamespaces.Add("System.Linq");
            ApplicationType.UsingNamespaces.Add("System.Xml.Linq");
            ApplicationType.UsingNamespaces.Add("System.Collections.Generic");
            ApplicationType.UsingNamespaces.Add("System.Threading.Tasks");

            ApplicationType.UsingNamespaces.Add("ScriptCoreLib");
            ApplicationType.UsingNamespaces.Add("ScriptCoreLib.JavaScript");
            ApplicationType.UsingNamespaces.Add("ScriptCoreLib.JavaScript.DOM");
            ApplicationType.UsingNamespaces.Add("ScriptCoreLib.JavaScript.DOM.HTML");
            ApplicationType.UsingNamespaces.Add("ScriptCoreLib.JavaScript.Components");
            ApplicationType.UsingNamespaces.Add("ScriptCoreLib.JavaScript.Extensions");
            
            ApplicationType.UsingNamespaces.Add("ScriptCoreLib.JavaScript.Windows.Forms");

            ApplicationType.UsingNamespaces.Add("ScriptCoreLib.Extensions");
            ApplicationType.UsingNamespaces.Add("ScriptCoreLib.Delegates");

            ApplicationType.UsingNamespaces.Add(Context.Name + ".HTML.Pages");
            ApplicationType.UsingNamespaces.Add(Context.Name + ".Design");

            // css

            //var DefaultStyle = new SolutionProjectLanguageType
            //{
            //    Name = "DefaultStyle"
            //};

            //var DefaultStyleField = DefaultStyle.ToInitializedField("style");

            //ApplicationType.Fields.Add(DefaultStyleField);



            var ApplicationConstructor = new StockMethodApplication(
                ApplicationType, Context.Interactive/*, DefaultStyleField*/);

            ApplicationType.Methods.Add(ApplicationConstructor);


            AddType(ApplicationType);

            #endregion


            #region Program

            var ProgramType = Context.Interactive.ProgramType;

            ProgramType.Namespace = Context.Name;


            ProgramType.UsingNamespaces.Add("System");
            ProgramType.UsingNamespaces.Add("jsc.meta.Commands.Rewrite.RewriteToUltraApplication");
            AddType(ProgramType);

            NotifyStartupType(ProgramType);

            #endregion



            #region packages

            new XElement("packages", new XComment("http://my.jsc-solutions.net")).With(
                //new XElement("packages").With(
              packages =>
              {
                  Context.NuGetReferences.WithEach(
                      n =>
                          packages.Add(
                              new XElement("package",

                                  // why wont it work implicitly?
                                  content: new object[] {
                                        new XAttribute("id", n.id),
                                        new XAttribute("version", n.version),
                                        new XAttribute("targetFramework", "net40")
                                    }

                              )
                          )
                  );

                  ItemGroupForCompile.Add(
                      new XElement("None",
                          new XAttribute("Include",
                              "packages.config"
                          )
                      )
                  );


                  var packages_config = new SolutionFile
                  {
                      Name = ToProjectFile("packages.config"),

                  };

                  packages_config.WriteXElement(packages);

                  AddFile(packages_config);
              }
          );
            #endregion
        }
        public override void WritePseudoExpression(SolutionFile File, object Parameter, SolutionBuilder Context)
        {
            var Code = Parameter as string;

            if (Code != null)
            {
                File.Write(Code);
                return;
            }


            var Argument = Parameter as SolutionProjectLanguageArgument;

            if (Argument != null)
            {
                File.Write(Argument.Name);
                return;
            }

            {
                var Constant = Parameter as PseudoStringConstantExpression;
                if (Constant != null)
                {
                    var Value = (string)Constant.Value;
                    File.Write(SolutionFileTextFragment.String,
                               // jsc escape string
                               "\"" + Value.Replace("\"", "\"\"") + "\""
                               );
                    return;
                }
            }


            {
                var Constant = Parameter as PseudoInt32ConstantExpression;
                if (Constant != null)
                {
                    File.Write("" + Constant.Value);
                    return;
                }
            }

            {
                var Constant = Parameter as PseudoDoubleConstantExpression;
                if (Constant != null)
                {
                    var Value = "" + Constant.Value;
                    if (!Value.Contains("."))
                    {
                        Value += ".0";
                    }

                    File.Write(Value);
                    return;
                }
            }

            var Call = Parameter as PseudoCallExpression;

            if (Call != null)
            {
                WritePseudoCallExpression(File, Call, Context);
                return;
            }

            var This = Parameter as PseudoThisExpression;

            if (This != null)
            {
                File.Write(Keywords.Me);
                return;
            }

            var Base = Parameter as PseudoBaseExpression;

            if (Base != null)
            {
                File.Write(Keywords.MyBase);
                return;
            }


            var Type = Parameter as SolutionProjectLanguageType;

            if (Type != null)
            {
                File.Write(Keywords.@GetType);
                File.Write("(");
                WriteTypeName(File, Type);
                File.Write(")");
                return;
            }

            var XElement = Parameter as XElement;

            if (XElement != null)
            {
                var x = File.IndentStack;

                var xx = XElement.Nodes().Last() as XText;
                if (xx != null)
                {
                    var Padding = xx.Value.SkipUntilLastOrEmpty("\n");
                    File.Write(Padding);
                }

                File.IndentStack = new Stack <Action>();
                File.WriteXElement(XElement);

                File.IndentStack = x;
                File.WriteLine();
                File.WriteIndent();
                return;
            }

            var Method = Parameter as SolutionProjectLanguageMethod;

            if (Method != null)
            {
                WriteMethod(File, Method, Context);
                return;
            }

            // F# match would be awesome here? :)
            var Field = Parameter as SolutionProjectLanguageField;

            if (Field != null)
            {
                // DeclaringType Object?
                File.Write(Field.Name);
                return;
            }
        }
        private IEnumerable <(string, ProjectIdInfo)> GetProjectPathsAndIdsFromSolutionOrFilter(string solutionOrFilterFilePath)
        {
            _logger.LogInformation($"Detecting projects in '{solutionOrFilterFilePath}'.");

            var solutionFilePath = solutionOrFilterFilePath;

            var projectFilter = ImmutableHashSet <string> .Empty;

            if (SolutionFilterReader.IsSolutionFilterFilename(solutionOrFilterFilePath) &&
                !SolutionFilterReader.TryRead(solutionOrFilterFilePath, out solutionFilePath, out projectFilter))
            {
                throw new InvalidSolutionFileException($"Solution filter file was invalid.");
            }

            var solutionFolder    = Path.GetDirectoryName(solutionFilePath);
            var solutionFile      = SolutionFile.ParseFile(solutionFilePath);
            var processedProjects = new HashSet <string>(StringComparer.OrdinalIgnoreCase);
            var result            = new List <(string, ProjectIdInfo)>();

            var solutionConfigurations = new Dictionary <ProjectId, Dictionary <string, string> >();

            foreach (var globalSection in solutionFile.GlobalSections)
            {
                // Try parse project configurations if they are remapped in solution file
                if (globalSection.Name == "ProjectConfigurationPlatforms")
                {
                    _logger.LogDebug($"Parsing ProjectConfigurationPlatforms of '{solutionFilePath}'.");
                    foreach (var entry in globalSection.Properties)
                    {
                        var guid           = Guid.Parse(entry.Name.Substring(0, 38));
                        var projId         = ProjectId.CreateFromSerialized(guid);
                        var solutionConfig = entry.Name.Substring(39);

                        if (!solutionConfigurations.TryGetValue(projId, out var dict))
                        {
                            dict = new Dictionary <string, string>();
                            solutionConfigurations.Add(projId, dict);
                        }
                        dict.Add(solutionConfig, entry.Value);
                    }
                }
            }

            foreach (var project in solutionFile.Projects)
            {
                if (project.IsNotSupported)
                {
                    continue;
                }

                // Solution files contain relative paths to project files with Windows-style slashes.
                var relativeProjectfilePath = project.RelativePath.Replace('\\', Path.DirectorySeparatorChar);
                var projectFilePath         = Path.GetFullPath(Path.Combine(solutionFolder, relativeProjectfilePath));
                if (!projectFilter.IsEmpty &&
                    !projectFilter.Contains(projectFilePath))
                {
                    continue;
                }

                // Have we seen this project? If so, move on.
                if (processedProjects.Contains(projectFilePath))
                {
                    continue;
                }

                if (string.Equals(Path.GetExtension(projectFilePath), ".csproj", StringComparison.OrdinalIgnoreCase))
                {
                    var projectIdInfo = new ProjectIdInfo(ProjectId.CreateFromSerialized(new Guid(project.ProjectGuid)), true);
                    if (solutionConfigurations.TryGetValue(projectIdInfo.Id, out var configurations))
                    {
                        projectIdInfo.SolutionConfiguration = configurations;
                    }
                    result.Add((projectFilePath, projectIdInfo));
                }

                processedProjects.Add(projectFilePath);
            }

            return(result);
        }
Exemple #39
0
        public void Initalize()
        {
            var solutionFilePath = _env.SolutionFilePath;

            if (string.IsNullOrEmpty(solutionFilePath))
            {
                var solutions = Directory.GetFiles(_env.Path, "*.sln");
                var result    = SolutionPicker.ChooseSolution(_env.Path, solutions);

                if (result.Message != null)
                {
                    _logger.WriteInformation(result.Message);
                }

                if (result.Solution == null)
                {
                    return;
                }

                solutionFilePath = result.Solution;
            }

            SolutionFile solutionFile = null;

            _context.SolutionPath = solutionFilePath;

            using (var stream = File.OpenRead(solutionFilePath))
            {
                using (var reader = new StreamReader(stream))
                {
                    solutionFile = SolutionFile.Parse(reader);
                }
            }

            _logger.WriteInformation(string.Format("Detecting projects in '{0}'.", solutionFilePath));

            foreach (var block in solutionFile.ProjectBlocks)
            {
                if (!_supportsProjectTypes.Contains(block.ProjectTypeGuid))
                {
                    if (UnityTypeGuid(block.ProjectName) != block.ProjectTypeGuid)
                    {
                        _logger.WriteWarning("Skipped unsupported project type '{0}'", block.ProjectPath);
                        continue;
                    }
                }

                if (_context.ProjectGuidToWorkspaceMapping.ContainsKey(block.ProjectGuid))
                {
                    continue;
                }

                var projectFilePath = Path.GetFullPath(Path.GetFullPath(Path.Combine(_env.Path, block.ProjectPath.Replace('\\', Path.DirectorySeparatorChar))));

                _logger.WriteInformation(string.Format("Loading project from '{0}'.", projectFilePath));

                var projectFileInfo = CreateProject(projectFilePath);

                if (projectFileInfo == null)
                {
                    continue;
                }

                var projectInfo = ProjectInfo.Create(ProjectId.CreateNewId(projectFileInfo.Name),
                                                     VersionStamp.Create(),
                                                     projectFileInfo.Name,
                                                     projectFileInfo.AssemblyName,
                                                     LanguageNames.CSharp,
                                                     projectFileInfo.ProjectFilePath);

                _workspace.AddProject(projectInfo);

                projectFileInfo.WorkspaceId = projectInfo.Id;

                _context.Projects[projectFileInfo.ProjectFilePath]        = projectFileInfo;
                _context.ProjectGuidToWorkspaceMapping[block.ProjectGuid] = projectInfo.Id;

                _watcher.Watch(projectFilePath, OnProjectChanged);
            }

            foreach (var projectFileInfo in _context.Projects.Values)
            {
                UpdateProject(projectFileInfo);
            }
        }
Exemple #40
0
        public bool Equals(SolutionFile x, SolutionFile y)
        {
            var equals = this.SolutionFileValueEqualityComparer.Equals(x, y);

            return(equals);
        }
Exemple #41
0
        public void GetSolutionConfigurations_ValidArguments(SolutionFile solution, IEnumerable <string> expected)
        {
            var actual = SolutionUtilities.GetSolutionConfigurations(solution);

            Assert.That(actual, Is.EqualTo(expected));
        }
Exemple #42
0
        static void Main(string[] args)
        {
            Parser parser = new Parser();

            if (!parser.ParseArguments(args, CommandLineOptions))
            {
                Console.WriteLine(CommandLineOptions.GetUsage());
                return;
            }

            if (string.IsNullOrEmpty(CommandLineOptions.Solution) && string.IsNullOrEmpty(CommandLineOptions.Project))
            {
                Console.WriteLine("No vcxproj or sln provided: nothing to do!");
                Console.WriteLine(CommandLineOptions.GetUsage());
                return;
            }

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

            if (!string.IsNullOrEmpty(CommandLineOptions.Solution) && File.Exists(CommandLineOptions.Solution))
            {
                try
                {
                    if (string.IsNullOrEmpty(CommandLineOptions.Project))
                    {
                        List <ProjectInSolution> SolutionProjects = SolutionFile.Parse(Path.GetFullPath(CommandLineOptions.Solution)).ProjectsInOrder.Where(el => el.ProjectType == SolutionProjectType.KnownToBeMSBuildFormat).ToList();
                        SolutionProjects.Sort((x, y) =>                         //Very dubious sort.
                        {
                            if (x.Dependencies.Contains(y.ProjectGuid))
                            {
                                return(1);
                            }
                            if (y.Dependencies.Contains(x.ProjectGuid))
                            {
                                return(-1);
                            }
                            return(0);
                        });
                        ProjectsToBuild = SolutionProjects.ConvertAll(el => el.AbsolutePath);
                    }
                    else
                    {
                        ProjectsToBuild.Add(Path.GetFullPath(CommandLineOptions.Project));
                    }

                    SolutionDir = Path.GetDirectoryName(Path.GetFullPath(CommandLineOptions.Solution));
                    SolutionDir = SolutionDir.Replace(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
                    if (SolutionDir.Last() != Path.AltDirectorySeparatorChar)
                    {
                        SolutionDir += Path.AltDirectorySeparatorChar;
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine("Failed to load input file: " + CommandLineOptions.Solution + ", exception thrown was: " + e.Message);
                    return;
                }
            }
            else if (!string.IsNullOrEmpty(CommandLineOptions.Project))
            {
                ProjectsToBuild.Add(Path.GetFullPath(CommandLineOptions.Project));
            }

            List <MSFBProject> EvaluatedProjects = new List <MSFBProject>();

            for (int i = 0; i < ProjectsToBuild.Count; ++i)
            {
                EvaluateProjectReferences(ProjectsToBuild[i], EvaluatedProjects, null);
            }

            int ProjectsBuilt = 0;

            foreach (MSFBProject project in EvaluatedProjects)
            {
                CurrentProject = project;
                //MSBuild 15 (2017?) may not provide these properties.
                string VCTargetsPath = CurrentProject.Proj.GetPropertyValue("VCTargetsPath14");
                if (string.IsNullOrEmpty(VCTargetsPath))
                {
                    VCTargetsPath = CurrentProject.Proj.GetPropertyValue("VCTargetsPath");
                }
                if (string.IsNullOrEmpty(VCTargetsPath))
                {
                    VCTargetsPath = CurrentProject.Proj.GetPropertyValue("VCTargetsPathActual");
                }
                if (string.IsNullOrEmpty(VCTargetsPath))
                {
                    Console.WriteLine("Failed to evaluate VCTargetsPath variable on " + Path.GetFileName(CurrentProject.Proj.FullPath) + ". Is this a supported version of Visual Studio?");
                    continue;
                }
                string BuildDllPath = VCTargetsPath + "Microsoft.Build.CPPTasks.Common.dll";
                if (!File.Exists(BuildDllPath))
                {
                    Console.WriteLine("Failed to find " + BuildDllPath + ". Is this a supported version of Visual Studio?");
                    continue;
                }

                CPPTasksAssembly  = Assembly.LoadFrom(BuildDllPath);
                BFFOutputFilePath = Path.GetDirectoryName(CurrentProject.Proj.FullPath) + "\\" + Path.GetFileName(CurrentProject.Proj.FullPath) + "_" + CommandLineOptions.Config.Replace(" ", "") + "_" + CommandLineOptions.Platform.Replace(" ", "") + ".bff";
                GenerateBffFromVcxproj(CommandLineOptions.Config, CommandLineOptions.Platform);

                if (!CommandLineOptions.GenerateOnly)
                {
                    if (HasCompileActions && !ExecuteBffFile(CurrentProject.Proj.FullPath, CommandLineOptions.Platform))
                    {
                        break;
                    }
                    else
                    {
                        ProjectsBuilt++;
                    }
                }
            }

            Console.WriteLine(ProjectsBuilt + "/" + EvaluatedProjects.Count + " built.");
        }
Exemple #43
0
        private (IReadOnlyCollection <ProjectGraphEntryPoint> NewEntryPoints, IReadOnlyDictionary <string, IReadOnlyCollection <string> > SolutionDependencies) ExpandSolutionIfPresent(IReadOnlyCollection <ProjectGraphEntryPoint> entryPoints)
        {
            if (entryPoints.Count == 0 || !entryPoints.Any(e => FileUtilities.IsSolutionFilename(e.ProjectFile)))
            {
                return(entryPoints, null);
            }

            if (entryPoints.Count != 1)
            {
                throw new ArgumentException(
                          ResourceUtilities.FormatResourceStringIgnoreCodeAndKeyword(
                              "StaticGraphAcceptsSingleSolutionEntryPoint",
                              string.Join(";", entryPoints.Select(e => e.ProjectFile))));
            }

            ErrorUtilities.VerifyThrowArgument(entryPoints.Count == 1, "StaticGraphAcceptsSingleSolutionEntryPoint");

            var solutionEntryPoint       = entryPoints.Single();
            var solutionGlobalProperties = ImmutableDictionary.CreateRange(
                keyComparer: StringComparer.OrdinalIgnoreCase,
                valueComparer: StringComparer.OrdinalIgnoreCase,
                items: solutionEntryPoint.GlobalProperties ?? ImmutableDictionary <string, string> .Empty);

            var solution = SolutionFile.Parse(FileUtilities.NormalizePath(solutionEntryPoint.ProjectFile));

            if (solution.SolutionParserWarnings.Count != 0 || solution.SolutionParserErrorCodes.Count != 0)
            {
                throw new InvalidProjectFileException(
                          ResourceUtilities.FormatResourceStringIgnoreCodeAndKeyword(
                              "StaticGraphSolutionLoaderEncounteredSolutionWarningsAndErrors",
                              solutionEntryPoint.ProjectFile,
                              string.Join(";", solution.SolutionParserWarnings),
                              string.Join(";", solution.SolutionParserErrorCodes)));
            }

            var projectsInSolution = GetBuildableProjects(solution);

            var currentSolutionConfiguration = SelectSolutionConfiguration(solution, solutionGlobalProperties);

            var newEntryPoints = new List <ProjectGraphEntryPoint>(projectsInSolution.Count);

            foreach (var project in projectsInSolution)
            {
                if (project.ProjectConfigurations.Count == 0)
                {
                    continue;
                }

                var projectConfiguration = SelectProjectConfiguration(currentSolutionConfiguration, project.ProjectConfigurations);

                if (projectConfiguration.IncludeInBuild)
                {
                    newEntryPoints.Add(
                        new ProjectGraphEntryPoint(
                            FileUtilities.NormalizePath(project.AbsolutePath),
                            solutionGlobalProperties
                            .SetItem("Configuration", projectConfiguration.ConfigurationName)
                            .SetItem("Platform", projectConfiguration.PlatformName)
                            ));
                }
            }

            newEntryPoints.TrimExcess();

            return(newEntryPoints, GetSolutionDependencies(solution));

            IReadOnlyCollection <ProjectInSolution> GetBuildableProjects(SolutionFile solutionFile)
            {
                return(solutionFile.ProjectsInOrder.Where(p => p.ProjectType == SolutionProjectType.KnownToBeMSBuildFormat).ToImmutableArray());
            }

            SolutionConfigurationInSolution SelectSolutionConfiguration(SolutionFile solutionFile, ImmutableDictionary <string, string> globalProperties)
            {
                var solutionConfiguration = globalProperties.ContainsKey("Configuration")
                    ? globalProperties["Configuration"]
                    : solutionFile.GetDefaultConfigurationName();

                var solutionPlatform = globalProperties.ContainsKey("Platform")
                    ? globalProperties["Platform"]
                    : solutionFile.GetDefaultPlatformName();

                return(new SolutionConfigurationInSolution(solutionConfiguration, solutionPlatform));
            }

            ProjectConfigurationInSolution SelectProjectConfiguration(
                SolutionConfigurationInSolution solutionConfig,
                IReadOnlyDictionary <string, ProjectConfigurationInSolution> projectConfigs)
            {
                // implements the matching described in https://docs.microsoft.com/en-us/visualstudio/ide/understanding-build-configurations?view=vs-2019#how-visual-studio-assigns-project-configuration

                var solutionConfigFullName = solutionConfig.FullName;

                if (projectConfigs.ContainsKey(solutionConfigFullName))
                {
                    return(projectConfigs[solutionConfigFullName]);
                }

                var partiallyMarchedConfig = projectConfigs.FirstOrDefault(pc => pc.Value.ConfigurationName.Equals(solutionConfig.ConfigurationName, StringComparison.OrdinalIgnoreCase)).Value;

                return(partiallyMarchedConfig ?? projectConfigs.First().Value);
            }

            IReadOnlyDictionary <string, IReadOnlyCollection <string> > GetSolutionDependencies(SolutionFile solutionFile)
            {
                var solutionDependencies = new Dictionary <string, IReadOnlyCollection <string> >();

                foreach (var projectWithDependencies in solutionFile.ProjectsInOrder.Where(p => p.Dependencies.Count != 0))
                {
                    solutionDependencies[FileUtilities.NormalizePath(projectWithDependencies.AbsolutePath)] = projectWithDependencies.Dependencies.Select(
                        dependencyGuid =>
                    {
                        // code snippet cloned from SolutionProjectGenerator.AddPropertyGroupForSolutionConfiguration

                        if (!solutionFile.ProjectsByGuid.TryGetValue(dependencyGuid, out var dependencyProject))
                        {
                            // If it's not itself part of the solution, that's an invalid solution
                            ProjectFileErrorUtilities.VerifyThrowInvalidProjectFile(
                                dependencyProject != null,
                                "SubCategoryForSolutionParsingErrors",
                                new BuildEventFileInfo(solutionFile.FullPath),
                                "SolutionParseProjectDepNotFoundError",
                                projectWithDependencies.ProjectGuid,
                                dependencyGuid);
                        }

                        // Add it to the list of dependencies, but only if it should build in this solution configuration
                        // (If a project is not selected for build in the solution configuration, it won't build even if it's depended on by something that IS selected for build)
                        // .. and only if it's known to be MSBuild format, as projects can't use the information otherwise
                        return(dependencyProject?.ProjectType == SolutionProjectType.KnownToBeMSBuildFormat
                                ? FileUtilities.NormalizePath(dependencyProject.AbsolutePath)
                                : null);
                    })
                                                                                                              .Where(p => p != null)
                                                                                                              .ToArray();
                }

                return(solutionDependencies);
            }
        }
 internal SolutionContext(string fileName)
 {
     FileName      = fileName;
     _solutionFile = SolutionFile.Parse(fileName);
 }
Exemple #45
0
        public void ProjectReferencesDeterminedInCrossTargetingBuild()
        {
            Dictionary <string, string> globalProperties = new Dictionary <string, string>
            {
                ["SlnGenLaunchVisualStudio"] = "false",
            };

            ProjectCollection projectCollection = new ProjectCollection(globalProperties);

            ProjectCreator
            .Create(Path.Combine(TestRootPath, "Directory.Build.props"))
            .Save();
            ProjectCreator
            .Create(Path.Combine(TestRootPath, "Directory.Build.targets"))
            .Import(Path.Combine(Environment.CurrentDirectory, "build", "Microsoft.VisualStudio.SlnGen.targets"), condition: "'$(IsCrossTargetingBuild)' != 'true'")
            .Import(Path.Combine(Environment.CurrentDirectory, "buildMultiTargeting", "Microsoft.VisualStudio.SlnGen.targets"), condition: "'$(IsCrossTargetingBuild)' == 'true'")
            .Save();

            ProjectCreator projectA = ProjectCreator.Templates
                                      .SdkCsproj(
                Path.Combine(TestRootPath, "ProjectA", "ProjectA.csproj"),
                targetFramework: "netcoreapp2.0")
                                      .Save();

            ProjectCreator projectB = ProjectCreator.Templates
                                      .SdkCsproj(
                Path.Combine(TestRootPath, "ProjectB", "ProjectB.csproj"),
                targetFramework: "net46")
                                      .Save();

            ProjectCreator projectC = ProjectCreator.Templates
                                      .SdkCsproj(
                Path.Combine(TestRootPath, "ProjectC", "ProjectC.csproj"),
                targetFramework: "net46")
                                      .ItemProjectReference(projectA)
                                      .Save();

            ProjectCreator projectD = ProjectCreator.Templates
                                      .SdkCsproj(
                Path.Combine(TestRootPath, "ProjectD", "ProjectD.csproj"),
                targetFramework: "net46")
                                      .ItemProjectReference(projectB)
                                      .ItemProjectReference(projectC)
                                      .Save();

            ProjectCreator mainProject = ProjectCreator
                                         .Create(
                Path.Combine(TestRootPath, "ProjectE", "ProjectE.csproj"),
                sdk: "Microsoft.NET.Sdk",
                projectCollection: projectCollection,
                projectFileOptions: NewProjectFileOptions.None)
                                         .PropertyGroup()
                                         .Property("TargetFrameworks", "net46;netcoreapp2.0")
                                         .Property("SlnGenAssemblyFile", Path.Combine(Environment.CurrentDirectory, "slngen.exe"))
                                         .ItemProjectReference(projectA, condition: "'$(TargetFramework)' == 'netcoreapp2.0'")
                                         .ItemProjectReference(projectB, condition: "'$(TargetFramework)' == 'net46'")
                                         .ItemProjectReference(projectC, condition: "'$(TargetFramework)' == 'net46'")
                                         .ItemProjectReference(projectD, condition: "'$(TargetFramework)' == 'net46'")
                                         .Save()
                                         .TryBuild("SlnGen", out bool result, out BuildOutput buildOutput, out _);

            result.ShouldBeTrue(buildOutput.GetConsoleLog());

            string expectedSolutionFilePath = Path.ChangeExtension(mainProject.FullPath, ".sln");

            File.Exists(expectedSolutionFilePath).ShouldBeTrue();

            SolutionFile solutionFile = SolutionFile.Parse(expectedSolutionFilePath);

            solutionFile.ProjectsInOrder.Select(i => Path.GetFullPath(i.AbsolutePath)).ShouldBe(new string[]
            {
                mainProject,
                projectA,
                projectB,
                projectC,
                projectD,
            });
        }
        static JObject ParseSolution(string file, JObject args)
        {
            var projects = ProjectHelpers.GetProjects(SolutionFile.Parse(file), ParamsToDic(args));

            return(Jsonify.ToJson(projects));
        }
        private void OnChanged(object source, FileSystemEventArgs e)
        {
            lock (r_watcher)
            {
                try
                {
                    WaitForFileToBeReleased(e.FullPath);

                    var newFilteredSolution = SolutionFile.FromFile(m_filteredSolution.SolutionFullPath);
                    var difference = newFilteredSolution.CompareTo(m_filteredSolution);
                    if (difference != null)
                    {
                        difference.Remove(diff => diff.Identifier.Name.Contains("SccProjectTopLevelParentUniqueName"));
                        if (difference.Subdifferences.Count > 0)
                        {
                            if (r_acceptDifferencesHandler(difference))
                            {
                                var newOriginalSolution = SolutionFile.FromElement((NodeElement)r_filterFile.SourceSolution.ToElement().Apply(difference));
                                newOriginalSolution.Save();
                                m_filteredSolution = newFilteredSolution;
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    // TODO Better handling of error, this assembly shouldn't display UI by itself
                    MessageBox.Show(ex.ToString(), "OnChanged handler");
                }
            }
        }
        private static Project CreateOriginalSolutionProject(
                    SolutionFile sourceSolutionFile)
        {
            var originalSolutionName = Path.GetFileName(sourceSolutionFile.SolutionFullPath);

            var propertyLines = new List<PropertyLine>();
            propertyLines.Add(new PropertyLine(originalSolutionName, originalSolutionName));
            if (sourceSolutionFile.Warnings.Count > 0)
            {
                var warningFileName = originalSolutionName + ".warnings.txt";
                var warningFullPath = Path.Combine(Path.GetDirectoryName(sourceSolutionFile.SolutionFullPath) ?? ".", warningFileName);
                using (var output = File.CreateText(warningFullPath))
                {
                    output.WriteLine("The following warnings were found while parsing the file '{0}': ", originalSolutionName);
                    output.WriteLine();
                    foreach (var warning in sourceSolutionFile.Warnings)
                    {
                        output.WriteLine(warning);
                    }
                }

                propertyLines.Add(new PropertyLine(warningFileName, warningFileName));
            }

            return new Project(
                        null,
                        "{3D86F2A1-6348-4351-9B53-2A75735A2AB4}",
                        KnownProjectTypeGuid.SolutionFolder,
                        "-OriginalSolution-",
                        "-OriginalSolution-",
                        null,
                        new[]
                                {
                                    new Section(
                                        "SolutionItems",
                                        "ProjectSection",
                                        "preProject",
                                        propertyLines)
                                },
                        null,
                        null);
        }
        public override void WritePseudoCallExpression(SolutionFile File, ScriptCoreLib.Ultra.Studio.PseudoExpressions.PseudoCallExpression Lambda, SolutionBuilder Context)
        {
            if (Lambda.Method.IsConstructor)
            {
                File.Write(Keywords.@new);
                File.WriteSpace();
                WriteTypeName(File, Lambda.Method.DeclaringType);
                InternalWriteParameterList(File, Lambda, Context);
                return;
            }

            if (Lambda.Method.OperatorName != null)
            {
                if (Lambda.ParameterExpressions.Length == 2)
                {
                    WritePseudoExpression(File, Lambda.ParameterExpressions[0], Context);
                    File.WriteSpaces(Lambda.Method.OperatorName);
                    WritePseudoExpression(File, Lambda.ParameterExpressions[1], Context);

                    return;
                }
            }


            var Objectless = true;

            if (IsExtensionMethod(Lambda))
            {
                WritePseudoExpression(File, Lambda.ParameterExpressions[0], Context);
                Objectless = false;
            }
            else
            {
                if (Lambda.Method.IsStatic)
                {
                    if (Lambda.Method.DeclaringType != null)
                    {
                        WriteTypeName(File, Lambda.Method.DeclaringType);
                        Objectless = false;
                    }
                }
                else
                {
                    if (Lambda.Object != null)
                    {
                        var Constructor = Lambda.Object as PseudoExpressions.PseudoCallExpression;
                        if (Constructor != null)
                        {
                            if (!Constructor.Method.IsConstructor)
                                Constructor = null;
                        }

                        if (Constructor != null)
                        {
                            File.Write("(");
                        }
                        WritePseudoExpression(File, Lambda.Object, Context);
                        if (Constructor != null)
                        {
                            File.Write(")");
                        }
                        Objectless = false;
                    }
                }
            }



            var Target = Lambda.Method.Name;

            if (Lambda.Method.IsProperty)
            {
                Target = Target.SkipUntilIfAny("set_").SkipUntilIfAny("get_");

            }

            if (!Objectless)
            {
                File.Write(".");
            }

            File.Write(
                new SolutionFileWriteArguments
                {
                    Fragment = SolutionFileTextFragment.None,
                    Text = Target,
                    Tag = Lambda.Method
                }
            );

            if (Lambda.Method.IsProperty)
            {
                if (Lambda.ParameterExpressions.Length == 1)
                {
                    File.WriteSpace();
                    if (Lambda.IsAttributeContext)
                        File.WriteSpace("=");
                    else
                        File.WriteSpace("<-");
                    WritePseudoExpression(File, Lambda.ParameterExpressions[0], Context);
                }

            }
            else
            {
                InternalWriteParameterList(File, Lambda, Context);
            }
        }
        public override void WriteMethodBody(SolutionFile File, SolutionProjectLanguageCode Code, SolutionBuilder Context)
        {
            // should this be an extension method to all languages?

            Action WriteCodeStatements =
                delegate
                {
                    var History = Code.History.ToArray();

                    for (int i = 0; i < History.Length; i++)
                    {
                        var IsReturnStatement = false;

                        Code.OwnerMethod.With(
                            m =>
                            {
                                if (m.ReturnType == null)
                                    return;

                                if (m.IsConstructor)
                                    return;

                                IsReturnStatement = i == History.Length - 1;
                            }
                        );


                        var item = History[i];

                        {
                            var Comment = item as string;
                            if (Comment != null)
                            {
                                File.WriteIndent();
                                this.WriteCommentLine(File, Comment);
                            }
                        }

                        {
                            var Comment = item as SolutionFileComment;
                            if (Comment != null)
                            {
                                Comment.WriteTo(File, this, Context);
                                return;
                            }
                        }

                        var If = item as PseudoIfExpression;

                        if (If != null)
                        {
                            if (If.IsConditionalCompilationDirective)
                            {

                                this.WriteConditionalCompilation(File, If, Context);

                            }
                            else
                            {

                                File.WriteIndent().WriteSpace(Keywords.@if);
                                File.Write("(");
                                WritePseudoExpression(File, If.Expression, Context);
                                File.Write(")");
                                File.WriteLine();

                                WriteMethodBody(File, If.TrueCase, Context);
                                File.WriteLine();

                                if (If.FalseCase != null)
                                {
                                    File.WriteIndent().WriteLine(Keywords.@else);

                                    WriteMethodBody(File, If.FalseCase, Context);
                                }
                            }

                            return;
                        }

                        var Lambda = item as PseudoCallExpression;

                        if (Lambda != null)
                        {
                            if (Code.IsLambdaExpression)
                            {
                                WritePseudoCallExpression(File, Lambda, Context);
                            }
                            else
                            {
                                if (Lambda.Comment != null)
                                    Lambda.Comment.WriteTo(File, this, Context);

                                if (Lambda.Method != null)
                                {
                                    File.WriteIndent();

                                    if (IsReturnStatement)
                                    {
                                        File.WriteSpace(Keywords.@return);
                                    }

                                    WritePseudoCallExpression(File, Lambda, Context);
                                    File.WriteLine(";");
                                }
                            }
                        }
                    }
                };

            Action WriteCodeStatementsAsBlock =
                delegate
                {
                    File.WriteIndent().WriteLine("{");
                    File.Indent(this, WriteCodeStatements);
                    File.WriteIndent().Write("}");
                };

            Code.OwnerIfExpression.With(n => n.IsConditionalCompilationDirective, n => WriteCodeStatementsAsBlock = WriteCodeStatements);

            if (Code.IsLambdaExpression)
                WriteCodeStatementsAsBlock = WriteCodeStatements;

            WriteCodeStatementsAsBlock();
        }
Exemple #51
0
 public void StartFilteredSolutionWatcher(SolutionFile filteredSolution, AcceptDifferencesHandler handler)
 {
     if (this.WatchForChangesOnFilteredSolution && (m_watcher == null))
     {
         m_watcher = new FilteredSolutionWatcher(
                     handler,
                     this,
                     filteredSolution);
         m_watcher.Start();
     }
 }
		public void Process(SolutionFile solutionFile)
		{
			solutionFile.Preamble = preamble;
			new PerProjectCommand((s, p) => transform.ApplyTransform(p.XmlFile));
		}
Exemple #53
0
        static void Run(string solutionPath, string oldProjectName, string newProjectName)
        {
            var(wasFound, oldProjectPath, solutionFolderPath) = findProject();
            if (!wasFound)
            {
                Error($"{oldProjectName} cannot be found in the solution");
            }

            var oldDir         = Path.GetDirectoryName(oldProjectPath);
            var newDir         = Path.Combine(Path.GetDirectoryName(oldDir), newProjectName);
            var newProjectPath = Path.Combine(newDir, $"{newProjectName}{ProjectFileExtension}");

            removeFromSolution();
            gitMove();
            replaceReferences();
            addToSolution();
            updatePaket();
            stageAllChanges();

            if (doesUserAgree("Finished - do you want to run a dotnet build to see whether all went well?"))
            {
                RunTool("dotnet", "build", () =>
                {
                    if (doesUserAgree(
                            "dotnet build returned an error or warning - do you want to rollback all changes?"))
                    {
                        RollbackGit();
                        Abort();
                    }
                });
            }

            if (doesUserAgree("Do you want me to create a commit for you?"))
            {
                var arguments = $"commit -m \"Renamed {oldProjectName} to {newProjectName}\"";
                RunTool("git", arguments, () => { Console.Error.WriteLine($"'git {arguments}' failed"); });
            }

            bool doesUserAgree(string question)
            {
                Console.WriteLine($"{question} [Enter=Yes, any other key=No]");
                var key = Console.ReadKey();

                return(key.Key == ConsoleKey.Enter);
            }

            void stageAllChanges() => RunGit("add .");

            void updatePaket()
            {
                if (Directory.Exists(".paket") &&
                    doesUserAgree("This solution uses paket - do you want to run paket install?"))
                {
                    runDotNet("paket install");
                }
            }

            void replaceReferences()
            {
                var projectFiles = Directory
                                   .EnumerateFiles(".", $"*{ProjectFileExtension}", SearchOption.AllDirectories)
                                   .ToList();

                var(oldReference, newReference) =
                    (searchPattern(oldProjectName), searchPattern(newProjectName));
                projectFiles.ForEach(replaceIn);

                void replaceIn(string projectFile)
                {
                    var contents = File.ReadAllText(projectFile, _projectFileEncoding);

                    contents = contents.Replace(oldReference, newReference);
                    File.WriteAllText(projectFile, contents, _projectFileEncoding);
                }

                string searchPattern(string name) => Path.Combine(name, name) + ProjectFileExtension;
            }

            void gitMove()
            {
                RunGit($"mv {oldDir} {newDir}");
                var oldPath = Path.Combine(newDir, Path.GetFileName(oldProjectPath));

                RunGit($"mv {oldPath} {newProjectPath}");
            }

            void addToSolution() => runDotNet($"sln add -s {solutionFolderPath} {newProjectPath}");
            void removeFromSolution() => runDotNet($"sln remove {oldProjectPath}");

            void runDotNet(string arguments) => RunTool("dotnet", arguments);

            (bool wasFound, string projectPath, string solutionFolder) findProject()
            {
                var solution = SolutionFile.Parse(solutionPath);
                var project  = solution.ProjectsInOrder.FirstOrDefault(p =>
                                                                       p.ProjectName.EndsWith(oldProjectName, StringComparison.InvariantCultureIgnoreCase));

                return(project switch
                {
                    null => (false, null, null),
                    _ when project.ParentProjectGuid == null => (true, project.AbsolutePath, null),
                    _ => (true, project.AbsolutePath,
                          path(solution.ProjectsByGuid[project.ParentProjectGuid]))
                });
        public override void WritePseudoExpression(SolutionFile File, object Parameter, SolutionBuilder Context)
        {
            var Code = Parameter as string;
            if (Code != null)
            {
                File.Write(Code);
                return;
            }

            var Argument = Parameter as SolutionProjectLanguageArgument;
            if (Argument != null)
            {
                File.Write(Argument.Name);
                return;
            }

            {
                var Constant = Parameter as PseudoStringConstantExpression;
                if (Constant != null)
                {
                    var Value = (string)Constant.Value;
                    File.Write(SolutionFileTextFragment.String,
                        // jsc escape string
                        "@\"" + Value.Replace("\"", "\"\"") + "\""
                    );
                    return;
                }
            }

            {
                var Constant = Parameter as PseudoInt32ConstantExpression;
                if (Constant != null)
                {
                    File.Write("" + Constant.Value);
                    return;
                }
            }

            {
                var Constant = Parameter as PseudoDoubleConstantExpression;
                if (Constant != null)
                {
                    var Value = "" + Constant.Value;
                    if (!Value.Contains("."))
                        Value += ".0";

                    File.Write(Value);
                    return;
                }
            }
            var Call = Parameter as PseudoCallExpression;
            if (Call != null)
            {
                WritePseudoCallExpression(File, Call, Context);
                return;
            }

            var This = Parameter as PseudoThisExpression;
            if (This != null)
            {
                File.Write(Keywords.@this);
                return;
            }

            var Base = Parameter as PseudoBaseExpression;
            if (Base != null)
            {
                File.Write(Keywords.@base);
                return;
            }


            var Type = Parameter as SolutionProjectLanguageType;
            if (Type != null)
            {
                File.Write(Keywords.@typeof);
                File.Write("(");
                WriteTypeName(File, Type);
                File.Write(")");
                return;
            }

            var XElement = Parameter as XElement;
            if (XElement != null)
            {
                WritePseudoCallExpression(File, XElement.ToPseudoCallExpression(), Context);
                return;
            }

            var Method = Parameter as SolutionProjectLanguageMethod;
            if (Method != null)
            {
                WriteMethod(File, Method, Context);
                return;
            }

            // F# match would be awesome here? :)
            var Field = Parameter as SolutionProjectLanguageField;
            if (Field != null)
            {
                // DeclaringType Object?
                File.Write(Field.Name);
            }


            #region PseudoArrayExpression
            var Array = Parameter as PseudoArrayExpression;
            if (Array != null)
            {
                File.Indent(this,
                    delegate
                    {
                        File.WriteLine();
                        File.WriteIndent();

                        File.Write(Keywords.@new);
                        File.WriteSpace();

                        WriteTypeName(File, Array.ElementType);
                        File.Write("[]");

                        File.WriteSpace();
                        File.Write("{");

                        File.Indent(this,
                            delegate
                            {
                                File.WriteLine();
                                File.WriteIndent();

                                Func<object, Action> AtWritePseudoExpression = k => () => WritePseudoExpression(File, k, Context);

                                Action WriteSeparator =
                                    delegate
                                    {
                                        File.Write(",");
                                        File.WriteLine();
                                        File.WriteIndent();
                                    };

                                Array.Items.ToArray().Select(AtWritePseudoExpression).SelectWithSeparator(WriteSeparator).Invoke();

                            }
                        );

                        File.WriteLine();
                        File.WriteIndent();

                        File.Write("}");

                    }
                );

                File.WriteLine();
                File.WriteIndent();

                return;
            }
            #endregion

        }
        private bool OpenSolutionResource(SolutionFile sr, string editor)
        {
            if (sr == null) return false;
            if (string.IsNullOrEmpty(sr.FilePath)) return false;
            IVsCommandWindow cmw = (IVsCommandWindow)GetService(typeof(SVsCommandWindow));
            if (cmw == null) return false;

            if (editor == null)
                cmw.ExecuteCommand("of \"" + sr.FilePath + "\"");
            else if (editor.Length == 0)
                cmw.ExecuteCommand("of \"" + sr.FilePath + "\" /editor");
            else
                cmw.ExecuteCommand("of \"" + sr.FilePath + "\" /e:\"" + editor + "\"");

            return true;
        }
Exemple #56
0
 protected void when_writing_solution()
 {
     Solution.Save();
     SlnContent = SlnFile.ReadString();
     Solution   = SolutionFile.Parse(SlnFile);
 }
		protected override void ProcessSolution(SolutionFile toSolution, Reconciliation<SolutionProject> reconciliation) {
			foreach (var project in reconciliation.Removed) {
				toSolution.Add(project);
			}
		}
Exemple #58
0
        /// <summary>
        /// Examines given solution file to collect all projects that are build under given 'configuration|platform'.
        /// This method retrieves their names, project file location and base intermediate output path.
        /// </summary>
        public void CollectProjects()
        {
            SolutionFile solution = SolutionFile.Parse(mSolutionPath);

            if (solution == null)
            {
                throw new ArgumentException(
                          $"The given path '{mSolutionPath}' does not define a visual studio solution.");
            }

            if (solution.SolutionConfigurations == null ||
                !solution.SolutionConfigurations.Any(
                    x => x.ConfigurationName.Equals(mConfiguration) && x.PlatformName.Equals(mPlatform)))
            {
                throw new ArgumentOutOfRangeException(
                          $"The given parameter set '{mConfiguration}|{mPlatform}' does not match an existing solution configuration.");
            }

            if (solution.ProjectsInOrder == null || solution.ProjectsInOrder.Count == 0)
            {
                sLog.Write(LogLevel.Note, "The given solution file does not contain any projects.");
                mFinishProcessing = true;
                return;
            }

            foreach (ProjectInSolution project in solution.ProjectsInOrder)
            {
                // only c# and c++ projects get processed which are build with given "configuration|platform"
                bool isProjectSupported = (Path.GetExtension(project.AbsolutePath).Equals(".csproj") ||
                                           Path.GetExtension(project.AbsolutePath).Equals(".vcxproj")) &&
                                          project.ProjectType == SolutionProjectType.KnownToBeMSBuildFormat;
                if (!isProjectSupported)
                {
                    continue;
                }
                bool isConfigurationBuild = project.ProjectConfigurations.Keys.Any(x =>
                                                                                   x.Equals($"{mConfiguration}|{mPlatform}") && project.ProjectConfigurations[x].IncludeInBuild);
                if (!isConfigurationBuild)
                {
                    continue;
                }

                string packagesConfigPath = Path.Combine(Path.GetDirectoryName(project.AbsolutePath), cPackagesConfig);
                if (File.Exists(packagesConfigPath))
                {
                    // project uses packages.config
                    sLog.Write(LogLevel.Developer, "Found '{0}' for '{1}'.", packagesConfigPath, project.ProjectName);
                    mProjectsToProcess.Add(new ProjectInfo(project.ProjectName, project.AbsolutePath,
                                                           packagesConfigPath, NuGetPackageDependency.PackagesConfig));
                    continue;
                }
                if (Path.GetExtension(project.AbsolutePath).Equals(".vcxproj"))
                {
                    // c++ project is included in build but has no valid NuGet dependencies
                    sLog.Write(LogLevel.Developer, "Found no valid NuGet dependencies for '{0}'", project.ProjectName);
                    mProjectsToProcess.Add(new ProjectInfo(project.ProjectName, project.AbsolutePath, "", NuGetPackageDependency.NoDependencies));
                    continue;
                }

                // project seems to use package reference
                sLog.Write(LogLevel.Developer, "Calculate path to '{0}' for '{1}'.", cProjectAssets, project.ProjectName);
                var    msBuildProject             = new Project(project.AbsolutePath);
                string baseIntermediateOutputPath = msBuildProject.GetPropertyValue("BaseIntermediateOutputPath");
                if (baseIntermediateOutputPath == null)
                {
                    sLog.Write(LogLevel.Error, "The project '{0}' does not define a 'BaseIntermediateOutputPath'", project.ProjectName);
                    mProjectsToProcess.Add(new ProjectInfo(project.ProjectName, project.AbsolutePath, "",
                                                           NuGetPackageDependency.NoDependencies));
                    continue;
                }

                sLog.Write(LogLevel.Developer, "Found BaseIntermediateOutputPath = '{0}'", baseIntermediateOutputPath);
                // calculate path to 'project.assets.json' for given project
                string projectAssetsPath = Path.Combine(baseIntermediateOutputPath, cProjectAssets);
                if (!Path.IsPathRooted(projectAssetsPath))
                {
                    // try 'BaseIntermediateOutputPath' is relative to solution
                    projectAssetsPath = Path.Combine(Path.GetDirectoryName(mSolutionPath),
                                                     baseIntermediateOutputPath, cProjectAssets);
                    if (!File.Exists(projectAssetsPath))
                    {
                        // 'BaseIntermediateOutputPath' is relative to project
                        projectAssetsPath = Path.Combine(Path.GetDirectoryName(project.AbsolutePath),
                                                         baseIntermediateOutputPath, cProjectAssets);
                    }
                }
                if (!File.Exists(projectAssetsPath))
                {
                    // project does not use 'project.assets.json' or no NuGet package is present
                    sLog.Write(LogLevel.Error, "No '{0}' found for '{1}'.", cProjectAssets,
                               project.ProjectName);
                    mProjectsToProcess.Add(new ProjectInfo(project.ProjectName, project.AbsolutePath, "",
                                                           NuGetPackageDependency.NoDependencies));
                    continue;
                }

                mProjectsToProcess.Add(new ProjectInfo(project.ProjectName, project.AbsolutePath, projectAssetsPath,
                                                       NuGetPackageDependency.PackageReference));
                sLog.Write(LogLevel.Developer, "Found '{0}' for '{1}'.", projectAssetsPath, project.ProjectName);
            }
            sLog.Write(LogLevel.Note, "Successful collect all projects for solution.");
            sLog.Write(LogLevel.Note, "--------------------------------------------------------------------------------");
        }
Exemple #59
0
        /// <summary>
        /// This function diplays the name of the Hierarchy node. This function is passed to the 
        /// Hierarchy enumeration routines to process the current node.
        /// </summary>
        /// <param name="hierarchy">Hierarchy of the current node</param>
        /// <param name="itemid">Itemid of the current node</param>
        /// <param name="recursionLevel">Depth of recursion in hierarchy enumeration. We add one tab
        /// for each level in the recursion.</param>
        private void ProcessSolutionNode(IVsHierarchy hierarchy, uint itemid, int recursionLevel)
        {
            int hr;

            // get name
            object objName;
            hr = hierarchy.GetProperty(itemid, (int)__VSHPROPID.VSHPROPID_Name, out objName);

            if (recursionLevel == 0) traversalState.CurrentSolutionName = (string)objName;
            if (recursionLevel == 1) traversalState.CurrentProjectName = (string)objName;

            // skip non-member items (dependencies, files not referenced by the solution)
            object objIsNonMember;
            hr = hierarchy.GetProperty(itemid, (int)__VSHPROPID.VSHPROPID_IsNonMemberItem, out objIsNonMember);
            if (objIsNonMember != null)
                if ((bool)objIsNonMember)
                    return;

            SolutionFile sr = new SolutionFile();
            sr.Name = (string)objName;
            sr.Project = traversalState.CurrentProjectName;
            sr.ItemId = itemid;

            // get canonical filename and last write time
            if (recursionLevel > 0 && itemid != VSConstants.VSITEMID_NIL && itemid != VSConstants.VSITEMID_ROOT)
            {
                try
                {
                    string filePath = "";
                    if (hierarchy.GetCanonicalName(itemid, out filePath) == VSConstants.S_OK)
                    {
                        if (!string.IsNullOrEmpty(filePath) && System.IO.Path.IsPathRooted(filePath))
                        {
                            if (File.Exists(filePath))
                            {
                                sr.FilePath = filePath;
                                sr.LastWriteTime = File.GetLastWriteTime(filePath);
                            }
                        }
                    }
                }
                catch (ArgumentException) { }
                catch (System.Reflection.TargetInvocationException) { }
                catch (Exception) { }
            }

            // Exclude empty names and paths (also non-existent files).
            if (string.IsNullOrEmpty(sr.Name) || string.IsNullOrEmpty(sr.FilePath))
                return;

            // Exclude canonical names that appear to be directories
            if (sr.FilePath.EndsWith("\\") || sr.FilePath.EndsWith("/"))
                return;

            // get icon
            object objIconIndex;
            hr = hierarchy.GetProperty(itemid, (int)__VSHPROPID.VSHPROPID_IconIndex, out objIconIndex);
            if (objIconIndex != null) sr.IconIndex = (int)objIconIndex;
            // TODO: look how to obtain item's icons for display in the list view
            //    -> http://connect.microsoft.com/VisualStudio/feedback/details/520256/cannot-find-icon-for-vs2010-database-project

            solutionFiles.Add(sr);
        }
        public override void WriteMethodBody(SolutionFile File, SolutionProjectLanguageCode Code, SolutionBuilder Context)
        {
            // should this be an extension method to all languages?

            Action WriteCodeStatements =
                delegate
            {
                var History = Code.History.ToArray();

                for (int i = 0; i < History.Length; i++)
                {
                    var IsReturnStatement = false;

                    Code.OwnerMethod.With(
                        m =>
                    {
                        if (m.ReturnType == null)
                        {
                            return;
                        }

                        if (m.IsConstructor)
                        {
                            return;
                        }

                        IsReturnStatement = i == History.Length - 1;
                    }
                        );


                    var item = History[i];


                    #region Comment
                    {
                        var Comment = item as string;
                        if (Comment != null)
                        {
                            File.WriteIndent();
                            this.WriteCommentLine(File, Comment);
                        }
                    }

                    {
                        var Comment = item as SolutionFileComment;
                        if (Comment != null)
                        {
                            Comment.WriteTo(File, this, Context);
                            return;
                        }
                    }
                    #endregion


                    #region If
                    var If = item as PseudoIfExpression;

                    if (If != null)
                    {
                        Func <SolutionFile> WriteDirectiveOrIndent = File.WriteIndent;


                        if (If.IsConditionalCompilationDirective)
                        {
                            WriteDirectiveOrIndent = File.WriteDirective;
                        }

                        WriteDirectiveOrIndent().WriteSpace(Keywords.If);
                        WritePseudoExpression(File, If.Expression, Context);
                        File.WriteSpace();
                        File.WriteLine(Keywords.Then);

                        WriteMethodBody(File, If.TrueCase, Context);

                        if (If.FalseCase != null)
                        {
                            WriteDirectiveOrIndent().WriteLine(Keywords.Else);

                            WriteMethodBody(File, If.FalseCase, Context);
                        }

                        WriteDirectiveOrIndent().WriteSpace(Keywords.End).WriteLine(Keywords.@If);

                        return;
                    }
                    #endregion


                    #region Lambda
                    var Lambda = item as PseudoCallExpression;

                    if (Lambda != null)
                    {
                        if (Code.IsLambdaExpression)
                        {
                            WritePseudoCallExpression(File, Lambda, Context);
                        }
                        else
                        {
                            if (Lambda.Comment != null)
                            {
                                Lambda.Comment.WriteTo(File, this, Context);
                            }

                            if (Lambda.Method != null)
                            {
                                File.WriteIndent();

                                if (IsReturnStatement)
                                {
                                    File.WriteSpace(Keywords.@Return);
                                }


                                WritePseudoCallExpression(File, Lambda, Context);
                                File.WriteLine();
                            }
                        }
                    }
                    #endregion
                }
            };

            if (Code.IsConditionalCompilationDirectiveCode)
            {
                WriteCodeStatements();
            }
            else
            {
                File.Indent(this, WriteCodeStatements);
            }
        }