Visual Studio: Printing all source files in a solution? - visual-studio

Is there a way to print all (*.cs) files in a solution at once, that is, without clicking on each of them and then hitting print?

From what I gather from a similar question asked elsewhere, this "feature" is not build into Visual Studio.
However it looks like MSDN has a macro you can use to print all of your code; perhaps you can use this, or something like it:
Sub PrintItemsInSelectedProject()
Dim proj As Project
Dim objProj As Object()
objProj = DTE.ActiveSolutionProjects
If objProj.Length = 0 Then
Exit Sub
End If
proj = DTE.ActiveSolutionProjects(0)
PrintItemsInSelectedProject(proj.ProjectItems)
End Sub
Private Sub PrintItemsInSelectedProject( _
ByVal projitems As ProjectItems)
Dim projitem As ProjectItem
For Each projitem In projitems
If (IsPrintableFile(projitem) = True) Then
If (projitem.IsOpen( _
EnvDTE.Constants.vsViewKindTextView)) Then
projitem.Document.PrintOut()
Else
Dim doc As Document
doc = projitem.Open( _
EnvDTE.Constants.vsViewKindTextView).Document
doc.PrintOut()
doc.Close(vsSaveChanges.vsSaveChangesNo)
End If
End If
PrintItemsInSelectedProject(projitem.ProjectItems)
Next
End Sub
Function IsPrintableFile( _
ByVal projItem As ProjectItem) As Boolean
Dim fileName As String
Dim extensions As _
New System.Collections.Specialized.StringCollection
' If you add a file to your project that is of
' a type that can be printed,
' then add the extension of that
' file type to this list.
Dim exts As String() = {".cs", ".vb", _
".aspx", ".xsd", ".xml", ".xslt", _
".config", ".htm", ".html", ".css", _
".js", ".vbs", ".wsf", ".txt", ".cpp", _
".c", ".h", ".idl", ".def", ".rgs", ".rc"}
extensions.AddRange(exts)
fileName = projItem.FileNames(1)
Return extensions.Contains( _
System.IO.Path.GetExtension(fileName).ToLower())
End Function

Putting aside the fun comments from tree-huggers, let's assume you want to printout the Visual Studio solution as PDF (and we won't ask what you do with it later).
For people who use VisualStudio there is a very nice program that used to be sold but is now available to download for free, called PrettyCode.Print for .NET 2.0. It is available for download here (the company retired the product).
It reads in a VisualStudio project (works with VS2005, VS2008 and VS2010) and let one print a selection of files with various printing options. It does a pretty decent job.

You can download PrettyCode.Print for .NET 2.0 (VS2008 and VS2005) in:http://pan.baidu.com/wap/shareview?&shareid=3968547697&uk=286220058&dir=%2FSoftz&page=1&num=20&fsid=1117386981714891&third=0
In my computer work fine with Visual Studio 2013.

Use powershell to print all *.cs files.
First get list of all files
$files = Get-Childitem -Path C:\Users\David\source\repos\ConsoleApp -Exclude AssemblyInfo.cs, Program.cs -Include *.cs -Recurse
When your happy with list
foreach ($file in $files){ Get-Content $file.FullName |Out-printer}

Related

Excel 2010 to PDF using VB

I have hundreds of Excel files being saved in a folder. I was wondering how I could write something in Visual Basic to convert these to PDF. Is there a way to call to Excel 2010's Save As function to save them in a different folder? I have checked Google and on here and all I can find is references to third party applications.
Dim excel As Microsoft.Office.Interop.Excel.Application
excel = New Microsoft.Office.Interop.Excel.Application
Dim tmpWorkbooks As Workbooks
tmpWorkbooks = excel.Workbooks
Dim wb As Microsoft.Office.Interop.Excel.Workbook
wb = tmpWorkbooks.Open(pathOfExcelFile)
excel.Visible = False
wb.Activate()
wb.ExportAsFixedFormat(XlFixedFormatType.xlTypePDF, fileName, , , , 1, 1, False, )
In Excel 2010 you can use this VBA code:
ActiveSheet.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:="C:\Temp\Workbook1.pdf", _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=True, _
OpenAfterPublish:=False
Of course you need to set Filenameto the correct path for your machine, and as it uses ActiveSheet I suppose you need to iterate through your sheets if you have more than one in your workbooks. See the MSDN for more details on the ExportAsFixedFormat function.

Outputting list of files that are part of a Visual Studio Project

I'm looking for a way to output a list of all files in a Visual Studio project for documentation purposes.
I would have thought this would be possible but I can't find any info. I'm not talking about using Sandcastle to hook up to XML comments, I just want a "simple" indented list of project files.
I'm guessing we could run an xsl file against the Proj file but hopefully somebody has already got a solution for this? Ideally this would work on both 2008 and 2010.
The VS2008 sample macros already contain a macro that practically does this (prints a list of source/header file to the output window). It's called ListProj1, under the Utilities samples. Here's the code in case you don't have it:
Sub ListProj()
Dim project As Project
Dim projectObjects As Object()
Dim window As Window
Dim target As Object
window = DTE.Windows.Item(Constants.vsWindowKindCommandWindow)
projectObjects = DTE.ActiveSolutionProjects
If projectObjects.Length = 0 Then
Exit Sub
End If
project = DTE.ActiveSolutionProjects(0)
If (DTE.ActiveWindow Is window) Then
target = window.Object
Else
target = GetOutputWindowPane("List Project")
target.Clear()
End If
ListProjAux(project.ProjectItems(), 0, target)
End Sub
Sub ListProjAux(ByVal projectItems As EnvDTE.ProjectItems, ByVal level As Integer, ByVal outputWinPane As Object)
Dim projectItem As EnvDTE.ProjectItem
For Each projectItem In projectItems
If projectItem.Collection Is projectItems Then
Dim projectItems2 As EnvDTE.ProjectItems
Dim notSubCollection As Boolean
OutputItem(projectItem, level, outputWinPane)
'' Recurse if this item has subitems ...
projectItems2 = projectItem.ProjectItems
notSubCollection = projectItems2 Is Nothing
If Not notSubCollection Then
ListProjAux(projectItems2, level + 1, outputWinPane)
End If
End If
Next
End Sub
Sub OutputItem(ByVal projectItem As EnvDTE.ProjectItem, ByVal level As Integer, ByVal outputWinPane As Object)
Dim i As Integer = 0
While (i < level)
outputWinPane.OutputString(" ")
i = i + 1
End While
outputWinPane.OutputString(projectItem.FileNames(1))
outputWinPane.OutputString(Microsoft.VisualBasic.Constants.vbCrLf)
End Sub

Report error/warning if missing files in project/solution in Visual Studio

Is there a way for Visual Studio to report an error/warning when you build a solution that has missing files (yellow triangle icon with exclamation) that do have necessarily cause a compile error? Like a missing config file that is read during run-time.
Thanks
You need to define an EnvironmentEvents macro. See the general description on how to do this here: Customize Your Project Build Process.
And here is the code you can directly paste in the macro environment to check missing files:
Private Sub BuildEvents_OnBuildBegin(ByVal Scope As EnvDTE.vsBuildScope, ByVal Action As EnvDTE.vsBuildAction) Handles BuildEvents.OnBuildBegin
For Each proj As Project In DTE.Solution.Projects
For Each item As ProjectItem In proj.ProjectItems
If (item.Kind <> "{6BB5F8EE-4483-11D3-8BCF-00C04F8EC28C}") Then ' only check physical file items
Continue For
End If
For i As Integer = 1 To item.FileCount
Dim path As String = item.FileNames(i)
If Not System.IO.File.Exists(item.FileNames(i)) Then
WriteToBuildWindow("!! Missing file:" & item.FileNames(i) + " in project " + proj.Name)
End If
Next
Next
Next
End Sub
Public Sub WriteToBuildWindow(ByVal text As String)
Dim ow As OutputWindow = DTE.Windows.Item(EnvDTE.Constants.vsWindowKindOutput).Object
Dim build As OutputWindowPane = ow.OutputWindowPanes.Item("Build")
build.OutputString(text & Environment.NewLine)
End Sub
It will display the "missing file" text directly in the Visual Studio "Build" output window. It should be fairly easy to understand and tune to your needs. For example, you could add errors to the error output.
When we had missing files, we were getting crazy compile errors, like unable to write xyz.pdb even though the file ended up getting written. I took what Simon had provided (thanks!) and flipped it around a bit; specifically, I added a bit of recursion and added support for folders and files with sub-files (e.g. datasets, code-behinds).
Private Sub BuildEvents_OnBuildBegin(ByVal Scope As EnvDTE.vsBuildScope, ByVal Action As EnvDTE.vsBuildAction) Handles BuildEvents.OnBuildBegin
For Each proj As Project In DTE.Solution.Projects
walkTree(proj.ProjectItems, False)
Next
End Sub
Private Sub walkTree(ByVal list As ProjectItems, ByVal showAll As Boolean)
For Each item As ProjectItem In list
' from http://msdn.microsoft.com/en-us/library/z4bcch80(v=vs.80).aspx
' physical files: {6BB5F8EE-4483-11D3-8BCF-00C04F8EC28C}
' physical folders: {6BB5F8EF-4483-11D3-8BCF-00C04F8EC28C}
If (item.Kind = "{6BB5F8EE-4483-11D3-8BCF-00C04F8EC28C}" OrElse _
item.Kind = "{6BB5F8EF-4483-11D3-8BCF-00C04F8EC28C}") Then
For i As Integer = 1 To item.FileCount ' appears to be 1 all the time...
Dim existsOrIsFolder As Boolean = (item.Kind = "{6BB5F8EF-4483-11D3-8BCF-00C04F8EC28C}" OrElse System.IO.File.Exists(item.FileNames(i)))
If (showAll OrElse _
existsOrIsFolder = False) Then
WriteToBuildWindow(String.Format("{0}, {1}, {2} ", existsOrIsFolder, item.ContainingProject.Name, item.FileNames(i)))
End If
Next
If (item.ProjectItems.Count > 0) Then
walkTree(item.ProjectItems, showAll)
End If
End If
Next
End Sub
Private Sub WriteToBuildWindow(ByVal text As String)
Dim ow As OutputWindow = DTE.Windows.Item(EnvDTE.Constants.vsWindowKindOutput).Object
Dim build As OutputWindowPane = ow.OutputWindowPanes.Item("Build")
build.OutputString(text & Environment.NewLine)
End Sub
In case anyone else stumbles across this thread, there's a plugin that will give you a build error when you have files missing from your project.
If you happen to have a linux-like environment with access to the project folder (for instance, if you use git for version control, you can probably use the included Git Bash for this, or if you use Cygwin), here's my really quick and dirty way:
grep '<Content Include="' "project_file.csproj" | sed 's/^.*"\([^"]*\)".*/\1/' | sed 's/\\/\//g' | xargs -d'\n' ls > /dev/null
(How this works: I try to ls every file named in the project, and send the stdout output of the ls command to /dev/null, so it will be hidden. If any files do not exist, ls will barf their names to stderr rather than stdout, so those will be visible.)
Note that this doesn't understand URL-encoded escapes, so you will get a few false positives if your project contains filenames with characters like '(' in them.

Visual Studio Automation: Programatically get a project output directory

I want to programatically get a project output directory in a Visual Studio macro.
I managed to get a string of the path (through prj.ConfigurationManager.ActiveConfiguration.Properties and looking at property OutputDirectory) but this string may contain macros such as $(foo) where foo is defined in a property sheet or whatnot.
How do I resolve this output directory string to the 'real' directory?
I wrote this function for my macros which searches for full absolute output path by substring.
Function FindOutBinaryNameByExtension(ByVal prj As EnvDTE.Project, ByVal extName As String) As String
FindOutBinaryNameByExtension = Nothing
Dim cm As ConfigurationManager = prj.ConfigurationManager
If cm IsNot Nothing Then
Dim ac As Configuration = cm.ActiveConfiguration
For Each grpOut In ac.OutputGroups
If grpOut.DisplayName = "Primary output" Then
Dim lst As Array = grpOut.FileURLs
For i As Long = 0 To lst.Length - 1
Dim fileName As String = lst.GetValue(i)
If fileName.Contains(extName) Then
FindOutBinaryNameByExtension = fileName
Exit Function
End If
Next
End If
Next
End If
End Function

How to select a folder only by using common dialog control

Using VB6
Code.
CommonDialog1.DialogTitle = "Open File"
CommonDialog1.Filter = "*.*"
CommonDialog1.FilterIndex = 1
CommonDialog1.Flags = cdlOFNAllowMultiselect + cdlOFNExplorer
CommonDialog1.Flags = cdlOFNFileMustExist + cdlOFNHideReadOnly
CommonDialog1.CancelError = True
On Error Resume Next
CommonDialog1.ShowOpen
If Err Then
'MsgBox "Select Folder"
Exit Sub
End If
From the above code, i am selecting a file, But i don't want to select a file, I want to select only the folder. How to modify my code.
Need vb6 code Help?
It's been a while since I've had to do any visual basic work but I think instead of using the common dialog box for getting the name of a file to open you should use the SHBrowseForFolder function which is already part of the Windows API. Here's a link to a page that describes it's usage.
Update (2017): Provided link is broken but a backed-up version can be viewed on archive.org
To select a folder, you can use the Shell and Automation Component.
Private shlShell As Shell32.Shell
Private shlFolder As Shell32.Folder
Private Const BIF_RETURNONLYFSDIRS = &H1
Private Sub Command1_Click()
If shlShell Is Nothing Then
Set shlShell = New Shell32.Shell
End If
Set shlFolder = shlShell.BrowseForFolder(Me.hWnd, "Select a Directory", BIF_RETURNONLYFSDIRS)
If Not shlFolder Is Nothing Then
MsgBox shlFolder.Title
End If
End Sub
You will need to add a reference to shell32.dll to your project. Use the Project/References... menu and then browse for shell32.dll.
Or you can use the Windows API as Twotymz suggests.
This is an old thread, but maybe someone will be helped by this.
This code works in VB6 for me:
Private Sub ChooseDir_Click()
Dim sTempDir As String
On Error Resume Next
sTempDir = CurDir 'Remember the current active directory
CommonDialog1.DialogTitle = "Select a directory" 'titlebar
CommonDialog1.InitDir = App.Path 'start dir, might be "C:\" or so also
CommonDialog1.FileName = "Select a Directory" 'Something in filenamebox
CommonDialog1.Flags = cdlOFNNoValidate + cdlOFNHideReadOnly
CommonDialog1.Filter = "Directories|*.~#~" 'set files-filter to show dirs only
CommonDialog1.CancelError = True 'allow escape key/cancel
CommonDialog1.ShowSave 'show the dialog screen
If Err <> 32755 Then ' User didn't chose Cancel.
Me.SDir.Text = CurDir
End If
ChDir sTempDir 'restore path to what it was at entering
End Sub
I though that is more general VBA question anyway, opening select folder dialog in VBA for Office >=2k3.
I could not believe that it is so hard, as I need same functionality. Little googling made it.
Here is nice simple solution take a look
Function GetFolderName()
Dim lCount As Long
GetFolderName = vbNullString
With Application.FileDialog(msoFileDialogFolderPicker)
.InitialFileName = OpenAt
.Show
For lCount = 1 To .SelectedItems.Count
GetFolderName = .SelectedItems(lCount)
Next lCount
End With
End Function

Resources