Commentor Blog

When Quality Matters

Commentor A/S

When Quality Matters

Contact usSend mail

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2010

Tech Talk Statisk Kode analyse

TecTalken gennemgik, hvorledes Visual Studio Team System 2008's statiske analyse kan benyttes til at højne ensartetheden og kvaliteten. Det blev gennemgået hvorledes reglerne kan tilpasses og nye regler kan implemeneteres. Herudover blev der fremlagt en "hvordan kommer vi i gang strategi".

 

Powerpoint ligger i Statisk Kodeanalyse Techtalk.pptx (722,96 kb)

Og regel-eksemplerne ligger i CommentorFxCopRules.zip (9,77 kb)

Currently rated 5.0 by 1 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Posted by ole.hedegaard on Wednesday, October 15, 2008 7:25 AM
Permalink | Comments (9) | Post RSSRSS comment feed

Tech Talk: Visual Studio Team System Profiler

TechTalken gennemgik, hvorledes Visual Studio Team System 2008 Profiler kan benyttes til nemt at finde flaskehalsene i C# programmer. Der blev gennemgået, hvilke muligheder profileren giver udvikleren.  

Der blev givet to praktiske eksempler på, hvorledes profileren bedst kan benyttes i forskellige scenarier til at finde flaskehalse, og hvad der kan gøres for at afhjælpe disse: Mandelbrot Fraktal tegningsprogram og et database deserialiseringsproblem.   

Gennemgangen af profileren dækkede de to metoder til performance-målinger: Sampling versus Instrumentering.  Herefter gennemgik jeg de forskellige views på de opsamlede målinger med fokus på hvilke, der kan bruges til hvad. 

Jeg har vedhæftet Profiler Techtalk.pptx (656,39 kb), et ”pseudo” profiler FattigMandsProfiler.zip (3,86 kb), og de to eksempler før optimeringen  DbTrial_Org.zip (3,70 kb) og   MandelC_.zip (22,46 kb).

Den sidste med tak til http://www.codeproject.com/KB/graphics/mandelbrot.aspx

Takker for det fine fremmøde og gode spørgsmål...

Efter ønske er her det optimerede datainitialiseringsprojekt: DbTrial_Tech_Talk.zip (3,63 kb)

Og analysen af forbedringen - en lidt skuffende faktor 290, men som det ses bruges tiden nu til en connection-open, så jo flere rækker des større forbedring:

Currently rated 5.0 by 1 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Posted by ole.hedegaard on Wednesday, October 01, 2008 7:29 AM
Permalink | Comments (8) | Post RSSRSS comment feed

Basic Web Part Creation

 1.     Create C# Class Library
Name the class library according to needs and relevant guidelines

2.     Rename class according to your web part
E.g. MyOwnWebPart

3.     Add refence to System.Web
This is the most needed reference for writing Web Parts – just add any other references your need accordingly.

4.     Derive from System.Web.UI.WebControls.WebParts.WebPart
Notice the fact that the solution derives from a “System.Web” class. If you need to connect web parts on different pages, need to create client side connections or leverage data caching in WSS 3 – you should use the Microsoft.Web.UI.WebControls.WebParts.WebPart (remember to reference Microsoft.SharePoint assembly in that case)

5.     Override The RenderContents method to suit your needs
This is where your imagination comes in J Build whatever functionality you need to output and handle the rendering here.
Remember if you need to access e.g. SharePoint web services, you’ll have to consider code access security and/or deploy to GAC scenario.

6.     Add [assembly: System.Security.AllowPartiallyTrustedCallers()] to AssemblyInfo.cs
This is needed unless you add your assembly to the GAC. If you try to add your Web Part to a page without this it will show a dialog box and refuse to add your solution.

7.     Make post-build event (xcopy)
E.g. 
xcopy "*.dll" "C:\Inetpub\wwwroot\wss\VirtualDirectories\80\bin\" /y

Reconstruct the line above to suit your own SharePoint installation. You could choose your output location for the dll to be the same as above, but that’s not recommended. That’s hard to maintain if you work against automatic builds that uses the project files to determine file locations and if your co-developers is not aware of it and wonders why they can’t find the dll after build.

8.     Sign assembly (project properties)
This is a reasonable practice and will make your standard development procedure more prepared for real-world deploy where signing with certificates etc. might be relevant.

9.     Build solution
To make your dll, copy it to the bin folder of the SharePoint solution you’re developing for, and make the signing available in the dll (so you can find the public key, you’ll need it in a minute), you’ll have to build the solution - so go ahead.

10.      Find the relevant information for SafeControl entry in web.config
The SafeControl entry may look like this (one line):

<SafeControl Assembly="WebPartTest, Version=1.0.0.0, Culture=neutral, PublicKeyToken=4580592393728f0b" Namespace="WebPartTest" TypeName="WebPartTest" Safe="True" />

The SafeControl entry is necessary in order to add the WebPart correctly to the WebPart gallery (and for the WebPart to function properly).

1.       First drop your dll on .NET Reflector (that extremely useful tool, for inspecting dll’s etc. Go get it, you’ll not be sorry). This will provide you with the “Assembly” part of the SafeControl entry.

2.       Then copy the Namespace from your solution to the “Namespace” part of the entry.

3.       Change the “TypeName” part of the entry to match your Class name from the WebPart solution.  

11.                       Add your Web Part to the Web Part gallery 
Choose: Site Actions →Site Settings → Web Parts (gallery) →”New”

Then navigate the list until you find your Web Part and check the checkbox.

Choose populate gallery to add your Web Part to the gallery

12.                       Add your Web Part to a page
Choose: Site Settings → Edit Page to add your Web Part to the current page.

When changing your implementation, all you need to do is to build the solution again, and the Web Part dll will be updated. Reload your page and voila!

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Categories: SharePoint
Posted by jane.noesgaard.larsen on Monday, August 18, 2008 2:26 AM
Permalink | Comments (0) | Post RSSRSS comment feed

Unit Testing for Smart Devices Webcast

On the 28th of February 2008, Microsoft Denmark will have the first and largest online launch for Windows Server 2008, SQL Server 2008, and Visual Studio 2008. We made a few webcasts related to the products and technologies to be released. Here's one that I made entitled "Unit Testing for Smart Devices"

http://blogs.commentor.dk/downloads/smart_device_unit_testing.wmv

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Posted by christian.resma.helle on Thursday, February 21, 2008 2:44 AM
Permalink | Comments (2) | Post RSSRSS comment feed

TFS web casts about TFS2008 source control features and Customizing Build

In relation to the upcomming Launch of Microsoft Visual Studio Team Foundation Server 2008 we have made a couple of web casts about new version control features and customization of builds:

http://blogs.commentor.dk/downloads/WebCast - Customisering af builds.wmv

http://blogs.commentor.dk/downloads/TFS2008 SC features.wmv

///Jørn

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Posted by jorn.floor.andersen on Tuesday, February 19, 2008 3:08 AM
Permalink | Comments (3) | Post RSSRSS comment feed

Integrating with Garmin Mobile XT

Half a year ago, I wrote an article about Integrating with TomTom Navigator. This time I'm gonna discuss how you can integrate a .NET Compact Framework application with the Garmin Mobile XT navigation software. The process is a bit similar to integrating with TomTom because the Garmin SDK only provides a native API.

Before we get started, we need to have the Garmin Mobile XT for the Windows Mobile platform. Unlike TomTom's SDK, Garmin's SDK is available free of charge for download.

Before we can get more into detail, we will need the following:
1) Visual Studio 2005 or 2008
2) Windows Mobile 5.0 SDK for Pocket PC
3) A windows mobile device a GPS receiver and the Garmin Mobile XT (and Maps)
4) Garmin Mobile XT SDK for the Windows Mobile platform

We will be making the same projects we made for Integrating with TomTom Navigator:
1) Native wrapper for the Garmin XT SDK
2) Managed Garmin XT SDK wrapper
3) Device application that will call the Garmin XT SDK wrapper methods


Let's get started...


Native wrapper for the Garmin XT SDK

The Garmin SDK ships with C++ header files and a static library that a native application can link to. For that reason we need to create a native DLL that exposes the methods that we need as C type funtions. Let's call this Garmin.Native.dll.

In this article, we will implement a managed call to the Garmin Mobile XT to allow us to launch the Garmin Mobile XT, Navigate to a specific address or GPS coordinate, and to Show an address on the Map. These tasks will be performed on a native wrapper and which will be called from managed code.

We will be using the following methods from the Garmin Mobile XT SDK:
- QueLaunchApp
- QueAPIOpen
- QueAPIClose
- QueCreatePointFromAddress
- QueCreatePoint
- QueRouteToPoint
- QueViewPointOnMap

These methods return specific error codes describing whether the command executed successfully or not. This error information is translated to a .NET Framework enum which we will see later.


#include "QueAPI.h"

#define EXPORTC extern "C" __declspec(dllexport)

long DecimalDegreesToSemicircles(double degrees);

BOOL APIENTRY DllMain(
  HANDLE hModule,
  DWORD ul_reason_for_call,
  LPVOID lpReserved)
{
  switch (ul_reason_for_call)
  {
    case DLL_PROCESS_ATTACH:
    case DLL_THREAD_ATTACH:
    case DLL_THREAD_DETACH:
    case DLL_PROCESS_DETACH:
    break;
  }
  return TRUE;
}

static void QueCallback(QueNotificationT8 aNotification)
{
  // Used for debugging purposes
}

EXPORTC int CloseAPI()
{
  QueErrT16 err = QueAPIClose(QueCallback);
  return err;
}

EXPORTC int OpenNavigator()
{
  QueErrT16 err = QueLaunchApp(queAppMap);
  return err;
}

EXPORTC int NavigateToAddress(
  const wchar_t *streetAddress,
  const wchar_t *city,
  const wchar_t *postalCode,
  const wchar_t *state,
  const wchar_t *country)
{
  QueErrT16 err = QueAPIOpen(QueCallback);
  if (err != gpsErrNone) {
    return err;
  }

  QueSelectAddressType address;
  QuePointHandle point = queInvalidPointHandle;

  memset(&address, 0, sizeof(QueSelectAddressType));
  address.streetAddress = streetAddress;
  address.city = city;
  address.postalCode = postalCode;
  address.state = state;
  address.country = country;

  err = QueCreatePointFromAddress(&address, &point);
  if (err == queErrNone && point != queInvalidPointHandle) {
    err = QueRouteToPoint(point);
  }

  QueAPIClose(QueCallback);
  return err;
}

long DecimalDegreesToSemicircles(double degrees)
{
  return degrees * (0x80000000 / 180);
}

EXPORTC int NavigateToCoordinates(double latitude, double longitude)
{
  QueErrT16 err = QueAPIOpen(QueCallback);
  if (err != gpsErrNone) {
    return err;
  }

  QuePointType point;
  QuePositionDataType position;

  memset(&position, 0, sizeof(QuePositionDataType));
  position.lat = DecimalDegreesToSemicircles(latitude);
  position.lon = DecimalDegreesToSemicircles(longitude);

  memset(&point, 0, sizeof(QuePointType));
  point.posn = position;

  QuePointHandle hPoint;
  memset(&hPoint, 0, sizeof(QuePointHandle));

  err = QueCreatePoint(&point, &hPoint);
  if (err == queErrNone && hPoint != queInvalidPointHandle) {
    err = QueRouteToPoint(hPoint);
  }

  QueAPIClose(QueCallback);
  return err;
}

EXPORTC int ShowAddressOnMap(
  const wchar_t *streetAddress,
  const wchar_t *city,
  const wchar_t *postalCode,
  const wchar_t *state,
  const wchar_t *country)
{
  QueErrT16 err = QueAPIOpen(QueCallback);
  if (err != gpsErrNone) {
    return err;
  }

  QueSelectAddressType address;
  QuePointHandle point = queInvalidPointHandle;

  memset(&address, 0, sizeof(QueSelectAddressType));
  address.streetAddress = streetAddress;
  address.city = city;
  address.postalCode = postalCode;
  address.state = state;
  address.country = country;

  err = QueCreatePointFromAddress(&address, &point);
  if (err == queErrNone && point != queInvalidPointHandle) {
    err = QueViewPointOnMap(point);
  }

  QueAPIClose(QueCallback);
  return err;
}

The Garmin Mobile XT SDK works in a straight forward way. Before making any calls to the API, you first need to Open it. Once open, you can start executing a series of methods and then once you're done you must Close the API. The Garmin Mobile XT has to be running before you can execute commands to it, otherwise you will get a communication error.

You might notice in the code above an empty static method called QueCallback(QueNotificationT8 aNotification). This is a callback method that receives the information about the application state. You can use this for making callbacks from native to managed code. You can pass a delegate method from managed code to the native methods that expect QueNotificationCallback as a parameter. We will only use it for debugging purposes in this example. We will not dig more into that in this article.

Normally when reverse geocoding an address to a GPS coordinates using some free service, you will get the coordinates in decimal degrees (WGS84 decimal format). Navigating to a coordinate using the Garmin Mobile XT SDK requires the coordinates to be in semicircles (2^31 semicircles equals 180 degrees).

To convert decimal degrees to semicircles we use the following formula:
semicircles = decimal degrees * (2^31 / 180)


Managed wrapper

In my article Integrating with TomTom Navigator, I created a Generic Navigator wrapper that uses the INavigator interface for defining methods to be used by the managed wrapper. The purpose of the Generic Navigator was to allow the application to integrate with several navigation solutions without changing any of the existing code. As I already discussed this in the past, I will skip this part and only focus on how to integrate with Garmin Mobile XT.

We first need to create an enumeration containing error codes we receive from the native wrapper.

public enum GarminErrorCodes : int
{
  None = 0,
  NotOpen = 1,
  InvalidParameter,
  OutOfMemory,
  NoData,
  AlreadyOpen,
  InvalidVersion,
  CommunicationError,
  CmndUnavailable,
  LibraryStillOpen,
  GeneralFailure,
  Cancelled,
  RelaunchNeeded
}

We of course need to create our P/Invoke declarations. This time let's put them in an internal class called NativeMethods()

internal class NativeMethods
{
  [DllImport("Garmin.Native.dll")]
  internal static extern int CloseAPI();

  [DllImport("Garmin.Native.dll")]
  internal static extern int OpenNavigator();

  [DllImport("Garmin.Native.dll")]
  internal static extern int NavigateToAddress(
    string address,
    string city,
    string postalcode,
    string state,
    string country);

  [DllImport("Garmin.Native.dll")]
  internal static extern int NavigateToCoordinates(
    double latitude,
    double longitude);

  [DllImport("Garmin.Native.dll")]
  internal static extern int ShowAddressOnMap(
    string address,
    string city,
    string postalcode,
    string state,
    string country);
}

Let's create a .NET exception that we can throw which contains native error details when a native method call fails. Let's call it GarminNativeException()

[Serializable]
public class GarminNativeException : Exception
{
  public GarminNativeException() { }

  public GarminNativeException(GarminErrorCodes native_error) { }

  public GarminNativeException(
    string message,
    GarminErrorCodes native_error) : base(message) { }
}

Now we need a class that we can use for calling the wrapped managed methods to the Garmin mobile XT. Let's call it GarminXT()

public class GarminXT : IDisposable
{
  public void Dispose()
  {
    NativeMethods.CloseAPI();
  }

  public void OpenNavigator()
  {
    GarminErrorCodes err = (GarminErrorCodes)NativeMethods.OpenNavigator();

    if (err != GarminErrorCodes.None) {
      ThrowGarminException(err);
    }
  }

  public void NavigateToAddress(
    string address,
    string city,
    string postalcode,
    string state,
    string country)
  {
    GarminErrorCodes err = (GarminErrorCodes)NativeMethods.NavigateToAddress(
      address,
      city,
      postalcode,
      state,
      country);

    if (err != GarminErrorCodes.None) {
      ThrowGarminException(err);
    }
  }

  public void NavigateToCoordinates(double latitude, double longitude)
  {
    GarminErrorCodes err = (GarminErrorCodes)NativeMethods.NavigateToCoordinates(
      latitude,
      longitude);

    if (err != GarminErrorCodes.None) {
      ThrowGarminException(err);
    }
  }

  public void ShowAddressOnMap(
    string address,
    string city,
    string postalcode,
    string state,
    string country)
  {
    GarminErrorCodes err = (GarminErrorCodes)NativeMethods.ShowAddressOnMap(
      address,
      city,
      postalcode,
      state,
      country);

    if (err != GarminErrorCodes.None) {
      ThrowGarminException(err);
    }
  }

  private GarminNativeException ThrowGarminException(GarminErrorCodes err)
  {
    string message = string.Empty;

    switch (err) {
      case GarminErrorCodes.NotOpen:
        message = "Close() called without having Open() first";
        break;
      case GarminErrorCodes.InvalidParameter:
        message = "Invalid parameter was passed to the function";
        break;
      case GarminErrorCodes.OutOfMemory:
        message = "Out of Memory";
        break;
      case GarminErrorCodes.NoData:
        message = "No Data Available";
        break;
      case GarminErrorCodes.AlreadyOpen:
        message = "The API is already open";
        break;
      case GarminErrorCodes.InvalidVersion:
        message = "The API is an incompatible version";
        break;
      case GarminErrorCodes.CommunicationError:
        message = "There was an error communicating with the API";
        break;
      case GarminErrorCodes.CmndUnavailable:
        message = "Command is unavailable";
        break;
      case GarminErrorCodes.LibraryStillOpen:
        message = "API is still open";
        break;
      case GarminErrorCodes.GeneralFailure:
        message = "General Failure";
        break;
      case GarminErrorCodes.Cancelled:
        message = "Action was cancelled by the user";
        break;
      case GarminErrorCodes.RelaunchNeeded:
        message = "Relaunch needed to load the libraries";
        break;
      default:
        break;
    }

    throw new GarminNativeException(message, err);
  }
}

The managed wrapper GarminXT() implements IDisposible for ensuring that the API will be closed when the GarminXT object gets disposed. I check the return code of every method to verify if the native method call succeeded or failed. If the native method call failed then I throw a GarminNativeException containing a text description of the error and the GarminErrorCode returned by the native method call.


Using the Managed Wrapper

Now that we have a managed wrapper for the Garmin Mobile XT SDK we can start testing it with a simple smart device application. Let's say that we created a simple application that accepts street address, city, postal code, country, latitude, longitude. We also have some buttons or menu items for: Navigating to an address, Navigating to coordinates, Showing an address on the map, and for launching Garmin Mobile XT.

Since the managed wrapper implements IDisposable, we surround our calls to it with the using statement:

using (GarminXT xt = new GarminXT()) {
  xt.OpenNavigator();
}

As I mentioned before, it is important that Garmin Mobile XT is running in the background for executing certain commands. Otherwise the managed Garmin XT wrapper will throw a GarminNativeException saying that there was an error communicating with the API. I would suggest handling the GarminNativeException everytime calls to the managed wrapper are made.

For launching Garmin Mobile XT:

try {
  using (GarminXT xt = new GarminXT()) {
    xt.OpenNavigator();
  }
}
catch (GarminNativeException ex) {
  Debug.Assert(false, ex.Message, ex.StackTrace);
}

For navigating to an address:

try {
  using (GarminXT xt = new GarminXT()) {
    xt.NavigateToAddress(
      "Hørkær 24",
      "Herlev",
      "2730",
      null,
      "Denmark");
  }
}
catch (GarminNativeException ex) {
  Debug.Assert(false, ex.Message, ex.StackTrace);
}

For navigating to coordinates:

try {
  using (GarminXT xt = new GarminXT()) {
    xt.NavigateToCoordinates(
      55.43019,
      12.26075);
  }
}
catch (GarminNativeException ex) {
  Debug.Assert(false, ex.Message, ex.StackTrace);
}

For showing an address on the map:

try {
  using (GarminXT xt = new GarminXT()) {
    xt.ShowAddressOnMap(
      "Hørkær 24",
      "Herlev",
      "2730",
      null,
      "Denmark");
  }
}
catch (GarminNativeException ex) {
  Debug.Assert(false, ex.Message, ex.StackTrace);
}


That wasn't that hard was it?

But there is one thing that I don't quite understand. Why do we have to wrap SDK's like this ourselves? Why don't they just provide managed SDK's? Hopefully this will change in the near future. Until then, I guess I can just write a few more articles about it.

Currently rated 4.0 by 1 people

  • Currently 4/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Posted by christian.resma.helle on Sunday, February 17, 2008 9:16 AM
Permalink | Comments (1) | Post RSSRSS comment feed

Upgrading TFS2005 to TFS2008 - AS problem

Last week we should upgrade a TFS2005 dual server installation to TFS2008. Pretty straight forward as we didn't wanted to upgrade SharePoint services from WSS 2.0 to WSS 3.0. So the installation followed the standard upgrade guide:

1) Uninstall TFS on the data-tier server

This should actually never have been there, but is just a left-over, which the MS team doing the Setup program didn't get rid of before the release - Unfortunately it has been a source of frustration as no database team in an IT department wants anything installed on their database servers :-(

2) Installation of TFS2008 on the Application-tier.

First we had to restore the changes we had made for accessing the TFS server over SSL/Basic authentication. This to ensure that the Setup program could access the WSS and reporting services. After we had ensured access to both wss and rs we could do the upgrade-installation. The process went well untill we got the following error:

The Error: 32000 on TfsDb.exe is pretty generic, so we had to run the step from the command line and then we could actually see that it stopped in processing the cube files:

\\[AS Files folder]\MSSQL.2\OLAP\Data\TfsWarehouse.0.db\Team System.13093.cub.xml

This file was for some reason corrupted, as it ended in the middle of the XML statements. The TfsDb.exe program couldn't instantiate an object based on that. The solution was to delete the file and then process the dataware house.

 After that the upgrade was successful.

 

Currently rated 5.0 by 1 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Posted by jorn.floor.andersen on Thursday, February 14, 2008 3:49 PM
Permalink | Comments (1) | Post RSSRSS comment feed

Transparent Controls in .NETCF

I work a lot with a graphic artist for developing solutions. The better the graphic artist you work with is, the harder it is to implement their designs to your application. One thing that my solutions have in common is that they all require transparent controls. My graphic artist loves having a image buttons on top of fancy background.

Here's some screen shots of what I've made with my graphic artist:

 

 

 

 

 

 

 

 



 

 

 

 

 

 

 

 

 

In these screen shots I heavily use a transparent label control over a Form that has a background image. I normally set my controls to be designer visible so I can drag and drop while designing. Visual Studio 2005 and 2008 will automatically load all Custom Controls and UserControls

Implementing Transparent Controls

For creating transparent controls, I need the following:

1) IControlBackground interface - contains BackgroundImage { get; }
2) TransparentControlBase - draws the BackgroundImage of an IControlBackground form
3) Transparent Control - Inherits from TransparentControlBase
4) FormBase Form - implements IControlBackground and draws the background image to the form

Let's start off with the IControlBackground interface. Like I mentioned above, it only contains a property called BackgroundImage.

public interface IControlBackground
{
  Image BackgroundImage { get; }
}

Next we will need to create the TransparentControlBase. Let's create a class that inherits from Control. We then need to override the OnPaintBackground() event to draw the IControlBackground.BackgroundImage of the Parent control. To do this, we create an instance of IControlBackground from the Parent. Once we have the BackgroundImage, we draw part of the BackgroundImage where the transparent control is lying on.

We also override the OnTextChanged() and OnParentChanged() events to force a re-draw whenever the text or parent of the control is changed.

public class TransparentControlBase : Control
{
  protected bool HasBackground = false;

  protected override void OnPaintBackground(PaintEventArgs e)
  {
    IControlBackground form = Parent as IControlBackground;
    if (form == null) {
      base.OnPaintBackground(e);
      return;
    } else {
      HasBackground = true;
    }

    e.Graphics.DrawImage(
      form.BackgroundImage,
      0,
      0,
      Bounds,
      GraphicsUnit.Pixel);
  }

  protected override void OnTextChanged(EventArgs e)
  {
    base.OnTextChanged(e);
    Invalidate();
  }

  protected override void OnParentChanged(EventArgs e)
  {
    base.OnParentChanged(e);
    Invalidate();
  }
}

Now we need to create a control that inherits from TransparentControlBase. I'll create a simple TransparentLabel control for this example. The control will have the same behavior as the standard Label control, except that it can be transparent when used over a form or control that implements IControlBackground.

public class TransparentLabel : TransparentControlBase
{
  ContentAlignment alignment = ContentAlignment.TopLeft;
  StringFormat format = null;
  Bitmap off_screen = null;

  public TransparentLabel()
  {
    format = new StringFormat();
  }

  public ContentAlignment TextAlign
  {
    get { return alignment; }
    set
    {
      alignment = value;
      switch (alignment) {
        case ContentAlignment.TopCenter:
          format.Alignment = StringAlignment.Center;
          format.LineAlignment = StringAlignment.Center;
          break;
        case ContentAlignment.TopLeft:
          format.Alignment = StringAlignment.Near;
          format.LineAlignment = StringAlignment.Near;
          break;
        case ContentAlignment.TopRight:
          format.Alignment = StringAlignment.Far;
          format.LineAlignment = StringAlignment.Far;
          break;
      }
    }
  }

  protected override void OnPaint(PaintEventArgs e)
  {
    if (!base.HasBackground) {
      if (off_screen == null) {
        off_screen = new Bitmap(ClientSize.Width, ClientSize.Height);
      }
      using (Graphics g = Graphics.FromImage(off_screen)) {
        using (SolidBrush brush = new SolidBrush(Parent.BackColor)) {
          g.Clear(BackColor);
          g.FillRectangle(brush, ClientRectangle);
        }
      }
    } else {
      using (SolidBrush brush = new SolidBrush(ForeColor)) {
        e.Graphics.DrawString(
          Text,
          Font,
          brush,
          new Rectangle(0, 0, Width, Height),
          format);
      }
    }
  }
}

Now that we have our transparent controls, we need to create a Form that will contain these controls. First we need to create a base class that will implement IControlBackground and inherit from Form.

In this example, I added a background image to the solution and as an embedded resource. My default namespace is called TransparentSample and my background image is located at the root folder with the filename background.jpg

public class FormBase : Form, IControlBackground
{
  Bitmap background;

  public FormBase()
  {
    background = new Bitmap(
      Assembly.GetExecutingAssembly().GetManifestResourceStream(
      "TransparentSample.background.jpg"));
  }

  protected override void OnPaint(PaintEventArgs e)
  {
    e.Graphics.DrawImage(background, 0, 0);
  }

  public Image BackgroundImage
  {
    get { return background; }
  }
}

For the last step, we need to create a Form that will contain these transparent controls. To start, let's add a new Form to our project and let it inherit from FormBase instead of Form.

Now we can add our transparent controls to the main form.

public class MainForm : FormBase
{
  TransparentLabel label;

  public MainForm()
  {
    label = new TransparentLabel();
    label.Font = new Font("Arial", 16f, FontStyle.Bold);
    label.ForeColor = Color.White;
    label.Text = "Transparent Label";
    label.Bounds = new Rectangle(20, 60, 200, 50);
    Controls.Add(label);
  }
}

That wasn't very complicated, was it? Having a nice and intuitive UI offers a very good user experience. Being creative, imaginative, and learning to work with a graphic artist can really pay off.

Currently rated 5.0 by 5 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Posted by christian.resma.helle on Sunday, January 13, 2008 9:30 AM
Permalink | Comments (14) | Post RSSRSS comment feed

SqlCeEngineEx - Extending the SqlCeEngine class

I use System.Data.SqlServer.SqlCeEngine() quite a lot in all my projects. I normally create the database on the fly when the application is launched for the first time and then I populate the initial data via a web service.

I often check if database objects exist before I create them. You can do this by querying the INFORMATION_SCHEMA views. I created a helper class called SqlCeEngineEx that contains the following methods for querying the INFORMATION_SCHEMA:

1) bool DoesTableExist(string table) - Checks if a table exists in the database
2) string[] GetTables() - Returns a string array of all the tables in the database
3) string[] GetTableConstraints(string table) - Returns a string array of all the constraints for a table
4) string[] GetTableConstraints() - Returns a string array of all the constraints in the database

And here is the full code:

public class SqlCeEngineEx : IDisposable
{
  private SqlCeEngine engine;

  public SqlCeEngineEx()
  {
   engine = new SqlCeEngine();
  }

  public SqlCeEngineEx(string connectionString)
  {
   engine = new SqlCeEngine(connectionString);
  }

  public bool DoesTableExist(string tablename)
  {
   bool result = false;

   using (SqlCeConnection conn = new SqlCeConnection(LocalConnectionString)) {
    conn.Open();
    using (SqlCeCommand cmd = conn.CreateCommand()) {
     cmd.CommandText =
      @"SELECT COUNT(TABLE_NAME)
       FROM INFORMATION_SCHEMA.TABLES
       WHERE TABLE_NAME=@Name"
;
     cmd.Parameters.AddWithValue("@Name", tablename);
     result = Convert.ToBoolean(cmd.ExecuteScalar());
    }
   }

   return result;
  }

  private string[] PopulateStringList(SqlCeCommand cmd)
  {
   List<string> list = new List<string>();

   using (SqlCeDataReader reader = cmd.ExecuteReader()) {
    while (reader.Read()) {
     list.Add(reader.GetString(0));
    }
   }

   return list.ToArray();
  }

  public string[] GetTables()
  {
   string[] tables;

   using (SqlCeConnection conn = new SqlCeConnection(LocalConnectionString)) {
    conn.Open();
    using (SqlCeCommand cmd = conn.CreateCommand()) {
     cmd.CommandText = "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES";
     tables = PopulateStringList(cmd);
    }
   }

   return tables;
  }

  public string[] GetTableConstraints()
  {
   string[] constraints;

   using (SqlCeConnection conn = new SqlCeConnection(LocalConnectionString)) {
    conn.Open();
    using (SqlCeCommand cmd = conn.CreateCommand()) {
     cmd.CommandText = "SELECT CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS";
     constraints = PopulateStringList(cmd);
    }
   }

   return constraints;
  }

  public string[] GetTableConstraints(string tablename)
  {
   string[] constraints;

   using (SqlCeConnection conn = new SqlCeConnection(LocalConnectionString)) {
    conn.Open();
    using (SqlCeCommand cmd = conn.CreateCommand()) {
     cmd.CommandText =
      @"SELECT CONSTRAINT_NAME
       FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
       WHERE TABLE_NAME=@Name"
;
     cmd.Parameters.AddWithValue("@Name", tablename);
     constraints = PopulateStringList(cmd);
    }
   }

   return constraints;
  }

  public string LocalConnectionString
  {
   get { return engine.LocalConnectionString; }
   set { engine.LocalConnectionString = value; }
  }

  public void Compact()
  {
   engine.Compact(null);
  }

  public void Compact(string connectionString)
  {
   engine.Compact(connectionString);
  }

  public void CreateDatabase()
  {
   engine.CreateDatabase();
  }

  public void Repair(string connectionString, RepairOption options)
  {
   engine.Repair(connectionString, options);
  }

  public void Shrink()
  {
   engine.Shrink();
  }

  public bool Verify()
  {
   return engine.Verify();
  }

  public void Dispose()
  {
   engine.Dispose();
   engine = null;
  }
}

Currently rated 5.0 by 1 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Posted by christian.resma.helle on Wednesday, December 05, 2007 9:40 AM
Permalink | Comments (0) | Post RSSRSS comment feed

Displaying the Calendar view on a DateTimePicker Control in .NETCF

I've recently made a solution where the customer requested to be able to bring up the calendar view in a DateTimePicker control by pressing on a specific button on the screen. The solution to that was really simple: Create a control that inherits from System.Windows.Forms.DateTimePicker and add a method called ShowCalendar() which I call to bring up the Calendar view.


public class DateTimePickerEx : DateTimePicker
{
  [DllImport("coredll.dll")]
  static extern int SendMessage(
    IntPtr hWnd, uint uMsg, int wParam, int lParam);

  const int WM_LBUTTONDOWN = 0x0201;

  public void ShowCalendar() {
    int x = Width - 10;
    int y = Height / 2;
    int lParam = x + y * 0x00010000;

    SendMessage(Handle, WM_LBUTTONDOWN, 1, lParam);
  }
}

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Posted by christian.resma.helle on Tuesday, July 24, 2007 4:11 PM
Permalink | Comments (1) | Post RSSRSS comment feed