Create default values in a datatable

Instead iterating for each row setting a default value like this

foreach(DataRow dr in dt.Rows)
{
dr["column"] = defaultValue
}


Just set the .DefaultValue property in the column. This will save some seconds.

dt.Columns["column"].DefaultValue = defaultValue;


You can also set expressions for calculated fields, per example if you want to concatenate the values of two columns.


dt.Columns["column"].Expression = "Column1+Column2";

Read command line args in a WPF application

If you are used to Winforms programming it is a little bit tricky how to read parameters sent from the command line. Well, in reality it is quite similar.
When you create a WPF application, It sets the App.Xaml as the starting point for the application. You normally have something like this:

xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
StartupUri="Window1.xaml">





This starting point is defined in the project properties

Well, the only thing you have to do to receive the parameters is define the event “Startup” in that App.Xaml

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





By doing this, the event handler is automatically generated in App.xaml.cs

///
/// Interaction logic for App.xaml
///

public partial class App : Application
{
private void Application_Startup(object sender, StartupEventArgs e)
{

}
}

Well, the commandline Arguments are defined in the StartupEventArgs, as a string array

Now we have the command line args, but How to read it from the application?
This is very easy, just define a public property that get those values

///
/// Interaction logic for App.xaml
///

public partial class App : Application
{
private static string[] _CommandLineArgs = null;
///
/// Command Line Arguments sent to the application
///

public static string[] CommandLineArgs
{
get
{
return _CommandLineArgs;
}
}
private void Application_Startup(object sender, StartupEventArgs e)
{
_CommandLineArgs = e.Args;
}
}

Now to access this we just call App.CommandLineArgs anywhere in our application

public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
string [] commandLineArgs = App.CommandLineArgs;
foreach(string argument in commandLineArgs)
{
MessageBox.Show(argument);
}
}
}

How to test it?
Just set the parameters you want to receive under the command line arguments in the debug tab of the project properties

That's all

Download a file in an aspx page

Simple code to download a file from the server
internal static class AspxHelper
{
///
/// Renders the file to the users Browser by specifying the file as a filestream
///

/// The user s page
/// The file report as a filestream.
/// Collection of paths of files to download
internal static void DownloadFile(System.Web.UI.Page pg, string _downloadpath)
{


FileStream fileReportStream = null;
try
{
fileReportStream = File.OpenRead(_downloadpath);
byte[] Buffer = new byte[fileReportStream.Length];
fileReportStream.Read(Buffer, 0, Buffer.Length);

string fileName = _downloadpath;
if (fileName.Contains("\\"))
{
fileName = fileName.Substring(fileName.LastIndexOf("\\")+1);
}
pg.Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName);

switch (new System.IO.FileInfo(_downloadpath).Extension.ToUpper())
{
case Constants.Extensions.PDF:
pg.Response.ContentType = "application/pdf";
break;
case Constants.Extensions.WORD:
pg.Response.ContentType = "application/msword";
break;
case Constants.Extensions.ACCESS:
pg.Response.ContentType = "application/vnd.ms-access";
break;
case Constants.Extensions.XML:
pg.Response.ContentType = "application/xml";
break;
case Constants.Extensions.ZIP:
pg.Response.ContentType = "application/zip";
break;
default:
break;
}

pg.Response.BinaryWrite(Buffer);
pg.Response.Flush();
pg.Response.Close();
pg.Response.End();


}
catch (Exception)
{
throw;
}
finally
{
if (fileReportStream != null)
{
fileReportStream.Close();
}
}
}
}

How to debug Databindings in WPF

While playing with WPF, I’ve realized databindings are hard to debug, but the framework provides an easy way to be able to debug it. Let’s see:

What I’m Going to do is Create an UserControl with a CheckBox. This checkbox will be visible depending on the value of a Boolean Property of the User Control Named “ShowVisibleCheck”

First of all we create that property in the User Control:


private bool _ShowVisibleCheck = false;
public bool ShowVisibleCheck
{
get
{
return _ShowVisibleCheck;
}
set
{
_ShowVisibleCheck = value;
}
}

I could have used the functionality framework 3 gives to just declare the property

public bool ShowVisibleCheck {get;set;}

So why didn’t I do that?

To be able to bind a property, the property must:
1 – Be a dependency property (Unless you only bind by “OneWayToSource” when that is not required)
2- Implement the INotifyPropertyChanged Interface (that is why I didn’t declare the property like that)

So let’s go:

To set this property as a dependency property we just register the dependency property as static, with the same name as our property and finishing the name with the “property” suffix. (note Row is the name of the class where my user control belongs to)


public static DependencyProperty ShowVisibleCheckProperty =
DependencyProperty.Register("ShowVisibleCheck", typeof(bool), typeof(Row));


Then we will implement the INotifyPropertyChanged Interface
In the class we set the interface:


public partial class Row : UserControl, INotifyPropertyChanged


This will set the members (in this case one event)


#region INotifyPropertyChanged Members

public event PropertyChangedEventHandler PropertyChanged;

#endregion



And in our property, we will notify when this property changes, so WPF will be able to redraw the binding according to the property.

Now, we have the property ok to be used, but there is one more problem. In this case I used a Boolean property instead a Visibility one to set the visibility of my CheckBox, I only have done this like this to introduce a converter into this code.
If I try to do a binding directly from a Boolean property (ShowVisibleCheck) versus a visibility one (Checkbox.Visible) I will have a casting problem. To help me solve that, I can use a class that will implement the IValueConverter that will manage to convert the value “true” to Visibility.Visible; and the value “false” to Visibility.Collapsed;
This is the code of my converter class:


namespace ReportDesigner.Classes
{
internal class VisibleConverter:IValueConverter
{
#region IValueConverter Members

public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
Boolean source = (Boolean)value;
if (source)
{
return Visibility.Visible;
}
else
{
return Visibility.Collapsed;
}
}

public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}

#endregion
}
}


Note I receive an object. I know this object is a Boolean because the object I’ll be passing is the ShowVisibleCheck property, and the only thing I have to do is convert it to Visibility.

Once this is done, to specify to use the converter, we will use Converter={StaticResource visibleConverter} in the binding of the property, where visibleConverter is an static resource in my user control



And classes Represents the namespace of my converter:

xmlns:classes="clr-namespace:ReportDesigner.Classes"


So now everything should be placed in order to make the binding.
To bind to a property of myself we will use the keyword RelativeSource={RelativeSource Self} this means I’ll do the binding to another property of my class. If I put it on the checkbox, it means it will bind this property to another property in my checkbox.
So if the checkbox is contained in the user control, I can access It via the Path using the keyword Parent.

Visibility="{Binding RelativeSource={RelativeSource Self}, Path=Parent.ShowVisibleCheck, Converter={StaticResource visibleConverter}}

And Now it should work, but when I run it … It doesn’t work!. Why?
NOW IS WHEN THE DATABINDING DEBUGGING COMES!!!

To introduce debugging of databinding there are two steps:
1 – Create a reference to System.Diagnostics in your namespaces
xmlns:debug="clr-namespace:System.Diagnostics;assembly=WindowsBase"
2 – Add debug:PresentationTraceSources.TraceLevel=High in the binding.

By doing this, Visual Studio will generate output information for the bindings, so I can check what is happening.
If I go to the output window I can see… Oh!, I forgot my control was contained in a Grid, and then in a StackPanel. I have to put another 2 Parents more in the Path!!!!
(In my case) UserControl (contains the property)->Grid->StackPanel->CheckBox




“System.Windows.Data Error: 39 : BindingExpression path error: 'ShowVisibleCheck' property not found on 'object' ''StackPanel' (Name='')'. BindingExpression:Path=Parent.ShowVisibleCheck; DataItem='CheckBox' (Name=''); target element is 'CheckBox' (Name=''); target property is 'Visibility' (type 'Visibility')”


So now I fix it, and this is how the binding ends:



Now it works!!!

TextChanged event handler in a WPF ComboBox

Looking to the WPF, I can see the event TextChanged has disappeared from the combo boxes. I am surprised, because I found it really useful for the editable Combo Boxes (IsEditable ="True").

So as I needed it for my personal purposes I decided to create a custom combo control inherited from the base one that has that event.

First of all I create a custom class, and I make it Inherit from combobox:



Now, the approach is create a TextBox control, that has the TextChanged event, and bind it to the ComboBox. As this is a class, we won't be able to do it via XAML.
Programmatically, it is something like this:

Instead iterating for each row setting a default value like this

using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Controls;
using System.Windows.Data;

namespace WpfApplication1
{
internal class CustomComboBox : System.Windows.Controls.ComboBox
{
//Define the TextChangedEventHandler
public event TextChangedEventHandler TextChanged;

//Have a texbox to handle the textchanged event of the combo
TextBox tb2;

///
/// On EndInit the control is fully loaded
///

public override void EndInit()
{
//Call the base method
base.EndInit();
//Create the texbox it is going to be linket to our combobox
tb2 = new TextBox();
//And bind the text of the texbox...
Binding b = new Binding("Text");
//To the text of the combo
b.Source = this;
//Set the bind
BindingOperations.SetBinding(tb2, TextBox.TextProperty, b);
//And handle the textchanged event of the textbox.
//There we will raise the textchanged event of the combobox
tb2.TextChanged += new TextChangedEventHandler(tb2_TextChanged);

}

void tb2_TextChanged(object sender, TextChangedEventArgs e)
{
//Just raise the textChanged Event of the combo if something it is
//subscribed to our event
if (TextChanged != null)
{
TextChanged(sender, e);
}
}
}
}

Starting the blog

Today I've created this blog. My aim is to write articles about the problems I face during work and how did I solve it, and talk about .Net technologies. I hope I can achieve at least a bit of what I plan..