26 Kasım 2009 Perşembe

Timer Task in Asp.net

http://nayyeri.net/how-to-build-a-task-scheduler-system-for-the-asp-net-part-1


using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Timers;
using System.Threading;
using System.IO;

namespace TaskSchedulerSample
{
public class Task
{
#region Fields

System.Timers.Timer timer = null;

#endregion

#region Properties

public string Name { get; set; }

public bool IsRunning { get; set; }

public DateTime LastRunTime { get; set; }

public bool IsLastRunSuccessful { get; set; }

public double Interval { get; set; }

public bool Stopped { get; set; }

public string FilePath { get; set; }

#endregion

#region Public Constructors

public Task(double interval)
{
this.Interval = interval;
Initialize();
}

#endregion

#region Public Methods

public void Start()
{
this.Stopped = false;
this.StartTask();
}

public void Stop()
{
this.Stopped = true;
}

#endregion

#region Private Methods

private void Initialize()
{
this.Stopped = false;

timer = new System.Timers.Timer(this.Interval);
timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
timer.Enabled = true;
}

private void StartTask()
{
if (!this.Stopped)
{
Thread thread = new Thread(new ThreadStart(Execute));
thread.Start();
}
}

private void Execute()
{
try
{
this.IsRunning = true;

this.LastRunTime = DateTime.Now;

File.AppendAllText(this.FilePath, DateTime.UtcNow.ToString() + "\n");

this.IsLastRunSuccessful = true;
}
catch
{
this.IsLastRunSuccessful = false;
// Handle the exception
}
finally
{
this.IsRunning = false;
}
}

void timer_Elapsed(object sender, ElapsedEventArgs e)
{
if (!this.IsRunning)
StartTask();
}

#endregion
}
}

25 Ekim 2009 Pazar

J2ME beklemeo moduna alma

// bekleme modu
long endTime=System. currentTimeMilli s ()+3000;

while(System. currentTimeMilli s () < endTime){

}
switchDisplayabl e(null, getGirisForm());

5 Ekim 2009 Pazartesi

Programming tips

sign = ( number < 0 ) ? -1 : (( number == 0 ) ? 0 : 1);


-------------------------------------------------------------

a=a*b;

b=a/b;

a=a/b;

--------------------------------------------------------

1 Ekim 2009 Perşembe

Thread in J2ME

if(cmd==cmd_Topla){
try {

final String sonuc = null;


Thread t=new Thread(){
public void run(){

item1.setText(WebServiceClient.Topla(10, 20));
}
};
t.start();


} catch (Exception ex) {
ex.printStackTrace();
item1.setText("HATA");

}

}

30 Eylül 2009 Çarşamba

CBS bilgisin elde etme

Problem

How to capture the Cell Info, which is displayed on the home screen of most of the GSM phones, if you set the Cell Info Display: ON in your phone settings. Cell info provides some (area)location related text info about the cell tower our device is present at the moment, along with some service providers advertisements. We don't have direct API in Java ME to capture this Cell Info from our application.
Solution

This Cell info is broadcasted as CBS (Cell Broadcast Service) message by the cell towers and received by all the GSM phones connected to this tower on certain predefined Channel (generally 050) by most of the service providers. Thus our Java ME application can listen to this CBS Channel using Push Registry and capture this information
Sample Code
Imports

import javax.wireless.messaging.*;
import javax.microedition.io.PushRegistry;

setupListening

Register your Midlet for Listening to CBS port 50 and setup a Message Listener

public void setupListening()
{
try{
PushRegistry.registerConnection("cbs://:50",this.getClass().getName(),"*");
}catch(Exception e){}
String[] connList;
connList = PushRegistry.listConnections(true);
if((connList == null) || (connList.length == 0))
{
// You can exit the app, if you want
}
else
{
try{
msgconn = (MessageConnection)Connector.open("cbs://:50");
msgconn.setMessageListener(this);
} catch( IOException e){ e.printStackTrace();}
}
}

notifyIncomingMessage

To Retrieve the CBS message payload.

public void notifyIncomingMessage(MessageConnection conn)
{
try{
txtmsg =(TextMessage)msgconn.receive();
}catch(Exception e){System.out.println(e);}
from = txtmsg.getAddress());
Msg = txtmsg.getPayloadText();
// Display from & Msg
}

Note

WMA 120/205 does not support CBS on most of the Nokia S40 devices, it works on Nokia S60 and other devices.

--Submitted by Amitabh Srivastava at 16:10(IST), 27 August 2009.

28 Eylül 2009 Pazartesi

Blackberry Applications

Web servis:

http://craigagreen.com/index.php?/Blog/blackberry-and-net-web-service-tutorial-part-2.html

GPS:

http://www.riccomini.name/Topics/Mobile/BlackBerry/BlackBerryGPS/

Sample Codes:

http://www.blackberry.com/knowledgecenterpublic/livelink.exe?func=ll&objId=800332&objAction=browse&sort=name

23 Eylül 2009 Çarşamba

hacking

http://www.cmswire.com/cms/web-cms/how-they-hack-your-website-overview-of-common-techniques-002339.php


Copy and paste these into Google:

inurl:passlist.txt
inurl:passwd.txt
…and this one is just priceless…
“login: *” “password= *” filetype:xls

//---------------------------------------------------------

bu sihirli kodları googleda bir aratın ve neler varmış bir görün.hackın en basit yolu budur.
intitle: private, protected, secret, secure, winnt
intitle:"DocuShare" inurl:"docushare/dsweb/" -faq -gov -edu
"#mysql dump" filetype:sql
"#mysql dump" filetype:sql faaaaeafc
"allow_call_time_pass_reference" "PATH_INFO"
"Certificate Practice Statement" inurlPDF | DOC)

LeapFTP intitle:"index.of./" sites.ini modified
master.passwd
mysql history files
NickServ registration passwords
passlist
passlist.txt (a better way)
passwd
passwd / etc (reliable)
people.lst
psyBNC config files
pwd.db
signin filetype:url
spwd.db / passwd
trillian.ini
wwwboard WebAdmin inurlasswd.txt wwwboard|webadmin

"# -FrontPage-" extwd inurlservice | authors | administrators | users) "# -FrontPage-"
inurl:service.pwd
"AutoCreate=TRUE password=*"
"http://*:*@www" domainname
"index of/" "ws_ftp.ini" "parent directory"
"liveice configuration file" ext:cfg -site:sourceforge.net
"powered by ducalendar" -site:duware.com
"Powered by Duclassified" -site:duware.com
"Powered by Duclassified" -site:duware.com "DUware All Rights reserved"
"powered by duclassmate" -site:duware.com
"Powered by Dudirectory" -site:duware.com
"powered by dudownload" -site:duware.com
"Powered By Elite Forum Version *.*"
"Powered by Link Department"
"sets mode: +k"
"Powered by DUpaypal" -site:duware.com
allinurl: admin mdb
auth_user_file.txt
config.php
eggdrop filetype:user user
etc (index.of)
ext:ini eudora.ini
ext:ini Version=... password
ext:txt inurl:unattend.txt
filetype:bak inurl:"htaccess|passwd|shadow|htusers"
filetype:cfg mrtg "target " -sample -cvs -example
filetype:cfm "cfapplication name" password
filetypef oekakibbs
filetypef sc_serv.conf
filetypef slapd.conf
filetypefig config intext:appSettings "User ID"
filetype:dat "password.dat"
filetype:dat wand.dat
filetype:inc dbconn
filetype:inc intext:mysql_connect
filetype:inc mysql_connect OR mysql_pconnect
filetype:inf sysprep
filetype:ini inurl:"serv-u.ini"
filetype:ini inurl:flashFXP.ini
filetype:ini ServUDaemon
filetype:ini wcx_ftp
filetype:ini ws_ftp pwd
filetype:ldb admin
filetype:log "See `ipsec copyright"
filetype:log inurl:"password.log"
filetype:mdb inurl:users.mdb
filetype:mdb wwforum
filetype:netrc password
filetypeass pass intext:userid
filetypeem intextrivate
filetyperoperties inurl:db intextassword
filetypewd service
filetypewl pwl
filetype:reg reg +intext:"defaultusername" +intext:"defaultpassword"
filetype:reg reg HKEY_CURRENT_USER SSHHOSTKEYS
filetype:sql ("values * MD" | "values * password" | "values * encrypt")
filetype:sql ("passwd values" | "password values" | "pass values" )
filetype:sql +"IDENTIFIED BY" -cvs
filetype:sql password
filetype:url +inurl:"ftp://" +inurl:";@"
filetype:xls username password email
htpasswd
htpasswd / htgroup
htpasswd / htpasswd.bak
intext:"enable secret $"
intext:"powered by Web Wiz Journal"
intitle:"index of" intextnect.inc
intitle:"index of" intext:globals.inc
intitle:"Index of" passwords modified
intitle:dupics inurladd.asp | default.asp | view.asp | voting.asp) -site:duware.com
intitle:index.of administrators.pwd
intitle:Index.of etc shadow
intitle:index.of intext:"secring.skr"|"secring.pgp"|"secring.bak"
inurl:"GRC.DAT" intext:"password"
inurl:"slapd.conf" intext:"credentials" -manpage -"Manual Page" -man: -sample
inurl:"slapd.conf" intext:"rootpw" -manpage -"Manual Page" -man: -sample
inurl:"wvdial.conf" intext:"password"
inurl:/db/main.mdb
inurl:/wwwboard
inurl:ccbill filetype:log
inurl:chap-secrets -cvs
inurlfig.php dbuname dbpass
inurl:filezilla.xml -cvs
inurl:lilo.conf filetypef password -tatercounter -bootpwd -man
inurl:nuke filetype:sql
inurl:ospfd.conf intextassword -sample -test -tutorial -download
inurlap-secrets -cvs
inurlerform filetype:ini
inurl:secring ext:skr | extgp | ext:bak
inurl:vtund.conf intextass -cvs
inurl:zebra.conf intextassword -sample -test -tutorial -download

"Generated by phpSystem"
"generated by wwwstat"
"Host Vulnerability Summary Report"
"HTTP_FROM=googlebot" googlebot.com "Server_Software="
"Index of" / "chat/logs"
"Installed Objects Scanner" inurl:default.asp
"Mecury Version" "Infastructure Group"
"Microsoft ® Windows * ™ Version * DrWtsn Copyright ©" ext:log
"Most Submitted Forms and Scripts" "this section"
"Network Vulnerability Assessment Report"
"not for distribution" confidential
"phone * * *" "address *" "e-mail" intitle:"curriculum vitae"
"phpMyAdmin" "running on" inurl:"main.php"
"produced by getstats"
"Request Details" "Control Tree" "Server Variables"
"robots.txt" "Disallow:" filetype:txt
"Running in Child mode"
"sets mode: +p"
"sets mode: +s"
"Thank you for your order" +receipt
"This is a Shareaza Node"
"This report was generated by WebLog"
( filetype:mail | filetype:eml | filetype:mbox | filetype:mbx ) intextassword|subject
(inurl:"robot.txt" | inurl:"robots.txt" ) intext:disallow filetype:txt
+":" +":" +":" filetype:txt
+"HSTSNR" -"netop.com"
-sitehp.net -"The PHP Group" inurl:source inurl:url extHp
FBR "ADOBE PHOTOSHOP"
AIM buddy lists
allinurl:/examples/jsp/snp/snoop.jsp
allinurl:servlet/SnoopServlet
cgiirc.conf
cgiirc.conf
data filetype:mdb -site:gov -site:mil
exported email addresses
ext:asp inurlathto.asp
ext:cgi inurl:editcgi.cgi inurl:file=
extf inurl:rsyncd.conf -cvs -man
extf NoCatAuth -cvs
ext:dat bpk.dat
ext:gho gho
ext:ini intext:env.ini
ext:ldif ldif
ext:log "Software: Microsoft Internet Information Services *.*"
ext:mdb inurl:*.mdb inurl:fpdb shop.mdb
ext:nsf nsf -gov -mil
extqi pqi -database
ext:reg "username=*" putty
ext:txt "Final encryption key"
ext:txt inurl:dxdiag
ext:vmdk vmdk
ext:vmx vmx
filetype:asp DBQ=" * Server.MapPath("*.mdb")
filetype:bkf bkf
filetype:blt "buddylist"
filetype:blt blt +intext:screenname
filetype:cfg auto_inst.cfg
filetype:cnf inurl:_vti_pvt access.cnf
filetypef inurl:firewall -intitle:cvs
filetypefig web.config -CVS
filetype:ctt Contact
filetype:ctt ctt messenger
filetype:eml eml +intext:"Subject" +intext:"From" +intext:"To"
filetype:fp fp
filetype:fp fp -site:gov -site:mil -"cvs log"
filetype:fp fp
filetype:inf inurl:capolicy.inf
filetype:lic lic intext:key
filetype:log access.log -CVS
filetype:mbx mbx intext:Subject
filetype:myd myd -CVS
filetype:ns ns
filetype:ora ora
filetype:ora tnsnames
filetypedb pdb backup (Pilot | Pluckerdb)
filetypehp inurl:index inurlhpicalendar -site:sourceforge.net
filetypeot inurl:john.pot
filetypest inurl:"outlook.pst"
filetypest pst -from -to -date
filetype:qbb qbb
filetype:rdp rdp
filetype:reg "Terminal Server Client"
filetype:vcs vcs
filetype:wab wab
filetype:xls -site:gov inurltact
filetype:xls inurl:"email.xls"
Financial spreadsheets: finance.xls
Financial spreadsheets: finances.xls
Ganglia Cluster Reports
haccess.ctl (one way)
haccess.ctl (VERY reliable)
ICQ chat logs, please...
iletype:log cron.log
intext:"Session Start * * * *:*:* *" filetype:log
intext:"Tobias Oetiker" "traffic analysis"
intextpassword | passcode) intextusername | userid | user) filetype:csv
intext:gmail invite intext:http://gmail.google.com/gmail/a
intext:SQLiteManager inurl:main.php
intitle:"Apache::Status" (inurl:server-status | inurl:status.html | inurl:apache.html)
intitle:"AppServ Open Project" -site:www.appservnetwork.com
intitle:"ASP Stats Generator *.*" "ASP Stats Generator" "- weppos"
intitle:"Big Sister" +"OK Attention Trouble"
intitle:"edna:streaming mp server" -forums
intitle:"FTP root at"
intitle:"index of" +myd size
intitle:"Index Of" -inurl:maillog maillog size
intitle:"Index Of" cookies.txt size
intitle:"index of" mysql.conf OR mysql_config
intitle:"Index of" upload size parent directory
intitle:"index.of *" admin news.asp configview.asp
intitle:"index.of" .diz .nfo last modified
intitle:"Multimon UPS status page"
intitle:"PHP Advanced Transfer" (inurl:index.php | inurl:showrecent.php )
intitle:"PhpMyExplorer" inurl:"index.php" -cvs
intitle:"statistics of" "advanced web statistics"
intitle:"System Statistics" +"System and Network Information Center"
intitle:"Usage Statistics for" "Generated by Webalizer"
intitle:"wbem" compaq login "Compaq Information Technologies Group"
intitle:"Web Server Statistics for ****"
intitle:"web server status" SSH Telnet
intitle:"welcome.to.squeezebox"
intitle:admin intitle:login
intitle:index.of "Apache" "server at"
intitle:index.of cleanup.log
intitle:index.of dead.letter
intitle:index.of inbox
intitle:index.of inbox dbx
intitle:index.of ws_ftp.ini
intitle:intranet inurl:intranet +intext:"phone"
inurl:"/axs/ax-admin.pl" -script
inurl:"/cricket/grapher.cgi"
inurl:"bookmark.htm"
inurl:"cacti" +inurl:"graph_view.php" +"Settings Tree View" -cvs -RPM
inurl:"newsletter/admin/"
inurl:"newsletter/admin/" intitle:"newsletter admin"
inurl:"putty.reg"
inurl:"smb.conf" intext:"workgroup" filetypef conf
inurl:*db filetype:mdb
inurl:/_layouts/settings
inurl:admin filetype:xls
inurl:admin intitle:login
inurl:backup filetype:mdb
inurl:cgi-bin/printenv
inurl:cgi-bin/testcgi.exe "Please distribute TestCGI"
inurl:changepassword.asp
inurl:ds.py
inurl:email filetype:mdb
inurl:fcgi-bin/echo
inurl:forum filetype:mdb
inurl:forward filetype:forward -cvs
inurl:getmsg.html intitle:hotmail
inurl:log.nsf -gov
inurl:main.php phpMyAdmin
inurl:main.php Welcome to phpMyAdmin
inurl:netscape.hst
inurl:netscape.hst
inurl:netscape.ini
inurl:odbc.ini ext:ini -cvs
inurlerl/printenv
inurlhp.ini filetype:ini
inurlreferences.ini "[emule]"
inurlrofiles filetype:mdb
inurl:report "EVEREST Home Edition "
inurl:server-info "Apache Server Information"
inurl:server-status "apache"
inurl:snitz_forums_.mdb
inurl:ssl.conf filetypef
inurl:tdbin
inurl:vbstats.php "page generated"
ipsec.conf
ipsec.secrets
ipsec.secrets
Lotus Domino address books
mail filetype:csv -site:gov intext:name
Microsoft Money Data Files
mt-db-pass.cgi files
MySQL tabledata dumps
mystuff.xml - Trillian data files
OWA Public Folders (direct view)
Peoples MSN contact lists
php-addressbook "This is the addressbook for *" -warning
phpinfo()
phpMyAdmin dumps
phpMyAdmin dumps
private key files (.csr)
private key files (.key)
Quicken data files
robots.txt
site:edu admin grades
SQL data dumps
Squid cache server reports
Unreal IRCd
WebLog Referrers
Welcome to ntop!

"adding new user" inurl:addnewuser -"there are no domains"
(inurl:/cgi-bin/.cobalt/) | (intext:"Welcome to the Cobalt RaQ")
+htpasswd +WS_FTP.LOG filetype:log
filetypehp HAXPLORER "Server Files Browser"
intitle:"Web Data Administrator - Login"
intitle:admin intitle:login
inurl:"phpOracleAdmin/php" -download -cvs
inurl:ConnectComputer/precheck.htm | inurl:Remote/logon.aspx
PHP Shell (unprotected)
PHPKonsole PHPShell filetypehp -echo
Public PHP FileManagers

"Index Of /network" "last modified"
"index of cgi-bin"
"index of" / picasa.ini
"index of" inurl:recycler
"Index of" rar r nfo Modified
"intitle:Index.Of /" stats merchant cgi-* etc
"Powered by Invision Power File Manager" (inurl:login.php) | (intitle:"Browsing directory /" )
"Web File Browser" "Use regular expression"
"Welcome to phpMyAdmin" " Create new database"
allinurl:"/*/_vti_pvt/" | allinurl:"/*/_vti_cnf/"
filetype:cfg ks intext:rootpw -sample -test -howto
filetype:ini Desktop.ini intext:mydocs.dll
filetype:torrent torrent
Index of phpMyAdmin
index.of.dcim
index.of.password
index.of.password
intext:"d.aspx?id" || inurl:"d.aspx?id"
intext:"Powered By: TotalIndex" intitle:"TotalIndex"
intitle:"album permissions" "Users who can modify photos" "EVERYBODY"
intitle:"Directory Listing For" intext:Tomcat -intitle:Tomcat
intitle:"HFS /" +"HttpFileServer"
intitle:"Index of *" inurl:"my shared folder" size modified
intitle:"Index of /CFIDE/" administrator
intitle:"Index of c:\Windows"
intitle:"index of" "parent directory" "desktop.ini" site:dyndns.org
intitle:"index of" -inurl:htm -inurl:html mp
intitle:"Index of" cfide
intitle:"index of" intext:"content.ie"
intitle:"index of" inurl:ftp (pub | incoming)
intitle:"index.of.personal"
intitle:"webadmin - /*" filetypehp directory filename permission
intitle:index.of (inurl:fileadmin | intitle:fileadmin)
intitle:index.of /AlbumArt_
intitle:index.of /maildir/new/
intitle:index.of abyss.conf
intitle:intranet inurl:intranet +intext:"human resources"
intitle:upload inurl:upload intext:upload -forum -shop -support -wc
inurl:/pls/sample/admin_/help/
inurl:/tmp
inurl:backup intitle:index.of inurl:admin
inurl:explorer.cfm inurldirpath|This_Directory)
inurl:jee/examples/jsp
inurl:ojspdemos
private
protected
secret
secure
winnt

filetypel -intext:"/usr/bin/perl" inurl:webcal (inurl:webcal | inurl:add | inurl:delete | inurlfig)
"File Upload Manager v." "rename to"
"Powered by Land Down Under "
"powered by YellDL"
ext:asp "powered by DUForum" inurlmessages|details|login|default|register) -site:duware.com
ext:asp inurlUgallery intitle:"." -site:dugallery.com -site:duware.com
ext:cgi inurl:ubb_test
ezBOO "Administrator Panel" -cvs
filetype:cgi inurl:cachemgr.cgi
filetype:cnf my.cnf -cvs -example
filetype:inc inc intext:setcookie
filetype:lit lit (books|ebooks)
filetype:mdb inurl:"news/news"
filetypehp inurl:"viewfile" -"index.php" -"idfil
filetype:wsdl wsdl
Gallery configuration setup files
intitle:"ASP FileMan" Resend -site:iisworks.com
intitle:"Directory Listing" "tree view"
intitle:"Index of /" modified php.exe
intitle:"PHP Explorer" exthp (inurlhpexplorer.php | inurl:list.php | inurl:browse.php)
intitle:"phpremoteview" filetypehp "Name, Size, Type, Modify"
intitle:mywebftp "Please enter your password"
inurl:" WWWADMIN.PL" intitle:"wwwadmin"
inurl:"nph-proxy.cgi" "Start browsing through this CGI-based proxy"
inurl:"plog/register.php"
inurl:cgi.asx?StoreID
inurl:changepassword.cgi -cvs
inurl:click.php intextToungueHPClickLog
inurlhp.exe filetype:exe -example.com
inurl:robpoll.cgi filetype:cgi
link:http://www.toastforums.com/
PHP-Nuke - create super user right now !
The Master List

"More Info about MetaCart Free"
Comersus.mdb database
inurl:midicart.mdb
inurl:shopdbtest.asp
POWERED BY HIT JAMMER .!
site:ups.com intitle:"Ups Package tracking" intext:"Z ### ### ## #### ### #"
VP-ASP Shop Administrators only

12 Eylül 2009 Cumartesi

Windows Mobile'da SMS ve Email gönderme

Tüm bu işlemleri yapmak için uygulamaıza Microsoft.WindowsMobile.PocketOutlook referansını eklememiz gerekmektedir. Bu referansı ekleyerek uygulamamıza başlayabiliriz.



Makalemize öncelikle uygulamamızdan nasıl sms atacağımızı inceleyerek başlayalım. Sms göndermek için SmsMessage nesnesini kullanacağız. Sms alıcılarını tanımlamak için ise Recipient nesnesini kullanacağız. SmsMessage nesnesi sadece sms mesajları için kullanılırken Recipient nesnesi tüm mesaj tipleri (Email, sms) için kullanılan ortak bir nesnedir. Öncelikle bu nesnelerin özelliklerini ve metodlarını inceleyelim.

SmsMessage nesnesi özellikleri :
Body(String) Bu özellik sms mesajının içeriğini taşımaktadır.
From(Recipient) Bu özellik sms'in kimden geldiği bilgisini taşımaktadır ve readonly bir özelliktir. Sms gönderilirken değil gelen sms'lerin incelenmesinde kullanılan bir özelliktir.
ItemId(ItemId) Bu özellik sms'e ait unique bir değer taşımaktadır. Bu özellik read only'dir.
LastModified(DateTime) Mesajın gönderildiği tarih bilgisini taşıyan özelliktir. Bu özellik read only'dir.
Read(bool) Sms'in okunup okunmadığı bilgisini taşıyan özelliktir. Read only'dir.
Received(DateTime) Sms'in alındığı tarih bilgisini taşıyan özelliktir. Read only'dir.
RequestDeliveryReport(bool) Gönderilen sms için delivery report istenip istenmediğinin tutulduğu özelliktir.
To(RecipientCollection) Sms'in alıcılarının bilgilerinin tutulduğu özelliktir. Her bir alıcı bir Recipient nesnesi ile temsil edilmektedir.

SmsMessage nesnesi metodları :
Send Sms'i göndermek için kullanacağımız metoddur. Sms'in aktif gsm şebekesi üzerinden gönderilmesini sağlar.

Recipient nesnesi özellikleri :
Address(string) Mesaj gönderilecek nokta bilgisini barındıran özelliktir. Sms mesajları için telefon numarası, Email mesajları için ise email adresidir.
Name(string) Mesaj gönderilecek kişiyi barındıran özelliktir.

Recipient nesnesi için bu değerlerin instance alırken tanımlanabileceği yapıcı metodlar mevcuttur. Bu nesnenin boş yapıcı metodu yoktur.

Şimdi isterseniz Sms göndermek için kullanabileceğimiz bir helper class'ını birlikte yazalım.

public static void SendSms(string parBody, string parRecipient)
{
SmsMessage insSmsMessage = new SmsMessage();
insSmsMessage.Body = parBody;
AddRecipient(insSmsMessage, parRecipient);
insSmsMessage.Send();
}
private static void AddRecipient(SmsMessage parSmsMessage, string parRecipient)
{
AddRecipient(parSmsMessage, new Recipient(parRecipient));
}


Gördüğünüz gibi birkaç satırlık kod yazarak sms göndermek mümkün. Bu metodların farklı parametreler alan overload'larını yazdığım bir class'ı Download kısmından indirebilirsiniz.

Şimdi isterseniz sms göndermeye çok benzer bir şekilde çalışan Email gönderme işlemini inceleyelim. Bunun için kullanacağımız nesne EmailMessage nesnesidir.

EmailMessage nesnesi özellikleri :
Attachments(AttachmentCollection) Mail mesajının eklerini barındıran özelliktir.
Bcc(RecipientCollection) Email'in bcc alıcılarının bilgilerinin tutulduğu özelliktir. Her bir alıcı bir Recipient nesnesi ile temsil edilmektedir.
BodyText(string) Email'in içeriğinin tutulduğu özelliktir.
Cc(RecipientCollection) Email'in cc alıcılarının bilgilerinin tutulduğu özelliktir. Her bir alıcı bir Recipient nesnesi ile temsil edilmektedir.
From(Recipient) Mesaj alıcısında gösterilecek mesajı gönderen adres ve kişi bilgisinin tutulduğu özelliktir.
Importance(Importance) Email'in önem derecesinin tutulduğu özelliktir. Aynı isimdeki Importance enum'undan değerler alır.
ItemId(ItemId) Bu özellik email'e ait unique bir değer taşımaktadır. Bu özellik read only'dir.
LastModified(DateTime) Mesajın gönderildiği tarih bilgisini taşıyan özelliktir. Bu özellik read only'dir.
Read(bool) Email'in okunup okunmadığı bilgisini taşıyan özelliktir. Read only'dir.
Received(DateTime) Email'in alındığı tarih bilgisini taşıyan özelliktir. Read only'dir.
Sensitivity(Sensitivity) Email'in kişisel mi confidential'mı olduğu gibi hassasiyet bilgilerinin tutulduğu özelliktir. Aynı isimdeki enum değerlerini taşır.
Subject(string) Email mesajının konusu'nun tutulduğu özelliktir.
To(RecipientCollection) Email'in alıcılarının bilgilerinin tutulduğu özelliktir. Her bir alıcı bir Recipient nesnesi ile temsil edilmektedir.

EmailMessage nesnesi metodları :
Send Email'i göndermek için kullanacağımız metoddur. Accountname veya EmailAccount nesnesini parametre alır ve parametre aldığı mail hesabı üzerinden gönderim yapar.

Şimdi isterseniz Email göndermek için kullanabileceğimiz bir helper class'ını birlikte yazalım.

public static void SendEmail(string parBody, string parRecipient)
{
EmailMessage insEmailMessage = new EmailMessage();
insEmailMessage.BodyText = parBody;
AddRecipient(insEmailMessage, parRecipient);
insEmailMessage.Send(GetAccountName());
}
private static string GetAccountName()
{
OutlookSession insOutlookSession = new OutlookSession();
return insOutlookSession.EmailAccounts[0].Name;
}
private static void AddRecipient(EmailMessage parEmailMessage, Recipient parRecipient)
{
parEmailMessage.To.Add(parRecipient);
}

Gördüğünüz gibi mail gönderme işlemi Sms göndermeye çok benzemektedir. Tek farklı nokta send metodunda mail hesabının veya hesap adının verilmesi gerekmesidir. Gördüğünüz gibi bunun içinde Outlook Session nesnesinden tanımlı mail hesaplarını okuyabilmekteyiz.

Şimdi isterseniz mobil cihazımıza yeni bir mesaj geldiğinden nasıl haberdar olabileceğimizi inceleyelim. Bunun için MessageInterceptor nesnesini kullanacağız. Bu nesne overloadında sadece Notify mı edileceği veya Notify edildikten sonra mesajın silinip silinmeyeceğine dair bir aksiyon parametresi ve bu işlem için mevcut thread'in kullanılıp kullanılmayacağını belirleyen boolean tipinde bir parametre almaktadır. Sonrasında ise bu nesnenin MessageReceived event'ını handle ederek mesaj geldiğinden haberdar olabiliriz. Bu nesnenin kullanımına ait bir örnek aşağıda verilmiştir.

MessageInterceptor msgInterceptor = new MessageInterceptor(InterceptionAction.Notify, true);

public SmsAgent()
{
msgInterceptor.MessageReceived += new MessageInterceptorEventHandler(msgInterceptor_MessageReceived);
}
void msgInterceptor_MessageReceived(object sender, MessageInterceptorEventArgs e)
{
}
Gördüğünüz gibi mesaj geldiğinde MessageInterceptor nesnesinden fırlayan event sayesinde bir çok işlem yapabiliriz. Event'ta bulunan MessageInterceptorEventArgs parametresinin Message özelliği ile gelen mesaja ait özellikleri alabiliriz.

Burda önemli bir soru belirli özelliklere sahip mesajları nasıl yakalayacağımızdır. Örneğin bir kullanıcıdan gelen mesajları yakalamak istiyorsak ne yapmamız gerektiğidir. Birçoğunuzun aklına bu durumu MessageRecieved event'ı içinde kontrol etmek gelmiştir. Ancak bunun için MessageCondition nesnesi vardır. Tek yapmanız gereken bu nesnenin ilgili property'lerini doldurmak ve MessageInterceptor nesnesinin MessageCondition özelliğine bu nesneyi atamaktır. Aşağıda bununla ilgili bir örnek kod parçası veriyorum.

MessageInterceptor msgInterceptor = new MessageInterceptor(InterceptionAction.Notify, true);
public SmsAgent()
{
msgInterceptor.MessageCondition = new MessageCondition(MessageProperty.Body, MessagePropertyComparisonType.StartsWith, "Hello");
msgInterceptor.MessageReceived += new MessageInterceptorEventHandler(msgInterceptor_MessageReceived);
}
void msgInterceptor_MessageReceived(object sender, MessageInterceptorEventArgs e)
{}

Umarım faydalı bir makale olmuştur.

Tamer Öz
http://www.yazgelistir.com/Makaleler/1000002315.ygpx

7 Eylül 2009 Pazartesi

how to get imei number

Siemens: System.getProperty("com.siemens.IMEI");

Samsung: System.getProperty("com.samsung.imei");

SonyEricsson: System.getProperty("com.sonyericsson.imei");

Motorola: System.getProperty("IMEI");

System.getProperty("com.motorola.IMEI");

Nokia: System.getProperty("com.nokia.mid.imei");

27 Ağustos 2009 Perşembe

OleDbConnection

DateTime bugun = DateTime.Now;

string constr = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Documents and Settings\Arastokrat.DYGOR-MOBILE\Belgelerim\Visual Studio 2008\Projects\WebSite1\DB\GelecegeMektupDB.accdb";
OleDbConnection con = new OleDbConnection(constr);

string query = "SELECT * FROM Mektuplar WHERE Tarih=@tarih;";
OleDbCommand cmd = new OleDbCommand(query, con);

cmd.Parameters.Add("@tarih", OleDbType.DBDate).Value = bugun;

OleDbDataAdapter dap = new OleDbDataAdapter(cmd);
DataSet ds = new DataSet();
dap.Fill(ds);

try
{
con.Open();

OleDbDataReader dr = cmd.ExecuteReader();

while (dr.Read())
{
if (dr.GetString(4).Equals(DateTime.Now.ToShortDateString()))
{
emailGonder(dr.GetString(1),dr.GetString(2),dr.GetString(3),dr.GetString(5));
}
}

dr.Close();
Response.Write("");
}
catch (Exception hata)
{
}
finally
{
con.Close();
}

23 Ağustos 2009 Pazar

Virtual Earth üzerinde işlemler

Kodu düzenlemeye bak, gerisini görürsün


20 Ağustos 2009 Perşembe

HashTables

This example creates a hashtable of numbers. It uses the names of the numbers as keys:

Hashtable numbers = new Hashtable();
numbers.put("one", new Integer(1));
numbers.put("two", new Integer(2));
numbers.put("three", new Integer(3));


To retrieve a number, use the following code:

Integer n = (Integer)numbers.get("two");
if (n != null) {
System.out.println("two = " + n);
}

18 Ağustos 2009 Salı

JAVA ile mail gonderme 2

String to = ""; // to address
String from = ""; // from address
String subject = ""; // the subject line
String message = null; // the body of the message
String mailhost = ""; // SMTP server
String user = ""; // user ID
String password = ""; // password
// password
boolean auth = true;
boolean ssl = false;
Properties props = System.getProperties();

if (mailhost != null) {
props.put("mail.smtp.host", mailhost);
}
if (auth) {
props.put("mail.smtp.auth", "true");
}
// Get a Session object
javax.mail.Session session = javax.mail.Session.getInstance(props, null);

// Construct the message
javax.mail.Message msg = new MimeMessage(session);

try {
// Set message details
msg.setFrom(new InternetAddress(from));
msg.setRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(to));
msg.setSubject(subject);
msg.setSentDate(new Date());
msg.setText(message);

// Send the thing off
SMTPTransport t = (SMTPTransport)session.getTransport(ssl ? "smtps" : "smtp");
try {
if (auth) {
t.connect(mailhost, user, password);
} else {
t.connect();
}
t.sendMessage(msg, msg.getAllRecipients());
} finally {
t.close();
}
log("Mail was sent successfully.");
} catch (Exception e) {
if (e instanceof SendFailedException) {
MessagingException sfe = (MessagingException)e;
if (sfe instanceof SMTPSendFailedException) {
SMTPSendFailedException ssfe = (SMTPSendFailedException)sfe;
log("Smtp_Send_Failed:");
}
Exception ne;
while ((ne = sfe.getNextException()) != null && ne instanceof MessagingException) {
sfe = (MessagingException)ne;
if (sfe instanceof SMTPAddressFailedException) {
SMTPAddressFailedException ssfe = (SMTPAddressFailedException)sfe;
log("Address failed:");
log(ssfe.toString());
log(" Address: " + ssfe.getAddress());
log(" Command: " + ssfe.getCommand());
log(" Return Code: " + ssfe.getReturnCode());
log(" Response: " + ssfe.getMessage());
} else if (sfe instanceof SMTPAddressSucceededException) {
log("Address succeeded:");
SMTPAddressSucceededException ssfe = (SMTPAddressSucceededException)sfe;
}
}
} else {
log("Got Exception : " + e);
}
}

16 Ağustos 2009 Pazar

JAVA ile mail gonderme

import javax.mail.*;
import javax.activation.*;

import java.util.Properties;
import java.util.Date;

public class Mesaj {

Message messages[];

int toplamMesajlar;
int yeniMesajlar;

Session session;

Store store;

Folder klasor;

private Properties props;

public Mesaj(String username,String password,String host,int port) {
try {

//Properties sinifinin örnegini(instance) olusturuyoruz.
props = new Properties();
props.put("mail.pop3.host",host);
props.put("mail.pop3.port",port);
props.setProperty("mail.pop3.socketFactory.class","javax.net.ssl.SSLSocketFactory");
props.setProperty("mail.pop3.socketFactory.fallback","false");
props.put("mail.pop3.starttls.enable","true");

//Session sinifindan, getInstance metoduyla, örnegini(instance) olusturuyoruz.
session = Session.getInstance(props,null);

//Debug true
session.setDebug(true);


//pop3 protokolunu kullanacağimizi belirtiyoruz.
store = session.getStore("pop3");

//Belirtilen host,port,username,password ile bağlantimizi gerçeklestiriyoruz
store.connect(host,port,username,password);

//INBOX klasörünü aliyoruz.
klasor = store.getFolder("INBOX");

//Klasorü READ_ONLY açiyoruz.
klasor.open(Folder.READ_ONLY);

messages = klasor.getMessages();

toplamMesajlar=klasor.getMessageCount();
yeniMesajlar = klasor.getNewMessageCount();

}

catch(MessagingException mex) {
System.err.println("Hata olustu :" +mex);
}
}

//Mesaj sinifina ait metodlar yer almaktadir.

public Date[] mesajgetDate() {
Date[] date= new Date[toplamMesajlar];

try {
for(int i=0;i date[i]=messages[i].getSentDate();

}


}
catch(MessagingException mex) {
System.err.println("Hata olustu : " +mex);

}

if(date == null) {
return null;
}
else {
return date;
}

}

public String[] mesajgetFrom() {
String[] from=new String[toplamMesajlar];
Address[] a;


try {
for(int k=0;k if ((a = messages[k].getFrom()) != null) {
for (int j = 0; j < a.length; j++) {
from[k]=a[j].toString();
}
}
}

}
catch (MessagingException mex) {
System.err.println("Hata olustu : "+mex);
}

return from;

}

public String[] mesajgetSubject() {
String[] s= new String[toplamMesajlar];

try {
for(int i=0;i
s[i]=messages[i].getSubject();

}
}
catch(MessagingException mex) {
System.err.println("Hata olustu : " +mex);
}
if(s == null) {
return null;
}
else {
return s;
}
}//mesajgetSubject();

public int toplamMesaj() {
int toplam=0;

try {
toplam = klasor.getMessageCount();
}
catch(MessagingException mex) {
System.err.println("Hata olustu: " + mex);
}

return toplam;
}

public int yeniMesaj() {
int yeni=0;
try {
yeni = klasor.getNewMessageCount();
}
catch(MessagingException mex) {
System.err.println("Hata olustu: " + mex);
}

return yeni;


}

public void closeConnection() {
try {
klasor.close(false);
store.close();

}
catch(MessagingException mex) {
System.err.println("Hata olustu: " +mex);
}
}

}

source: http://www.mutasyon.net/soruoku.asp?id=158

1 Ağustos 2009 Cumartesi

Excel'den veri okuma

1. Önce http://sourceforge.net/projects/jexcelapi/files/ adresinden jxl.jar dosyasını indir.

2.Projenin altında Libraries -> right click -> Add jar file ile jxl.jar'ı projeye ekliyoruz.

3. kod şu şekilde:


import java.io.*;
import java.io.File;
import jxl.*;
import java.util.Date;
import javax.swing.JOptionPane;

/**
*
* @author Arastokrat
*/

public class Main {

/**
* @param args the command line arguments
*/
public static void main (String[] args) {
// TODO code application logic here

try{
Workbook kitap=Workbook.getWorkbook(new File("C:\\Documents and Settings\\Arastokrat.DYGOR-MOBILE\\Belgelerim\\JAVA\\liste.xls"));

Sheet sayfa=kitap.getSheet(0);
Cell hucre0=sayfa.getCell(0, 0); //(sutun, satır)
String data=hucre0.getContents();
System.out.println(data);
kitap.close();
//JOptionPane.showInputDialog(data);
}
catch(Exception ex){
ex.printStackTrace();
}
}

}

NOT: Excel 2003 için geçerli. 2007 de çalışöıyor.
Sutunları x, satırları y olarak alıyor.

7 Temmuz 2009 Salı

Java da soket programlama

// Serialization example.
2 // Derived by Hadi from previous DateServer.java
3 import java.util.Date;
4 import java.net.*;
5 import java.io.*;
6 public class DateServer {
7 public static void main (String [] args) {
8 try {
9 DateServer world = new DateServer();
10 } catch (IOException e) {
11 System.out.println("IO exception " + e);
12 }
13 }
14 static final public int portNumber = 4291;
15 public DateServer () throws IOException {
16 ServerSocket server = new ServerSocket(portNumber);
17 while (true) {
18 System.out.println("Waiting for a client");
19 Socket sock = server.accept();
20 System.out.println("Got a client, send a message");
21 ObjectOutputStream out = new ObjectOutputStream(sock.getOutputStream());
22
23 out.writeObject(new Date());
24 }
25 }
26 }


===============================================================================
===============================================================================
===============================================================================


1 import java.net.*;
2 import java.io.*;
3 public class DateClient {
4 public static void main (String [] args) {
5 try {
6 DateClient world = new DateClient();
7 } catch (IOException e) {
8 System.out.println("Received an IO exception " + e);
9 }
10 }
11 static final public int portNumber = 4291;
12 public DateClient () throws IOException {
13 Socket sock = new Socket(InetAddress.getLocalHost(), portNumber);
14 Reader isread = new InputStreamReader(sock.getInputStream());
15 BufferedReader input = new BufferedReader(isread);
16 System.out.println("message is " + input.readLine());
17 }
18 }


===============================================================================
===============================================================================
===============================================================================


1 import java.net.*;
2 import java.io.*;
3 class Therapist {
4 static public void main (String [ ] args) {
5 try {
6 Therapist world = new Therapist();
7 } catch (IOException e) {
8 System.out.println("Received an IO Exception" + e);
9 }
10 }
11 static final public int portNumber = 5321;
12 public Therapist () throws IOException {
13 ServerSocket server = new ServerSocket(portNumber);
14 while (true) {
15 Socket sock = server.accept();
16 Thread session = new TherapySession
17 (sock.getInputStream(), sock.getOutputStream());
18 session.start();
19 }
20 }
21 }

===============================================================================
===============================================================================
===============================================================================


1 import java.io.*;
2 import java.util.Vector;
3 import java.util.StringTokenizer;
4 class TherapySession extends Thread {
5 public TherapySession (InputStream ins, OutputStream outs) {
6 Reader isread = new InputStreamReader(ins);
7 in = new BufferedReader(isread);
8 out = new OutputStreamWriter(outs);
9 }
10 private String name = "";
11 private BufferedReader in;
12 private Writer out;
13 private String response(String text) {
14 // answer a question with a question
15 if (text.endsWith("?"))
16 return "Why do you want to know?";
17 // break up line
18 Vector words = new Vector();
19 StringTokenizer breaker = new StringTokenizer(text, " .,?!");
20 while (breaker.hasMoreElements())
21 words.addElement(breaker.nextElement());
22 // look for ``I feel''
23 if ((words.size() > 1) &&
24 words.elementAt(0).equals("i") &&
25 words.elementAt(1).equals("feel"))
26 return "Why do you feel that way?";
27 // look for relatives
28 for (int i = 0; i < words.size(); i++) {
29 String relative = (String) words.elementAt(i);
30 if (isRelative(relative))
31 return "Tell me more about your " + relative;
32 }
33 // nothing else, generic response
34 return "Tell me more";
35 }
36 private boolean isRelative(String name) {
37 return name.equals("mother") || name.equals("father")
38 || name.equals("brother") || name.equals("sister")
39 || name.equals("uncle");
40 }
41
42 public void run() {
43 try {
44 // get name
45 out.write("Hello. Welcome to therapy. What is your name?\n");
46 out.flush();
47 name = in.readLine();
48 out.write("Well " + name + " what can we do for you today?\n");
49 out.flush();
50 // now read and respond
51 while (true) {
52 String text = in.readLine();
53 out.write(response(text) + "\n");
54 out.flush();
55 }
56 } catch (IOException e) { stop(); }
57 }
58 }



===============================================================================
===============================================================================
===============================================================================



1 import java.io.*;
2 import java.net.*;
3 class TherapyClient {
4 public static void main (String [ ] args) {
5 try {
6 TherapyClient world = new TherapyClient();
7 } catch (IOException e) {
8 System.out.println("got IO exception " + e);
9 }
10 }
11 static final public int portNumber = 5321;
12 private BufferedReader input, term;
13 private Writer output;
14 public TherapyClient () throws IOException {
15 // open standard input as buffered reader
16 term = new BufferedReader(new InputStreamReader(System.in));
17 // open socket as a reader and a writer
18 Socket sock = new Socket(InetAddress.getLocalHost(), portNumber);
19 Reader isread = new InputStreamReader(sock.getInputStream());
20 input = new BufferedReader(isread);
21 output = new OutputStreamWriter(sock.getOutputStream());
22 // now read and print
23 while (true) {
24 // read and print something from therapist
25 String line = input.readLine();
26 System.out.println(line);
27 // get our response
28 line = term.readLine();
29 if (line.equals("Quit"))
30 break;
31 output.write(line + "\n");
32 output.flush();
33 }
34 }
35 }

Ağ Üzerinden Nesne Aktarımı

Nesnelerin ağ üzerinden aktarılması nesne dizileştirme (object serialization) yötemiyle mümkündür. Nesne dizileştirme metodu çalışma esnasında üretilen herhangibir nesnenin o anki durumunu saklamak ve bir dahaki işletimde kalınan yeerden devam etmek gibi amaçlarla da kullanılmaktadır. Burada yapılan sadece nesneyi, diske veya ağ üzerinden karşı tarafa aktarabilecek şekilde karakter dizilerine çevirmektir. Sonra aynı işlemin tersi (unserialization) yapılarak diskten veya ağ üzerinden okunan karakter dizileri programın kullanabileceği nesneler haline getirilir.

Örnek olarak daha önce verilen 'DateServer.java' ve 'DateClient.java' uygulaması biraz değiştirilerek sunucunun verdiği zamanın istemcinin çalıştığı makinanın yerel zaman formatında gösterilmesini sağlandı.

Sunucu tarafında (DateServer.java), çıkış akımı (stream), 'ObjectOutputStream' türü bir nesne olarak açılarak sistem zamanını gösteren 'Date' türü nesnemiz 'writeObject' metoduyla bu akıma verildi. Bu fonksiyon içinde nesne dizileştirilerek ağ üzerinden karşı makineye gönderilir.

İstemci tarafında (DateClient.java) ise giriş akımı (stream), 'ObjectInputStream' türü bir nesne olarak açılır ve 'readObject' metodu kullanılarak soketin giriş akımı üzerinden, gönderilen dizi alınır ve tekrar nesne haline getirilir. Sonra da nesnenin yerel makinadaki karşılığı 'String' olarak alınarak ekrana basılır.

http://www.godoro.com/divisions/ehil/mecmua/Magazines/Articles/txt/html/article_JavaNetworkProgramming.html

6 Temmuz 2009 Pazartesi

Bluetooth Java

import java.util.*;

import java.io.*;
import javax.microedition.io.*;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.bluetooth.*;
import javax.obex.*;

public class BluetoothGPSMidlet extends MIDlet implements CommandListener{

public Display display;
public Form discoveryForm;
public Form readyToConnectForm;
public Form dataViewForm;
public ImageItem mainImageItem;
public Image mainImage;
public Image bt_logo;
public TextField addressTextField;
public TextField subjectTextField;
public TextField messageTextField;
public Command selectCommand;
public Command exitCommand;
public Command connectCommand;
public List devicesList;
public Thread btUtility;
public String btConnectionURL;
//public StreamConnection connection;
//public InputStream in;
public boolean readData = false;

public BluetoothGPSMidlet() {
display=Display.getDisplay(this);
discoveryForm = new Form("Bluetooth GPS");

try{
mainImage = Image.createImage("/btlogoBIG.png");
bt_logo = Image.createImage("/btlogo.png");
} catch (java.io.IOException e){
e.printStackTrace();
}
mainImageItem = new ImageItem("Bluetooth GPS Reader", mainImage, Item.LAYOUT_CENTER, "");
discoveryForm.append(mainImageItem);
discoveryForm.append("\nThis application will scan the area for Bluetooth devices and determine if any are offering wireless serial port services.\n\n");

btUtility = new BTUtility();

/// discoveryForm initialization

exitCommand = new Command("Exit", Command.EXIT, 1);
discoveryForm.addCommand(exitCommand);
discoveryForm.setCommandListener(this);

/// devicesList initialization

devicesList = new List("Select a Bluetooth Device", Choice.IMPLICIT, new String[0], new Image[0]);
selectCommand = new Command("Select", Command.ITEM, 1);
devicesList.addCommand(selectCommand);
devicesList.setCommandListener(this);
devicesList.setSelectedFlags(new boolean[0]);

/// readyToConnectForm initialization

readyToConnectForm = new Form("Ready to Connect");
readyToConnectForm.append("The selected Bluetooth device is currently offering a valid serial port service, and is ready to connect. Please click on the 'Connect' button to connect and read the data.");
connectCommand = new Command("Connect", Command.ITEM, 1);
readyToConnectForm.addCommand(connectCommand);
readyToConnectForm.setCommandListener(this);

/// dataViewForm initialization

dataViewForm = new Form("Serial Data Viewer");
dataViewForm.append("The following lines of data are being read from the serial input:\n\n");
dataViewForm.addCommand(exitCommand);
dataViewForm.setCommandListener(this);

}


public void commandAction(Command command, Displayable d) {
if(command == selectCommand) {
btUtility.start();
}
if(command == exitCommand ) {
readData = false;
destroyApp(true);
}
if(command == connectCommand ) {
Thread commReaderThread = new COMMReader();
commReaderThread.start();
display.setCurrent(dataViewForm);
}
}


public void startApp() {
display.setCurrent(discoveryForm);
}


public void pauseApp() {

}

public void destroyApp(boolean b) {
notifyDestroyed();
}


////////////////

/**
* This is an inner class that is used for finding
* Bluetooth devices in the vicinity
*
*/
class BTUtility extends Thread implements DiscoveryListener {

Vector remoteDevices = new Vector();
Vector deviceNames = new Vector();

DiscoveryAgent discoveryAgent;

// obviously, 0x1101 is the UUID for
// the Serial Profile
UUID[] uuidSet = {new UUID(0x1101) };

// 0x0100 is the attribute for the service name element
// in the service record
int[] attrSet = {0x0100};


public BTUtility() {
try {
LocalDevice localDevice = LocalDevice.getLocalDevice();
discoveryAgent = localDevice.getDiscoveryAgent();
discoveryForm.append(" Searching for Bluetooth devices in the vicinity...\n");
discoveryAgent.startInquiry(DiscoveryAgent.GIAC, this);

} catch(Exception e) {
e.printStackTrace();
}
}

public void deviceDiscovered(RemoteDevice remoteDevice, DeviceClass cod) {
try{
discoveryForm.append("found: " + remoteDevice.getFriendlyName(true));
} catch(Exception e){
discoveryForm.append("found: " + remoteDevice.getBluetoothAddress());
} finally{
remoteDevices.addElement(remoteDevice);
}
}



public void inquiryCompleted(int discType) {

if (remoteDevices.size() > 0) {

// the discovery process was a success
// so let's out them in a List and display it to the user
for (int i=0; i try{
devicesList.append(((RemoteDevice)remoteDevices.elementAt(i)).getFriendlyName(true), bt_logo);
} catch (Exception e){
devicesList.append(((RemoteDevice)remoteDevices.elementAt(i)).getBluetoothAddress(), bt_logo);
}
}
display.setCurrent(devicesList);
} else {
// handle this
}

}


public void run(){

try {
RemoteDevice remoteDevice = (RemoteDevice)remoteDevices.elementAt(devicesList.getSelectedIndex());
discoveryAgent.searchServices(attrSet, uuidSet, remoteDevice , this);

} catch(Exception e) {
e.printStackTrace();
}
}



public void servicesDiscovered(int transID, ServiceRecord[] servRecord){

for(int i = 0; i < servRecord.length; i++) {

DataElement serviceNameElement = servRecord[i].getAttributeValue(0x0100);
String _serviceName = (String)serviceNameElement.getValue();
String serviceName = _serviceName.trim();
btConnectionURL = servRecord[i].getConnectionURL(ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false);

}
display.setCurrent(readyToConnectForm);
readyToConnectForm.append("\n\nNote: the connection URL is: " + btConnectionURL);

}

public void serviceSearchCompleted(int transID, int respCode) {

if (respCode == DiscoveryListener.SERVICE_SEARCH_COMPLETED) {
// the service search process was successful

} else {
// the service search process has failed
}

}

}
////////////////


////////////////

/**
* This is an inner class that is used for reading
* the serial stream of data from a RFCOMM device
*
*/
class COMMReader extends Thread {

public COMMReader() {

}

public void run(){

try{
StreamConnection connection = (StreamConnection)Connector.open(btConnectionURL);

//
// open an input stream to get some data
//

InputStream in = connection.openInputStream();

byte[] serialData;
readData = true;
while(readData == true){
int lengthavai=0;
lengthavai = in.available();

if(lengthavai > 0){
serialData = new byte[lengthavai];
int length = in.read(serialData);
System.out.println("data read: " + new String(serialData));
dataViewForm.append(new String(serialData));
}
}

in.close();
connection.close();

}catch(IOException ioe){
ioe.printStackTrace();
}


}


}

}







30 Haziran 2009 Salı

Design Patterns

Introduction

Since the invention of Object Oriented Programming, its philosophy has become exceedingly popular among the programming community and has had a wide spread acceptance in the technology world. Although OOP has become largely popular, it has spawned some repeated design problems with its continuous use. There was a need for rectifying these recurring problems in software designs. The need of the hour was a solution for these common problems. The use of design patterns has been a significant improvement in Object Oriented Design (OOD) and facilitates the design and development of high quality, maintainable software at a much faster rate and at a lower cost. Design Patterns are the proven and best solution to the common problems and increasing complexities involved in software development life cycles. One of the most important factors that determine the efficiency of a software design is its adaptability to change. My intent in authoring this article is to provide the readers an overview of Design Patterns, their applicability and the common pitfalls of improper usage or application of these design patterns in software designs.

Prerequisites

The reader should have a good background in the concepts of Object Oriented Programming and any one of the object oriented languages (C++, Java, C#, etc) for understanding the concepts covered in this article. A prior knowledge of Unified Modeling Language (UML) is an added advantage though it is not mandatory.

What are Design Patterns?

A Design Pattern essentially consists of a problem in a software design and a solution to the same. In Design Patterns each pattern is described with its name, the motivation behind the pattern and its applicability. Understanding the applicability of a design pattern is of utmost importance prior to implementing it.

According to MSDN, "A design pattern is a description of a set of interacting classes that provide a framework for a solution to a generalized problem in a specific context or environment. In other words, a pattern suggests a solution to a particular problem or issue in object-oriented software development. Additionally, patterns take into account design constraints and other factors that limit their applicability to the solution in general. Together, the classes, the communication and interconnections among those classes, and the contextual specifics define a pattern that provides a solution to any problem in object-oriented software design that presents characteristics and requirements matching those addressed by the pattern context."

"A design pattern systematically names, motivates, and explains a general design that addresses a recurring design problem in object-oriented systems. It describes the problem, the solution, when to apply the solution, and its consequences. It also gives implementation hints and examples. The solution is a general arrangement of objects and classes that solve the problem. The solution is customized and implemented to solve the problem in a particular context". -- Design Patterns: Elements of Reusable Object-Oriented Software by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides.

Benefits of Design Patterns

The following are some of the major advantages of using Design Patterns in software development.

  • Flexibility
  • Adaptability to change
  • Reusability

When to use Design Patterns

Design Patterns are particularly useful in one of the following scenarios.

  • When the software application would change in due course of time.
  • When the application contains source code that involves object creation and event notification.

When not to use Design Patterns

This section discusses the main points that can be used to evaluate whether or not to use design patterns to solve a problem context. Do not use design patterns in any of the following situations.

  • When the software being designed would not change with time.
  • When the requirements of the source code of the application are unique.

If any of the above applies in the current software design, there is no need to apply design patterns in the current design and increase unnecessary complexity in the design. The common pitfalls that are observed or rather encountered in a design when applying design patterns to solve a problem that does not need it is discussed later in this article.

The Gang of Four (GOF) Patterns

The invention of the design patterns that we commonly use today can be attributed to the following four persons: Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides. These men invented 23 patterns in all that are commonly known as the Gang of Four patterns or the GOF patterns. These patterns are named based on their intent and purpose and are classified in three broad categories stated below.

  • Creational
  • Structural
  • Behavioral

Each of these groups in turn contains related sub patterns. These patterns are discussed in the sections that follow. The sub patterns under the major three groups discussed above and their brief explanation are provided for better understanding.

Creational Patterns

The Creational Patterns deals with the best possible way of creating an object or an instance of a class. They simplify object creation and provide a flexible approach towards object creation. The following are the sub-patterns that fall under this group.

  • Abstract Factory
  • Factory
  • Builder
  • Prototype
  • Singleton

Both the Abstract Factory and the Factory pattern have the same intent. They have the same names and do the same thing. It is only the way that they operate that is important. Both the Abstract Factory and the Factory pattern deal with the creation of an object. The difference being that the Abstract Factory pattern uses objects to manage object creation while the Factory pattern does the same using inheritance. The Abstract Factory pattern provides an interface for creation of a family of related objects, but without specifying their concrete classes. The Factory pattern also provides an interface for the creation of objects, but allows the inherited classes to decide on the appropriate time of these instantiations.

The Builder Pattern is one that isolates the construction of a complex object from its representation, thus ensuring that several different representations can be created depending on the requirements. The Prototype Pattern allows an initialized and instantiated class to be copied or cloned to create new instances rather than creating new instances. The Singleton Pattern indicates that there can be only one instance of a class throughout the Application’s life cycle. A singleton class is one that can be instantiated only once in the application domain and provides a global point of access to it.

Structural Patterns

Structural Patterns provides the flexibility to specify how objects and classes can interoperate. The following are the sub patterns that comprise the Structural Patterns group.

  • Adapter
  • Facade
  • Bridge
  • Composite
  • Decorator
  • Flyweight
  • Proxy
  • Adapter
  • Bridge
  • Composite
  • Decorator
  • Flyweight
  • Proxy

The Adapter Pattern allows different classes to inter-operate even with incompatible interfaces. The Facade Pattern depicts a single class that represents a high level class in an entire subsystem and makes the subsystem easier to use. As an example, a Façade design pattern ensures that we can have a class that can act as a layer between the User Interface Layer and the Business Service Layer. Thus, it acts as an agent in the sense that it facilitates the communication between the User Interface Layer and the Business Service Layer in a typical n–tier application design. It is to be noted here that both the Adapter and Façade design patterns can be used to change the interfaces of the classes, thus enabling an easier communication of these classes from the User Interface Layer.

The Bridge Pattern eliminates the need of adapter classes in a sub system and decouples an object’s interface from its implementation so that both can work independent of each other. The Composite Pattern is a design pattern that is used to compose a tree like structure of simple and composite objects so that the clients can treat the individual objects and their compositions in a uniform manner. The Decorator Pattern provides an alternative for sub classing to extend functionality in a sub system and adds responsibilities to objects even after construction of the design of the system. The Flyweight Pattern is a fine-grained instance used for efficient sharing. The Proxy Pattern shows an object representing another object and, like the Adapter Design Pattern, it acts as a layer between the client or the consumer application and the actual object.

Behavioral Patterns

Behavioral patterns help you define a structure for inter-object communication between objects in your system. This design pattern is typically used to monitor the messages that are transmitted when the objects communicate in a system. The following are the sub patterns under Behavioral Patterns.

  • Chain of Responsibility
  • Command
  • Interpreter
  • Iterator
  • Mediator
  • Memento
  • Observer
  • State
  • Strategy
  • Template Method
  • Visitor

The Chain of Responsibility Pattern is one that details a way of passing a request between a chain of objects. The Command Pattern encapsulates a command request as an object. The Interpreter Pattern is a way to include language elements in a program. The Iterator Pattern sequentially accesses the elements of a collection. The Mediator Pattern defines simplified communication between classes. The Memento Pattern captures and restores an object's internal state. The Observer Pattern is a design pattern that provides a way of notifying a change to a number of its dependant classes. Therefore, when one object changes its state, so do all its dependant objects in the sub system. The State Pattern is a design pattern that changes an object's behavior when the internal state of the object changes. The Strategy Pattern is used to encapsulate a family of algorithms inside a class and use them interchangeably and independent of the client application that use the same. The Template Method Pattern is a design pattern that is used to provide a template of an algorithm and defers some of the steps of the algorithm to the subclasses. The Visitor Pattern is one that is used to define a new operation to a class without a change.

A Word of Caution

It is agreed that design patterns can solve complexities and problems in software design phases, but improper applicability of Design Patterns can lead to bad designs that can facilitate software design errors. Be very careful when using or applying design patterns. Do not use a pattern to solve a problem that does not need it. Do not simply ornament software design using a design pattern when it is not at all required in that context. Think twice before you decide to use them in your design. Understand the scope of the problem context and then search for a design pattern that best fits in that context to solve the problem. Further, one should have an excellent understanding of the scope and applicability of each design pattern before using it. Analyze the problem carefully, consider all options and apply the appropriate design pattern to solve the problem. What I personally feel is that we should only implement a design pattern in our software design provided we have sufficient knowledge of its applicability and scope. At the same time, we should be able to analyze the problem context and judge the applicability of the correct design pattern (if it is required at all) as a solution to the problem in question. It is quite unnecessary and not wanted of a software architect to implement a design pattern in a problem domain and increase complexity when it can be solved without using one.

References

Design Patterns (MSDN)
Gang of Four Design Patterns

Conclusion

I have provided a brief introduction to the all three categories of the Gang of Four Design Patterns in this article. The reader should be well aware of when to use which pattern in designing the software. Recognizing the feature and benefit of a particular pattern is of utmost importance when implementing it. The best advantage that can be gained from using these patterns is by applying the right type of pattern at the right place in the design. Stay tuned for more articles in which I would like to provide a detailed know-how on each and every pattern with sample code examples in each case for better understanding of a design pattern, its intent and applicability. I welcome your comments and suggestions. Happy reading!


Source: http://www.dotnetjohn.com/articles.aspx?articleid=272

Encapsulation

Encapsulation using Private, Public, Friendly, or Protected:

These are always asked in an interview!!!

public: a field, method, or class that is accessible to every class.

protected: a field, method, or class that is accessible to the class itself, subclasses, and all classes in the same package or directory.

friendly: a field, method, or class that is accessible to the class itself and to all classes in the same package or directory. Note that friendly is not a separate keyword. A field or method is declared friendly by virtue of the absence of any other access modifiers.

private: a field or method that is accessible only to the class in which it is defined. Note that a class can not be declared private as a whole.

Question: Write a class containing a private, public, and friendly field. Then try to access these fields from another class?

We need to write two classes: one class with various fields, and a second class to attempt to access these fields.

class AccessTest
{ // declare each of the fields
private int privateNum = 1;
public int publicNum = 3;
int friendlyNum = 4;
}

class Tester
{ // instantiate a methods
public static void main(String args[])
{
AccessTest a = new AccessTest();
System.out.println(a.privateNum);
System.out.println(a.friendlyNum);
System.out.println(a.publicNum);
}
}

Variable privateNum in class AccessTest not accessible from class Tester. Good Luck!

Source: http://www.dotnetjohn.com/articles.aspx?articleid=177

10 Haziran 2009 Çarşamba

Zeka sorusu

Aşağıda, bir sayı ile ilgili üç tane önerme veriliyor.

Eğer bu sayı 4 ün tam katı değilse; o zaman 60 ile 69 arasındadır.

Eğer bu sayı 3 ün tam katı değilse; o zaman 50 ile 59 arasındadır.

Eğer bu sayı 6 nın tam katı değilse; o zaman 70 ile 79 arasındadır.

Buna göre bu sayı kaçtır?

yanıt : 66

27 Mayıs 2009 Çarşamba

E-mail gonderme

In order to send email in C# code, do the following:

// create mail message object
MailMessage mail = new MailMessage();
mail.From = ""; // put the from address here
mail.To = ""; // put to address here
mail.Subject = ""; // put subject here
mail.Body = ""; // put body of email here
SmtpMail.SmtpServer = ""; // put smtp server you will use here
// and then send the mail
SmtpMail.Send(mail);

13 Mayıs 2009 Çarşamba

LINQ işlemleri

int[] sayilar={3,2,5,6,1,2,8,9,0};
var bulunan = from n in sayilar
where n <= 6 orderby n select n;

Ex: Diziyle verilen isimleri alıp onları büyük ve küçük harflere çeviren LINQ ve devamı. Aynı olan isimleri ikinciye almaz.

string[] names = { "aHmet", "uZuN", "IsTanBul", "bUrSA" ,"AHmet"};
var withLowerUpperLetters = (from n in names
orderby n
select new { Lower = n.ToLower(), Upper = n.ToUpper() }).Distinct();
string sonuc = "";
foreach (var v in withLowerUpperLetters)
{
sonuc += v.Lower + " ";
}
sonuc += "\n";
foreach (var v in withLowerUpperLetters)
{
sonuc += v.Upper + " ";
}
MessageBox.Show(sonuc);



son örnek olarak; sayilar dizisindeki elemanları 5'e bölümünden kalan sayılarına göre gruplayan LINQ.


string sonuc = "";
int[] sayilar = { 0, 2, 3, 7, 8, 9, 6, 4, 1 };
var numberGroups = from n in sayilar
group n by n % 5 into g
select new { g.Key, numbers = g };
foreach (var g in numberGroups)
{
sonuc += g.Key + " kalanı verenler ";
foreach (var n in g.numbers)
{
sonuc += n+" ";
}
sonuc += "\n";
}
MessageBox.Show(sonuc);


LINQ to SQL


Veritabanını sorgulamak için kulanılan LINQ ya denir.
Herhangi bir veritabanına ait bir tabloyu sorgulamak için projenizin içerisine Add->New Item->LINQ To SQL Classes eklemeniz gerekiyor. Bu bize projemizde .dbml uzantılı bir sayfa daha oluşmasını sağlıyor. Sonra sorgulamak istediğimiz tabloları Server Explorer dan bu sayfa üzerine sürükleyip bırakmalıyız. Biraz sonraki örneklerde Northwind veritabanı ve içinde calisanlar ve siparisler veritabanı kullanılmıştır.
Şimdi öncelikle kod kısmında yeni oluşturduğumuz sayfayı kullanabilmek için bir kopyasını alalım
NorthwindDataContext db = new NorthwindDataContext();

Ex1: Calisanlar tablosundan unvanı Mr. olanları çekelim. Bunu ilk önce bildiğimiz yöntemle yapalım aradaki fark anlaşılsın diye.

string baglanti = "Server=.; Database=Northwind; Integrated Security=SSPI;";
SqlConnection con = new SqlConnection(baglanti);
DataTable calisanlar = new DataTable();
SqlDataAdapter da = new SqlDataAdapter("Select * from calisanlar where unvan = 'Mr.'", con);
da.Fill(calisanlar);
dataGridView1.DataSource = calisanlar;
Şimdi de eşdeğer LINQ sorgusu
var calisanlar = from n in db.Calisanlars
where n.Unvan == "Mr."
select n;
dataGridView1.DataSource = calisanlar;


Ex2: Calisanlar ve siparisler tablosunu birleştirerek calisanID, adSoyad, ulke, unvan ve nakliyeUcretleri alanlarından ilk 10 tanesini alan LINQ

var calisanlar = (from c in db.Calisanlars
from s in db.Siparislers
where c.CalisanID == s.CalisanID
select new { s.CalisanID, adSoyad = c.Ad + " " + c.Soyad, c.Ulke, c.Unvan, s.NakliyeUcreti }).Take(10);


Ex3: Veri tabanına yeni bir kayıt ekleyelim.
Calisanlar calisan = new Calisanlar();
calisan.Ad = "Ahmet";
calisan.Soyad = "Kısa";
calisan.Unvan = "Mr.";
calisan.DogumTarihi = DateTime.Now;
db.Calisanlars.InsertOnSubmit(calisan);
db.SubmitChanges(); //Veri tabanına değişikleri kaydediyor. Adapter nesnesinin Update metodu gibi.

Ex4: Soyadımı yanlış yazmışım onu UPDATE edelim.

Calisanlar calisan = db.Calisanlars.First(c => c.Ad == "Ahmet");
calisan.Soyad = "UZUN";
db.SubmitChanges();


Ex5: Birden çok kayıt olursa UPDATE etmek istediğimiz. Calisanlar tablosunda bolge alanları boş bırakılmış en azından o alanlara boş yazalım.

var calisanlar = from c in db.Calisanlars
select c;
foreach (var calisan in calisanlar)
{
calisan.Bolge = "yok";
}
db.SubmitChanges();


Ex6: Yabancıların yanında benim adım iyi durmadı onu SİLelim.

var silinecek = from c in db.Calisanlars
where c.Ad == "Ahmet" && c.Soyad == "UZUN"
select c;
db.Calisanlars.DeleteAllOnSubmit(silinecek);
db.SubmitChanges();

SQL alan genişliği kullanma

SELECT ID, Turkce, Ingilizce
FROM TE
WHERE (LEN(Ingilizce) < 50)

ArrayList

protected void Page_Load(object sender, EventArgse)

{

List<string>RenkListesi = new List<string>();

RenkListesi.Add("Kırmızı");

RenkListesi.Add("Yeşil");

RenkListesi.Add("Mavi");

RenkListesi.Add("Sarı");

RenkListesi.Add("Turuncu");

CheckBoxList1.DataSource = RenkListesi;

CheckBoxList1.DataBind();

}

2 Mayıs 2009 Cumartesi

PDA Bluetooth device arama

public bool ConnectBlueTooth()

{

string BTMac = "00:01:58:08:3D:ED";

BluetoothAddress BTAddress;

BluetoothClient BTClient = new BluetoothClient();

BluetoothEndPoint BTEndPoint;

Guid spguid = BluetoothService.SerialPort;

BTAddress = BluetoothAddress.Parse(BTMac);

BTEndPoint = new BluetoothEndPoint(BTAddress, spguid);

try

{

BluetoothSecurity.PairRequest(BTAddress, strDevicePassKey);

Application.DoEvents();

BTClient = new BluetoothClient();

BTClient.Connect(BTEndPoint);

return true;

}

catch { return false; }

}

25 Nisan 2009 Cumartesi

DataAdaptor

private void btnDoldur_Click(object sender, System.EventArgs e)
{
OleDbConnection conFriends=new OleDbConnection("Provider=SQLOLEDB;Data Source=localhost;initial catalog=Friends;integrated security=SSPI");
string sqlIfadesi="Select * From Makale";
OleDbDataAdapter daFriends=new OleDbDataAdapter(sqlIfadesi,conFriends);
DataSet ds=new DataSet();
daFriends.Fill(ds);
dgMakale.DataSource=ds;
}


>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>><>>>


private void btnDoldur_Click(object sender, System.EventArgs e)
{
OleDbConnection conFriends=new OleDbConnection("Provider=SQLOLEDB;Data Source=localhost;initial catalog=Friends;integrated security=SSPI");

string sqlIfadesi1="Select * From Makale";
string sqlIfadesi2="Select * From Kitap";

OleDbDataAdapter daMakale=new OleDbDataAdapter(sqlIfadesi1,conFriends);
OleDbDataAdapter daKitap=new OleDbDataAdapter(sqlIfadesi2,conFriends);

DataSet ds=new DataSet();
daMakale.Fill(ds);
daKitap.Fill(ds);
dgMakale.DataSource=ds;
}


>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>



private void btnDoldur_Click(object sender, System.EventArgs e)
{
OleDbConnection conFriends=new OleDbConnection("Provider=SQLOLEDB;Data Source=localhost;initial catalog=Friends;integrated security=SSPI");
OleDbCommand cmd=new OleDbCommand("Makaleler",conFriends);
cmd.CommandType=CommandType.StoredProcedure;
OleDbDataAdapter da=new OleDbDataAdapter(cmd);
DataSet ds=new DataSet();
da.Fill(ds,"TumMakaleler");
dgMakale.DataSource=ds;
}


23 Nisan 2009 Perşembe

PDA Bluetooth

System.IO.Ports.SerialPort sp;

try
{
sp = new System.IO.Ports.SerialPort("COM4");
sp.Open();

Encoding encode ;
encode = System.Text.Encoding.Unicode;
sp.Encoding = encode;
sp.WriteLine("Yazicidan cikti alma");
sp.Close();
}
catch
{ MessageBox.Show("yazıcı portu bulunamadı"); }

pda ler veri çıktısı için com4 ve com 9 u kullanırlar. bunu bluetoot ayarlarından
sen kendin belirliyorsun.

22 Nisan 2009 Çarşamba

N Queen problem

private static int[] NQueenProblem(int N)
{
int[] dizi=new int[N];

int kalan = N % 12;
int control = 0;
int bir_index = 0, uc_index = 0, bes_index = 0;


for (int i = 2; i <= N; i+=2)
{
dizi[control] = i;
control++;
}

if (kalan == 9 || kalan == 3)
{

for (int i = 0; i < control-1; i++)
{
dizi[i] = dizi[i + 1];
}
dizi[control-1] = 2;
}

for (int i = 1; i <= N; i += 2)
{
dizi[control] = i;
control++;
}

if (kalan == 2)
{
// 1 ve 3 un yerını degis, 5 i liste sonuna al

for (int i = 0; i < control; i++)
{
if (dizi[i] == 1)
{
bir_index = i;
}
else if (dizi[i] == 3)
{
uc_index = i;
}
else if (dizi[i] == 5)
{
bes_index = i;
}

}
dizi[bir_index] = 3;
dizi[uc_index] = 1;

for (int i = bes_index; i < control-1; i++)
{
dizi[i] = dizi[i + 1];
}
dizi[control - 1] = 5;
}

if (kalan == 3 || kalan == 9)
{
// 1 ve 3 u liste sonuna al

for (int i = 0; i < control; i++)
{
if (dizi[i] == 1)
{
bir_index = i;
}
else if (dizi[i] == 3)
{
uc_index = i;
}


}

for (int i = bir_index; i < control - 1; i++)
{
dizi[i] = dizi[i + 1];
}
dizi[control - 1] = 1;

for (int i = uc_index; i < control - 1; i++)
{
dizi[i] = dizi[i + 1];
}
dizi[control - 1] = 3;

}

return dizi;
}