Find files in project/solution that no longer exist - visual-studio-2010

Visual Studio 2010 has a bug (or annoying behavior) that it always starts a new build for a project if it includes a reference to a (source) file that no longer exists (and subsequently all depending projects). Now I have a rather large project and the only way I know of to find such files is to manually open every file.
Is there an easier way to identify such invalid references in project files?

I wrote a python script that identifies missing files and prints them to the console.
import os
import re
import sys
def show_help():
print()
print("Syntax:", sys.argv[0], "[filename]")
print()
def check_missing_project_includes(filename):
f = open(filename, 'r')
p = re.compile('(ClCompile|ClInclude) Include="(.*?)" />', re.IGNORECASE)
missing_files = []
for line in f:
m = re.search(p, line)
if m:
filename = m.group(2)
if not os.path.exists(filename):
missing_files.append(filename)
return missing_files
if len(sys.argv) != 2:
show_help()
exit()
filename = sys.argv[1]
missing_files = check_missing_project_includes(filename)
if len(missing_files) > 0:
print("Missing files:")
for mf in missing_files:
print("\t", mf)

A technique that I've used to diagnose missing files is to install a SCC provider Addin (eg AnkhSVN if you're using Subversion), then in the Solution Explorer missing files will have a different icon. This isn't as useful for larger projects, but for smaller ones it's quite quick to see at a glance.

Have you tried opening the proj file in an editor like Notepad++ and locate and remove the references from there? (If I'm understanding the question correctly that is)

Related

programmatically alter project settings

I have an old MFC solution with 120 projects in it.
Now Im trying to compile it with VisualC 2017 but every project emits the error:
cannot open file mfc140d.lib
Opening project properties, change the platform toolset to VS2017 141 and the the language version to C++17 fixes it.
But it will take a looooong time to do this for 120 projects and then the same for release build. Which are the settings in the project files that I can change programatically to set these two options? I sure cant find them
Wrote a python script that adds stdcpp17 and v141 to the vcxproj file if non existing. Maybe somebody finds a use for it:
def get_all_files(basedir):
for root, subfolders, files in os.walk(basedir):
for file in os.listdir(root):
yield root, file
def all_lines_from_file(file):
with open(file, 'r') as fd:
for line in fd.readlines():
yield line
def update_VCXPROJ():
standard = '<LanguageStandard>stdcpp17</LanguageStandard>'
toolset = '<PlatformToolset>v141</PlatformToolset>'
add1 = '<CharacterSet>MultiByte</CharacterSet>'
add2 = '<DebugInformationFormat>'
for root, file in get_all_files('c:/projects/6thcycle/sources/'):
if not file.lower().endswith('.vcxproj'):
continue
thisfile = ''
for line in all_lines_from_file('{0}/{1}'.format(root, file)):
if toolset in line or standard in line:
continue
if add1 in line:
line += ' {0}\n'.format(toolset)
elif add2 in line:
line += ' {0}\n'.format(standard)
thisfile += line
with open('{0}/{1}'.format(root, file), 'w') as fd:
fd.write(thisfile)
update_VCXPROJ()

How to ship or export an sdl project made in codeblocks

The project uses external image files and codeblocks is configured to find the library and header files for SDL. How can I turn the project into a format so that it can be easily shipped ? I intend to create a single executable file or an installer which is portable .
How can I do this ?
I've done that many times.
You just have to put the necessary DLLs (I use SDL 1.2, so SDL.dll, SDL_image.dll,zlib.dll, ...) where the executable is, which may be not so good with codeblocks/VC++ tree and the Debug/bin & Release/bin directories but would work with a .bat file which could run the executable.
OR
Consider that your development project is NOT the one the users will see.
Do you think that Microsoft guys code all system32 commands in one single source directory?
So develop however you like and then create a deliver script to put everything in the root directory. Like that you don't have the constraints of delivered product while you are developping and reverse.
I recommend this approach.
Checkout My bagman SDL remake to see what I mean
When I create the archive for distribution, I use a custom script that I include here. This one has all the works, libmpeg for mp3 decompression, and all. If you unzip the Bagman archive, it works right away on a windows PC.
Here's my directory tree
Bagman\bin
Bagman\exploit
Bagman\icons
Bagman\music
Bagman\obj
Bagman\resource
Bagman\sound
Bagman\src
Bagman\work
Bagman\bin\Debug
Bagman\bin\Debug256
Bagman\bin\Release
Bagman\exploit\mkf
Bagman\obj\Amiga
Bagman\obj\Debug
Bagman\obj\Debug256
Bagman\obj\NDS
Bagman\obj\NDSEMU
Bagman\obj\Release
Bagman\obj\Debug\src
Bagman\obj\Debug\src\characters
Bagman\obj\Debug\src\engine
Bagman\obj\Debug\src\gfx
Bagman\obj\Debug\src\screens
Bagman\obj\Debug\src\sys
Bagman\obj\Debug256\src
Bagman\obj\Debug256\src\characters
Bagman\obj\Debug256\src\engine
Bagman\obj\Debug256\src\gfx
Bagman\obj\Debug256\src\sys
Bagman\obj\NDS\src
Bagman\obj\NDS\src\characters
Bagman\obj\NDS\src\engine
Bagman\obj\NDS\src\gfx
Bagman\obj\NDS\src\sys
Bagman\obj\NDSEMU\src
Bagman\obj\NDSEMU\src\characters
Bagman\obj\NDSEMU\src\engine
Bagman\obj\NDSEMU\src\gfx
Bagman\obj\NDSEMU\src\sys
Bagman\obj\Release\src
Bagman\obj\Release\src\characters
Bagman\obj\Release\src\engine
Bagman\obj\Release\src\gfx
Bagman\obj\Release\src\sys
Bagman\resource\1x
Bagman\resource\maps
Bagman\resource\1x\images
Bagman\resource\1x\sprites
Bagman\src\characters
Bagman\src\engine
Bagman\src\gfx
Bagman\src\screens
Bagman\src\sys
Here's the python script that copies all necessary files in the user archive:
import sys,os,zipfile,re,shutil,glob
import find,which # custom modules I created myself
MODULE_FILE = sys.modules[__name__].__file__
PROGRAM_DIR = os.path.abspath(os.path.dirname(MODULE_FILE))
ROOTDIR=os.path.realpath(os.path.join(PROGRAM_DIR,os.pardir))
PRODUCT_NAME="Bagman"
music=False
dev=False
version = "1.2"
print("making archive for version "+version)
os.chdir(ROOTDIR)
archname=PRODUCT_NAME+"-win32-"+version+".zip"
zfn = os.path.join(ROOTDIR,os.pardir,archname)
if os.path.exists(zfn):
os.remove(zfn)
zf = zipfile.ZipFile(zfn,mode="w",compression=zipfile.ZIP_DEFLATED)
dll_list = ["SDL.dll","SDL_Mixer.dll"]+["smpeg.dll","libgcc_s_sjlj-1.dll","libstdc++-6.dll","libgcc_s_dw2-1.dll"] # MP3 playing needs the second part
items_list = ["bagman*.bat","*.cbp","*.dev","*.txt","COPYING","resource","exploit","sound","src"]
real_items_list = []
for i in items_list:
real_items_list.extend(glob.glob(i))
for d in dll_list:
print("processing '"+d+"'")
dp = which.which(d)
if len(dp)==0:
raise Exception("%s not found in PATH" % d)
zf.write(dp[0],arcname=PRODUCT_NAME+"/"+d)
for i in real_items_list:
print("processing '"+i+"'")
if os.path.isfile(i):
zf.write(i,arcname=PRODUCT_NAME+"/"+i)
else:
fnd = find.Find()
items = fnd.init(i)
for f in items:
if i == "resource" and os.path.basename(f) in ["settings","soundbank.bin"]:
pass
else:
fi = f.replace(os.sep,"/")[2:]
if os.path.isfile(fi):
if fi.endswith("~"):
pass
else:
zf.write(fi,arcname=PRODUCT_NAME+"/"+fi)
else:
zfi = zipfile.ZipInfo(PRODUCT_NAME+"/"+fi+"/")
zf.writestr(zfi, '')
zfi = zipfile.ZipInfo(PRODUCT_NAME+"/bin/")
zf.writestr(zfi, '')
zfi = zipfile.ZipInfo(PRODUCT_NAME+"/bin/Release/")
zf.writestr(zfi, '')
zfi = zipfile.ZipInfo(PRODUCT_NAME+"/bin/Debug/")
zf.writestr(zfi, '')
zf.write("bin/Release/bagman.exe",arcname=PRODUCT_NAME+"/bin/Release/bagman.exe")
zf.close()
I know that there are existing python modules which will help you achieve such things (distutils). I did not use them because I wasn't aware of them.

Mass Convert .xls and .xlsx to .txt (Tab Delimited) on a Mac

I have about 150 .xls and .xlsx files that I need converting into tab-delimited. I tried using automator, but I was only able to do it one-by-one. It's definitely faster than opening up each one individually, though. I have very little scripting knowledge, so I would appreciate a way to do this as painlessly as possible.
If you would be prepared to use Python for this I have written a script that converts Excel spreadsheets to csv files. The code is available in Pastebin.
You would just need to change the following line:
writer = csv.writer(fileout)
to:
writer = csv.writer(fileout, delimiter="\t")
to make the output file tab delimited rather than the standard comma delimited.
As it stands this script prompts you for files one at a time (allows you to select from a dialogue), but it could easily be adapted to pick up all of the Excel files in a given directory tree or where the names match a given pattern.
If you give this a try with an individual file first and let me know how you get on, I can help with the changes to automate the rest if you like.
UPDATE
Here is a wrapper script you could use:
#!/usr/bin/python
import os, sys, traceback
sys.path.insert(0,os.getenv('py'))
import excel_to_csv
def main():
# drop out if no arg for excel dir
if len(sys.argv) < 2:
print 'Usage: Python xl_csv_wrapper <path_to_excel_files>'
sys.exit(1)
else:
xl_path = sys.argv[1]
xl_files = os.listdir(xl_path)
valid_ext = ['.xls', '.xlsx', '.xlsm']
# loop through files in path
for f in xl_files:
f_name, ext = os.path.splitext(f)
if ext.lower() in valid_ext:
try:
print 'arg1:', os.path.join(xl_path,f)
print 'arg2:', os.path.join(xl_path,f_name+'.csv')
excel_to_csv.xl_to_csv(os.path.join(xl_path,f),
os.path.join(xl_path,f_name+'.csv'))
except:
print '** Failed to convert file:', f, '**'
exc_type, exc_value, exc_traceback = sys.exc_info()
lines = traceback.format_exception(exc_type, exc_value, exc_traceback)
for line in lines:
print '!!', line
else:
print 'Sucessfully conveted', f, 'to .csv'
if __name__ == '__main__':
main()
You will need to replace the :
sys.path.insert(0,os.getenv('py'))
At the top with an absolute path to the excel_to_csv script or an environment variable on your system.
Use VBA in a control workbook to loop through the source workbooks in a specified directory or a list of workbooks, opening each, saving out the converted data, then closing each in turn.

"Tabify" all files in Visual Studio solution?

There's a "tabify" command in
Edit > Advanced > Tabify Selected Lines
(and the Power Tools 2010 also provide this functionality on a per-file basis) but is there a way to do this for all code files in a solution?
ReSharper has a Clean Up command but the only half-suitable option I found there is to run formatting on all files which does more than I want (I don't want to run a complete formatting, just tabifying).
If you have added the Microsoft Productivity Power tools extension (which if you haven't I would recommned) it adds an option to tabify files. This does not apply across all files in a solution, but it's prompted for when editing each file, on a per file basis. Not quite what you're after but a help.
Also you might try setting your IDE editor settings to use tabs, then do menu-edit-advanced-format document (CTRL+E,D). This will replace groups of tab length spaces with a tab, and that should be scriptable for all files in the solution via a macro.
The request contains links to IDE macros that can do the job:
http://blogs.msdn.com/b/kevinpilchbisson/archive/2004/05/17/133371.aspx
http://web.archive.org/web/20090217094033/http://chriseargle.com/post/Format-Solution.aspx
Here is sample code for a Visual Studio macro that automatically formats all *.cs, *.h, *.cpp, and *.hpp files in an open solution, which includes converting spaces to tabs (depending on your Tab settings in Tools > Options > Text Editor > specific language or "All Languages" > Tabs):
Imports System
Imports EnvDTE
Imports EnvDTE80
Imports System.Diagnostics
Public Module ConvertTabsToSpaces
Public Sub FormatSolution()
Dim sol As Solution = DTE.Solution
For i As Integer = 1 To sol.Projects.Count
FormatProject(sol.Projects.Item(i))
Next
End Sub
Private Sub FormatProject(ByVal proj As Project)
If Not proj.ProjectItems Is Nothing Then
For i As Integer = 1 To proj.ProjectItems.Count
FormatProjectItem(proj.ProjectItems.Item(i))
Next
End If
End Sub
Private Sub FormatProjectItem(ByVal projectItem As ProjectItem)
If projectItem.Kind = Constants.vsProjectItemKindPhysicalFile Then
If projectItem.Name.LastIndexOf(".cs") = projectItem.Name.Length - 3 Then
Dim window As Window = projectItem.Open(Constants.vsViewKindCode)
window.Activate()
projectItem.Document.DTE.ExecuteCommand("Edit.FormatDocument")
window.Close(vsSaveChanges.vsSaveChangesYes)
ElseIf ((projectItem.Name.LastIndexOf(".cpp") = projectItem.Name.Length - 4) OrElse (projectItem.Name.LastIndexOf(".hpp") = projectItem.Name.Length - 4) OrElse (projectItem.Name.LastIndexOf(".h") = projectItem.Name.Length - 2)) Then
Dim window As Window = projectItem.Open(Constants.vsViewKindCode)
window.Activate()
projectItem.Document.DTE.ExecuteCommand("Edit.SelectAll")
projectItem.Document.DTE.ExecuteCommand("Edit.FormatSelection")
window.Close(vsSaveChanges.vsSaveChangesYes)
End If
End If
'Be sure to format all of the ProjectItems.
If Not projectItem.ProjectItems Is Nothing Then
For i As Integer = 1 To projectItem.ProjectItems.Count
FormatProjectItem(projectItem.ProjectItems.Item(i))
Next
End If
'Format the SubProject if it exists.
If Not projectItem.SubProject Is Nothing Then
FormatProject(projectItem.SubProject)
End If
End Sub
End Module
Instructions (Visual Studio 2005, but similar for newer versions):
Launch Visual Studio
Tools > Macros > Macros IDE...
Right-click MyMacros > Add > Add New Item...
Select Module
Enter "ConvertSpacesToTabs" without quotes in the Name field
Click Add
Replace the contents of the new module with the code above
Click Save
Close the Macros IDE
Tools > Macros > Macro Explorer
Expand MyMacros > ConvertSpacesToTabs
Double-click on FormatSolution
Wait for the macro to finish
Edit
I updated the code to also support *.h, *.cpp, and *.hpp files using code from Siegmund Frenzel here:
https://stackoverflow.com/a/14766393/90287
as far as I know what "Tabify" does is this - it only replaces " " (4 spaces) with a tab, it does not change the formatting or anything else.
Although I would suggest using document formatting, the "tabification" could easily be done via a custom application which would mimic the same action on all the files that you want.
Hope this helps!
For vs2010, you can use the following find and replace (this example is for tabs to 4 spaces).
In the find box, enter: ^{ *} (^{ space *} tab)
In the replace box, enter \1 (\1 space space space space)
Check the condition box and set to regular expressions.
Newer versions of vs use different regular expression syntax, but the same should be doable.
Update
This worked by executing once for vb files, but required multiple passes for a resx file, so you may have to execute multiple times depending on the file type...
There's a new way using the dotnet CLI:
Install dotnet format by running the following command:
dotnet tool install -g dotnet-format
Run it, replacing SolutionFile.sln with the path to your solution file, with the following command line:
dotnet format SolutionFile.sln
The indent_style of .editorconfig will be used to determine if the code will use tabs or spaces.
Macros have been removed from Visual Studio 2013 onwards (and the new version of Macros uses JavaScript rather than VBScript), so to get Rami A.'s answer to work in Visual Studio 2019:
Download and install the Visual Commander extension
Extensions > VCmd > Edit macro
Name it
Paste the following code. I have had to make some changes to it to make the code work with Visual Commander. I have also changed the file extensions that it tabifies to .cs, .aspx and .ascx so change these if you need C++/other file extensions.
Imports System
Imports EnvDTE
Imports EnvDTE80
Imports System.Diagnostics
Imports Microsoft.VisualStudio.Shell
Imports VisualCommanderExt
Public Class ConvertTabsToSpaces
Implements ICommand
Sub Run(DTE As DTE2, package As Package) Implements ICommand.Run
Dim sol As Solution = dte.Solution
For i As Integer = 1 To sol.Projects.Count
FormatProject(sol.Projects.Item(i))
Next
End Sub
Private Sub FormatProject(ByVal proj As Project)
If Not proj.ProjectItems Is Nothing Then
For i As Integer = 1 To proj.ProjectItems.Count
FormatProjectItem(proj.ProjectItems.Item(i))
Next
End If
End Sub
Private Sub FormatProjectItem(ByVal projectItem As ProjectItem)
If projectItem.Kind = Constants.vsProjectItemKindPhysicalFile Then
If (projectItem.Name.LastIndexOf(".cs") = projectItem.Name.Length - 3 OrElse (projectItem.Name.LastIndexOf(".aspx") = projectItem.Name.Length - 5 OrElse (projectItem.Name.LastIndexOf(".ascx") = projectItem.Name.Length - 5))) Then
Dim window As Window = projectItem.Open(Constants.vsViewKindCode)
window.Activate()
Try
projectItem.Document.DTE.ExecuteCommand("Edit.RemoveAndSort")
Catch
' Do nothing
End Try
Try
projectItem.Document.DTE.ExecuteCommand("Edit.SelectAll")
projectItem.Document.DTE.ExecuteCommand("Edit.FormatSelection")
Catch
' Do nothing
End Try
window.Close(vsSaveChanges.vsSaveChangesYes)
End If
End If
'Be sure to format all of the ProjectItems
If Not projectItem.ProjectItems Is Nothing Then
For i As Integer = 1 To projectItem.ProjectItems.Count
FormatProjectItem(projectItem.ProjectItems.Item(i))
Next
End If
'Format the SubProject if it exists
If Not projectItem.SubProject Is Nothing Then
FormatProject(projectItem.SubProject)
End If
End Sub
End Class
Save
Run
To save for future use: Extensions > VCmd > Save macro as command > Name it > Save

Add last modified date in Visual Studio

How can I easily add 'last modified date' comment to my source files in Visual Studio 2008, so that I don't have to manually update the comment every time I edit the file?
Use a revision control system that supports the RCS $Date$ keyword, such as RCS, CVS, or SVN.
Instructions for doing that in Subversion are here.
If you are using source control then the last modified date can be obtained from the date of the last check in.
If you're working on your own projects then you still should use source control and as you're not affecting anyone else you can check in incomplete code.
If you're working on a project with others you can still do this if you create individual branches and have a suitable merge schedule and procedure in place.
import os
import csv
import time
from os.path import join,splitext
path = r"location of file"
fileinfo=[]
for path,dirs,files in os.walk(path):
for file in files:
datetime = os.path.getmtime(path)
moddatetime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(datetime))
size = os.stat(path).st_size
extension = os.path.splitext(file)[-1]
newrow = [path, file, moddatetime, size]
fileinfo.append(newrow)
def task_csv(filelist=[]):
csv_writer = csv.writer(open('14012021_csv' , 'w', newline=''), delimiter =',')
csv_writer.writerow(['file name:','folderpath:','extensions:','dateandtime'])
for row in filelist:
csv_writer.writerow(row)
task_csv(fileinfo)

Resources