/// <summary>
        /// Delete the entire project from the server
        /// </summary>
        public static void DeleteProject()
        {
            if (ProjectID == 0)
            {
                DialogResult dialogResult = MessageBox.Show("Please open a project first", "Open Project", MessageBoxButtons.OK);
                return;
            }

            DialogResult dialogResult2 = MessageBox.Show("Warning! This will delete your project locally and from QuantConnect's servers. Are you sure you want to proceed?", "Delete Project From QuantConnect", MessageBoxButtons.YesNo);

            if (dialogResult2 == DialogResult.Yes)
            {
                //Close Visual Studio
                Solution4 soln = (Solution4)QCPluginPackage.ApplicationObject.Solution;
                soln.Close();

                if (ProjectName != "")
                {
                    System.IO.Directory.Delete(Directory + ProjectID + " - " + ProjectName, true);
                }

                //Delete project
                API.ProjectDelete(ProjectID);

                //Reset Project Details:
                ProjectName = "";
                ProjectID   = 0;
                SetButtonsState(false);
            }
            else if (dialogResult2 == DialogResult.No)
            {
                return;
            }
        }
示例#2
0
        public static SolutionFolder AddSolutionFolderEx(this Solution4 solution, string folderName)
        {
            var folder = solution.GetSolutionFolderEx(folderName) ??
                         ((Solution4)solution).AddSolutionFolder(folderName).Object;

            return(folder);
        }
示例#3
0
        public void AddProjectsUnderPathToSolution(Solution4 solution, string folderPath, string pattern = @"*.*proj")
        {
            string[] projFiles = Directory.GetFiles(folderPath, pattern, SearchOption.AllDirectories);

            bool          hadErrors = false;
            StringBuilder errorsb   = new StringBuilder();

            var           slnProjects     = GetProjects();
            List <string> slnProjectNames = new List <string>();

            if (slnProjects != null)
            {
                slnProjectNames = (from p in slnProjects
                                   select p.Name.ToLowerInvariant()).ToList();
            }

            foreach (string path in projFiles)
            {
                try {
                    var pathInfo = new FileInfo(path);
                    if (!slnProjectNames.Contains(pathInfo.Name.ToLowerInvariant()))
                    {
                        Project projectAdded = solution.AddFromFile(path, false);
                    }
                }
                catch (Exception ex) {
                    errorsb.AppendLine(ex.ToString());
                }
            }

            if (hadErrors)
            {
                MessageBox.Show(errorsb.ToString());
            }
        }
示例#4
0
 private static IEnumerable <Project> GetAllProjects(this Solution4 solution)
 {
     return(solution.Projects
            .Cast <Project>()
            .SelectMany(GetChildProjects)
            .Union(solution.Projects.Cast <Project>())
            .Where(p => !string.IsNullOrEmpty(p.FullName ?? string.Empty)));
 }
示例#5
0
        public static SolutionFolder GetSolutionFolderEx(this Solution4 solution, string folderName)
        {
            var solutionFolder = ((Solution2)solution)
                                 .Projects
                                 .OfType <Project>()
                                 .FirstOrDefault(p => p.Name == folderName);

            return(solutionFolder?.Object);
        }
示例#6
0
        public static Project AddProject(this Solution4 solution, string destination, string projectName, string templateName)
        {
            var projectPath  = Path.Combine(destination, projectName);
            var templatePath = solution.GetProjectTemplate(templateName, "CSharp");

            solution.AddFromTemplate(templatePath, projectPath, projectName, false);

            return(solution.GetProject(projectName));
        }
示例#7
0
        public Solution4 GetSolution()
        {
            Solution4 result = null;

            if (_dte2 != null)
            {
                result = ((Solution4)_dte2.Solution);
            }

            return(result);
        }
        private static IEnumerable <Project> GetProjectsInSolution(Solution4 solution)
        {
            List <Project> projects = new List <Project>();

            foreach (Project project in solution.Projects)
            {
                GetProjects(project, projects);
            }

            return(projects);
        }
 private void RestoreLinks(Solution4 dteSolution)
 {
     if (dteSolution != null)
     {
         foreach (Project project in GetProjectsInSolution(dteSolution))
         {
             ErrorHandler.ThrowOnFailure(_solution.GetProjectOfUniqueName(project.UniqueName, out IVsHierarchy hierarchy));
             RestoreLinksForHierarchy(hierarchy);
         }
     }
 }
示例#10
0
        private static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            //var prices = new int[] { 7, 1, 5, 3, 6, 4 };
            var prices = new int[] { 1, 2, 3, 4, 5, 6 };

            var s = new Solution4();

            Console.WriteLine(s.MaxProfit(prices));
        }
示例#11
0
        public void Save()
        {
            DTE2 dte = Globals.DTE;

            if (!dte.HasSolution())
            {
                return;
            }

            Solution4 solution = dte.Solution as Solution4;

            XmlFileSerializer <Options> .Serialize(loadedSettingsFile.FullName, Options.Instance);
        }
        // Add global replacement parameters     
        public void RunStarted(object automationObject, Dictionary<string, string> replacementsDictionary, WizardRunKind runKind, object[] customParams)
        {
            // Place "$saferootprojectname$ in the global dictionary. 
            // Copy from $safeprojectname$ passed in my root vstemplate  
            GlobalDictionary["$saferootprojectname$"] = replacementsDictionary["$safeprojectname$"];

            //Check if WizardRunKind equals AsMultiProject. 
            if (runKind != WizardRunKind.AsMultiProject) return;

            var dte2 = automationObject as DTE2;
            if (dte2 != null) _solution = (Solution4)dte2.Solution;

            //Get existing projects.
            _existingProjects = GetProjects() ?? new Project[0];
        }
示例#13
0
        public void Load()
        {
            DTE2 dte = Globals.DTE;

            if (!dte.HasSolution())
            {
                return;
            }

            Solution4 solution = dte.Solution as Solution4;

            var solutionDirectory = new DirectoryInfo(Path.GetDirectoryName(solution.FullName));

            var parentSettingsFile = new FileInfo(
                solutionDirectory.Parent.FullName +
                Path.DirectorySeparatorChar +
                "default.ivyvisual");

            FileInfo settingsFileToDeserialize = null;

            if (parentSettingsFile.Exists)
            {
                settingsFileToDeserialize = parentSettingsFile;
            }
            else
            {
                var settingsFile = new FileInfo(solution.FullName + ".ivyvisual");

                if (settingsFile.Exists)
                {
                    settingsFileToDeserialize = settingsFile;
                }
                else
                {
                    return;
                }
            }

            loadedSettingsFile = settingsFileToDeserialize;
            Options options = XmlFileSerializer <Options> .Deserialize(settingsFileToDeserialize.FullName);

            Instance.ResolveAndUnresolveReferencesOnOpenAndClose = options.ResolveAndUnresolveReferencesOnOpenAndClose;
            Instance.DependenciesPattern = options.DependenciesPattern;
            Instance.WorkspacePath       = options.WorkspacePath;
            Instance.RetrieveCommand     = options.RetrieveCommand;
        }
示例#14
0
        /// <summary>
        /// The OpenRepositoryAsync.
        /// </summary>
        /// <param name="solutionFilePath">The solutionFilePath<see cref="string"/>.</param>
        /// <returns>The <see cref="Task"/>.</returns>
        public async Task OpenRepositoryAsync(string solutionFilePath)
        {
            if (File.Exists(solutionFilePath))
            {
                await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

                Solution2.OpenSolutionFile(_addToCurrent, solutionFilePath);

                Solution4.EnsureSolutionIsLoaded((uint)__VSBSLFLAGS.VSBSLFLAGS_None);

                Solution2.SaveSolutionElement((uint)__VSSLNSAVEOPTIONS.SLNSAVEOPT_ForceSave, null, 0);

                await _collapser.CollapseSolutionAsync();
            }
            else
            {
                MessageDialog.Show("Solution File Error", $"The soution file {solutionFilePath} does not exist.", MessageDialogCommandSet.Ok);
            }
        }
示例#15
0
        public void Add(Solution4 solution, string projectType, string templateProjectName, string projectName)
        {
            try
            {
                var solutionFileInfo = new FileInfo(solution.FullName);
                var solutionName = solutionFileInfo.Name.Replace(".sln", string.Empty);
                projectName = String.Format("{0}.{1}", solutionName, projectName);
                var projectDirectoryName = string.Format("{0}/{1}", solutionFileInfo.DirectoryName, projectName);

                var templateProjectPath = solution.GetProjectTemplate(projectType, Constants.Language);

                //Add a project
                var project = solution.AddFromTemplate(templateProjectPath, projectDirectoryName, projectName);
            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.Message);
            }
        }
        /// <summary>
        /// Check if project compiles locally
        /// </summary>
        public static bool LocalCompile()
        {
            // Save Files to Project in QC
            bool success;

            // Compile Locally
            Microsoft.Build.Execution.BuildManager buildSolution = new Microsoft.Build.Execution.BuildManager();
            Solution4 soln = (Solution4)QCPluginPackage.ApplicationObject.Solution;

            soln.SolutionBuild.Build(true);
            if (soln.SolutionBuild.LastBuildInfo != 0)
            {
                success = false;
            }
            else
            {
                success = true;
            }
            return(success);
        }
        public void RunStarted(object automationObject,
            Dictionary<string, string> replacementsDictionary,
            WizardRunKind runKind, object[] customParams)
        {
            solution = ((DTE)automationObject).Solution as Solution4;
            try
            {

                InitDictionary();

                foreach (var item in sharedDictionary)
                {
                    replacementsDictionary.Add(item.Key, item.Value);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
示例#18
0
        public override void RunFinished()
        {
            try {
                base.RunFinished();

                // show the dialog
                var form         = new PocWindow();
                var windowResult = form.ShowDialog();

                if (windowResult.HasValue && windowResult.Value)
                {
                    Solution4 solution = GetSolution();

                    if (solution != null)
                    {
                        string projectFolder = RemovePlaceholderProjectCreatedByVs(ProjectName);
                        var    properties    = new Hashtable();
                        if (!string.IsNullOrWhiteSpace(solution.FileName))
                        {
                            properties.Add("SolutionFile", new FileInfo(solution.FileName).FullName);
                            properties.Add("SolutionRoot", new FileInfo(solution.FileName).DirectoryName);
                        }
                        string newFolder = new DirectoryInfo(projectFolder).Parent.FullName;
                        Directory.Delete(projectFolder, true);
                        PowerShellInvoker.Instance.RunPwCreateProjectScript(ProjectName, newFolder, form.TemplateName, form.TemplatePathOrUrl, form.TemplateBranch, properties);
                        AddProjectsUnderPathToSolution(solution, newFolder, "*.*proj");
                    }
                    else
                    {
                        // TODO: Improve
                        throw new ApplicationException("Solution is null");
                    }
                }
            }
            catch (Exception ex) {
                // TODO: Improve this
                MessageBox.Show(ex.ToString());
            }
        }
示例#19
0
        private object CreateProjectLinkTracker(IServiceContainer container, Type serviceType)
        {
            if (container != _package)
            {
                return(null);
            }

            try
            {
                if (typeof(ISProjectLinkTracker) == serviceType)
                {
                    IVsTrackProjectDocuments2 trackProjectDocuments = _package.GetService <IVsTrackProjectDocuments2, SVsTrackProjectDocuments>();
                    IVsSolution solution = _package.GetService <IVsSolution, SVsSolution>();
                    if (solution == null)
                    {
                        _package.ShowInformationalMessageBox("Solution null", "Solution null", false);
                    }
                    IVsOutputWindow outputWindow = _package.GetService <IVsOutputWindow, SVsOutputWindow>();
                    DTE             dte          = _package.GetService <DTE, SDTE>();
                    Solution4       dteSolution  = null;
                    if (dte != null)
                    {
                        dteSolution = (Solution4)dte.Solution;
                    }

                    return(new ProjectLinkTracker(trackProjectDocuments, solution, new OutputWindowLogger(outputWindow), dteSolution));
                }
            }
            catch (NotImplementedException nex)
            {
                _package.ShowInformationalMessageBox(Resources.ProjectLinkerCaption, nex.Message + nex.StackTrace, true);
            }
            catch (Exception ex)
            {
                _package.ShowInformationalMessageBox(Resources.ProjectLinkerCaption, ex.Message, true);
            }

            return(null);
        }
        // Add global replacement parameters
        public void RunStarted(object automationObject, Dictionary <string, string> replacementsDictionary, WizardRunKind runKind, object[] customParams)
        {
            // Place "$saferootprojectname$ in the global dictionary.
            // Copy from $safeprojectname$ passed in my root vstemplate
            GlobalDictionary["$saferootprojectname$"] = replacementsDictionary["$safeprojectname$"];

            //Check if WizardRunKind equals AsMultiProject.
            if (runKind != WizardRunKind.AsMultiProject)
            {
                return;
            }

            var dte2 = automationObject as DTE2;

            if (dte2 != null)
            {
                _solution = (Solution4)dte2.Solution;
            }

            //Get existing projects.
            _existingProjects = GetProjects() ?? new Project[0];
        }
        public override void RunFinished()
        {
            try {
                base.RunFinished();

                Solution4 solution = GetSolution();

                if (solution != null)
                {
                    string projectFolder = RemovePlaceholderProjectCreatedByVs(ProjectName);
                    if (projectFolder == null)
                    {
                        throw new ApplicationException("project folder could not be found");
                    }
                    string newFolder  = new DirectoryInfo(projectFolder).Parent.FullName;
                    var    properties = new Hashtable();
                    if (!string.IsNullOrWhiteSpace(solution.FileName))
                    {
                        properties.Add("SolutionFile", new FileInfo(solution.FileName).FullName);
                        properties.Add("SolutionRoot", new FileInfo(solution.FileName).DirectoryName);
                    }

                    Directory.Delete(projectFolder, true);

                    PowerShellInvoker.Instance.RunPwCreateProjectScript(ProjectName, newFolder, TemplateName, TemplateSource, TemplateSourceBranch, properties);
                    AddProjectsUnderPathToSolution(solution, newFolder, "*.*proj");
                }
                else
                {
                    // TODO: Improve
                    throw new ApplicationException("Solution is null");
                }
            }
            catch (Exception ex) {
                // TODO: Improve this
                MessageBox.Show(ex.ToString());
            }
        }
示例#22
0
        public void AddProjectsUnderPathToSolution(Solution4 solution, string folderPath, string pattern = @"*.*proj")
        {
            string[] projFiles = Directory.GetFiles(folderPath, pattern, SearchOption.AllDirectories);

            bool          hadErrors = false;
            StringBuilder errorsb   = new StringBuilder();

            foreach (string path in projFiles)
            {
                // TODO: Check to see if the project is already added to the solution
                try {
                    Project projectAdded = solution.AddFromFile(path, false);
                    // ProjectHelper.UpdatePackagesPathInProject(projectAdded,GetSolution());
                }
                catch (Exception ex) {
                    errorsb.AppendLine(ex.ToString());
                }
            }

            if (hadErrors)
            {
                MessageBox.Show(errorsb.ToString());
            }
        }
 public void RunStarted(object automationObject, Dictionary <string, string> replacementsDictionary, WizardRunKind runKind, object[] customParams)
 {
     _safeProjectName      = replacementsDictionary["$safeprojectname$"];
     _destinationDirectory = replacementsDictionary["$destinationdirectory$"];
     _solution             = ((automationObject as DTE2).Solution as Solution4);
 }
        public void RunStarted(object automationObject, Dictionary<string, string> replacementsDictionary, WizardRunKind runKind, object[] customParams)
        {
            this.ItemTemplateParams = replacementsDictionary;
            _dte = (DTE)automationObject;
            _solution = (Solution4)dte.Solution;

            OnWizardStart(automationObject);
            WizardCancel += new CancelEventHandler(OnWizardCancel);

            if (this.Pages.Count > 0)
            {
                this.CenterToScreen();

                System.Windows.Forms.DialogResult dlgResult = this.ShowDialog();

                if (dlgResult == System.Windows.Forms.DialogResult.OK)
                {
                    OnWizardFinish();

                } else
                if (dlgResult == System.Windows.Forms.DialogResult.Cancel)
                {
                    throw new WizardCancelledException();
                }
         
            }
           
        }
 public SolutionFolderRepository(Solution4 solution)
 {
     Solution = solution;
 }
        public ProjectLinkTracker(IVsTrackProjectDocuments2 documentTracker, IVsSolution solution, ILogger logger, Solution4 dteSolution = null)
        {
            logger?.Log(string.Format(CultureInfo.CurrentCulture, Resources.InitializingProjectTracker));

            _documentTracker = documentTracker;
            _solution        = solution;
            _logger          = logger;
            ErrorHandler.ThrowOnFailure(documentTracker.AdviseTrackProjectDocumentsEvents(this, out _trackProjectDocumentsCookie));
            ErrorHandler.ThrowOnFailure(solution.AdviseSolutionEvents(this, out _solutionCookie));

            RestoreLinks(dteSolution);
        }
示例#27
0
        public static string GenerateSolution()
        {
            DTE2   dte;
            object obj;
            string outputfolder = "";

            try
            {
                if (SolutionGenerator.SelectedType == CompType.Addon)
                {
                    SolutionGenerator.TemplateFileName = "CSharpAddon.zip";
                }
                else // interpreter
                {
                    SolutionGenerator.TemplateFileName = "CSharpInterpreter.zip";
                }

                // Prefer latest VS
                System.Type type = null;
                if (type == null)
                {
                    type = System.Type.GetTypeFromProgID("VisualStudio.DTE.14.0");
                }
                if (type == null)
                {
                    type = System.Type.GetTypeFromProgID("VisualStudio.DTE.12.0");
                }
                if (type == null)
                {
                    type = System.Type.GetTypeFromProgID("VisualStudio.DTE.11.0");
                }
                if (type == null)
                {
                    type = System.Type.GetTypeFromProgID("VisualStudio.DTE.10.0");
                }

                obj = Activator.CreateInstance(type, true);
                dte = (DTE2)obj;
                Solution4 sln = (Solution4)dte.Solution;

                outputfolder = Path.Combine(TargetFolder, SolutionName);
                string solutionName = SolutionName + ".sln";

                if (Directory.Exists(outputfolder))
                {
                    Directory.Delete(outputfolder, true);
                }

                // Unpack the sufficent template project
                Stream TemplateStream = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream(
                    System.Reflection.Assembly.GetExecutingAssembly().GetName().Name + ".Templates." + SolutionGenerator.TemplateFileName);
                FileStream FileWriter = new FileStream(Path.Combine(SolutionGenerator.ProjectTemplateLocation, SolutionGenerator.TemplateFileName), FileMode.Create);
                using (TemplateStream)
                    using (FileWriter)
                    {
                        TemplateStream.CopyTo(FileWriter);
                    }

                sln.Create(outputfolder, solutionName);

                string TemplatePath = sln.GetProjectTemplate(SolutionGenerator.TemplateFileName, "CSharp");
                sln.AddFromTemplate(TemplatePath, outputfolder, SolutionName, false);
                var project       = sln.Projects.Item(1);
                var dotNetVersion = new FrameworkName(".NETFramework", new Version(4, 0));
                var fullname      = dotNetVersion.FullName;
                project.Properties.Item("TargetFrameworkMoniker").Value = dotNetVersion.FullName;
                sln.Close();
            }
            finally
            {
                obj = dte = null;
            }
            return(outputfolder);
        }
        /// <summary>
        /// Open your QuantConnect project in Visual Studio
        /// </summary>
        /// <param name="selectedProject"></param>
        /// <param name="api"></param>
        /// <param name="projectName"></param>
        public static bool OpenProject(int selectedProject, string projectName, Action enableForm)
        {
            // Don't let user open the same project he's working in
            if (selectedProject == ProjectID)
            {
                DialogResult dialogResult = MessageBox.Show("You are currently working on this project.", "Invalid Operation", MessageBoxButtons.OK);
            }

            ProjectID   = selectedProject;
            ProjectName = CleanInput(projectName);
            // Check if file already exists
            if (!ExistingFileChecker(ProjectName, ProjectID))
            {
                return(false);
            }

            Async.Add(new APIJob(APICommand.OpenProject, (files, errors) =>
            {
                List <File> projectFiles = (List <File>)files;

                // Create Solution
                Solution4 soln = (Solution4)QCPluginPackage.ApplicationObject.Solution;
                soln.Create(Directory + ProjectID + " - " + ProjectName, ProjectName + ".sln");

                // Create Project
                soln.AddFromTemplate(Directory + @"QCTemplate\csQCTemplate.vstemplate", Directory + ProjectID + " - " + ProjectName, ProjectName, false);

                // Add Files to Project:
                foreach (EnvDTE.Project proj in soln.Projects)
                {
                    foreach (var file in proj.ProjectItems)
                    {
                        EnvDTE.ProjectItem item = file as EnvDTE.ProjectItem;
                        if (item.Name == "Class1.cs")
                        {
                            item.Remove();
                        }
                    }

                    foreach (var file in projectFiles)
                    {
                        System.IO.File.WriteAllText(Directory + ProjectID + " - " + ProjectName + @"\" + file.Name, file.Code);

                        //Add files to project:
                        try
                        {
                            proj.ProjectItems.AddFromFile(Directory + ProjectID + " - " + ProjectName + @"\" + file.Name);
                        }

                        catch (SystemException ex)
                        {
                            MessageBox.Show("ERROR: " + ex);
                        }
                    }

                    //Add References
                    var vsProject = proj.Object as VSProject;
                    if (vsProject == null)
                    {
                        continue;
                    }

                    var commonDLL = Directory + @"QCAlgorithm-master\QuantConnect.Algorithm\bin\Debug\QuantConnect.Common.dll";
                    if (!System.IO.File.Exists(commonDLL))
                    {
                        //Download and unzip:
                        API.DownloadQCAlgorithm(Directory);
                    }

                    //Safe to add reference:
                    vsProject.References.Add(commonDLL);
                    vsProject.References.Add(Directory + @"QCAlgorithm-master\QuantConnect.Algorithm\bin\Debug\MathNet.Numerics.dll");
                    vsProject.References.Add(Directory + @"QCAlgorithm-master\QuantConnect.Algorithm\bin\Debug\QuantConnect.Algorithm.dll");
                    vsProject.References.Add(Directory + @"QCAlgorithm-master\QuantConnect.Algorithm\bin\Debug\QuantConnect.Algorithm.Interface.dll");
                }
                //Save & open solution
                soln.SaveAs(Directory + ProjectID + " - " + ProjectName + @"\" + ProjectName + ".sln");
                ProjectLoaded = true;
                if (enableForm != null)
                {
                    enableForm();
                }
            }, selectedProject));
            return(true);
        }
示例#29
0
 public static Project GetProject(this Solution4 solution, string projectName) =>
 solution.GetAllProjects().FirstOrDefault(p => p.Name.Equals(projectName));
示例#30
0
 public ProjectRepository(Solution4 solution)
 {
     Solution = solution;
 }
示例#31
0
        static void Main(string[] args)
        {
            #region Q5
            string q51 = new Solution5().LongestPalindrome("babad");
            Console.WriteLine(q51);
            string q52 = new Solution5().LongestPalindrome("cbbd");
            Console.WriteLine(q52);
            string q53 = new Solution5().LongestPalindrome("ccd");
            Console.WriteLine(q53);
            string q54 = new Solution5().LongestPalindrome("aacdefcaa");
            Console.WriteLine(q54);
            string q55 = new Solution5().LongestPalindrome("a");
            Console.WriteLine(q55);
            string q56 = new Solution5().LongestPalindrome("aa");
            Console.WriteLine(q56);
            string q57 = new Solution5().LongestPalindrome("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
            Console.WriteLine(q57);
            #endregion

            #region Q4
            var q41 = new Solution4().FindMedianSortedArrays(new[] { 1, 3 }, new[] { 2 });
            Console.WriteLine("OK");
            var q42 = new Solution4().FindMedianSortedArrays(new[] { 1, 3 }, new[] { 2, 4 });
            Console.WriteLine("OK");
            #endregion

            #region Q3
            var q30 = new Solution3().LengthOfLongestSubstring("abcabcbb");
            Console.WriteLine(q30);
            var q31 = new Solution3().LengthOfLongestSubstring("bbbbb");
            Console.WriteLine(q31);
            var q32 = new Solution3().LengthOfLongestSubstring("pwwkew");
            Console.WriteLine(q32);
            var q33 = new Solution3().LengthOfLongestSubstring("jlygy");
            Console.WriteLine(q33);
            #endregion

            #region Q2
            var x = new Solution2.ListNode(2)
            {
                next = new Solution2.ListNode(4)
                {
                    next = new Solution2.ListNode(3)
                }
            };

            var y = new Solution2.ListNode(5)
            {
                next = new Solution2.ListNode(6)
                {
                    next = new Solution2.ListNode(4)
                }
            };

            var x1 = new Solution2.ListNode(9);
            var y1 = new Solution2.ListNode(1)
            {
                next = new Solution2.ListNode(9)
                {
                    next = new Solution2.ListNode(9)
                }
            };

            var q2 = new Solution2().AddTwoNumbers(x1, y1);
            Console.Write("ok");
            #endregion

            #region Q1
            var q1 = new Solution1().TwoSum(new[] { 5, 75, 25 }, 100);
            Console.WriteLine(q1);
            #endregion
        }
示例#32
0
        public static void UnresolveProject(Solution4 solution, Projects projects, Project project)
        {
            var solutionDirectoryPath = Path.GetDirectoryName(solution.FullName); // can be moved out side this method
            var projectDirectoryPath = Path.GetDirectoryName(project.FullName);

            VSProject2 vsProject = project.Object as VSProject2;

            // load ivymodules
            List<KeyValuePair<IvyModule, string>> ivyModules = GetIvyModules(project);

            References references = vsProject.References;

            // http://social.msdn.microsoft.com/Forums/en-US/vsx/thread/03d9d23f-e633-4a27-9b77-9029735cfa8d/
            string fullPath = project.Properties.Item("FullPath").Value.ToString();
            string outputPath = project.ConfigurationManager.ActiveConfiguration.Properties.Item("OutputPath").Value.ToString();
            string outputDir = Path.Combine(fullPath, outputPath);

            // very important! we need to delete the output dir since it won't otherwise add references with and hintpath, instead it references the binary to their bin\Debug directory, took forever to understand!
            Directory.Delete(outputDir, true);

            foreach (Reference3 reference in references)
            {
                // do only check for assemlby references which has is a project reference and it its directory should not be a part of the solution. since we don't want to resolve our main project
                if (reference.Type == prjReferenceType.prjReferenceTypeAssembly && reference.SourceProject != null && !reference.SourceProject.FullName.Contains(solutionDirectoryPath))
                {
                    var referenceFileName = Path.GetFileName(reference.Path);

                    IvyModule foundIvyModule = null;
                    string foundIvyModulePath = null;
                    Artifact foundIvyModuleArtifact = null;

                    foreach (KeyValuePair<IvyModule,string> kvp in ivyModules)
                    {
                        IvyModule ivyModule = kvp.Key;
                        string ivyModulePath = kvp.Value;

                        foreach (Artifact artifact in ivyModule.Publications.ArtifactList)
                        {
                            if (artifact.Filename == referenceFileName)
                            {
                                foundIvyModule = ivyModule;
                                foundIvyModulePath = ivyModulePath;
                                foundIvyModuleArtifact = artifact;
                                break;
                            }
                        }

                        if (foundIvyModule != null)
                        {
                            break;
                        }
                    }

                    if (foundIvyModule == null)
                    {
                        Output.Instance.WriteLine("Could not find a matching ivy module for reference '" + reference.Name + "'");
                        continue;
                    }

                    // the calulated path to the binary reference
                    var referenceFile = new FileInfo(GetCalculatedReferencePath(projectDirectoryPath, foundIvyModule, foundIvyModuleArtifact, referenceFileName));

                    Output.Instance.WriteLine("Found a matching ivy module for reference '" + reference.Name + "', assumed path to the binary file is '" + referenceFile.FullName + "'");

                    if (!referenceFile.Exists)
                    {
                        Output.Instance.WriteLine("The reference file does not exist, assure that you'r following the patterns for dependencies.");
                        continue;
                    }

                    reference.Remove();
                    vsProject.References.Add(referenceFile.FullName);
                }
            }

            project.Save(project.FullName);

            if (!projectDirectoryPath.Contains(solutionDirectoryPath))
            {
                solution.Remove(project);
            }
        }
示例#33
0
        private static void ResolveProject(Solution4 solution, Projects projects, Project project)
        {
            var vsProject = project.Object as VSProject2;

            if (vsProject == null)
                return;

            // load ivymodules
            List<KeyValuePair<IvyModule, string>> ivyModules = GetIvyModules(project);

            References references = vsProject.References;

            foreach (Reference3 reference in references)
            {
                if (reference.Type == prjReferenceType.prjReferenceTypeAssembly && reference.SourceProject == null)
                {
                    KeyValuePair<IvyModule, string> matching = ivyModules.SingleOrDefault(kvp => kvp.Key.Publications.ArtifactList.Count(artifact => artifact.Filename == Path.GetFileName(reference.Path)) > 0);

                    if (matching.Key == null || matching.Value == null)
                    {
                        Output.Instance.WriteLine("Could not find a matching ivy module for reference '" + reference.Name + "'");
                        continue;
                    }

                    Output.Instance.WriteLine("Found matching ivy module for reference '" + reference.Name + "'");

                    // project base directory
                    var projectDirectory = new DirectoryInfo(Path.GetDirectoryName(matching.Value));

                    Output.Instance.WriteLine("Ivy modules base directory is '" + projectDirectory.FullName + "'");

                    if (!projectDirectory.Exists)
                    {
                        Output.Instance.WriteLine("The directory does not seem to exist, will skip this reference!");
                        continue;
                    }

                    // find the project file which exists in the directory
                    FileInfo[] projectFiles = projectDirectory.GetFiles("*.csproj", SearchOption.TopDirectoryOnly);

                    if (projectFiles.Length == 0 || projectFiles.Length > 1)
                    {
                        Output.Instance.WriteLine("Could not find a project file in the directory '" + projectDirectory.FullName + "', will skip this reference");
                        continue;
                    }

                    // get the first project file, as a rule it should only exist one
                    FileInfo projectFile = projectFiles.First();

                    Output.Instance.WriteLine("The selected project file for reference '" + reference.Name + "' is '" + projectFile.FullName + "'");

                    Project result = null;

                    // parse thru all existing projects to see if it already has been added
                    foreach (Project proj in projects)
                    {
                        if (proj.FullName == projectFile.FullName)
                            result = proj;
                    }

                    // if the project wasn't added earlier add it, and resolve its references
                    if (result == null)
                    {
                        result = solution.AddFromFile(projectFile.FullName, false);
                        ResolveProject(solution, projects, result);
                    }

                    // remove the old binary reference
                    reference.Remove();
                    vsProject.References.AddProject(result);
                }
            }
        }
示例#34
0
        protected override void RunStartedOverride(Solution4 solution, Dictionary<string, string> replacementsDictionary, object[] customParams)
        {
            _replacementsDictionary = replacementsDictionary;

            var vstemplateName = (string)customParams[0];
            _tmpFolder = Path.GetDirectoryName(vstemplateName);
            replacementsDictionary["$saferootprojectname$"] = replacementsDictionary["$safeprojectname$"];

            var wizardDataFileName = Path.Combine(_tmpFolder, WizardDataLoader.WizardDataFielName);
            var wizardData = WizardDataLoader.LoadAsync(wizardDataFileName).Result;

            _wizardDataViewModel = null;

            if (wizardData == null)
            {
                return;
            }

            var projectName = replacementsDictionary["$projectname$"];

            _wizardDataViewModel = new WizardDataViewModel(wizardData)
            {
                Title = $"{wizardData.Title} - {projectName}"
            };

            var solutions = _wizardDataViewModel.Solutions.ToArray();

            if (solutions.Length == 1)
            {
                var solutionDataViewModel = solutions[0];
                if (solutionDataViewModel.UseOnlyDefautValues)
                {
                    solutionDataViewModel.SelectedVariant = solutionDataViewModel.Variants.First();
                    _wizardDataViewModel.SetSelectedSolution(solutionDataViewModel);
                    return;
                }
            }

            var window = WpfServices.CreateWindow<WizardWindow>(_wizardDataViewModel);
            WpfServices.SetWindowOwner(window, solution.DTE.MainWindow);
            var retVal = window.ShowDialog() ?? false;
            if (!retVal)
            {
                throw new WizardCancelledException();
            }
        }
示例#35
0
        public override void RunFinished()
        {
            try {
                base.RunFinished();

                // check required properties
                var errorSb = new StringBuilder();
                if (string.IsNullOrWhiteSpace(ProjectName))
                {
                    errorSb.AppendLine("ProjectName is null");
                }
                if (string.IsNullOrWhiteSpace(TemplateName))
                {
                    errorSb.AppendLine("TemplateName is null");
                }
                if (string.IsNullOrWhiteSpace(TemplateSource))
                {
                    errorSb.AppendLine("TemplateSource is null");
                }

                if (!string.IsNullOrWhiteSpace(errorSb.ToString()))
                {
                    throw new ApplicationException(errorSb.ToString());
                }

                if (string.IsNullOrWhiteSpace(TemplateSource))
                {
                    TemplateSource = ExtensionInstallDir;
                }

                Solution4 solution = GetSolution();
                if (solution != null)
                {
                    string projectFolder = RemovePlaceholderProjectCreatedByVs(ProjectName);
                    var    properties    = new Hashtable();

                    string slnRoot = SolutionDirectory;
                    if (!string.IsNullOrEmpty(SolutionDirectory))
                    {
                        slnRoot = SolutionDirectory;
                    }
                    if (string.IsNullOrEmpty(slnRoot) && !string.IsNullOrWhiteSpace(solution.FileName))
                    {
                        slnRoot = new FileInfo(solution.FileName).DirectoryName;
                    }
                    if (string.IsNullOrWhiteSpace(slnRoot))
                    {
                        throw new ApplicationException("solution is null");
                    }

                    DirectoryInfo projFolderInfo = new DirectoryInfo(projectFolder);
                    properties.Add("SolutionRoot", slnRoot);
                    string newFolder = new DirectoryInfo(projectFolder).Parent.FullName;
                    Directory.Delete(projectFolder, true);

                    PowerShellInvoker.Instance.RunPwCreateProjectScript(ProjectName, projFolderInfo.FullName, TemplateName, TemplateSource, TemplateSourceBranch, properties);
                    // TODO: allow override of pattern via custom parameter
                    AddProjectsUnderPathToSolution(solution, projFolderInfo.FullName, "*.*proj");
                }
                else
                {
                    throw new ApplicationException("Soluiton is null");
                }
            }
            catch (Exception ex) {
                // TODO: Improve this
                MessageBox.Show(ex.ToString());
            }
        }
示例#36
0
        void IWizard.RunStarted(object automationObject, Dictionary<string, string> replacementsDictionary, WizardRunKind runKind, object[] customParams)
        {
            if (runKind != WizardRunKind.AsMultiProject)
            {
                return;
            }

            DTE2 dtE2 = automationObject as DTE2;
            var solution4 = dtE2.Solution as Solution4;
            if (solution4 != null)
            {
                _solution = (Solution4)dtE2.Solution;
            }

            RunStartedOverride(solution4, replacementsDictionary, customParams);
        }
        public void RunStarted(object automationObject, Dictionary<string, string> replacementsDictionary, Microsoft.VisualStudio.TemplateWizard.WizardRunKind runKind, object[] customParams)
        {
            _replacementsDictionary = replacementsDictionary;

            _dte2 = automationObject as DTE2;
            if (_dte2 != null) _solution = (Solution4)_dte2.Solution;

            if (NewWidgetForm.ShowDialog(replacementsDictionary) == false)
                    throw new WizardCancelledException("The wizard has been cancelled by the user.");

            //_existingProjects = getProjects() ?? new Project[0];
        }
示例#38
0
 protected virtual void RunStartedOverride(Solution4 solution, Dictionary<string, string> replacementsDictionary, object[] customParams)
 {
     
 }
示例#39
0
        public void AddProjectsUnderPathToSolution(Solution4 solution, string folderPath,string pattern=@"*.*proj") {
            string[] projFiles = Directory.GetFiles(folderPath, pattern, SearchOption.AllDirectories);

            bool hadErrors = false;
            StringBuilder errorsb = new StringBuilder();
            foreach (string path in projFiles) {
                // TODO: Check to see if the project is already added to the solution
                try {
                    Project projectAdded = solution.AddFromFile(path, false);
                    // ProjectHelper.UpdatePackagesPathInProject(projectAdded,GetSolution());
                }
                catch(Exception ex) {
                    errorsb.AppendLine(ex.ToString());
                }
            }

            if (hadErrors) {
                MessageBox.Show(errorsb.ToString());
            }
        }
示例#40
0
        private void GenerateSolutionFile()
        {
            string fullPath = Path.Combine(IntDir, _solutionName + ".sln");

            if (File.Exists(fullPath))
            {
                File.Delete(fullPath);
            }

            int  retry   = 100;
            bool success = false;

            while (!success && retry > 0)
            {
                try
                {
                    _dte.Solution.Create(IntDir, _solutionName);

                    success = true;
                }
#if DEBUG
                catch (Exception ex)
#else
                catch
#endif
                {
                    success = false;
                    retry--;

                    if (retry > 0)
                    {
                        System.Threading.Thread.Sleep(150);

#if DEBUG
                        Log.LogMessage(MessageImportance.High, "Exception: " + ex.ToString());
#endif
                    }
                    else
                    {
                        throw;
                    }
                }
            }

            retry   = 100;
            success = false;
            while (!success && retry > 0)
            {
                try
                {
                    _solution = (Solution4)_dte.Solution;
                    success   = true;
                }
#if DEBUG
                catch (Exception ex)
#else
                catch
#endif
                {
                    success = false;
                    retry--;

                    if (retry > 0)
                    {
                        System.Threading.Thread.Sleep(150);

#if DEBUG
                        Log.LogMessage(MessageImportance.High, "Exception: " + ex.ToString());
#endif
                    }
                    else
                    {
                        throw;
                    }
                }
            }
        }
        private void ReadSolutionInfo()
        {
            SolutionState state          = SolutionState.NoSolution;
            string        workspaceName  = string.Empty;
            string        branchLocation = string.Empty;
            string        solutionFile   = string.Empty;
            string        errorMessage   = string.Empty;

            Solution4 sol = (Solution4)_dte2.Solution;

            try
            {
                if (sol.IsOpen == false)
                {
                    state = SolutionState.NoSolution;
                    _trace.TraceEvent(TraceEventType.Verbose, 0, "No Solution Opened");
                }
                else
                {
                    solutionFile = sol.FileName;

                    _trace.TraceEvent(TraceEventType.Information, 0, "Opened Solution: {0}", sol.FullName);

                    if (_vcExt == null)
                    {
                        _trace.TraceEvent(TraceEventType.Information, 0, "No TFS object");
                        state = SolutionState.TfsNotPresent;
                    }
                    else if (_vcExt.SolutionWorkspace == null)
                    {
                        _trace.TraceEvent(TraceEventType.Information, 0, "No TFS Workspace for this Solution ");
                        state = SolutionState.NotInTfs;
                    }
                    else
                    {
                        VersionControlServer vcServer = _vcExt.SolutionWorkspace.VersionControlServer;
                        _trace.TraceEvent(TraceEventType.Verbose, 0, "Connected to TFS Collection: {0}", vcServer.TeamProjectCollection.Name);

                        // find out where the TFS info is.
                        string serverSol = _vcExt.SolutionWorkspace.GetServerItemForLocalItem(sol.FullName);
                        if (string.IsNullOrEmpty(serverSol) == true)
                        {
                            _trace.TraceEvent(TraceEventType.Warning, 0, "Solution file is NOT in TFS");
                            state = SolutionState.NotInTfs;
                        }
                        else
                        {
                            workspaceName  = _vcExt.SolutionWorkspace.Name;
                            branchLocation = TfsHelpers.GetBranchLocationForItem(vcServer, serverSol);
                            _trace.TraceEvent(TraceEventType.Information, 0, "Solution is in Branch: {0}", branchLocation);
                            state = SolutionState.InTfs;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                state = SolutionState.Error;
                _infoService.CurrentSolutionInfo = new TfsInfo(ex);
            }

            if (state != SolutionState.Error)
            {
                _infoService.CurrentSolutionInfo = new TfsInfo(state, solutionFile, branchLocation, workspaceName);
            }
        }
示例#42
0
        public void AddProjectsUnderPathToSolution(Solution4 solution, string folderPath, string pattern = @"*.*proj") {
            string[] projFiles = Directory.GetFiles(folderPath, pattern, SearchOption.AllDirectories);

            bool hadErrors = false;
            StringBuilder errorsb = new StringBuilder();

            var slnProjects = GetProjects();
            List<string> slnProjectNames = new List<string>();
            if(slnProjects != null) {
                slnProjectNames = (from p in slnProjects
                                   select p.Name.ToLowerInvariant()).ToList();
            }

            foreach (string path in projFiles) {                
                try {
                    var pathInfo = new FileInfo(path);
                    if (!slnProjectNames.Contains(pathInfo.Name.ToLowerInvariant())) {
                        Project projectAdded = solution.AddFromFile(path, false);
                    }
                }
                catch (Exception ex) {
                    errorsb.AppendLine(ex.ToString());
                }
            }

            if (hadErrors) {
                MessageBox.Show(errorsb.ToString());
            }
        }