Add last modified date in Visual Studio - 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)

Related

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.

Visual SourceSafe 6: Resetting all working folders

I've got a few old sourcesafe repositories which I want to delete. Before deleting them, I want to get the latest version of all code out recursively and then archive this code.
Various projects within the repositories have "working code" folders set which means that when I recursively get everything, code goes everywhere.
I'm trying to find a way to clear all working folders from a repository.
I've tried:
googling
looking through Tools->Options
looking at the "set working folder" dialog
looking at the "get multiple" dialog (but not closely enough - see answer below)
looking into the behind-the-scenes file structures for anything obvious I could nuke
Alternatively, if there's a way of backing the code of the repository up which frees it from requiring sourcesafe to view, that would also be good.
<Edit>Although the below actually does what I stated I wanted, there is an easier way to accomplish getting the latest version of code in the structure it appears in in the repository, which is to tick the "Build Tree (override working folders)" in the "Get Multiple" dialog.</Edit>
OK, worked it out. In the sourcesafe file structure, there is a folder called "users", within this will be your windows username, within this will be a ss.ini file.
Editing ss.ini to remove any entries which are in square brackets (and the text immediately under these sections) got rid of all working folder information for me. Note: It may also have lost some other information, but this is of no concern to me as I need only to get the latest version of code.
Example extract of file:
... more file above here ...
Preview_Rect (TQPC0137) = 321, 215, 703, 524, 1024, 768
Viewer_Font (TQPC0222) = Courier, 10, 400,, 0
Dft_Report_Type = 2
PrjFilesRpt_IncFiles = Yes
PrjFilesRpt_NamesOnly = No
... remove these sections below ...
[$/TQ/LRI/DataCaptureTest]
Dir (PC0137) = C:\PROJECT\DATACAPTURETEST
[$/AutoReference]
Dir (PC0137) = G:\WORKING CODE VBNET\TEST
[$/]
Dir (PC0222) = C:\WORKING CODE
Dir (PC0204) = G:\WORKING CODE VBNET\BOB
Dir (PC0118) = G:\WORKING CODE VBNET\BOB
Dir (PC0137) = G:\WORKING CODE VBNET\BOB
Dir (PC0168) = G:\WORKING CODE VBNET\BOB
... more file after this (but, in my instances, all the same type of stuff ...

Find files in project/solution that no longer exist

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)

Is there a way to get a local timestamp in my IPython prompt?

Is there a way to get a local timestamp in my IPython prompt? I'm using IPython 0.10 and Python 2.6 on 64-bit Windows Vista.
My current default prompt is
[C:Python26/Scripts]
|9>
OK, I tried to follow your directions exactly. However, my experience has been that all config editing is best kept to my ipy_user_conf.py. To quote from it:
User configuration file for IPython (ipy_user_conf.py)
This is a more flexible and safe way to configure ipython than *rc files
(ipythonrc, ipythonrc-pysh etc.)
This file is always imported on ipython startup. You can import the
ipython extensions you need here (see IPython/Extensions directory).
Feel free to edit this file to customize your ipython experience.
Note that as such this file does nothing, for backwards compatibility.
Consult e.g. file 'ipy_profile_sh.py' for an example of the things
you can do here.
See http://ipython.scipy.org/moin/IpythonExtensionApi for detailed
description on what you could do here.
So I now have these lines in main():
# -- prompt
# A different, more compact set of prompts from the default ones, that
# always show your current location in the filesystem:
o.prompt_in1 = r'\C_LightBlue[\C_LightCyan\Y2\C_LightBlue]\C_Normal\n\C_Green|\#>'
o.prompt_in2 = r'.\D: '
o.prompt_out = r'[\#] '
And I get this, for an example:
16:49:50 In[9]:1/7
1 [9] 0.14285714285714285
16:50:09 In[10]:
Questions:
What is that 1?
How can I keep the current directory in the prompt? Before, I had
[C:Python26/Scripts]
|8>
Once more with feeling.
I'm so sorry for the mess I've made. I need to report the lines I either added or modified actually are:
import_all("os sys random datetime")
o.prompt_in1 = r'\C_LightBlue[\C_LightCyan\Y2\C_LightBlue]\C_Normal\n\C_Green|\#>'
o.prompt_in1 = r'${datetime.now().strftime("%H:%M:%S")}[\#]:'
o.prompt_out = r'[\#] '
The easiest way is to edit your ipythonrc (in your home\_ipython directory), and add these lines:
import_mod datetime
prompt_in1 '${datetime.datetime.now()} In [\#]: '
# or
prompt_in1 '${datetime.datetime.now().strftime("%H:%M:%S")} In [\#]: '
Alternatively, you can also just add the import_mod datetime to the rc file, and add this to the main() function of ipy_user_conf.py (in the same directory):
o = ip.options
o.prompt_in1 = r'${datetime.datetime.now()} In [\#]: '
# or
o.prompt_in1 = r'${datetime.datetime.now().strftime("%H:%M:%S")} In [\#]: '

"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

Resources