Blackberry Development using Netbeans

Please let me know if you find any errors or missing steps.

Installation and setup:

Step 1 - download and install Suns Java SDK

Step 2 - download and install Netbeans IDE

Step 3 - download and install Netbeans Mobility Pack

Step 4 - download and install RIMs Blackberry JDE

Step 5 - Launch Netbeans, from the toolbar select tools > java platform manager > add platform and select ‘custom java micro edition platform emulator’

Step 6 - Enter (or paste) Rims JDE home directory, for example: ‘C:\Program Files\Research In Motion\BlackBerry JDE 4.2.0′ as the Platform Home, then add ‘Platform Name’ (eg. Rim) and ‘Device Name’ (eg. Blackberry)

Step 7 - Select ‘Next’, From the ‘Bootstrap Libraries’ list, remove every item except ‘net_rim_api.jar’

Step 8 - Select ‘Next’, Ignore the ‘Sources’ pane but add the path to the Blackberry javadocs, for example: ‘C:\Program Files\Research In Motion\BlackBerry JDE 4.2.0\docs\api\’ then click ‘finish’

Step 9 - Restart Netbeans

Create a simple Blackberry Application:

Step 1 - Create a new project by selecting ‘mobile application’ from the ‘mobile category’, uncheck the ‘Create Hello Midlet’ option

Step 2 - Select the Blackberry platform that you’ve just created above

Step 3 - Add this xml data to the build.xml file which is visible if you select the ‘Files’ pane

Step 4 - Next you need to create an .alx file which is a Blackberry ‘Application Loader’ xml file, in the ‘Files’ pane, right-click and select ‘new’ > ‘empty file’
Name the file the same as your application (eg. myApp.alx), and add this xml data [important - only use numerics in the version number, any letters can cause issues for OTA installing of the application when you’re done, for example do not use any ‘beta’ version notifiers like b1.0

Step 5 - You’re now ready to start writing your application, switch back to the ‘Project’ pane and create your application, native Blackberry apps extend the UiApplication class instead of Midlet so you’ll have cheat Netbeans by entering your main class as the Midlet: right click on your application in the project pane and select ‘Properties’, under ‘Application Descriptor’ > MIDLets enter the name of your class that extends UiApplication (ignore any warnings)

Step 6 - Right click on your project and select ‘Clean and Build’, once you know your application will build select ‘Debug’ from the same menu. Netbeans should spawn the ‘Rim Remote Debug Server’ and the Blackberry Simulator, all your System.out.println statements will appear in the Debug Server not in the Netbeans output pane.


that's it....

...S.VinothkumaR.

Regex and MatchCollection

Using Regex, we can replace string with regular expression. Here is the sample of using Regex.

using System.Text.RegularExpressions;


string mail = "test";
MatchCollection mcMail = Regex.Matches(mail, @"\w+?@\w+?\.(comnetin)");
string phoneNo = "My Phone Number is 98393 94893";
MatchCollection mcPhoneNo = Regex.Matches(phoneNo, @"\d\d\d\d\d \d\d\d\d\d");
if(mcMail.Count>0)
mail = mcMail[0].ToString();
if(mcPhoneNo.Count>0)
phoneNo = mcPhoneNo[0].ToString();


If we have a string with multiple phone number like "My Phone Number is 98393 94893 other no is 93759 84595", we can use Multiple MatchCollection as follows,


string phoneNo = "My Phone Number is 98393 94893 other no is 93759 84595";
MatchCollection mcPhoneNo = Regex.Matches(phoneNo, @"\d\d\d\d\d \d\d\d\d\d");


if (mcPhoneNo.Count > 0)
{
phoneNo = "";
for (int i = 0; i < phoneno ="phoneNo+mcPhoneNo[i].ToString()+">

From the MatchCollection, there are some properties available. Here is explonation for some of that properties.

Success:
Indicates whether a match was found. You should test this value before processing the match.

Index
Indicates the position in the string where the match starts.

Length
Indicates the length of the substring that matches the pattern. Value Equals the substring that did match the pattern.

Groups
Returns a collection of Group objects.

...S.VinothkumaR.

Log File creation for web application

public string logPath = ConfigurationManager.AppSettings["LogPath"] + DateTime.Now.ToString("MM-dd-yyyy")+".txt";
public string logStatus;

logStatus = " Created! \t:" + DateTime.Now.ToString("hh:mm:ss");
if (!File.Exists(logPath))
{
File.WriteAllText(logPath, logStatus);
logStatus = System.Environment.NewLine;
logAppending(logStatus);
}
else
{
logAppending(logStatus);
}

logAppending
---------------
private void logAppending(string allStatus)
{
StreamWriter sw = new StreamWriter(logPath, true);
sw.WriteLine(allStatus + System.Environment.NewLine);
sw.Close();
}


...S.VinothkumaR.

Getting Image from Panel

Bitmap bmp = new Bitmap(panel1.Width, panel1.Height);
Rectangle rect = new Rectangle(0, 0, panel1.Width, panel1.Height);
panel1.DrawToBitmap(bmp, rect);
bmp.Save("test.jpg");

...S.VinothkumaR.

Converting List to byte[] in C#.

public byte[] GetBytesFromList()
{
List lstByte= new List(90);
byte[] byteArr = Encoding.ASCII.GetBytes("Test");
lstByte.AddRange(byteArr);
return lstByte.ToArray();
}

...S.VinothkumaR.

Converting String to Stream in C#

Stream s = new MemoryStream(ASCIIEncoding.Default.GetBytes("Test String"));

...S.VinothkumaR.

String Encryption and Decryption in C# using Cryptography.Rijndael algorithm.

Here is the sample coding for string Encryption and Decryption using Rijndael algorithm.


using System.Security.Cryptography;
using System.IO;


public static string Encrypt(string clearText, string Password)
{
byte[] clearBytes = System.Text.Encoding.Unicode.GetBytes(clearText);
PasswordDeriveBytes pdb = new PasswordDeriveBytes(Password,
new byte[] {0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d,
0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76});


// PasswordDeriveBytes is for getting Key and IV.
// Using PasswordDeriveBytes object we are first getting 32 bytes for the Key (the default
//Rijndael key length is 256bit = 32bytes) and then 16 bytes for the IV.
// IV should always be the block size, which is by default 16 bytes (128 bit) for Rijndael.

byte[] encryptedData = Encrypt(clearBytes, pdb.GetBytes(32), pdb.GetBytes(16));
return Convert.ToBase64String(encryptedData);
}



// Encrypt a byte array into a byte array using a key and an IV

public static byte[] Encrypt(byte[] clearData, byte[] Key, byte[] IV)
{
MemoryStream ms = new MemoryStream();
Rijndael alg = Rijndael.Create();


// Algorithm. Rijndael is available on all platforms.

alg.Key = Key;
alg.IV = IV;
CryptoStream cs = new CryptoStream(ms, alg.CreateEncryptor(), CryptoStreamMode.Write);


//CryptoStream is for pumping our data.

cs.Write(clearData, 0, clearData.Length);
cs.Close();
byte[] encryptedData = ms.ToArray();
return encryptedData;
}



public static byte[] Decrypt(byte[] cipherData, byte[] Key, byte[] IV)
{
MemoryStream ms = new MemoryStream();
Rijndael alg = Rijndael.Create();
alg.Key = Key;
alg.IV = IV;
CryptoStream cs = new CryptoStream(ms,alg.CreateDecryptor(), CryptoStreamMode.Write);
cs.Write(cipherData, 0, cipherData.Length);
cs.Close();
byte[] decryptedData = ms.ToArray();
return decryptedData;
}



// Decrypt a string into a string using a password
// Uses Decrypt(byte[], byte[], byte[])


public static string Decrypt(string cipherText, string Password)
{
byte[] cipherBytes = Convert.FromBase64String(cipherText);
PasswordDeriveBytes pdb = new PasswordDeriveBytes(Password,
new byte[] {0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65,
0x64, 0x76, 0x65, 0x64, 0x65, 0x76});
byte[] decryptedData = Decrypt(cipherBytes, pdb.GetBytes(32), pdb.GetBytes(16));
return System.Text.Encoding.Unicode.GetString(decryptedData);
}

Play a mp3 sound using MediaPlayer in C#.

Here is sample coding for how to play a mp3 song in C# applicatin using AxWMPLib library.

- First add the library from Com reference with the name of Windows Media Player (wmp.dll).

- Drag the media player control from tool box in to your form.

- Copy the following code into Form_Load


axWindowsMediaPlayer1.URL = "C:\\test.mp3";
axWindowsMediaPlayer1.Ctlcontrols.stop();


- Copy the following code when click the play button


axWindowsMediaPlayer1.Ctlcontrols.play();

- Copy the following code when click the pause button.


axWindowsMediaPlayer1.Ctlcontrols.pause();

- We can get the time duration of playing file as follows,


axWindowsMediaPlayer1.currentMedia.attributeCount.ToString();

axWindowsMediaPlayer1.currentMedia.durationString;

axWindowsMediaPlayer1.Ctlcontrols.currentPositionString;


...S.VinothkumaR.

Find All Text files in all directories.

Here is the sample code for find all text file in all directories.

private void Form1_Load(object sender, EventArgs e)
{
foreach (string drives in Environment.GetLogicalDrives()) // Getting Logical drivers
{
FindFiles(drives);
}
}


private void FindFiles(string drives)
{
try
{
string[] directory = Directory.GetDirectories(drives); // Getting directories from a Directory
if (directory.Length > 0)
{
for (int i = 0; i < directory.Length; i++)
{
try
{
string[] files = Directory.GetFiles(directory[i], "*.txt"); //Finding Text files only
if (files.Length > 0)
{
for (int j = 0; j < files.Length; j++)
{
try
{
lstAllFiles.Items.Add(files[j]); //Adding files in to a list box
}
catch { }
}
}
}
catch { }
FindFiles(directory[i]);
}
}
}
catch { }
}

Getting the Values of Controls on the Master Page

The following example shows how you can get a reference to controls on the master page.

// gets a reference to a textbox control inside a contentplaceholder

ContentPlaceHolder mpContentPlaceHolder;
TextBox mpTextBox;
mpContentPlaceHolder = ( ContentPlaceHolder ) Master.FindControl("ContentPlaceHolder1");
if ( mpContentPlaceHolder != null )
{
mpTextBox = ( TextBox ) mpContentPlaceHolder.FindControl ( "TextBox1" );
if ( mpTextBox != null )
{ mpTextBox.Text = "TextBox found!"; }
}

RoleManagement in Asp.Net

To enable role management for your ASP.NET application, use the roleManager element of the system.web section in the Web.config file for your application, as shown in the following example,

DataSet.HasChanges using in C#.

Sample code for using DataSet.HasChanges function.


private void UpdateDataSet(DataSet myDataSet)
{
// check for changes with the HasChanges method first.
if (!myDataSet.HasChanges(DataRowState.Modified))
return;
// create temporary DataSet variable.
DataSet tempDataSet;
// getChanges for modified rows only.
tempDataSet = myDataSet.GetChanges(DataRowState.Modified);
// check the DataSet for errors.
if (tempDataSet.HasErrors)
{
// ... insert code to resolve errors here ...
}
// after fixing errors, update db with the DataAdapter used to fill the DataSet.
myDataAdapter.Update(tempDataSet);
}


...S.VinothkumaR.

XML Serialization and DeSerialization using C#.

Here is the sample coding for a simple Serialization and DeSerialization program using C#.

myClass.CS

using System;
using System.Collections.Generic;
using System.Text;
namespace Serialization
{
public class myClass
{
protected string namefield;
protected string placefield;
public string name
{
get { return namefield; }
set { namefield = value; }
}
public string place
{
get { return placefield; }
set { placefield = value; }
}
}


button1_Click


myClass myClassObj = new myClass();
myClassObj.name = "Vinoth";
myClassObj.place = "Chennai";
XmlSerializer serializer = new XmlSerializer(typeof(myClass));
string path = Environment.CurrentDirectory + "\\serialization.xml";
TextWriter writer = new StreamWriter(path,true);
serializer.Serialize(writer, myClassObj);
writer.Close();

MessageBox.Show("Serialized");

FileStream fs = File.OpenRead(Environment.CurrentDirectory + "\\serialization.xml");
myClassObj=(myClass)serializer.Deserialize(fs);


MessageBox.Show(myClassObj.name);

That's it....

....S.VinothkumaR.

XML to XSD And XSD to CS

Here is the way to create xsd file from xml using XSD in VS.Net 2005

For this we need to put our xml file in to c:\Program Files\Microsoft Visual Studio 8\VC and run the following command in visual studio command prompt.

xsd test.xml // here test.xml is our xml file.

The following command for creating a CSharp class from xsd.

xsd test.xsd /c

Converting a CS file in to DLL

Here is the code for creating dll from CS file.

First put your cs file in C:\Program Files\Microsoft Visual Studio 8\VC

And choose Dot Net command prompt as follows,

Start ->
All Programs ->
Microsoft Visual Studio 2005 ->
Visual Studio 2005 Command Prompt

Enter the following and press enter key,

csc /t:library /r:System.Web.Services.dll /r:System.Xml.dll myClass.cs

t --> means Target

r --> means Reference.

Note:

Here,

System.Web.Services.dll is webservice's reference.
System.Xml.dll is XML's reference.