Showing posts with label Snippet. Show all posts
Showing posts with label Snippet. Show all posts

Wednesday, November 24, 2010

Store data from async web service call with Silverlight

Did you ever tried to store data on Silverlight from an async web service call using SaveFileDialog - and get told it doesn’t work?
But that is only half the truth. Here it how it works!

Thursday, June 24, 2010

Remote Certificate validation

Sooner or later every developer has to deal on retrieving information from some resource accessible through HTTP protocol.

While it is easy to get this information from unsecured HTTP resources it's often the case that such a resource is only available for secured access through HTTP.

In that case and to ensure that this connection is trusted you have to check the server certificate for that connection.
Some sample piece of code to access and download data over http can look like this one:
string data = String.Empty;
using (WebClient webClient = new WebClient())
{
   byte[] rawData = webClient.DownloadData(new Uri(/* path to resource */));

   using (MemoryStream memStream = new MemoryStream(rawData))
   {
      using (StreamReader reader = new StreamReader(memStream, true))
      {
         data = reader.ReadToEnd();
      }
   }
}

This code works well for connections through HTTP.

Now you have to access the same resource over HTTPS and this is where you have to face a new challenge:

Validation of Certificates.

In the case of .NET there is the ServicePointManager that let you intercept the mechanism of validation.
It defines the ServerCertificateValidationCallback method which is called on secure resource access.

The adjusted code is now something like this:
string data = String.Empty;
using (WebClient webClient = new WebClient())
{
   RemoteCertificateValidationCallback validationCallback =
      (sender, cert, chain, errors) =>
      {
         return true;
      };

   ServicePointManager.ServerCertificateValidationCallback += validationCallback;

   try
   {
      byte[] rawData = webClient.DownloadData(new Uri(/* path to resource */));

      using (MemoryStream memStream = new MemoryStream(rawData))
      {
         using (StreamReader reader = new StreamReader(memStream, true))
         {
            data = reader.ReadToEnd();
         }
      }
   }
   finally
   {
      ServicePointManager.ServerCertificateValidationCallback -= validationCallback;
   }
}

This code simply declares all certificates as valid which is some kind of stupid.

Let's focus on the validation of the certificate. Feel free to implement you own code of validation or just simply use .NET integrated features.

Something I did at bugtraqplugin is to use the default validation chain which depends on certificates stored at the Windows certification storage.

My simple approach:
RemoteCertificateValidationCallback validationCallback =
   (sender, cert, chain, errors) =>
   {
      return (certificate as X509Certificate2 ?? new X509Certificate2(certificate)).Verify();
   };

All code put together can be available at source code of bugtraqplugin.

Monday, February 15, 2010

Customizing Visual Studio code templates to fit your needs

Did you ever get rid of that the default template on project context menu > add > class misses you prefered regions, default method overrides, properties or constructors?

Here is a guide how do you extend this template.

Wednesday, December 9, 2009

Printing numeric values as HEX

I sometimes need to print integer numeric values as a hexadecimal string for better reading and everytime I have to search about it with google.

So here is a collection of printing values as hexadecimal string.

The simpliest way is to use the IFormattable interface:
   1:  String.Format("{0:X02}", int.MaxValue);

Other ways with support of differend radix is to user Convert.ToString().
Radix could be 2, 8, 10, or 16.
   1:  Convert.ToString(int.MaxValue, 2);

From:
MSDN: Convert.ToString()
mikrocontroller.net


Are there any other ways? So let me know!

Monday, December 7, 2009

Advanced Stringreplace

While handling string data it's often needed to replace or cut a partial string. String.Replace is such a simple method to replace values in C#.

But what about if you have to deal with patterns to replace or manipulate partial string?

Here you have to go beyond String.Replace and deal with regular expressions.
If you have't heared about Regular Expressions, I suggest to read this articles about it:
and some tools to check you patterns against data:

And now, time for some excamples.

Assume you have a string like
   1:  string data = "52/00000012340056";
and have to replace the zeros after the slash.

Your regex could be the following
   1:  Regex regex = new Regex(@"0+");

but take care about the zeros within the numbers. So you have to extend you regex like this:
   1:  Regex regex = new Regex(@"^\d+/0+");

If you run this expression over the sample data, the result looks like this:
   1:  string result = regex.Replace(data, String.Empty);
   2:  // result == "12340056";

Missing the prefix?

Extend the expressions with some named groups and use the matching values:
   1:  Regex regex = new Regex(@"^(?<prefix>\d+/)(0+)");
   2:  string result = regex.Replace(data, "${prefix}"); 
   3:  // result == "52/12340056";


That's it!

Thursday, September 10, 2009

Keep clean with temporary files

Every developer runs into a situation where temporary files are needed. In cause of an error, many developers forget to clean up this garbage within the temporary files directory. And I HATE that.

So therefore here is an hint for C# developers:
Just use the
FileOptions.DeleteOnClose
value as parameter of the
FileStream
constructor, this will keep you handles clean.

Heres comes an excample:
using (FileStream fStream = new FileStream(Path.GetTempFileName(), FileMode.Create, FileAccess.Write, FileShare.None, 4096, FileOptions.DeleteOnClose)))
{
// do work
}

Good luck.

Exchange variables for experts - or these who want to be

To show how cool you could code, you can use the following snippet to impress your girlfriend 8)

estimating x and y are integers
x = x ^ y;
y = y ^ x;
x = x ^ y;

shorter
x ^= y;
y ^= x;
x ^= y;

and a one liner if you like sunglasses
x ^=  y; y ^=  x; x ^=  y;

Cool as ice ...