martedì 17 dicembre 2013

Merge several TIFF images to single multipage TIFF

C# .NET Framework 4.0

In my application, I have wanted to merge and compress several TIFF images to single multipage TIFF, for this purpose I used the framework Bitmap object with EncoderParameters like explained in this link http://stackoverflow.com/questions/3478292/whats-the-recommended-tiff-compression-for-color-photos/3480411#3480411 . Unfortunately, this solution was very slow! 3’:20’’ for merging of 1420 images.


So I searched in the web and I found this awesome solution http://bitmiracle.com/libtiff/help/merge-several-tiff-images-to-single-multipage-tiff.aspx : the time for merging images has dropped to 26’’! 

That’s miracle!

giovedì 28 novembre 2013

WPF (MVVM) - Retrieve the Listbox SelectedItems property

C# .NET Framework 4.0 MVVM Light Toolkit

In my WPF (MVVM) application, I want to use the Listbox SelectedItems property but this property has no setter and for this reason it’s not “bindable“ to my view model.
I have tried to use the property (IsSelected) in my object and in the XAML this item container style.

<ListBox.ItemContainerStyle>
        <Style TargetType="{x:Type ListBoxItem}">
<Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
        </Style>
</ListBox.ItemContainerStyle>

This solution works fine if the Listbox SelectionMode property is set to Single but if the selection mode is “Extended” (SelectionMode="Extended") it doesn’t work correctly, sometimes a few items remain selected.
Finally, I found a solution that works for me. I use the MenuItem’s CommandParameter for accessing to the Listbox SelectedItems property.

Like this.

<ListBox.ContextMenu>
<ContextMenu>
                    <MenuItem Command="{Binding AddImagesSelectedCommand}" CommandParameter="{Binding PlacementTarget.SelectedItems, RelativeSource={RelativeSource AncestorType={x:Type ContextMenu}}}" Header="{Binding Source={StaticResource CustomResources}, Path=LocalizedStrings.mnuAddImagesSelected}" />
</ContextMenu>
</ListBox.ContextMenu> 

Then in the view model:

AddImagesSelectedCommand = new RelayCommand<object>(OnAddImagesSelected, CanAddImagesSelected);

private void OnAddImagesSelected(object param)
        {
            var selectedImages = ((IEnumerable)param).Cast<CaptureImage>().ToList();

     //To do something …           
        }   

private bool CanAddImagesSelected(object param)
        {
            if (param != null)
            {
                var selectedImages = ((IEnumerable) param).Cast<CaptureImage>().ToList();

                return (selectedImages != null && selectedImages.Count > 0);
            }
            return false;
        }

We must use the PlacementTarget object because the ContextMenu is not in the same part of the Visual Tree, so that is why you cannot use ElementName etc. to reference the ListBox.


See you soon for the next trick!

lunedì 11 novembre 2013

WPF - Zoom an image with the slider control.

C# .NET Framework 4.0

In a WPF (XAML) view I want to zoom an image using a slider control and also in this occasion the binding help me to do this with a few code rows.

<Grid>
<Grid.RowDefinitions>
             <RowDefinition Height="*"></RowDefinition>
              <RowDefinition Height="30"></RowDefinition>
       </Grid.RowDefinitions>
       <Image Grid.Row="0" Name="ImgReader" Source="Images/Exit.png" Stretch="Uniform" RenderTransformOrigin="0.5, 0.5" >
             <Image.RenderTransform>
                    <ScaleTransform ScaleX="{Binding ElementName=SliderDocument, Path=Value}" ScaleY="{Binding ElementName=SliderDocument, Path=Value}"/>
              </Image.RenderTransform>
       </Image>
       <Slider Grid.Row="1" Name="SliderDocument" VerticalAlignment="Center" Minimum="0.1" Maximum="1" />
</Grid>


It’s great!

Strange error: 'DockingManager' does not exist in XML namespace ...' - Unblock DLL

C# .NET Framework 4.0

I have had a strange error in my WPF application when I referenced an external library (Xceed.Wpf.AvalonDock.dll).

This error

 Error The tag 'DockingManager' does not exist in XML namespace 'http://avalondock.codeplex.com'. Line 41 Position 10.

 appeared at design time but not at run-time, so after a few hours I’ve founded that this was a “security error”, because Windows protects you from components downloaded from the Internet.



After that I clicked on “Unblock” and the error is missed.

Thanks Microsoft … :-|

mercoledì 25 settembre 2013

martedì 16 luglio 2013

Could not load file or assembly Microsoft.Practices.EnterpriseLibrary.Logging exception

C# 4.0, MS Practices Enterprise Library 5.0

I have used the Enterprise Library Configuration tool for creating a Logging Application Block and I have obtained a configuration file like this:

<section name="loggingConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.LoggingSettings, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="true" />
<loggingConfiguration name="" tracingEnabled="true" defaultCategory="General">
                …
                …
</loggingConfiguration>

Unfortunately, I got the following exception while trying to use the Enterprise Library Logging Application Block:

“An error occurred creating the configuration section handler for validation: Could not load file or assembly 'Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)”

I solved this problem by setting to null the PublicKeyToken.


PublicKeyToken=null

giovedì 4 luglio 2013

Retrieving data from a SQL Server stored procedure using LINQ to entities

C# .NET Framework 4.0, SQL Server 2008, ADO.NET Entity Data Model, LINQ to Entities

I’ve a GetCompanies SQL Server 2008 stored procedure that returns a resultset like this

Field1
Field2
Field3
Field4
Field5
Field6
Field7
Field8
VE
7471
033333333
Environment s.r.l.
1
Roma, 6
Vigonza
35010
VE
7499
033333322
Active s.r.l.
4
Venezia, 8
Padova
35100

So, in my application I want to read this resultset data using LINQ to Entities.

1.       Add a new ADO.NET Entity Data Model (Shapshot.edmx) at the solution.
2.       Follow the wizard for creating a new connection to your database and select the GetCompanies (for this example) stored procedure from the objects list.
3.       Click on Model Browser.
4.       Select the SnapshotModel tree, ComplexTypes.
a.       Right click on CopmplexTypes and then click on “Add new Complex Type”.
b.      Type a name, for example “CompanyEntity”.
                                                               i.      Select CompanyEntity, right click on “Add” -> “Scalar Property” and select the type property: Int32, String, Boolean and so on.
                                                             ii.      In my example I obtain a structure like this
1.       Field1 -> String
2.       Field2 -> Int32
3.       Field3 -> String
4.       Field4 -> String
5.       Field5 -> Int32
6.       Field6 -> String
7.       Field7 -> String
8.       Field8 -> String
c.       Expand the Function Imports folder and double click on GetCompanies stored procedure, you‘ll see a dialog box like this. Select the “Complex” option button and then the type that you have created before.



5.       Now, you can retrieve data using this C# code (Company is an internal object).
GetCompanies() returns a System.Data.Objects.ObjectResult<CompanyEntity> object.

public Company[] GetCompanies()
        {   
            var companiesList = new List<Company>();
            using (var context = new SnapshotEntities())
            {
                var query = context.GetCompanies();

                foreach (var c in query)
                {
                    var company = new Company
                        {
                            Field1 = c.Field1,
                            Field2 = c.Field2,
                            Field3 = c.Field3,
                            Field4 = c.Field4,
                            Field5 = c.Field5,
                            Field6 = c.Field6,
                            Field7 = c.Field7
                            Field8 = c.Field8
                        };

                    companiesList.Add(company);
                }
            }

            return companiesList.ToArray();
        }


That’s all folk!

lunedì 1 luglio 2013

Rebuild Enterprise Library 5.0 (script error)

Windows 7 Professional 64 bit

After I ‘ve downloaded the Microsoft Enteprise Libray 5.0, I wanted to rebuild all assemblies by ..\EntLib50Src\Scripts\BuildLibrary.bat script, but I received following error: “The specified solution configuration Debug|BPC is invalid. Please specify a valid solution configuration using the Configuration and Platform properties (e.g. MSBuild.exe Solution.sln /p:Configuration=Debug /p:Platform=”Any CPU”) or leave those properties blank to use the default solution configuration."

So, in the 2013 if you want resolve this problem you MUST delete a key registry.

Using regedit.exe navigate to the registry path

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment

and select the key Platform. Platform had the value BPC.
Then you delete only the value BPC. After this, the key Platform was still there but empty. Close Regedit, restart your PC and run the BuildLibrary.bat script.

giovedì 30 maggio 2013

Daily log file using the Microsoft Practices Enterprise Library Logging

C# 4.0, Microsoft Practices Enterprise Library 5.0

When you implement a Microsoft Practices Enterprise Library Logging, maybe you could need to distinguish  the file logging by date and for to do this you can follow these traces.

1.       Open the configuration file (like app.config) and search the “listeners” element near “loggingConfiguration”, set the “add” element’s attribute “fileName” in this way.

<add fileName="C:\Project\logs\Project.log" header="----------------------------------------" footer="----------------------------------------" formatter="Text Formatter" listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.RollingFlatFileTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" traceOutputOptions="DateTime" filter="All" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.RollingFlatFileTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" name="RollingFile TraceListener" rollFileExistsBehavior="Increment" rollInterval="Day" rollSizeKB="0" timeStampPattern="yyyy-MM-dd"/>

2.       Search the “listeners” element near “categorySources”, set the “add” element’s attribute “name” to “RollingFile TraceListener”.

<add name="RollingFile TraceListener"/>

3.       Search the “listeners” element near “specialSources”, set the “add” element’s attribute “name” to “RollingFile TraceListener”.

<add name="RollingFile TraceListener"/>

In this way you obtain a log file similar this:
Project.2012-08-20.1.log


mercoledì 17 aprile 2013

POST WebRequest e Content-Type


C# 2.0

Dovevo effettuare una richiesta POST ad un Url passando alcuni parametri e per far questo ho utilizzato le seguenti righe di codice:

string url = "http://pippo.it/api";

WSSEDigest wsseDigest = new WSSEDigest();
string token = wsseDigest.GetPasswordDigestAsBase64(userName, password);

HttpWebRequest webReq = (HttpWebRequestWebRequest.Create(url);
webReq.Method = "POST";
webReq.Headers["X-WSSE"] = token;
webReq.ContentType = "application/x-www-form-urlencoded";

ASCIIEncoding encoding = new ASCIIEncoding();
byte[] data = encoding.GetBytes(uriRequestBurn.Parameters);
Stream requestParametersStream = webReq.GetRequestStream();
requestParametersStream.Write(data, 0, data.Length);
requestParametersStream.Close();

try
{
    HttpWebResponse webResp = (HttpWebResponse) webReq.GetResponse();
    Stream answer = webResp.GetResponseStream();
    StreamReader answerReader = new StreamReader(answer);
    string responseContent = answerReader.ReadToEnd();
}
catch (WebException ex)
{
    Stream answer = ex.Response.GetResponseStream();
    StreamReader answerReader = new StreamReader(answer);
    string message = ex.Message;
    string responseContent = answerReader.ReadToEnd();                       
}

Inizialmente non specificavo il content-type ed avevo la seguente anomalia: per alcune chiamate tutto andava bene per altre invece mi ritornava sempre una Web Eception, anche analizzando il flusso dati con Fiddler tutto mi sembrava corretto, i parametri  sembravano sempre valorizzati allo stesso modo, peccato però che dalla parte del servizio arrivasse, in questo caso, sempre un array vuoto.

Alla fine grazie al Plug-In Poster di Firefox sono riuscito a capire che il problema stava nel Content-Type.