A New Internet Library: Add Your Website/Blog or Suggest A Website/Blog to our Free Web Directory http://anil.myfunda.net.

Its very simple, free and SEO Friendly.
Submit Now....

Monday, January 5, 2009

Tip #41: Did you know... establishing a remote connection to a IIS server with self-issued certificate will require a certificate validation delegate?

Either through WMSvc or through your own script, whenever you try to establish a connection with a remote server, which doesn’t provide a trusted certificate you need to provide a delegate for this certificate validation check to validate untrusted certificates.

The signature for this delegate is as follows

Namespace: System.Net.Security
Assembly:  System (in System.dll)

public delegate bool RemoteCertificateValidationCallback(      Object sender,      X509Certificate certificate,      X509Chain chain,      SslPolicyErrors sslPolicyErrors  )

Thus, to accept ALL server certificates, you will need to set the callback of ServicePointManager to validate a server certificate in the following manner:

ServicePointManager.ServerCertificateValidationCallback = RemoteCertificateValidationCallbackFlag;    bool RemoteCertificateValidationCallbackCheck(      Object sender,      X509Certificate certificate,      X509Chain chain,      SslPolicyErrors sslPolicyErrors  )  {      return true;  }

For the official MSDN documentation on this delegate refer to RemoteCertificateValidationCallback Delegate and ServicePointManager.ServerCertificateValidationCallback Property

Kateryna Rohonyan
SDET, IIS Team



Source Click Here.

Fun With Named Formats, String Parsing, and Edge Cases

Recently I found myself in a situation where I wanted to format a string using a named format string, rather than a positional one. Ignore for the moment the issue on whether this is a good idea or not, just trust me that I'll be responsible with it.

The existing String.Format method, for example, formats values according to position.

string s = string.Format("{0} first, {1} second", 3.14, DateTime.Now);

But what I wanted was to be able to use the name of properties/fields, rather than position like so:

var someObj = new {pi = 3.14, date = DateTime.Now};  string s = NamedFormat("{pi} first, {date} second", someObj);

Looking around the internet, I quickly found three implementations mentioned in this StackOverflow question.

All three implementations are fairly similar in that they all use regular expressions for the parsing. Hanselman's approach is to write an extension method of object (note that this won't work in VB.NET until they allow extending object). James and Oskar wrote extension methods of the string class. James takes it a bit further by using DataBinder.Eval on each token, which allows you to have formats such as {foo.bar.baz} where baz is a property of bar which is a property of foo. This is something else I wanted, which the others do not provide.

He also makes good use of the MatchEvaluator delegate argument to the Regex.Replace method, perhaps one of the most underused yet powerful features of the Regex class. This ends up making the code for his method very succinct.

Handling Brace Escaping

I hade a chat about this sort of string parsing with Eilon recently and he mentioned that many developers tend to ignore or get escaping wrong. So I thought I would see how these methods handle a simple test of escaping the braces.

String.Format with the following:

Console.WriteLine(String.Format("{{{0}}}", 123));

produces the output (sans quotes) of "{123}"

So I would expect with each of these methods, that:

Console.WriteLine(NamedFormat("{{{foo}}}", new {foo = 123}));

Would produce the exact same output, "{123}". However, only James's method passed this test. But when I expanded the test to the following format, "{{{{{foo}}}}}", all three failed. That should have produced "{{123}}".

Certainly this is not such a big deal as this really is an edge case, but you never know when an edge case might bite you as Zune owners learned recently. More importantly, it poses an interesting problem - how do you handle this correctly? I thought it would be fun to try.

This is possible to handle correctly using regular expressions, but it's challenging. Not only are you dealing with balanced matching, but the matching depends on whether the number of consecutive braces are odd or even.

For example, the following "{0}}" is not valid because the right end brace is escaped. However, "{0}}}" is valid. The expression is closed with the leftmost end brace, which is followed by an even number of consecutive braces, which means they are all escaped sequences.

Performance

As I mentioned earlier, only James's method handles evaluation of sub-properties/fields via the use of the DataBinder.Eval method. Critics of his blog post point out that this is a performance killer.

Personally, until I've measured it in the scenarios in which I plan to use it, I doubt that the performance will really be an issue compared to everything else going on. But I thought I would check it out anyways, writing a simple console app which runs each method over 1000 iterations, and then divides by 1000 to get the number of milliseconds each method takes. Here's the result:

format perf

Notice that James's method is 43 times slower than Hanselman's. Even so, it only takes 4.4 milliseconds. So if you don't use it in a tight loop with a lot of iterations, it's not horrible, but it could be better.

My Implementation

At this point, I thought it would be fun to write my own implementation using manual string parsing rather than regular expressions. I'm not sure my regex-fu is capable of handling the challenges I mentioned before. After implementing my own version, I ran the performance test and saw the following result.

haackformat perf

Nice! by removing the overhead of using a regular expression in this particular case, my implementation is faster than the other implementations, despite my use of DataBinder.Eval. Hopefully my implementation is correct, because fast and wrong is even worse than slow and right.

One drawback to not using regular expressions is that the code for my implementation is a bit long. I include the entire source here. I've also zipped up the code for this solution which includes unit tests as well as the implementations of the other methods I tested, so you can see which tests they pass and which they don't pass.

The core of the code is in two parts. One is a private method which parses and splits the string into an enumeration of segments represented by the ITextExpression interface. The method you call joins these segments together, evaluating any expressions against a supplied object, and returning the resulting string.

I think we could optimize the code even more by joining these operations into a single method, but I really liked the separation between the parsing and joining logic as it helped me wrap my head around it. Initially, I hoped that I could cache the parsed representation of the format string since strings are immutable thus I could re-use it. But it didn't end up giving me any real performance gain when I measured it.

public static class HaackFormatter  {    public static string HaackFormat(this string format, object source)    {        if (format == null) {          throw new ArgumentNullException("format");      }        var formattedStrings = (from expression in SplitFormat(format)                   select expression.Eval(source)).ToArray();      return String.Join("", formattedStrings);    }      private static IEnumerable<ITextExpression> SplitFormat(string format)    {      int exprEndIndex = -1;      int expStartIndex;        do      {        expStartIndex = format.IndexOfExpressionStart(exprEndIndex + 1);        if (expStartIndex < 0)        {          //everything after last end brace index.          if (exprEndIndex + 1 < format.Length)          {            yield return new LiteralFormat(                format.Substring(exprEndIndex + 1));          }          break;        }          if (expStartIndex - exprEndIndex - 1 > 0)        {          //everything up to next start brace index          yield return new LiteralFormat(format.Substring(exprEndIndex + 1            , expStartIndex - exprEndIndex - 1));        }          int endBraceIndex = format.IndexOfExpressionEnd(expStartIndex + 1);        if (endBraceIndex < 0)        {          //rest of string, no end brace (could be invalid expression)          yield return new FormatExpression(format.Substring(expStartIndex));        }        else        {          exprEndIndex = endBraceIndex;          //everything from start to end brace.          yield return new FormatExpression(format.Substring(expStartIndex            , endBraceIndex - expStartIndex + 1));          }      } while (expStartIndex > -1);    }      static int IndexOfExpressionStart(this string format, int startIndex) {      int index = format.IndexOf('{', startIndex);      if (index == -1) {        return index;      }        //peek ahead.      if (index + 1 < format.Length) {        char nextChar = format[index + 1];        if (nextChar == '{') {          return IndexOfExpressionStart(format, index + 2);        }      }        return index;    }      static int IndexOfExpressionEnd(this string format, int startIndex)    {      int endBraceIndex = format.IndexOf('}', startIndex);      if (endBraceIndex == -1) {        return endBraceIndex;      }      //start peeking ahead until there are no more braces...      // }}}}      int braceCount = 0;      for (int i = endBraceIndex + 1; i < format.Length; i++) {        if (format[i] == '}') {          braceCount++;        }        else {          break;        }      }      if (braceCount % 2 == 1) {        return IndexOfExpressionEnd(format, endBraceIndex + braceCount + 1);      }        return endBraceIndex;    }  }

And the code for the supporting classes

public class FormatExpression : ITextExpression  {    bool _invalidExpression = false;      public FormatExpression(string expression) {      if (!expression.StartsWith("{") || !expression.EndsWith("}")) {        _invalidExpression = true;        Expression = expression;        return;      }        string expressionWithoutBraces = expression.Substring(1          , expression.Length - 2);      int colonIndex = expressionWithoutBraces.IndexOf(':');      if (colonIndex < 0) {        Expression = expressionWithoutBraces;      }      else {        Expression = expressionWithoutBraces.Substring(0, colonIndex);        Format = expressionWithoutBraces.Substring(colonIndex + 1);      }    }      public string Expression {       get;       private set;     }      public string Format    {      get;      private set;    }      public string Eval(object o) {      if (_invalidExpression) {        throw new FormatException("Invalid expression");      }      try      {        if (String.IsNullOrEmpty(Format))        {          return (DataBinder.Eval(o, Expression) ?? string.Empty).ToString();        }        return (DataBinder.Eval(o, Expression, "{0:" + Format + "}") ??           string.Empty).ToString();      }      catch (HttpException) {        throw new FormatException();      }    }  }    public class LiteralFormat : ITextExpression  {    public LiteralFormat(string literalText) {      LiteralText = literalText;    }      public string LiteralText {       get;       private set;     }      public string Eval(object o) {      string literalText = LiteralText          .Replace("{{", "{")          .Replace("}}", "}");      return literalText;    }  }

I mainly did this for fun, though I plan to use this method in Subtext for email fomatting.

Let me know if you find any situations or edge cases in which my version fails. I'll probably be adding more test cases as I integrate this into Subtext. As far as I can tell, it handles normal formatting and brace escaping correctly.



Source Click Here.

Friday, January 2, 2009

Year End Reading for 2008

A small set of links reviewing 2008, and looking forward to 2009, from tech to news to photos, annotated with some personal comments...

Source Click Here.

Reading: Designing for the Social Web

A little bit about Designing for the Social Web - an interesting, insightful and fun read on what to keep in mind when designing social experiences on the web.

Source Click Here.

Predictions for 2009

Every year I ask everyone I know to try to make some predictions for the following year.  Truthfully, I've never gone back and compared my predictions with reality (that would spoil the fun I think).  Well, here are my predictions for 2009.

  1. Deep / Long Recession:  2009 will be a year of change in the IT industry, sparked, of course, by the recession that started in 2008.  With every recession we face there will be challenges, but there will also be opportunities.  I predict that there will be a "weeding" out of IT organizations, those who will survive will be the ones who have adapted their practices even before the recession took hold. 
  2. Spark of Innovation:  Recessions always get us to think about doing more with less - and I think that this will further spark new ideas on how we can add value to business and industry as a whole. 
  3. Head in the Cloud:  Doing more with less, being nimble, cutting operational costs, reducing risks - these are all great reasons why I think cloud services will become much more mainstream.
  4. Too Many Damn Social Network and Social Network Aggregators:  2008 truly birthed social networking (I remember, this was something I did predict).  Social networking has proliferated throughout our societies entire online life - from our computers, to our mobile devices, and of course into the world of online gaming.  Facebook has proven to be a catalyst for them all - Twitter has truly taken hold - and there are dozens of others such as Ping.fm that can be used to help broadcast our lives out into the ether like never before.  These types of communities will reach a turning point this year.
  5. SharePoint 2010 will be announced:  (I'm speculating here folks) SharePoint will go through another revolutionary change - just as it has done with every release.  SharePoint will bring not only advances in document management but it will begin to truly leverage Silverlight from a user experience perspective.  I predict that Microsoft will also announce much of what we see in the new online Live services down into the SharePoint space - allowing organizations to have Micro-social networks much easier than we can today with the product.  I also believe that SharePoint will be "meshafied" - meaning, we should be able to experience SharePoint leveraging offline/synchronization functionality that mesh and the synchronization framework have. 
  6. Microsoft Groove will morph:. into the "meshafied" version of SharePoint.  We will have offline content of virtually all aspects of SharePoint - from the social network experience to document and list management. 
  7. Azurameshafication: Microsoft Azure offers cloud solutions, and many organizations will start to provide services using these core services.  That's a given, however, I also predict that Microsoft Mesh will play a much larger role and savvy organizations will think long and hard about coupling a fantastic online experience with a P2P/Offline experience.
  8. 100 Gb of Online Storage for the World:  Today SkyDrive gives us 25gigs of free online space.  I predict that throughout the year, as the demand for cloud services increases, Google, Microsoft, and Amazon will jump frog each other providing more and more free online storage until each of us can get up to 100 GB of storage for free.
  9. Explosion of User Experience:  Silverlight 2.0 now makes it more realistic to build business applications outside of the traditional ASP.NET/WPF/Winform boundaries.  Today a lot of the Silverlight controls for business applications look very similar to Winform control - and I think in 2009 those organizations who will truly push these boundaries of user experience controls will truly make the biggest influence on how the world works.  I predict 1 or 2 vendors who will offer amazingly innovative and useful Silverlight controls that will allow us to express business value in ways we haven't seen today.
  10. Windows 7 Hype:  I believe that Windows 7 will have a great deal more hype.  Software vendors will be biting at the bit trying to think of ways of providing multi-touch user experiences to their apps (see prediction #9).  Microsoft will announce limited multi-touch functionality to Vista SP3 scheduled  to be released the late part of 2009 or early 2010.
  11. Microsoft to announce Office 2010 Live will be pay per use:  I predict that Microsoft announce that they will give away base functionality for Office Live 14, and also provide greater functionality/scale/features/no-adverts to those willing to pay incrementally on either a pay per use model or a monthly subscription model.

Let me know what you think by posting your own predictions and linking to mine! 

Happy New Year everyone! 



Source Click Here.

Tip #40: Did you know.How to scope master pages?

Master page is a  template page that can be used to create a consistent layout for your application. First you create a master page to define the look & feel of the application and then you create the content pages that contains the content.

You can attach these content pages to the master page at the following three levels:

  1. Page Level: You can use the page directive on each of the content pages

    <@Page Language="VB" MasterPageFile="~/Main.master"%>

    Or programmatically set it in the content page Page_PreInit Event

    for VB
    Protected Sub Page_PreInit(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreInit
            Me.MasterPageFile = "~/Main.master"
    End Sub

    for C#
    protected void Page_PreInit(Object sender, EventArgs e)
            {
                this.MasterPageFile = "~/Main.Master";
            }

  2. Application Level : By specifying the following in web.config file, all the aspx files will use the master page as Main.master (If  aspx file does not contain a Content control, the master page won't be applied to it )

    <configuration>
        <system.web>
                   <pages masterPageFile="~/Main.master" />
       </system.web>
    </configuration>

    [You will notice that the pages node already exists in web.config, add the masterPageFile attribute to this node]

  3. Folder Level: By specifying the following in web.config all the aspx files in a specified folder (admin) will use the master page as Admin.master (If  aspx file does not contain a Content control, the master page won't be applied to it )

    <configuration>
        <location path="admin">
        <system.web>
                   <pages masterPageFile="~/Admin.master" />
       </system.web>
       </location>
    </configuration>

    [you will notice system.web already exists, leave it as it is & add a new node 'location' with the above content under 'configuration']

By setting master page programmatically or thru web.config you may not get the Visual Studio master page design time features.

 

Deepak Verma
SDET | Visual Web Developer



Source Click Here.

Not Your Typical Top Ten Of 2008 Post

At the end of the year, it's very common for bloggers to take a look back at their own blog and list their favorite 10 blog posts. I find that somewhat narcissistic, so you know I'm going to do that.

But before I do, I thought it would be great to list the top 10 blog posts by others I read in 2008. The only problem is, I have very bad short-term memory and I can't seem to remember which ones I read that had a real impact on my thinking. I'll have to try and keep better track in 2009.

So based on a cursory Google search and look through my Google Reader app, here are some of my favorite blog posts of 2008 by you all, I couldn't even list 10. Please do comment with your own favorite blog posts, mine or otherwise of 2008.

Favorite Posts I Read

My Top Posts (Using the Ayende Formula)

A while back, Ayende wrote up a weighted query for Subtext to determine the top posts. I updated it to only include mine published in 2008. Here are the top 5.

Milestones Moments

There are some posts that I personally liked because they represent important events that happened to me in 2008.

Ok, so maybe this post is pretty typical and doesn't live up to the title I gave it. Oh well, I tried.

I'm sure I'm forgetting a whole lot of other important events that happened in 2008. I'm probably neglecting great blog posts that I read. But that's the great thing about a blog, I'm confident people will point out my shortcomings in the comments to this post, and for that, I'm grateful. You all rock!

And with that, I leave you with this moment of zen, a photo taken near my house.

giant snowman



Source Click Here.

Originals Enjoy