Mercurial , writing hooks using a .NET api - c#

Hi I am looking for examples of how to write Mercurial hooks in a .NET language, including how to setup .hg/hgr
I have used the "Mercurial.Net" Api, but the information in the Windows environment variables is a bit limited and returning error messages on the standard error channel does not appear to work. I guess I am doing something wrong.
I am using .Net for a number of reasons , one being to link up with other systems using WFC

EDIT The new version of Mercurial.Net makes writing hooks easier, see see http://mercurialnet.codeplex.com/discussions/261283
Create a "Windows Application" project (eg MyHook).
Add a reference to "Mercurial.Net" (you can use NuGet to make it easier http://nuget.org/List/Packages/Mercurial.Net).
In your main method, do whatever processing you want (eg retrieve the log and then the info on the last commit - see http://mercurialnet.codeplex.com/discussions/261283 for examples). You can add a MessageBox.Show(message) to check that the hook is indeed executed.
Compile your project.
Add the hook to your .hg/hgrc file (below is an example of a hook that will be executed after each commit, see https://www.mercurial-scm.org/wiki/Hook for more info, http://hgbook.red-bean.com/read/handling-repository-events-with-hooks.html for even more info):
[hooks]
commit.hook1 = "C:\path to file\MyHook.exe"
The next time you commit your hook should be executed.
Check http://docs.vkarlsen.no/Mercurial.Net/ to learn about the classes of Mercurial.Net.

Related

SonarQube: Log to Console

Is this rule applied to console applications? If yes, how can we log to the conosle then? Or why shouldn't you do it?
http://dist.sonarsource.com/plugins/csharp/rulesdoc/0.10.0-RC/S2228.html
You can disable this rule on Console Applications. Nevertheless, even for console applications, it can be a good idea to limit the number of Console.WriteLine() calls for instance to make it easier to later on change your application. For example, you don't want to see Console.* calls spread to the whole codebase, but see it perhaps contained in a single class. If that is the case, feel free to mark those issues as Won't Fix in SonarQube, to indicate that you have reviewed them and that they are expected and accepted.
you ca try to implement a sonar-project.properties file that would contain a sonar exclusions definition and you can exclude from Sonar scan the files containing console.log calls.
example:
sonar.exclusions=**/__tests__/**/*,**/*.js

How to test whether a given functional code unit (C#) does NOT create/write any files to disk?

Imagine there's a mission-critical process that'll be used in a business which handles sensitive information (think of Credit Card, social security, patient records...etc). I would think this unit ideally should do whatever it has to do on-the-fly, meaning it won't intentionally write files to disk containing sensitive information. The idea here is that if the computer that runs this process is compromised, no sensitive information can be leaked, at least not by means of files.
What approaches could be taken to, say, come up with a unit test that will fail if the unit under test tries to write any file to disk?
There is the FileSystemWatcher (http://www.c-sharpcorner.com/uploadfile/puranindia/filesystemwatcher-in-C-Sharp/) however this requires you to know a specific directory. In your case this probably isn't very helpful since the program could write anything to disk any where. This introduces a unique problem. However, I have also found something called Detours from Microsoft. This appears to intercept all native win32 api calls. http://research.microsoft.com/en-us/projects/detours/ The issue with this is that its kind of hard to test, and integrating it into unit testing will be a challenge.
When you have to treat your software as "untrusted" in the sense that you need to prove it doesn't do something, testing becomes a complex task that requires you to run them on very controlled environments. When hooking in to the Win32 API, you will be deluged with API calls that need to be processed quickly. This can result in unintentional side effects because the application is not running in a truly native environment.
My suggestion to you (having worked several years doing software testing for Pharma automation to the exacting standards of the FDA) is to create a controlled environment, eg a virtual machine, that has a known starting state. This can be accomplished by never actually saving vmdk changes to disk. You have to take a snapshot of the file system. You can do this by writing a C# app to enumerate all files on the virtual drive, getting their size, some timestamps and maybe even a hash of the file. This can be time consuming so you may want (or be able) to skip the hashing. Create some sort of report, easiest would be by dropping them in a CSV or XML export. You then run your software under normal circumstances for a set period of time. Once this is complete, you run a file system analysis again and compare the results. There are some good apps out there for comparing file contents (like WinMerge). When taking these snap shots, the best way to do it would be to mount the vmdk as a drive in the host OS. This will bypass any file locks the guest OS might have.
This method is time intensive but quite thorough. If you don't need something of this depth, you can use something like Process Monitor and write the output to a file and run a report against that. However in my work I would have to prove that Process Monitor shows all IO before I could use it which can be just as hard as the method I spoke of above.
Just my 2 cents.
UPDATE:
I've been thinking about it, and you might be able to achieve fairly reliable results if you remove all references to System.IO from your code. Write a library to wrap around System.IO that either does not implement a write method, or only implements one that also writes to a log file. In this case, you simply have to validate that every time a write occurs using your library, it gets logged. Then validate using reflection that you don't reference System.IO outside of this new wrapper library. Your tests can then simply look at this log file to make sure only approved writes are occurring. You could make use of a SQL Database instead of a flat log file to help avoid cases of tampering or contaminated results. This should be much easier to validate than trying to script a virtual machine setup like I described above. This, of course, all requires you to access to the source code of the "untrusted" application, although since you are unit testing it, I assume you do.
1st option:
Maybe you could use Code Access Security, but the "Deny" is obsolete in .NET 4 (but should works in previous version):
[FileIOPermission(SecurityAction.Deny)]
public class MyClass
{
...
}
You may reactivate this behavior in .NET 4 using NetFx40_LegacySecurityPolicy
2nd option:
reducing the level of privilege may also works, as I know that downloaded app can't write on the disk and must use a special storage area.
3rd option:
Remove any reference to System.IO and replace by an interface that your code must use to write data to disk.
Then write an implementation that use System.IO (in a separate project)
In the nunit test, mock this interface and throw an exception when a method id called.
Problem is to ensure any developers will not call System.IO anymore. You can try to do this by enforcing coding rules using FxCop (or other similar tools)

Passing commandline argument after service installation using c#

We had a problem with WCF hosting on service in Windows 2003.
We found a command line tool (httpcfg) which helped us to resolve the issue temporarily.
The following command line argument needs to run after the service installation:
httpcfg set urlacl -u http://+:8080/ -a "D:(A;;GX;;;S-1-5-21-490459244-4280451753-3120260354-1829)"
We need to pass this argument via installer using C#
That is via service controller after installer event. How would I do the same in C# using ServiceController?
I can think of two approaches:
Just run httpcfg.exe using System.Diagnostics.Process
Use PInvoke to access the underlying Win32 API HttpSetServiceConfiguration
The second approach is a little messy but not that hard. The PInvoke.net page describes the call and even gives a working example:
PInvoke.net: httpsetserviceconfiguration (httpapi)
EDIT: Some notes about cleanup issues inspired by Rob's comment. I put them here in this existing answer, because they don't make a good one on their own.
Please note, that whatever approach you take (httpcfg.exe or direct use of the HTTP-API), make really sure that you unregister the URLs in your uninstall process.
The reason is, that HTTP.SYS (which actually is a kernel component) has only so much (nonpaged) memory available for managing URL reservations. If you exceed this, by having to many (possibly stale / left-over) registrations, you get errors and cannot register any new URLs (see http://support.microsoft.com/kb/824033).
While this is "solvable" by manually using httpcfg.exe to cleanup registrations you think(!) are orphaned (or allowing more memory - careful!) it is a royal pain and totally unnecessary, if uninstallers work as suggested.

Hook into the Windows File Copy API from C#

Is there a way to hook into the Windows File Copy API from C#? I'm aware this would require unmanaged code, but a code sample or starter would be helpful. I've already seen the C++ code, but it's all greek.
UPDATE: I apologize, I should have been more clear about my intentions. I wish to actually change the copy feature of Windows to be more rigid (e.g. allow queing, scheduling, handle restarts, pauses, etc.). When I said hook, I meant API hook so that when someone starts a copy I get the sources and destinations and can handle it to my heart's desire. I'm old school and used to hook the Mac OS API a lot to do these things so I assumed that in the C++ WINAPI world there was some type of equiv.
Update:
As others have stated, why not just use System.IO.File.Copy(...)? It calls this same underlying API. As Michael G points out, perhaps you intend to call the the FileCopyEx API that allows you to hook progress-indication callbacks(???) That's really the only reason to P/Invoke file-copy stuff in .NET. Details on how to implement FileCopyEx that can be found here: http://pinvoke.net/default.aspx/kernel32/CopyFileEx.html
Original answer: (which you really shouldn't use...)
Code snippet removed because you really shouldn't use it...
If you're hell-bent on making busted-code, you can find out how to use it at: Found at http://pinvoke.net/default.aspx/kernel32/CopyFile.html
I wish to actually change the copy feature of Windows to be more rigid
You shouldn't do that in managed code, because of the same reasons you should not write managed shell extensions.
You can do so by calling System.IO.File.Copy. Its internal implementation already uses the Windows API.
Edit: File.Copy also handles permissions correctly and has the benefit of throwing an exception with meaningful data if something fails, so you don't have to manually check and analyze the return status.
You can use Deviare API Hook that lets you intercept any API from .NET and read parameters using VARIANT types. There is a full example very easy to follow in C#.
The other benefit of using unmanaged Copy File API is the ability to have a progress callback.
Note: as stated in other answers, I would use the managed version of File.Copy as it's safer, and can usually do everything you require.

Error logging in C#

I am making my switch from coding in C++ to C#. I need to replace my C++ error logging/reporting macro system with something similar in C#.
In my C++ source I can write
LOGERR("Some error");
or
LOGERR("Error with inputs %s and %d", stringvar, intvar);
The macro & supporting library code then passes the (possibly varargs) formatted message into a database along with the source file, source line, user name, and time. The same data is also stuffed into a data structure for later reporting to the user.
Does anybody have C# code snippets or pointers to examples that do this basic error reporting/logging?
Edit: At the time I asked this question I was really new to .NET and was unaware of System.Diagnostics.Trace. System.Diagnostics.Trace was what I needed at that time. Since then I have used log4net on projects where the logging requirements were larger and more complex. Just edit that 500 line XML configuration file and log4net will do everything you will ever need :)
Lots of log4net advocates here so I'm sure this will be ignored, but I'll add my own preference:
System.Diagnostics.Trace
This includes listeners that listen for your Trace() methods, and then write to a log file/output window/event log, ones in the framework that are included are DefaultTraceListener, TextWriterTraceListener and the EventLogTraceListener. It allows you to specify levels (Warning,Error,Info) and categories.
Trace class on MSDN
Writing to the Event Log in a Web Application
UdpTraceListener - write log4net compatible XML messages to a log viewer such as log2console
I would highly recommend looking at log4Net. This post covers the majority of what you need to get started.
Another good logging library is NLog, which can log to a lot of different places, such as files, databases, event logger etc.
I use The Object Guy's Logging Framework--as do most people who try it. This guy has some interesting comments about it.
Enterprise Library is a solid alternative to log4net and it offers a bunch of other capabilities as well (caching, exception handling, validation, etc...). I use it on just about every project I build.
Highly recommended.
Even though I personally hate it, log4net seems to be the de facto standard for C# logging. Sample usage:
log4net.ILog log = log4net.LogManager.GetLogger(typeof(Program));
log.Error(“Some error”);
log.ErrorFormat("Error with inputs {0} and {1}", stringvar, intvar);
As I said in another thread, we've been using The Object Guy's Logging Framework in multiple production apps for several years. It's super easy to use and extend.
Log4Net is a rather comprehensive logging framework that will allow you to log to different levels (Debug, Error, Fatal) and output these log statements to may different places (rolling file, web service, windows errors)
I am able to easily log anywhere by creating an instance of the logger
private static readonly ILog _log = LogManager.GetLogger(typeof([Class Name]));
and then logging the error.
_log.Error("Error messsage", ex);
Serilog is late to the party here, but brings some interesting options to the table. It looks much like classical text-based loggers to use:
Log.Information("Hello, {0}", username);
But, unlike earlier frameworks, it only renders the message and arguments into a string when writing text, e.g. to a file or the console.
The idea is that if you're using a 'NoSQL'-style data store for logs, you can record events like:
{
Timestamp: "2014-02-....",
Message: "Hello, nblumhardt",
Properties:
{
"0": "nblumhardt"
}
}
The .NET format string syntax is extended so you can write the above example as:
Log.Information("Hello, {Name}", username);
In this case the property will be called Name (rather than 0), making querying and correlation easier.
There are already a few good options for storage. MongoDB and Azure Table Storage seem to be quite popular for DIY. I originally built Serilog (though it is a community project) and I'm now working on a product called Seq, which provides storage and querying of these kinds of structured log events.
You can use built in .NET logging. Look into TraceSource and TraceListeners, they can be configured in the .config file.
Ditto for log4net. I'm adding my two bits because for actual use, it makes sense to look at some open source implementations to see real world code samples with some handy additions. For log4net, I'd suggest off the top of my head looking at subtext. Particularly take a look at the application start and assemblyinfo bits.
Further to the couple of comments realting to the use of the System.Diagnostics methods for logging, I would also like to point out that the DebugView tool is very neat for checking debug output when needed - unless you require it, there is no need for the apps to produce a log file, you just launch DebugView as and when needed.
The built in tracing in System.Diagnostics is fine in the .NET Framework and I use it on many applications. However, one of the primary reasons I still use log4net is that the built in .NET Framework tracing lacks many of the useful full featured appenders that log4net already supplies built in.
For instance there really isn't a good rolling file trace listener defined in the .NET Framework other than the one in a VB.NET dll which really is not all that full featured.
Depending on your development environment I would recommend using log4net unless 3rd party tools are not available, then I'd say use the System.Diagnostics tracing classes. If you really need a better appender/tracelistener you can always implement it yourself.
For instance many of our customers require that we do not use open source libraries when installed on their corporate machines, so in that case the .NET Framework tracing classes are a perfect fit.
Additionally - http://www.postsharp.org/ is an AOP library I'm looking into that may also assist in logging as demonstrated here on code project:http://www.codeproject.com/KB/dotnet/log4postsharp-intro.aspx.
ExceptionLess is one of the easiest nuget package available to use for logging. Its an open source project. It automatically takes care of unhandled exception, and options for manually logs are available. You can log to online or self host on local server.
Log4Net, as others have said, is fairly common and similar to Log4j which will help you if you ever do any Java.
You also have the option of using the Logging Application Block http://www.codeproject.com/KB/architecture/GetStartedLoggingBlock.aspx

Categories