Solibulo

Uninteresting things

NSSM, a free “modern” alternative to srvany+instsrv

by softlion 28. December 2009 11:32

 

 

When you want to run a program as a service on Windows, the program have to be created specifically for this by implementing the Windows service interface.

 

When you don’t want to waste your time, or for any reason you could think of, there is a solution to run an exe as service. You can use the well known solution combining instsrv+srvany which works only on 32 bit windows, or NSSM which now works both on Win32 and x64.

 

Usage: type NSSM without argument:

 

image

 

Practical usage

 

For use in a single install.bat batch file without any user interaction:

 

rem stop and uninstall the service. Useful if the .bat is run twice.
sc stop YourServiceName
nssm remove YourServiceName confirm


rem install and configure the service
nssm install YourServiceName “%CD%\Your Service Name.exe” 
sc config YourServiceName start= auto depend= tcpip/LmHosts/Eventlog
sc description YourServiceName "Description of your service for display in service manager"
sc start YourServiceName 

 

In .bat files, %CD% is replaced with the current path.

 

Our service is configured to start at boot (start= auto), so we need to specify which service should be up before this service can start (depend= …)

 

Replace nssm by nssm-x64 if you run on 64 bits Windows.

 

Download

 

Download File - NSSM-2.1

 

References

 

Original NSSM (2006)

 

 

___

Tags:

General

How To: modify the default template of "Create New Stored Procedure" in SQL Server Management Studio

by softlion 1. December 2009 14:44

 

Simply modify the file “Create Stored Procedure (New Menu).sql” in:

 

C:\Program Files\Microsoft SQL Server\(version: 90, 100, …)\Tools\Binn\VSShell\Common7\IDE\SqlWorkbenchProjectItems\Sql\Stored Procedure

Tags:

sql

How to fix a bug in an obfuscated third party DLL

by softlion 1. December 2009 12:55

Recently a customer wanted me to evaluate the cost and fix all XSS holes in their website. Their security specialist found some holes using an obscure software only security specialists have and gave me his report and a list of webpage where it occurs.

After some digging I found there was one main hole - the same and on every page of their website. The hole was coming from the code of an UI component, a four years old version of the Telerik UI library for ASP.NET where XSS was not in the light.

 

My first report was to replace this component everywhere. As it would cost too much to the company, I was aimed to propose another solution : decompile the faulty assembly, find and fix the bug, and recompile it. It seemed easy. Helas ! This commercial library is obfuscated by Xenocode (a commercial obfuscator) which removes a lot of code unused by the CLR but necessary to the recompilation. So it was not an option.

 

THE SOLUTION

 

Then I came with an idea from my childhood where I was playing with raw asm and modified a tetris software because the blocs were not rotating in the correct direction …

Why not replace the faulting method pointer with the pointer of a fixed method dynamically in memory ? A lot of things run against this idea.One of them is that the code memory area is protected since Windows XP. And code injection does not work on 64 bit platforms at all.

Then I googled and found the graal… A post by Ziad Elmalki called “CLR Injection: Runtime Method Replacer”.

 

With a few lines of code I make it work with the web project.

I created a class “Demo.Fix” with a method InjectFix to be called in global.axax’s Application_Start event.

The first thing this method does is to check wether the assembly containing the code to fix is already loaded. If it is not it handles the AppDomain’s AssemblyLoad event.

 

using System; using System.Reflection; using System.Web; using System.Linq; using NativeAssemblerInjection; namespace Demo { public class Fix { /// <summary> /// Dynamically replace the failing method with our /// </summary> /// <remarks> /// First search if the assembly containing the class and method to replace is already /// loaded. If it is not already loaded, handle the AssemblyLoad event on the /// application domain. /// </remarks> public static void InjectFix() { var assembly = (from a in AppDomain.CurrentDomain.GetAssemblies() where a.FullName.Contains("FaultingAssemblyName") select a).FirstOrDefault(); if (assembly != null) DoReplace(assembly); else AppDomain.CurrentDomain.AssemblyLoad += CurrentDomain_AssemblyLoad; } /// <summary> /// Wait for the assembly containing the class and method to replace to be loaded. /// </summary> /// <param name="sender"></param> /// <param name="args"></param> static void CurrentDomain_AssemblyLoad(object sender, System.AssemblyLoadEventArgs args) { if (args.LoadedAssembly.FullName.Contains("FaultingAssemblyName")) { DoReplace(args.LoadedAssembly); AppDomain.CurrentDomain.AssemblyLoad -= CurrentDomain_AssemblyLoad; } } /// <summary> /// Dynamically replace the failing method in <paramref name="assembly"/> by our /// own method. /// </summary> /// <param name="assembly">assembly containing the failing method</param> private static void DoReplace(Assembly assembly) { MethodBase oldMethod = assembly.GetType("FullNamespace.WebControls.x7fbe3d3b15648174")

.GetMethod("xe07c485b9dc80480", BindingFlags.NonPublic | BindingFlags.Instance); MethodBase newMethod = typeof(Fix).GetMethod("ReplacementMethod", BindingFlags.NonPublic | BindingFlags.Instance); MethodUtil.ReplaceMethod(newMethod, oldMethod); } /// <summary> /// Replacement method which corrects the behaviour of the original method /// </summary> /// <remarks> /// The signature must be the exact same as the original method. When called, the context /// (this) is the one from the original object, not the one from this class. /// </remarks> private string ReplacementMethod() { ... } } }

And it works both in 32 and 64 bits … amazing.

 

References

CLR Injection: Runtime Method Replacer

Tags:

Easy Snippet: get embedded resource

by softlion 16. November 2009 18:07

 

       public static string GetEmbeddedTextResource(string fullyQualifiedNameOfResource)
        {
            var assembly = Assembly.GetCallingAssembly();

            using (var reader = new StreamReader(assembly.GetManifestResourceStream(fullyQualifiedNameOfResource)))
            {
                //Automatic close/dispose
                return reader.ReadToEnd();
            }
        }

        public static byte[] GetEmbeddedBinaryResource(string fullyQualifiedNameOfResource)
        {
            var assembly = Assembly.GetCallingAssembly();
            byte[] result;

            using (var stream = assembly.GetManifestResourceStream(fullyQualifiedNameOfResource))
            {
                var reader = new BinaryReader(stream);
                result = reader.ReadBytes((int)stream.Length);
                reader.Close();
            }

            return result;
        }

 

Tags:

Silverlight 3 – Tip of the month #2 - Using Data Binding with Static Resources in Silverlight

by softlion 10. October 2009 13:06

 

In his blog, Pedro wrote a post showing how to bind a property to a static resource where the resource name is given by the binded property. But his solution needs WPF libraries and does not work in Silverlight.

This is the first way to write it which comes to mind. But it doesn’t work as StaticResource does not support Binding (it is static by nature).

<Image Source="{StaticResource {Binding AvailabilityStateResourceName}}" />

 

The solution I came with is elegant. It uses a custom converter to find the resource in the application resource dictionary. The binding source must be a string containing the name of the static resource.

 

<Image Source="{Binding AvailabilityStateResourceName, Converter={StaticResource StaticResourceConverter}}" />

 

To use it, declare a static resource refering to the converter like this:

<Application ...
             xmlns:shc="clr-namespace:Softlion.Silverlight.Shared.Converters;assembly=Softlion.Silverlight.Shared" 
             >
    <Application.Resources>
        <shc:StaticResourceConverter x:Key="StaticResourceConverter" />
        ...
    </Application.Resources>
</Application>

 

And the source code of the StaticResourceConverter which is simple and straightforward:

using System;
using System.Windows.Data;
using System.Windows;

namespace Softlion.Silverlight.Shared.Converters
{
    /// <summary>
    /// Enables a binding on a static resource in the application resource dictionary.
    /// Convert from a static resource name to a resource instance in the application resource dictionary.
    /// </summary>
    public class StaticResourceConverter : IValueConverter
    {
        #region IValueConverter Members
        /// <summary>
        /// Convert from a static resource name to a resource instance in the application resource dictionary.
        /// </summary>
        /// <param name="value">must be a reference to an existing resource in the application resource dictionary</param>
        /// <param name="targetType">defined by the resource</param>
        /// <param name="parameter">not used</param>
        /// <param name="culture">not used</param>
        /// <returns>A resource in the Application.Current.Resources dictionary</returns>
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (!(value is string))
                throw new ArgumentException("value");

            return Application.Current.Resources[value];
        }

        /// <summary>
        /// Not implemented, no use
        /// </summary>
        /// <param name="value"></param>
        /// <param name="targetType"></param>
        /// <param name="parameter"></param>
        /// <param name="culture"></param>
        /// <returns></returns>
        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
        #endregion
    }
}

SL3 – Sunday reviews

by softlion 4. October 2009 10:12

Bryant Likes wrote a good post about choosing how to add a functionality to an existing control : behaviour, subclassing or attached property along with an example for each.

Behaviors vs Subclassing in Silverlight

 

Timmy Kokke wrote a detailed post about how to style a treeview.

http://geekswithblogs.net/tkokke/archive/2009/06/29/styling-a-treeview-in-silverlight-and-blend-3.aspx

Silverlight 3 - Tip of the month #1 – Binding Color property

by softlion 4. October 2009 08:04

In XAML you can not bind a property of type Color directly. I’m not sure why. Maybe because it is a structure (ie: value type).

You can bind a Brush instead :

 

[DataMember]
internal Color color;
public Brush DisplayColorBrush { get { return new SolidColorBrush(color); } }

 

Binding to a static color resource is working though:

<TextBlock.Foreground>
    <SolidColorBrush Color="{StaticResource UserOffersInfoColor}"/>
</TextBlock.Foreground>

 

<Application.Resources>
    <Color x:Key="UserOffersInfoColor">#FFE97F26</Color>
</Application.Resources>

 

Binding a Text property in a Run tag of a TextBlock tag doesn’t work either. You must bind to the Text property of the TextBlock tag instead.

<TextBlock Margin="6,3" FontWeight="Bold" FontSize="12">
    <Run Text="Chips: "/>
    <Run Text="{Binding ChipsRemaining}"/>
</TextBlock>

What outbound ip is used by windows and when ?

by softlion 3. September 2009 08:54

Or how the hell windows selects a network interface and an ip address from that interface (if it has more than one) for outbound packets ?

This excellent and easy to understand post from the Microsoft Network Team explain it all, along with differences between Win3K/XP and Win2K8/Vista.

Read it there: http://blogs.technet.com/networking/archive/2009/04/24/source-ip-address-selection-on-a-multi-homed-windows-computer.aspx

 

I repro it here: More...

How to improve the much-to-be-desired Silverlight installation experience?

by softlion 29. July 2009 10:02

The Silverlight installation in all browsers is confusing, unsettling, and scary.

 

Update 09/2009 : you can get Microsoft's white paper and sample code about Silverlight installation.

Because of the numerous security warnings and lack of options other than to abort installation, you unfortunately get the false impression that Silverlight is a Trojan horse of sorts that "could infect and harm your computer with viruses and malicious code" with no apparent way to protect your computer other than agreeing to install it and hope for the best.

In addition you have to download a file then go find it then execute it.

It is a step that many people finds frustrating.

It will likely be a reason why they never get Silverlight installed on their machine.

And a reason I will lost them as customers.

 

Silverlight installation experience in FIREFOX 3:

  • see: the graphic button to "Install Microsoft Silverlight" (which I put in my object tag)
  • click the button
  • see: "you have chosen to install Silverlight 3.0" [save file] [cancel]
  • click [save file]
  • click [save]
  • (sit there wondering what happened)
  • ...eventually ask someone what to do or get lucky and right click download message and choose "open"
  • see: "silverlight 3.0.exe" is an executable file...may contain viruses...malicious code...harm your computer...use caution...are you sure?... [OK] [Cancel]
  • in spite of the fear that I am infecting my computer with "viruses and malicious code", I click [OK]
  • see: "Security warning...may potentionally harm your computer..." [Run] [Cancel]
  • fearfully click "Run"
  • says: "extracting files...Install Silverlight 3" one button: [Install Now]
  • click [Install Now]
  • says: "Silverlight is being installed on your computer", then shows checkbox "enable microsoft update (recommended) ... privacy statement..." [Next]
  • click [Next]
  • says: "Installation Successful, you may have to refresh the web page..." [Close]
  • click [Close]
  • go back to web page and click the refresh button on browser
  • I see the silverlight application, success.

Silverlight installation experience in INTERNET EXPLORER 6/7/8:

  • see: the graphic button to "Install Microsoft Silverlight" (which I put in my object tag)
  • click the button
  • see: "To help protect your security...blocked this site from downloading files to your computer" and "did you notice the information bar" [OK]
  • click [OK]
  • (sit there wondering what to do)
  • finally click the bar on top, see "what's the risk?" click "download file" anyway
  • see: "Security warning...may potentionally harm your computer..." [Run] [Cancel]
  • click [Run]
  • watch it download, 15 seconds
  • see: "Security warning...can potentially harm your computer" [Run] [Don't Run]
  • click [Run]
  • says "Install Silverlight 3" one button: [Install Now]
  • click [Install Now]
  • says: "Silverlight is being installed on your computer", then shows checkbox "enable microsoft update (recommended) ... privacy statement..." [Next]
  • click [Next]
  • says: "Installation Successful, you may have to refresh the web page..." [Close]
  • click [Close]

Someone answered:

Well, considering you now know what steps the user is going to have to do you could create a help page for the user. Granted, it isn't the best thing (a simplified install experience would be better, obviously) but at least the user would be able to easily find steps on what is going on.

Source: http://stackoverflow.com/questions/523596/how-to-improve-the-much-to-be-desired-silverlight-installation-experience

Tags:

Bug with Blend 3 RC and sample data

by softlion 25. July 2009 12:26

 

This has been fixed in RTM version : in the "build action" property of all files which are in the SampleData folder a "DesignTimeOnly" value is set so sample data is no compiled in your release project (if you unticked the "Enable when running Application" choice in the datasource property in Blend 3).

 

Update: it is not fixed at all ! The .cs file is still set to "compile" (as the referenced sample data is still in app.xaml this makes sense). This workaround is still needed.

 

In Blend 3 there is a userful feature called sample data which helps design UIs binded to data not currently existing.

 

When using this feature, blend adds a “SampleData” folder in your silverlight project, and new XAML files with their associated codebehind (.xaml.cs). It also modifies your App.xaml to reference the sample data class and creates a new global instance of this xaml.

 

When switching to release mode, your xap file will grow bigger than needed. So in the xaml.cs file there is a conditional compilation symbol which can be define in ‘project/properties/build’ tab to minimize the content of the cs file: DISABLE_SAMPLE_DATA

 

The default .xaml.cs generated by blend 3 contains :

 

#if DISABLE_SAMPLE_DATA
    internal class BoardInfosDataSource { }
#else

 

But when in release mode, the compiler removes all non public unused objects. And your silverlight application will throw an errror (if you use asp:Silverlight you won’t see the error just a blank screen. Use the object tag with onerror set to your javascript instead. See MSDN for more infos.).

 

To correct this set the class public:

 

#if DISABLE_SAMPLE_DATA
    public class BoardInfosDataSource { }
#else

 

Tags: