We have a code generator that munges the schema of a given database to automate our inhouse n-tier architecture. The output is various C# partial classes, one per file.
In the code to munge all the strings, we try and keep on top of the indenting and formatting as much as possible, but invariably when you come to open the file in Visual Studio the formatting is awry. A quick ctrl-k, ctrl-d fixes it, but obviously this reformatting is lost the next time the class is generated.
What I'd like to know, is if there's a way I can somehow automatically format the contents of the textfile in the same way Visual Studio does?
Pseudocode
Create "code" object, passing text file to constructor
Invoke "format" method
Re-save text file
Any help greatly appreciated.
EDIT:
I should clarify - I want to be able to invoke the formatting from my C# code that creates the textfile containing my generated C#. The format of the code can be standardised (doesn't have to be per-developer), and I don't want to have to install any 3rd-party apps.
I seem to remember there's a namespace containing loads of classes for creating C# in C#: http://msdn.microsoft.com/en-us/library/system.codedom(VS.80).aspx, but I'm not sure if it contains any classes that could help.
FURTHER EDIT:
My code generator is a winforms app deployed via a click-once install. It's used by many developers in-house. I need a solution that doesn't require each developer to have a tool installed on their machine.
To properly indent code programmatically you would need Microsoft.CodeAnalysis.CSharp nuget package and .NET framework 4.6+. Sample code:
public string ArrangeUsingRoslyn(string csCode) {
var tree = CSharpSyntaxTree.ParseText(csCode);
var root = tree.GetRoot().NormalizeWhitespace();
var ret = root.ToFullString();
return ret;
}
One-liner:
csCode = CSharpSyntaxTree.ParseText(csCode).GetRoot().NormalizeWhitespace().ToFullString();
You may also use NArrange to sort methods in your cs file, organize usings, create regions, etc. Note that NArrange does not indent anything.
Take a look at Narrange.You'll probably need to automate these things as part of the build.
Not sure if it meets all your requirements though.
To quote:
NArrange is a .NET code beautifier
that automatically organizes code
members and elements within .NET
classes.
You can use CodeDOM and the CSharpCodeProvider. It is all in the namespaces Microsoft.CSharp and System.CodeDom.
Her is an example of a property:
StringWriter writer = new StringWriter();
CSharpCodeProvider provider = new CSharpCodeProvider();
CodeMemberProperty property = new CodeMemberProperty();
property.Type = new CodeTypeReference(typeof(int));
property.Name = "MeaningOfLifeUniverseAndEverything";
property.GetStatements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(42)));
provider.GenerateCodeFromMember(property, writer, null);
Console.WriteLine(writer.GetStringBuilder().ToString());
This code will generate:
private int MeaningOfLifeUniverseAndEverything {
get {
return 42;
}
}
The CodeDOM is a quite chatty way to generate code. The good thing is that you can generate multiple languages. Perhaps you can find a Erlang.NET CodeProvider?
You might be able to do a few shortcuts by using CodeSnippetExpression.
Only if you're running the code generator as a VS add-on - each developer is going to have different settings.
Here's how to do it from the context of a macro or add-in:
var dte = (EnvDTE80.DTE2)System.Runtime.InteropServices.Marshal.GetActiveObject("VisualStudio.DTE.8.0");
dte.ExecuteCommand("File.OpenFile", filename);
dte.ExecuteCommand("Edit.FormatDocument", filename);
dte.ActiveDocument.Close(vsSaveChanges.vsSaveChangesYes);
Warning: As #Greg Hurlman says, the output will vary depending on the user's current options.
Edit:
unfortunately your method requires me to have an instance of VS running alongside my winforms app. Can you think of a way to create an instance of VS from within my app (if that's even possible)?
I think it might be possible to do from within your Win.Form app. However, you'll have to have Visual Studio installed on the machine running the code.
Try this:
var dte = (EnvDTE80.DTE2)Microsoft.VisualBasic.Interaction.CreateObject("VisualStudio.DTE.8.0", "");
dte.ExecuteCommand("File.OpenFile", filename);
dte.ExecuteCommand("Edit.FormatDocument", filename);
dte.ActiveDocument.Close(vsSaveChanges.vsSaveChangesYes);
Keep in mind that you'll need references to the EnvDTE80.dll assembly.
Related
I'm trying to automate a tedious process that currently involves launching Word, Creating a new document from a .dot, saving it, running one or two plug-ins that were written in C# using VSTO, saving it again, exiting the document, and exiting Word.
I want to write a C# commandline app that the user can launch with one or two args (conveying all the information that would normally require interaction with dialogs in Word), then walk away from as it runs without further interaction... suppressing any and all focus-stealing by Word while it's running if necessary and possible.
Is there some straightforward way to accomplish this? Here's a Java-like pseudocode example of what I have in mind:
// magic to non-interactively launch Word and expose it as an object
WordHost word = xx;
// create new Word document based on a specific template that isn't the default one.
WordDocument doc = MSWord.create("z:\path\to\arbitraryTemplate.dot");
// If we can avoid physically saving it at this point and just assign a concrete
// file path, it would be even better because the network is glacially slow.
doc.saveAs("z:\path\to\newDoc.docx");
// someZeroArgPlugin and aTwoArgPlugin are VSTO plugins written with C#
doc.someZeroArgPlugin();
doc.aTwoArgPlugin("first", "second");
// done!
doc.save();
doc=null;
word=null; // something like word.unload() first?
// now do more things that don't involve Word directly...
Assuming I'm on the right track...
I'm pretty sure I can find most of what I need to know by searching... once I figure out what I need to be searching for. What should I be searching for?
What kind of project do I want to be creating in Visual Studio? A .net 4.5 C# console application? A Word 2010 Add-In? Some other kind of project?
Details that might or might not make a difference:
my program will only be run on computers that have Word 2010 installed. Compatibility with older versions isn't necessary.
It would be nice if it can run under Vista, but it only has to work under Win7.
I have Visual Studio Ultimate 2012
Here's what you'll need to do:
Have Visual Studio and Office installed.
Create a C# console project using the .NET framework of your choice (recommend 4.0 or above).
Add a reference to the Word COM library (Project menu => Add Reference, COM tab, Microsoft Word XX.0 Object library -- Word 2010 is 14.0).
Set the Embed Interop Types setting to false for the references added above
Expand References in Solution Explorer
Select Microsoft.Office.Core, Microsoft.Office.Interop.Word and VBIDE
Right-click and select Properties to bring up the Properties panel for the references.
In the Properties panel, set Embed Interop Types to False
Code away.
Here's some sample code.
using System;
using Microsoft.Office.Interop.Word;
namespace CSharpConsole
{
static class Program
{
[STAThread]
static void Main()
{
var application = new ApplicationClass();
var document = application.Documents.Add();
document.SaveAs("D:\test.docx");
application.Quit();
}
}
}
For more information, see http://msdn.microsoft.com/en-us/library/office/ff601860(v=office.14).aspx
I'm trying to use SharpSvn to read the contents of two revisions of a file. When I run the following code the fileVersions collection only contains one item..
var svnClient = new SvnClient();
var revisionInfo = new SvnFileVersionsArgs
{
Start = 80092,
End = 80093
};
Collection<SvnFileVersionEventArgs> fileVersions;
svnClient.GetFileVersions(
new SvnUriTarget("https://DbDiff.svn.codeplex.com/svn/DbDiffCommon/DataAccess/SqlCommand11.xml"),
revisionInfo,
out fileVersions);
However I would expect it to include two items. Using TortoiseSVN I can see that the file changed in revision 80088, so I would expect to get this version when I use Start = 80092..
Using Start = 80091 doesn't help either..
The problem is not in your code but in the SvnBridge software used by codeplex. (They store the data in TFS and provide access via the bridge instead of using a real Subversion backend).
The bridge software doesn't implement this api properly. (I added an issue on it years ago, but as far as I can tell it was never fixed).
Subversion itself only uses this api for 'svn blame' (/praise/annotate), so I think the SvnBridge developers didn't care enough to fix this.
In AnkhSVN I detect the case of just receiving one file and then use SvnClient.Write() to obtain the file the slow way :(
I need to create a resource file for a .net project (by hand) and compile it using the ResGen.exe tool provided by the .NET framework. I can't find any documentation for this. I need to write the resource file by hand because I'm in a situation where I don't want to download/buy extra tools (like VS) to generate this resource file, and also I feel more productive through the command-line (helps me understand how things really work).
So I need to write a resource file by hand to store an ICON in the executable and use it from within my program. I would also like to use this icon to represent my executable in Windows Explorer.
Any references would be great!
Visual C# Express Edition will do what you want for free. If nothing else you can download that, create the resource file and then use that as a subject for your admirable curiosity about 'how it really works'. This may also save you some time in manual experimentation to get it right the first time around.
These 2 links in conjunction provide information on using that tool to create and embed an icon file, it seems specific to C#. Of course i'm guessing at your full intention, let me know if this points you in the proper direction.
http://www.xtremedotnettalk.com/showthread.php?t=75449
specifically there is a post which states;
I think you should first create a *.resources-File from the Icon with the tool named "Resgen.exe"...
resgen App.ico App.ico.resources
the next step would be compiling...
csc /t:winexe /out:Keygen.exe /res:App.ico.resources /r:Crypto.dll /win32icon:App.ico Keygen.cs AssemblyInfo.cs
I'm sure you were here already.
http://msdn.microsoft.com/en-us/library/ccec7sz1(VS.80).aspx
You should check this link:
http://msdn.microsoft.com/en-us/library/ekyft91f.aspx
It explains what formatter is used and gives some code samples to generate one from code. You could then write a small wrapper app that you can call from the command line. No downloads needed!
We have a report generator. Daily, it writes its data into a excel file.
For reasons of version controlling and file data safety, we need to alter this file, and commit the changes into a repository.
Do you recommend any .net SVN API you've used?
You should take a look at the SharpSvn .NET library. You will probably need checkout and commit commands:
Checking out:
string wcPath = "c:\\my working copy";
using (SvnClient client = new SvnClient())
{
client.CheckOut(new Uri("http://server/path/to/repos"), wcPath);
}
Committing:
string wcPath = "c:\\my working copy";
SvnCommitArgs a = new SvnCommitArgs();
a.LogMessage = "My log message";
using (SvnClient client = new SvnClient())
{
client.Commit(wcPath, a);
}
You might be able to turn on Autoversioning for your repository. Since it uses WebDAV, you can treat the repository just like a network drive (Web Folder). And you can treat the file as a normal file, just open, modify, and save.
If it were me , I would create a new repository for the excel data files. I don't think I'd like my code being autoversioned :)
We are using tool that actually searching for installed TortoiseSVN in predefined locations and using it command-line api. If that is for Windows and it's for not redistribution - it might be easier to do.
Helpful code for cmd:
#echo off
if exist "%ProgramW6432%\TortoiseSVN\bin\TortoiseProc.exe" set patht=%ProgramW6432%
if exist "%ProgramFiles%\TortoiseSVN\bin\TortoiseProc.exe" set patht=%ProgramFiles%
if exist "%ProgramFiles(x86)%\TortoiseSVN\bin\TortoiseProc.exe" set patht=%ProgramFiles(x86)%
echo Placing SVN Commit
"%patht%\TortoiseSVN\bin\TortoiseProc.exe" /command:commit /path:"%CD%" /notempfile
If you still want to do that task from code - SharpSVN http://sharpsvn.open.collab.net is better choiсe
The simplest would be to spawn a process and call SVN.exe
to commit your changes.
Here is a similiar question that was asked.
Does anyone know of a good C# API for Subversion?
Here is another resource
SVN Libraries for .NET?
In a C# .NET 3.5 app (a mix of WinForms and WPF) I want to let the user select a folder to import a load of data from. At the moment, it's using System.Windows.Forms.FolderBrowserDialog but that's a bit lame. Mainly because you can't type the path into it (so you need to map a network drive, instead of typing a UNC path).
I'd like something more like the System.Windows.Forms.OpenFileDialog, but for folders instead of files.
What can I use instead? A WinForms or WPF solution is fine, but I'd prefer not to PInvoke into the Windows API if I can avoid it.
Don't create it yourself! It's been done. You can use FolderBrowserDialogEx -
a re-usable derivative of the built-in FolderBrowserDialog. This one allows you to type in a path, even a UNC path. You can also browse for computers or printers with it. Works just like the built-in FBD, but ... better.
Full Source code. Free. MS-Public license.
Code to use it:
var dlg1 = new Ionic.Utils.FolderBrowserDialogEx();
dlg1.Description = "Select a folder to extract to:";
dlg1.ShowNewFolderButton = true;
dlg1.ShowEditBox = true;
//dlg1.NewStyle = false;
dlg1.SelectedPath = txtExtractDirectory.Text;
dlg1.ShowFullPathInEditBox = true;
dlg1.RootFolder = System.Environment.SpecialFolder.MyComputer;
// Show the FolderBrowserDialog.
DialogResult result = dlg1.ShowDialog();
if (result == DialogResult.OK)
{
txtExtractDirectory.Text = dlg1.SelectedPath;
}
Unfortunately there are no dialogs other than FolderBrowserDialog for folder selection. You need to create this dialog yourself or use PInvoke.
So far, based on the lack of responses to my identical question, I'd assume the answer is to roll your own dialog from scratch.
I've seen things here and there about subclassing the common dialogs from VB6 and I think this might be part of the solution, but I've never seen anything about modifying what the dialog thinks it's selecting. It'd be possible through .NET via PInvoke and some other tricks, but I have yet to see code that does it.
I know it's possible and it's not Vista-specific because Visual Studio has done it since VS 2003.
Here's hoping someone answers either yours or mine!
After hours of searching for a similar solution I found this answer by leetNightShade to a working solution.
There are three things I believe make this solution much better than all the others.
It is simple to use.
It only requires you include two files (which can be combined to one anyway) in your project.
It falls back to the standard FolderBrowserDialog when used on XP or older systems.
The author grants permission to use the code for any purpose you deem fit.
There’s no license as such as you are free to take and do with the code what you will.
Download the code here.