Friday, June 29, 2012

Access Skype Functionality in Web Site

The Skype protocol allows users to deal with Skype related activities. The only condition is to have installed Skype  in client side. Getting a call, sending a IM, sending a voicemail and having a conference call  are still possible when the Skype username is known.

The following examples use 'echo123' demo user provided by Skype. Replace it with your friend's Skype username.

Call a Skype user

call Skype demo user

[sourcecode language="html"]
<a href="skype:echo123?call">call Skype demo user</a>
[/sourcecode]

Send a Skype IM message

Chat with Skype demo user

[sourcecode language="html"]
<a href="skype:echo123?chat">Chat with Skype demo user</a>
[/sourcecode]

Send a voicemail

Send voicemail to demo user

[sourcecode language="html"]
<a href="skype:echo123?voicemail">Send voicemail to demo user</a>
[/sourcecode]

Create a Skype conference call

conference call

[sourcecode language="html"]
<a href="skype:echo123;ANOTHER_USER?call">conference call</a>
[/sourcecode]

Thursday, June 28, 2012

How to Display Current Date in your program

Find it difficult to get the current date and time? Then read on, I this tutorial I demonstrate getting current date and time in different programming languages.

Java

Using Calendar

output: 28/6/2012

[sourcecode language="java"]
Calendar cal = new GregorianCalendar();
int month = cal.get(Calendar.MONTH);
int year = cal.get(Calendar.YEAR);
int day = cal.get(Calendar.DAY_OF_MONTH);
System.out.println("Current date : " + day + "/" + (month + 1) + "/" + year);
[/sourcecode]

Using SimpleDateFormat

output: 28/06/2012

[sourcecode language="java"]
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date date = new Date();
String sDate= sdf.format(date);
[/sourcecode]




C#
Using DateTime format

output: Jun Fri 27 11:41 2012

[sourcecode language="csharp"]
DateTime time = DateTime.Now; // Use current time
string format = "MMM ddd d HH:mm yyyy"; // Use this format
Console.WriteLine(time.ToString(format));
[/sourcecode]

Some other patterns for DateTime
MMM : display three-letter month
ddd : display three-letter day of the WEEK
d : display day of the MONTH
HH : display two-digit hours on 24-hour scale
mm : display two-digit minutes
yyyy : display four-digit year

Single-letter format

output :
6/28/2012
Thursday, June 28, 2012
Thursday, June 28, 2012 11:36 AM
Thursday, June 28, 2012 11:36:21 AM
6/28/2012 11:36 AM
6/28/2012 11:36:21 AM
June 28
June 28
2012-06-28T11:36:21.8863219+05:30
2012-06-28T11:36:21.8863219+05:30
2012-06-28T11:36:21
11:36 AM
11:36:21 AM
2012-06-28 11:36:21Z
Thursday, June 28, 2012 6:06:21 AM
June, 2012
June, 2012

[sourcecode language="csharp"]
DateTime now = DateTime.Now;
Console.WriteLine(now.ToString("d"));
Console.WriteLine(now.ToString("D"));
Console.WriteLine(now.ToString("f"));
Console.WriteLine(now.ToString("F"));
Console.WriteLine(now.ToString("g"));
Console.WriteLine(now.ToString("G"));
Console.WriteLine(now.ToString("m"));
Console.WriteLine(now.ToString("M"));
Console.WriteLine(now.ToString("o"));
Console.WriteLine(now.ToString("O"));
Console.WriteLine(now.ToString("s"));
Console.WriteLine(now.ToString("t"));
Console.WriteLine(now.ToString("T"));
Console.WriteLine(now.ToString("u"));
Console.WriteLine(now.ToString("U"));
Console.WriteLine(now.ToString("y"));
Console.WriteLine(now.ToString("Y"));
[/sourcecode]

Using Date strings to control the output

output:
Thursday, June 28, 2012
12:03:53 PM
6/28/2012
12:03 PM
6/28/2012 12:03:53 PM

[sourcecode language="csharp"]
DateTime now = DateTime.Now;
Console.WriteLine(now.ToLongDateString());
Console.WriteLine(now.ToLongTimeString());
Console.WriteLine(now.ToShortDateString());
Console.WriteLine(now.ToShortTimeString());
Console.WriteLine(now.ToString());
[/sourcecode]




PHP

output : 2012-06-28 17:33:07

[sourcecode language="php"]
$date = date('Y-m-d H:i:s');
echo $date;
[/sourcecode]

output : 2012/06/28 17:33:07

[sourcecode language="php"]
$date = date('Y/m/d H:i:s');
echo $date;
[/sourcecode]

This time is based on the default server time zone. To get the time in a different time zone it should be set first.

[sourcecode language="php"]
date_default_timezone_set('Australia/Sydney');
$date = date('Y/m/d H:i:s');
echo $date;
[/sourcecode]




JavaScript

output : Thursday, June 28, 2012

[sourcecode language="javascript"]
<script type="text/javascript"><!--
var now = new Date();
var Weekday = new Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday");
var Month = new Array("January","February","March","April","May","June","July","August","September","October","November","December");
document.write(Weekday[now.getDay()]+", "+Month[now.getMonth()]+" "+now.getDate()+", "+now.getFullYear());
//--></script>
[/sourcecode]

output : 6/28/2012

[sourcecode language="javascript"]
<script type="text/javascript"><!--
var now = new Date();
document.write((now.getMonth()+1)+"/"+now.getDate()+"/"+now.getFullYear());
//--></script>
[/sourcecode]

output : 06/28/2012
[sourcecode language="javascript"]
<script type="text/javascript"><!--
var now = new Date();
var month = now.getMonth()+1;
if( month < 9 ) { month = "0"+month; }
var day = now.getDate();
if( day < 9 ) { day = "0"+day; }
document.write(month+"/"+day+"/"+now.getFullYear());
//--></script>
[/sourcecode]




ios

[sourcecode language="objc"]
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:@"hh:mm a"];
NSString *str_date = [dateFormatter stringFromDate:[NSDate date]];
NSLog(@"str_date:%@",str_date);
[/sourcecode]

Monday, June 25, 2012

Send Location To Mobile From Your Web Site



This is a SMS widget offered by zhiing to send SMS free anywhere in the world. With zhiing, you not limited to plain text message but directions and maps are also possible. Static or dynamic widgets can be generated according to your needs. A great widget obviously.

Get the widget

Sunday, June 24, 2012

Save and Retrieve images in WPF From Database



Download Sourcecode

[sourcecode language="csharp"]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Win32;
using System.Data;
using System.IO;
using System.Data.SqlClient;
using System.Drawing.Imaging;

namespace imageDBWPF
{

public partial class MainWindow : Window
{
DataSet ds;
string imageName;

public MainWindow()
{
InitializeComponent();
}

private void insertData()
{
if (imageName == "")
{
return;
}

try
{
//Initialize a file stream to read the image file
FileStream fs = new FileStream(@imageName, FileMode.Open, FileAccess.Read);
//Initialize a byte array with size of stream
byte[] imgByteArr = new byte[fs.Length];
//Read data from the file stream and put into the byte array
fs.Read(imgByteArr, 0, Convert.ToInt32(fs.Length));
fs.Close();

//Save binary data in database
string constr = @"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\imageDB.mdf;Integrated Security=True;User Instance=True";
using (SqlConnection conn = new SqlConnection(constr))
{
conn.Open();
string sql = "insert into tbl_Image(id,img) values('" + textBox1.Text + "',@img)";
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.Add(new SqlParameter("img", imgByteArr));
int result = cmd.ExecuteNonQuery();
if (result == 1)
{
MessageBox.Show("Image Added");
refreshImageList();
}
}
}
}
catch (Exception ex)
{

MessageBox.Show(ex.Message);
}
}

private void refreshImageList()
{
try
{
string connstr = @"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\imageDB.mdf;Integrated Security=True;User Instance=True";

using (SqlConnection conn = new SqlConnection(connstr))
{
conn.Open();

using (SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM tbl_Image", conn))
{
ds = new DataSet("myDataSet");
adapter.Fill(ds);
DataTable dt = ds.Tables[0];

//Alternatively can fill data into a data table directly
//DataTable dt2 = new DataTable();
//adapter.Fill(dt2);

comboBox1.Items.Clear();

foreach (DataRow dr in dt.Rows)
{
comboBox1.Items.Add(dr["id"].ToString());
}
comboBox1.SelectedIndex = 0;

}
}

}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

private void button1_Click(object sender, RoutedEventArgs e)
{
try
{

FileDialog fldlg = new OpenFileDialog();
fldlg.InitialDirectory = Environment.SpecialFolder.MyPictures.ToString();
fldlg.Filter = "Image File (*.jpg;*.bmp;*.gif)|*.jpg;*.bmp;*.gif";
fldlg.ShowDialog();
{

imageName = fldlg.FileName;
ImageSourceConverter isc = new ImageSourceConverter();
image1.SetValue(Image.SourceProperty,isc.ConvertFromString(imageName));

}

fldlg = null;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}

private void button2_Click(object sender, RoutedEventArgs e)
{
insertData();
}

private void button3_Click(object sender, RoutedEventArgs e)
{
DataTable dataTable = ds.Tables[0];

foreach (DataRow row in dataTable.Rows)
{
if (row[0].ToString() == comboBox1.SelectedItem.ToString())
{
//Store binary data read from the database in a byte array
byte[] blob = (byte[])row[1];
MemoryStream stream = new MemoryStream();
stream.Write(blob, 0, blob.Length);
stream.Position = 0;

System.Drawing.Image img = System.Drawing.Image.FromStream(stream);
BitmapImage bi = new BitmapImage();
bi.BeginInit();

MemoryStream ms = new MemoryStream();
img.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
ms.Seek(0, SeekOrigin.Begin);
bi.StreamSource = ms;
bi.EndInit();
image2.Source = bi;

}
}
}

}
}

[/sourcecode]

Save and Retrieve images in C# from SQL Database



Download Sourcecode

[sourcecode language="csharp"]
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.IO;

namespace imageDB
{
public partial class Form1 : Form
{
DataSet ds;
string imageName;

public Form1()
{
InitializeComponent();
}

//Without using statements
/*private void insertData()
{
try
{

if (imageName != "")
{
//Initialize a file stream to read the image file
FileStream fs = new FileStream(@imageName, FileMode.Open, FileAccess.Read);
//Initialize a byte array with size of stream
byte[] imgByteArr = new byte[fs.Length];
//Read data from the file stream and put into the byte array
fs.Read(imgByteArr, 0, Convert.ToInt32(fs.Length));
fs.Close();

//Save binary data in database
string constr = @"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\imageDB.mdf;Integrated Security=True;User Instance=True";
SqlConnection conn = new SqlConnection(constr);
conn.Open();
string sql = "insert into tbl_Image(id,img) values('" + textBox1.Text + "',@img)";

SqlParameter imageParameter = new SqlParameter();
imageParameter.SqlDbType = SqlDbType.Image;
imageParameter.ParameterName = "img";
imageParameter.Value = imgByteArr;
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.Add(imageParameter);
int result = cmd.ExecuteNonQuery();
if (result == 1)
{
MessageBox.Show("Image Added");
}

cmd.Dispose();
conn.Dispose();

}
}

catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}*/

private void insertData()
{
if (imageName == "")
{
return;
}

try
{
//Initialize a file stream to read the image file
FileStream fs = new FileStream(@imageName, FileMode.Open, FileAccess.Read);
//Initialize a byte array with size of stream
byte[] imgByteArr = new byte[fs.Length];
//Read data from the file stream and put into the byte array
fs.Read(imgByteArr, 0, Convert.ToInt32(fs.Length));
fs.Close();

//Save binary data in database
string constr = @"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\imageDB.mdf;Integrated Security=True;User Instance=True";
using (SqlConnection conn = new SqlConnection(constr))
{
conn.Open();
string sql = "insert into tbl_Image(id,img) values('" + textBox1.Text + "',@img)";
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.Add(new SqlParameter("img", imgByteArr));
int result = cmd.ExecuteNonQuery();
if (result == 1)
{
MessageBox.Show("Image Added");
refreshImageList();
}
}
}
}
catch (Exception ex)
{

MessageBox.Show(ex.Message);
}
}

private void refreshImageList()
{
try
{
string connstr = @"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\imageDB.mdf;Integrated Security=True;User Instance=True";

using (SqlConnection conn = new SqlConnection(connstr))
{
conn.Open();

using (SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM tbl_Image", conn))
{
ds = new DataSet("myDataSet");
adapter.Fill(ds);
DataTable dt = ds.Tables[0];

//Alternatively can fill data into a data table directly
//DataTable dt2 = new DataTable();
//adapter.Fill(dt2);

comboBox1.Items.Clear();

foreach (DataRow dr in dt.Rows)
{
comboBox1.Items.Add(dr["id"].ToString());
}
comboBox1.SelectedIndex = 0;

//Display queried data in a grid view
dataGridView1.DataSource = dt;
}
}

}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

private void button1_Click(object sender, EventArgs e)
{
try
{

FileDialog fldlg = new OpenFileDialog();
fldlg.InitialDirectory = Environment.SpecialFolder.MyPictures.ToString();
fldlg.Filter = "Image File (*.jpg;*.bmp;*.gif)|*.jpg;*.bmp;*.gif";
if (fldlg.ShowDialog() == DialogResult.OK)
{
imageName = fldlg.FileName;
Bitmap bmp = new Bitmap(imageName);
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
pictureBox1.Image = (Image)bmp;
}

fldlg = null;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}

private void button2_Click(object sender, EventArgs e)
{
insertData();
}

private void button3_Click(object sender, EventArgs e)
{
DataTable dataTable = ds.Tables[0];
//If there is an already an image in picturebox, then delete it
if (pictureBox2.Image != null)
{
pictureBox2.Image.Dispose();
}

//Initialize a file stream to write image data
FileStream fs = new FileStream("image.jpg", FileMode.Create);

foreach (DataRow row in dataTable.Rows)
{
if (row[0].ToString() == comboBox1.SelectedItem.ToString())
{
//Store binary data read from the database in a byte array
byte[] blob = (byte[])row[1];

//Write data in image file using file stream
fs.Write(blob, 0, blob.Length);
fs.Close();
fs = null;

pictureBox2.Image = Image.FromFile("image.jpg");
pictureBox2.SizeMode = PictureBoxSizeMode.StretchImage;
pictureBox2.Refresh();

}
}
}
}

}

[/sourcecode]

Friday, June 22, 2012

Open a file with default file extension in C#

[sourcecode language="csharp"]
var fileToOpen = "PATH_TO_FILE";
var process = new Process();
process.StartInfo = new ProcessStartInfo()
{
UseShellExecute = true,
FileName = fileToOpen
};

process.Start();
process.WaitForExit();

[/sourcecode]

UseShellExecute parameter tells Windows to use the default program for the type of file.

WaitForExit will cause your application to wait until the application luanched has been closed.

c# database access class

[sourcecode language="csharp"]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;
using System.Windows.Forms;

namespace IDStore.db
{
class DBAccess
{
SqlConnection conn;
string table = "tbl_Accounts";
AutoCompleteStringCollection autoCompleteCollection = new AutoCompleteStringCollection();

public DBAccess()
{
conn = ConnectionManager.GetConnection();
}

public void Openconn()
{
if (conn.State == ConnectionState.Closed || conn.State == ConnectionState.Broken)
{
conn.Open();
}

}

public void Closeconn()
{
if (conn.State == ConnectionState.Open)
{
conn.Close();
}

}

public int ExecuteNonQuery(string query)
{
int result = 0;
conn.Open();

try
{
SqlCommand cmd = new SqlCommand();
cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = query;
result = cmd.ExecuteNonQuery();
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
return result;
}

public DataSet ExecuteQuery(string query)
{
conn.Open();
try
{
SqlDataAdapter adapter = new SqlDataAdapter(query, conn);
DataSet ds = new DataSet();
adapter.Fill(ds, "Table");
return ds;

}
finally
{
conn.Close();
}
}

public List<Account> getAllAccountsASList()
{
List<Account> list = new List<Account>();
conn.Open();

SqlCommand cmd = new SqlCommand();
cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT * FROM " + table;
SqlDataReader dr = cmd.ExecuteReader();

while (dr.Read())
{
int accountID = dr.GetInt32(0);
string type = dr.GetString(1);
string username = dr.GetString(2);
string password = dr.GetString(3);
string description = dr.GetString(4);
list.Add(new Account { AccountID = accountID, Type = type, Username = username, Password = password, Description = description });
}
return list;
}

public bool HasRows(string query)
{
conn.Open();
try
{
SqlDataReader dr;
SqlCommand cmd = new SqlCommand();
cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = query;
dr = cmd.ExecuteReader();

if (dr.HasRows)
{
return true;
}

}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}

return false;
}
}
}

[/sourcecode]

Download the complete sample project

Wednesday, June 20, 2012

Java DAO Tutorial

How to map a model object to a database table?
(Model object is a real world object such as User,Student,Place)

How to get a clean separation of data tier from the business tier ?
The ultimate target is high maintainability, reusability and many more...

I highly recommend to read this article

Tuesday, June 19, 2012

Java Database application using JavaDB – Part 2

In the first part of this tutorial, I discussed  how to work with Java DB inside Netbeans and basically how we are going to manually perform database operations. In this section I will show you the way a real java application initiates a Java DB database connection and use for data manipulation within the application.
First you should remove the database connection  if it  already has a connection.
1. Expand the Database Explorer in the Services window and find your database.
2. Have a look at your database connection node. In my case it is jdbc:derby://localhost:1527/IDDB [ on APP]
3. Check whether the node icon is displayed as broken node. Then  it's disconnected. Otherwise you need to right click on the node and select Disconnect. Obviously it is our application that should initiate this connection during its execution. (Actually it is not necessary to disconnect the connection if it's already connected. But we can understand what happens behind the scene)
4. Next you should start the Java DB server if it is not started yet. This is because Server should be able to listen for a database connection request made by applications. To start the server, right click on Java DB in the Services window. From the menu that appears, click Start Server. If your firewall needs your permission for this, you should allow the connection.
5. Then you need to add a client driver so that driver manager can make a connection with our database. This driver is sprcific to each database type
eg. mysql,Java DB
Accordingly, you are going to add the driver that supports Java DB type database.
In Projects tab right click on  Libraries and select Add JAR/Folder. In a Windoes, you can find the driver at
C:\Program Files\Sun\JavaDB\lib\derbyclient.jar
Locate this jar file and click Open. It will appear in your Libraries folder.



5. Enter the following code into your main method.

[sourcecode language="java"]
public static void main(String[] args)
{
try
{
String url = "jdbc:derby://localhost:1527/IDDB";
String username = "";
String password = "";
Connection con = DriverManager.getConnection(url ,username, password);
}
catch(SQLException ex)
{
System.out.println(ex.getMessage());
}
}
[/sourcecode]

In the above code, we have created a connection object for our database.
If everything is OK Run the project.

If you encounter following errors please go back and recheck above steps carefully.
"java.net.ConnectException : Error connecting to server localhost on port 1527 with message Connection refused: connect." >>
There 's a problem with connecting to the server.

"No suitable driver found for jdbc:derby://localhost:1527/Employees" >>
There 's a problem with adding derby driver.

6. Now you have the database connection. Threfore you can write SQL queries for manipulating data in the database.
First  we try to pull all the data from the table. It will be easier in your side to have some records in your database table.
Enter the following code.

[sourcecode language="java"]
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM TBL_ACCOUNTS");

while(rs.next())
{
int id = rs.getInt(1);
String uname = rs.getString(2);
String pw = rs.getString(3);
System.out.println(id + " " + uname + " " + pw);

}

[/sourcecode]

You should have a Statement object to run SQL queries.
In Statement class, there 's a bunch of methods such as execute(), executeQuery(), executeUpdate()
In this example we need to pull  data from the table. We need to use a SELECT query. So the preferred method is the executeQuery() which returns a resultSet object.
Now you should extract whatever you need from the ResultSet.

Here comes the Cursor concept. Cursor is a pointer to record in a table. But the idea is to identify a particular row in your table. We can control the position of the Cursor with the help of some predefined methods.



Just think the ResultSet as a table and there 's the Cursor pointing to one of its record. At first, cursor points to just before the first record when the data is loaded. The first call to next() causes the Cursoe to move the first record.  The second call moves the Cursor to second row and so on.

ResultSet class provides methods to extract the data  from each row.

In this way you can build a CRUD application which accesses Java DB as its database server. I 'll complete this tutorial series with  my next post which includes a complete CRUD application.
Happy coding!

Java Database application using JavaDB - Part 1

Java supports varoius RDBMS in the market. If you need to connect your application with database for CRUD operations, the preferred way is to use a Database Management System. File based storage mechanism is recommended for simple data management tasks.

With regard to Java, there are many RDBMS solutions such as MySQL,Oracle,PostgreSQL,Java DB,SQLite...etc. Each solution is ideal for specific scenarios. This article demonstrates how to connect your application to Java DB(previously known as Derby).

We are going to build the application with Netbeans IDE and Java DB is a in-built database within Netbeans installation package.

In Java platform, it uses an API called JDBC for database connectivity. Then, who are going to connect your application to database?.  It's JDBC Driver Manager. This is common for most of the database connection scenarios with Java.

Create new Java Application with Netbeans and  go to Services tab.
It displays all the database engines, drivers and database connections available.


Java DB is a virtual server. We need to start the server.
Right click Java DB under databases select Start Server.
To create a database, right click Java DB and select Create Database.
You can change the database location with properties.



Newly created database will be added to the list.


Now you can connect with the database and create tables.
Right click on your database and select Connect. It will display hierarchical view of Tables,Views and Procedures for your database. Perhaps this hierarchy may appear in APP category under your database.


To create a table, right click on Tables and select Create Table. This will prompt Create Table dialog. You can enter a table name, add/remove column and define indexes in this dialog.



Unfortunately, Java DB does not support to define the auto increment feature using AUTO_INCREMENT keyword for a column. We can not set this property using the IDE interface. But still possible with writing SQL query to create your table. For that we need to drop the table and write the suitable query to create a table with an auto generated field.
To minimize the troubles , let's try to reuse what we have now. Hopefully, we can save the current table structure before dropping the table. Then you open the saved binary data file and edit the structure so that our requirement will get reflected.
(BTW, Dropping  a table causes to remove all the data within the table and we  have no other solution than this as we need to change the table structure.)
Right click on your table and select Grab Structure. This will prompt you to save it in your disk.
Next simply drop the table.
Right click on Tables and select Recreate Table to open saved structure earlier.


Click on Edit table script in the dialog appeared. Now you will be able to edit your table structure to include auto generated property. So you need to add following property for the desired column to be auto generated.

GENERATED ALWAYS AS IDENTITY(START WITH 1, INCREMENT BY 1)



Ok. Now you have achived it!

Now you can play with the table by adding some data. You can also write SQL queries for data manipulation tasks. Let's move to next section of out tutorial. That 's data management task within the application. We write some code to programmatically connect with the database and handle some database operations.

Part 2

 

Thursday, June 14, 2012

Get Directions with Bing Maps using Geocordinates.

With Bing Map API, you can easily get the directions to some place. You only need to know  the start location and end location. If this start location is not specified, your current location is treated as the start.

In this tutorial we use Bing Maps Directions Task which is one of the many launchers bundled with Windows Phone7 Mango series. Hopefully, they make developer's life easy. They are really useful when integrate social sharing features to your applicaton. Otherwise you need to deal with OAth protocol for a considerable amount of time. You do not need to touch those dirty ...
Enough  pep talk. Let's get started.

You have two options to enter location details either by text based or geocordinates which are in latitude and longitude format. These two methods are demonstrated below.

Text based location

[sourcecode language="csharp"]
BingMapsDirectionsTask bmDirectionTask = new BingMapsDirectionsTask();
LabeledMapLocation start = new LabeledMapLocation("Sydney", null);
LabeledMapLocation end = new LabeledMapLocation("Perth", null);
bmDirectionTask.Start = start;
bmDirectionTask.End = end;
bmDirectionTask.Show();
[/sourcecode]

Based on geocordinates

[sourcecode language="csharp"]
BingMapsDirectionsTask bingMapsDirectionsTask = new BingMapsDirectionsTask();

GeoCoordinate userLocation = new GeoCoordinate(33.8683,151.2086);
LabeledMapLocation start = new LabeledMapLocation("From", userLocation);
bingMapsDirectionsTask.Start = start;

GeoCoordinate placeLocation = new GeoCoordinate();
LabeledMapLocation end = new LabeledMapLocation(31.9554,115.8585);
bingMapsDirectionsTask.End = end;

bingMapsDirectionsTask.Show();
[/sourcecode]

Tuesday, June 12, 2012

Customized PushPin on bing Map

This tutorial demonstrates how to create a pushpin from a specified image.



First add your image to the silverlight project.

Add the bing map control to the page.

[sourcecode language="xml"]
<my:Map x:Name="map" CredentialsProvider="YOUR_BING_MAP_API_KEY" Height="600" >
</my:Map>
[/sourcecode]

Define a control template inside the required page or inside App.xaml page. Things we declare in App.xaml are global. If you need to use bing map on several pages App.xaml is preferred. So we maintain code reusability.

For this example, I define control template in one of my inside page within PhoneApplicationPage.Resources section.

[sourcecode language="xml"]
<phone:PhoneApplicationPage.Resources>
<ControlTemplate x:Key="PushpinControlTemplate" TargetType="my:Pushpin">
<Image x:Name="pinImage" Height="64" Source="/Images/push_pin.png"/>
</ControlTemplate>
</phone:PhoneApplicationPage.Resources>
[/sourcecode]

Value of TargetType  attribute consists of your bing map control namespace which can be found in your xaml page. Here, it 's 'my'.

To display the pushpin add this code.
Here we should specify the relevant control template that we need.

[sourcecode language="csharp"]
Pushpin pin1 = new Pushpin();
pin1.Location = new GeoCoordinate(51.5171, 0.1062);
pin1.Template = (ControlTemplate)(this.Resources["PushpinControlTemplate"]);
map.Children.Add(pin1);
map.SetView(pin1.Location, 10);
[/sourcecode]

That 's it!

If you can not see the pushpin, set the Build Action of the image to Content and try.

Roundedc Corner Rectangles

[sourcecode language="xml"]
<Rectangle x:Name="rec_1" Width="100" Height="100" RadiusX="20" RadiusY="20" Fill="Blue" />
[/sourcecode]

RadiusX determines the radius of the corners on the x-axis and RadiusY determines the radius of the corners on the y-axis.

Monday, June 11, 2012

Send SMS with Windows Phone 7

[sourcecode language="csharp"]
SmsComposeTask smsComposeTask = new SmsComposeTask();
smsComposeTask.To = textBox1.Text; // Get recepient's number
smsComposeTask.Body = textBox2.Text; //Get message body
smsComposeTask.Show(); // Invoke the native sms task
[/sourcecode]



SMS Sending user interface.



After Send button is clicked it opens up the native SMS application with message & phone number filled.



Once the user clicks on Send Button on native SMS application, SMS will be sent.

Friday, June 8, 2012

Facebook OAUTH dialog with new Graph API

Demo Download

You need a PHP enabled real server to test this application.

Login to your Facebook account and add a developer application
Facebook developers
tips : App Domain should be in myDomain.com format
Canvas URL should point to a directory in your server.
eg : http://www.mysite.com/fb/

Get the application id and secret key for your application.
Now we are going to build our application.

Download facebook php sdk from github. Upload files inside 'src' directory to  your server.

You need to enter your app id and secret key in the source code when communicating with Facebook server. They help identify your application uniquely among other applications. Facebook server uses these keys whenever it receives a request  from any application for validation purposes.
From the developer's perspective, it is a good practice to keep those configuration data separate from the general application.
Therefore, create a config.php file and add these data.

config.php

[sourcecode language="php"]
<?php
require_once 'facebook.php';
$facebook = new Facebook(array(
'appId' => 'APP_ID',
'secret' => 'SECRET_KEY'
'cookie' => true,
'appBaseUrl' => 'http://apps.facebook.com/fb',
));
?>
[/sourcecode]



appBaseUrl represents the index.php file in your server where you hope to deploy your application.
In my case,  I specified my canvas URL as http://www.mysite.com/fb/
Accordingly, my Base URL should be something like http://apps.facebook.com/fb

We have included php sdk inside config.php. So no need to bother about it later. We only need to include config.php

Create index.php and add the following code.

[sourcecode language="php"]
<?php
require_once('config.php');

$user = $facebook->getUser();
$me = null;
if($user) {
try {
$me = $facebook->api('/me');
} catch (FacebookApiException $e) {
}
}
if($me) {
echo 'User is logged in and has a valid session';
//header('Location:REDIRECTION_URL');
}
else {
$loginUrl = $facebook->getLoginUrl(array('req_perms' =>
'publish_stream',));

/**Use this code for iframe application*/
//echo '<script> top.location.href="'. $loginUrl .'"; </script>';
/**Use this code for third party application*/
header('Location: '.$loginUrl);
}

$logoutUrl = $facebook->getLogoutUrl(array('next' => 'http://apps.
facebook.com/fb/',));
?>

<br>

<a href ="#" onclick="top.location.href='<?php echo $logoutUrl; ?>';
return false;">Logout</a>


[/sourcecode]

upload both config.php and index.php to the same directory where facebook php sdk resides.
Test your application.
Happy Facebooking!

Wednesday, June 6, 2012

jQuery popup dialog

[sourcecode language="html"]
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style type="text/css">
/* Mask for background, by default is not display */
#mask {
display: none;
background: #000;
position: fixed; left: 0; top: 0;
z-index: 10;
width: 100%; height: 100%;
opacity: 0.8;
z-index: 999;
}

/* You can customize to your needs  */
.login-popup{
display:none;
background: #fff;
padding: 10px;
border: 2px solid #ddd;
float: left;
font-size: 1.2em;
position: fixed;
top: 50%; left: 50%;
z-index: 99999;
box-shadow: 0px 0px 20px #999; /* CSS3 */
-moz-box-shadow: 0px 0px 20px #999; /* Firefox */
-webkit-box-shadow: 0px 0px 20px #999; /* Safari, Chrome */
border-radius:3px 3px 3px 3px;
-moz-border-radius: 3px; /* Firefox */
-webkit-border-radius: 3px; /* Safari, Chrome */
}

img.btn_close { Position the close button
float: right;

}

fieldset {
border:none;
}

form.signin .textbox label {
display:block;
padding-bottom:7px;
}

form.signin .textbox span {
display:block;
}

form.signin p, form.signin span {
color:#999;
font-size:11px;
line-height:18px;
}

form.signin .textbox input {
background:#666666;
border-bottom:1px solid #333;
border-left:1px solid #000;
border-right:1px solid #333;
border-top:1px solid #000;
color:#fff;
border-radius: 3px 3px 3px 3px;
-moz-border-radius: 3px;
-webkit-border-radius: 3px;
font:13px Arial, Helvetica, sans-serif;
padding:6px 6px 4px;
width:200px;
}

form.signin input:-moz-placeholder { color:#bbb; text-shadow:0 0 2px #000; }
form.signin input::-webkit-input-placeholder { color:#bbb; text-shadow:0 0 2px #000;  }

.button {
background: -moz-linear-gradient(center top, #f3f3f3, #dddddd);
background: -webkit-gradient(linear, left top, left bottom, from(#f3f3f3), to(#dddddd));
background:  -o-linear-gradient(top, #f3f3f3, #dddddd);
filter: progid:DXImageTransform.Microsoft.gradient(startColorStr='#f3f3f3', EndColorStr='#dddddd');
border-color:#000;
border-width:1px;
border-radius:4px 4px 4px 4px;
-moz-border-radius: 4px;
-webkit-border-radius: 4px;
color:#333;
cursor:pointer;
display:inline-block;
padding:6px 6px 4px;
margin-top:10px;
font:12px;
width:214px;
}
.button:hover { background:#ddd; }
</style>

<script type="text/javascript" src="public/js/jquery-1.7.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('a.login-window').click(function() {

//Getting the variable's value from a link
var loginBox = $(this).attr('href');

//Fade in the Popup
$(loginBox).fadeIn(300);

//Set the center alignment padding + border see css style
var popMargTop = ($(loginBox).height() + 24) / 2;
var popMargLeft = ($(loginBox).width() + 24) / 2;

$(loginBox).css({
'margin-top' : -popMargTop,
'margin-left' : -popMargLeft
});

// Add the mask to body
$('body').append('<div id="mask"></div>');
$('#mask').fadeIn(300);

return false;
});

// When clicking on the button close or the mask layer the popup closed
$('a.close, #mask').live('click', function() {
$('#mask , .login-popup').fadeOut(300 , function() {
$('#mask').remove();
});
return false;
});
});
</script>
</head>

<body>
<a href="#login-box">Login / Sign In</a>
<div id="login-box">
<a href="#"><img src="public/img/cross.png" title="Close Window" alt="Close" /></a>
<form method="post" action="#">
<fieldset>
<label>
<span>Username</span>
<input id="username" name="username" value="" type="text" autocomplete="on" placeholder="Username">
</label>
<label>
<span>Password</span>
<input id="password" name="password" value="" type="password" placeholder="Password">
</label>
<button type="button">Sign in</button>
<p>
<a href="#">Forgot your password?</a>
</p>
</fieldset>
</form>
</div>
</body>
</html>


[/sourcecode]

PHP File Upload Class

uploader.php

[sourcecode language="php"]


class Uploader
{
private $destinationPath;
private $errorMessage;
private $extensions;
private $maxSize;
private $uploadName;
private $seqnence;
private $renamedState = 0;

public function setDir($path)
{
$this->destinationPath = $path;
}

public function setMaxSize($sizeMB)
{
$this->maxSize = $sizeMB * (1024*1024);
}

public function setExtensions($options)
{
$this->extensions = $options;
}

public function getExtension($string)
{
$ext = "";
try
{
$parts = explode(".",$string);
$ext = strtolower($parts[count($parts)-1]);
}
catch(Exception $c)
{
$ext = "";
}
return $ext;
}

public function setMessage($message)
{
$this->errorMessage = $message;
}

public function getMessage()
{
return $this->errorMessage;
}

public function getUploadName()
{
return $this->uploadName;
}

public function setSequence($seq)
{
$this->imageSeq = $seq;
}

public function getRandom()
{
return strtotime(date('Y-m-d H:iConfused')).rand(1111,9999).rand(11,99).rand(111,999);
}

public function getRenamedState()
{
return $this->renamedState;
}

public function renameFile($state,$newName)
{
$this->renamedState = $state;
$this->uploadName = $newName;
}

public function deleteUploaded()
{
unlink($this->destinationPath.$this->uploadName);
}

public function uploadFile($fileBrowse)
{
$result = false;
$size = $_FILES[$fileBrowse]["size"];
$name = $_FILES[$fileBrowse]["name"];
$ext = $this->getExtension($name);
if(!is_dir($this->destinationPath))
{
$this->setMessage("Destination folder is not a directory ");
}
else if(!is_writable($this->destinationPath))
{
$this->setMessage("Destination is not writable !");
}
else if(empty($name))
{
$this->setMessage("File not selected ");
}
else if($size>$this->maxSize)
{
$this->setMessage("Too large file !");
}
else if(in_array($ext,$this->extensions))
{
switch ($this->getRenamedState())
{
case 0: //Keep original file name
$this->uploadName= $name;
break;
case 1: //Rename file with randomly-generated name
$this->uploadName = $this->imageSeq."-".substr(md5(rand(1111,9999)),0,8).$this->getRandom().rand(1111,1000).rand(99,9999).".".$ext;
break;
case 2: //Rename file with given name when calling renameFile() function
$this->uploadName.= ".".$ext;
break;
default:
$this->uploadName= $name;
}


if(move_uploaded_file($_FILES[$fileBrowse]["tmp_name"],$this->destinationPath.$this->uploadName))
{
$result = true;
}
else
{
$this->setMessage("Upload failed");
}
}
else
{
$this->setMessage("Invalid file format!");
}
return $result;
}

}




[/sourcecode]

How to use this uploader class

[sourcecode language="php"]
<?php
if(isset($_POST['btnSub']))
{
require_once('uploader.php');
$uploader = new Uploader();
$uploader->setDir('public/img');
$uploader->setExtensions(array('jpg','jpeg','png','gif')); //allowed extensions list
$uploader->setMaxSize(.5); //set max file size to be allowed in MB

//Select one of the following alternatives
//$uploader->renameFile(0,""); //Keep original file name
//$uploader->renameFile(1,""); //Rename file with randomly-generated name
//$uploader->renameFile(2,"sample"); // Rename file with 'sample'

if($uploader->uploadFile('txtFile'))//specify file field
{
$image = $uploader->getUploadName(); //get uploaded file name
}
else
{
echo $uploader->getMessage(); //get upload error message
}

}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>File Upload Example</title>
</head>

<body>
<form action="" method="post" enctype="multipart/form-data">
<input name="txtFile" type="file" />
<input name="btnSub" type="submit" />
</form>
</body>
</html>
[/sourcecode]

Sunday, June 3, 2012

Share a link with social networks

Share a link with Facebook

[sourcecode language="html"]
<a name="fb_share" type="icon" share_url="http://codezone4.wordpress.com"></a>
<script src="http://static.ak.fbcdn.net/connect.php/js/FB.Share" type="text/javascript">
</script>
[/sourcecode]

Share a link with Twitter

[sourcecode language="html"]
<a href="http://twitter.com/share?text=An Awesome Link&url=http://codezone4.wordpress.com">
Share This on Twitter</a>
[/sourcecode]

How to enable CORS in Laravel 5

https://www.youtube.com/watch?v=PozYTvmgcVE 1. Add middleware php artisan make:middleware Cors return $next($request) ->header('Acces...