Archive

Archive for the ‘How To’ Category

How To: Read String Line by Line

January 19, 2011 Leave a comment

Breaking a string containing multi-line text to a list of lines can be easily done using StringReader. Here is a method that does this and small test program:


class Program
{
    static void Main(string[] args)
    {
        IList<string> lines = BreakLines("This is a test for breaking multiline string \nto a list of lines.");

        foreach (var item in lines)
        {
            Console.WriteLine(item);
        }

        Console.ReadLine();
    }

    private static IList<string> BreakLines(string text)
    {
        IList<string> lines = new List<string>();

        using (StringReader reader = new StringReader(text))
        {
            string line;
            while ((line = reader.ReadLine()) != null)
            {
                lines.Add(line);
            }
        }

        return lines;
    }
}

 

Categories: Development, How To Tags: ,

How To: Perform column-based selection in Visual Studio

July 22, 2010 Leave a comment

Sometimes is is needed to copy some information from source code in a column-based style (parts of several lines starting from some position inside the line). It turned out that there is very easy way to achieve that. Just need to use Shift + Alt during selecting area with the mouse.

Column-based selection in Visual Studio

Categories: Development, How To Tags:

How To: Get Correct Messages for Exceptions Fired from .Net Compact Framework Classes

March 31, 2010 Leave a comment

Sometimes message from exception that occurred inside .Net CF classes doesn’t look handly at all:

An error message cannot be displayed because an optional resource assembly containing it cannot be found.

The thing is that error messages are actually in the resource assembly which is not installed on the device. So to fix the problem you just need to install this assembly:

  1. Navigate to CompactFramework folder in the SDK which is “%Program Files%\Microsoft.NET\SDK\CompactFramework”.
  2. Navigate to Diagnostics folder under desired .Net CF version (“v3.5\WindowsCE\Diagnostics” for 3.5 or “v2.0\WindowsCE\Diagnostics” for 2.0).
  3. Copy resource CAB file to device according to the language you want and install it.

How To: Unit Test a Singleton

February 25, 2010 Leave a comment

Unit testing a Singleton is not a trivial task because each test needs untouched Singleton object to keep all the tests isolated. One way to achieve this is to recreate underlying singleton object using reflection during test setup or teardown as described by Jonathan de Halleux and Omer van Kloeten.

But I think that a better way is to extract implementation from singleton into a separated class. This way we’ll have a class that contains all the logic to be tested and another class used to wrap it into a singleton.

public class LoadBalancer {
	internal LoadBalancer() {
	}

	// LoadBalancer class implementation goes here...
}

public sealed class LoadBalancerSingleton {
	private static readonly LoadBalancer _instance = new LoadBalancer();

	private LoadBalancerSingleton() {
	}

	public static LoadBalancer Instance {
		get {
			return _instance;
		}
	}
}

Using InternalsVisibleTo attribute in this assembly we can allow test project to perform needed unit testing. Although technically it is possible to create another instance of the LoadBalancer class inside this assembly comments on constructor and common sense should prevent such a situation.

So to my mind it’s a good alternative to reflection approach.

Categories: Development, How To Tags:

How To: Catch “Home” Key Press on Smartphone

January 28, 2010 Leave a comment

There is a great tip on this in Alex Yakhnin blog.

How To: Rotate Screen on Windows Mobile Device

December 24, 2009 Leave a comment

Below is a snapshot that shows how to change screen orientation from normal to 90 degree rotated or from 90 degree back to normal depending on current screen state:

if (SystemSettings.ScreenOrientation == ScreenOrientation.Angle0) {
	SystemSettings.ScreenOrientation = ScreenOrientation.Angle90;
}
else {
	SystemSettings.ScreenOrientation = ScreenOrientation.Angle0;
}

To make this code compile don’t forget to import Microsoft.WindowsCE.Forms namespace.

How To: Refresh Home Screen on Windows Mobile 6.5

December 16, 2009 Leave a comment

New home screen available in Windows Mobile 6.5 should be refreshed differently for Professional and Standard editions of OS. It can be done using the same API methods as for earlier versions of Windows Mobile.

For Professional edition it can be done like this:

[DllImport("coredll.dll")]
private static extern IntPtr PostMessage(int hWnd, int msg, uint wParam, uint lParam);

private const int HWND_BROADCAST = 0xFFFF;
private const int WM_WININICHANGE = 0x001A;

public static void Refresh() {
	PostMessage(HWND_BROADCAST, WM_WININICHANGE, 0xF2, 0);
}

For Standard edition the trick is to provide correct GUID to API. This GUID can be found in SlidingPanel.home.xml file located in “\Application Data\Home” folder. Here is the code:

[DllImport("aygshell.dll")]
public extern static uint SHOnPluginDataChange(ref Guid clsid);

public static void Refresh() {
	Guid guid = new Guid("{E9267CAB-02EE-4f37-8216-6BF6A8FF5A71}");
	SHOnPluginDataChange(ref guid);
}

How To: Load Image from Embedded Resource

December 9, 2009 Leave a comment

Here is a code for loading embedded image named MyImage.png stored directly in project directory:

Assembly assembly = Assembly.GetExecutingAssembly();
string iconFileName = string.Format("{0}.MyImage.png", assembly.GetName().Name);
using (Stream io = assembly.GetManifestResourceStream(iconFileName)) {
	return new Bitmap(io);
}

Name of resource to load contains three elements divided by dots:

  • Assembly name;
  • Path where resource is stored inside of a project (must be omitted if resource is in project directory);
  • File name of resource.

Path to resource should be created using names of folders. For example, if resource is in “Resources/Images” folder than path will be “Resources.Images”.

How To: Save XmlDocument without Declaration

December 4, 2009 Leave a comment

Normally saving XmlDocument leads to xml declaration at the beginning of file. In case it is desirable to omit it, XmlWriterSettings comes to help:

XmlDocument doc = new XmlDocument();
// Do with document whatever is needed...

// Save xml document without xml declaration.
XmlWriterSettings writerSettings = new XmlWriterSettings();
writerSettings.OmitXmlDeclaration = true;
using (XmlWriter writer = XmlWriter.Create(@"\omit.xml", writerSettings)) {
	doc.Save(writer);
}

How To: Make File Writable on Windows Mobile

December 3, 2009 Leave a comment

Making read-only file writable with full .Net Framework is a piece of cake: there is FileInfo.IsReadOnly. Just set it to false and it’s done.

With Compact Framework we need to use FileInfo.Attributes and a solid knowledge of bitwise operations:

FileInfo info = new FileInfo(pathToReadonlyFile);
info.Attributes &= ~FileAttributes.ReadOnly;

Follow

Get every new post delivered to your Inbox.