Aklımda Kalası Kelimeler

* давайте работать вместе
* Zarf ve Mazruf, Zerafet(xHoyratlık) ile aynı kökten(za-ra-fe) gelir
* Bedesten
* Suç subuta ermiştir - Suç sabit olmuştur

29 Mayıs 2011 Pazar

Öğrenmek üzerine

web.sakarya.edu.tr/~rkutanis/Orgutsel/ogrenme.ppt

Bütün Halinde Yada Parçalara Bölerek Öğrenme


Bir üniversite öğrencisinin ders kitabında bir
üniteye çalışırken o üniteyi başlıklarına dikkat
ederek hızla okuması, daha sonra üzerinde
durulması gereken ayrıntılara tekrar dönmesi ve
tekrar bütüne çalışması gerekmektedir. Üniversite
öğrencileri için en uygun stratejilerden biri,
bütün-parça-bütün stratejisidir.

Geri Bildirim ve Programlanmış Öğrenme


Öğrenmeyi hızlandırmanın ve verimli hale
getirmenin bir diğer yolu da öğrenen kişiye,
öğrenilecek malzemeyi ne denli iyi öğrendiği
konusunda bilgi vermektir. Bu işleme “Geri
Bildirim” denilmektedir. Geri bildirim tekniğinden
yararlanılarak oluşturulan Programlanmış
Öğrenme Tekniğinde öğrenilecek malzeme
kolaydan zora doğru, kavranması zor olmayan
küçük adımlara bölünmüştür.

Okuma ve Anlatma


Öğrenmenin kalıcı ve verimli olabilmesi için,
okuma malzemesinin aktif bir şekilde okunması
gerekir. Okunan malzemenin özünü kavramanın en
kolay yollarından biri de malzemeyi kendi
sözcüklerimizle tekrarlamak ve organize etmektir.

Javascript ile yeni şifre belirleme ve doğrulama


function Validatetextarea(field) {
var valid = "ABCDEFGHIJKLMNOPRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-.";
var temp;

for (var i=0; i<field.length; i++) {
temp = "" + field.substring(i, i+1);
if (valid.indexOf(temp) == "-1") {
return false;
}
}
return true;
}

function checkForm(fp){
if (fp.www.value != "") {
if (Validatetextarea(fp.www.value)==false){
alert("Lütfen Türkçe karakter kullanmayınız.");
fp.www.focus();
fp.www.select();
return false;
}
}

if (fp.password.value == "") {
alert("Lütfen şifrenizi yazınız.");
fp.password.focus();
return false;
}

if (fp.password.value != fp.Repassword.value) {
alert("Girdiğiniz iki şifre bir birinden farklı");
fp.Repassword.focus();
return false;
}


fp.ok.disabled=true;
fp.ok.value='İşlem Yapılıyor...'
}

Javascript ile şifre üretme


function GeneratePassword() {

var length=6;
var sPassword = "";

var noPunction = 1;
var randomLength = 2;

if (randomLength) {
length = Math.random();

length = parseInt(length * 100);
length = (length % 7) + 6
}

for (i=0; i < length; i++) {
numI = getRandomNum();
if (noPunction) { while (checkPunc(numI)) { numI = getRandomNum(); } }
sPassword = sPassword + String.fromCharCode(numI);
}

document.WebSiteAdd.password.value = sPassword;
}

function getRandomNum() {
var rndNum = Math.random()
rndNum = parseInt(rndNum * 1000);
rndNum = (rndNum % 94) + 33;
return rndNum;
}

function checkPunc(num) {
if ((num >=33) && (num <=47)) { return true; }
if ((num >=58) && (num <=64)) { return true; }
if ((num >=91) && (num <=96)) { return true; }
if ((num >=123) && (num <=126)) { return true; }

return false;
}

Android ile DOTNET web servislerine bağlanmak



http://code.google.com/p/ksoap2-android/ adresinden ksoap2-android-assembly-2.5.4-jar-with-dependencies.jar dosyasını indirelim.


package cem.examples.webservicecall;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends Activity {

final static String SOAP_ACTION = "http://tempuri.org/CelsiusToFahrenheit";
final static String METHOD_NAME = "CelsiusToFahrenheit";
final static String NAMESPACE = "http://tempuri.org/";
final static String URL = "http://www.w3schools.com/webservices/tempconvert.asmx";

TextView tv;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.main);
// ---------------------------------------------------
tv = (TextView) findViewById(R.id.editText1);

SoapObject Request = new SoapObject(NAMESPACE, METHOD_NAME);
Request.addProperty("Celsius", "32");

SoapSerializationEnvelope soapEnvelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
soapEnvelope.dotNet = true;

soapEnvelope.setOutputSoapObject(Request);
HttpTransportSE aht = new HttpTransportSE(URL);
aht.call(SOAP_ACTION, soapEnvelope);
String result = "Sonuç: "+(SoapPrimitive) soapEnvelope.getResponse();

tv.setText("Sonuç: " + result);
}
}

28 Mayıs 2011 Cumartesi

Activity ler arasında geçiş


Activity1.java

package cem.examples.activityswitch;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class Activity1 extends Activity implements OnClickListener {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);this.setContentView(R.layout.main);
// ------------------------------------------------------
Button btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener(this);
}

@Override
public void onClick(View v) {
Intent myint = new Intent(v.getContext(),Activity2.class);
startActivityForResult(myint, 0);
}
}


Activity2.java

package cem.examples.activityswitch;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.LinearLayout;

public class Activity2 extends Activity implements OnClickListener {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.activite2);
// --------------------------------------------------------------
Button btnPre = new Button(this);
btnPre.setText("Geriiiii");
// Butonun layout üzerinde alacağı görünüm parametreleri
LayoutParams params = new LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT);
// --------------------------------------------------------------
LinearLayout layout = (LinearLayout) findViewById(R.id.lout);
layout.addView(btnPre, params);
// --------------------------------------------------------------
// Önceki aktiviteye gidelim.
btnPre.setOnClickListener(this);
}

@Override
public void onClick(View v) {
// Call this to set the result that your activity will return to its caller.
setResult(RESULT_OK);
// Call this when your activity is done and should be closed
finish();
}
}


AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="cem.examples.activityswitch" android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="8" />

<application android:icon="@drawable/icon" android:label="@string/app_name">

<activity android:name=".Activity1" android:label="Activite Etiketi"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".Activity2"></activity>
</application>
</manifest>

Toast androidin MessageBox'ı gibi




package cem.examples.activityswitch;

import android.app.Activity;
import android.os.Bundle;
import android.text.Html;
import android.text.Spanned;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class Activity1 extends Activity implements OnClickListener {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.main);
Button btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener(this);
}

@Override
public void onClick(View v) {
String shtml = "İşte "
+ "ekranda"
+ " mesaj"
+ " kutusu";
Spanned sMesaj = Html.fromHtml(shtml);
Toast.makeText(this, sMesaj, Toast.LENGTH_SHORT).show();
}
}



android.widget.Toast

A toast is a view containing a quick little message for the user. The toast class helps you create and show those.

When the view is shown to the user, appears as a floating view over the application. It will never receive focus. The user will probably be in the middle of typing something else. The idea is to be as unobtrusive as possible, while still showing the user the information you want them to see. Two examples are the volume control, and the brief message saying that your settings have been saved.

The easiest way to use this class is to call one of the static methods that constructs everything you need and returns a new Toast object.

Activity ve AndroidManifest.xml ilişkisi ve No Launcher activity found! hatası

Proje oluşturulurken "Main Activity" oluşturulmamışsa AndroidManifest.xml dosyası aşağıdaki gibidir.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="cem.examples.activityswitch" android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="8" />

<application android:icon="@drawable/icon" android:label="@string/app_name">

</application>
</manifest>

Buna göre program AVD ye yüklenirken Console çıktısı şöyle olur:

...
[2011-05-28 13:31:16 - switchActivity] Android Launch!
[2011-05-28 13:31:16 - switchActivity] adb is running normally.
[2011-05-28 13:31:16 - switchActivity] No Launcher activity found!
[2011-05-28 13:31:16 - switchActivity] The launch will only sync the application package on the device!

[2011-05-28 13:31:16 - switchActivity] Performing sync
...

AndroidManifest.xml dosyasına başlatılacak Activity sınıfından türetilmiş bir ***.java dosyasının sınıfını LAUNCH edilecek MAIN action olarak belirtmemiz gerekiyor. Bunu da aşağıdaki <activity> xml elemanını <application> xml elemanının içine koyarak yaparız:

<activity android:name=".Activity1" android:label="Activite Etiketi" android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>

Sonuç:


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="cem.examples.activityswitch" android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="8" />

<application android:icon="@drawable/icon" android:label="@string/app_name">

<activity android:name=".Activity1" android:label="Activite Etiketi"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>

</application>
</manifest>


Android API Level

Platform Version API Level
Android 2.2 8
Android 2.1 7
Android 2.0.16
Android 2.0 5
Android 1.6 4
Android 1.5 3
Android 1.1 2
Android 1.0 1

27 Mayıs 2011 Cuma

Neden android'de + işaretini id nin önüne koyarız?



@+id/degiskenAdi
uygulamanın namespace inde "degiskenAdi" isimli bir "id" oluşturuyorsun demektir.

Bu durumda degiskenAdi uygulamada R.java dosyasına eklenecek.

Artık @id/degiskenAdi diyerek erişebilirsin.
Her ID nin bir integer değere karşılık geldiğini ama objenin bulunduğu layoutun xml'inde string olarak belirtilir.

@android:id/degiskenAdi
android isim uzayında (namespace) tanımlı degiskenAdi'nı işaret ediyorsun demektir(Android resource ID) ve + kullanman gerekmez. Android resource ID ye ulaşmak için kesinlikle "@android:" ile başlaman gerekir.

android:*** Android framework'ündeki *** diye tanımlı şeye referans verdiğini gösterir.




ID

http://developer.android.com/guide/topics/ui/declaring-layout.html

Any View object may have an integer ID associated with it, to uniquely identify the View within the tree. When the application is compiled, this ID is referenced as an integer, but the ID is typically assigned in the layout XML file as a string, in the id attribute. This is an XML attribute common to all View objects (defined by the View class) and you will use it very often. The syntax for an ID, inside an XML tag is:

android:id="@+id/my_button"

The at-symbol (@) at the beginning of the string indicates that the XML parser should parse and expand the rest of the ID string and identify it as an ID resource. The plus-symbol (+) means that this is a new resource name that must be created and added to our resources (in the R.java file). There are a number of other ID resources that are offered by the Android framework. When referencing an Android resource ID, you do not need the plus-symbol, but must add the android package namespace, like so:

android:id="@android:id/empty"

With the android package namespace in place, we're now referencing an ID from the android.R resources class, rather than the local resources class.

In order to create views and reference them from the application, a common pattern is to:

1. Define a view/widget in the layout file and assign it a unique ID:

<button id="@+id/my_button" layout_width="wrap_content" layout_height="wrap_content" text="@string/my_button_text">

2. Then create an instance of the view object and capture it from the layout (typically in the onCreate() method):

Button myButton = (Button) findViewById(R.id.my_button);

Defining IDs for view objects is important when creating a RelativeLayout. In a relative layout, sibling views can define their layout relative to another sibling view, which is referenced by the unique ID.

An ID need not be unique throughout the entire tree, but it should be unique within the part of the tree you are searching (which may often be the entire tree, so it's best to be completely unique when possible).

Eclipse Kısayolları

Kod içinde kısayollarla Property, Contstructor vs oluşturmak

Amaç source içindeki menülere hızlı ulaşmak olunca Alt+Shift+S ile menüye ulaşmak.


Aşağıdaki ekran görüntüsünde "field"lar belli bunların "property"lerini oluşturmak istiyorum.


Getter ve Setter eklenerek propertyler oluşturuldu:


Alt + Shift + S : Shows the Source menu.


Alt + Shift + M : Extract Method.


Alt + Shift + L : Once you have a expression selected (a method call, or whatever), then Alt + Shift + L extracts that to a local variable.

CTRL + I
Corrects indentation.

ALT + Up/Down Arrow
Dikey işaretleme.

CTRL+SHIFT+O
Organize imports.

CTRL+1
Quick fix.

Ctrl + L : Jump to a Line number

CTRL+SHIFT+T
Open Type. Display available types.

CTRL + B
Build.

CTRL + F11
Runs the application.

CTRL + SHIFT + F
Formats code. You can make a beautiful looking code out of a mess with this. It requires a bit of setup, but it is well worth it. You can find its settings under Window->Preferences->Java->Code style->Formatter

CTRL + J
Incremental search.

CTRL + SHIFT + L
Shows you a list of your currently defined shortcut keys.

CTRL+SHIFT+G
Bind this to "Generate getters and setters".




ALT+C
Bind this to SVN/CVS "Commit".

ALT+U
Bind this to SVN/CVS "Update".

CTRL + D
Delete row.

ALT + Left/Right Arrow
Move to the last location you edited.

CTRL+E
Shows you a list of all open editors


CTRL+F6
Use to move between open editors

CTRL+F8
Move between perspectives.


CTRL + M
Maximize or umaximize current tab.

Ref1: http://eclipse.dzone.com/news/effective-eclipse-shortcut-key
Ref2: http://theshyam.com/2009/07/eclipse-productivity-shortcuts/

26 Mayıs 2011 Perşembe

ListView'ı SimpleCursorAdapter ile bağlamak




public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

setContentView(R.layout.main);

ListView lv1 = (ListView) findViewById(R.id.lv1);
lv1.setAdapter(getContactsAdapter());
}

private SimpleCursorAdapter getContactsAdapter() {
Cursor cursor = getCursor();
SimpleCursorAdapter sca = new SimpleCursorAdapter(
this,
R.layout.list_layout,
cursor,
new String[] { "DISPLAY_NAME", "_id" },
new int[] { R.id.name_entry, R.id.number_entry });
return sca;
}

private Cursor getCursor() {
String[] projection = null; // new String[]{
// ContactsContract.Contacts.DISPLAY_NAME,
// ContactsContract.Contacts.PHOTO_ID };

// DISPLAY_NAME LIKE ? AND HAS_PHONE_NUMBER = ?
String selection = ContactsContract.Contacts.DISPLAY_NAME
+ " LIKE ? AND " + ContactsContract.Contacts.HAS_PHONE_NUMBER
+ " = ?";

// Adı A ile başlayan ve telefon numarası olanlar
String[] selectionArgs = new String[] { "A%", "1" };

// Sıralama _ID ye göre tersten olsun
String sort = ContactsContract.Contacts._ID + " DESC";

Cursor cursor = getContentResolver().query(
ContactsContract.Contacts.CONTENT_URI, projection, selection,
selectionArgs, sort);
return cursor;
}

25 Mayıs 2011 Çarşamba

Content Provider ile Telefon Rehberini TextView içinde görüntülemek



TextView içine kriterlere uyan telefondaki kişiler listesini renklendirerek eklemek.


package com.example.telefonlistesi;

import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.text.Html;
import android.widget.TextView;

public class TelefonListesi extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

setContentView(R.layout.main);

TextView tv = (TextView) findViewById(R.id.txt1);

getContacts(tv);
}

public void getContacts(TextView tv) {

String[] projection = null; // new String[]{
// ContactsContract.Contacts.DISPLAY_NAME,
// ContactsContract.Contacts.PHOTO_ID };

// DISPLAY_NAME LIKE ? AND HAS_PHONE_NUMBER = ?
String selection = ContactsContract.Contacts.DISPLAY_NAME
+ " LIKE ? AND " + ContactsContract.Contacts.HAS_PHONE_NUMBER
+ " = ?";

// Adı A ile başlayan ve telefon numarası olanlar
String[] selectionArgs = new String[] { "A%", "1" };

// Sıralama _ID ye göre tersten olsun
String sort = ContactsContract.Contacts._ID + " DESC";

Cursor cursor = getContentResolver().query(
ContactsContract.Contacts.CONTENT_URI,
projection,
selection,
selectionArgs,
sort);

while (cursor.moveToNext()) {

String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
String hasPhone = cursor.getString(cursor.getColumnIndex("HAS_PHONE_NUMBER"));
String displayName = cursor.getString(cursor.getColumnIndex("display_name"));
tv.append("\nID: " + contactId);
tv.append("\tDISP. NAME: " + displayName);

if (Integer.parseInt(hasPhone) > 0) {

Cursor crPhones = getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + contactId,
null,
null);

while (crPhones.moveToNext()) {
String phoneNumber = crPhones.getString(
crPhones.getColumnIndex(
ContactsContract.CommonDataKinds.Phone.NUMBER
)
);
tv.append(Html.fromHtml("\tPHONE: " + phoneNumber+""));
}
crPhones.close();
}
}
}
}

24 Mayıs 2011 Salı

Layouts

Linear Layout




<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation= "vertical"
android:layout_width= "fill_parent"
android:layout_height= "fill_parent" >

<LinearLayout
android:orientation= "horizontal"
android:layout_width= "fill_parent"
android:layout_height= "fill_parent"
android:layout_weight= "1" >
<TextView
android:text= "red"
android:gravity= "center_horizontal"
android:background= "#aa0000"
android:layout_width= "wrap_content"
android:layout_height= "fill_parent"
android:layout_weight= "1" />
<TextView
android:text= "green"
android:gravity= "center_horizontal"
android:background= "#00aa00"
android:layout_width= "wrap_content"
android:layout_height= "fill_parent"
android:layout_weight= "1" />
<TextView
android:text= "blue"
android:gravity= "center_horizontal"
android:background= "#0000aa"
android:layout_width= "wrap_content"
android:layout_height= "fill_parent"
android:layout_weight= "1" />
<TextView
android:text= "yellow"
android:gravity= "center_horizontal"
android:background= "#aaaa00"
android:layout_width= "wrap_content"
android:layout_height= "fill_parent"
android:layout_weight= "1" />
</LinearLayout>

<LinearLayout
android:orientation= "vertical"
android:layout_width= "fill_parent"
android:layout_height= "fill_parent"
android:layout_weight= "1" >
<TextView
android:text= "row one"
android:textSize= "15pt"
android:layout_width= "fill_parent"
android:layout_height= "wrap_content"
android:layout_weight= "1" />
<TextView
android:text= "row two"
android:textSize= "15pt"
android:layout_width= "fill_parent"
android:layout_height= "wrap_content"
android:layout_weight= "1" />
<TextView
android:text= "row three"
android:textSize= "15pt"
android:layout_width= "fill_parent"
android:layout_height= "wrap_content"
android:layout_weight= "1" />
<TextView
android:text= "row four"
android:textSize= "15pt"
android:layout_width= "fill_parent"
android:layout_height= "wrap_content"
android:layout_weight= "1" />
</LinearLayout>

</LinearLayout>



Relative Layout




<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:id="@+id/label"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Type here:"/>
<EditText
android:id="@+id/entry"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="@android:drawable/editbox_background"
android:layout_below="@id/label"/>
<Button
android:id="@+id/ok"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/entry"
android:layout_alignParentRight="true"
android:layout_marginLeft="10dip"
android:text="OK" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toLeftOf="@id/ok"
android:layout_alignTop="@id/ok"
android:text="Cancel" />
</RelativeLayout>



Table Layout





<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:stretchColumns="1">

<TableRow>
<TextView
android:layout_column="1"
android:text="Open..."
android:padding="3dip"/>
<TextView
android:text="Ctrl-O"
android:gravity="right"
android:padding="3dip"/>
</TableRow>

<TableRow>
<TextView
android:layout_column="1"
android:text="Save..."
android:padding="3dip"/>
<TextView
android:text="Ctrl-S"
android:gravity="right"
android:padding="3dip"/>
</TableRow>

<TableRow>
<TextView
android:layout_column="1"
android:text="Save As..."
android:padding="3dip"/>
<TextView
android:text="Ctrl-Shift-S"
android:gravity="right"
android:padding="3dip"/>
</TableRow>

<View
android:layout_height="2dip"
android:background="#FF909090"/>

<TableRow>
<TextView
android:text="X"
android:padding="3dip"/>
<TextView
android:text="Import..."
android:padding="3dip"/>
</TableRow>

<TableRow>
<TextView
android:text="X"
android:padding="3dip"/>
<TextView
android:text="Export..."
android:padding="3dip"/>
<TextView
android:text="Ctrl-E"
android:gravity="right"
android:padding="3dip"/>
</TableRow>

<View
android:layout_height="2dip"
android:background="#FF909090"/>

<TableRow>
<TextView
android:layout_column="1"
android:text="Quit"
android:padding="3dip"/>
</TableRow>
</TableLayout>



Grid View



Ref: http://mono-android.net/Tutorials/Hello_Views/Grid_View

<?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/gridview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:columnWidth="90dp"
android:numColumns="auto_fit"
android:verticalSpacing="10dp"
android:horizontalSpacing="10dp"
android:stretchMode="columnWidth"
android:gravity="center"
/>



Tab Layout


Nasıl yapılır?


List View


2 Mayıs 2011 Pazartesi

PowerShell ve Netsh ile Server, Scope, Leased, Reserved IP ler v.s. alımı


Add-Type -TypeDefinition @"
public struct DHCPDNSConfiguration {
public string Level;
public bool AllowDynamicUpdate;
public string UpdateTrigger;
public bool DiscardStaleRecords;
public bool AllowLegacyClientUpdate;
public int Value;
public override string ToString() {
switch(Value) {
case -1: return (Level=="Server")?"(Default) Update by Client Request With Cleanup":"Inherited from Parent";
case 0: return "Dynamic Updates Disabled";
case 1: return "Update by Client Request Without Cleanup";
case 2: return "Dynamic Updates Disabled";
case 3: return "Update Legacy Clients and by Client Request Without Cleanup";
case 4: return "Dynamic Updates Disabled";
case 5: return "Update by Client Request With Cleanup";
case 6: return "Dynamic Updates Disabled";
case 7: return "Update Legacy Clients and by Client Request With Cleanup";
case 16: return "Dynamic Updates Disabled";
case 17: return "Always Update Clients Without Cleanup";
case 18: return "Dynamic Updates Disabled";
case 19: return "Always Update [Legacy] Clients Without Cleanup";
case 20: return "Dynamic Updates Disabled";
case 21: return "Always Update Clients With Cleanup";
case 22: return "Dynamic Updates Disabled";
case 23: return "Always Update [Legacy] Clients With Cleanup";
default: return "Invalid Configuration";
}
}
}

public struct DHCPIPRange {
public string StartAddress;
public string EndAddress;
public override string ToString() { return StartAddress+" - "+EndAddress; }
}

public struct DHCPOption {
public int OptionID;
public string OptionName;
public string ArrayType;
public string OptionType;
public string[] Values;
public string Level;
public override string ToString() { return OptionName; }
}

public struct DHCPReservation {
public string IPAddress;
public string MACAddress;
public string Scope;
public string Server;
public DHCPOption[] Options;
public DHCPDNSConfiguration DNSConfiguration;
public override string ToString() { return IPAddress; }
}

public struct DHCPLeasedIp {
public string IPAddress;
public string SubnetMask;
public string MACAddress;
public string LeaseExpires;
public string Tip;
public override string ToString() { return IPAddress; }
}

public struct DHCPScope {
public string Address;
public string SubnetMask;
public string Name;
public string Description;
public string State;
public string Server;
public DHCPIPRange[] IPRanges;
public DHCPIPRange[] ExclusionRanges;
public DHCPReservation[] Reservations;
public DHCPLeasedIp[] LeasedIPs;
public int Lease;
public DHCPOption[] Options;
public DHCPDNSConfiguration DNSConfiguration;
public override string ToString() { return Address; }
}

public struct DHCPServer {
public string Name;
public string IPAddress;
public DHCPDNSConfiguration DNSConfiguration;
public int ConflictDetectionAttempts;
public DHCPScope[] Scopes;
public DHCPOption[] Options;
public override string ToString() { return Name; }
}

public struct DHCPScopeStatistics {
public string Scope;
public string Server;
public int TotalAddresses;
public int UsedAddresses;
public int PendingOffers;
public override string ToString() { return Scope; }
}

public struct DHCPServerStatistics {
public string Server;
public int Discovers;
public int Offers;
public int Requests;
public int Acks;
public int Naks;
public int Declines;
public int Releases;
public System.DateTime StartTime;
public int Scopes;
public DHCPScopeStatistics[] ScopeStatistics;
public override string ToString() { return Server; }
}
"@

function Show-DHCPServers {
<#
.Synopsis
Displays a list of all DHCP servers in Active Directory.
.Description
The Show-DHCPServers cmdlet is used to display all DHCP servers registered in Active Directory.
.Outputs
PSObject
.Notes
Name: Show-DHCPServers
Module: Microsoft.DHCP.PowerShell.Admin.psm1
Author: Jeremy Engel
Date: 03.15.2011
#>
$servers = @()
$text = $(Invoke-Expression "cmd /c netsh dhcp show server")
$result = if($text.GetType() -eq [string]){$text}else{$text[($text.Count-1)]}
if($result.Contains("completed successfully")) {
foreach($line in $text) {
if($line.Contains("Server [")) {
$parts = $line.Split("[")
$name = $parts[1].Split("]")[0]
$ip = $parts[2].Split("]")[0]
$server = New-Object PSObject
$server | Add-Member NoteProperty Server($name)
$server | Add-Member NoteProperty IPAddress($ip)
$servers += $server
}
}
return $servers
}
else { Write-Host "ERROR: $result" -ForeGroundColor Red }
}

function Get-DHCPScope {
<#
.Synopsis
Retieves all or specifics scopes for a given server.
.Example
Get-DHCPScope -Server dhcp01.contoso.com
This example retrieves all scopes on dhcp01.contoso.com.
.Example
$server | Get-DHCPScope -Scope 192.168.1.0
Given that $server is the DHCPServer object for dhcp01.contoso.com, this example retrieves the scope 192.168.1.0.
.Description
The Get-DHCPScope cmdlet is used to retieves all or specific DHCP scopes on a given server. The return value for success is one or an array of DHCPScope objects.
.Parameter Server
The value for this parameter can be a DHCPServer object or the name or FQDN of the DHCP server. The designated server must by a valid DHCP server.
.Parameter Scope
The value for this parameter must be the subnet address of the scope.
.Outputs
DHCPScope
.Notes
Name: Get-DHCPScope
Module: Microsoft.DHCP.PowerShell.Admin.psm1
Author: Jeremy Engel
Date: 12.16.2010
#>
Param([Parameter(Mandatory = $true, ValueFromPipeline = $true)][PSObject]$Server,
[Parameter(Mandatory = $false)][string]$Scope
)
$dhcpScopes = @()
$scopeList = @{}
$text = $(Invoke-Expression "cmd /c netsh dhcp server \\$Server show scope")
if($text[2].Contains("Server may not function properly")) { Write-Host "ERROR: $Server is inaccessible or is not a DHCP server." -ForeGroundColor Red; return }
for($i=5;$i -lt $text.Count;$i++) {
if(!$text[$i]) { break }
$parts = $text[$i].Split("-") | %{ $_.Trim() }
$scopeList.Add($parts[0],@($parts[1],$parts[2],$parts[3],$parts[4]))
}

<#
$scopeList:
Name Value
---- -----
10.214.15.128 {255.255.255.128, Disabled, pdawireless, }
10.214.15.0 {255.255.255.128, Active, base, }
#>

foreach($address in $scopeList.Keys) {
if($Scope -and $address -ne $Scope) { continue }
$dhcpScope = New-Object DHCPScope
$dhcpScope.Address = $address
$dhcpScope.Server = $Server.ToString()
$dhcpScope.SubnetMask = $scopeList[$address][0]
$dhcpScope.State = $scopeList[$address][1]
$dhcpScope.Name = $scopeList[$address][2]
$dhcpScope.Description = $scopeList[$address][3]
$dhcpScope.IPRanges = Get-DHCPIPRanges -Server $Server -Scope $address -Type "ipRange"
$dhcpScope.ExclusionRanges = Get-DHCPIPRanges -Server $Server -Scope $address -Type "excluderange"
$dhcpScope.Reservations = Get-DHCPReservation -Server $Server -Scope $address
$dhcpScope.LeasedIPs = Get-DHCPLeasedIps -Server $Server -Scope $address
$lease = Get-DHCPOption -Owner $dhcpScope -OptionID 51 -Force
$dhcpScope.Lease = if($lease){$lease.Values[0]}else{0}
$dhcpScope.Options = Get-DHCPOption -Owner $dhcpScope
$dhcpScope.DNSConfiguration = Get-DHCPDNSConfiguration -Owner $dhcpScope
$dhcpScopes += $dhcpScope
}
return $dhcpScopes
<#

Address : 10.214.15.128
SubnetMask : 255.255.255.128
Name : pdawireless
Description :
State : Disabled
Server : 10.214.15.12
IPRanges : {10.214.15.140 - 10.214.15.180}
ExclusionRanges :
Reservations :
Lease : 691200
Options : {Router, DNS Domain Name, DNS Servers}
DNSConfiguration : Inherited from Parent

Address : 10.214.15.0
SubnetMask : 255.255.255.128
Name : base
Description :
State : Active
Server : 10.214.15.12
IPRanges : {10.214.15.21 - 10.214.15.99}
ExclusionRanges :
Reservations :
Lease : 691200
Options : {Router, DNS Domain Name, DNS Servers}
DNSConfiguration : Inherited from Parent

#>
}

function Get-DHCPDNSConfiguration {
<#
.Synopsis
Retrieves the DNS update configuration for a given DHCP object.
.Example
Get-DHCPDNSConfiguration -Owner dhcp01.contoso.com/192.168.1.0/192.168.1.237
This example retrieves the DNS update configuration for the reservation 192.168.1.237 in the scope of 192.168.1.0 on server dhcp01.contoso.com.
.Description
The Get-DHCPDNSConfiguration cmdlet is used to retrieve the DNS update configuration for a given DHCP server, scope, or reservation. If no configuration is defined, then the configuration from its parent is inherited, except at the server level, which uses the default configuration.
.Parameter Owner
The value for this parameter can be a DHCPServer, DHCPScope, or DHCPReservation object. It can also be a string representation of these objects, defined thus:
ServerNameOrFQDN
ServerNameOrFQDN/ScopeAddress
ServerNameOrFQDN/ScopeAddress/ReservationAddress
.Outputs
DHCPDNSConfiguration
.Notes
Name: Get-DHCPDNSConfiguration
Module: Microsoft.DHCP.PowerShell.Admin.psm1
Author: Jeremy Engel
Date: 04.22.2011
#>
Param([Parameter(Mandatory = $true, ValueFromPipeline = $true)][PSObject]$Owner)
if($Owner.GetType() -eq [string]) {
switch($Owner.Split("/").Count) {
1 { $level = "Server" }
2 { $level = "Scope" }
3 { $level = "Reservation" }
default { return }
}
}
else { $level = $Owner.GetType().ToString().Substring(4) }
if(!($option = Get-DHCPOption -Owner $Owner -OptionID 81 -Force)) { return }
$value = [int]$option.Values[0]
$dnsConfig = New-Object DHCPDNSConfiguration
$dnsConfig.Level = $level
$dnsConfig.Value = $value
if($value -eq -1) {
if($level -ne "Server") {
if($Owner.GetType() -eq [string]) {
$parts = $Owner.Split("/")
$Owner = $parts[0..($parts.Count-2)] -Join "/"
}
elseif($Owner.GetType() -eq [DHCPReservation]) { $Owner = "$($Owner.Server)/$($Owner.Scope)" }
elseif($Owner.GetType() -eq [DHCPScope]) { $Owner = $Owner.Server }
else { return }
$dnsConfig = Get-DHCPDNSConfiguration -Owner $Owner
$dnsConfig.Level = $level
return $dnsConfig
}
else { $value = 5 }
}
if($value -ge 16) {
$dnsConfig.UpdateTrigger = "Always"
$value -= 16
}
else { $dnsConfig.UpdateTrigger = "ClientRequest" }
if($value -ge 4) {
$dnsConfig.DiscardStaleRecords = $true
$value -= 4
}
else { $dnsConfig.DiscardStaleRecords = $false }
if($value -ge 2) {
$dnsConfig.AllowLegacyClientUpdate = $true
$value -= 2
}
else { $dnsConfig.AllowLegacyClientUpdate = $false }
$dnsConfig.AllowDynamicUpdate = if($value -eq 1){$true}else{$false}
return $dnsConfig
}

function Get-DHCPIPRanges {
Param([Parameter(Mandatory = $false)][PSObject]$Server,
[Parameter(Mandatory = $true, ValueFromPipeline = $true)][PSObject]$Scope,
[Parameter(Mandatory = $true)][string]$Type
)
$ipranges = @()
if($Scope.GetType() -eq [DHCPScope] -and !$Server) { $Server = $Scope.Server }
$text = $(Invoke-Expression "cmd /c netsh dhcp server \\$Server scope $Scope show $Type")
$result = if($text.GetType() -eq [string]){$text}else{$text[($text.Count-1)]}
if($result.Contains("The command needs a valid Scope IP Address")) { Write-Host "ERROR: $Scope is not a valid scope on $Server." -ForeGroundColor Red; return }
if($result.Contains("Server may not function properly")) { Write-Host "ERROR: $Server is inaccessible or is not a DHCP server." -ForeGroundColor Red; return }
for($i=6;$i -lt $text.Count;$i++) {
if(!$text[$i]) { break }
$parts = $text[$i].Split("-") | %{ $_.Trim() }
$ipRange = New-Object DHCPIPRange
$ipRange.StartAddress = $parts[0]
$ipRange.EndAddress = $parts[1]
$ipRanges += $ipRange
}
return $ipRanges
}

function Get-DHCPOption {
<#
.Synopsis
Retrieves all or specific DHCP options and their values for a given level.
.Example
Get-DHCPOption -Owner dhcp01.contoso.com/192.168.1.0/192.168.1.237
This example retrieves all the options set for the reservation 192.168.1.237 in the scope of 192.168.1.0 on server dhcp01.contoso.com.
.Example
$scope | Get-DHCPOption -OptionID 3
Given that $scope is the DHCPScope object for subnet 192.168.1.0 on dhcp01.contoso.com, this examples retrieves scope option 3, the gateway address.
.Example
Get-DHCPOption -Owner $server -OptionID 81 -Force
Given that $server is the DHCPServer object for dhcp01.contoso.com, this example retrieves server option 81, dynamic dns configuration. For more information on why the -Force parameter was needed, please read its parameter
description under -full.
.Description
The Get-DHCPOption cmdlet is used to retrieve all or specific standard DHCP options and their values for a given server, scope, or reservation. Non-standard classes (eg: BOOTP) are not currently being recorded. The return value for success is one or an array of DHCPOption objects.
.Parameter Owner
The value for this parameter can be a DHCPServer, DHCPScope, or DHCPReservation object. It can also be a string representation of these objects, defined thus:
ServerNameOrFQDN
ServerNameOrFQDN/ScopeAddress
ServerNameOrFQDN/ScopeAddress/ReservationAddress
.Parameter OptionID
The value for this parameter must be the id of a valid DHCP option as listed by Get-DHCPOptionDefinitions.
.Parameter Force
This switch parameter is only needed if you want to retrieve options 51 (lease time in seconds) or 81 (int value for the dynamic dns configuration). These are otherwise not returned as their values are expressed elsewhere.
.Outputs
DHCPOption
.Notes
Name: Get-DHCPOption
Module: Microsoft.DHCP.PowerShell.Admin.psm1
Author: Jeremy Engel
Date: 12.16.2010
#>
Param([Parameter(Mandatory = $true, ValueFromPipeline = $true)][PSObject]$Owner,
[Parameter(Mandatory = $false)][int]$OptionID,
[Parameter(Mandatory = $false)][switch]$Force
)
$server = $null
$scope = $null
$reservation = $null
if($Owner.GetType() -eq [DHCPServer]) { $server = $Owner.Name }
elseif($Owner.GetType() -eq [DHCPScope]) {
$server = $Owner.Server
$scope = $Owner.Address
}
elseif($Owner.GetType() -eq [DHCPReservation]) {
$server = $Owner.Server
$scope = $Owner.Scope
$reservation = $Owner.IPAddress
}
else {
$parts = $Owner.ToString().Split("/")
$server = $parts[0]
if($parts.Count -gt 1) { $scope = $parts[1] }
if($parts.Count -gt 2) { $reservation = $parts[2] }
}
$command = if($scope){"\\$server scope $scope show optionvalue"}else{"\\$server show optionvalue"}
if($reservation) { $command = "\\$server scope $scope show reservedoptionvalue $reservation" }
$text = $(Invoke-Expression "cmd /c netsh dhcp server $command")
$result = if($text.GetType() -eq [string]){$text}else{$text[($text.Count-1)]}
if($result.Contains("Server may not function properly")) { Write-Host "ERROR: $server is inaccessible or is not a DHCP server." -ForeGroundColor Red; return }
if($result.Contains("The command needs a valid Scope IP Address")) { Write-Host "ERROR: $scope is not a valid scope on $server." -ForeGroundColor Red; return }
if($result.Contains("client is not a reserved")) { Write-Host "ERROR: $reservation is not a valid reservation in $scope on $server." -ForeGroundColor Red; return }
$options = @()
$work = @{}
$optiondefs = Get-DHCPOptionDefinitions -Server $server
$option = New-Object PSOBject
$option | Add-Member NoteProperty OptionName("DNS Configuration")
$option | Add-Member NoteProperty ArrayType("UNARY")
$option | Add-Member NoteProperty OptionType("DWORD")
$optiondefs.Add(81,$option)
$id = $null
$block = $false
for($i=0;$i -lt $text.Count;$i++) {
if($text[$i] -eq "Command completed successfully.") {
if(!!$id) {
$option = New-Object DHCPOption
$option.OptionID = $id
$option.OptionName = $optiondefs[$id].OptionName
$option.ArrayType = $optiondefs[$id].ArrayType
$option.OptionType = $optiondefs[$id].OptionType
$option.Values += $work[$optiondefs[$id].OptionName]
$option.Level = if($reservation){"Reservation"}elseif($scope){"Scope"}else{"Server"}
$options += $option
}
}
if($block) {
if($text[$i].Contains("DHCP Standard Options")) { $block = $false }
continue
}
if($text[$i].Contains("For vendor class") -or $text[$i].Contains("For user class")) { $block = $true; continue }
if($text[$i].Contains("OptionId")) {
if(!!$id) {
$option = New-Object DHCPOption
$option.OptionID = $id
$option.OptionName = $optiondefs[$id].OptionName
$option.ArrayType = $optiondefs[$id].ArrayType
$option.OptionType = $optiondefs[$id].OptionType
$option.Values += $work[$optiondefs[$id].OptionName]
$option.Level = if($reservation){"Reservation"}elseif($scope){"Scope"}else{"Server"}
$options += $option
}
$id = [int]($text[$i].Split(":")[1].Trim())
if($OptionID -and $OptionID -ne $id) { $id = $null; continue }
if(!$Force -and ($id -eq 81 -or $id -eq 51)) { $id = $null; continue }
$work.Add($optiondefs[$id].OptionName,$null)
}
elseif(!$id) { continue }
else {
if(!($text[$i].Contains("Option Element Value"))) { continue }
$desc = $optiondefs[$id].OptionName
$type = $optiondefs[$id].ArrayType
$values = $work[$desc]
$val = $text[$i].Split("=")[1].Trim()
if($type-eq"ARRAY") { $values += @($val) }
else { $values = $val }
$work[$desc] = $values
}
}
if($Force -and !($options | Where-Object { $_.OptionID -eq 81 }) -and $OptionID -eq 81) {
$id = 81
$option = New-Object DHCPOption
$option.OptionID = $id
$option.OptionName = $optiondefs[$id].OptionName
$option.ArrayType = $optiondefs[$id].ArrayType
$option.OptionType = $optiondefs[$id].OptionType
$option.Values += -1
$option.Level = if($reservation){"Reservation"}elseif($scope){"Scope"}else{"Server"}
$options += $option
}
return $options
}

function Get-DHCPOptionDefinitions {
<#
.Synopsis
Retrieves all DHCP options defined on a given server.
.Example
Get-DHCPOptionDefinitions -Server dhcp01.contoso.com
This example retrieves all the options defined on server dhcp01.contoso.com.
.Example
$server | Get-DHCPOptionDefinitions
Given that $server is the DHCPServer object for dhcp01.contoso.com, this example accomplishes the same as the one in Example 1.
.Description
The Get-DHCPOptionDefinitions cmdlet is used to retrieve all DHCP options defined on a given server.
.Parameter Server
The value for this parameter can be a DHCPServer object or the name or FQDN of the DHCP server. The designated server must by a valid DHCP server.
.Outputs
HashTable
.Notes
Name: Get-DHCPOptionDefinitions
Module: Microsoft.DHCP.PowerShell.Admin.psm1
Author: Jeremy Engel
Date: 12.16.2010
#>
Param([Parameter(Mandatory = $true, ValueFromPipeline = $true)][PSObject]$Server)
$options = @{}
$text = $(Invoke-Expression "cmd /c netsh dhcp server \\$Server show optiondef")
if($text[2].Contains("Server may not function properly")) { Write-Host "ERROR: $Server is inaccessible or is not a DHCP server." -ForeGroundColor Red; return }
for($i=7;$i -lt $text.Count;$i++) {
if(!$text[$i]) { break }
$parts = $text[$i].Split("-") | %{ $_.Trim() }
if($parts[2] -eq "to") {
$parts[1] = $parts[1]+"-"+$parts[2]+"-"+$parts[3]
$parts[2] = $parts[4]
$parts[3] = $parts[5]
}
$option = New-Object PSOBject
$option | Add-Member NoteProperty OptionName($parts[1])
$option | Add-Member NoteProperty ArrayType($parts[2])
$option | Add-Member NoteProperty OptionType($parts[3])
if($options.Keys -notcontains [int]$parts[0]) { $options.Add([int]$parts[0],$option) } #Needed if clause for some weird funkiness on Windows 2003 servers
}
return $options
}

function Get-DHCPReservation {
<#
.Synopsis
Retieves all or specific DHCP reservations for a given scope.
.Example
Get-DHCPReservation -Server dhcp01.contoso.com -Scope 192.168.1.0
This example retrieves all reservations in the 192.168.1.0 scope on dhcp01.contoso.com.
.Example
$scope | Get-DHCPReservation -IPAddress 192.168.1.237
Given that $scope is the DHCPScope object for subnet 192.168.1.0 on dhcp01.contoso.com, this example retrieves the 192.168.1.237 reservation.
.Description
The Get-DHCPReservation cmdlet is used to retieves all or specific DHCP reservations for a given scope. The return value for success is one or an array of DHCPReservation objects.
.Parameter Server
The value for this parameter can be a DHCPServer object or the name or FQDN of the DHCP server. The designated server must by a valid DHCP server.
.Parameter Scope
The value for this parameter can be a DHCPScope object or the subnet address of the scope. If entering the subnet address, the Server parameter must be defined and be the host of this scope.
.Parameter IPAddress
The value for this parameter must be in an IP address string format (ie: 0.0.0.0).
.Outputs
DHCPReservation
.Notes
Name: Get-DHCPReservation
Module: Microsoft.DHCP.PowerShell.Admin.psm1
Author: Jeremy Engel
Date: 12.16.2010
#>
Param([Parameter(Mandatory = $false)][PSObject]$Server,
[Parameter(Mandatory = $true, ValueFromPipeline = $true)][PSObject]$Scope,
[Parameter(Mandatory = $false)][string]$IPAddress
)
$reservations = @()
if($Scope.GetType() -eq [DHCPScope] -and !$Server) { $Server = $Scope.Server }
$text = $(Invoke-Expression "cmd /c netsh dhcp server \\$Server scope $Scope show reservedip")
$result = if($text.GetType() -eq [string]){$text}else{$text[($text.Count-1)]}
if($result.Contains("The command needs a valid Scope IP Address")) { Write-Host "ERROR: $Scope is not a valid scope on $Server." -ForeGroundColor Red; return }
if($result.Contains("Server may not function properly")) { Write-Host "ERROR: $Server is inaccessible or is not a DHCP server." -ForeGroundColor Red; return }
for($i=7;$i -lt $text.Count;$i++) {
if(!$text[$i]) { break }
$parts = $text[$i].Split("-") | %{ $_.Trim() }
if($IPAddress -and $parts[0] -ne $IPAddress) { continue }
$reservation = New-Object DHCPReservation
$reservation.IPAddress = $parts[0]
$reservation.MACAddress = [string]::Join("-",$parts[1..6])
$reservation.Scope = $Scope
$reservation.Server = $Server
$reservation.Options = Get-DHCPOption -Owner $reservation
$reservation.DNSConfiguration = Get-DHCPDNSConfiguration -Owner $reservation
$reservations += $reservation
}
return $reservations
}

function Get-DHCPLeasedIps {
<#
.Synopsis
Retieves all or specific DHCP leased IP lists for a given scope.
.Example
Get-DHCPReservation -Server dhcp01.contoso.com -Scope 192.168.1.0
This example retrieves all reservations in the 192.168.1.0 scope on dhcp01.contoso.com.
.Example
$scope | Get-DHCPReservation -IPAddress 192.168.1.237
Given that $scope is the DHCPScope object for subnet 192.168.1.0 on dhcp01.contoso.com, this example retrieves the 192.168.1.237 reservation.
.Description
The Get-DHCPReservation cmdlet is used to retieves all or specific DHCP reservations for a given scope. The return value for success is one or an array of DHCPReservation objects.
.Parameter Server
The value for this parameter can be a DHCPServer object or the name or FQDN of the DHCP server. The designated server must by a valid DHCP server.
.Parameter Scope
The value for this parameter can be a DHCPScope object or the subnet address of the scope. If entering the subnet address, the Server parameter must be defined and be the host of this scope.
.Parameter IPAddress
The value for this parameter must be in an IP address string format (ie: 0.0.0.0).
.Outputs
DHCPReservation
.Notes
Name: Get-DHCPReservation
Module: Microsoft.DHCP.PowerShell.Admin.psm1
Author: Jeremy Engel
Date: 12.16.2010
#>
Param([Parameter(Mandatory = $false)][PSObject]$Server,
[Parameter(Mandatory = $true, ValueFromPipeline = $true)][PSObject]$Scope,
[Parameter(Mandatory = $false)][string]$IPAddress
)
$leasedIPs = @()
if($Scope.GetType() -eq [DHCPScope] -and !$Server) { $Server = $Scope.Server }
$text = $(Invoke-Expression "cmd /c netsh dhcp server \\$Server scope $Scope show clients")
$result = if($text.GetType() -eq [string]){$text}else{$text[($text.Count-1)]}
if($result.Contains("The command needs a valid Scope IP Address")) { Write-Host "ERROR: $Scope is not a valid scope on $Server." -ForeGroundColor Red; return }
if($result.Contains("Server may not function properly")) { Write-Host "ERROR: $Server is inaccessible or is not a DHCP server." -ForeGroundColor Red; return }
for($i=8;$i -lt $text.Count;$i++) {
if(!$text[$i]) { break }
$parts = $text[$i].Split("-") | %{ $_.Trim() }
if($IPAddress -and $parts[0] -ne $IPAddress) { continue }
$leased = New-Object DHCPLeasedIp
$leased.IPAddress = $parts[0]
$leased.SubnetMask = $parts[1]
$leased.MACAddress = [string]::Join("-",$parts[2..7])
$leased.LeaseExpires = $parts[8]
$leased.Tip = $parts[9]
$leasedIPs += $leased
}
return $leasedIPs
}



$servers = Show-DHCPServers
$scopes = Get-DHCPScope -Server $servers[0].IPAddress
$rezervasyonlar = $scopes[0].Reservations
$cem = "Topkaya"

1 Mayıs 2011 Pazar

PowerShell script ile Netsh üzerinden OptionValue değerlerini öğrenmek

PS C:\hp\Debug> $(Invoke-Expression "cmd /c netsh dhcp server \\10.130.214.13 scope 10.214.102.0 show optionvalue")

Changed the current scope context to 10.214.102.0 scope.

Options for Scope 10.214.102.0:

DHCP Standard Options :
General Option Values:
OptionId : 15
Option Value:
Number of Option Elements = 1
Option Element Type = STRING
Option Element Value = fresenius.com.tr
OptionId : 51
Option Value:
Number of Option Elements = 1
Option Element Type = DWORD
Option Element Value = 691200
OptionId : 6
Option Value:
Number of Option Elements = 2
Option Element Type = IPADDRESS
Option Element Value = 10.130.214.13
Option Element Value = 10.130.214.12
OptionId : 3
Option Value:
Number of Option Elements = 1
Option Element Type = IPADDRESS
Option Element Value = 10.214.102.3
Command completed successfully.
PS C:\hp\Debug>

option value = 51 kiralama süresini saniye cinsinden verir.

PowerShell script ile Netsh'ı çağırmak ve kiralanmış IP adreslerini öğrenmek

Daha iyi powershell script için adres: http://gallery.technet.microsoft.com/scriptcenter/05b1d766-25a6-45cd-a0f1-8741ff6c04ec



PS C:\hp\Debuggt; $(Invoke-Expression "cmd /c netsh dhcp server \\10.130.214.13 scope 10.214.102.0 show clients")

Changed the current scope context to 10.214.102.0 scope.

Type : N - NONE, D - DHCP B - BOOTP, U - UNSPECIFIED, R - RESERVATION IP
==================================================================================
IP Address - Subnet Mask - Unique ID - Lease Expires -Type
==================================================================================

10.214.102.20 - 255.255.255.0 - 00-1c-bf-b7-d3-b8 -07.05.2011 17:54:59 -D
10.214.102.21 - 255.255.255.0 - 00-21-6b-61-19-fe -07.05.2011 14:45:01 -D
10.214.102.22 - 255.255.255.0 - 00-21-6b-5f-9e-72 -07.05.2011 11:51:58 -D
10.214.102.23 - 255.255.255.0 - 00-21-6b-1d-6a-5c -07.05.2011 18:28:48 -D
10.214.102.24 - 255.255.255.0 - ac-81-12-26-57-06 -07.05.2011 13:57:07 -D
10.214.102.25 - 255.255.255.0 -ac-81-12-1b-9f-59 - NEVER EXPIRES -U
10.214.102.26 - 255.255.255.0 - 00-21-6b-5f-c5-3c -08.05.2011 20:12:02 -D
10.214.102.27 - 255.255.255.0 - 00-22-fa-ee-00-58 -07.05.2011 18:44:30 -D
10.214.102.28 - 255.255.255.0 - 00-26-82-56-95-78 -08.05.2011 11:29:41 -D
10.214.102.30 - 255.255.255.0 - 00-27-10-24-81-b4 -05.05.2011 14:46:26 -D
10.214.102.31 - 255.255.255.0 - 58-94-6b-87-22-98 -07.05.2011 12:38:43 -D
10.214.102.32 - 255.255.255.0 - 00-26-c6-59-c0-22 -07.05.2011 22:04:10 -D
10.214.102.33 - 255.255.255.0 - ac-81-12-0b-57-75 -07.05.2011 08:29:14 -D

DHCP Lease (IP Kiralama) süresini öğrenme ve değiştirme


netsh dhcp server scope>help
list - Lists all the commands available.
dump - Dumps scope configuration to a text file.
help - Displays help.
? - Displays help.
add - Adds a configuration entry to a table.
delete - Deletes a configuration entry from a table.
initiate - Initiates an operation.
set - Sets configuration information.
show - Displays information.

netsh dhcp server scope>show optionvalue 51

Options for Scope 10.214.102.0:

DHCP Standard Options :
General Option Values:
OptionId : 15
Option Value:
Number of Option Elements = 1
Option Element Type = STRING
Option Element Value = fresenius.com.tr
OptionId : 51
Option Value:
Number of Option Elements = 1
Option Element Type = DWORD
Option Element Value = 691200
OptionId : 6
Option Value:
Number of Option Elements = 2
Option Element Type = IPADDRESS
Option Element Value = 10.130.214.13
Option Element Value = 10.130.214.12
OptionId : 3
Option Value:
Number of Option Elements = 1
Option Element Type = IPADDRESS
Option Element Value = 10.214.102.3
Command completed successfully.
// 51 bizim dhcp lease süresi. bu değeri değiştirmek için aşağıdaki gibi yazarız
netsh dhcp server scope>set optionvalue 51 DWORD 3600

691200 değeri = 8 gün = 8 x 24 saat = 8 x 24 x 3600(saniye)

Netsh ile DHCP den bilgi çekmek

Tabi cmd yi çalıştırırken "runas Administrator" olursa daha iyi olur.

c:\Netsh (Enter)
netsh>dhcp (Enter)
netsh dhcp>server (Enter)
netsh dhcp server>show server(Enter)


netsh dhcp server server> show scope(Enter)

netsh dhcp server server>scope 10.214.102.0 (Enter)

netsh dhcp server server scope> show clients (Enter)

Marshalling ve InteropServices üzerine güzel bir yazı

Referans: www.rupj.net/portfolio/docs/dws-writeup.pdf


3.1 Interop

The Interop software layer, known in the code base as the namespace Unf.Dhcp.Smo.Interop, is the foundation of DHCP Web Services. The DHCP server API defines functions, structures, and enumerations used to manage a DHCP server. Because the DHCP server API is in C and this project was written in C# .NET, this layer was created, as an interoperability interface between the two. This layer can also be referred to as a p/invoke wrapper. This wrapper defines C# prototypes, structures, and enumerations, to mimic its C library counterpart, using a .NET utility namespace called System.Runtime.InteropServices. Classes within this namespace allow .NET managed code to make external calls to C functions, which are exported in Dynamic Link Libraries (DLLs). The namespace contains a Marshal class that facilitates data type conversions to and from both C platform dependent types and .NET Framework types. This process is known as marshalling. The Marshal class also contains functions that allocate unmanaged memory, a normal operation when developing in C. When using p/invoke, developers have to manage memory, as if they were developing in C, since .NET does not provide a garbage collection system for this type of service. This is why a memory management class was created, called MemManager. MemManager manages memory allocations for p/invoke calls, along with the proper release of that memory, after use. In addition, the .NET Marshal class automatically does some marshaling of data types, so developers do not have to worry about memory allocations or type conversions in certain situations. For example, a C char* is automatically converted to a .NET String type, by the Marshal class. The Marshal class does not automatically handle structures, unions, and most pointer types. Instead, it provides helper functions to facilitate the marshaling of these types. Unions are one of the more difficult structures with which to deal, because C# does not have a construct for a union. However, the Marshal class does define special attributes to help mimic a C union, the most important of which is the FieldOffset attribute. This attribute allows a developer to define the byte location where a structure member starts, relative to the explicit size of that structure in memory. With this mechanism, a developer can make all union members start at the same byte offset, thus mimicking a C union in C#. This technique was used on more than one occasion in the Interop layer, since the DHCP server API defines a couple of structures containing unions.

By using the previously described techniques of p/invoke, a C# wrapper class was created. It contains all known and documented functions exported by the DHCP server API DLL, thus allowing an exchange of data between C and C#. C# extern prototypes of the DHCPSAPI functions were created in the NativeMethods class within the Unf.Dhcp.Smo.Interop namespace. For example, the NativeMethods.DhcpSetOptionValueV5 method directly references its counterpart in the external DHCPSAPI DLL. When a call to this method occurs, the system marshals the C# parameters to C data types, pushes them onto the call stack, and then executes the DHCPSAPI DLL C function. C# structures, located in the NativeStructs.cs source file, were created to mimic the C function parameters used by DHCPSAPI. NativeMethods, MemManager, and native structures make up the Unf.Dhcp.Smo.Interop namespace. These are used by the next layer, DHCP Server Management Objects, which abstracts low-level details of the C like types and functions.