One line how to’s : Save text in a file, or read text from a file.

Posted June 12th, 2011 in .NET, HowTo by Sam Beauvois

Sometimes your solution lies in a single line.

How to save a string in a text file


System.IO.File.WriteAllText("c://yourfile.txt",
"here is the content of my file !");

How to read a text file


string content =  System.IO.File.ReadAllText("c://yourfile.txt");
How does it work ?

A bit or Reflector gives us :

For the write method


public static void WriteAllText(string path, string contents)
{
if (path == null)
{
throw new ArgumentNullException("path");
}
if (path.Length == 0)
{
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
}
InternalWriteAllText(path, contents, StreamWriter.UTF8NoBOM);
}

and the “InternalWriteAllText” method :


private static void InternalWriteAllText(string path, string contents, Encoding encoding)
{
using (StreamWriter writer = new StreamWriter(path, false, encoding))
{
writer.Write(contents);
}
}

For the Read method :

public static string ReadAllText(string path)
{
    if (path == null)
    {
        throw new ArgumentNullException("path");
    }
    if (path.Length == 0)
    {
        throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
    }
    return InternalReadAllText(path, Encoding.UTF8);
}

And the “InternalReadAllText” :

private static string InternalReadAllText(string path, Encoding encoding)
{
    using (StreamReader reader = new StreamReader(path, encoding))
    {
        return reader.ReadToEnd();
    }
}

As you can see it don’t check if the file exists, so you have to check it by yourself :


if (System.IO.File.Exists("your file path"))
{
string content = System.IO.File.ReadAllText("your file path");
}
public static string ReadAllText(string path) { if (path == null) { throw new ArgumentNullException(“path”); } if (path.Length == 0) { throw new ArgumentException(Environment.GetResourceString(“Argument_EmptyPath”)); } return InternalReadAllText(path, Encoding.UTF8); }

6+ sources of videocasts

Posted March 3rd, 2011 in .NET, Resources by admin

Here is a list of sites where you can find videos to form youself and learn a bit of new things

Get the first day of the current week

Posted February 24th, 2011 in .NET, Extension Methods by admin

Here is a quick way to get the first day of the current week.

If you are happy with sunday as the first day of the week, then you can simply do this :


 public static DateTime FirstDayOfWeek(this DateTime date)
 {
            return DateTime.Today.AddDays(-(int)DateTime.Today.DayOfWeek);
 }

But if you want that the first day of the week matches your culture (eg: the belgian week starts on monday), you have to take care of the culture’s DateTime format.

So the method will change a bit :


public static DateTime FirstDayOfWeek(this DateTime date)
{
     return DateTime.Today.AddDays(-((int)DateTime.Today.DayOfWeek - (int)CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek));
}
Usage :

    DateTime FirstDayOfWeek = DateTime.Today.FirstDayOfWeek();

or

 DateTime FirstDayOfWeek = DateTime.Now.FirstDayOfWeek();

Windows Phone 7 Numeric TextBox

Posted January 11th, 2011 in .NET, WP7 by Sam Beauvois

There is no “built in” numeric textbox in the current Silverlight for Windows phone.

Here a few solutions to realize one anyway : it remembers me the early years of the .NET framework or nothing was in the framework …

All my solutions are based on the same principle : we handle the keydown event of a textbox then we check the code of the pressed key.

If the code matches a number, we let it do, in the other case we stop the process.

First solution :  A simple textbox

In the xaml of the application, we add a textbox and we set it’s InputScrope property to “TelephoneNumber” to set the keyboard to a layout with numbers (we should also use the “Number” value for this property but the keys are smaller, this is not the best for a small device) so the input keyboard will look like this

This is not enough, because we can use the special characters (*, #, ., / and the space bar).

So we add an handler for the keydown event


<TextBox Name="SimpleTbx" InputScope="TelephoneNumber" KeyDown="SimpleTbx_KeyDown"/>

In the code behind, we will add our logic:

First, we specify an array of the allowed key codes :


private readonly Key[] numeric = new Key[] {Key.Back, Key.NumPad0, Key.NumPad1, Key.NumPad2, Key.NumPad3, Key.NumPad4,
Key.NumPad5, Key.NumPad6, Key.NumPad7, Key.NumPad8, Key.NumPad9 };

(don’t forget the back button because we still want to use it ! It works also if I don’t put it in the array but I prefer to let it just in case)

In the keydown event handler we check the pressed key code:


private void SimpleTbx_KeyDown(object sender, KeyEventArgs e)
{
// handles non numeric
if (Array.IndexOf(numeric, e.Key) == -1)
{
e.Handled = true;
}
}

If the array don’t contains the code we stop to process the key.

That’s it for the first solution.

Second solution : create an user control

If we don’t want to repeat the operations of the first solution on every textbox in the project we can use a user control.

So we add an user control to the project (right click on the project-> Add –> new item)

In this user control we add a textbox and we repeat exactly the same operations than for the first solution.


<Grid x:Name="LayoutRoot" Background="{StaticResource PhoneChromeBrush}" Height="Auto" Width="Auto">
<TextBox Name="NumericTextBox" KeyDown="NumericTextBox_KeyDown" InputScope="TelephoneNumber"/>
</Grid>

We still have a little additional work to do : add a property linked to the text of the textbox. So we can retrieve the result in our page.

public string Text
{
  get
  {
    return NumericTextBox.Text;
  }
  set
  {
    NumericTextBox.Text = value;
  }
}

To use it in the mainpage, we need to reference the namespace of the usercontrol:


xmlns:my="clr-namespace:WPNumericTextBox.Controls"

then we can use it this way :


<my:NumericTextBoxUserControl x:Name="NumericTbxUC" />

End of the second solution.

Third solution : inherit the textbox to create a numeric textbox

We can inherit the textbox and made it responsive to numbers only:

  • Add a class to your project
  • Inherit from textbox
  • Set the InputScope to InputScopeNameValue.TelephoneLocalNumber
  • Override the keydown event
  • That’s it .

Here is the complete code :


using System;
using System.Windows.Controls;
using System.Windows.Input;

namespace WPNumericTextBox.Controls
{
public class NumericTextBox : TextBox
{
private readonly Key[] numeric = new Key[] {Key.Back, Key.NumPad0, Key.NumPad1, Key.NumPad2, Key.NumPad3, Key.NumPad4,
Key.NumPad5, Key.NumPad6, Key.NumPad7, Key.NumPad8, Key.NumPad9 };

public NumericTextBox()
{
this.InputScope = new InputScope();
this.InputScope.Names.Add(new InputScopeName() { NameValue = InputScopeNameValue.TelephoneLocalNumber });
}

protected override void OnKeyDown(KeyEventArgs e)
{
if(Array.IndexOf(numeric,e.Key) == -1)
{
e.Handled = true;
}
base.OnKeyDown(e); // important, if not called the back button is not handled
}
}

}

do not forgot to call the base.OnKeyDown method, otherwise your back button will be inefficient.

To use it in the mainpage : reference the namespace of the usercontrol:


xmlns:my="clr-namespace:WPNumericTextBox.Controls"

then use the control :


<my:NumericTextBox x:Name="NumTbx"/>

Fourth Solution : create a numeric textbox in a control library

This solution is an improvement of the third : we add our control in a windows phone library so we can reuse it for another project !

To use it in the mainpage : reference the namespace of the usercontrol:


xmlns:my1="clr-namespace:WPControls;assembly=WPControls"

then use the control :


<my1:NumericTextBox Name="NumericTextBox"/>

I created a demo app :

The full demo source is available for download :

http://www.sambeauvois.be/Demos/WP7/NumericTextBox/WPNumericTextBox.zip

Do not overuse the custom exceptions, use the ones provided by the framework

Posted January 6th, 2011 in .NET by Sam Beauvois

As a .NET developper you may be tempted to create a custom exception class for each of your exceptions you throw.

But plenty of them are already present in the .NET framework.

If your need matches one of these Exceptions, use it instead of reinvent the wheel.

I generated a list of the available exceptions, you can consult it here.