50% OFF!!!

Sunday, May 22, 2011

c# WinForm | Check form window size and location

Hello,


I wanted to open a new window form, exactly near another form. (pinning one form to another).
Because of the border difference among Windows XP, Vista and Windows7 (win7), it didn't work easily.

So to determine windows size under win7/vista, I had to check if Windows Aero. (checking made by short&easy code)

Now, after checking this, I had to also support winXP (which does not have AERO technology).

For finding the left and right window border size (width) I used the SystemInformation Class which provides information about the current system environment.

Note:
I recommend to check if it works for other FormBorderStyle.

The code:
internal static bool IsAeroEnabled()
{
    bool isEnabled = false;
    if (Environment.OSVersion.Version.Major >= 6)
    {
        try
        {
            DwmIsCompositionEnabled(out isEnabled);
        }
        catch (Exception ex)
        {
            Logger.WriteLog(ex);
        }
    }
    return isEnabled;
}
[DllImport("dwmapi.dll")]
internal static extern int DwmIsCompositionEnabled(out bool enabled);

Best regard,
MDB Blog

Monday, May 2, 2011

Check HOSTS file - C# WinForms

Hello,

In today's post i'm giving a good (and simple) anti-hacking tool which allow your application to CHECK for any changes in the Windows HOSTS file.

So, the operation is simple:
Just read the hosts file content, and validate that your site DNS is not included in the list.
[basiclly, check if hosts file contains your dns name]
if so, the user probably is trying to bypass your server so you can stop him from doing so.

The code:
static bool IsDnsByPassed(string p_dnsName)
{
    string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), @"drivers\etc\hosts");
    string hostsText = File.ReadAllText(path);
    return hostsText.ToLower().Contains(p_dnsName.ToLower());
}

Note:
Although reading the HOSTS file is allowed to all user, do not try to edit the HOSTS file, because on Vista & Windows7 this operation is allowed only for administrators. if your application is NOT running as Admin, then you won't have permission for this (and an Exception will be thrown).

Best regard,
MDB-Blog

Thursday, February 10, 2011

MSI | Embed images inside MSI installer file

In this post I show how to embed images inside MSI installer file.

The first try i made was to try adding splash image and banners to the installer through Visual-Studio User-Interface. (just added two jpg files into "Common Files Folder", and set the SplashBitmap and BannerBitmap attributes). But doing so, created a problem - when changing the image, new version installer did NOT changed the images (or the images disappeared).
So i needed another solution...

The next solution is just to INSERT those images (banner&splash) directly into the MSI file created by Visual-Studio.
I created file run.js file, which automaticlly runs when the build process finished, and edits the MSI. This is achieved by setting the PostBuildEvent on the Windows Installer project.

The event that added is to the PostBuildEvent: (remember to copy the file to the main folder of the Windows Installer project)
cscript.exe "$(ProjectDir)run.js" "$(BuiltOuputPath)"

In this way, you don't have to add any image file to your project, and it s embedded in the msi file (which u can edit any time).

The run.js file:
// run.js // Performs a post-build fixup of an msi

if (WScript.Arguments.Length != 1)
{
       WScript.StdErr.WriteLine(WScript.ScriptName + " file");
       WScript.Quit(1);
}

var filespec = WScript.Arguments(0);
var installer = WScript.CreateObject("WindowsInstaller.Installer");
var database = installer.OpenDatabase(filespec, 1/*msiOpenDatabaseModeTransact*/);

var sql
var view
var record

try {

    WScript.Echo("UPDATE default banner image");

    sql = "UPDATE `Binary` SET `Data` = ? WHERE `Name`= 'DefBannerBitmap'";
    view = database.OpenView(sql)
    record = installer.CreateRecord(1);
    record.SetStream(1, "C:\\installer_banner_img.jpg");
    view.Execute(record);
    view.Close();
       WScript.Echo("ADD splash image");
    sql = "INSERT INTO `Binary` (`Name`, `Data`) VALUES ('DefSplashBitmap', ?)";
    view = database.OpenView(sql)
    record = installer.CreateRecord(1);
    record.SetStream(1, "C:\\Installer_splash_img.jpg");
    view.Execute(record);
    view.Close();

    WScript.Echo("Update splash control");
    sql = "UPDATE `Control` SET `Text`='DefSplashBitmap' WHERE `Dialog_`='SplashForm' AND `Control`='SplashBmp'";
    view = database.OpenView(sql)
    view.Execute();
    view.Close();
       database.Commit();
}
catch (e) {
    WScript.StdErr.Write("|||ERROR||| ");
    WScript.StdErr.WriteLine(e.Message);
    WScript.Quit(1);
}

Note:
Before running this script, add a splash screen to the installer (using User-Interface view in Visual Studio)

(*) this is also a good example how to add/update binary(image) into your MSI using a sql script.

Best regard,
MDB-Blog

Tuesday, February 1, 2011

C# | Determine if Adobe (Macromedia) Flash player installed.

All started when I needed to integrate an Adobe (Macromedia) Flash object in my C# WinForm application.
I saw several posts about it, where two solutions where presents:
1. Add WebBrowser Control and just nevigate to the "test.swf" file.
2. Create COM object of ADOBE MACROMEDIA.

I liked the 1st option more, because I don't need to handle COM objects (and to add another DLL to the app).
Here is the code I used:
WebBrowser wb = new WebBrowser();
//wb.Location = SOME LOCATION
//wb.Size = SOME SIZE
wb.AllowNavigation = false;
wb.IsWebBrowserContextMenuEnabled = false;
this.Controls.Add(wb); // this = FORM
wb.Navigate(@"C:\test.swf");

BUT, Then i noticed that when a pc do NOT have Adobe (Macromedia) Flash player installed, the webbrowser display a big red X.
SO, before I use the FLASH image in my winform application, I needed to check if FLASH player is INSTALLED or not!

The idea is to check the registry for:
HKEY_LOCAL_MACHINE\SOFTWARE\Macromedia\FlashPlayer\CurrentVersion

And indeed it worked!
Here is the full code for testing if FLASH installed (and also get the major Version):
internal static int? GetFlashPlayerVersion()
{
    using (RegistryKey rk = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Macromedia\FlashPlayer"))
    {
        if (rk != null)
        {
            string version = rk.GetValue("CurrentVersion") as string;
            if (string.IsNullOrEmpty(version) == false)
            {
                int idx = version.IndexOf(",");
                if (idx > 0)
                {
                    int value;
                    if (int.TryParse(version.Substring(0, idx), out value) == true)
                    {
                        return value;
                    }
                }
            }
        }
    }
    return null;
}

And the code which using the method:
int? flashVersion = WindowsUtils.GetFlashPlayerVersion();
if (flashVersion.HasValue == true && flashVersion > 6)
{
    WebBrowser wb = new WebBrowser();
    wb.AllowNavigation = false;
    wb.IsWebBrowserContextMenuEnabled = false;
    this.Controls.Add(wb); // this = FORM
    wb.Navigate(@"C:\test.swf");
}

Best regards,
MDB-Blog