Command-line scanning a directory or file with Microsoft Security Essentials

After doing the usual web search with Google and Bing I found only sites claiming doing a scan with Microsoft Security Essentials of a file or directory from the command-line was not possible. Most sites just say it’s possible to initiate a quick or full scan or even update signatures from the command-line. But as Microsoft Security Essentials has real-time protection there is no need to scan manually (as a lot of us are used to) to make sure the file is scanned.

But on Windows 7 (x64 version confirmed) the tools in %ProgramFiles%\Microsoft Security Client contain some files that look promising. My first guess was to look into %ProgramFiles%\Microsoft Security Client\msseces.exe, but that program only pops-up the user-interface and worse case starts a default scan.

As Microsoft Security Essentials is able to scan manually (it has a explorer context menu, located in %ProgramFiles%\Microsoft Security Client\shell.ext.dll)

A far shot was to search for rundll32 to be used to fire the context menu but all I found was references to viruses and trojans doing the same (so not the best way to walk)

Finally I accidently fired up one of the other executables in %ProgramFiles%\Microsoft Security Client with a promising name (MpCmdRun.exe) with a switch –h and voila a long description with the answer tucked inside.

By issuing the command

“%ProgramFiles%\Microsoft Security Client\MpCmdRun.exe” -Scan -ScanType 3 –File “<file or folder to scan>”

one is able to start the command-line version of Microsoft Security Essentials, make it perform a file or folder scan and thus integrate it with popular tools like Winrar like:

image

Note: although %ProgramFiles% points to c:\program files at both Windows x86 and x64, not all applications will expand it properly to something like c:\program files.

Posted in Uncategorized | Leave a comment

Getting the Name of a C# Component.

Today I had the need to address a C# Component I wrote and that is part of a larger C# UserControl by name (so by a String). I know there are other ways to address components but for some reason I will not explain in this blog post I needed this feature.

The main problem is that Components do not have a Name property although in the Visual Studio Property Inspector components do show a ‘(Name)’ property containing the value I was after.

I started searching the internet but without luck. Plenty of solutions for Controls but none for Components except for the obvious ‘why do need this anyway’ type of non-solutions and a fair number of unanswered questions.

Some months ago I already solved a minor piece of the puzzle by finding a way to get the Component’s Name at Design Time.

A simple ToString() and some string cutting was enough to get the value of the myserious ‘(Name)’ property. This with one limitation, the Component should not have it’s own ToString() method overriding the default one.  The following code does the trick:

   1: /// <summary>

   2: /// GetName() only works at Design Time.

   3: /// </summary>

   4: /// <returns>The Name of the Component as shown in the Designer</returns>

   5: public string GetName()

   6: {

   7:     int split = ToString().IndexOf(' ');

   8:     return ToString().Substring(0, split);

   9: }

However nice this works on Design-Time, on Run-Time this code fails completely as the ToString() is empty or at best contains the class name of the Component.

So how do we get this Design-Time value available at Run-Time? The answer was a specially defined property that behaves differently at Design and Run-Time.

   1: [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]

   2: [Browsable(false)]

   3: public String ColumnName

   4: {

   5:     get

   6:     {

   7:         //If at designTime we store GetName into fColumnName.

   8:         if (ToString().IndexOf(' ') != -1)

   9:         {

  10:             fColumnName = GetName();

  11:         }

  12:         return fColumnName;

  13:     }

  14:     set

  15:     {

  16:         //If at designTime we store fColumnName and ignore value.

  17:         if (ToString().IndexOf(' ') != -1)

  18:         {

  19:             fColumnName = GetName();

  20:         }

  21:         else

  22:         {

  23:             fColumnName = value;

  24:         }

  25:     }

  26: }

  27: private String fColumnName;

 

Above code will use part of the GetName() method’s code to distinguish between Design-Time (ToString()’s value is a combination of Design-Time name and ClassName separated by a space) and Run-Time where ToString() is just the ClassName.

The getter and setters work differently at Design-Time and Run-Time.

Both getter and setter set the private storage field ‘fColumnName’ at Design-Time with the value returned by GetName() and the getter off-course returns this value. So on Design-Time the setter totally ignores the ‘value’ parameter passed.

On Run-Time the getter does return the private storage field and the setter does set it with value as a normal property would do.

Finally, the attributes of the property make sure it is not visible in the property inspector but will be saved into the *.designer.cs file properly. I experimented with the ReadOnly attribute too but that only leads to the form designer not saving the property into the *.designer.cs file. If you remove the ‘Browsable’ attribute or set it to true you can see the ColumnName property at Design-Time.

Basically what happens is that the Design-Time value end up in the private storage field of a property that is saved into the *.designer.cs file. At Run-Time GetName() is totally ignored and the value retrieved from the *.designer.cs file is used as if it where a normal property.

The result is a property that changes nicely when a Component is renamed and cannot be edited at Design-Time but is serialized into the *.designer.cs file as it should.

Note: the code presented in this blog post only works on Components you write yourself and frees you from maintaining a separate Name property that has no actual link to the Components Design-Time name nor will be adjusted when renaming the Component.

Maybe someone can bolt it on with an extension method.

Posted in Uncategorized | Leave a comment

Static properties on design-time

A couple of weeks ago I was working on a component to use & generate html help files. The idea was to drop a component on each form where it would do it’s work:

  1. Generate files for Microsoft’s HtmlHelp Workshop when executed from Visual Studio.
  2. Show all kind of context sensitive help when executed outside Visual Studio.

During the writing I needed an Enable property visible in the property inspector of Visual Studio that was global to all instances of my component.

I used the following (simple) construct:

   1:  

   2: public Boolean Enabled {

   3:   get { 

   4:     return fEnabled; 

   5:   }

   6:   set { 

   7:     fEnabled = value; 

   8:   }

   9: }

  10:  

  11: private static fEnabled = true;

  12:  

This code shows a Enabled property in the property inspector, but when the value is of a single component instance is changed, the changed value in all other instances too.

Posted in C#, Programming | Leave a comment

RadioCheck for MenuToolStrip

Today I wanted to code a submenu with menu items that are checked like a radio button group. So once a single menu item has been checked, there is exactly one item checked all the time.

The task proved a bit harder than I expected. The RadioCheck property is no longer present in MenuToolStrip and ToolStripMenuItem as it was in the old MenuItem class.

So time to code one!

Basically the code below assumes you have a ToolStripMenuItem which contains all ToolStripMenuItems that are part of the radio button group in its DropDownItems collection.

Optionally you may check one ToolStripMenuItem as startup. Once a ToolStripMenuItem is checked there is no way to uncheck them all.

Each of these ToolStripMenuItems must have the CheckOnClick property set to true and have a event handler attached like:

   1: tmi.CheckedChanged += new EventHandler(tmi_CheckedChanged);

 

The event handler code below unchecks all other ToolStripMenuItems in the DropDownItems collection in such way that one does not end up with a stack overflow exception.

   1: /// <summary>

   2: /// Simulate RadioCheck MenuItems.

   3: /// </summary>

   4: /// <param name="sender"></param>

   5: /// <param name="e"></param>

   6: void tmi_CheckedChanged(object sender, EventArgs e)

   7: {

   8:     ToolStripMenuItem tmi = (ToolStripMenuItem)sender;

   9:     ToolStripItemCollection items = ((ToolStripMenuItem)(tmi.OwnerItem)).DropDownItems;

  10:  

  11:     //Make sure that one menu item is always checked.

  12:     if (tmi.Checked)

  13:     {

  14:         //Uncheck all other menu items.

  15:         foreach (ToolStripMenuItem tmi2 in items)

  16:         {

  17:             if (!tmi.Equals(tmi2) && tmi2.Checked)

  18:             {

  19:                 tmi2.Checked = false;

  20:             }

  21:         }

  22:     }

  23:     else

  24:     {

  25:         //If anything else is already checked, 

  26:         //bail out to prevent a stack overflow.

  27:         foreach (ToolStripMenuItem tmi2 in items)

  28:         {

  29:             if (tmi2.Checked)

  30:             {

  31:                 return;

  32:             }

  33:         }

  34:  

  35:         //If nothing is checked, check ourselves again.

  36:         tmi.Checked = true;

  37:     }

  38: }

/// <summary>
/// Simulate RadioCheck MenuItems.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void tmi_CheckedChanged(object sender, EventArgs e)
{
    ToolStripMenuItem tmi = (ToolStripMenuItem)sender;
    ToolStripItemCollection items = 
((ToolStripMenuItem)(tmi.OwnerItem)).DropDownItems; //Make sure that one menu item is always checked. if (tmi.Checked) { //Uncheck all other menu items. foreach (ToolStripMenuItem tmi2 in items) { if (!tmi.Equals(tmi2) && tmi2.Checked) { tmi2.Checked = false; } } } else { //If anything else is already checked, //bail out to prevent a stack overflow. foreach (ToolStripMenuItem tmi2 in items) { if (tmi2.Checked) { return; } } //If nothing is checked, check ourselves again. tmi.Checked = true; } }
Posted in C#, Programming, Windows | Leave a comment

Access a local Tomcat through Apache

Heard a nice ‘trick’ some time ago I need to write about (so I do not forget it ;-).

I wanted to access a tomcat web application on a server that was mainly running a Drupal CMS.

As I do not like shooting holes in firewalls I dislike the use of port 8080 too. The solution I heard was both simple and elegant.

Basically one installs and configures a Tomcat server and deploy a web application on this Tomcat server listening top a port that can only be reached on the server itself (8081 in the example below).

In the Apache ‘httpd.conf’ file you enable mod_proxy by uncommenting the line:

   1: LoadModule proxy_module modules/mod_proxy.so

Then you define a mapping of the tomcat URL to a URL inside the apache servers web space.

   1:  

   2: # http://<ip>:8081//?">http://<ip>:8081/<Webapp>/<Webappurl>?<parameters>

   3: # is mapped mapped to: 

   4: # http://<ip>/<Webappurl>?<parameters> 

   5:  

   6: ProxyPass /OAIHandler http://127.0.0.1:8081/LiLiTarget/OAIHandler

   7: ProxyPassReverse /OAIHandler http://127.0.0.1:8081/LiLiTarget/OAIHandler

In above example:

  • 8081 is the local port to the Tomcat server, not reachable from the outside.
  • 127.0.0.1 is the local address of the server, not reachable from the outside.
  • OAIHandler is a URL inside the web application that does the work (and I re-used it as URL inside the Drupal webspace). URL parameters are nicely appended.
  • LiLiTarget is the name of the web application inside Tomcat’s ‘webapps’ directory.
  • The name of the web application is not used as part of the URL.

Nice side effect of this approach is that you easily swap Tomcat servers or have multiple Tomcat servers running, each with their own port number and each running only a single webapp deployed. This way you can nicely restart/maintain a single Tomcat without affecting the reset of the instances or have multiple Tomcat versions running on a single server.

Posted in Tomcat | Leave a comment

JScript parameters

Ever wondered how to get rid of those pesky *.js.php files where you need PHP to write a single variable into a JScript?

After a lot of searching I stumbled upon a nice solution (see http://feather.elektrum.org/book/src.html) that allows you to pass query parameters to a script in it the SCRIPT’s tag’s SRC attribute just like normal html pages. The problem inside the script is that there are potentially two sets of query data, one for the script (the one we’re after) and one for the page the script is a part of. This last set is access through the usual window.location object.

   1: var scripts = document.getElementsByTagName('script');

   2: var myScript = scripts[ scripts.length - 1 ];

   3:  

   4: var queryString = myScript.src.replace(/^[^\?]+\??/,'');

   5:  

   6: var params = parseQuery( queryString );

   7:  

   8: function parseQuery ( query ) {

   9:    var Params = new Object ();

  10:    if ( ! query ) return Params; // return empty object

  11:    var Pairs = query.split(/[;&]/);

  12:    for ( var i = 0; i < Pairs.length; i++ ) {

  13:       var KeyVal = Pairs[i].split('=');

  14:       if ( ! KeyVal || KeyVal.length != 2 ) continue;

  15:       var key = unescape( KeyVal[0] );

  16:       var val = unescape( KeyVal[1] );

  17:       val = val.replace(/\+/g, ' ');

  18:       Params[key] = val;

  19:    }

  20:    return Params;

  21: }

After which you can simple use it with params[‘course’] or whatever you’re after.

Posted in Uncategorized | Leave a comment

Tomcat running on x64

Today I solved a problem that hunted me for the last couple of days. When I use Eclipse x64 and startup Tomcat, the Tomcat server runs in 32 bits mode.

So I started Googling for answers and found not much more than that it should be supported since version x. No luck thus.

Today I took another approach: I uninstalled all 32 bits Java versions and also the x64 JRE so I only had a single x64 JDK left on my machine. This off-course crashes the 32 bits Eclipse version I still have hanging around but that’s another story.

Starting Tomcat with this configuration still showed a 32 bits Java version. So I started examining the batch files used for Tomcat startup. There I found a curious setenv.bat containing code to reset the JRE_HOME after probing the bundled Tomcat JRE.

The resolution was simple (if the JAVE_HOME environment variable is set correctly to the x64 JDK location), just delete the bundles 32 bits JRE directory and Tomcat will happily start in 64-bits mode.

Nice side-effect is that I know only have to update a single Java version and am freed of yet another old bundled version that isn’t automatically updated.

Posted in Tomcat | Leave a comment

Command line completion for Windows

When using a command shell on Linux another Unix dialect you have the ability to complete a part of a path by pressing tab. I was always under the impression that windows did not have such thing (off-course it does have auto completion in the gui but not at the command line). Big was my surprise when I encountered an obscure option of cmd.exe (the Windows command interpreter/shell). The option, /f (or /f:on or /f:off) lets you toggle path and filename completion on and off under windows when inside a cmd console window. The default keys for completion are CTRL-F for filenames and CTRL-D for directories. The Windows command interpreter even automatically inserts or removes quotes when necessary it encounters spaces in a path or filename. In the registry one can even change the keys for both completions to both the same key (tab for instance to mimic Unix). It’s also possible to set these keys on either a user-by-user basis or system-wide. I only did not find a way to turn it on permanently, but the easiest way around this is to simply add /f:on to a cmd.exe shortcut. The registry keys are:

HKEY_LOCAL_MACHINE\Software\Microsoft\Command Processor\CompletionChar
HKEY_LOCAL_MACHINE\Software\Microsoft\Command Processor\PathCompletionChar

for the logged-on user and:

HKEY_LOCAL_MACHINE\Software\Microsoft\Command Processor\CompletionChar
HKEY_LOCAL_MACHINE\Software\Microsoft\Command Processor\PathCompletionChar

for all users. The values are the character codes in hex. For more information just Google.

Posted in Windows | Leave a comment

Debugging Java HTTP sessions

At the moment I use 32 bits Eclipse under Windows 7 x64 for writing Java applications.

Some days ago I tried to mimic a web browser session that included logging into Drupal.

Because Drupal uses form based login and cookies, I installed a Drupal module that allows HTTP authentication for a single page. So for that page the IE, Chrome or Firefox login dialog pops up nicely. After analyzing the traffic with my favorite too called Fiddler I saw that after the authentication a cookie was set and I could submit a form post containing the usual multi-part mime stuff.

So my goal was to mimic this in Java and perform a whole bunch of post request with generated multi-part mime form data.

But after writing some basic code I noticed that I was virtually blind regarding to what exactly went over the IP connection between java and server. So I started looking for enabling Fiddler for Java. I know there are some java tools that act just alike (create a proxy between the application and the server) but Fiddler is very rich tool that checks for a whole plethora of protocol errors and offer a good insight in timing, performance and content.

After some digging around I found that I had to add two lines of code to be able to connect the Java application through the Fiddler proxy to the web server:

HttpURLConnection conn;
try {
  //Enable Fiddler2 (set Java HTTP Proxy in code)
			
  Properties systemProperties = System.getProperties();
  systemProperties.setProperty("http.proxyHost", "127.0.0.1");
  systemProperties.setProperty("http.proxyPort", "8888");

  //Create an HttpURLConnection etc...
  conn = (HttpURLConnection) url.openConnection();

After this you can instruct Fiddler to listen only to non web-browser applications.

Unfortunately it did not help as the Drupal module (or Drupal itself) somehow rejected the HTTP POST request, but I was able to login and obtain the required session cookie from Drupal. I solved my problem by using just executing a series of Drush commands (Drush is a Drupal Shell module).

Posted in Programming | Leave a comment

Add an additional directory to the Global Assembly Cache

Today I re-found an old trick I used to keep all my assemblies in a single place but outside the global cache of DotNet. The ‘trick’ works by adding your own search location to the assembly cache. As there is only a single GAC, it actually consists of more then one directory and that is what I used.

As It took me two hours to find it again it’s time to document it somewhere.

First the advantage:

We’ll the advantage is that you always have a single version of a assembly without to much fuzz. And a single place where all your dll’s pdb’s en xml files go when building an assembly.

Second, the how:

  1. Simply create a directory where you want your own assembly dll’s, pdb’s and xml files to go.
  2. Then add a key under HKLM\Software\Microsoft\.NetFramework\AssemblyFolders  (like MyAssemblies).
  3. In this key set the default REG-SZ value to the full path of your own newly created assembly directory.

Working with it:

  • The only thing you have to do when you compile a assembly set the output path to your own assembly folder. Your own controls will now show up nicely in the Visual Studio Toolbox as a result.
  • Visual Studio normally copies the dll’s into the applications output directory at each build, so you will have an up to date version there.
  • Creating installers also works like normal as Visual Studio only looks at the referenced assemblies and tries to locate them in the applications output folder.

Drawbacks:

  • I have found no serious drawbacks in this solution.
  • Sometimes you have tell the project not to use a specific version but the latest (by double clicking the reference in the solution explorer).
    If you forget to set the output path the assemblies will go in the normal location.
Posted in Uncategorized | Leave a comment