Thursday, December 24, 2009

How to remove all the screens in display stack in Blackberry

In recently i want to delete all the screens in display stack.  I used following code to do it.

 
int screenCount = UiApplication.getUiApplication().getScreenCount();
for (int i = 0; i < screenCount; i++) {
Screen screen = UiApplication.getUiApplication().getActiveScreen();
UiApplication.getUiApplication().popScreen(screen);
}

Monday, December 21, 2009

Simple Socket Client to connect to a server

private void ConnectToServer()
{
using (TcpClient tc = new TcpClient("127.0.0.1", 12))
{
NetworkStream ns = tc.GetStream();
StreamWriter sw = new StreamWriter(ns);
StreamReader sr = new StreamReader(ns);

sw.WriteLine("test message");
sw.Flush();
System.Console.WriteLine(sr.ReadLine());
}
}
This code can be used to connect to a server using a socket and send a simple message to it.

How to listen to TCP socket in C#

The code below illustrate how to listen to Tcp/Ip port for incoming stream.  The code can use to listen any port but some times you may encountered an exception (Refer).  

private void Run_Server()
{
// Listen to our own port 80 (HTTP protocol port).
IPAddress localAddr = IPAddress.Parse("127.0.0.1");
TcpListener listen = new TcpListener(localAddr, 80);

try
{
// Start listening
listen.Start();
Byte[] bytes = new byte[256];
TcpClient client = listen.AcceptTcpClient();
// This waits until we getting a connection
NetworkStream stream = client.GetStream();

int i;
String data = null;

while (stream.DataAvailable)
{
i = stream.Read(bytes, 0, bytes.Length);
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
txtMessages.Text += data.ToString();
}
client.Close();
}
catch (SocketException exceptionError)
{
MessageBox.Show(exceptionError.Message);
}
finally
{
listen.Stop();
}
}

An attempt was made to access a socket in a way forbidden by its access permissions

// Listen to our own port 80 (HTTP protocol port).
IPAddress localAddr = IPAddress.Parse("127.0.0.1");
TcpListener listen = new TcpListener(localAddr, 80);
This exception occurred me in Vista because of Port. This exception rise some well-known ports thus using other port (Ex:- 12 , 8008) you may resolve this.

Thursday, December 17, 2009

Ugly Number Calculation Algorithm

package javaapplication1;
/**
** @author sachika
*/
public class Main {

public static void main(String[] args) {

Main mainObj = new Main();
int no = mainObj.getNthUglyNo(11);
System.out.print(no);
try{
System.in.read();
}
catch(Exception s) {}

}

int maxDivide(int a, int b)
{
while (a%b == 0)
a = a/b;
return a;
}

boolean isUgly(int no)
{
no = maxDivide(no, 2);
no = maxDivide(no, 3);
no = maxDivide(no, 5);

return (no == 1)? true : false;
}

int getNthUglyNo(int n)
{
int i = 1;
int count = 1; /* ugly number count */

/*Check for all integers untill ugly count
becomes n*/
while (n > count)
{
i++;
if (isUgly(i))
count++;
}
return i;
}

}

Thursday, December 10, 2009

Multiple Columns in Crystal Report

Some times you might want to print the report Column wise

image

so this is simple. what you have to do is go to Section Expert and –>Details and check the Format with Multiple Columns.

image

then Layout tab will appear . then  configure the relevant values.

image

after pressing ok , you can see your detail section is resized.

image

Now you are done.

The GridView 'GridViewID' fired event PageIndexChanging which wasn't handled.

This is a common error when you are binding data to the data grid. you can correct it as giving following code to the  PageIndexChanging event.

protected void gridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gridView.PageIndex = e.NewPageIndex;
gridView.DataBind();
}

Thursday, November 26, 2009

How to Download a File using C#.NET in Visual Studio

System.Net.WebClient wc = new System.Net.WebClient();
wc.DownloadFile("http://www.images.com/some.jpg",@"C:\some.jpg");

this is so simple. You can download any kind of file using this.

Thursday, November 19, 2009

How to send a SMS using C# (Compact Framework) in Windows Mobile

Sending SMS though our own application is very necessary when we talking business application. Windows Mobile SDK comes with PocketOutlook that we can use to send SMSs.

First you need to create a smart device application. and layout your form as below.

image

Then add the PoketOutlook assemply to your application as a reference.

image image

here is the code.

Method1

using Microsoft.WindowsMobile.PocketOutlook;
private void btnSend_Click(object sender, EventArgs e)
{
String number = txtNumber.Text;
String boby = txtBody.Text;
SmsMessage message = new SmsMessage(number,boby);
message.Send();
}

Method2 – Send SMS to Multiple recipients

private void btnSend_Click(object sender, EventArgs e)
{
SmsMessage message = new SmsMessage();

Recipient r1 = new Recipient("Name1", txtNumber.Text);
Recipient r2 = new Recipient("Name2", "0772789456");

message.To.Add(r1);
message.To.Add(r2);

message.Body = txtBody.Text;

message.Send();
}

Monday, November 16, 2009

Configure XAMPP with vista when IIS is running

Go to XAMPP installed folder and go to

Apache /Conf/ Extra folder  and open the httpd-ssl.conf file with note pad or some text editor.

# Note: Configurations that use IPv6 but not IPv4-mapped addresses need two
# Listen directives: "Listen [::]:443" and "Listen 0.0.0.0:443"
#
 
Listen 443

find the above code and change 443 to something like 4499.

DocumentRoot "c:/web/xampp/htdocs"ServerName localhost:443
ServerAdmin admin@localhost

and also find the above and change it to 4499
and save the file.Then open the file httpd.conf in apache/conf folder.

#Listen [::]:80
Listen 80

find above and change 80 to something like 8080

#
ServerName localhost:80

and find this and change it also to 8080

Thursday, November 12, 2009

Change the background color in Blackberry Fields

There are four basic background available in blackberry.

    • SolidBackground
    • SolidBackgroundwithTranparency
    • GradientBackground
    • BitmapBackground
// Solid Background
Background b=BackgroundFactory.createSolidBackground(Color.ANTIQUEWHITE);
setBackground(b);
 
// Solid Background with Transperancy                                       //Alpha
Background b=BackgroundFactory.createSolidTransparentBackground(Color.AZURE,180);
setBackground(b);
 
// Gradient Background
Background b = BackgroundFactory.createLinearGradientBackground(
Color.AZURE,Color.BISQUE,Color.AZURE, Color.BISQUE);
setBackground(b);
 
// Bitmap Background
Background b = BackgroundFactory.createBitmapBackground(yourImage, 0, 0,0);
setBackground(b);

GO language by Google

Google released new programming language called GO. This is a Open Source Programming

language. GO combines the performance and security benefits associated with using a compiled language like C++ with the speed of a dynamic language like Python.

This is how google describes GO,

Go attempts to combine the development speed of working in a dynamic language like Python with the performance and safety of a compiled language like C or C++. In our experiments with Go to date, typical builds feel instantaneous; even large binaries compile in just a few seconds. And the compiled code runs close to the speed of C. Go is designed to let you move fast.

References,Tutorials

Wednesday, October 28, 2009

Programmatically Read JAD file in Blackberry

in here following code worked but you have to deploy the application using JAD file (download through the web)  not the using alx file.

public static String getJADProperty(String Name){
    CodeModuleGroup[] allGroups = CodeModuleGroupManager.loadAll();
    CodeModuleGroup myGroup = null;
    String moduleName="";
    moduleName = ApplicationDescriptor.currentApplicationDescriptor().getModuleName();
    for (int i = 0; i < allGroups.length; i++) {
    if (allGroups[i].containsModule(moduleName)) {
    myGroup = allGroups[i];
    break;
    }
    }
 
    // Get the property
    String prop = myGroup.getProperty(Name);
    return prop;
}

You can get the custom property by calling



// You can get the MyTag:something
String value = getJADProperty("MyTag")

Tuesday, October 27, 2009

Asynchronous Threading in Blackberry

clip_image001[10]

Assume that you are having a class called Class A it needs to call Class Z as a thread. Therefore you can  implement class Z from Runnable interface and implement your code in run().

Ex:-
public class ClassZ implements Runnable {
 
    public static final int METHOD1 =1;
    public static final int METHOD2= 2;    
 
    int code;
    
    public ClassZ(int code)
    { this.code=code; }     
 
    private void method1()
    { //Code for Method1 }
 
    private void method2()
    { //Code for Method2 }
 
    public void run() {
    
        switch (code)
        {
        case ClassZ.METHOD1 :
            method1();
            break;
        case ClassZ.METHOD2:
            method2();
            break;
        }
    }
 
    public void runThread() {
    thread = new Thread(this);
    thread.start();
    }
}


If you start the Thread using ClassZ it runs ClassZ’s run method. Therefore  if you have several method in side the class you need to have a variable telling which method you want to run. Thus in here i used code variable to  keep the information about the method which i want to run. And also we wrote a method to start the thread called runThread(). 





public Class ClassA 
{
    method()
    {
        // Initialize the ClassZ by passing which
        // method we used to invoke as thread
        ClassZ clsz = new ClassZ(ClassZ.method1);
        clsz.runThread();
    }
}


Sometimes we want to do something after finish executing the thread. But in here there are no return vales in a thread. therefore we use mechanism called callBack().










 clip_image001[12]
Assume that you are calling the thread class  from ClassA or ClassB and want to get some feedback according the caller. Therefore we can change the code as below.



public class ClassZ implements Runnable {
 
    public static final int METHOD1 =1;
    public static final int METHOD2= 2;    
 
    int code;
    Object object;
    
    public ClassZ(int code,Object object)
    { this.code=code;
      this.object=object;  
    }     
 
    private void method1()
    { //Code for Method1
        callBack();
    }
 
    private void method2()
    { //Code for Method2 
        callBack();
    }
 
    public void run() {
    
        switch (code)
        {
        case ClassZ.METHOD1 :
            method1();
            break;
        case ClassZ.METHOD2:
            method2();
            break;
        }
    }
 
    public void runThread() {
    thread = new Thread(this);
    thread.start();
    }
 
    void callBack()
    {
        if (object instanceof ClassA) {
            ((ClassA) object).callBack();
        }
        
        else if (object instanceof ClassB) {
            ((ClassB) object).callBack();
        }
    }
}
If method finished executed it invoke callBack(). The method check the object instance and invoke relevant callBack() in the class.



public Class ClassA 
{
    method()
    {
        // Initialize the ClassZ by passing which
        // method we used to invoke as thread and 
        // object itself
        ClassZ clsz = new ClassZ(ClassZ.method1,this);
        clsz.runThread();
    }
 
    public void callBack()
    {
        // code after executing the
        // thread
    }
}

Thursday, October 22, 2009

Best Practices in programming

I though to write a continuous article describing best practices in programming. Here I’m not going to talking about  coding conventions but talking about enhanced cording techniques you can use.

Using IO, Network connections

InputStream streamRead =null;
try {
    //  Use InputStream to do your work   
} catch (Exception ex) {
    // Exception Handling
}
finally
{
    try {
    // Try to close the stream, This may also give erros
    // resulting opened stream
    streamRead.close();
    } catch (IOException e) {
    }
    // Set Stream to null to prevent
    // unwanted openings
    streamRead=null;
}

Not to use methods in loop’s conditions

// This is not optimized
for (int i = 0; i < elements.capacity(); ++i)
{
    // Code Here     
}
 
// This is optimized,
// elements.capacity() only call in one time
int capacity = elements.capacity();
for (int i = 0; i < capacity; ++i)
{
    // Code Here  
}

Use String Buffer wherever possible.

// This will create two string and
// append it
String str = new String ("My Name is : ");
str += "Mleick";
 
// This is better
StringBuffer str = new StringBuffer ("My Name is :");
str.append("Mleick!!");

Use Threads to call server calls where ever possible.


This prevents user to feel as hang the system during the network calls. I’ll write a article including asynchronous server calls.