50% OFF!!!

Monday, November 22, 2010

Bootstrapper Package | Visual Studio 2010 | Microsoft .NET Framework Version 2.0 Redistributable


After long searching & reading, I created Bootstrapper package for using prerequisites on my setup project for my dot.net 2.0 application.

First of all, there must exist the Microsoft .NET Framework Version 2.0 Redistributable packages installation files:
1. dotnetfx.exe - for x86 (download here)
2. NetFx64.exe - for x64 (download here)
3. NetFx64.exe - for IA64-Itanium (download here)

Let's rename the files (respectively) so they will be more readable:
1. dotnetfx_x86.exe (for x86)
2. NetFx64_x64.exe (for x64)
3. NetFx64_IA64.exe (for IA64-Itanium)

Now, we have to create new Bootstrapper Package for this cause Visual Studio 2010 not contains in its setup prerequisites the Microsoft .NET Framework Version 2.0.

First we create a folder on C:\ and then copy the finished folder to the Bootstrapper folder.

Step 1
Create a folder under C:\ and name it DotNetFx20
Inside DotNetFx20, create:
a. copy the 3 downloaded Redistributable files to it (dotnetfx_x86.exe, NetFx64_x64.exe, NetFx64_IA64.exe)
b. create an (empty) XML file named Product.xml (will be edited later)
c. create a folder named en (for english locale) and create an (empty) XML file named package.xml

Step 2
[Expand/Collapse] Edit file Product.xml:

Step 3
[Expand/Collapse] Edit file package.xml:

Step 4
Copy the folder DotNetFx20 to the Bootstrapper packages folder which is under:
C:\Program Files\Microsoft SDKs\Windows\v7.0A\Bootstrapper\Packages\


Step 5
That's it.. :)

Here is the whole Bootstrapper Package ready-to-use folder to download without (dotnetfx_x86.exe, NetFx64_x64.exe, NetFx64_IA64.exe) which can be downloaded from MSDN directly (links above):
download here (updated file)

Update (29.11.2010):
There was problem with the Product.xml file, so file updated and also zip file for downloading. The filenames did NOT match...





Regards,
MDB-Blog


Sunday, November 14, 2010

C# | Winforms | Textbox within Button

Here is an example for creating a Button control which contains a Textbox inside it.
This is very usefull when the button functionality is based (only) on the textbox content text, and it is very usefull for the user.

Screenshot (image) example:


The Code:
class ButtonWithTextbox : Button
{
    TextBox _textbox = new TextBox();

    public int TextboxWidth
    {
        get { return _textbox.Width; }
        set { _textbox.Width = value; }
    }
    public Point TextboxLocation
    {
        get { return _textbox.Location; }
        set { _textbox.Location = value; }
    }
    /** And we may add all properties of the Textbox ***/

    public ButtonWithTextbox()
    {
        this.Controls.Add(_textbox);
    }
}

Also work great on the designer... :)

MDB-Blog
http://mdb-blog.blogspot.com

Wednesday, October 6, 2010

C# | How to deskew an image

I found this code on CodeProject site:
http://www.codeproject.com/KB/graphics/Deskew_an_Image.aspx
By mackenb | 25 Apr 2006

The article describes an algorithm to calculate the skew angle of an image.

This is converted to C#: (tested and working)
The Code:
using System.Drawing;
using System.Drawing.Imaging;
using System;
using System.Diagnostics;


public class gmseDeskew
{
    // Representation of a line in the image.
    public class HougLine
    {
        //' Count of points in the line.
        public int Count;
        //' Index in Matrix.
        public int Index;
        //' The line is represented as all x,y that solve y*cos(alpha)-x*sin(alpha)=d
        public double Alpha;
        public double d;
    }

    // The Bitmap
    Bitmap cBmp;
    // The range of angles to search for lines
    double cAlphaStart = -20;
    double cAlphaStep = 0.2;
    int cSteps = 40 * 5;
    // Precalculation of sin and cos.
    double[] cSinA;
    double[] cCosA;
    // Range of d
    double cDMin;
    double cDStep = 1;
    int cDCount;
    // Count of points that fit in a line.
    int[] cHMatrix;

    // calculate the skew angle of the image cBmp

    public double GetSkewAngle()
    {
        HougLine[] hl;
        int i;
        double sum = 0;
        int count = 0;

        //' Hough Transformation
        Calc();
        //' Top 20 of the detected lines in the image.
        hl = GetTop(20);
        //' Average angle of the lines
        for (i = 0; i < 19; i++)      
        {          
             sum += hl[i].Alpha;
             count += 1;
         }
         return sum / count;
     }

     //    ' Calculate the Count lines in the image with most points.
    private HougLine[] GetTop(int Count)
     {
         HougLine[] hl;
         int j;
         HougLine tmp;
         int AlphaIndex, dIndex;
         hl = new HougLine[Count];
         for (int i = 0; i < Count; i++)
         {
             hl[i] = new HougLine();
         }
         for (int i = 0; i < cHMatrix.Length - 1; i++)
         {
             if (cHMatrix[i] > hl[Count - 1].Count)
            {
                hl[Count - 1].Count = cHMatrix[i];
                hl[Count - 1].Index = i;
                j = Count - 1;
                while (j > 0 && hl[j].Count > hl[j - 1].Count)
                {
                    tmp = hl[j];
                    hl[j] = hl[j - 1];
                    hl[j - 1] = tmp;
                    j -= 1;
                }
            }
        }
        for (int i = 0; i < Count; i++)
         {
             dIndex = hl[i].Index / cSteps;
             AlphaIndex = hl[i].Index - dIndex * cSteps;
             hl[i].Alpha = GetAlpha(AlphaIndex);
             hl[i].d = dIndex + cDMin;
         }
         return hl;
     }
     public void New(Bitmap bmp)
     {
         cBmp = bmp;
     }

     //    ' Hough Transforamtion:
     private void Calc()
     {
         int x;
         int y;
         int hMin = cBmp.Height / 4;
         int hMax = cBmp.Height * 3 / 4;
         Init();
         for (y = hMin; y < hMax; y++)
         {
             for (x = 1; x < cBmp.Width - 2; x++)
             {
                 //' Only lower edges are considered.
                 if (IsBlack(x, y) == true)
                 {
                     if (IsBlack(x, y + 1) == false)
                     {
                         Calc(x, y);
                     }
                 }
             }
         }
     }

     //    ' Calculate all lines through the point (x,y).
     private void Calc(int x, int y)
     {
         double d;
         int dIndex;
         int Index;
         for (int alpha = 0; alpha < cSteps - 1; alpha++)
         {
             d = y * cCosA[alpha] - x * cSinA[alpha];
             dIndex = (int)CalcDIndex(d);
             Index = dIndex * cSteps + alpha;

             try
             {
                 cHMatrix[Index] += 1;
             }
             catch (Exception ex)
             {
                 Debug.WriteLine(ex.ToString());
             }
         }
     }
     private double CalcDIndex(double d)
     {
         return Convert.ToInt32(d - cDMin);
     }
     private bool IsBlack(int x, int y)
     {
         Color c;
         double luminance;
         c = cBmp.GetPixel(x, y);
         luminance = (c.R * 0.299) + (c.G * 0.587) + (c.B * 0.114);
         return luminance < 140;
     }
     private void Init()
     {
         double angle;
         //' Precalculation of sin and cos.
         cSinA = new double[cSteps - 1];
         cCosA = new double[cSteps - 1];
         for (int i = 0; i < cSteps - 1; i++)
         {
             angle = GetAlpha(i) * Math.PI / 180.0;
             cSinA[i] = Math.Sin(angle);
             cCosA[i] = Math.Cos(angle);
         }
         //' Range of d
:         cDMin = -cBmp.Width;
         cDCount = (int)(2 * (cBmp.Width + cBmp.Height) / cDStep);
         cHMatrix = new int[cDCount * cSteps];
     }
     public double GetAlpha(int Index)
     {
         return cAlphaStart + Index * cAlphaStep;
     }     public static Bitmap RotateImage(Bitmap bmp, double angle)
     {
         Graphics g;
         Bitmap tmp = new Bitmap(bmp.Width, bmp.Height, PixelFormat.Format32bppRgb);
         tmp.SetResolution(bmp.HorizontalResolution, bmp.VerticalResolution);
         g = Graphics.FromImage(tmp);
         try       
         {
             g.FillRectangle(Brushes.White, 0, 0, bmp.Width, bmp.Height);
             g.RotateTransform((float)angle);
             g.DrawImage(bmp, 0, 0);
         }
         finally
         {
             g.Dispose();
         }
         return tmp;
     }
 }


enjoy...

Monday, October 4, 2010

Trim Image white-spaces (black&white) | C# Winforms

I searched for a simple code that preform "TRIMMING" to an image.
By "trimming" i mean, that if i have a LARGE image that contains information (painting/drawing...) only in small part of the image and all other is white-space (WHITE or BLACK pixels).

I needed to remove such whitespace and also to decrease image size.
Following three code examples:

Code #1 - Gets the NON-WHITE-SPACE bounds of an image
private Rectangle GetImageNonWhiteSpaceBounds(Bitmap p_img, bool p_isBlackWhitespace)
{
    Rectangle rect = new Rectangle();
    unsafe
    {
        BitmapData bdActual = null;
        try
        {
            int width = p_img.Width;
            int height = p_img.Height;

            bdActual = p_img.LockBits(new Rectangle(0, 0, width, height), System.Drawing.Imaging.ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
            Int32 i;
            Int32 pSize = 3;
            Byte whiteTrashold = (Byte)240;
            Byte blackTrashold = (Byte)10;
            Byte* sourceRow;

            Int32 minX = width;
            Int32 maxX = 0;
            Int32 minY = height;
            Int32 maxY = 0;
            bool isWhitepace;

            for (Int32 _y = 0; _y < height; ++_y)             {                 sourceRow = (Byte*)bdActual.Scan0 + (_y * bdActual.Stride);                 for (Int32 _x = 0; _x < width; ++_x)                 {                     i = _x * pSize;                     isWhitepace =                         (p_isBlackWhitespace && sourceRow[i] <= blackTrashold && sourceRow[i + 1] <= blackTrashold && sourceRow[i + 2] <= blackTrashold)                         ||                         (!p_isBlackWhitespace && sourceRow[i] >= whiteTrashold && sourceRow[i + 1] >= whiteTrashold && sourceRow[i + 2] >= whiteTrashold);

                    if (isWhitepace == false)
                    {
                        // NO whitespace!!!
                        minX = Math.Min(_x, minX);
                        maxX = Math.Max(_x, maxX);

                        minY = Math.Min(_y, minY);
                        maxY = Math.Max(_y, maxY);
                    }
                }
            }

            rect.X = minX;
            rect.Y = minY;
            rect.Width = maxX - minX;
            rect.Height = maxY - minY;
        }
        finally
        {
            if (bdActual != null)
            {
                p_img.UnlockBits(bdActual);
            }
        }
    }
    return rect;
}

Code #2 - Draw rectangle around the NON-WHITE-SPACE
private void DrawNonWhiteSpaceRectangle(Bitmap p_img, bool p_isBlackWhitespace, Color p_color)
{
    unsafe
    {
        BitmapData bdActual = null;
        try
        {
            int width = p_img.Width;
            int height = p_img.Height;

            bdActual = p_img.LockBits(new Rectangle(0, 0, width, height), System.Drawing.Imaging.ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
            Int32 i;
            Int32 pSize = 3;
            Byte whiteTrashold = (Byte)240;
            Byte blackTrashold = (Byte)10;
            Byte* sourceRow;

            Int32 minX = width;
            Int32 maxX = 0;
            Int32 minY = height;
            Int32 maxY = 0;
            bool isWhitepace;

            for (Int32 _y = 0; _y < height; ++_y)             {                 sourceRow = (Byte*)bdActual.Scan0 + (_y * bdActual.Stride);                 for (Int32 _x = 0; _x < width; ++_x)                 {                     i = _x * pSize;                     isWhitepace =                         (p_isBlackWhitespace && sourceRow[i] <= blackTrashold && sourceRow[i + 1] <= blackTrashold && sourceRow[i + 2] <= blackTrashold)                         ||                         (!p_isBlackWhitespace && sourceRow[i] >= whiteTrashold && sourceRow[i + 1] >= whiteTrashold && sourceRow[i + 2] >= whiteTrashold);

                    if (isWhitepace == false)
                    {
                        // NO whitespace!!!
                        minX = Math.Min(_x, minX);
                        maxX = Math.Max(_x, maxX);

                        minY = Math.Min(_y, minY);
                        maxY = Math.Max(_y, maxY);
                    }
                }
            }

            // draw rectagle:
            for (Int32 _y = minY; _y <= maxY; ++_y)             {                 sourceRow = (Byte*)bdActual.Scan0 + (_y * bdActual.Stride);                 i = minX * pSize;                 sourceRow[i] = (Byte)p_color.R;                 sourceRow[i + 1] = (Byte)p_color.G;                 sourceRow[i + 2] = (Byte)p_color.B;                 i = maxX * pSize;                 sourceRow[i] = (Byte)p_color.R;                 sourceRow[i + 1] = (Byte)p_color.G;                 sourceRow[i + 2] = (Byte)p_color.B;             }             Byte* sourceRowX1 = (Byte*)bdActual.Scan0 + (minY * bdActual.Stride);             Byte* sourceRowX2 = (Byte*)bdActual.Scan0 + (maxY * bdActual.Stride);             for (Int32 _x = minX; _x <= maxX; ++_x)             {                 i = _x * pSize;                 sourceRowX1[i] = (Byte)p_color.R;                 sourceRowX1[i + 1] = (Byte)p_color.G;                 sourceRowX1[i + 2] = (Byte)p_color.B;                 sourceRowX2[i] = (Byte)p_color.R;                 sourceRowX2[i + 1] = (Byte)p_color.G;                 sourceRowX2[i + 2] = (Byte)p_color.B;             }         }         finally         {             if (bdActual != null)             {                 p_img.UnlockBits(bdActual);             }         }     } }


Code #3 - Trim Image whitespaces
private Bitmap CropImageWhitespaces(Bitmap p_img, bool p_isBlackWhitespace)
{
    Rectangle rect = new Rectangle();
    unsafe
    {
        BitmapData bdActual = null;
        try
        {
            int width = p_img.Width;
            int height = p_img.Height;

            bdActual = p_img.LockBits(new Rectangle(0, 0, width, height), System.Drawing.Imaging.ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
            Int32 i;
            Int32 pSize = 3;
            Byte whiteTrashold = (Byte)240;
            Byte blackTrashold = (Byte)10;
            Byte* sourceRow;

            Int32 minX = width;
            Int32 maxX = 0;
            Int32 minY = height;
            Int32 maxY = 0;
            bool isWhitepace;

            for (Int32 _y = 0; _y < height; ++_y)             {                 sourceRow = (Byte*)bdActual.Scan0 + (_y * bdActual.Stride);                 for (Int32 _x = 0; _x < width; ++_x)                 {                     i = _x * pSize;                     isWhitepace =                         (p_isBlackWhitespace && sourceRow[i] <= blackTrashold && sourceRow[i + 1] <= blackTrashold && sourceRow[i + 2] <= blackTrashold)                         ||                         (!p_isBlackWhitespace && sourceRow[i] >= whiteTrashold && sourceRow[i + 1] >= whiteTrashold && sourceRow[i + 2] >= whiteTrashold);

                    if (isWhitepace == false)
                    {
                        // NO whitespace!!!
                        minX = Math.Min(_x, minX);
                        maxX = Math.Max(_x, maxX);

                        minY = Math.Min(_y, minY);
                        maxY = Math.Max(_y, maxY);
                    }
                }
            }

            rect.X = minX;
            rect.Y = minY;
            rect.Width = maxX - minX;
            rect.Height = maxY - minY;
        }
        finally
        {
            if (bdActual != null)
            {
                p_img.UnlockBits(bdActual);
            }
        }
    }

    return p_img.Clone(rect, p_img.PixelFormat);
}

I hope it will be helpful for you.
this code if fast and easy to use.

Wednesday, September 1, 2010

C# | check if program/application is installed

I searched for a code that getting the list of installed application/programs on my windows pc, but the result wat not satisfying.
I saw that the list of installed programs that i find is NOT like the "Add-Remove Programs" list!!!
The solution is to search for 3 places in registry:
1. SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall inside CurrentUser
2. SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall inside LocalMachine
3. SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall in LocalMachine
And this is my solution...

The Code:
public static bool IsApplictionInstalled(string p_name)
{
    string displayName;
    RegistryKey key;

    // search in: CurrentUser
    key = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall");
    foreach (String keyName in key.GetSubKeyNames())
    {
        RegistryKey subkey = key.OpenSubKey(keyName);
        displayName = subkey.GetValue("DisplayName") as string;
        if (p_name.Equals(displayName, StringComparison.OrdinalIgnoreCase) == true)
        {
            return true;
        }
    }

    // search in: LocalMachine_32
    key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall");
    foreach (String keyName in key.GetSubKeyNames())
    {
        RegistryKey subkey = key.OpenSubKey(keyName);
        displayName = subkey.GetValue("DisplayName") as string;
        if (p_name.Equals(displayName, StringComparison.OrdinalIgnoreCase) == true)
        {
            return true;
        }
    }

    // search in: LocalMachine_64
    key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall");
    foreach (String keyName in key.GetSubKeyNames())
    {
        RegistryKey subkey = key.OpenSubKey(keyName);
        displayName = subkey.GetValue("DisplayName") as string;
        if (p_name.Equals(displayName, StringComparison.OrdinalIgnoreCase) == true)
        {
            return true;
        }
    }

    // NOT FOUND
    return false;
}

This is great for searching for installed / uninstall programs.
I would like for some comments...

Thursday, August 5, 2010

C# / Asp.Net - Some string format...

DateTime Format:
yyyy-MM-ddTHH:mm:ss.fffffff ==> 2007-06-10T13:52:55

String format for bits:
int[] values = { 0, 0x111, 0xfffff, 0x8888, 0x22000022};
foreach (int v in values)
{
Console.WriteLine("~0x{0:x8} = 0x{1:x8}", v, ~v);
}
Output:
~0x00000000 = 0xffffffff
~0x00000111 = 0xfffffeee
~0x000fffff = 0xfff00000
~0x00008888 = 0xffff7777
~0x22000022 = 0xddffffdd


String format for double:
// just two decimal places
String.Format("{0:0.00}", 123.4567); // "123.46"
String.Format("{0:0.00}", 123.4); // "123.40"
String.Format("{0:0.00}", 123.0); // "123.00"

// max. two decimal places
String.Format("{0:0.##}", 123.4567); // "123.46"
String.Format("{0:0.##}", 123.4); // "123.4"
String.Format("{0:0.##}", 123.0); // "123"

// at least two digits before decimal point
String.Format("{0:00.0}", 123.4567); // "123.5"
String.Format("{0:00.0}", 23.4567); // "23.5"
String.Format("{0:00.0}", 3.4567); // "03.5"
String.Format("{0:00.0}", -3.4567); // "-03.5"

// Thousands separator
String.Format("{0:0,0.0}", 12345.67); // "12,345.7"
String.Format("{0:0,0}", 12345.67); // "12,346"

// formatted a zero (of double type)
String.Format("{0:0.0}", 0.0); // "0.0"
String.Format("{0:0.#}", 0.0); // "0"
String.Format("{0:#.0}", 0.0); // ".0"
String.Format("{0:#.#}", 0.0); // ""

// Align numbers with spaces
String.Format("{0,10:0.0}", 123.4567); // " 123.5"
String.Format("{0,-10:0.0}", 123.4567); // "123.5 "
String.Format("{0,10:0.0}", -123.4567); // " -123.5"
String.Format("{0,-10:0.0}", -123.4567); // "-123.5 "

// Custom formatting for negative numbers and zero
String.Format("{0:0.00;minus 0.00;zero}", 123.4567); // "123.46"
String.Format("{0:0.00;minus 0.00;zero}", -123.4567); // "minus 123.46"
String.Format("{0:0.00;minus 0.00;zero}", 0.0); // "zero"

// Other
String.Format("{0:my number is 0.0}", 12.3); // "my number is 12.3"
String.Format("{0:0aaa.bbb0}", 12.3); // "12aaa.bbb3"

Tuesday, June 22, 2010

lwuit | j2me link control (component)

Here is an implemantation of a LINK component for the LWUIT enviroment under J2ME (Java ME).
This code creates a lwuit link component based on the lwuit button which not have a border and is transparent! also have an appropriate color (blue) and font style (underline).
hope it is helpful:

code example:

Button btn = new Button("LINK1");
//btn.getStyle().setBorder(Border.createEmpty());
btn.getUnselectedStyle().setBorder(Border.createEmpty());
btn.getSelectedStyle().setBorder(Border.createEmpty());

//btn.getStyle().setBgTransparency(100);
btn.getUnselectedStyle().setBgTransparency(100);
btn.getSelectedStyle().setBgTransparency(100);

//btn.getStyle().setFont(Font.createSystemFont(Font.FACE_SYSTEM, Font.STYLE_UNDERLINED, Font.SIZE_MEDIUM));
btn.getUnselectedStyle().setFont(Font.createSystemFont(Font.FACE_SYSTEM, Font.STYLE_UNDERLINED, Font.SIZE_MEDIUM));
btn.getSelectedStyle().setFont(Font.createSystemFont(Font.FACE_SYSTEM, Font.STYLE_UNDERLINED | Font.STYLE_BOLD, Font.SIZE_MEDIUM));

//btn.getStyle().setFgColor(0x0000ff);
btn.getUnselectedStyle().setFgColor(0x0000ff);
btn.getSelectedStyle().setFgColor(0x0000ff);



Enjoy!

Sunday, May 23, 2010

J2ME | read BlackBerry device name, device id (under MIDP)

Hello to all.

I searched the web and not found any implemantaion of reading device name or device id using J2ME MIDP for blackberry.

There exists an RIM api: "net.rim.device.api.system.DeviceInfo.getDeviceName()" which allow you to read the blackberry device information, but on when creating a global application for all MIDP devices, this api will not work for other devices like Sony-Ericsson, NOKIA, Samsung, Motorola, HTC and so...

The solution is to dynamicly load an outer JAR (dynamic library = dll) only when a blackberry device detected and read all data.
NOTE: if we will access to this library (JAR) without validating the RIM device, an excaption will be thrown!!

So, the solution is:
Step 1:
Create a new project: Mobile Class Library.
Name it: BlackberryInfo

Step 2:
create new Class named: DeviceInfo
with the following code:

Code for step 2:
package BlackberryInfo;

public class DeviceInfo
{
   static public String getDeviceName()
   {
      return net.rim.device.api.system.DeviceInfo.getDeviceName();
   }

   static public String getManufacturerName()
   {
      return net.rim.device.api.system.DeviceInfo.getManufacturerName();
   }

   static public int getDeviceId()
   {
      return net.rim.device.api.system.DeviceInfo.getDeviceId();
   }

   static public String getPlatformVersion()
   {
      return net.rim.device.api.system.DeviceInfo.getPlatformVersion();
   }
}

Step 3:
Build project and get JAR and JAD named: BlackberryInfo.jar
Note: build this JAR using Blackberry BlackBerry JDE (I used 5.0.0) (BlackBerry JDE downloads)
if you want, i can upload this library to the blog...

Step 4:
In your application (J2ME MIDP), just add BlackberryInfo.jar as library.

Step 5:
Now, all you have to do, is just to validate that this is RIM Blackberry device, and the read all device info.

Code for step 5:
static public boolean isBlackberryPlatform()
{
    try
    {
        Class.forName("net.rim.blackberry.api.browser.Browser");
        return true;
    }
    catch (Exception ex)
    {
        return false;
    }
}

// some func for read device information (device name, device id, device
 if (isBlackberryPlatform() == true)
{
            System.out.println("Blackberry platform:");
            System.out.println(BlackberryInfo.DeviceInfo.getDeviceName());
            System.out.println(BlackberryInfo.DeviceInfo.getManufacturerName());
            System.out.println(BlackberryInfo.DeviceInfo.getPlatformVersion());
            System.out.println(BlackberryInfo.DeviceInfo.getDeviceId() + "");
}



Notice that, the JAR is loaded only when trying to access it, so other devices expect RIM blackberry will NOT get to this line so they won't try to load unavailable api of rim blackberry.

reference to DeviceInfo implemantation (5.0.0)
http://www.blackberry.com/developers/docs/5.0.0api/net/rim/device/api/system/DeviceInfo.html

hope i could help someone outthere...
p.s.
this method can work for every OUTER/UNKNOWN API in J2ME.

Monday, May 17, 2010

J2ME | determine BlackBerry device (OS)

Here is a code for determine whether a J2ME application is running over Blackberry device.

The idea is to check for a class that exists only in Blackberry platform and not on J2ME MIDP Operation system.
here I choose to determine using "net.rim.blackberry.api.browser.Browser" which exists only in Blackberry OS (NOT in other OSs).

The code using Class.forClass method (link) which returns the Class object associated with the class or interface with the given string name. if the class exists (so we in Blackberry) the method return an object, otherwise throws an exception.

here is a simple code:
static public boolean isBlackberryPlatform()
{
        try
        {
            Class.forName("net.rim.blackberry.api.browser.Browser");
            return true;
        }
        catch (Exception ex)
        {
            return false;
        }
}

enjoy, and post replies...

J2ME | identify MIDP runner over Android OS

Here is a good code for determine whether a J2ME application is running over MIDP runner over Android OS.

The idea is to check for a class that exists only in Android platform and not on J2ME MIDP Operaion system.
here I choose to determine using "android.Manifest" which exists in Android OS and NOT in other OSs.

The code using Class.forClass method (link) which returns the Class object associated with the class or interface with the given string name. if the class exists (so we in Android) the method return an object, otherwise throws an exception.

here is a simple code:
static public boolean isAndroidPlatform()
{
        try
        {
            Class.forName("android.Manifest");
            return true;
        }
        catch (Exception ex)
        {
            return false;
        }
}

enjoy, and post replies...

Thursday, February 18, 2010

xHTML | Align center table

After hours of searching and checking, the following code makes your table
to align center of the screen.
This code tested and working on some WAP xHTML (MP) devices.

The first code should set table's margin as the following:
table
{
  margin-left: auto;
  margin-right: auto;
}


now, insert your table in div element:
<div style="text-align: center;">
  <table>
  ...
  </table>
</div>

Enjoy.
Ask question if needed...

Sunday, January 31, 2010

Javascript | clear input file value = file url

Included javascript function for clearing INPUT FILE contents!
I did it for disable uploading NON excel file (.xls).
(a message should be include...)

The CODE for ASP.NET:
<asp:FileUpload ID="txtFile" runat="server"
Enabled="true"
onchange="if (this.value.endsWith('.xls') == false) { this.parentNode.innerHTML = this.parentNode.innerHTML; }" />

The CODE HTML:

<input type="file" onchange="if (this.value.endsWith('.xls') == false) { this.parentNode.innerHTML = this.parentNode.innerHTML; }" style="width:216px;" />



Enjoy...
:)

Asp.Net - check/validate cookies support

Here is a code for checking/validating that user device (browser) supports cookies. in other words this code checks if cookies are enabled on the browser.

Here the code implemented in the Login page:
    // Constants:
    protected const string QUERYSTRING_CHECK_COOKIE = "checkcookie";
    protected const string TEST_COOKIE_NAME = "check_cookie";
    protected const string TEST_COOKIE_VALUE = "ok";

    // On-load event, at page load:
    protected override void OnLoad(EventArgs p_eventArgs)
    {
        if (IsPostBack == false)
        {
            // Check if browser support cookies
            if (Request[QUERYSTRING_CHECK_COOKIE] == null)
            {
                // try to insert cookie:
                Response.Cookies.Add(new HttpCookie(TEST_COOKIE_NAME, TEST_COOKIE_VALUE));
                string newUrl = string.Format("Login.aspx?{1}=1", QUERYSTRING_CHECK_COOKIE);
                this.Redirect(newUrl, true);
                return;
            }
            else
            {
                // here, client sould contain test cookie:
                HttpCookie cookie = Request.Cookies[TEST_COOKIE_NAME];
                bool isCookieEnabled = cookie != null && cookie.Value == TEST_COOKIE_VALUE;
                if (isCookieEnabled == false)
                {
                    // cookies are disabled!!! show error message
                    Label1.Text = "Device NOT support Cookies!";
                    return;
                }
            }

        }
    }

You can implement this also in other pages than Login page.
:)

Tuesday, November 10, 2009

Asp.Net - Make short ids for controls

Here is a code for making your controls names/ids shorten than it is, because asp.net as default make every control name: {parent-id}_{control-id} and it makes html code length larger...


public class BasePage : Page
{
protected override void OnInit(EventArgs p_eventArgs)
{
MakeIdsShorted(this, true);
base.OnInit(p_eventArgs);
}

private int currentId = 0;
private void MakeIdsShorted(Control p_ctrl, bool p_recursive)
{
if (p_ctrl is Login)
{
return; // ignore ASP.Login controls
}
if (string.IsNullOrEmpty(p_ctrl.ID) == false)
{
//this.EnsureID();
p_ctrl.ID = "c" + currentId; // p_ctrl.ID.GetHashCode();
currentId++;
}

if (p_recursive == true)
{
foreach (Control c in p_ctrl.Controls)
{
MakeIdsShorted(c, true);
}
}
}
}



Make sure your created page is inherits from BasePage...
:)