Showing posts with label .Net Compact Framework. Show all posts
Showing posts with label .Net Compact Framework. Show all posts

Saturday, September 18, 2010

Repairing a Corrupted Database

When we are regularly using databases, sometimes those will get corrupted. This happened to one of my applications, it was a Windows Mobile application with SQL Server CE database. Since it is running in a mobile it is bit difficult for us to fix the database using the desktop machine. I used the following .Net Compact framework code to fix the corrupted database while the database is in the mobile.





  1. private void btnRepair_Click(object sender, EventArgs e)
  2. {
  3.     Cursor.Current = Cursors.WaitCursor;
  4.     Cursor.Show();
  5.     // txtDBPath will contain the path to the database.
  6.     engine = new SqlCeEngine(@"Data Source=" + txtDBPath.Text + ";Password=DBPassword");
  7.     try
  8.     {
  9.         if (!engine.Verify())
  10.         {
  11.             Cursor.Current = Cursors.Default;
  12.             Cursor.Hide();
  13.             DialogResult result = MessageBox.Show("Database is corrupted. Do you want to repair?", "My App", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1);
  14.             if (result == DialogResult.Yes)
  15.             {
  16.                 Cursor.Current = Cursors.WaitCursor;
  17.                 Cursor.Show();
  18.                 // You can also use RepairOption.DeleteCorruptedRows.
  19.                 engine.Repair(null, RepairOption.RecoverCorruptedRows);
  20.                 Cursor.Current = Cursors.Default;
  21.                 Cursor.Hide();
  22.                 MessageBox.Show("Database repaired successfully.", "My App");
  23.             }
  24.         }
  25.         else
  26.         {
  27.             Cursor.Current = Cursors.Default;
  28.             Cursor.Hide();
  29.             MessageBox.Show("Database is not corrupted.", "My App");
  30.         }
  31.     }
  32.     catch (Exception ex)
  33.     {
  34.         Cursor.Current = Cursors.Default;
  35.         Cursor.Hide();
  36.         MessageBox.Show(ex.Message, "Error!");
  37.     }
  38. }




Next time you get a corrupted SQL CE database try it out.

Tuesday, August 03, 2010

Rounding a value Down

If you did work with .Net Math classes you may have noted that you can quite easily round value upwards. But what about rounding values down?

For example if you tried to round the value 1.23501 into 2 decimal places using the Round method provided by the Math class as below, the result you will get is 1.24. Meaning .Net had rounded the value up.





  1. double dbl = Math.Round(1.23501, 2);




If the value is rounded down it should be 1.23, but in .Net I couldn’t find an easy way to get this done. So I did create a small code to get it done. It is very simple only a method with one statement as shown below.





  1. double RoundDown(double Number, int Digits)
  2. {
  3.     try
  4.     {
  5.         return Math.Truncate(Number) +
  6.             (Math.Floor(Math.Round((Number % 1), Digits) * Math.Pow(10, (Math.Round((Number % 1), Digits).ToString().Length - 3)))) *
  7.             (1 / Math.Pow(10, Math.Round((Number % 1), Digits).ToString().Length - 3));
  8.     }
  9.     catch (Exception)
  10.     {
  11.         MessageBox.Show("Error ! Please check values.");
  12.         return 0.0;
  13.     }
  14. }




Ohh, I think this is complicated right? Please find a bit of self explanatory code below.





  1. double RoundDownExplained(double Number, int Digits)
  2. {
  3.     try
  4.     {
  5.         // Get the whole number from the double value.
  6.         // For example we'll take Number = 788.34567 and Digits = 3.
  7.         // WholeNumberPart = 788.
  8.         double WholeNumberPart = Math.Truncate(Number);
  9.         // Getting the decimal part from the doouble value.
  10.         // DecimalNumberPart = 0.3457.
  11.         double DecimalNumberPart = Math.Round((Number % 1), Digits);
  12.         // Finding the number of decimal places so we can multiply by 10 to make it suitable for Floor().
  13.         // MultiplicationValue = 3.
  14.         int MultiplicationValue = Math.Round((Number % 1), Digits).ToString().Length - 3;
  15.         // Create the double value to round down.
  16.         // RoundedDownValue = 345.
  17.         double RoundedDownValue = Math.Floor(DecimalNumberPart * Math.Pow(10, MultiplicationValue));
  18.         // Finding the value to devide the result to make it decimal again.      
  19.         // DivisionValue = 0.001.            
  20.         double DivisionValue = 1 / Math.Pow(10, MultiplicationValue);
  21.         // Creating the decimal part with rounded down value.
  22.         // RoundedDownValue_Float = 0.345.
  23.         double RoundedDownValue_Float = RoundedDownValue * DivisionValue;
  24.         // Creating the full rounded down value.
  25.         // return = 788.345.
  26.         return WholeNumberPart + RoundedDownValue_Float;
  27.     }
  28.     catch (Exception)
  29.     {
  30.         MessageBox.Show("Error ! Please check values.");
  31.         return 0.0;
  32.     }
  33. }




The complete code of the application I created is below with a screenshot of the application running. Hope this helps to you.





  1. using System;
  2. using System.Text;
  3. using System.Windows.Forms;
  4. namespace WindowsFormsApplication1
  5. {
  6.     public partial class Form1 : Form
  7.     {
  8.         public Form1()
  9.         {
  10.             InitializeComponent();
  11.         }
  12.         double RoundDown(double Number, int Digits)
  13.         {
  14.             try
  15.             {
  16.                 return Math.Truncate(Number) +
  17.                     (Math.Floor(Math.Round((Number % 1), Digits) * Math.Pow(10, (Math.Round((Number % 1), Digits).ToString().Length - 3)))) *
  18.                     (1 / Math.Pow(10, Math.Round((Number % 1), Digits).ToString().Length - 3));
  19.             }
  20.             catch (Exception)
  21.             {
  22.                 MessageBox.Show("Error ! Please check values.");
  23.                 return 0.0;
  24.             }
  25.         }
  26.         double RoundDownExplained(double Number, int Digits)
  27.         {
  28.             try
  29.             {
  30.                 // Get the whole number from the double value.
  31.                 // For example we'll take Number = 788.34567 and Digits = 3.
  32.                 // WholeNumberPart = 788.
  33.                 double WholeNumberPart = Math.Truncate(Number);
  34.                 // Getting the decimal part from the doouble value.
  35.                 // DecimalNumberPart = 0.3457.
  36.                 double DecimalNumberPart = Math.Round((Number % 1), Digits);
  37.                 // Finding the number of decimal places so we can multiply by 10 to make it suitable for Floor().
  38.                 // MultiplicationValue = 3.
  39.                 int MultiplicationValue = Math.Round((Number % 1), Digits).ToString().Length - 3;
  40.                 // Create the double value to round down.
  41.                 // RoundedDownValue = 345.
  42.                 double RoundedDownValue = Math.Floor(DecimalNumberPart * Math.Pow(10, MultiplicationValue));
  43.                 // Finding the value to devide the result to make it decimal again.      
  44.                 // DivisionValue = 0.001.            
  45.                 double DivisionValue = 1 / Math.Pow(10, MultiplicationValue);
  46.                 // Creating the decimal part with rounded down value.
  47.                 // RoundedDownValue_Float = 0.345.
  48.                 double RoundedDownValue_Float = RoundedDownValue * DivisionValue;
  49.                 // Creating the full rounded down value.
  50.                 // return = 788.345.
  51.                 return WholeNumberPart + RoundedDownValue_Float;
  52.             }
  53.             catch (Exception)
  54.             {
  55.                 MessageBox.Show("Error ! Please check values.");
  56.                 return 0.0;
  57.             }
  58.         }
  59.         private void button1_Click(object sender, EventArgs e)
  60.         {
  61.             try
  62.             {
  63.                 label1.Text = RoundDown(double.Parse(textBox1.Text), int.Parse(textBox2.Text) + 1).ToString();
  64.             }
  65.             catch (Exception)
  66.             {
  67.                 MessageBox.Show("Error ! Please check values.");
  68.             }
  69.         }
  70.         private void button2_Click(object sender, EventArgs e)
  71.         {
  72.             try
  73.             {
  74.                 label2.Text = RoundDownExplained(double.Parse(textBox1.Text), int.Parse(textBox2.Text) + 1).ToString();
  75.             }
  76.             catch (Exception)
  77.             {
  78.                 MessageBox.Show("Error ! Please check values.");
  79.             }
  80.         }
  81.     }
  82. }




Monday, December 28, 2009

Disabling Date-Time Changes

Do you know that you can programmatically stop the user changing the date and time of a Pocket PC device?

This is useful if your applications need to take time accurately for some reason from the device.

The following code will disable the user from accessing the date time changing settings using his Windows Mobile powered device.





  1. private void btnDisableClock_Click(object sender, EventArgs e)
  2. {
  3.     RegistryKey hklm = Registry.LocalMachine;
  4.     hklm = hklm.OpenSubKey(@"\Software\Microsoft\Clock\", true);
  5.     System.Byte[] offValue = new byte[1];
  6.     offValue[0] = 0x30;
  7.     hklm.SetValue("AppState", offValue);
  8.     lblTitle.Text = "Change Clock Status - Disabled";
  9. }




 

If you want to re-enable the setting, to make the user able to change the data and time use the below code.





  1. private void btnEnableClock_Click(object sender, EventArgs e)
  2. {
  3.     RegistryKey hklm = Registry.LocalMachine;
  4.     hklm = hklm.OpenSubKey(@"\Software\Microsoft\Clock\", true);
  5.     System.Byte[] offValue = new byte[1];
  6.     offValue[0] = 0x11;
  7.     hklm.SetValue("AppState", offValue);
  8.     lblTitle.Text = "Change Clock Status - Enabled";
  9. }




Tuesday, September 25, 2007

Breakpoints are Not Working in Visual Studio - .NET Compact Framework (.NET CF)

Recently I had the issue while debugging a smart device application. All my breakpoints stop functioning. But if I ran the application in the device emulator the breakpoints are working fine.
So it was occurring only when I debug in an actual device (In my case Pocket PC).

After some trying I found that the problem is in the .NET CF which was installed in the Pocket PC.
To fix the thing,
1. Stop all the applications running in the Pocket PC (Do a soft restart or use the Runnning Programs tab in the System -> Memory).
2. Un install the .NET CF from the Pocket PC and soft reset the Pocket PC again.
3. Install the .NET CF in to the Pocket PC. (Also note that you can make the Visual Studio install the .NET CF by starting an application from Visual Studio.)
4. Connect the Pocket PC to the computer using Active Sync and try debugging. In most cases now the breakpoints should work.

If this did not fix the issue you will have to cold reset the Pocket PC and also I would instruct you to reinstall the SDKs (Windows Mobile 5/6 Pocket PC SDKs) if you have any installed.

Thursday, August 02, 2007

Retrieving MAC Address in Compact Framework

Recently I have seen that getting the MAC address of a Pocket PC network card using the .Net Compact Framework requires calling to the API 'iphlpapi.dll'. This is because the Windows Management Instrumentation (WMI) classes are not in Compact Framework. Otherwise you should have used WMI to get the MAC address.
But believe me that the process involved in Compact Framework to get the MAC address is complex. So as a suggestion I would say to use the OpenNETCF class libraries. You have to use OpenNETCF.Net and OpenNETCF to successfully get the MAC address. If you want to know what is happening underneath you also can download the OpenNETCF source code too.

OpenNETCF web site is http://www.opennetcf.com/, visit them and see.

The code for getting the MAC address of the first adapter using OpenNETCF would be,

' Creating a variable to hold all the retrieved adapters.
Dim adpcol As OpenNETCF.Net.AdapterCollection = OpenNETCF.Net.Networking.GetAdapters
If adpcol.Count = 1 Then
' adpcol.Item(0).MacAddress will be returning in Byte stream, you have to use Bit Converter to convert the stream to string.
GetDeviceMAC = BitConverter.ToString(adpcol.Item(0).MacAddress)
Else
GetDeviceMAC = "No Adapters Fetched"
End If

(You have to refer OpenNETCF.Net and OpenNETCF to make this code run.)

Thursday, July 12, 2007

Analyzing Device Application Performance


Recently I tried analyzing my applications' performance running on a Pocket PC. This can be achieved using .Net Compact Framework (.Net CF) Remote Performance Monitor (RPM). .Net CF RPM provides facility to monitor applications which run on devices that are connected to the computer using Active Sync or by general network.

To monitor your device application performance you have to have at least .Net CF SP1 since .Net CF RPM will come with .Net CF Service Pack 1. If you have not yet installed .Net CF SPs then download the SP2 from Microsoft using the following link.
http://www.microsoft.com/downloads/details.aspx?FamilyID=aea55f2f-07b5-4a8c-8a44-b4e1b196d5c0&DisplayLang=en


RPM consists of 3 main files.
1. NetCFRPM.exe - This is the application file which will run on your computer. This will show performance related data of the device application. This file can be found at C:\Program Files\Microsoft.NET\SDK\CompactFramework\v2.0\bin if you installed the Service Packs to the default location.

2. netcflaunch.exe - This will give you the connection parameters to the device. The details provided will be in handy if the device is not connected to the computer using Active Sync.

3. netcfrtl.dll - This dll facilitates the connection between the computer and the device.

You have to copy both above files to the device Windows folder (\Windows).


If you need more information on how to use .Net CF RPM visit Steven Pratschner's .Net CF weblog articles.
http://blogs.msdn.com/stevenpr/archive/2006/04/17/577636.aspx
http://blogs.msdn.com/stevenpr/archive/2007/03/08/finding-managed-memory-leaks-using-the-net-cf-remote-performance-monitor.aspx

Thursday, February 08, 2007

Visual Studio 2005 not adding reference dlls to the deployment project

Recently I did face a problem when I created the setup for my Pocket PC application. My application had several projects and each project is supposed to add a dll to the setup. The problem was when I build the project it didn't add the reference dlls to the setup but only added the main application.

Later I found the solution for this which was to remove the main project output from the deployment project then go to debug mode and add the main project back again to the deployment project. The when the project is rebuilt all the dlls will be included properly.

Monday, October 02, 2006

Playing Media Files in .Net Compact Framework 2.0

I have seen many people asking how to play media files in device applications. Here I am playing media files using Windows Media Player.



This is the ProcessHandler class which imports Coredll Dll and uses it's CreateProcess to create a seperate process with the required application.


This is the main form which has a button to start the Player, then it will ask the user to browse for a media file to play.


The ProcessHandler.CreateProcess function can be used to start any application which is installed in the device by simply replacing the 'WMPlayer' by the required application qualified name (IExplorer).