50% OFF!!!

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

Tuesday, October 20, 2009

Excel - Copy table to one column

This article copy table to one column, i.e. convert multiple columns into one column!
(after the operation, it also allows to remove empty cells)
also allow to convert multiple columns into more than one column!

This tutorial tested and found working on:
* Microsoft Office Excel 2003 with help of: Microsoft Office Word 2003
* Microsoft Office Excel 2007 with help of: Microsoft Office Word 2007


Instructions (WORKING TUTORIAL):
1. we have an excel file that contains table with data.
2. select all table data and press COPY (Ctrl + C)
3. open new Word document (Tested on Microsoft Office Word 2003)
4. PASTE (Ctrl + V) the copied table into word document.
5. Select the table (in word document) and select MENU: Table > Convert > Table to Text
[Microsoft Office Word 2007: Data (or View, should be last one) Group > Convert to Text]
Table selection using     icon
6. Set a character that not exists in the table (for example |)
7. Keep the text selected and press on MENU: Table > Convert > Text to Table
[Microsoft Office Word 2007: Insert Group > Table > Convert Text to Table]
8. Set number of columns = 1
9. Notice that the character is still | (that we selected)
10. Press OK
11. Now we have table with 1 column (and it is selected!)
12. Select entire table and press COPY (Ctrl + C)
Table selection using     icon
13. Open new EXCEL file (or use the original file)
14. PASTE (Ctrl + V) the table.
15. NOW you have 1 Column table!!!

Hope it helped you...
:)

Thursday, September 3, 2009

J2ME | Binary search algorithem


Binary search algorithem method/function for j2me platform.
Use is with sorted String array!!!
Enjoy... this works great with my example on J2ME | String array sort. link here.



public static int binarySearch(String[] p_arraySorted, String p_key)
{
return binarySearch(p_arraySorted, 0, p_arraySorted.length, p_key);
}



public static int binarySearch(String[] p_arraySorted, int p_first, int p_upto, String p_key)
{
int compare, mid;
while (p_first < p_upto)
{
// Compute mid point.
mid = (p_first + p_upto) / 2;

compare = p_key.compareTo(p_arraySorted[mid]);
if (compare < 0) // p_key < p_arraySorted[mid]
{
// repeat search in bottom half
p_upto = mid;
}
else if (compare > 0) // p_key > p_arraySorted[mid]
{
// Repeat search in top half
p_first = mid + 1;
}
else
{
// Found it. return position
return mid;
}
}

// Failed to find key
return -1;
}


Sort it and search it wisely...

J2ME | String array sort

Here is a good function for sorting string arrays.
The algorithem is BUBBLE-SORT algorithm.
The algorithem sorts the string array (dictionary comparison)


static void bubbleSort(String[] p_array) throws Exception
{
boolean anyCellSorted;
int length = p_array.length;
String tmp;
for (int i = length; --i >= 0;)
{
anyCellSorted = false;
for (int j = 0; j < i; j++)
{
if (p_array[j].compareTo(p_array[j + 1]) > 0)
{
tmp = p_array[j];
p_array[j] = p_array[j + 1];
p_array[j + 1] = tmp;
anyCellSorted = true;
}

}
if (anyCellSorted == false)
{
return;
}
}
}



if you want i will upload more SORT algorithems...

Friday, August 28, 2009

J2ME String Split method

Here is my code for splitting a string under Java - J2ME.
this is very helpfull for using a string array instead of string manipulation.

This is the best & fastest splitting method

Code:

public static String[] split(String p_text, String p_seperator)
{
Vector vecStrings = new Vector();

int index;
int prevIdx = 0;

while ((index = p_text.indexOf(p_seperator, prevIdx)) > -1)
{
vecStrings.addElement(p_text.substring(prevIdx, index));
prevIdx = index + 1;
}
vecStrings.addElement(p_text.substring(prevIdx));

String[] result = new String[vecStrings.size()];
vecStrings.copyInto(result);

return result;
}

Monday, July 6, 2009

Javascript html date control (validation)


Here is a sample code for an html input date control include DATE validation!
I searched a lot for such method for integration with PHP page but was little difficult.

Here is the HTML CODE:
<input id="inputDate1" name="Field1" value="21/07/2006" type="text" onblur="validateDate(this, '/')" maxlength="10">

<button onclick="setTodayDate(this.previousSibling, '/')">today</button>



Here is the JAVASCRIPT CODE:
function validateDate(p_inputObj, delim)
{
var text = p_inputObj.value;
var errorMsgs = "Following error(s) :\n";
var isDateCorrect = true;

var delim1 = text.indexOf(delim);
var delim2 = text.indexOf(delim, delim1+1);
if (delim2 <= delim1)
{
isDateCorrect = false;
errorMsgs = errorMsgs + "- Must be in format of dd/mm/yyyy like (21/09/2008)\n";
}
else
{
var day = parseInt(text.substring(0, delim1), 10);
var splitter1 = text.substring(delim1, delim1+1);
var month = parseInt(text.substring(delim1+1, delim2), 10);
var splitter2 = text.substring(delim2, delim2+1);
var year = parseInt(text.substring(delim2+1), 10);

if (isNaN(day) || isNaN(month) || isNaN(year))
{
isDateCorrect = false;
if (isNaN(day)) { errorMsgs = errorMsgs + "- Day not in correct format!\n"; }
if (isNaN(month)) { errorMsgs = errorMsgs + "- Month not in correct format!\n"; }
if (isNaN(year)) { errorMsgs = errorMsgs + "- Year not in correct format!\n"; }
}
else
{
if (day<1)
{
errorMsgs = errorMsgs + "- Day must be between grater than 0\n";
isDateCorrect = false;
}

if (month>12 || month<1)
{
isDateCorrect = false;
errorMsgs = errorMsgs + "- Month must be between 01 to 12\n";
}
else
{
if (month==1 || month==3 || month==5 || month==7 || month==8 || month==10 || month==12 )
{
if (day>31)
{
errorMsgs = errorMsgs + "- Day must be between 1 to 31\n";
isDateCorrect = false;
}
}
else if(month==2)
{
// is leap year
if (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0))
{
if (day>29)
{
errorMsgs = errorMsgs + "- Day must be between 1 to 29\n";
isDateCorrect = false;
}
}
else
{
if (day>28)
{
errorMsgs = errorMsgs + "- Day must be between 1 to 28\n";
isDateCorrect = false;
}
}
}
else
{
if (day>30)
{
errorMsgs = errorMsgs + "- Day must be between 1 to 30\n";
isDateCorrect = false;
}
}
}

if (year<2000)
{
isDateCorrect = false;
errorMsgs = errorMsgs + "- Year not valid. must be more than 2000!\n";
}
else if (year>9999)
{
isDateCorrect = false;
errorMsgs = errorMsgs + "- Year must be 4 digits!\n";
}
}
}

if (isDateCorrect == true)
{
var newStr = (day<10 ? '0' : '') + day + delim +
(month<10 ? '0' : '') + month + delim +
year; // +" "+hour+":"+minute+" "+AMPM;
p_inputObj.title = '';
var date = new Date();
date.setFullYear(year, month-1, day);
p_inputObj.dateVal = date;
p_inputObj.value = newStr;
p_inputObj.style.backgroundColor='#FFFFFF';
return true;
}
else
{
//alert(errorMsgs);
errorMsgs = errorMsgs.substring(0, errorMsgs.length-1);
p_inputObj.dateVal = null;
p_inputObj.title = errorMsgs;
p_inputObj.style.backgroundColor='#ffaaaa';
p_inputObj.focus();
return false;
}
}

function setTodayDate(p_inputObj, p_delim)
{
var dtNow = new Date();
var day = dtNow.getDate();
var month = dtNow.getMonth() + 1;
var year = dtNow.getFullYear();
p_inputObj.value = (day<10 ? '0' : '') + day + p_delim +
(month<10 ? '0' : '') + month + p_delim +
year;
}


Date format if dd/MM/yyyy but it can also be MM/dd/yy or yyyy!
Enjoy... :)

Tuesday, June 23, 2009

Html (& javascript) Slider example


Here is an example for html slider - Only using HTML & Javascript.
Nice animated slider (good looking animation)

Code:
<html>
<head>
<style>
.spltr {width: 4px; background-color: firebrick;}
</style>
<script language="javascript" type="text/javascript">
function scrollSpeedAdd(obj,step)
{
scrollStop();
scrollAdd(obj, scrollAdd.step + step);
}
function scrollAdd(obj,step)
{
scrollAdd.elem = document.getElementById('MainSlideDiv');
if(scrollAdd.elem)
{
scrollAdd.step = step;
scrollAdd.I = window.setInterval(startScroll,10);
}
}
function startScroll()
{
scrollAdd.elem.scrollLeft = scrollAdd.elem.scrollLeft + scrollAdd.step;
}
function scrollStop()
{
window.clearInterval(scrollAdd.I);
}
</script>
</head>
<body
<b>Set your mouse over the arrows...</b><br /><br />
<table width="700" border="0" cellspacing="0" cellpadding="0" bgcolor="khaki">
<tr style="text-align: center;">
<td width="30" onmouseout="scrollStop();" onmouseover="scrollAdd(this,-2)" onclick="scrollSpeedAdd(this,-1)"> << </td>
<td width="640" align="center">
<div style="overflow:hidden; width:630; height:55;" id="MainSlideDiv" dir="rtl">
<table width="100%" style="text-align:center" border="0" cellspacing="5" cellpadding="5">
<tr>
<td>Test 1111 </td>
<td class="spltr"> </td>
<td>Test 2222 </td>
<td class="spltr"> </td>
<td>Test 3333 </td>
<td class="spltr"> </td>
<td>Test 4444 </td>
<td class="spltr"> </td>
<td>Test 5555 </td>
<td class="spltr"> </td>
<td>Test 6666 </td>
<td class="spltr"> </td>
<td>Test 7777 </td>
<td class="spltr"> </td>
<td>Test 8888 </td>
<td class="spltr"> </td>
<td>Test 9999 </td>
<td class="spltr"> </td>
<td>Test AAAA </td>
<td class="spltr"> </td>
<td>Test BBBB </td>
<td class="spltr"> </td>
<td>Test CCCC </td>
<td class="spltr"> </td>
<td>Test DDDD </td>
<td class="spltr"> </td>
<td>Test EEEE </td>
<td class="spltr"> </td>
<td>Test FFFF </td>
<td class="spltr"> </td>
</tr>
</table>
</div>
</td>
<td width="30" onmouseout="scrollStop()" onmouseover="scrollAdd(this,2)" onclick="scrollSpeedAdd(this,+1)"> >> </td>
</tr>
</table>
</body>
</html>