Showing posts with label Simple. Show all posts
Showing posts with label Simple. Show all posts

Thursday, October 21, 2010

Detect current network setting with C#

In cause of my latest project Simple Proxy Switch I had to face the challenge of detecting the setting of the current network the computer is connected to.

Now here’s my snippet how do I retrieve the current network setting:

// zero conf ip address
IPAddress zeroConf = new IPAddress(0);
// get current assigned addresses
IPAddress[] hostAddresses = Dns.GetHostAddresses(Dns.GetHostName());

var networkData = NetworkInterface.GetAllNetworkInterfaces()
  // filter running network interfaces
  .Where(network => network.OperationalStatus == OperationalStatus.Up)
  // filter unknown interfaces
  .Where(network => network.NetworkInterfaceType != NetworkInterfaceType.Unknown)
  // filter loopback interfaces
  .Where(network => network.NetworkInterfaceType != NetworkInterfaceType.Loopback)
  // get the properties
  .Select(network => network.GetIPProperties())
  // filter initialized gateways
  .Where(ipProps => ipProps.GatewayAddresses.All(gateway => gateway.Address != zeroConf))
  // filter and get ip addresses
  .SelectMany(ipProps => ipProps.UnicastAddresses.Where(ucAddress => hostAddresses.Contains(ucAddress.Address)))
  .Where(ucAddress => hostAddresses.Contains(ucAddress.Address))
  // simply use the first
  .FirstOrDefault();

Be the force with you!

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!

Monday, September 28, 2009

Just a prefix issue

Everybody who has to deal with XML and XPath in .NET just Run into an issue of accessing elements without having any prefix for the default namespace.

Assume a sample:
You've got an XML-File books.xml as follows:
<books xmlns="urn:books">
 <book>
  <author>It's just me</author>
  <publisheddate>2009-09-25T09:06</publisheddate>
 </book>
</books>

And now? How to access a node?

First attempt:
XmlDocument doc = new XmlDocument();
doc.Load("books.xml");
 
// just build xPath for testing
StringBuilder xPath = new StringBuilder();
XmlNode someNode = doc.DocumentElement.FirstChild.FirstChild;
 
do
{
   xPath.Insert(0, someNode.LocalName);
   xPath.Insert(0, "/");
   someNode = someNode.ParentNode;
}
while (someNode != null && someNode.NodeType != XmlNodeType.Document);
 
// xPath == "/books/book/author"
XmlNode author = doc.DocumentElement.SelectSingleNode(xPath.ToString());

What is the value of author? Right, it's null, hu.

Next attempt, try using XmlNamespaceManager.
XmlNamespaceManager manager = new XmlNamespaceManager(doc.NameTable);
// try to access with XmlNamespaceManager
XmlNode author = doc.DocumentElement.SelectSingleNode(xPath.ToString(), manager);

What is the value of author? Right, it's still null, hu.

And now?

Try to explain: The Namespace and the Prefix of the used namespace is not defined so xpath could not be resolved.

So try this:
XmlNamespaceManager manager = new XmlNamespaceManager(doc.NameTable);
// try to access with XmlNamespaceManager
XmlNode author = doc.DocumentElement.SelectSingleNode(xPath.ToString(), manager);

So try this:
string prefix = "mySample";
if (String.IsNullOrEmpty(manager.LookupPrefix(doc.DocumentElement.NamespaceURI)))
{
   // namespace not added
   manager.AddNamespace(prefix, doc.DocumentElement.NamespaceURI);
}
 
// injecting the namespace
xPath.Replace("/", String.Format("/{0}:", prefix));
 
// xPath is now  "/{mySample}:books/{mySample}:book/{mySample}:author"
author = doc.DocumentElement.SelectSingleNode(xPath.ToString(), manager);

And now, author sould be the selected node.

Thursday, September 10, 2009

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 ...