31 Ocak 2012 Salı

Encode / Decode HTML Entities

Encode / Decode HTML Entities

Blog'da html paylaşmak istediğinizde kodunuzu bu linkten rahatlıkla encode ve decode edebilirsiniz.
Mesela bir html kod parçaçığı ekleyeceğinizde kodunuzu öncelikle bu linkteki alana yapıştırın,
encode edin ve sonucu tekrar ordan kopyalıyıp blog postunuza yapıştırabilirsiniz.

Java - System Tray Kullanımı

Java programınızın iconunu notification area ya eklemek için örnek program:

Referans






bulb.gif




import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.net.URL;
import javax.swing.*;

public class TrayIconDemo {
public static void main(String[] args) {
/* Use an appropriate Look and Feel */
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
//UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
} catch (UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
} catch (IllegalAccessException ex) {
ex.printStackTrace();
} catch (InstantiationException ex) {
ex.printStackTrace();
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
}
/* Turn off metal's use of bold fonts */
UIManager.put("swing.boldMetal", Boolean.FALSE);
//Schedule a job for the event-dispatching thread:
//adding TrayIcon.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}

public static void createAndShowGUI() {
//Check the SystemTray support
if (!SystemTray.isSupported()) {
System.out.println("SystemTray is not supported");
return;
}
final PopupMenu popup = new PopupMenu();

System.out.println(new File("bulb.gif").exists());

Image img = new ImageIcon("bulb.gif").getImage();
final TrayIcon trayIcon =
new TrayIcon(img);

trayIcon.setImageAutoSize(true);
final SystemTray tray = SystemTray.getSystemTray();

// Create a popup menu components
MenuItem aboutItem = new MenuItem("About");
CheckboxMenuItem cb1 = new CheckboxMenuItem("Set auto size");
CheckboxMenuItem cb2 = new CheckboxMenuItem("Set tooltip");
Menu displayMenu = new Menu("Display");
MenuItem errorItem = new MenuItem("Error");
MenuItem warningItem = new MenuItem("Warning");
MenuItem infoItem = new MenuItem("Info");
MenuItem noneItem = new MenuItem("None");
MenuItem exitItem = new MenuItem("Exit");

System.out.println("oldu");

//Add components to popup menu
popup.add(aboutItem);
popup.addSeparator();
popup.add(cb1);
popup.add(cb2);
popup.addSeparator();
popup.add(displayMenu);
displayMenu.add(errorItem);
displayMenu.add(warningItem);
displayMenu.add(infoItem);
displayMenu.add(noneItem);
popup.add(exitItem);

trayIcon.setPopupMenu(popup);

try {
tray.add(trayIcon);
} catch (AWTException e) {
System.out.println("TrayIcon could not be added.");
return;
}

trayIcon.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null,
"This dialog box is run from System Tray");
}
});

aboutItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null,
"This dialog box is run from the About menu item");
}
});

cb1.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
int cb1Id = e.getStateChange();
if (cb1Id == ItemEvent.SELECTED){
trayIcon.setImageAutoSize(true);
} else {
trayIcon.setImageAutoSize(false);
}
}
});

cb2.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
int cb2Id = e.getStateChange();
if (cb2Id == ItemEvent.SELECTED){
trayIcon.setToolTip("Sun TrayIcon");
} else {
trayIcon.setToolTip(null);
}
}
});

ActionListener listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
MenuItem item = (MenuItem)e.getSource();
//TrayIcon.MessageType type = null;
System.out.println(item.getLabel());
if ("Error".equals(item.getLabel())) {
//type = TrayIcon.MessageType.ERROR;
trayIcon.displayMessage("Sun TrayIcon Demo",
"This is an error message", TrayIcon.MessageType.ERROR);

} else if ("Warning".equals(item.getLabel())) {
//type = TrayIcon.MessageType.WARNING;
trayIcon.displayMessage("Sun TrayIcon Demo",
"This is a warning message", TrayIcon.MessageType.WARNING);

} else if ("Info".equals(item.getLabel())) {
//type = TrayIcon.MessageType.INFO;
trayIcon.displayMessage("Sun TrayIcon Demo",
"This is an info message", TrayIcon.MessageType.INFO);

} else if ("None".equals(item.getLabel())) {
//type = TrayIcon.MessageType.NONE;
trayIcon.displayMessage("Sun TrayIcon Demo",
"This is an ordinary message", TrayIcon.MessageType.NONE);
}
}
};

errorItem.addActionListener(listener);
warningItem.addActionListener(listener);
infoItem.addActionListener(listener);
noneItem.addActionListener(listener);

exitItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
tray.remove(trayIcon);
System.exit(0);
}
});
}

//Obtain the image URL
protected static Image createImage(String path, String description) {

URL imageURL = TrayIconDemo.class.getResource(path);

if (imageURL == null) {
System.err.println("Resource not found: " + path);
return null;
} else {
return (new ImageIcon(imageURL, description)).getImage();
}
}
}


30 Ocak 2012 Pazartesi

C - TCP Server

#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <memory.h>

///--------------------------------------------------------
///
int main(int argc, char* argv[]){
int serverSock;
struct sockaddr_in me;
int ret;
int optVal;

//
// Create a TCP/IP stream socket to "listen" to connections
//
serverSock = socket(AF_INET, // Address family
SOCK_STREAM, // Socket type (TCP)
IPPROTO_TCP); // Protocol
if (serverSock < 0){
printf("Unable to create the socket\n");
return 0;
} //end-if


optVal = 1;
ret = setsockopt(serverSock, SOL_SOCKET, SO_REUSEADDR, &optVal, sizeof(optVal));
if (ret < 0) printf("setsockopt failed\n");

// Initialize my and peer's address structures.
me.sin_family = AF_INET;
me.sin_addr.s_addr = htonl(INADDR_ANY);
me.sin_port = htons(20000); // TCP port 20000

//
// bind the name to the socket
//
ret = bind(serverSock, // Socket
(struct sockaddr *)&me, // Our address
sizeof(me)); // Size of address structure
if (ret < 0){
printf("Bind failed.\n");
close(serverSock);
return 0;
} //end-if


// Start listening for a connection
ret = listen(serverSock, 10); // Connection request queue
if (ret < 0){
printf("listen failed\n");
close(serverSock);
return 0;
} //end-if

while (1){
struct sockaddr_in clientAddr;
int addrLength = sizeof(clientAddr);
unsigned char *p = (unsigned char *)&clientAddr.sin_addr;
int clientSock;

printf("Server is ready and waiting for connections at port %d\n", 20000);

//
// Wait for an incoming request
//
clientSock = accept(serverSock, // Listening socket
(struct sockaddr *)&clientAddr, // Optional client address
&addrLength);
if (clientSock < 0){
close(serverSock);
return 0;
} //end-if

printf("Accepted a connection..");
printf("clientIPAddr: %d.%d.%d.%d:%d\n", p[0], p[1], p[2], p[3], ntohs(clientAddr.sin_port));

char buffer[100000];
while (1){
ret = recv(clientSock, buffer, 100000, 0);
if (ret <= 0) break;

printf("Received %d bytes from the client\n", ret);
} //end-while

printf("Client closed connection.\n");
close(clientSock);
} //end-while

close(serverSock);
return 0;
} //end-main

C - TCP Client


#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <memory.h>

///-----------------------------------
/// Main function: Program entry point
///
int main(int argc, char* argv[]){
int clientSock; // Client socket
char destIP[100];

// 1. Create a socket
clientSock = socket(AF_INET, // Address family
SOCK_STREAM, // Socket type
IPPROTO_TCP); // Protocol
if (clientSock < 0){
printf("Unable to create the socket\n");
return 0;
} //end-if

printf("Enter TCP server's IP address: ");
gets(destIP);

// Initialize server's IP + port and connect to the server
struct sockaddr_in serverAddr;
serverAddr.sin_family = AF_INET;
serverAddr.sin_addr.s_addr = inet_addr(destIP);
serverAddr.sin_port = htons(20000); // Port: 20000

// Connect to the server
if (connect(clientSock, (struct sockaddr *)&serverAddr, sizeof(serverAddr)) < 0){
perror("connect");
close(clientSock);
return -1;

} else
printf("Connected to the server...\n");

while (1){
char buffer[100000];
int msgSize;
int ret;

memset(buffer, 'A', 100000);
printf("Enter MsgSize [-1 to quit]>>");
scanf("%d", &msgSize);
if (msgSize > 100000) msgSize = 100000;
if (msgSize < 0) break;

ret = send(clientSock, buffer, msgSize, 0);
if (ret < 0) printf("send failed. Connection closed!\n");
} //end-while

close(clientSock);
return 0;
} //end-main

29 Ocak 2012 Pazar

.NET Ajax Update Progress



ajax-loader.gif

<style type="text/css">
.overlay
{
position: fixed;
z-index: 98;
top: 0px;
left: 0px;
right: 0px;
bottom: 0px;
background-color:ButtonHighlight;
filter: alpha(opacity=80);
opacity: 0.8;
}
.overlayContent
{
z-index: 99;
margin: 250px auto;
width: 80px;
height: 80px;
}
.overlayContent h2
{
font-size: 18px;
font-weight: bold;
color: #000;
}
.overlayContent img
{
width: 80px;
height: 80px;
}
</style>
<form id="form2" runat="server">
<asp:UpdatePanel ID="UpdatePanel2" runat="server">
<ContentTemplate>
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
****içeriği istediğiniz gibi doldurabilirsiniz*****
</ContentTemplate>
</asp:UpdatePanel>
<div style="height: 73px">
<asp:UpdateProgress ID="UpdateProgress2" runat="server" DisplayAfter="0" AssociatedUpdatePanelID="UpdatePanel2">
<ProgressTemplate>
<div class="overlay" />
<div class="overlayContent">
<h2>Searching...</h2>
<img src="ajax-loader.gif" alt="Loading" />
</div>
</div>
</ProgressTemplate>
</asp:UpdateProgress>
</div>
</form>

SQL Azure Connection

private static string userName = "bahar";
private static string password = "12341234";
private static string dataSource = "i7x8ktgn28.database.windows.net";
private static string sampleDatabaseName = "ATSDB";

SqlConnectionStringBuilder cs;
cs = new SqlConnectionStringBuilder();
cs.DataSource = dataSource;
cs.InitialCatalog = sampleDatabaseName;
cs.Encrypt = true;
cs.TrustServerCertificate = false;
cs.UserID = userName;
cs.Password = password;


// Connect to the database and perform various operations
using (SqlConnection conn = new SqlConnection(cs.ToString()))
{
using (SqlCommand cmd = conn.CreateCommand())
{
conn.Open();

// Query the table
cmd.CommandText = "insert into Bus (TID, Firm, FromCity, ToCity, DepartureTime, Duration, Price) VALUES ('" + tid + "','" + listBus[i].firmName + "','" + startUtf + "','" + destinationUtf + "','" + listBus[i].time + "','" + listBus[i].duration + "'," + listBus[i].price + ")";
cmd.ExecuteNonQuery();

conn.Close();

}
}

27 Ocak 2012 Cuma

.NET Google Maps API

1. dll ini references a eklemek lazım öncelikle.
bu linkten indirebilirsiniz :
Google Maps
2. Toolbox' da sağ tıklayıp Add Tab diyoruz.
3. Yarattığımız tab a sağ tıklayıp Choose Items diyoruz.
4. Browse diyip indirdiğimiz dll i seçiyoruz.
5. Google maps toolları toolbox a eklenmiş oluyor. Sürükleyip bırakarak sayfaya ekleyebiliriz artık :)


Sayfamıza bir GMap objesi ekledikten sonra:

1. Enini ve boyunu ayarlamak için default.aspx.cd de:

GMap1.Height = 400;
GMap1.Width = 900;

2. Merkezini (haritanın odak noktası) şu şekilde değiştiriyoruz:
Bu Türkiye'nin yaklaşık ortasını merkez alıyor.
6 ise haritanın zoom unu belirtiyor. (Haritayı ne kadar yakın göstereceğini)

GMap1.setCenter(new GLatLng(38.918689, 34.801743), 6);




3. Overview map control eklemek için:
GMap1.addControl(new GControl(GControl.preBuilt.GOverviewMapControl));



4. Large Map Control 3D eklemek için:
GMap1.addControl(new GControl(GControl.preBuilt.LargeMapControl3D));

Eklemek istediğiniz controlleri (Map search mesela) bu şekilde addControl methodu ile ekleyebilrisiniz.
5. Map üzerinde iki nokta arasında çizği çizmek için:
List points = new List();
GLatLng g1 = new GLatLng(s1, s2); //s1, s2 birinci noktanın enlem-boylam değerleri
GLatLng g2 = new GLatLng(d1, d2); //d1, d2 ikinci noktanın enlem-boylam değerleri
points.Add(g1);
points.Add(g2);
var polyline = new GPolyline(points, color, 5);
polyline.clickable = true;
GMap1.addPolyline(polyline);



6. Bilgi penceresi eklemek için de :
GMarker marker = new GMarker(g1); //g1 notun ekleneceği nokta
//start: şehrin adı veya ne yazmak istiyosanız
GInfoWindow window = new GInfoWindow(marker, "
" + start + "
", true);
GMap1.addInfoWindow(window);




26 Ocak 2012 Perşembe

.NET Excel Dosyayı Okuma

Microsoft.Office.Interop.Excel dll ini eklemeniz lazım.
Bu linkten indirebilirsiniz:

Microsoft.Office.Interop.Excel

private static Microsoft.Office.Interop.Excel.Application excelNesnesi = new Microsoft.Office.Interop.Excel.Application();
static object type = Type.Missing;
//relative path for the excel file in the project directory
static string directory = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
static string pathMesafe = System.IO.Path.Combine(directory, "ilmesafe.xls");
Workbook theWorkbook = excelNesnesi.Workbooks.Open(pathMesafe, type, type, type, type, type, type,type, type, type, type, type, type, type, type);
//sayfaları al
Sheets sheets = theWorkbook.Worksheets;
//bu örnekte tek bir sayfa olduğu için get_Item(1) dedim
Worksheet worksheet =(Microsoft.Office.Interop.Excel.Worksheet)sheets.get_Item(1);
//bir aralık belirtiyoruz A'dan CE'e kadar, c1 bir integer mesela: Range(A1, CE1)
Range rangeCity = worksheet.get_Range("A" + (c1 + 1).ToString(), "CE" + (c1 + 1).ToString());
//bu range deki değerleri bir arraye atıyoruz
System.Array myvalues = (System.Array)rangeCity.Cells.Value2;
//bu array dende hangi hücreyi istiyosak alıyoruz c2: integer
string value = myvalues.GetValue(1, c2 + 2).ToString();

Yapay Zeka - Greedy Best-First Search ve A* algoritmasıyla Türkiye Şehirler Arası Mesafe Hesabı

Eskişehir'den Aksaray'a path sorguluyoruz.

hesapla dediğimizde ilk olarak Greedy Best-First Search yapıyor.
Eskişehir - Konya - Aksaray mesafe : 486 km


Sonra A* Search yapıyor. Eskişehir - Ankara - Aksaray mesafe : 458 km

Son olarak da bu ikisini karşılaştırıp best path i şeçiyor.Bu örnekte ise A* search ün (458 km) seçiyor. Faydalı linkler:

Best-first_search
A*_search_algorithm
iller arası mesafe


Download Code

19 Ocak 2012 Perşembe

ATSearch

Yazılım mühendisliği dersi kapsamında geliştirdiğimiz projemizin final sunumunu 16 sında pazartesi günü atlattık. Projenin gelişim sürecinde yardımlarından ve desteğinden dolayı canım arkadaşım Ebru Göktürk'e çok teşekkür ederim. İkimiz projeyi sırtlandık ve başarılı bir şekilde sonuca ulaştırdık. :)

Türkiyedeki ulaşımları birleştirmeyi ve aktarma noktalarını kullanıcıya sunuyor. Otobüs, uçak, tren bunların hepsine tek bir noktadan sorgulama imkanı ve aktarma noktalarını da kullanıcıya sunuyor. Keyfine göre birini seçmek ve biletini almak da kullanıcıya kalıyor :)

11 Ocak 2012 Çarşamba

Windows Azure Trial Accunt

Eğer azure trial account kullanıyorsanız dikkat edin, 3 ay sonunda tüm verileriniz sql azure daki database leriniz dahil hepsi siliniyor ve geri getirmenin bir yolu yok. Benim başıma geldi. Haftaya proje sunumumuz var ve tüm veri tabanını tekrardan oluşturmak zorunda kaldık :(