sabato 29 giugno 2013

[WPF] Applicazioni in stile metro con MahApps.Metro

MahApps.Metro è un toolkit per creare applicazioni WPF in stile metro.
E' possibile installarlo tramite NuGet:

PM> Install-Package MahApps.Metro

oppure scaricare i sorgenti direttamente dal repository ufficiale

  

Il toolkit comprende i seguenti controlli:
  • MetroWindow
  • Panorama
  • Buttons
    • Standard Button
    • MetroCircleButton
    • Square button
    • FlatButton
  •  Toggle Switch
  •  TextBox
  • Progress Ring
  • AnimatedTabControl
  • AnimatedSingleRowTabControl
  • Range Slider
  • TransitioningContentControl
MahApps.Metro non iclude i file di risorse. Tuttavia è possibile installarle tramite NuGet:

PM> Install-Package MahApps.Metro.Resources
Sito ufficiale

venerdì 28 giugno 2013

Codificare stringa in MD5

public static string CodificaMD5(string txt)
{
    MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
    byte[] bs = Encoding.UTF8.GetBytes(txt);
    bs = md5.ComputeHash(bs);
    StringBuilder s = new StringBuilder();
    foreach (byte b in bs)
    {
        s.Append(b.ToString("x2").ToLower());
    }
    return s.ToString();
}

Validare indirizzo E-Mail con le Regex

public static bool ValidaEMail(string strIn)
{
    if (String.IsNullOrEmpty(strIn))
        return false;
 
    return Regex.IsMatch(strIn,
            @"^(?("")(""[^""]+?""@)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])@))" +
            @"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-\w]*[0-9a-z]*\.)+[a-z0-9]{2,17}))$",
            RegexOptions.IgnoreCase);
}

Visual Studio 2013 Preview disponibile per il download

Visual Studio 2013 Preview e Visual Studio Express 2013 Preview sono finalmente disponibili per il download.

Con l'installazione di VS 2013 Preview verrà fornito anche .NET Framework 4.5.1 Preview.

Link utili:

Download
Build 2013

giovedì 27 giugno 2013

Windows 8.1 Preview

E' finalmente disponibile la preview di Windows 8.1


Per maggiori informazioni visitare la pagina ufficiale.

[WPF] Ottenere la TextBox inserita nella ComboBox

public static TextBox getTextBox(ComboBox combo)
{
    return combo.Template.FindName("PART_EditableTextBox"comboas TextBox;
}

mercoledì 26 giugno 2013

[WPF] Caricare un'immagine a runtime

Ecco come caricare un'immagine a runtime:

public void LoadImage(string path)
{
    BitmapImage bmp = new BitmapImage();
    bmp.BeginInit();
    bmp.UriSource = new Uri(pathUriKind.RelativeOrAbsolute);
    bmp.EndInit();
 
    img.Source = bmp;
}

Ottenere l'handle del processo corrente mediante la funzione GetCurrentProcess

La funzione GetCurrentProcess consente di ottenere l'handle del processo corrente.
public static class API
{
    [DllImport("KERNEL32.DLL", EntryPoint = "GetCurrentProcess", SetLastError = true, CallingConvention = CallingConvention.StdCall)]
    public static extern IntPtr GetCurrentProcess();
} 

Esempio:
IntPtr handle = API.GetCurrentProcess();

martedì 25 giugno 2013

Implementare pattern Singleton

Il desing pattern Singleton ha lo scopo di garantire che di una classe ne venga creata una ed una sola istanza.
Ecco una delle possibili implementazioni:
class ClasseSingleton
{
    static ClasseSingleton instance = null;
    static readonly object padlock = new object();
 
    public static ClasseSingleton Instance
    {
        get
        {
            lock (padlock)
            {
                if (instance == null)
                {
                    instance = new ClasseSingleton();
                }
                return instance;
            }
        }
    }
 
    private ClasseSingleton() { }
 
    public void Test(string str)
    {
        Console.WriteLine(str);
    }
}
 
class TestSingleton
{
    public void RichiamaMetodoSingleton()
    {
        ClasseSingleton.Instance.Test("Metodo singleton");
    }
}

Ottenere il nome del mese a partire dal numero ad esso associato

CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(8)

Ottenere la directory dei programmi

Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles);

[WPF] Utilizzare controlli WinForms in WPF

Per integrare nei progetti WPF dei controli WinForms ci viene in aiuto la classe WindowsFormHost di WindowsFormIntegration.dll
<Window x:Class="EsempioWPF.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="401.124" Width="792.416">
    <Grid>
        <WindowsFormsHost Margin="0">
            <xxx:TuoControlloWinForms x:Name="controlloWinForm"/>
        </WindowsFormsHost>
    </Grid>
</Window>

lunedì 24 giugno 2013

[WPF] PasswordBox e DataBinding

Nativamente la passwordbox non consente si effettuare il databinding perché la proprità Password non è una di tipo DependencyProperty. Per ovviare a ciò non ci resta che creare la classe di supporto PasswordHelper:

public static class PasswordHelper
    {
        public static readonly DependencyProperty PasswordProperty =
            DependencyProperty.RegisterAttached("Password",
            typeof(string), typeof(PasswordHelper),
            new FrameworkPropertyMetadata(string.EmptyOnPasswordPropertyChanged));
 
        public static readonly DependencyProperty AttachProperty =
            DependencyProperty.RegisterAttached("Attach",
            typeof(bool), typeof(PasswordHelper), new PropertyMetadata(falseAttach));
 
        private static readonly DependencyProperty IsUpdatingProperty =
           DependencyProperty.RegisterAttached("IsUpdating"typeof(bool),
           typeof(PasswordHelper));
 
 
        public static void SetAttach(DependencyObject dpbool value)
        {
            dp.SetValue(AttachPropertyvalue);
        }
 
        public static bool GetAttach(DependencyObject dp)
        {
            return (bool)dp.GetValue(AttachProperty);
        }
 
        public static string GetPassword(DependencyObject dp)
        {
            return (string)dp.GetValue(PasswordProperty);
        }
 
        public static void SetPassword(DependencyObject dpstring value)
        {
            dp.SetValue(PasswordPropertyvalue);
        }
 
        private static bool GetIsUpdating(DependencyObject dp)
        {
            return (bool)dp.GetValue(IsUpdatingProperty);
        }
 
        private static void SetIsUpdating(DependencyObject dpbool value)
        {
            dp.SetValue(IsUpdatingPropertyvalue);
        }
 
        private static void OnPasswordPropertyChanged(DependencyObject sender,
            DependencyPropertyChangedEventArgs e)
        {
            PasswordBox passwordBox = sender as PasswordBox;
            passwordBox.PasswordChanged -= PasswordChanged;
 
            if (!(bool)GetIsUpdating(passwordBox))
            {
                passwordBox.Password = (string)e.NewValue;
            }
            passwordBox.PasswordChanged += PasswordChanged;
        }
 
        private static void Attach(DependencyObject sender,
            DependencyPropertyChangedEventArgs e)
        {
            PasswordBox passwordBox = sender as PasswordBox;
 
            if (passwordBox == null)
                return;
 
            if ((bool)e.OldValue)
            {
                passwordBox.PasswordChanged -= PasswordChanged;
            }
 
            if ((bool)e.NewValue)
            {
                passwordBox.PasswordChanged += PasswordChanged;
            }
        }
 
        private static void PasswordChanged(object senderRoutedEventArgs e)
        {
            PasswordBox passwordBox = sender as PasswordBox;
            SetIsUpdating(passwordBoxtrue);
            SetPassword(passwordBoxpasswordBox.Password);
            SetIsUpdating(passwordBoxfalse);
        }
    }

XAML:
xmlns:helper="clr-namespace:XXX.Utility" 
<PasswordBox helper:PasswordHelper.Attach="True" helper:PasswordHelper.Password="{Binding Password,UpdateSourceTrigger=PropertyChanged,Mode=TwoWay}" />

venerdì 21 giugno 2013

[WP7] UpdateSourceTrigger = PropertyChanged TextBox

WP7 essendo basato sul Silverlight 3 non supporta nativamente UpdateSourceTrigger = PropertyChanged. Per ovviare a ciò non ci resta che creare una classe ad hoc di supporto: BindingUtility.
public class BindingUtility
{
    public static bool GetUpdateSourceOnChange(DependencyObject d)
    {
        return (bool)d.GetValue(UpdateSourceOnChangeProperty);
    }
 
    public static void SetUpdateSourceOnChange(DependencyObject d, bool value)
    {
        d.SetValue(UpdateSourceOnChangeProperty, value);
    }

    public static readonly DependencyProperty
        UpdateSourceOnChangeProperty =
        DependencyProperty.RegisterAttached(
        "UpdateSourceOnChange",
        typeof(bool),
                    typeof(BindingUtility),
        new PropertyMetadata(false, OnPropertyChanged));
 
    private static void OnPropertyChanged(DependencyObject d,
        DependencyPropertyChangedEventArgs e)
    {
        var textBox = d as TextBox;
        if (textBox == null)
            return;
        if ((bool)e.NewValue)
        {
            textBox.TextChanged += OnTextChanged;
        }
        else
        {
            textBox.TextChanged -= OnTextChanged;
        }
    }
 
    static void OnTextChanged(object s, TextChangedEventArgs e)
    {
        UpdatePropertyChangedTextBox(s as TextBox);
    }
 
    public static void UpdatePropertyChangedTextBox(TextBox textBox)
    {
        if (textBox == null)
            return;
 
        var bindingExpression = textBox.GetBindingExpression(TextBox.TextProperty);
        if (bindingExpression != null)
        {
            bindingExpression.UpdateSource();
        }
    }
}

L'utilizzo della classe è veramente semplice:
xmlns:utility="clr-namespace:XXX.Utility" 
<TextBox Text="{Binding TuaProprieta,Mode=TwoWay}" utility:BindingUtility.UpdateSourceOnChange="True"/>

[WP7] Ottenere l'ApplicationBar globale

public static IApplicationBar GetGlobalAppBar()
{
    return (IApplicationBar)Application.Current.Resources["GlobalApplicationBar"];
}

[WP7] Grafico senza legenda

Rimuovere la legenda da un grafico (DataVisualization.Charting).

<Style x:Key="NoLegendStyle" TargetType="dataVis:Legend">
     <Setter Property="Width" Value="0"/>
     <Setter Property="Height" Value="0"/>
</Style> 
N.B.: dataVis indica il seguente namespace:
xmlns:dataVis="clr-namespace:System.Windows.Controls.DataVisualization;
assembly=System.Windows.Controls.DataVisualization.Toolkit"

[WPF] Sfondo di selezione trasparente ListBoxItem

Da incollare nel file App.xaml
<Style x:Key="ListBoxItemStyleTransparentSelect" TargetType="ListBoxItem">
 <Setter Property="Foreground" Value="Black"/>
 <Setter Property="FontSize" Value="10"/>
 <Setter Property="FontFamily" Value="Arial"/>
 <Setter Property="Padding" Value="1"/>
 <Setter Property="HorizontalContentAlignment" Value="Stretch"/>
 <Setter Property="VerticalContentAlignment" Value="Top"/>
 <Setter Property="Background" Value="Transparent"/>
 <Setter Property="BorderThickness" Value="0"/>
 <Setter Property="Template">
  <Setter.Value>
   <ControlTemplate TargetType="ListBoxItem">
    <Grid Background="{TemplateBinding Background}">
     <VisualStateManager.VisualStateGroups>
      <VisualStateGroup x:Name="CommonStates">
       <VisualState x:Name="Normal"/>
       <VisualState x:Name="MouseOver">
        <Storyboard>
         <DoubleAnimation Duration="0" To=".35" Storyboard.TargetProperty="Opacity" Storyboard.TargetName="fillColor"/>
        </Storyboard>
       </VisualState>
       <VisualState x:Name="Disabled">
        <Storyboard>
         <DoubleAnimation Duration="0" To=".55" Storyboard.TargetProperty="Opacity" Storyboard.TargetName="contentPresenter"/>
        </Storyboard>
       </VisualState>
      </VisualStateGroup>
      <VisualStateGroup x:Name="SelectionStates">
       <VisualState x:Name="Unselected"/>
       <VisualState x:Name="Selected"/>
      </VisualStateGroup>
      <VisualStateGroup x:Name="FocusStates">
       <VisualState x:Name="Focused"/>
       <VisualState x:Name="Unfocused"/>
      </VisualStateGroup>
     </VisualStateManager.VisualStateGroups>
     <Rectangle x:Name="fillColor" IsHitTestVisible="False" Opacity="0" RadiusY="1" RadiusX="1"/>
     <Rectangle x:Name="fillColor2" IsHitTestVisible="False" Opacity="0" RadiusY="1" RadiusX="1"/>
     <ContentPresenter x:Name="contentPresenter" ContentTemplate="{TemplateBinding ContentTemplate}" Content="{TemplateBinding Content}" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" Margin="{TemplateBinding Padding}"/>
     <Rectangle x:Name="FocusVisualElement" RadiusY="1" RadiusX="1" StrokeThickness="1" Visibility="Collapsed"/>
    </Grid>
   </ControlTemplate>
  </Setter.Value>
 </Setter>
</Style>

[MySQL] Reset autoincrement tabella

Query per resettare l'autoincrement di una tabella:

ALTER TABLE nome_tabella AUTO_INCREMENT=0;

martedì 18 giugno 2013

Rilasciare le risorse implementando IDisposable

Esempio di come rilasciare le risorse implementando l'interfaccia IDisposable.

public class MiaClasseIDisposable
{
    #region DISPOSE
 
    private IntPtr handle;
    private Component component = new Component();
    private bool disposed = false;
 
    [DllImport("Kernel32")]
    private extern static Boolean CloseHandle(IntPtr handle);
 
    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }
 
    private void Dispose(bool disposing)
    {
        if (!this.disposed)
        {
            if (disposing)
            {
                component.Dispose();
            }
 
            CloseHandle(handle);
            handle = IntPtr.Zero;
 
            disposed = true;
        }
    }
 
    ~DataBaseHandler()
    {
        Dispose(false);
    }
 
    #endregion
 
    public MiaClasse(IntPtr handle)
    {
        this.handle = handle;
    }
} 

[SL4] Forzare il re-binding di un controllo

public static void ForceControlRebind(Control cntrl, DependencyProperty depprop)
{
    try
    {
        BindingExpression BindExp = cntrl.GetBindingExpression(depprop);
        Binding Bind = BindExp.ParentBinding;
        cntrl.SetBinding(depprop, Bind);
    }
    catch { }
}

[WPF/SL/WP] Clonare ObservableCollection

Metodo esteso che consente di clonare una generica ObservableCollection.
public static ObservableCollection<T> Clone<T> (this ObservableCollection<T> source)
{
    if (source != null)
    {
        var res = new ObservableCollection<T>();
 
        foreach (var item in source)
        {
            res.Add(Clone<T>(item));
        }
        return res;
    }
    return null;
}

[SL4] Settare pulsante di defualt

public class DefaultButton
{
    public static DependencyProperty DefaultButtonProperty = DependencyProperty.RegisterAttached("DefaultButton",
                                                                typeof(Button),
                                                                typeof(DefaultButton),
                                                                new PropertyMetadata(null, DefaultButtonChanged));
 
    private static void DefaultButtonChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var uiElement = d as UIElement;
        var button = e.NewValue as Button;
        if (uiElement != null && button != null)
        {
            uiElement.KeyUp += (sender, arg) =>
            {
                var peer = new ButtonAutomationPeer(button);
 
                if (arg.Key == Key.Enter)
                {
                    peer.SetFocus();
                    uiElement.Dispatcher.BeginInvoke((Action)delegate
                    {
                        var invokeProv = peer.GetPattern(PatternInterface.Invoke) as IInvokeProvider;
                        if (invokeProv != null)
                        {
                            if (button.IsEnabled)
                            {
                                invokeProv.Invoke();
                            }
                        }
                    });
                }
            };
        }
    }
 
    public static Button GetDefaultButton(UIElement obj)
    {
        return (Button)obj.GetValue(DefaultButtonProperty);
    }
 
    public static void SetDefaultButton(DependencyObject obj, Button button)
    {
        obj.SetValue(DefaultButtonProperty, button);
    }
}

XAML
<TextBox utility:DefaultButton.DefaultButton="{Binding ElementName=nomeBottone}"/>

[WP7] Array byte to BitmapImage

Codice per convertire un array di byte in bitmapimage.   
public static BitmapImage ImageFromBuffer(byte[] bytes)
{
    var stream = new MemoryStream(bytes);
    {
        var image = new BitmapImage();
        image.SetSource(stream);
        return image;
    }
}

[Win32] Funzione TerminateProcess

Terminare un processo e tutti i suoi thread mediante la funzione TerminateProcess (Kernel32.dll)


public static class API
{
      [DllImport("Kernel32.dll")]
      public static extern bool TerminateProcess(IntPtr handle,
                                                 int exitCode);
}

  • 1° Parametro: handle della finestra
  • 2° Parametro: codice di uscita (Maggiori info)
Esempio:

var processi = Process.GetProcesses("nomeProcesso");
if (processi.Length > 0)
{
   API.TerminateProcess(processi[0].Handleprocessi[0].ExitCode);
}  

lunedì 17 giugno 2013

[WCF] Attivare compatilità ASP.NET

Per attivare la compatibilità ASP.NET su servizi WCF basta seguiere i seguenti passi:
  •  Abilitatare AspNetCompatibilitynel file web.config
 <system.serviceModel>
  ...
  <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
</system.serviceModel>

  •  Aggiungere il seguente attributo sulla definizione del servizio
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]


Errore visualizzto:
Impossibile attivare il servizio perché richiede la compatibilità ASP.NET. La compatibilità ASP.NET non è abilitata per questa applicazione. Abilitare la compatibilità ASP.NET in web.config o impostare la proprietà AspNetCompatibilityRequirementsAttribute.AspNetCompatibilityRequirementsMode su un valore diverso da Required.

Inglese: 
The service cannot be activated because it requires ASP.NET compatibility. ASP.NET compatibility is not enabled for this application. Either enable ASP.NET compatibility in web.config or set the AspNetCompatibilityRequirementsAttribute.AspNetCompatibilityRequirementsMode property to a value other than Required.

[WPF] Stile validazione campo TextBox

Da incollare nel file App.xaml

<Style TargetType="{x:Type TextBox}">
                <Setter Property="Validation.ErrorTemplate">
                    <Setter.Value>
                        <ControlTemplate>
                            <DockPanel LastChildFill="True">
                                <TextBlock DockPanel.Dock="Right" Foreground="Gray" Margin="2" FontSize="12pt" Text="*" />
                                <Border >
                                    <AdornedElementPlaceholder Name="MyAdorner" />
                                </Border>
                            </DockPanel>
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
                <Style.Triggers>
                    <Trigger Property="Validation.HasError" Value="true">
                        <Setter Property="ToolTip" Value="{Binding RelativeSource={RelativeSource Self}, Path=(Validation.Errors).CurrentItem.ErrorContent}"/>
                    </Trigger>
                </Style.Triggers>
            </Style>

[WPF] Binding Radio Button To Enum

Codice per effettuare il binding fra radio button ed un enumeratore
C#
 public class EnumBooleanConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            string parameterString = parameter as string;
            if (parameterString == null)
                return DependencyProperty.UnsetValue;
 
            if (System.Enum.IsDefined(value.GetType(), value) == false)
                return DependencyProperty.UnsetValue;
 
            object parameterValue = System.Enum.Parse(value.GetType(), parameterString);
 
            return parameterValue.Equals(value);
        }
 
        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            string parameterString = parameter as string;
            if (parameterString == null)
                return DependencyProperty.UnsetValue;
 
            return System.Enum.Parse(targetType, parameterString);
        }
    }
 
XAML
IsChecked="{Binding Enumeratore, Converter={StaticResource EnumBooleanConverter}, ConverterParameter=Valore,UpdateSourceTrigger=PropertyChanged}"/>

Ottenere il colore partendo dal codice esadecimale


Color color = (Color)ColorConverter.ConvertFromString("#FFDFD991");

Ottenere un sub-array da un array esistente

 

static T[] SubArray<T>(this T[] data, int index, int length)
{
 T[] result = new T[length];
 Array.Copy(data, index, result, 0, length);
 return result;
}