Salı, Mart 31, 2009

YTÜ Semineri ardından

Merhabalar,

Bu hafta sonu güzel bir etkinliği daha geride bıraktık. Yıldız Teknik Üniversitesinde gerçekleşen etkinlikte sql server ‘dan crm ‘e, WPF ‘den MultiPoint ‘e ve daha bir çok konuya değinildi. Seminer içeriğinde bende WPF ‘i anlattım. Genel olarak izleyicilerin görüşleri oldukça güzeldi. Seminer sonunda katılımcıların gözlerinin içinin güldüğünü görmek benim içinde oldukça iyi bir durumdur.

Seminerde anlattığım sunuya linkten erişebilirsiniz. Bir sonraki seminerde sizlerle görüşmek üzere, iyi çalışmalar…

Salı, Mart 24, 2009

YazGeliştir Seminerleri @İstanbul - Yıldız Teknik Üniversitesi

Merhabalar,

Benim konuşmacıları arasında olduğum Yazgelistir ekibi 28 Mart Cumartesi günü Yıldız Teknik Üniversitesinde olacağız. Benim anlatacağım konu Windows Presentation Foundation. Etkinlik ile ilgili duyuruyu yazının devamında okuyabilirsiniz. Katılımlarınızı büyük bir merak ve heyacanla bekliyoruz…

Duyuru;

Yazgeliştir, 2009 seminer turuna Yıldız Teknik Üniversitesi'nden devam ediyor. 28 Mart 2009 Cumartesi günü tüm gün sürecek olan, altı konuşmacının yedi ayrı konuyu anlatacağı seminerlerde sizde yerinizi alın!
Etkinlik Tarihi: 28 Mart 2009 Cumartesi

Etkinlik Programı:

09:30-10:15:    Mustafa Acungil - İş zekası nedir?
10:15-10:30:    ARA
10:30-11:15:    Mustafa Acungil - SQL Server 2008 İle Gelen Yeni Veri Tipleri
11:15-11:30:    ARA
11:30-12:15:    Volkan Korkmaz - Dynamics CRM 4.0
12:15-13:00:    YEMEK ARASI
13:00-13:45:    Turhal Temizer - Windows Presentation Foundation
13:45-14:00:    ARA
14:00-14:45:    Burak Batur - Microsoft Office SharePoint Server 2007
14:45-15:00:    ARA
15:00-15:45:    Daron Yöndem - MultiPoint Programlama
15:45-16:00:    ARA
16:00-16:45:    Emre Coşkun - Composite WPF

Etkinlik Yeri :
Yıldız Teknik Üniversitesi Beşiktaş Kampüsü, YTÜ C Blok Konferans Salonu

Pazar, Mart 22, 2009

Internet Explorer 8

Uzun bir beta sürecinin ardından çıkan RC1 sürümü ile kullanıcıların yüzünü güldürmeyi başaran yeni nesil web tarayıcısı Internet Explorer 8'in nihai sürümü yayımlandı. Tarayıcı, geçerli web standartlarını destekleyen ilk Microsoft tarayıcısı olma unvanını taşıyor.

Görsel RSS olarak tanımlanabilecek WebSlices, gezdiğiniz sayfadan çıkmadan ek bilgi edinmenizi sağlayan Accelerators ve gizli sörf yapmayı mümkün kılan InPrivate Mode gibi yeni özellikler sunan web tarayıcısı, 6 thread'li yeni motoru ile önceki IE sürümlerine göre çok daha hızlı sayfa gösterimleri vaat ediyor.

Aşağıdaki linklerden web tarayıcısını Windows XP ve Windows Vista işletim sisteminde çalışan sürümleriniburadan indirebilirsiniz.

Cumartesi, Mart 21, 2009

ASP.NET MVC Yayınlandı

ASP.NET MVC yayınlandı. ASP.NET MVC ile ilgili detaylı bilgi almak, themalara erişmek ve eğitim içeriğine erişebilmek için,
http://www.asp.net/mvc/

ASP.NET MVC'yi indimek için de aşağıdaki adresi kullanabilirsiniz
Link

Perşembe, Mart 19, 2009

WPF AutoComplete Folder TextBox

Introduction

This article demos how to create a TextBox that can suggest items at runtime based on input, in this case, disk drive folders.

Background

There is a number of AutoComplete TextBox implementation around but some don't support data binding, others don't support runtime items polling and so on. After lot of research and Googling, I decided to write my own instead of continue looking for one.

My Design process

My first design is based on ComboBox, I copy the default template and remove the drop down button and develop from that, it doesnt work because combobox have it's own autocomplete mechanism which will change the selection of textbox when Items is changed, it's not designed for Items that change at realtime.

So the second design is based on TextBox, I create the following style :

<Style x:Key="autoCompleteTextBox" TargetType="{x:Type TextBox}"><Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type TextBoxBase}"> <Grid x:Name="root"> <ScrollViewer Margin="0" x:Name="PART_ContentHost"/> <Popup x:Name="PART_Popup" AllowsTransparency="true"

Placement="Bottom" IsOpen="False" PopupAnimation="{DynamicResource

{x:Static SystemParameters.ComboBoxPopupAnimationKey}}"> <ListBox x:Name="PART_ItemList" SnapsToDevicePixels

="{TemplateBinding SnapsToDevicePixels}" VerticalContentAlignment="Stretch" HorizontalContentAlignment

="Stretch" KeyboardNavigation.DirectionalNavigation="Contained" /> </Popup> </Grid> </ControlTemplate> </Setter.Value> </Setter> </Style>

and then create a custom control and hook the style to it :

<TextBox x:Class="QuickZip.Controls.SelectFolderTextBox" Style="{DynamicResource autoCompleteTextBox}" >...
</TextBox>

PART_ContentHost is actually a control that TextBoxView, it is required for TextBox template
(with that name), or the control won't function, the another two part (PART_Popup and PART_ItemList)
is defined so I can use them in the custom control :

public partial class SelectFolderTextBox : TextBox

{

Popup Popup { get { return this.Template.FindName("PART_Popup", this) as Popup; } }

ListBox ItemList { get { return this.Template.FindName("PART_ItemList", this) as ListBox; } }

ScrollViewer Host { get { return this.Template.FindName("PART_ContentHost", this) as ScrollViewer; } }

UIElement TextBoxView { get { foreach (object o in LogicalTreeHelper.GetChildren(Host)) return o as UIElement; return null; } }

}

AutoCompleteTextBox

If text is changed, the suggestion item list is updated as well :

protected override void OnTextChanged(TextChangedEventArgs e)

{

if (_loaded)

{

try

{

if (lastPath != Path.GetDirectoryName(this.Text))

{

lastPath = Path.GetDirectoryName(this.Text);

string[] paths = Lookup(this.Text);

ItemList.Items.Clear();

foreach (string path in paths)

if (!(String.Equals(path, this.Text, StringComparison.CurrentCultureIgnoreCase)))

ItemList.Items.Add(path);

}

Popup.IsOpen = true;

//I added a Filter so Directory polling is only called once per directory, thus improve speed

ItemList.Items.Filter = p =>

{

string path = p as string;

return path.StartsWith(this.Text, StringComparison.CurrentCultureIgnoreCase) &&

!(String.Equals(path, this.Text, StringComparison.CurrentCultureIgnoreCase));

};

}

catch

{

}

}

}

A number of handlers is then defined :

public override void OnApplyTemplate()

{

base.OnApplyTemplate();

_loaded = true;

this.KeyDown += new KeyEventHandler(AutoCompleteTextBox_KeyDown);

this.PreviewKeyDown += new KeyEventHandler(AutoCompleteTextBox_PreviewKeyDown);

ItemList.PreviewMouseDown += new MouseButtonEventHandler(ItemList_PreviewMouseDown);

ItemList.KeyDown += new KeyEventHandler(ItemList_KeyDown);

}

AutoCompleteTextBox_PreviewKeyDown :

if user press down button, the textbox will move focus to the Listbox, so the user can choose an item from it, this is placed in PreviewKeyDown instead of KeyDown because TextBox's mechanism will consume the event before it reach KeyDown if the button is down button.

void AutoCompleteTextBox_PreviewKeyDown(object sender, KeyEventArgs e)

{

if (e.Key == Key.Down && ItemList.Items.Count > 0 && !(e.OriginalSource is ListBoxItem))

{

ItemList.Focus();

ItemList.SelectedIndex = 0;

ListBoxItem lbi = ItemList.ItemContainerGenerator.ContainerFromIndex(ItemList.SelectedIndex) as ListBoxItem;

lbi.Focus();

e.Handled = true;

}

}

AutoCompleteTextBox_KeyDown

if user press <enter> button, the textbox will close the popup and update the binding.

void AutoCompleteTextBox_KeyDown(object sender, KeyEventArgs e)

{

if (e.Key == Key.Enter)

{

Popup.IsOpen = false;

updateSource();

}

}

ItemList_PreviewMouseDown and ItemList_PreviewMouseDown

if user press <enter> button (or select by mouse), the text textbox will be updated with ListBox.SelectedValue, and then update the binding.

void ItemList_KeyDown(object sender, KeyEventArgs e)

{

if (e.OriginalSource is ListBoxItem)

{

ListBoxItem tb = e.OriginalSource as ListBoxItem;

Text = (tb.Content as string);

if (e.Key == Key.Enter)

{

Popup.IsOpen = false;

updateSource();

}

}

}

void ItemList_PreviewMouseDown(object sender, MouseButtonEventArgs e)

{

if (e.LeftButton == MouseButtonState.Pressed)

{

{

TextBlock tb = e.OriginalSource as TextBlock;

if (tb != null)

{

Text = tb.Text;

updateSource();

Popup.IsOpen = false;

e.Handled = true;

}

}

}

updateSource is required because I bound text's UpdateSourceTrigger as Explicit, if updateSource is not called it wont update the text :

void updateSource()

{

if (this.GetBindingExpression(TextBox.TextProperty) != null)

this.GetBindingExpression(TextBox.TextProperty).UpdateSource();

}

The component is working now, but if you want to add validation as well, read below :

To support validation, a Validation Rule is written :

If the path is not found or an exception raised when looking up, it will return ValidationResult false, the error will be

accessed by using the attached properties Validation.Errors and Validation.HasError.

public class DirectoryExistsRule : ValidationRule

{

public static DirectoryExistsRule Instance = new DirectoryExistsRule();

public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)

{

try

{

if (!(value is string))

return new ValidationResult(false, "InvalidPath");

if (!Directory.Exists((string)value))

return new ValidationResult(false, "Path Not Found");

}

catch (Exception ex)

{

return new ValidationResult(false, "Invalid Path");

}

return new ValidationResult(true, null);

}

}

and change the binding : (to use the created Validation rule, noted that UpdateSourceTrigger is Explicit. )

<local:SelectFolderTextBox x:Name="stb" DockPanel.Dock="Bottom" Margin="4,0,0,0">

<local:SelectFolderTextBox.Text>

<Binding Path="Text" UpdateSourceTrigger="Explicit" >

<Binding.ValidationRules>

<t:DirectoryExistsRule />

</Binding.ValidationRules>

</Binding>

</local:SelectFolderTextBox.Text>

</local:SelectFolderTextBox>

Now the textbox show a red border if directory not exists. As a red border isnt clear enough, we can change the behavior :

to disable the default red border:

<Style x:Key="autoCompleteTextBox" TargetType="{x:Type TextBox}">

<...>

<Setter Property="Validation.ErrorTemplate">

<Setter.Value>

<ControlTemplate >

<AdornedElementPlaceholder />

<!-- The TextBox Element -->

</ControlTemplate>

</Setter.Value>

</Setter>

</Style>

then change the control template, which will show the dockWarning when Validation.HasError :

<ControlTemplate TargetType="{x:Type TextBoxBase}">

<Border Name="Border" CornerRadius="2" Background="{StaticResource WindowBackgroundBrush}"

BorderBrush="{StaticResource SolidBorderBrush}" BorderThickness="1" Padding="1" >

<Grid x:Name="root">

<...>

<DockPanel x:Name="dockWarning" Visibility="Collapsed" LastChildFill="False" >

<Border DockPanel.Dock="Right" BorderBrush="Red" Background="Red" BorderThickness="2" CornerRadius="2,2,0,0">

<TextBlock x:Name="txtWarning" DockPanel.Dock="Right" Text="{TemplateBinding ToolTip}" VerticalAlignment="Top"

Background="Red" Foreground="White" FontSize="10" />

<Border.RenderTransform>

<TranslateTransform X="2" Y="{Binding ElementName=dockWarning, Path=ActualHeight,

Converter={x:Static t:InvertSignConverter.Instance}}"/>

<!--TranslateTransform move the border to upper right corner, outside the TextBox -->

<!--InvertSignConverter is a IValueConverter that change + to -, - to + -->

</Border.RenderTransform>

</Border>

</DockPanel>

</Grid>

</Border>

<ControlTemplate.Triggers>

<MultiTrigger>

<MultiTrigger.Conditions>

<Condition Property="Validation.HasError" Value="true" />

<Condition SourceName="PART_Popup" Property="IsOpen" Value="False" />

</MultiTrigger.Conditions>

<Setter Property="ToolTip" Value="{Binding RelativeSource={RelativeSource Self}, Path=(Validation.Errors)[0].ErrorContent}"/>

<Setter TargetName="dockWarning" Property="Visibility" Value="Visible" />

<Setter TargetName="Border" Property="BorderThickness" Value="2" />

<Setter TargetName="Border" Property="Padding" Value="0" />

<Setter TargetName="Border" Property="BorderBrush" Value="Red" />

</MultiTrigger>

</ControlTemplate.Triggers>

</ControlTemplate>

Cumartesi, Mart 14, 2009

C# 4.0: Dynamic Programming

If C# 3.0 was all about Language Integrated Query (LINQ), then C# 4.0 is all about dynamic programming. What exactly does that mean? It means that C# 4.0 brings some of flexibility and declarative style of programming to C#.

image_3

But what does that really mean?

To sum it up in one keyword: dynamic.

C# 4.0 is adding a new dynamic keyword which is used as a data type in much the same way the var keyword is used. Why is this important? The biggest reason is that it allows a C# program to use dynamic dispatch to more naturally create objects coming from a dynamic language.

For example, suppose you have a Calculator object declared in C#, meaning it is statically typed. You interact with your object like this:

Calculator calc = GetCalculator();
int sum = calc.Add(10, 20);

That’s pretty simple and straight forward. Now suppose the Calculator is not a statically typed .NET class (or it is a .NET class but you don’t know the specific type of class), you must do something like this:

object calc = GetCalculator();
Type calcType = calc.GetType();
object res = calcType.InvokeMember("Add",
BindingFlags.InvokeMethod, null,
new object[] { 10, 20 });
int sum = Convert.ToInt32(res);

That’s not nearly as simple. In fact, it’s downright ugly. There is a lot of non-type-safe calls and reflection going on here that you really shouldn’t have to see.

To take this a step further, if we knew that Calculator was a JavaScript class, you must use similar (but still significantly different) code:

ScriptObject calc = GetCalculator();
object res = calc.Invoke("Add", 10, 20);

int sum = Convert.ToInt32(res);

The reason for the differences in syntax is that there is no unification between the two APIs.

In C# 4.0, you can now use the following syntax:

dynamic calc = GetCalculator();
int sum = calc.Add(10, 20);

If you look at this syntax and the earlier statically typed call, you should notice that the only difference is that in C# we are declaring the data type to be dynamic.

image_6

Does this mean that C# is loosing it's roots as a statically typed language or that we should all start moving towards dynamic languages? Absolutely not. What is means is that it is now easier for you to write C# code that talks to objects (or APIs) written in dynamically typed languages. It also means that there is a unified API to talk to any dynamic language. You no longer need to worry about what language you are interoperating with to determine which C# code you must write.

So how does the dynamic keyword work? As I mentioned, it's a keyword in a similar fashion to var. You declare at compile-time the type to be dynamic, but at run-time you get a strongly typed object.

image_9

The dynamic keyword is great for writing C# code that consumes a dynamic object, but what about going the other direction and writing C# code that can be called from a dynamic language? You do this by implementing the IDynamicObject interface (or more simply, inheriting from the abstract DynamicObject class) and providing your own implementation for the member lookup and invocation.

Using the features and capabilities of the new dynamic keyword, the IDynamicObject interface, and the fact that the dynamic dispatch can dispatch to both dynamic and static types, C# effectively gets support for duck-typing.

C# 4.0: dynamic ?

I've not played with the VS2010 CTP much yet, and I've only looked briefly at the documentation and blogs about the new C# 4.0 dynamic type, but a thought occurred to me: why not have the option of making it generic as a way of saying "I will dynamically support this set of operations"?

As an example of what I mean, suppose you have an interface IMessageRouter like this:

public interface IMessageRouter
{
void Send(string message, string destination);
}

(This is an arbitrary example, by the way. The idea isn't specifically more suitable for message routing than anything else.)

I may have various implementations, written in various languages (or COM) which support the Send method with those parameters. Some of those implementations actually implement IMessageRouter but some don't. I'd like to be able to do the following:

dynamic<IMessageRouter> router = GetRouter();
// This is fine (but still invoked dynamically)
router.Send("message", turhal.temizer@netron.com.tr);
// Compilation error: no such overload
router.Send("message", "turhal.temizer@netron.com.tr", 20);

Intellisense would work, and we'd still have some of the benefits of static typing but without the implementations having to know about your interface. Of course, it would be quite easy to create an implementation of the interface which did exactly this - but now imagine that instead of IMessageRouter we had MessageRouter - a concrete class. In this case the compiler would still restrict the caller to the public API of the class, but it wouldn't have to be the real class. No checking would be performed by the compiler that your dynamic type actually supported the operations - given that we're talking about dynamic invocation, that would be impossible to do. It would instead be an "opt-in" restriction the client places on themselves. It could also potentially help with performance - if the binding involved realised that the actual type of the dynamic object natively implemented the interface or was/derived from the class, then no real dynamic calls need be made; just route all directly.

This may all sound a bit fuzzy - I'm extremely sleepy, to be honest - but I think it's a potentially interesting idea. Thoughts?

Pazar, Mart 01, 2009

"Hacker Olimpiyatları"

Önümüzdeki ay Vancouver'da düzenlenecek "Hacker Olimpiyatları"nda cep telefonu ve internet tarayıcısı kırma dallarında müsabakalar mevcut.

Digital Vaccine Labs'ın sponsorluğunda düzenlenen Pwn2Own "Hacker Olimpiyatları", bu sene Vancouver CanSecWest güvenlik konferansı dahilinde katılımcı bekliyor. Amaç, belirlenen cep telefonu işletim sistemleri ve internet tarayıcılarının zayıf noktalarını bulmak. Şartlar ise bulunan açıkların üreticilerle paylaşılması ve bu açıklar giderilene kadar sır olarak kalmalarından ibaret.

Cep telefonu dalında Android, Symbian ve Windows Mobile işletim sistemiyle çalışan ve aralarında iPhone ve BlackBerry'nin bulunduğu cihazlar kırılmaya çalışılacak. Sistemde açık bulan katılımcılar 10 bin dolarla ödüllendirilecek ve kırdıkları telefon da yanlarına kalıcak.

İnternet tarayıcısı dalında ise yarış Windows 7 yüklü Sony Vaio üzerinde çalışan Internet Explorer 8, Firefox ve Google Chrome ile OS X yüklü MacBook üzerinde çalışan Safari ve yine Firefox arasında geçecek. Bu dalın ödülü 5 bin dolar.

Geçen yıl aynı yarışmayı OS X yüklü MacBook'u kıran Charlie Miller kazanmıştı. İkinciliği ise Windows Vista'yı kıran yarışmacı alırken, severek kullandığımız Linux dağıtımı Ubuntu kırılamamıştı.