One machine can do the work of fifty ordinary men. No machine can do the work of one extraordinary man

Tuesday, January 1, 2019

How to take input from user in Java

This is one of the common and frequently asked question in Java language. There are few ways to get the user inputs from user via a keyboard.
  • Scanner
  • BufferedReader and InputStreamReader
  • Console
  • DataInputStream (This is deprecated)

Scanner

This is the easiest way to get keyboard inputs from the user. Java Scanner class comes under the java.util package. Normally scanner tokenize the input from the white spaces as a default delimiter. An another advantage of the Scanner is you don't have to write another like to convert the value into a different (required) data format.

import java.util.Scanner;

// Set the default input stream (keyboard) to the scanner object.
Scanner scan = new Scanner(System.in);

// Default next method returns you the value as a String.
String s = scan.next();

// Use the nextInt(), nextDouble() like methods to read the input and parse that directly to a required data format.

int i = scan.nextInt();

// Can read the whole line at once.
String s = scan.nextLine();

Buffered Reader and Input Stream Reader

These two classes comes under the java.io package.

import java.io.BufferedReader; 
import java.io.InputStreamReader; 

BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 

String s = br.readLine(); 

int i = Integer.parseInt(br.readLine());

Console

The Console class is also comes under the java.io package.

import java.io.Console;
Console console = System.console();

String s = console.readLine();

Monday, December 31, 2018

How to split a String by space (any white space)

The String splitting is a very common requirement in any programming language. In java it is very much straight forward since there is a split() method in String. Normally what we do is provide the delimiter to the split method and get the tokens into a String array.

But most of beginners don't know we can pass regular expression as a delimiter.

Here I am using a regular expression as a delimiter to split the String by any white space regardless it is a tab, space, multiple tabs or spaces.

str = "This is     the String with    different white spaces";
String[] splited = str.split("\\s+");

Saturday, December 29, 2018

Iterate Map in Java 8


Java 1.8 is a huge bump in the programming world with the introduction of great features sometimes object oriented programmers didn't even imagine. They introduced some of the functional programming features into Java world such as functional interfaces, lamda functions and that helps programmers to use object oriented concepts in a better way.

Sometimes iterating through a collection such as a map or list is a headache for a programmer since there can be concurrent issues.


The most famous way of doing it is using an Iterator (This is the best way before 1.8).

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class Main {

public static void main(String[] args) {

// Creating students.
Student s01 = new Student("001", "Steven");
Student s02 = new Student("002", "Mathews");

// Creating a map.
Map<String, Student> students = new HashMap<>();

// Populating the map.
students.put(s01.getId(), s01);
students.put(s02.getId(), s02);

// Get the Iterator.
Iterator<Map.Entry<String, Student>> iterator = students.entrySet().iterator();

// Iterator through the map using the iterator.
while(iterator.hasNext()) {

Map.Entry<String, Student> studentEntry = iterator.next();

// Can retrieve the id if required.
String id = studentEntry.getKey();

// Retrieve the student from the map entry.
Student student = studentEntry.getValue();

System.out.println(student);

}
}


static class Student {

private String id;
private String name;

public String getId() {
return id;
}

public void setId(String id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public Student(String id, String name) {
this.id = id;
this.name = name;
}

@Override
public String toString() {
return "Student{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
'}';
}
}
}


The simplest way is a for loop.


public static void main(String[] args) {
// Creating students.
Student s01 = new Student("001", "Steven");
Student s02 = new Student("002", "Mathews");

// Creating a map.
Map<String, Student> students = new HashMap<>();

// Populating the map.
students.put(s01.getId(), s01);
students.put(s02.getId(), s02);

// Iterator through the entry set.
for(Map.Entry<String, Student> entry: students.entrySet()) {

// Accessing the entry.
Student student = entry.getValue();

System.out.println(student);
}
}

Now with the introduction of lamda functions, we have a better way of doing this.

public static void main(String[] args) {
// Creating students.
Student s01 = new Student("001", "Steven");
Student s02 = new Student("002", "Mathews");

// Creating a map.
Map<String, Student> students = new HashMap<>();

// Populating the map.
students.put(s01.getId(), s01);
students.put(s02.getId(), s02);

// Use forEach method for a collection in Java 8.
students.entrySet().forEach((studentEntry) -> {

// Access the entry of the map.
Student student = studentEntry.getValue();

System.out.println(student);

});
}


Hope this helps you, please let me know your comments about the post.

Friday, December 27, 2013

C# Part 1 : Hello World Program

This is a starting of new tutorial series for C# beginners. You don't need to have big experiences with any programming language and I am expecting very basic computer knowledge as an requirement.

I am conducting this sessions using 'Microsoft Visual Studio 2010' product. If you don't have licence version of that you can download free light version called 'Visual C# 2010 Express' from the Microsoft official web site.




Now we are going to write the "Hello World" program.

Step 1 : Open Visual Studio 2010 software


Step 2 : Then create a new project

File -> New -> Project


As the first program we are going to create a console C# application. Once you got the New Project window, follow the instructions in the above picture and press OK to create the project.

Then it will generate a simple program automatically for you. After that you can add following lines to the Main() method (which is the starting point of the program).

Console.WriteLine("Hello World");
Console.ReadLine();

Following picture describe the program properly.


1) Namespaces used by the program (Actually this small program required only 'System' namespace). Namespace is a collection of Classes, Delegates, Enums and Namespaces which we will go in depth in next tutorials.

2) Namespace of the current class

3) Declaration of the class (In this case the class name is 'Program')

4) Starting point of the program

5) Ending point of the program

6) 'WriteLine()' is the method inside the 'Console' class that we use to write something to the console. 'Console' class is in the 'System' namespace.

7) 'ReadLine()' is the method inside the 'Console' class that we use to read user inputs from the console (In this case we use this method to wait the program until we press any key).

Please put a comment if you have any doubts. Play around with this code and ask any question regarding the issues you faced. See you in the next tutorial.



Friday, March 29, 2013

Generate HTML Content in JAVA

This post is for generating HTML content in java. You can use 3rd party jar called rendersnake to do this kind of thing very easily. This has class called HTMLCanvas and you use hierarchical structure to build the HTML.

You can find more samples and information from
http://rendersnake.org/index.html
https://code.google.com/p/rendersnake/

This is a free opensource library and can find the license here : http://www.apache.org/licenses/LICENSE-2.0.html

Here is a sample code snippet

    HtmlCanvas htmlCanvas = new HtmlCanvas();

HtmlAttributes tableAttributes = new HtmlAttributes();
tableAttributes
.add("border", "1")
.add("bgcolor", "#E8E8E8")
.add("cellspacing", "0")
.add("cellpadding", "5")
.add("bordercolor", "#B0B0B0");

HtmlAttributes rowHeaderAttribute = new HtmlAttributes();
rowHeaderAttribute.add("bgcolor", "#C8C8C8");

HtmlAttributes taskRowHeaderAttribute = new HtmlAttributes();
taskRowHeaderAttribute.add("bgcolor", "#C8C8C8");
taskRowHeaderAttribute.add("width", "400");
taskRowHeaderAttribute.add("height", "50");

HtmlAttributes cellColor = new HtmlAttributes();
cellColor.add("bgcolor", "#009933");

htmlCanvas.html()
.body()
.b().content("Status : OK")
.br()
.table(tableAttributes).th(taskRowHeaderAttribute).content("Task")
.th(rowHeaderAttribute).content("User")
.th(rowHeaderAttribute).content("Host")
.th(rowHeaderAttribute).content("Status");

for(int i=0; i<10; i++) {
htmlCanvas.tr().td().content("Task " + i)
.td().content("User " + i)
.td().content("Host " + i)
.td(cellColor).content("Status " + 1)
._tr();
}
htmlCanvas._table().br().br()._body()._html();
   System.out.println("Result : " + htmlCanvas.toHtml());

Following is the result of above code.



You need to add the jar that downloaded from the above link and can do this kind of table very easily. If there is a exception occurred when you run the application call specifically "commons-lang3-3.1.jar" not found, you need to add that jar file as well. You can find this jar from http://commons.apache.org/proper/commons-lang/download_lang.cgi

Wednesday, March 27, 2013

Java DateTime Formatting

You can use following mechanism to get the date and time as a format you preferred. You need to use the Calendar class in the java.util package. It is possible to filter the date time using SimpleDateFormat class in the java.text package by passing the format to the constructor.

LetterDate or Time ComponentPresentationExamples
GEra designatorTextAD
yYearYear199696
MMonth in yearMonthJulyJul07
wWeek in yearNumber27
WWeek in monthNumber2
DDay in yearNumber189
dDay in monthNumber10
FDay of week in monthNumber2
EDay in weekTextTuesdayTue
aAm/pm markerTextPM
HHour in day (0-23)Number0
kHour in day (1-24)Number24
KHour in am/pm (0-11)Number0
hHour in am/pm (1-12)Number12
mMinute in hourNumber30
sSecond in minuteNumber55
SMillisecondNumber978
zTime zoneGeneral time zonePacific Standard TimePSTGMT-08:00
ZTime zoneRFC 822 time zone-0800



public String getTimeStamp(){
Calendar cal = Calendar.getInstance();
Date date = cal.getTime();

SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd_hhmmss");

String timeStamp = "";

try {
timeStamp = format.format(date);
} catch (Exception e1) {
   e1.printStackTrace();
}

return timeStamp;
}

Thursday, July 12, 2012

Fire Alarm When You Insert a Row to SQL Table

First you have to write a particular trigger for run the .exe file, when you insert a record to the data table.

Following is the Trigger


create trigger runexe
on tbDetails
for insert
As
Begin
print 'Inserted'
Exec Master..xp_cmdshell 'E:\Hiran\Alarm.exe'
End

Some SQL Server versions does not allowed to run the "xp_cmdshell" command. In that case you have to enable that feature by executing the following commands.


EXEC sp_configure ‘show advanced options’, 1

EXEC sp_configure ‘xp_cmdshell’, 1


After that you have to write a particular C# program to run the particular batch (.bat) file. The program.cs should look like below. We can run the batch file at once. But then, it will not be Asynchronous and we have to wait until finish the wave file to insert the record. Therefore the best way is this.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Diagnostics;
using System.Security;


namespace Alarm
{
    static class Program
    {
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            System.Diagnostics.Process.Start("cmd.exe", @"/c E:\Hiran\aaa.bat");
            Application.Exit();
        }
    }
}

Then open the notepad and write the below cording. After that save it using .bat extension.

sndrec32 /play /close "E:\Hiran\SirenSound.wav"


Now You are done. Please comment if you need any help.
Thank You.









Sunday, May 20, 2012

C++ Program Connect with SQL Database


First i am going to show you how to build up the connection between SQL database and the C++ application that you have created.

1st STEP
=======

First you have to add the following name spaces.

using namespace System::Data;
using namespace System::Data::SqlClient;

2nd STEP
=======

Once you add this namespaces then you have to set the connection string and you have to open the connection before you interact with database(inside the particular method that you want to call the query).

SqlConnection ^cn = gcnew SqlConnection();
cn->ConnectionString ="Server=localhost;Database=NVIS;Integrated Security=true";
cn->Open(); 

In here my server is localhost and the database is NVIS.

3rd STEP
=======

If you want to execute the insert query following code should be added.

SqlCommand ^insertCommand 
= gcnew SqlCommand(("insert into Vessel values ('"+gcnew String(b.Name)+"', '"+gcnew String(b.Type)+"', '"+gcnew String(b.Signature)+"', "+b.MaximumSpeed+", "+b.Length+", "+b.MaximumRange+", "+b.MaximumDisplacement+", "+b.NumberOfCrew+");")  ,  cn  );

insertCommand->ExecuteNonQuery();

In here first parameter is the Query that you want to execute (string type), and the second parameter is the Connection (SqlCommad Type).

If you want to do a update or delete you can use the same procedure.

4th STEP
=======

If you do selection,
1) Select a single  row only
2) Select more than one row

1) Select a single  row only
---------------------------
SqlConnection ^cn = gcnew SqlConnection();
  
SqlCommand ^selectQuery = gcnew SqlCommand("select * from Vessel where vesselName='"+txtSearch->Text+"'",cn);

SqlDataReader ^ reader;
reader = selectQuery->ExecuteReader();

reader->Read();

try{txtName->Text=reader->GetString(0);}catch(...){}
try{cmbType->Text=reader->GetString(1);}catch(...){}
try{txtSignature->Text=reader->GetString(2);}catch(...){}
try{txtMaxSpeed->Text=reader->GetDouble(3).ToString();}catch(...){}
try{txtLength->Text=reader->GetDouble(4).ToString();}catch(...){}
try{txtMaxRange->Text=reader->GetDouble(5).ToString();}catch(...){}
try{txtMaxDisplacement->Text=reader->GetDouble(6).ToString();}catch(...){}
try{txtCrew->Text=reader->GetInt32(7).ToString();}catch(...){}

reader->Close();

2) Select more than one row
----------------------------
    SqlCommand ^selectQuery = gcnew SqlCommand("select * from Vessel",cn);
itm = new ItemOnList[count];
SqlDataReader ^ reader;
reader = selectQuery->ExecuteReader();

int i=0;
while(reader->Read())
{
try{u.StringToChar(itm[i].Name, reader->GetString(0));}catch(...){}
try{u.StringToChar(itm[i].Type, reader->GetString(1));}catch(...){}
try{u.StringToChar(itm[i].Signature, reader->GetString(2));}catch(...){}
try{itm[i].MaxSpeed=reader->GetDouble(3);}catch(...){}
try{itm[i].Length=reader->GetDouble(4);}catch(...){}
try{itm[i].MaxRange=reader->GetDouble(5);}catch(...){}
try{itm[i].MaxDisplacement=reader->GetDouble(6);}catch(...){}
try{itm[i].Crew=reader->GetInt32(7);}catch(...){}
    }

Here are all the codings to connect with SQL Database and the C++ Program.
If there are any issue or a question please don't forget to put a comment.










Thursday, May 10, 2012

How To Read A Weight Scale via Serial Port

For my project that given by my company, I have created a application for take readings inside c# function. This is a serial port connected weighing machine and this is a CAS PDII machine. But technique that I have used is applicable for any serial port connected weighing machine. Before I do this I followed many blogs and sits. But I couldn't find anything that successfully worked. I think this may helpful to you definitely.

First you have to create a separate method to be called to take weight.


Then you have to fill the code in event handler. Following is the code inside the event handler.
You have to keep two double variables value and the weight.


Now connect your weighing to serial port and try to execute. Hope this will help you a lot.

Friday, July 1, 2011

WPF transparent form application

1) First you have to create a new WPF application project
                                           File -> New -> project
select WPF application and press OK

2) Then you have to create a circle inside the form using the Ellipse tool in the toolbox
3) After that you have to do few changes to the XAML coding


Your  coding appear like the following


<Window x:Class="MyApp.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="300" Width="300">
    <Grid>
        <Ellipse Margin="-1,-1,-1,1" Name="ellipse1" Stroke="Black"/>
    </Grid>
</Window>


That must change like following


<Window x:Class="MyApp.Window1" MouseLeftButtonDown="Window_MouseLeftButtonDown" WindowStyle="None" AllowsTransparency="True" Background="Transparent"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="300" Width="300">
    <Grid>
        <Ellipse Margin="-1,-1,-1,1" Name="ellipse1" Stroke="Black" Fill="Gray" Opacity="0.5"/>
        <Button Height="23" Margin="99,28,104,0" Name="button1" VerticalAlignment="Top">Close</Button>
    </Grid>
</Window>


following picture show you the changes by underlining newly added parts
4) Then double click on the button and write the following coding part
               Close();
5) Then write the following code inside the "Window_MouseLeftButtonDown" method
               DragMove();
   You can see the above 2 steps from the picture
6) Finally build the solution and see the result. you can drag the form by draging the content of the form
This is a very basic WPF form application. You can develop any complex interfaces or application same as the normal windows form application by using this theory

Wednesday, March 9, 2011

Pharmacy Software for beginners

This is my first year project that we have in the software technology subject. we have to create a pharmacy software which use in the their stores using c++ language. But at that time we don't have a knowledge to use databases. Therefore we use linked list method to implement this project. Then we can store our inputed values until we close the program using linked list. Click here to download the .exe file and try it and see how to work. First of all you have to input stocks. Then input items. After that you can check other functions.


In the picture you can see the the Add Items tab. There are two tabs inside that. Because if we want to add new item what we don't have in the inventory we have to add that item separately, otherwise we can input that immediately. Different stocks in the same item separate by the expire date.


Above you can see the release item tab. when we release items we have to reduce the stored values and it will automatically calculate the price and it will show you how much you have in your hand after you release this amount. If that quantity in hand is less than Re-order level we give you a massage "please reorder the item".


When we move to the edit item tab, there are two tabs for Edit Items and Edit stocks. If we want to edit one item of a stock we can use edit item tab and if we want to edit whole stock details we can use edit stock tab.


This is a Delete item tab. First you have to specify the deletion type and you can select items for delete. When you delete items if the Re-order level reached it will show you a message to inform that. 


When we move to the Report tab there are more reports to the user that provide various information about items. Before you watch the results you have to refresh the table.


Click here to download the source code. This software created using visual studio 2008 IDE. Because of that your system have visual studio 2008 to see the source code. That the zip file I provide, you have to extract first. then goto that folder and double click the visual studio file. Then you can see the source code and other interfaces.


Saturday, March 5, 2011

New software "Media Center" to watch TV, Listen Radio and read News

Web is too  decentralized place. If we want to watch TV or listen Radio and read news, we have to go through search engines to find out them. I think about a software to centralize all of them. That is the Media Center (beta version)software


You can watch TV, listen Radio, Watch e-papers and go to the other news  sites very easily by only pressing a one button.


Click Here to Download.
when this software run sometimes system will ask you permission for connect to the internet. Then you have to Allow it. Otherwise it will not working properly. Some channels did not provide that services at sometimes. If those are not working you have to try that channel after few minutes.
There can be errors. Because this is a beta version. Please inform us about if there are any errors.Your comments are very useful to improve this software. 

Thursday, February 10, 2011

Shell Scripting - Tutorials

To view the full size image, you have to click on the image.......

01. This example coding gives you a clear idea about how to write a switch statements and how to get user inputs in shell script. 

Write a menu driven shell script to perform the following tasks
        [1] Show Today's date/time
        [2] Show file in current directory
        [3] Show calender
        [4] Start editor to write letters
        [5] Exit/Stop
02.This example coding is helpful to you to understand how to use advance for-loops


Write a shell script to display the even numbers 2,4,6,......100
04. Suppose you have a text file named dirList containing a list of directories. Write a shell script that goes to each of them, execute the command make and comes back to the working directory
05. How to perform real number calculation? How to calculate 5.12 + 2.5 real number calculation at $ prompt in shell?
                echo 5.12 + 2.5 | bc


Thursday, February 3, 2011

java - Methods to manipulate characters



I will give you examples to get a clear idea about each and every method


1. isDigit()                                 - check whether the character is a digit or not
2. isLetter()                               - check whether the chatacter is a letter or not
3. isLowerCase()                       - check whether the character is a lowercase or not
4. isUpperCase()                       - check whether the character is a uppercase or not
5. toLowerCase()                      - convert the uppercase character to lowercase character
6. toUpperCase()                      - convert the Lowercase character to Uppercase character
7. isWhiteSpace()                     -  check whether the character is a space, tab or newline or not
8. isSpaceChar()                       - check whether the character is a space or not


01)  isDigit() and isLetter()


class hsp{
public static void main(String args[]){
System.out.println(Character.isDigit('a'));
System.out.println(Character.isDigit('2'));
System.out.println(Character.isLetter('a'));
System.out.println(Character.isLetter('2'));
}
}


you have to use covering class to use these methds


Character.isDigit('a')
Character.isLetter('a')


output : 














02)  isLowerCase() and isUpperCase()


class hsp{
public static void main(String args[]){
System.out.println(Character.isLowerCase('a'));
System.out.println(Character.isLowerCase('A'));
System.out.println(Character.isLowerCase('2'));
System.out.println(Character.isUpperCase('a'));
System.out.println(Character.isUpperCase('A'));
System.out.println(Character.isUpperCase('2'));
}
}


Output:
















03)  toLowerCase() and toUpperCase()


class hsp{
public static void main(String args[]){
System.out.println(Character.toLowerCase('a'));
System.out.println(Character.toLowerCase('A'));
System.out.println(Character.toLowerCase('2'));
System.out.println(Character.toUpperCase('a'));
System.out.println(Character.toUpperCase('A'));
System.out.println(Character.toUpperCase('2'));
}
}


Output:
















04)  isSpaceChar()


class hsp{
public static void main(String args[]){
System.out.println(Character.isSpaceChar('a'));
System.out.println(Character.isSpaceChar('A'));
System.out.println(Character.isSpaceChar('2'));
System.out.println(Character.isSpaceChar('\t'));
System.out.println(Character.isSpaceChar(' '));
  }
}


Output:
















05)  isWhitespace()


class hsp{
public static void main(String args[]){
System.out.println(Character.isWhitespace('a'));
System.out.println(Character.isWhitespace('A'));
System.out.println(Character.isWhitespace('2'));
System.out.println(Character.isWhitespace('\t'));
System.out.println(Character.isWhitespace('\n'));
System.out.println(Character.isWhitespace(' '));
}
}


Remember the "space" word in the "isWhitespace()" keyword is lower case.


Output:



Saturday, January 29, 2011

Create a simple console calculator using shell scripts

This coding gives you a some idea about, how to use loops and if else statements and other simple things. I think this coding will be more valuable for beginners.
You can use editors that support graphical interface and you can detect your errors very easily. 
Application -> Accessories -> Text Editors
First you have to save your script using .sh extension.   
                ex :-  cal.sh
After that you can type the coding......


#This is a simple calculator


option=-1
num1=0
num2=0


echo This is my calculator
echo Availabale operations
echo -e "\tAddition\t\t - 0"
echo -e "\tSubstraction\t\t - 1"
echo -e "\tMultiplication\t\t - 2"
echo -e "\tDivition\t\t - 3"
echo -e "\tFactorial\t\t - 4"
echo -e "\tAny power of any base\t - 5"


echo -n "What is the operation that you want  -  "
read num


if [ $num -eq 0 ]
then 
        echo -n "Enter the number 1 - "
        read num1
        echo -n "Enter the number 2 - "
        read num2
        echo Answer is `expr $num1 + $num2`
else
        if [ $num -eq 1 ]
        then
                  echo -n "Enter the number 1 - "
                  read num1   
                  echo -n "Enter the number 2 - "
                  read num2
                 echo Answer is `expr $num1 - $num2
        else
                 if [ $num -eq 2 ]
                 then       
                      echo -n "Enter the number 1 - "
                         read num1
                         echo -n "Enter the number 2 - "
                         read num2
                         echo Answer is `expr $num1 \* $num2`
                 else
                    if [ $num -eq 3 ]
                    then 
                                         echo -n "Enter the number 1 - "
                                    read num1
                                    echo -n "Enter the number 2 - "
                                    read num2
                                    echo Answer is `expr $num1 \/ $num2`
                                 echo Remainder is `expr $num1 \% $num2`
                    else     
                                        if [ $num -eq 4 ]
                                then
                                            echo -n "Enter the number - "
                                            read num1
                                            answer=1
                                            while [ $num1 -gt 0 ]
                                             do
                                              answer=`expr $answer \* $num1`
                                              num1=`expr $num1 - 1`
                                            done
                                            echo "Answer is " $answer
                                else
                                   if [ $num -eq 5 ]
                                   then
                                               echo -n "Enter the Base - "
                                               read num1
                                               echo -n "Enter the power - "
                                               read num2
                                               answer=1
                                                       while [ $num2 -gt 0 ]
                                                        do
                                                          answer=`expr $answer \* $num1`
                                                          num2=`expr $num2 - 1`
                                                       done
                                                       echo "Answer is " $answer
                                    fi 
                                fi
                       fi
                 fi
         fi
fi

After finish the coding you have to execute this script. To execute you have to open the terminal first. 
Then type sh<space><script name>
          ex :- sh cal.sh
Then press Enter and see the out put

java VS .NET

How to create your own web browser using visual studio C#

1. As usually first you have to create a windows form application
2. Then change your form name and change "IsMdiContainer" property to "True"










3. Then drag and drop a web browser and a tool Strip from the web browser.




4. Then Add buttons and labels and text boxes to your tool strip.
   you can use any amount of buttons to go to your preferable sites by pressing one button.
  you  can set images and sizes to your buttons.
5.After that you have to write codings for every butoon click event (double click on the button).
  Add below codings for that events.


Next button 
webBrowser1.GoForward();


Previous button
webBrowser1.GoBack();


Go button
webBrowser1.Navigate(new Uri("http://"+toolStripTextBox1.Text));


Facebook shortcut button
webBrowser1.Navigate(new Uri("http://www.facebook.com/"));


Gmail shortcut button
webBrowser1.Navigate(new Uri("http://www.gmail.com/"));


  After all these, coding will be view like below. 
6. You can run and check your own web browser.



Wednesday, January 26, 2011

How to create a simple media player using Visual Studio C#

As usually you have to create a windows form application in visual studio
File->New->Project


Then you have to select c# windows form application and give the name and location for your project. After that press ok.


Then Right-click on the toolbox and press "choose Items". Then the following window will appear.


Press "COM component" tab.
Then put a tick on windows media player according to the following picture and press OK.


Now you can see there is tool "Windows media player" on the bottom of the toolbox.


Then drag and drop and change the size as you wish.


After that drag and drop a Menu Strip from the toolbox and give the first one as "Open".


Then Double-click on "Open".



Write a coding as it is in the following picture.



                    OpenFileDialog open = new OpenFileDialog();
                    open.Title = "Open";
                    open.Filter = "All Files|*.*";
                    try
                    {
            
                              if(open.ShowDialog()==System.Windows.Forms.DialogResult.OK)
                                                      axWindowsMediaPlayer1.URL=(open.FileName);
                    }
                    catch (Exception ex)
                    {
                             MessageBox.Show(ex.Message.ToString(),"Error", MessageBoxButtons.OK,       MessageBoxIcon.Error);                
                    }

At last run the program and watch a movie using your own media player.