JAJAH Development Blog

Blogs by JAJAH Developers

Archive for the ‘c#’ Category

Thursday, April 17th, 2008

In a previous post, I wrote about how to run a method when the device wakes up, or comes back from sleep mode. In that post I wrote about calling the CeRunAppAtEvent native function, which signals a given  event (hEvent) when the device wakes up.  I used the WaitForSingleObject(hEvent, INFINITE) function to wait until the hEvent is signaled.

The problem occurs when wanting to close the application, and a thread, which called the WaitForSingleObject()  is still waiting for the event. In that post, I wrote that in case wanting to close the application the below function should be called in order to terminate the waiting thread. 

public static void Close()
{
    _close = true;
    if(_wakeupServiceThread != null)
       _wakeupServiceThread.Abort();
}

Unfortunately, The wakeupServiceThread could not be aborted, since it was waiting due to the call to WaitForSingleObject function.

The solution was to stop waiting on the WaitForSingleObject function,  and for that the _nativeWakupEvent event needed to be signaled.

Here is the code:

[DllImport("coredll.dll", SetLastError = true)]
        public static extern bool EventModify(IntPtr hEvent,
            [In, MarshalAs(UnmanagedType.U4)] int dEvent);
private const int NATIVE_EVENT_SET = 3;

public static void Close()
{
     _close = true;
     if (_hEvent != IntPtr.Zero)
             SetEvent(_hEvent);
}
private static bool SetEvent(IntPtr hEvent)
{
     return EventModify(hEvent, NATIVE_EVENT_SET);
}

Friday, March 28th, 2008

While looking for a full article about this I found out it won’t hurt to have another quick explanation about this process.

Sometimes when creating an application you want some sort of verification about which phone is accessing your service (service-client application). A good way to do this is to use the unique device id.

Now I will explain how we do it, we are going to get a 40 char string that is hashed with an AppString we will provide which will be unique to each and every device, and will be constant for this device and AppString.

First we define the P/Invoke signature:

[DllImport("coredll.dll")]
private static extern int GetDeviceUniqueID([In, Out] byte[] appdata, int cbApplictionData,
                                            int dwDeviceIDVersion,
                                            [In, Out] byte[] deviceIDOuput, ref uint pcbDeviceIDOutput);

Now we are going to define a private static member so we don’t go through the entire process every time we need this and then create it with a public static method:

private static string s_UniqueDeviceID;

/// 
/// Gets the unique device id, this is an unique id of the phone
/// which is hashed with the AppString
/// 
/// a 40 characters unique id
public static string GetUniqueDeviceID()
{
    if (string.IsNullOrEmpty(s_UniqueDeviceID))
    {
        // define AppString
        string AppString = "MyAppString";

        // get the byte array for the string
        byte[] AppData = Encoding.ASCII.GetBytes(AppString);

        // some parameters for the native call
        int appDataSize = AppData.Length;
        uint SizeOut = 20;

        // our out parameter
        byte[] DeviceOutput = new byte[20];

        // Call the native GetDeviceUniqueID method from coredll.dll
        GetDeviceUniqueID(AppData, appDataSize, 1, DeviceOutput, ref SizeOut);

        // check that we got something
        if (SizeOut > 0)
        {
            // build text from received bytes
            StringBuilder resultText = new StringBuilder();
            for (int i = 0; i < DeviceOutput.Length; i++)
            {
                resultText.Append(string.Format("{0:x2}", DeviceOutput[i]));
            }

            // set up result
            s_UniqueDeviceID = resultText.ToString();
        }
    }

    return s_UniqueDeviceID;
}

As you can see the AppString can really be whatever we want it to be. the rest is a little work in order to transform it all from bytes to string but that is why we do it only once!

The only important thing I can see about the AppString is that it won’t be null\empty and that it will be constant throughout your application and usage.

Hope this was clear.

Cheers,

Nadav

Monday, March 17th, 2008

I guess this is quite the easy one but the fact is that while I was searching the web for this answer it was very hard to find.

This is something I knew and forgot so it is good that I will have it here for future quick reference.

Just use:

Environment.TickCount

This will return the time in milliseconds that has passed since the last boot.

Quick Note:

I have read here that this might overflow on systems running for a few days, they also give a solution. as I am using this for a Windows Mobile device I don’t have that option. (CF.Net being deprecated and all…)

Hope you found this faster then I did.

Good luck,

Nadav

Wednesday, March 12th, 2008

I wanted to test a function’s duration (for various  cases).

I thought it to be simple and be as in . Net C#.

I wrote something like this:

DateTime start = DateTime.Now;
//function code……

DateTime end = DateTime.Now;
TimeSpan duration = end - start;

I got that the duration is 0!! I also tried using

duration.TotalMilliseconds; and DateTime.Now.Ticks;

but the ticks for the start and end were the same. this seemed very strange.

To solve the problem, instead of using  DateTime.Now I used

System.Environment.TickCount;

It seems that the time resolution for DateTime.Now depends on the operation system, and for .Net compact framework its  one Second!!!.

 

How to create Excel Workbooks In C#

Tuesday, March 4th, 2008
Accessing and using office components from .net framework is not trivial (god knows why). There is a complex office API and some weird security configurations that need to be done. After wasting a lot of time trying to create a simple file with a simple table, I decided to share with you the articles that helped me. Accessing office components from c# are well described in this great article By Doctor Peter A. Bromberg. But!!!! this is not sufficient. after executing this code you will bump into weird security exceptions. Solving those issues are well described in this article by Sushmita Kumari Have fun

Which is faster? switch or if-else ?

Thursday, February 7th, 2008

Every time I have a state where I need to use switch\if-else-irritation I can’t quite figure our which is the better choice. I am pretty sure there is no one answer to this question, but i did stumble upon an interesting test:

Link

This test shows that, as i suspected all along(Mu-ha-ha), the switch is faster, and in a significant way.

I’m sure that some people will still state if-else is more readable, but personally, i do not agree with that.

What do you choose when you face this issue? if-else/switch? or an entirely different mechanism?

Have a good one, =]
Nadav

How to: Control the keyboard(SIP - Soft Input Panel) on Windows Mobile

Friday, February 1st, 2008

As you might have noticed, what I do here in this blog is write about the things I look for, than, when I can’t find them or I find too complicated and evasive answers I write simple ones here.

So, let’s get to the reason we’re all here.

I will give here an example on how you can change the visibility of the keyboard and you will probably be able to figure out the rest.

the steps are as follows:

  1. Add a reference to Microsoft.WindowsCE.Forms.dll
  2. Create our new class:
    using Microsoft.WindowsCE.Forms;
    
    namespace Environment.Keyboard
    {
        public class Keyboard
        {
  3. Create our private InputPanel member:

    private static InputPanel m_inputPanel = new InputPanel();
  4. Create the property to check if the Keyboard is open:

    public static bool KeyboardOpen
    {
        get { return m_inputPanel.Enabled; }
        set { m_inputPanel.Enabled = value; }
    }
  5. Were done!

It’s that simple. the Enabled property in the InputPanel signifies if the keyboard is currently open or not.

Check out this link for a more comprehensive article.

See you next time,

Nadav

How to: Unit test events

Tuesday, January 22nd, 2008

When we come to write unit tests we stumble upon many different problems with many different parts of our code, because no matter how hard you try, your code is never as simple as the examples around the web. If it’s singletons, static methods, private members that need mocking, or even events that need to be checked.

lately I spent some time writing unit tests and fumbled around with many of this problems. There are many articles around the web telling you the problem is not that you don’t know how to test this parts, it is that it shouldn’t exist in the first place. I really don’t like this answer, saying I shouldn’t write my code this way because there is a better one is a valid argument, but telling me I HAVE to change my code in order for it to work is usually not true. Some places don’t say this but still, most don’t give you a solution.

After this brief intro I will go into saying that I will try in a few different posts to clear up some of the problems in unit testing, mainly the ways to overcome them.

Lets start =]

As the title states, in this post I will show how to unit test events.

What we are going to do here is use an Anonymous delegate in order to catch the event inside our test.

The code: (look afterwards for the explanation and break down)

[TestFixture]
public class SettingsFixture
{
    [Test]
    public void ChangeSettingFiresSettingsChangedEvent()
    {
        // success variable
        bool success = false;

        // new setting
        string key = "SomeKey";
        string value = "SomeValue";

        // set a new instance
        SettingsManager settingsManager = new SettingsManager();

        // register to the event
        settingsManager.SettingsChanged += delegate(object sender,
          EventArgs e)
        {
            // event raise, test successfull
            success = true;
        };

        // update a setting to raise the event
        settingsManager.UpdateSetting(key,value);

        Assert.True(success);
    }
}

So what we have here?

We have a TestFixture with a single Test called:

ChangeSettingFiresSettingsChangedEvent

Change Setting Fires SettingsChanged Event.

First, we setup the success variable which we will commit later as the test’s result.

Second, set up our "new" setting, if we would use a special Type to submit to the UpdateSetting method, ISetting lets say, this will be the place to Mock(Mocking will be discussed in a future post, I will link to it then) it.

Third, setup a new instance of our SettingsManager.

Fourth, register to the SettingsChanged event as we usually will, with one big difference. instead of using a new instance of the right delegate we use an Anonymous delegate, look at the code for the syntax, it is very simple.

Fifth, call UpdateSetting with our "new" setting so the event will be raised.

Sixth, commit the result, hoping that it all went as planned ;].

Seventh, show off to your friends and go home, it’s late! (somewhere in the world…)

Hope it was clear enough.

A nice post about this:

Just to clarify: I am using C#(if you haven’t noticed yet) with NUnit.

See you next time =].

Nadav

How to add a parameter to a Predicate

Monday, January 14th, 2008

When using a “Find” method in a generic List, there is a need to implement a Predicate(T) delegate that defines the conditions of the element to search for. a not good MSDN example can be found here. why not good? because usually we want to add extra parameters to the Predicate(T) delegate.
A good way of doing it is by using Anonymous Method as below:

ourList.Find(delegate(OurObject objectItem)
{
return objectItem.StringToFind == stringToCheck;
}
);
a good reference for Anonymous Method can be found here

BTW, this post was written with a great assistance of our Telephony team )

How To: Bring your program to the foreground on WM6

Sunday, January 13th, 2008

This topic is one I have been spending some time studying.
How do you get your program to the foreground when a certain event accurse ?

The answer is quite simple actually, you just need to call a UI component. like:

MessageBox.Show("Show Me");

And it will show the top most form in your application. Another thing you can do is call a form with Show().

Now, for a little bonus I have for you the…

How to send it back to the background!

What we need to do here is to call Hide() on all the visible forms in our application, this will essentially cause all our UI to go to the background and will bring back the last active application.

A little hint, you might want to use what you learned, and combine it with the previous post ;].

Nadav

Jajah is the VoIP player that brought you web-activated telephony.