EnumDescriptionConverter

by Piotrosz 20. May 2012 03:37

Typ wyliczeniowy:

[Flags]
enum Flavour
{
    [Description("black chocolate")]
    Chocolate = 1 << 0,

    [Description("vanilla")]
    Vanilla = 1 << 2,

    [Description("cherry")]
    Cherry = 1 << 3,

    [Description("coffee")]
    Coffee = 1 << 4,
}

Użycie EnumDescriptionConverter:

var converter = new EnumDescriptionConverter(typeof(Flavour));

// Convert string to enum. 
string enumStr = "black chocolate, cherry, coffee";
Flavour flavour = (Flavour)converter.ConvertFromString(enumStr);

// Convert enum to string. 
enumStr = converter.ConvertToString(flavour);
Console.WriteLine(enumStr);

Post na blogu All-In-One Code Framework z kodem źródłowym i opisem: http://blogs.msdn.com/b/codefx/archive/2012/04/05/sample-of-apr-5th-c-vb-enum-string-converter.aspx

All-In-One Code Framework na CodePlex: http://1code.codeplex.com/

Rozszerzenie do Visual Studio: http://visualstudiogallery.msdn.microsoft.com/b3aaa8f6-1b72-4ce2-bb39-f597489d55da

Tags: , ,

WPF: localization

by Piotrosz 9. February 2012 21:19

W jaki sposób udostępnić UI aplikacji WPF w różnych językach:

1. Edycja .csproj (dodanie tagu UICulture):

 <PropertyGroup>
    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
	<UICulture>en-US</UICulture>
Po przebudowaniu w bin\Debug pojawi się dodatkowy katalog en-US zawierający plik AssemblyName.resources.dll

2. Edycja AssemblyInfo.cs (dodanie "neutralnych zasobów"):

[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]

3. Stworzenie "UI localization IDs" dla plików .xaml:

msbuild /t:updateuid ProjectName.csproj
Teraz każdy element w xaml ma swój unikalny x:Uid:
...
<Label x:Uid="Label_1">Hello</Label>
...

4. Stworzenie pliku .csv z tłumaczeniami przy pomocy narzędzia LocBaml.

Program LocBaml jest dostępny tutaj: http://go.microsoft.com/fwlink/?LinkID=160016.
Są to źródła, które należy zbudować:
msbuild LocBaml_SDK.csproj
Po przekopiowaniu LocBaml.exe do katalogu bin\Debug aplikacji WPF, którą chcemy "zlokalizować":
LocBaml.exe /parse en-US\AssemblyName.resources.dll /out:en-US.csv
Stworzony jest plik .csv z wszystkimi wartościami, które należy przetłumaczyć:
...
WpfApplication1.g.en-US.resources:mainwindow.baml,Label_1:System.Windows.Controls.Label.$Content,Label,True,True,,Hello:
...

5. Tłumaczenie na inny język:

LocBaml.exe /generate en-US\AssemblyName.resources.dll /trans:fr-CA.csv /out:fr-CA /cul:fr-CA
Sprawdzenie, czy tłumaczenie działa:
public partial class App : Application
{
    public App()
    {
        CultureInfo ci = new CultureInfo("fr-CA");
        Thread.CurrentThread.CurrentCulture = ci;
        Thread.CurrentThread.CurrentUICulture = ci;
    }
}
Dokładny opis: http://msdn.microsoft.com/en-us/library/ms746621.aspx.

Tags: ,

C# | WPF | XAML

IValueConverter - przykład

by Piotrosz 8. February 2012 23:26
using System;
using System.Windows.Data;
using System.Windows;
using System.Threading;
using System.Globalization;

namespace IValueConverterExample
{
    public class Person
    {
        public string Name { get; set; }
    }

    [ValueConversion(typeof(string), typeof(Person))]
    public class PersonConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return new Person { Name = value.ToString() };
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return ((Person)value).Name;
        }
    }

    class Program
    {
        static void Main()
        {
            var converter = new PersonConverter();
            var converted = (Person) converter.Convert("Jan", typeof(Person), null, Thread.CurrentThread.CurrentCulture);

            string convertedBack = (string) converter.ConvertBack(converted, typeof(string), null, Thread.CurrentThread.CurrentCulture);
        }
    }
}

Tags:

C# | WPF

UpdateSourceTrigger

by Piotrosz 8. February 2012 23:11
<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525"
        xmlns:src="clr-namespace:WpfApplication1"
        >
    <Window.Resources>
        <src:Person x:Key="myDataSource" Name="Joe"/>
    </Window.Resources>
    
    <StackPanel>
        <TextBox>
            <TextBox.Text>
                <Binding Source="{StaticResource myDataSource}" 
                         Path="Name"
                    UpdateSourceTrigger="PropertyChanged"/>
            </TextBox.Text>
        </TextBox>

        <TextBlock Text="{Binding Source={StaticResource myDataSource}, Path=Name}"/>
    </StackPanel>
</Window>
namespace WpfApplication1
{
    public class Person
    {
        public string Name { get; set; }
    }
}

Tags: ,

WPF | XAML

Definiowanie własnej DependencyProperty

by Piotrosz 8. February 2012 22:47
using System;
using System.Windows.Data;
using System.Windows;

namespace CollectionViewExample
{
    public class Person : DependencyObject
    {
        public static readonly DependencyProperty NameProperty =
            DependencyProperty.Register("Name", typeof(string), typeof(Person));

        public string Name
        {
            get { return (string) GetValue(NameProperty); }
            set { SetValue(NameProperty, value); }
        }
    }

    class Program
    {
        static void Main()
        {
            // support styling, data binding, inheritance, animations, and default values
            // callbacks, validation

            var p = new Person();
            p.Name = "A";
        }
    }
}

Tags: ,

C# | WPF

CollectionView - przykład

by Piotrosz 8. February 2012 22:25
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel; 
using System.Collections.Specialized;
using System.ComponentModel;
using System.Windows.Data;

namespace CollectionViewExample
{
    public class Person
    {
        private string name;

        public Person(string name)
        {
            this.name = name;
        }

        public string Name
        {
            get { return name; }
            set { name = value; }
        }
    }

    class Program
    {
        static void Main()
        {
            var collView = new CollectionView(
                new List<Person>()
                {
                    new Person("A"),
                    new Person("B"),
                    new Person("C"),
                    new Person("D"),
                    new Person("E")
                });
           
            // Navigate
            Console.WriteLine("Current person is: {0}", ((Person)collView.CurrentItem).Name);
            collView.MoveCurrentToNext();
            Console.WriteLine("Current person is: {0}", ((Person)collView.CurrentItem).Name);
            
            // Result:
            //Current person is: A
            //Current person is: B

            // Filter
            collView.Filter = o => 
            { 
                if (o is Person) 
                {
                    return ((Person)o).Name == "A";
                } 
                return false; 
            };

            foreach (var item in collView)
                Console.WriteLine(((Person)item).Name);

            // Result:
            // A

            // Undo filtering
            collView.Filter = null;

            foreach (var item in collView)
                Console.WriteLine(((Person)item).Name);

            // Result:
            //A
            //B
            //C
            //D
            //E

            Console.WriteLine(collView.CanSort); // Zawsze false (override w klasach potomnych)!
            Console.WriteLine(collView.CanGroup); // Zawsze false (override w klasach potomnych)!
        }
    }
}

Tags: , , ,

ObservableCollection - przykład

by Piotrosz 8. February 2012 21:32
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel; 
using System.Collections.Specialized;

namespace ObservableCollectionExample
{
    public class Person
    {
        private string name;

        public Person(string name)
        {
            this.name = name;
        }

        public string Name
        {
            get { return name; }
            set { name = value; }
        }
    }

    class Program
    {
        static void Main()
        {
            var list = new ObservableCollection<Person>();
            list.Add(new Person("John"));
            list.CollectionChanged += new NotifyCollectionChangedEventHandler(list_CollectionChanged);
            list.Add(new Person("Sydney"));

            // Result:
            //Collection has been changed.
            //Action was Add
            //Sydney
        }

        static void list_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {           
            Console.WriteLine("Collection has been changed.");
            Console.WriteLine("Action was {0}", e.Action);

            foreach (object o in e.NewItems)
                Console.WriteLine(((Person)o).Name);
        }
    }
}

Tags: ,

C#

INotifyPropertyChanged - przykład

by Piotrosz 8. February 2012 20:14
using System;
using System.Collections.Generic;
using System.ComponentModel; // INotifyPropertyChanged

namespace INotifyPropertyChangedExample
{
    public class Person : INotifyPropertyChanged
    {
        #region INotifyPropertyChanged members
        public event PropertyChangedEventHandler PropertyChanged;
        #endregion

        private void NotifyPropertyChanged(string info)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(info));
            }
        }

        private string name;

        public string Name
        {
            get { return this.name; }

            set
            {
                if (value != this.name)
                {
                    this.name = value;
                    NotifyPropertyChanged("Name");
                }
            }
        }
    }

    class Program
    {
        static void Main()
        {
            var p = new Person();
            p.PropertyChanged += new PropertyChangedEventHandler(p_PropertyChanged);

            p.Name = "dsdsds";

            // Result:
            // Name has been changed.
        }

        static void p_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            Console.WriteLine(e.PropertyName + " has been changed.");
        }
    }
}

Tags: , ,

C#

Jest Git

by Piotrosz 5. February 2012 22:38
Bardzo niekompletny zestaw komend gita.

Setup:

Imię i e-mail

$ git config --global user.name "Firstname Lastname"
$ git config --global user.email "your_email@youremail.com"

Notepad++ jako domyślny edytor (zwrócić uwagę na " i '):

git config --global core.editor 
"'C:\Program Files (x86)\Notepad++\notepad++.exe' 
-multiInst -notabbar -nosession -noPlugin"

Autocrlf

$ git config --global core.autocrlf true

Wyświetlanie wartości config:

git config --get user.name

Tworzenie nowego repozytorium:

mkdir [Nazwa]
cd [Nazwa]
git init
touch README
git add README
git commit -m 'first commit'
git remote add origin git@github.com:user/Project.git
git push -u origin master

Klonowanie istniejącego repozytorium (dołączanie do projektu):

git clone git://... mydir

Sprawdzanie statusu plików (pliki zmodyfikowane, pliki w staging area):

git status

Wysyłanie swoich zakomitowanych zmian na zdalne repozytorium:

git push [remote-name] [branch-name]
na przykład:
git push origin master

Aktualizacja ze zdalnego repozytorium (automerge):

git pull [remote-name] [branch-name]

Commit z pominięciem 'staging area', czyli add + commit:

git commit -a -m 'Commit message'

Wycofywanie commita (np. w celu poprawki komentarza lub dodania kolejnego pliku):

git commit --amend
git commit --amend -m 'New commit message'

Tagging:

git tag -a v1.4 -m 'my version 1.4'

git push --tags

Usuwanie (na przykład, gdy zapomnieliśmy umieścić czegoś w pliku .gitignore):

git rm 
git rm --cached 

Zmiana nazwy (tak naprawdę robi git add dla nowego pliku i git rm dla starego pliku):

git mv [from] [to]

Historia (do historii najlepiej chyba używać narzędzi graficznych, np. msysgit):

git log
git log -p -2   - diff only 2
git log --stat
git log --pretty-oneline
git log --pretty --graph

Unstaging a staged file:

git reset HEAD [filename]

GAŁĘZIE:

Lista gałęzi lokalnych:

git branch

Lista gałęzi zdalnych:

git branch -r

Lista wszystkich gałęzi (lokalnych i zdalnych):

git branch -a

Tworzenie i checkout gałęzi:

git chechout -b branchname
=
git branch branchname
git chechout branchname

Merge'owanie

git checkout master
git merge branchname
Usunięcie gałęzi:
git branch -d hotfix

Pobranie określonej rewizji:

git checkout 

Unstage a staged file:

$ git reset HEAD <file>

Wyświetlenie adresu zdalnego repozytorium:

git remote show origin

Cofanie modyfikacji (unmodifying a modified file):

git checkout -- <file>

Linki o Gicie

http://progit.org/book/
http://2010.osdc.com.au/proposal/196/git-ages-4-and
http://think-like-a-git.net
Git cheat sheets
Undoing things in Git

No i Git.

Tags:

Git

Słownik rosyjsko-rosyjski

by Piotrosz 28. January 2012 13:15
Program umożliwia:
  • sprawdzanie definicji rosyjskich słów w serwisach gramota.ru, Google oraz BabelPoint,
  • przechowywanie historii szukanych słów,
  • asynchroniczne pobieranie definicji.
Zrzuty ekranu:

RuDict

RuDict

RuDict

DOWNLOAD: https://github.com/piotrosz/RuDict/downloads

GitHub: https://github.com/piotrosz/RuDict

Programik jest napisany przy wykorzystaniu biblioteki WPF. Do przechowywania historii używa RavenDb.

Tags: ,

nauka rosyjskiego

Notatnik związany głównie z C#, .NET, ASP.NET MVC/Web Forms i SharePoint

GitHub: https://github.com/piotrosz/

Month List