This title could sound a bit strange, but that’s what this post is about :) . I needed to load some images and delete them after the application has been closed. The problem was that I couldn’t delete them because “Another process is still using this file”.

So the first thing is to unlock my images. Since I’m working with WPF, I’m using BitmapImage, and a typical use is:

BitmapImage image = new BitmapImage(new Uri("C:\\myimage.png"));//absolute path
BitmapImage image = new BitmapImage(new Uri("/Images/myimage.png", UriKind.Relative));//relative path

But this code locks the image and is not optimized at all!

Before reveal the “magic” code, I would introduce another note. I needed also to show those images into a ListBox, using the Binding and a Template, something like:

<DataTemplate x:Key="ImageTemplate">
    <Image Source="{Binding MySourceImage}"/>
</DataTemplate>

 

<ListBox x:Name="_imageList" Grid.Column="1" AllowDrop="True" Drop="Grid_Drop" Margin="5, 0,0,0"
            ItemsSource="{DynamicResource ResourceKey=Photos}"
            ItemTemplate="{StaticResource ImageTemplate}">
    <ListBox.ItemsPanel>
        <ItemsPanelTemplate>
            <WrapPanel MaxWidth="800"/>
        </ItemsPanelTemplate>
    </ListBox.ItemsPanel>
</ListBox>

 

As you can see the ItemTemplate in the ListBox is linked via Binding to the DataTemplate. This means that every item passed into the ListBox looks like those specified  DataTemplate, and  the DataTempate has an Image that expects a variable containing the ImageSource (like a BitmapImage) and this variable MUST be called MySourceImage.

Now we need two things:

  1. Optimize the code to create the BitmapImage
  2. Create the images without locking them

Takes more to say it then doing it actually. To have a lock free Image loaded from disk, we have to create a copy ( also called “cached image”) and work on the copy. To do this “hard work” in BitmapImages we can write the following code:

BitmapImage bi = new BitmapImage();
            bi.BeginInit();
            bi.DecodePixelWidth = 64;
            bi.CacheOption = BitmapCacheOption.OnLoad;
            bi.UriSource = new Uri("/Images/myImage.png", UriKind.Relative);
            bi.EndInit();

So here you can see BitmapCachedOption set to OnLoad, which means that the cache will be used at loading time. That’s all :) .

The optimization is on DecodedPixelWidth option that lets programmers balance between resolution and memory usage, and the lock free is the image copy or cache, as you want to call it.

Tricky Tricks: String to Bitmap Converter

As we all know, one of the most slowest operation is not CPU calculation but moving objects around memory, and when we pass Objects between functions in our application, the cost is “how big is our Object”. So if we create bunch of BitmapImages and pass them to the ListBox, this will result in slowing down our App. The best would be get the path and let the ListBox resolve “itself”.

This will be done by “StringToBitmap” Converter. Converters in WPF are really handy and let you convert objects from one to another, like enumerations to numbers, or boolean to Bitmap ecc, you can convert what you want, and do a lot of exotic tricks.

A converter is a class that extends IValueConverter, and has two methods: Convert and ConvertBack. The second usually is left unused because typically you have the starting value.

If we pass the string path (of  our image) this will be taken into the converter as a generic object and we just need a cast to pass it into the Uri Object. Let’s see how create the converter:

public class UriToBitmapConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        BitmapImage bi = new BitmapImage();
        bi.BeginInit();
        bi.DecodePixelWidth = 64;
        bi.CacheOption = BitmapCacheOption.OnLoad;
        bi.UriSource = new Uri(value.ToString());
        bi.EndInit();

        return bi;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new Exception("The method or operation is not implemented.");
    }
}

And you will use it in xaml:

<converter:UriToBitmapConverter x:Key="thumbnailConverter"/>

<DataTemplate x:Key="ImageTemplate">
    <Image Source="{Binding MySourceImage, Converter={StaticResource thumbnailConverter}}"/>
</DataTemplate>

that’s it :) .

Below, as usually the code. Is WPF in .NET 4.

-dave

 

Qualche giorno fa ho scoperto una roba fichissima, ma per raccontarvela partiamo dall’inizio.

Quanti social network, chat, servizi e balle varie usate? Io mille, un po’ per lavoro e un po’ per non rimanere “esiliato” quando parlo con le persone. Prima di avere Facebook, ero una persona normale, e le serate erano a suon di risate per le cretinate che si trovavano su FB, ma io non ero mai “taggato”, non mi “scrivevano in bacheca”, “non partecipavo agli eventi” e non ero “fan di un ca**o”. Insomma fuori dal mondo. Alla fine mi sono ritrovato con MSN, Skype, Facebook, Linked-in, Twitter, due blog, pfff…..

Con tutto il lavoro che ho da fare in questi ultmi anni, tra università, clienti e attività Microsoft è diventato improbabile che mi si trovi su tutti tutti i giorni. E’ molto che ho messo la summercard di Vodafone :) .

E’ troppo stressante la finirei così:

 image image

e alla fine non riuscirei a vedere più entrambi i delfini:

image :P

Ho scoperto un programma GRATUITO e molto funzionale che raggruppa in una sola schermata un botto di servizi, si chiama TweetDeck image ed è alla versione beta, ma funziona alla grande :) .

Ecco uno screenshot dal mio TweetDeck per Windows

image

Bene, il mio post l’ho fatto, ora manca solo usarlo :)

 

-dave

Not a real post, but just to give some inspiration for the Imagine Cup 2011.

 

-dave

Yup guys, I’ve took some weeks to discover new stuff on Silverlight and especially on Silverlight 4 and fun/useful features.

I’ll just show something really cool on this post that came into my hands few days ago.

This post talks about painless COM interoperability, emails from Outlook using Silverlight 4. Whaaat ?? :P yes send an email from Outlook with Silverlight 4 takes more time to describe it than implement it.

I’m going to use “dynamic” keyword introduced in C# 4.

dynamic is a type, like “int” or “string” but has a lot of meanings, a sort of “var”, but this magic keyword allows us to call methods in python, ruby or whatever COM IDispatch object without an interop assembly, it resolves all the headache for us.

 

its simply :

dynamic d = GetSomethingCool();

d.MyMethod();

 

To use it you must import Microsoft.CSharp dll and since we are going to use COM objects we have to import System.Windows dll to use AutomationFactory class that allows us to communicate with any software in your PC and, for our purpose, Outlook.

image

image

When using a dynamic expression you do not have Intellisense support, because everything is resolved @ runtime…hey folks I didn’t said that is all for free :D , but is a little cost that sometimes we can pay.

Now, create a new Silverlight 4 project and Add a button in XAML:

<UserControl x:Class="ComInteropWithSilverlight.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    d:DesignHeight="300" d:DesignWidth="400">

    <Grid x:Name="LayoutRoot" Background="OrangeRed">
        <Button x:Name="_installButton" Width="300" Height="100" Content="Install"
                FontSize="20" Click="_installButton_Click"/>
    </Grid>
</UserControl>

and in C# we add a global variable called outlook

dynamic outlook;

And in the following two methods we’ll open Outlook application and get everything ready to send (including some checks if outlook is available):

 

private void PrepareOutlook()
{
    try
    {
        outlook = AutomationFactory.GetObject("Outlook.Application");
        Send();
    }
    catch (Exception)
    {
        try
        {
            outlook = AutomationFactory.CreateObject("Outlook.Application");
            Send();
        }
        catch (Exception)
        {
            MessageBox.Show("Outlook is unavailable");
        }
    }
}

private void Send()
{
    int inbox = 6;
    int newemail = 0;
    outlook.Session.GetDefaultFolder(inbox).Display();

    dynamic mail = outlook.CreateItem(newemail);
    mail.Recipients.Add("myname@contoso.com");
    mail.Subject = "CodeZero Team";
    mail.Body = "This message was sent from Silverlight 4";

    mail.Save();
    mail.Display();
}

Last step is to check if  the Silverlight 4 application is installed and has elevated privileges. For security reasons we need to let Silverlight  run OOB (out of browser) and then give it elevated privileges, otherwise we cannot communicate with Outlook.

To achieve this right click in your solution and select “Properties”

image

Then enable OOB and click the settings button

image

Make sure that elevated trust check is selected

image

Once you have all this stuff ready add few lines to implement what the button has to do in its click event

 

private void _installButton_Click(object sender, RoutedEventArgs e)
{
    if (!App.Current.InstallState.Equals(InstallState.Installed))
    {
        App.Current.Install();
    }
    else if (App.Current.HasElevatedPermissions)
    {
        PrepareOutlook();
    }
}

and you are ready to open outlook with new email ready.

image 

image

As always the link ad the source code. Enjoy!

-dave

Hi guys, today we got two new contributors. Let me present them:

Francesco & Giuseppe

image image

I’ve seen great stuff from them, we’re sure that they can just make this blog richer :)

 

-dave

Waaaah guys, today I received another request for continuing the tutorial I’ve began last year. 15 requests are enough to me to decide to continue it. (The code is at the end)

First, it might not be the same, since I’ve lost the code, so I just tried to do approximately the same.

As you might guess our animation should run on GPU and so we have to create an effect. This effect morphs our window. The morphing algorithm is done with Beziér curbs, and the concept is pretty simple.

We need to get some handle and blend them and all pixels around, like in the figure I want to push L2 and L3 handles down and all others should stretch consequently.

Our algorithm subdivide a texture into 16 handles (Left [1,2,3,4], Upper[1,2,3,4], Right[1,2,3,4], Down[1,2,3,4]).

image

Since we want to act at window level we can first get a trick, to understand what’s going on and then get real window part and move them. Pass into the effect the Window view as texture.

Here goes the HLSL effect used (the zip at the end )

 

sampler2D implicitInput : register(s0);
float lp0 : register(c0);
float lp1 : register(c1);
float lp2 : register(c2);
float lp3 : register(c3);

float rp0 : register(c4);
float rp1 : register(c5);
float rp2 : register(c6);
float rp3 : register(c7);

//up-down coordinates
float up0 : register(c8);
float up1 : register(c9);
float up2 : register(c10);
float up3 : register(c11);

float dp0 : register(c12);
float dp1 : register(c13);
float dp2 : register(c14);
float dp3 : register(c15);

float BezierInterpolate(float x0, float x1, float x2, float x3, float t)
{
    float b0 = pow(1-t, 3);
    float b1 = 3*t*pow(1-t,2);
    float b2 = 3*t*t*(1-t);
    float b3 = pow(t, 3);
    return b0*x0 + b1*x1 + b2*x2 + b3*x3;
}

float4 main(float2 uv : TEXCOORD) : COLOR
{
    float left = BezierInterpolate(lp0, lp1, lp2, lp3, uv.y);
    float right = BezierInterpolate(rp0, rp1, rp2, rp3, uv.y);
    float up = BezierInterpolate(up0, up1, up2, up3, uv.x);
    float down = BezierInterpolate(dp0, dp1, dp2, dp3, uv.x);

    //apply the warp effect to texture color
    if (uv.x >= left && uv.x <= right && uv.y >=up && uv.y <= down)
    {
        float tx = lerp(0, 1, (uv.x-left)/(right-left));
        float ty = lerp(0, 1, (uv.y-up)/(down-up));
        float2 pos = float2(tx, ty);
        return tex2D(implicitInput, pos);
    }
    //leave the background transparent
    else return float4(0,0,0,0);
}

 

And we have to map into a C# class with the respective dependency properties, and I’m not going to list here the class since is pretty dumb, and attached into the zip.

Now we need to use this effect.

  1. Create a storyboard that controls the handles
  2. Put the window as texture of the effect
  3. Make window transparent and re-arrange open/minimize/close buttons
  4. Listen and intercept when window is closing

Lets try.

1. Create a Storyboard similar to this one to open and close the window.

<Storyboard x:Key="L1Point" AutoReverse="False" Completed="CloseAnim_Completed" >
            <DoubleAnimationUsingKeyFrames BeginTime="00:00:00" Storyboard.TargetName="fx" Storyboard.TargetProperty="(L3)">
                <SplineDoubleKeyFrame KeyTime="00:00:00" Value="0" />
                <SplineDoubleKeyFrame KeyTime="00:00:01" Value="0.8" />
            </DoubleAnimationUsingKeyFrames>
            <DoubleAnimationUsingKeyFrames BeginTime="00:00:00" Storyboard.TargetName="fx" Storyboard.TargetProperty="(L4)">
                <SplineDoubleKeyFrame KeyTime="00:00:00" Value="0" />
                <SplineDoubleKeyFrame KeyTime="00:00:01" Value="0.75" />
            </DoubleAnimationUsingKeyFrames>

Where “fx” refers to our effect and (L3) to the handler of our texture.

2.Put the window as texture of the effect.

This one is simple. Create a Border to wrap the main Grid and add an effect to this Border.

<Border x:Name="myBorder">
            <Border.Effect>
                <warp3D:WarpEffect Input="{Binding ElementName=win}" x:Name="fx"/>
            </Border.Effect>
            <Grid x:Name="LayoutRoot" Background="OrangeRed">
                <!-- ... code ... -->

            </Grid>
        </Border>

and as you can see the Input parameter of the effect refers to “win” which is the name given to the window

<Window x:Class="WPFGeenieWindow.Window1"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:warp3D="clr-namespace:WarpShaderLibrary;assembly=WarpEffectLibrary3D"
            Title="Warp WPF Window "
            x:Name="win" >

            <!-- ... code ... -->

        </Window>

3. Make window transparent and re-arrange open/minimize/close buttons

This is a bit tricky. We are going to replace the top control bar with a custom one. So split the main grid into 2 rows, the first 30 px height and the rest to the app. Do not forget to manage the handle to drag around the window.

<Border x:Name="myBorder">
            <Border.Effect>
                <warp3D:WarpEffect Input="{Binding ElementName=win}" x:Name="fx"/>
            </Border.Effect>
            <Grid x:Name="LayoutRoot" Background="OrangeRed">
                <Grid.RowDefinitions>
                    <RowDefinition Height="30"/>
                    <RowDefinition Height="*"/>
                </Grid.RowDefinitions>

                <!--close windo buttons-->
                <Grid Grid.Row="0" Background="#7825AA78" MouseLeftButtonDown="Grid_MouseLeftButtonDown">
                    <StackPanel Orientation="Horizontal" HorizontalAlignment="Right" >
                        <Button x:Name="MinimizeButton" Width="25" Height="25" Click="MinimizeButton_Click" FontSize="18" Content="-"/>
                        <Button x:Name="ExitButton" Width="25" Height="25" Click="ExitButton_Click" FontFamily="Wingdings 2" FontSize="18" Content="V"/>
                    </StackPanel>
                </Grid>

            </Grid>

and the fun parts:

a) handle the drag

private void Grid_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            this.DragMove();
        }

b) intercept the closing event

protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
        {
            //allows shutdown
            if(!state.Equals("close"))
                e.Cancel = true;
            base.OnClosing(e);
        }

where state is a custom variable changed to be able to determine when closing and when minimizing. If not closing, cancel the action.

Here the wonderful app

image

and here the animation:

image

Here goes the full source code, as promessed. Hopefully lots comments ;) will come, tell me your solutions/experiences.

Next time I’ll going to show another solution, more efficient for sure :) , based on this one.

 

Enjoy

-dave

Hello guys! This year CodeZero team decided to participate to Imagine Cup, the largest technology competition for students in the Hearth, organized by Microsoft. 

Let me spend two words on Imagine Cup, before to dig into what we’ve done.

To participate to Imagine Cup students have to create a team and submit for one of the offered categories, which may vary each year. Main categories are:

  • Software Design
  • Embedded development
  • Game Design
  • Windows Phone 7
  • ….

We all have a common theme, which can vary each year, but last two years was to reach one of 8 Millennium Goals.

The competition starts on August 1st and ends on April, but this is decided by each Country. In fact Students first participate to National finals and the first team on Software Design goes to World Finals.

 

This year in Italy we were 250 competitors, and each year the number is growing, which means, better competitors, and better softwares!

As CodeZero we developed a software called Flexy, and we placed 2nd for Software Design! It’s been a wonderful experience.

Flexy is a software that let you have a better way to Work. Our slogan is BETTER WORK, BETTER WORLD. It does not follow directly the 8 Millennium Goals, but  what we thought is that, if we can have less dirty money floating around, let people find work more easily, a good way to organize the work, we can also export this good organization and have money to build schools, reduce the ignorance, do advertising campaign, to reach Millennium Goals.

Now, people said to us, “ok, but you can get money from everywhere, even buying an ice cream and give money to Millennium Goals”. True, but is not an organized massive way to do it, and does not teach something to the community.

But anyway we didn’t directly followed the Millennium Goals, even thought that our work was HUGE, and well organized and presented.

We were amazed how difficult for the jury was to decide among 6 complex softwares (finalists).

 

image

 

Another aspect of the competition was to meet companies that look for talents. We meet them and we’re really satisfied how things turned out well for us. We’ll see and we’ll update as soon as possible. So just for now we won’t open to everybody our secrets as we usually do, but we’ll share the advertising video for Flexy.

 

image

 

For people who speaks enough italian to read some articles we are proud to point out some good articles that talks about this competition and about us (plus all other guys and teams)

 

Links

 

Another good source is facebook with our own page, official Imagine Cup italian page, and the official italian blog (designed by Code Zero :P ).

Comments are always appreciated!

-dave & roby

Prima di iniziare a descrivervi la “tranquilla” pasquetta di quest’anno un po’ di terminologia per i non addetti ai lavori:

Dicesi comunemente porceddu il maialetto schironato (cioè con una spranga che lo trapassa dal c***ulo alla bocca ) questo:

image

che è diverso da un tizio che pensa a questo:

image

:) . “A porceddu tirato” quindi significa “avere un maialetto succulento da cuocere”.

Comunque dopo un’oretta e mezzo di macchina arriviamo nel posto designato per la nostra tranquilla scampagnata in montagna, dove troviamo si e no il mondo :| . Well si tratta di un’area attrezzata per cotture e quindi ci arraffiamo il nostro posto ed iniziamo la ricerca di un tavolino…beh essendo in 9 (5 males e 4 females) siamo riusciti a trovarlo con relativa facilità e a culo pure vicino al barbecue.

La ricerca della legna è stata più difficile, per trovare dei rami grossi abbiamo anche pensato di tirar via da un albero un ramo di circa 50 cm che sembrava ormai morto. “A tipo Jackie Chan”

image

mi sono pure arrampicato per poi scoprire che non si sarebbe staccato manco “a crick”, ma sono dettagli.

Il dettaglio importante è che la gente lì era stra organizzata, non come noi “di città”, cazzo legna seria e maialetto tirato (e schironato).

Well tuttavia ci siamo difesi benissimo con i nostri 3 Kg e passa di carne. Senza contare le 5 bottiglie di vino (e le ragazze non bevevano) hanno fatto il loro “lavoro”.

Vino rigorosamente Cannonau, da bravi sardi :) image

Ovviamente la preparazione della carne e legna richiede birra, non vino, e nemmeno quella mancava :| .

Ce n’era anche per i vicini di barbecue. La cosa incredibile era la quantità enorme di ragazzi che c’erano, una roba da concerto, e c’erano pure dei tizi con un gazebo e della musica a palla, dal reggae al metal. Sti tizi davano merda alla protezione civile in fatto di organizzazione, avevano pure un frigo gigante pieno di birra :| SERIO!!!! E non è tutto. Dopo pranzo tirano fuori batteria, chitarre e microfono e hanno fatto un concerto, così, gratis, per tutti!  Cazzo una mini woodstock. Uno dei nostri “sotto effetto Cannonau” ha cantato tutto il repertorio…Grandi risate, la sbronza goliardica è sempre la migliore :P .

Beh abbiamo un posto dove andare la prossima pasquetta, nel buco del c*** del mondo è stra zeppo di gente e una gran figata di posto! Dove? Col c++++ che ve lo dico hahaha. Sappiate che è in

image

-dave

Hi guys, here we go again. Today me and Xar had a speech on C & C++ dev for students who didn’t even know what a programming language is. It was quite hard and fun, and is the first Seminar released by Code Zero Team.

Anyway Xar did the big job, I simply talked about Object Oriented programming style and created simple tasks to show how to manage classes in Visual C++.

Below the video (in italian), the source codes and the slides.

link to video (ita)

link to slides

link to src codes

-dave

Hi guys I’m sharing as always the full source code and video about my speeches, and, as you already know each seminar is different, each demo is new, and hopefully you’ll enjoy them ;)

The full video of my speech you’ll find in Code Zero TV, and here the sources.

Please take a look even to Roby’s blog (and src) and Giuseppe’s blog (link to post)to get source codes.

Here goes a picture of Giuseppe during the speech ;)

enjoy ;)