IlMerge – Merge .NET Assemblies

by Svetlozar Angelov 2. February 2010 11:06

One of the reasons why I like the .NET framework is the huge amount of third party libraries in the .NET world. However, adding references to dll class libraries leads to several assemblies into your bin directory when sometimes it is more suitable to have just one exe.

Here comes the ILMerge utility. It is a tool for merging multiple .NET assemblies into a single .NET assembly.   

Here is an example how you cam merge an exe and a class library dll into one exe.

lmerge.exe /out:C:\SomePath\TheOnlyOneExe.exe 
                C:\....\bin\Debug\someexe.exe C:\....\bin\Debug\somedll.dll /t:exe

It is important to place your primary assembly (the exe in this case) as the first assembly added in order to keep the entry point. /out: stands for output file and /t: stands for target. 

Tags:

programming

ASP.NET MVC – Pdf View

by Svetlozar Angelov 1. February 2010 11:49

Here is an example how you can return a pdf response in a asp.net mvc project. First of all you need a FileStreamResultmethod in your controller(it handles the pdf request).

public FileStreamResult PdfViewDemo()
{
    Stream Pdf = //code that returns pdf stream
    HttpContext.Response.AddHeader("content-disposition", "attachment; filename=pdfexample.pdf");
    return new FileStreamResult(Pdf, "application/pdf"); 
}  

I’m going to implement a simple pdf load from the hard drive, but the more powerful approach is to generate your pdf “on the fly” using library such as ITextSharp.

public class ReportsHelper
{
    public Stream GeneratePdf()
    {
        FileStream inputPdf = File.OpenRead("C:\\YourPath\SomePdf.pdf");
        MemoryStream ms = new MemoryStream();
        ms.SetLength(inputPdf.Length);
        inputPdf.Read(ms.GetBuffer(), 0, (int)inputPdf.Length);
        return ms;
    }
}   //end ReportsHelper class

and the FileStreamResult method becomes

public FileStreamResult PdfViewDemo() 
{
    ReportsHelper repHelper = new ReportsHelper();
    Stream Pdf = repHelper.GeneratePdf();
    HttpContext.Response.AddHeader("content-disposition", "attachment; filename=pdfexample.pdf");
    return new FileStreamResult(Pdf, "application/pdf"); 
}   

Tags: ,

programming

DBNull.Value To Decimal

by Svetlozar Angelov 26. January 2010 10:00

These day I had to read some data from SqlDataReader and populate a List of user-defined objects.

while (reader.Read())
{
    //populate the list
}

There was a few decimal values in my result set(as the user-defined object had decimal fields) so I needed a conversion to decimal. I was quite surprised that

Convert.ToDecimal(null)

returns 0.00, while

Convert.ToDecimal(DBNull.Value)

throws System.InvalidCastException. Investigating the nature of DbNull.Value I found out that you can not convert it to anything. However a simple extension method would do the trick 

public static class CustomExtensions
{
    public static Decimal ToDecimal(this SqlDataReader reader, string index)
    {
        if (reader[index] == DBNull.Value)
            return 0;
        else
            return Convert.ToDecimal(reader[index]);
    }
}

Tags:

programming

WPF - DataTriggers

by Svetlozar Angelov 19. January 2010 17:43

Let’s see how we can make certain items in a ListBox look different from the others. Let’s create the ItemsSource and the Binding

public partial class Window1 : Window
{
    private ObservableCollection<Student> _students = new ObservableCollection<Student>()
    {
        new Student { Name = "Svetlozar Angelov", Age = 22 }
        , new Student { Name = "Ivan Ivanov", Age = 20  }
        , new Student { Name = "Ivan Georgiev", Age = 23  }
        , new Student { Name = "George Ivanov", Age = 18  }
        , new Student { Name = "Georgi Georgiev", Age = 27  }
        , new Student { Name = "Todor Ivanov", Age = 19  }
    };

    public ObservableCollection<Student> Students
    { get { return _students; } }

    public Window1()
    {
        InitializeComponent();
        listStudents.ItemsSource = Students;
    }
}

public class Student
{
    public string Name { get; set; }
    public int  Age { get; set; }
}

and the xaml

<Window x:Class="WpfApplication4.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:WpfApplication4">
    <ListBox x:Name="listStudents">
        <ListBox.DataContext>local:Window1</ListBox.DataContext>
    </ListBox>
</Window>

Let’s create a DataTemplate for the ListBoxItem to show only the name of a student

<Window.Resources>
    <DataTemplate x:Key="ItemTemplate">
        <TextBlock Text="{Binding Path=Name}" />    
    </DataTemplate>
</Window.Resources>
<ListBox x:Name="listStudents" ItemTemplate="{StaticResource ItemTemplate}">
    <ListBox.DataContext>local:Window1</ListBox.DataContext>
</ListBox>

Let’s suppose we want to change the background of those students, whose age is under 21. The first step is to create a bool property to make the check for us.

public class Student
{
    public string Name { get; set; }
    public int  Age { get; set; }
    public bool UnderAge { get { return Age < 21 ? true : false; } }
}

Now we have to create a Style with a DataTrigger

<Style TargetType="{x:Type ListBoxItem}" x:Key="ItemStyle">
        <Style.Triggers>
            <DataTrigger Binding="{Binding Path=UnderAge}" Value="True">
                <Setter Property="Background" Value="Red" />
            </DataTrigger>
        </Style.Triggers>
</Style>

and to apply it

<ListBox x:Name="listStudents" 
         ItemTemplate="{StaticResource ItemTemplate}" 
         ItemContainerStyle="{StaticResource ItemStyle}">
    <ListBox.DataContext>local:Window1</ListBox.DataContext>
</ListBox>

There is nothing interesting about DataTriggers, just another example why Binding is so cool.

Tags:

programming

WPF – Binding to a DateTime

by Svetlozar Angelov 18. January 2010 16:33

Suppose we want to bind a TextBlock.Text to a DateTime.Now – the first step is to add the namespace -

xmlns:sys="clr-namespace:System;assembly=mscorlib"

Then the binding -

<TextBlock Text="{Binding Source={x:Static sys:DateTime.Now}, StringFormat=D}"/> 

It looks fine, short and clean, but unfortunately it doesn’t… For some reason in the biding system by default, WPF uses en-US as the culture, regardless of the system settings. So if you are with Bulgarian locale settings (Like I am) this doesn’t work (the date is in English). Of course there is a workaround, you have to change the used culture by hand. This must be done before any GUI created, so a good place to put the code is into the Startup EventHandler -

<Application x:Class="WpfApplication2.App"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Startup="Application_Startup"
    StartupUri="Window1.xaml">
</Application>

and the actual implementation -

private void Application_Startup(object sender, StartupEventArgs e)
{
    FrameworkElement.LanguageProperty.OverrideMetadata(typeof(FrameworkElement)
        , new FrameworkPropertyMetadata(
            XmlLanguage.GetLanguage(CultureInfo.CurrentCulture.IetfLanguageTag)));
}

The culture is changed, the Date is ok.

Tags:

programming

Powered by BlogEngine.NET 1.5.0.7
Theme by Mads Kristensen