Nadav and the wonders of the web


Archive for the ‘How to’ Category

How to: Get unique device id in C# (Windows Mobile)

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;

/// <summary>
/// Gets the unique device id, this is an unique id of the phone
/// which is hashed with the AppString
/// </summary>
/// <returns>a 40 characters unique id</returns>
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

The Ultimate Firefox setup!

Wednesday, March 26th, 2008

After writing a post about the best Windows setup I realized the setting up Firefox to max its potential can be just as or even more complicated. So, here I will detail what i believe to be the Ultimate Firefox setup!

Preferences:

Go to Tools->Options

  1. On Main tab - I would set up my download folder here so when I download files they won’t just end up on my desktop. Choose Save files to and browse to the folder of your choosing.
  2. Tabs tab - We’ll use an add-on for this one.
  3. Privacy tab - You might want to mark Always clear my private data when I close Firefox and choose the correct Settings for you. this is good for security reasons.
  4. Security tab - I HIGHLY recommend you use a master password for all your saved passwords, it is really no hassle and adds a very important security layer. Just mark Use a master password.

I didn’t talk about any other thing in the options because the rest of the default values seem fine to me.

Add-ons:

This are add-ons I use and find helpful for fun and productivity.

For setting up specific add-on settings go to Tools->Add-ons->[add-on name]->Options

  1. Download Statusbar - Gives you a small downloads status indication at the status bar.
    After install and restart choose in it’s settings:
    Top right Mini Mode.
  2. Fasterfox - Does different optimizations to your Firefox installation so it will run much faster.
  3. Firebug - This might be the best one in the list. If you are a web developer this is the extension for you, extensive all-web related features. viewing and editing in real time of DOM,CSS,HTML,JS… and a JS console and a view of all requests sent including AJAX requests.
    And what I consider to be the coolest feature, live JS debug with breakpoints !
  4. Flashgot - When combined with a download manager (Flashget\GetRight\DAP…) enables to send to download all links in a page, links marked, building a gallery of picture\video and many many more.
  5. Forecastfox - Weather in your status bar. Personally I change the settings so it will only show icons and just when I hover above one give me more details.
  6. Foxmarks Bookmark Synchronizer - Does exactly what the name says. I use this to keep a backup of bookmarks and at the same time keep my Portable Firefox synched with my standard installation.
  7. IE Tab - Enables viewing of pages using IE’s engine inside Firefox. Very useful for web-developers or just people that use non-standard web sites.
  8. Long Titles - Makes sure that the image tool tips will show completely.
  9. Master Password Timeout - If you wish your master password will expire every so minutes than use this extension.
  10. ProfileSwithcer - Firefox add-on developers or just people that want a clean\different profile for normal usage can install this for a quick and easy switch.
  11. Resurrect Pages - Don’t you just hate it when you go to some site and get the 404 missing error ? Well, this extension lets you view this page from many different web cache archives, can be very useful at times.
  12. Tab Mix Plus - Adds a whole lot of features for the Firefox tabs. I highly recommend going through it’s settings and setting it to your liking.
  13. Update Notifier - Notifies of new updates to the main Firefox program and to add-ons.
  14. Web Developer - A must have for web developers, just get it and explore all the wonderful options. this does not conflict with Firebug, they complete each other.
  15. iFox Smooth - A nice theme I have been using for a while now.
  16. JAJAH Click-to-call - Last but not least, our very own. - adds telephony functionality to your pages with number recognition and other cool features.

I recommend going through each new add-on you install and its various settings options and choosing what is right for you.

Tweaks:

Write at the address bar about:config and now we are going to search for values and change them, if a value does not exist, add it.

This is a little more complicated and dangerous for your Firefox installation so use at your own risk.

I found a few good articles about this specific subject so I will link to them and leave the fame to who ever deserves it.

  1. Link 1
  2. Link 2

– — – — – — – — – — – — —- —- —- —- —- —- —- —- —- –

Hope this helped you.

Tell me what is your ultimate Firefox setup in the comments.

Some credit goes to Lifehacker for ideas.

Cheers,
Nadav

How to: Get system up time in C#

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.

Update:

After further looking into this I have found a nice article about how to overcome the overflow problem, here is the solution:

public static TimeSpan GetTimeSinceBoot()
{
    long _newTicks = Convert.ToInt64("0x" + Environment.TickCount.ToString("X"), 16);

    int days = (int) (_newTicks/(1000*60*60*24));
    int hours = (int) ((_newTicks/(1000*60*60)) - (days*24));
    int minutes = (int) ((_newTicks/(1000*60)) - (days*24*60) - (hours*60));
    int seconds = (int) ((_newTicks/1000) - (days*24*60*60) - (hours*60*60) - (minutes*60));
    int milliseconds =
        (int) (_newTicks - (days*24*60*60*1000) - (hours*60*60*1000) - (minutes*60*1000) - (seconds*1000));

    return new TimeSpan(days, hours, minutes, seconds, milliseconds);
}

The ticks represent milliseconds and when I just call the constructor for TimeSpan it doesn’t treats it this way, that is why i am doing all of this.

Good luck,

Nadav

Windows XP tweaks & useful programs - the new computer necessities

Monday, March 3rd, 2008

A couple of weeks ago I got a new computer and after spending quite a while setting it up and collecting all the different programs and little tweaks I like I figured it’s a good idea to make a list of it all.

at the end there’s a bonus!

Programs:

.Net Development:

  1. Resourcer - Enables looking at what’s inside .Net’s binary resource files. - Link
  2. Reflector - Enables looking at assemblies wether they are the .Net assemblies or your own. can be very useful - Link
  3. Guidance Explorer - Contains different guidance lines in regards to .Net development. - Link
  4. TailXP - this is not really geared solely on .Net, this is a tool used to watch a certain text file for changes, this is very useful when watching a text log file change in real time. - Link

General purpose:

  1. Notepad++ - An excellent free text editor. - Link
  2. 7zip - A free zip\rar\7zip(their own) compression\decompression program. - Link
  3. Paint.NET - An open-source photo editing program written in .Net - Link
  4. CDBurnerXP - A very nice program for burning different CD’s\DVD’s.(FREE!) - Link
  5. SharpKeys - I used this little program to change some keys behavior on my laptop’s keyboard. you can use it to change the behavior of most keys on most keyboards - Link
  6. foobar2000 - A music player. The reason I use this music player and not Winamp\Windows media player\ITunes\Whatever are both that it’s FREE and that uses virtually no memory once minimized(in today’s scale). - Link
  7. Firefox - Of course - Link
  8. SyncBack - A very good program for synching different locations including FTP servers.(there’s a free version) - Link
  9. CCleaner - Cleans all temporary locations on your computer and fixes some registry issues. free and very good. - Link
  10. Daemon Tools - A free CD\DVD drive emulation, very useful when downloading an install CD you don’t want to really burn. - Link
  11. WinSCP - Useful for accessing SFTP\FTP servers. - Link
  12. Putty - Simple SSH client - Link
  13. VLC - Good media player(I use it solely for video though it supports audio playback as well) - Link
  14. Gimp - If you are looking for a more professional alternative to Paint.NET but don’t want to pay for Photoshop, The Gimp might be for you - Link
  15. Windows Live Writer - The software I am using to write this posts. - Link
  16. Picasa - My choice for photo organizing. -

Windows tweaks:

  1. You know it when some program crashes(all do eventually) and you get that annoying "Send\Don’t send" message? well, you can set it up so it just shows the error and a close button. This way you won’t click the send by accident.
    Right click My Computer->Properties->Advanced->Error Reporting(at bottom)->Disable Error Reporting. Leave the mark as it is.
  2. Some times you have a simple file you wish to open with Notepad but Windows doesn’t recognize the file type and won’t do this by default, yes, you can fix it manually but that will only help this file type. what I like to do(or at least liked[better idea coming up]) is to add a shortcut to Notepad on the "Send To" list.
    Start menu->Run-> write "sendto"->right click the empty space->new->shortcut->write "notepad.exe"->Next->write "Notepad"->Finish
    And your done! now you can just right click a file and choose sendto->notepad and it will open up with notepad.
  3. A new way I found of doing the previous mentioned tweak is to have a "Open with Notepad" context menu item so you don’t need to go to "send to" the How to is detailed here: Link
    You are probably wondering why then have I wrote here the previous one, the answer is that i think the previous tweak is quite useful for many different usages even if just to remove useless links from the sendto list.
  4. Most people look into choosing a nice desktop wallpaper and a nice screen saver, what they forget about is looking through the power options and setting them to they’re liking. it can be a real pain to leave your computer on at night for a big download and come back the next day to find out it turned itself off after a couple of hours.
    Right click on the desktop->properties->Screen Saver->Power…(at the bottom)
    Go through all the options and choose what’s best for you, if you don’t know what something means leave it as it is.
  5. Using hibernation - If you wish to shut-down your computer but you want it to boot back to the same exact situation that you left it in you can put your computer in hibernation. what windows does when you do this is copy all your current RAM(memory) to the hard-drive and then restore it the next time you boot. I found this most useful with laptops mainly as it shortens boot-up time quite drastically.
    Go to Power as before->Hibernate(tab)->Mark Enable Hibernation(if it’s not already marked).
    If you are using the old\server style of the shut down screen then you have a list view when you choose "Shut down" from the start menu. If this is the case then you will see the hibernation option at the bottom of the list. if you are using the default XP shut down view then you will need to hold down the "Shift" button while viewing the screen and then the standby button will change into hibernate.

    If you are experiencing problems with the boot up after hibernation you can rapidly click a few times on the F8 key just before Windows start loading(right after the BOIS screen is gone). This will open up the boot option screen for windows, you can choose here to boot normally and not from the hibernation data created earlier.

    I would also recommend rebooting the computer the old fashion way at least once every 3-5 days, this is Windows were talking about after all…

Hope you found at least one cool thing here. If there is anything you want me to try and find out for you just say so in the comments and I will give it my best.

Cheers,
Nadav

Ow right… the bonus! - just a free nice game, very cool indeed. - Link
and if you are into shooters and such look into F.E.A.R(I will leave this one for you to find, the multi-player should be free).

A few useful Linux commands for the newbie

Saturday, February 16th, 2008

Here is a list of a few useful Linux commands for us newbies. =]

This are most of the commands that i have come to use in Linux, this are the ones that I think it’s worth to at least know. You never know when it will come in handy…

  1. ls - Works the same as “dir” in DOS, lists all the files and folders at the current path.
  2. cat filename - Pasts the contents of filename to the screen.
  3. man command - Loads the manual file for the command\program.
  4. wget url - I think this actually a program but it will most likely be available on every Linux system you will use. It fetches the file\page at the url.
  5. mkdir name - Create a directory named name.
  6. rm filename - Delete filename.
  7. rmdir foldername -Delete foldername.
  8. ps - Lists processes.
  9. passwd - Change the password of the current user.
  10. chmod - Read about this one, this is used to change the rights regarding read/write/execution of a file or folder.
  11. chown - Used to change the owner of a file or folder.
  12. cp filename1 filename2 - Used to copy files from filename1 to filename2.
  13. df - Used to review hard-drive space, personally, I use it with “-hT”.
  14. fdisk /dev/*** - Used to partition a hard-drive, usually the drives location will be /dev/hda or /dev/sda or /dev/hdb and so on…
  15. find key - Find files on the file system. I am not very familiar with it but I know that sometimes you would prefer to use locate.
  16. grep regularExpression- used to find lines that correspond with the regularExpression usually used in parallel to another command like ps. [ps | grep cups]
  17. ifconfig -Lists the available network adapters and their status.
  18. kill - Stop a process by PID[Program ID].
  19. killall - Stop a process by name.
  20. lsmod - Lists currently loaded modules[this is a subject of it's own].
  21. rmmod mode - Unload a module from the kernel.
  22. lsusb - Lists all USB devices.
  23. mount - Used to mount a device/partition to a certain path.
  24. umount - Used to un-mount a device/partition.
  25. dig serverAddress -Used to query the DNS server.
  26. sftp - ftp, but secure!.
  27. ssh address - Connect to a SSH server at address.
  28. su username - Start using the shell as username.
  29. sudo command - Run command as if you were root. This command is currently used in many different distros to re-authenticate the user in order to make sure this is not some kind of a harmful program.
  30. tar - Create or restore file from a tarball.
  31. traceroute address - Shows the entire route it takes a request in order to get to address. Useful when trying to find bottle necks in networks.

For more info on any of this commands either use “man” or call the command and “–help” or “-h” after the command(or click the link…). It should list the different possibilities of usage to that command.

Hope this helps you with your Linux endeavours. BTW - most or at-least some of the commands should work on UNIX based systems as well. This is due to the fact that both Linux and UNIX adhere to POSIX.

Until next time, have a good one! =]

Nadav

Cool Visual Studio 2005 stuff.

Friday, February 15th, 2008

Lately I stumbled upon a few cool things you can change in the Visual Studio 2005 to get some nice to have features.

Here they are:

  1. Change the start-up behavior:
    If you’re like me and you don’t like the fact that it takes a while for VS to load, partially because of the start-up screen, while you don’t use it anyway… then this for you !
    Go to: Tools->Options->Environment->Startup
    And choose whatever fits you best.
  2. Enable line numbering:
    Some times when you use a log file or you look in the windows event handler you will see certain errors you want to check in the code, but while looking for the right line you keep looking at the status bar to see in which line you are. NO MORE!
    Go to: Tools->Options->Text Editor->[Choose your language or All Languages]->General
    And set the check box at the bottom named “Line numbers”.
  3. You might want to go through the “Formatting” section and set it up to your liking.
  4. If you don’t like it that when you implement an Interface VS automatically wraps it with a #region than you can go to the same place but look at [Language]->Advanced
    And unset the check box at the bottom under “Implement Interface”
  5. If like me you don’t use the WYSIWYG editor for HTML than you might want to go to:
    Tools->Options->HTML Designer
    And choose “Source View” at the top.
  6. A cool and not so known feature of VS is that you can set special keywords to show up on the Task List.
    First, what you want to do is open the Task List window, you do this by View->Task List(or just Ctrl+T).
    Second, go to Tools->Options->Environment->Task List. Here you can set up your own keywords or removed ones you don’t like. this can be used so when you need to do a little fix in your code at a latter time you put a little “//TODO: ….” comment there, then, when you look at the Task List not only you will see all the TODO’s[and other keywords] comments but a double click on it will bring you to the exact line. Now that’s a time saver! no more searching the entire solution for those TODO comments.
  7. Another very cool and probably not very known feature of VS is that you can Import and Export your settings! this means that after you go through all the settings and set everything to your liking you can save it so the next time you install VS you will easily set it up in no time.

Hope you found this informative and that it helped you a little.

Until next time, 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: Run a program on start up on Windows mobile

Wednesday, January 30th, 2008

Thinking about how to run a program on the Smart Phone’s boot sequence got me searching and I did find the answer but it was not as easy and as clear to find as I hoped. That is the reason that i came to write this post.

The very simple and easy way to do this is to add a shortcut to the program we want to run under \Windows\StartUp

Yes its that simple.

There might be a different way to do this using the registry, but i couldn’t find one and quite frankly, I don’t see the need for it.

What you might want to do is add your created shortcut to the your installation CAB[I will try and have a different post regarding this one, it is a big subject.] under this folder so it will be done on installment and you won’t have to do it programmatically in a later phase. On the other hand, doing it programmatically leaves you the option to have this as a setting in your application that the user can set. I will leave the choice down to you. =]

Hope this was helpful!

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: 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.