This project is read-only.
Quickstart:
Table of content:
1 - Register and read a simple value
2 - Register and read a simple value - other types
3 - Write a simple QueryString token
4 - Instantiate IUriWriter
5 - Restrict allowed values with validation
6 - Encryption of tokens
7 - Entryption of entire querystring
8 - Change path of uri
9 - Suppress Exceptions
10 - Using checksums
11 - Customizations (to come...)
12 - Nullable types

1 - Register and read a simple value

  • First register the token which we want to work with. In this case a personId, which we read from the parameter "pid". We declare the variable using the generic IQueryStringToken interface, and initialize to an instance of ValueTypeToken. This class has various properties which is covered later.

using Birkelund.QueryStrings.Interfaces;
using Birkelund.QueryStrings.Tokens;

internal static class QueryStrings
{
  // recommended signature is public static readonly 
  // but is here shorter because of readability
  public static IQueryStringToken<int> PersonId = new ValueTypeToken<int>("pid");
}
  • Now we can read the value from our web page. The read value is of cause of type int
protected void Page_Load(object sender, EventArgs e)
{
  // assuming the querystring is http://test.com/default.aspx?pid=3
  // personId will get the value of 3
  int personId = QueryStrings.PersonId.ReadValue()
}

2 - Register and read a simple value - other types

As above example other types can be used. There are some examples. Only the registration is shown. The reading is similar to above - strongly typed reading.
Built in tokens are located in "QueryStrings.Tokens" namespace.
internal static class QueryStrings
{
  public static IQueryStringToken<MyEnum> MyEnum = new ValueTypeToken<MyEnum>("myenum");
  public static IQueryStringToken<bool> DoSort = new ValueTypeToken<bool>("sort");
  public static IQueryStringToken<DateTime> Time = new ValueTypeToken<DateTime>("time");
  public static IQueryStringToken<Guid> Id = new ValueTypeToken<Guid>("id");
  public static IQueryStringToken<float> Number = new ValueTypeToken<float>("number");
  // note the StringToken class is used for string types
  public static IQueryStringToken<string> Text = new StringToken("text");
  public static IQueryStringToken<DateTime> CustomDate = new CustomDateTimeToken("custom");
  public static IQueryStringToken<Uri> Link = new UriToken("redirect");
}

3 - Write a simple QueryString token

This example shows how to write tokens to the querystring.
  • The registration for this example
internal static class QueryStrings
{
  public static IQueryStringToken<bool> DoSort = new ValueTypeToken<bool>("sort");
  public static IQueryStringToken<int> Id = new ValueTypeToken<int>("id");
}
  • Then the writing
protected void Page_Load(object sender, EventArgs e)
{
  // say current url = http://test.com/default.aspx....
  IUriWriter writer = UriWriterFactory.CreateEmptyFromCurrentUri();
  // we write two values via the fluent API. Writing is strongly typed.
  writer
    .SetToken(QueryStrings.DoSort, false)
    .SetToken(QueryStrings.Id, 123);
  
  // .... uri wil have the value http://test.com/default.aspx?id=123&sort=False
  Uri uri = writer.GenerateQueryAsUri();
  string uriString = writer.GenerateQueryAsString();
}

4 - Instantiate IUriWriter

  • There are several options to work with IUriWriter. Here is a quick walk through
// The current url is http://test.com/default.aspx?id=4&sort=False

// Remove all querystring tokens: http://test.com/default.aspx
IUriWriter writer = 
  UriWriterFactory.CreateEmptyFromCurrentUri();

// Let querystring tokens remain unchanged: http://test.com/default.aspx?id=4&sort=False
IUriWriter writer2 = 
  UriWriterFactory.CreateFromCurrentUri();

// Remove all querystring tokens from our custom uri http://test.com/default.aspx
IUriWriter writer3 = 
  UriWriterFactory.CreateEmptyFromUri("http://test.com/default.aspx?id=4&sort=False");

// Let querystring tokens remain unchanged: http://test.com/default.aspx?id=4&sort=False
IUriWriter writer4 = 
  UriWriterFactory.CreateFromUri("http://test.com/default.aspx?id=4&sort=False");

5 - Restrict allowed values with validation

This example shows how to add validation to your tokens.

internal static class QueryStrings
{
  public static IQueryStringToken<int> Id = new ValueTypeToken<int>("id")
  {
    //validates that the read value is between 0 and 10. 
    // This is a just delegate so anything is possible in here
    Validator = (input) => input > 0 && input < 10 
  };
}

protected void Page_Load(object sender, EventArgs e)
{
  try
  {
    // if the value does not meet the validation criteria, an exception is thrown
    int id = QueryStrings.Id.ReadValue();
  }
  catch (TokenParserException ex)
  {
    if (ex.FailureArgs.Reason == FailureReason.ValidationError)
    {
      // do something
    }
  }
}

6 - Encryption of tokens

Here you will see how easy is it to encrypt by using the default encryption. It is invisible to the reading that we work with encryption. That makes makes it easy to change strategy any time (even though you should be aware that if you suddenly start to use encryption bookmarks will change as well)

internal static class QueryStrings
{
  public static IQueryStringToken<int> Id = new ValueTypeTokenEncrypted<int>("id");
  public static IQueryStringToken<string> Text = new StringTokenEncrypted("text");
}

protected void Page_Load(object sender, EventArgs e)
{
  IUriWriter writer = UriWriterFactory.CreateEmptyFromCurrentUri();
  writer
    .SetToken(QueryStrings.Id, 2)
    .SetToken(QueryStrings.Text, "secret");

  // Uri = http://localhost:3489/samples/sample1.aspx?id=wyvJ773GZf4%3d&text=i5I23QTojSY%3d
  // Note that each value is encrypted seperately in the querystring
  Uri uri = writer.GenerateQueryAsUri();

  // id = 2. We read the value from the parameter uri but could also have chosen to 
  // read from current uri (as the prev. examples). Note that the encryption/decryption is 
  // handled for you, so no changed code here.
  int id = QueryStrings.Id.ReadValue(uri);
  // text = secret
  string text = QueryStrings.Text.ReadValue(uri); 
}

7 - Entryption of entire querystring

Also the entire querystring can be encrypted by following this example. Again, the reader has no clue that encryption is being used
internal static class QueryStrings
{
  static QueryStrings()
  {
    //Simply tell the framework that full (default) encryption should take place. 
    // An overload let you provide a custom encryption algorithm.
    QueryStringConfiguration.Instance.SetFullEncryption();
  }

  // class ValueTypeToken is now used - not ValueTypeTokenEncrypted.
  public static IQueryStringToken<int> Id = new ValueTypeToken<int>("id");
  public static IQueryStringToken<string> Text = new StringToken("text");
}

protected void Page_Load(object sender, EventArgs e)
{
  IUriWriter writer = UriWriterFactory.CreateEmptyFromCurrentUri();
  writer
    .SetToken(QueryStrings.Id, 2)
    .SetToken(QueryStrings.Text, "secret");

  // Uri = http://localhost:3489/samples/sample1.aspx?fe=FVEGH//WKyYrlCq0jArjC14uWOnAfchk
  // Note that only one value seams to appear in the querystring

  Uri uri = writer.GenerateQueryAsUri();
  // id = 2. We read the value from the parameter uri but could also have chosen to 
  // read from current uri (as the prev. examples). Note that the encryption/decryption is 
  // handled for you, so no changed code here.
  int id = QueryStrings.Id.ReadValue(uri);
  // text = secret
  string text = QueryStrings.Text.ReadValue(uri);
}

8 - Change path of uri

It is possible to change the uri by using the following operations:
protected void Page_Load(object sender, EventArgs e)
{
  IUriWriter writer = UriWriterFactory.CreateFromUri("http://test.com/pages/temp/page1.aspx")
    .DirectoryBack(1) // go one directory back
    .DirectoryAdd("newDir") // ~ can be used to clear the directory structure
    .SetFileName(null); // could also enter a real filename

  // uri = http://test.com/pages/newDir/
  string uri = writer.GenerateQueryAsString();
}

9 - Suppress Exceptions

Per default an exception is thrown is something wrong happends. Though it is possible to supress throwing the Exception individually on each token. See here how.
internal static class QueryStrings
{
  public static IQueryStringToken<int> Id = new ValueTypeToken<int>("id")
  {
    ExceptionNotificationBehaviour = ExceptionNotificationBehaviour.Silent
  };

  public static IQueryStringToken<bool> DoSort = new ValueTypeToken<bool>("sort")
  {
    ExceptionNotificationBehaviour = ExceptionNotificationBehaviour.Silent,
    ReadFailureAction = (args) => Logger.Log(args.ToString())
  };
}

protected void Page_Load(object sender, EventArgs e)
{
  string uri = "http://test.com/default.aspx?id=hello&sort=hello";

  // id = default(int) = 0 as hello cannot be parsed into an int and 
  // ExceptionNotificationBehaviour = ExceptionNotificationBehaviour.Silent
  int id = QueryStrings.Id.ReadValue();

  // doSort = default(bool) = false. Furthermore the details are logged
  bool doSort = QueryStrings.DoSort.ReadValue();
}

10 - Using checksums

internal static class QueryStrings
{
  //static QueryStrings()
  //{
  //    //choose which algorithm you'd like to use. Basic is shorter and less secure than Hash. Though is will be fine to make simple checksum control.
  //    QueryStringConfiguration.Instance.ChecksumCalculator = ChecksumCalculators.Hash;
  //    QueryStringConfiguration.Instance.ChecksumCalculator = ChecksumCalculators.Basis; //this is the default value.
  //}

  // this token is not aware that checksum is used
  public static IQueryStringToken<int> Id = new ValueTypeToken<int>("id");
}

protected void Page_Load(object sender, EventArgs e)
{
  IUriWriter writer = UriWriterFactory.CreateEmptyFromCurrentUri()
    .SetToken(QueryStrings.Id, 99);

  writer.ApplyCheckSumControl = true;

  // uri = http://localhost:3489/Samples/Sample1.aspx?id=99&cs=7984
  Uri uri = writer.GenerateQueryAsUri();
  
  //this line will fail if the id is anything but 99. Note that the reader explicitly states that the reading must be performed with checksum control.
  try
  {
    int id = QueryStrings.Id.ReadValue(uri, ReadValueMode.CheckSumControl);
  }
  catch (TokenParserException ex)
  {
    if (ex.FailureArgs.Reason == FailureReason.CheckSumError || ex.FailureArgs.Reason == FailureReason.CheckSumTokenDoesNotExist)
    {
      // do something
    }
  }

11 - Customizations

... comes soon...

12 - Nullable types

By using the extension method NullIfEmpty we can treat the value as nullable

internal static class QueryStrings
{
  // this token is not aware that checksum is used
  public static IQueryStringToken<int> Id = new ValueTypeToken<int>("id");
}

protected void Page_Load(object sender, EventArgs e)
{
  Uri initialUrl = new Uri("http://test.com/default.aspx");

  // id gets the value null
  int? id = QueryStrings.Id.NullIfEmpty(initialUrl);
}

Last edited Mar 17, 2012 at 7:38 AM by kasperbirkelund, version 13

Comments

No comments yet.