Sorting custom data objects the easy way

by martin 28. September 2009 22:32

I recently had to implement custom sorting on couple of ASP.net pages that had to bind to a collection of custom data objects.  Not wanting to re-invent the wheel on every page, I looked for an easier solution online.  I ran across at least two worth mentioning: Generic Sorting Using Reflection in .NET By Jon Wojtowicz (http://www.eggheadcafe.com/articles/pfc/propertycomparer.asp) and Rocky Lhotka's MSDN article where he presents his Generics based PropertyComparer.  I liked Jon's solution in that it was written using recursion so that you could easily sort by properties of properties.  However Jon's implementation was not "Generics" based.  Rocky's implementation was generics based, but it lacked the recursion that my solution needed.  In the end, I ended up modifying Jon's code to be generics based.  I sent Jon an email asking for permission to share his modified code online, but unfortunately he never responded to my email.

Below is a link to my patch file to Jon's PropertyComparer.cs file.  You can download the original directly from Jon's project hosted on EggHeadCafe in the link above.

PropertyComparer.patch (2.99 kb)

Here is an example of how you would use this to support sorting in a Telerik RadGrid:

        protected void RadGrid1_SortCommand(object source, GridSortCommandEventArgs e)
        {
            List<Employee> employees = (List<Employee>)RadGrid1.DataSource;
            CompareOrder cmpOrder;
            GridSortExpression expression = new GridSortExpression(); 

            if (e.NewSortOrder.Equals(GridSortOrder.Ascending))
            {
                cmpOrder = CompareOrder.Ascending;
                expression.SortOrder = GridSortOrder.Ascending;
            }
            else
            {
                cmpOrder = CompareOrder.Descending;
                expression.SortOrder = GridSortOrder.Descending;
            }

            employees.Sort(new PropertyComparer<Employee>(e.SortExpression, cmpOrder));

            expression.FieldName = e.SortExpression;

            e.Item.OwnerTableView.SortExpressions.Clear();
            e.Item.OwnerTableView.SortExpressions.AddSortExpression(expression);
            e.Item.OwnerTableView.Rebind();
            e.Canceled = true;
        } 
 

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: , , , ,

ASP.Net | C#

RegEx helper method to make extracting patterns from strings a cinch

by martin 12. July 2009 15:10

Quite often I find myself trying to create a custom string from the “pattern” found in an input string.  Through trial and error, I have found a real simple and powerful way to do this, and here it is!  It works simply by using the grouping operator “()” for regular expressions and utilizing the power of String.Format.  This implementation is written as a .Net 3.5 extension method for the String class.  I overloaded it to be more flexible; you can pass in RegexOptions, a String representation of a regular expression, or a precompiled Regex object for optimal efficiency.  One important note is that Regex works such that the entire expression is always the first group match (grouping 0) and that all groupings that you explicitly state start at grouping number 1 and enumerate up from there.

StringRegexHelper.cs (1.54 kb)

    1 using System;

    2 using System.Text.RegularExpressions;

    3 

    4 namespace CustomExtensions

    5 {

    6     public static class StringRegexHelper

    7     {

    8         public static String FindAndFormat(this String StringToSearch,

    9             Regex RegularExpressionToSearchFor, String FormattingExpression)

   10         {

   11             String strResult = null;

   12             Match match = RegularExpressionToSearchFor.Match(StringToSearch);

   13             if (match.Success)

   14             {

   15                 String[] arrCaptures = new String[match.Groups.Count];

   16                 for (int i = 0; i < match.Groups.Count; i++)

   17                 {

   18                     arrCaptures[i] = match.Groups[i].Captures[0].Value;

   19                 }

   20                 strResult = String.Format(FormattingExpression, arrCaptures);

   21             }

   22             return strResult;

   23         }

   24 

   25         public static String FindAndFormat(this String StringToSearch,

   26             String RegularExpressionToSearchFor, String FormattingExpression)

   27         {

   28             return FindAndFormat(StringToSearch,

   29                 new Regex(RegularExpressionToSearchFor),

   30                 FormattingExpression);

   31         }

   32 

   33         public static String FindAndFormat(this String StringToSearch,

   34             String RegularExpressionToSearchFor, String FormattingExpression,

   35             RegexOptions RegularExpressionOptions)

   36         {

   37             return FindAndFormat(StringToSearch,

   38                 new Regex(RegularExpressionToSearchFor,

   39                     RegularExpressionOptions),

   40                 FormattingExpression);

   41         }

   42     }

   43 }

Here are 3 examples of how this can be used:

    1 strResult = "myusername-file1.txt".FindAndFormat(@"(\w+)-.",

    2     "{1}@ad.domain.com");

    3 // Returns "myusername@ad.domain.com"

    4 

    5 strResult = "BatchFile072009.txt".FindAndFormat(@"BatchFile(\d\d)(\d\d\d\d)\.txt",

    6     "Batch file for year {2} and month {1} retrieved from {0}");

    7 // Returns "Batch file for year 2009 and month 07 retrieved from BatchFile072009.txt"

    8 

    9 String strInput = "John_Doe;123-45-6789;04/12/2005";

   10 strResult = strInput.FindAndFormat(@"(\w+)_(\w+);(\d{3})-(\d{2})-(\d{4});(\d+)/(\d+)/(\d+)",

   11     "Last name = {2}  First name = {1}  SSN = {3}{4}{5}  DOB = {6}-{7}-{8}");

   12 // Returns "Last name = Doe  First name = John  SSN = 123456789  DOB = 04-12-2005"

Currently rated 5.0 by 1 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: ,

C#

Anonymous HTTP PUT with IIS 7

by martin 22. June 2009 21:32
From googling around in trying to get HTTP put enabled on IIS 7, I have concluded that turning on HTTP PUT verb support requires the installation of the WebDAV handler extension and that even then it only works in integrated authentication mode.  If this is not true, please let me know as I was forced to write my own put HTTP handler.  It actually turned out to be a lot easier than I thought it was going to be though.  Implementing IHttpHandler, I ended up just having to binaryread the request into a byte array and then use a binarywriter to write it to a file after validating the PhysicalPath of the request for user permissions and validating that the "pattern" is safe (ex. file extension, path).  I haven't tested the performance against the IIS 6 native solution, but it seems quite fast on today's server hardware.

Currently rated 5.0 by 1 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: , ,

ASP.Net | C# | Windows

Simple Web Application Stress Test Utility

by martin 19. June 2009 21:25

I was recently involved in migrating a web application from IIS 5 to IIS 7 on Server 2008.  One of the quintessential components to this app was originally written as a VC++ ISAPI server extension.  I've read many articles touting the efficiency of the integrated .Net pipeline in IIS 7, so I thought I would rewrite this legacy component in C# as an Http handler instead.  Once the code was written, I was looking for a way to test the speed of the old implementation versus the new.  To my surprise, there were very few free tools available to do this type of testing easily and quickly.  Microsoft offers two tools, Web Application Stress Tool and Web Capacity Analysis Tool.  Both were a complete disappointment for me.  WAST seems like it hasn't been updated or recompiled for years, and I couldn't even get it to install without errors on Windows 2008 x64.  WCAT installed, but it offers no GUI and seemed buggy.  So being the geek that I am, I wrote my own.

The tool that I wrote lets you enter multiple URLs to test and allows you to control the number of concurrent requests (threads) that attempt to retrieve the URLs.  You can also specify if you would like the URLs to be requested in a round-robin fashion or randomly.  Statistics are then displayed for all the requests, and per each URL.  Stats given include: the average number of bytes in response, the average round trip request-response time in milliseconds, requests per second, the total number of requests, and the total elapsed time.

This application was written in C# and it requires .Net 2.0+ or Mono 2.0+ to run.  It is available free of charge via the download link below, but if you find it useful, please feel free to donate a few bucks via the paypal link at the top right of this page.

 Download: SimpleMultiThreadedWebStressTester.exe (18.50 kb)



Currently rated 3.0 by 5 people

  • Currently 3/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: , ,

C# | Linux | Mono | Windows

Service Oriented Programming and DSLs?

by martin 19. November 2008 22:20

I recently attended Dev Connections and was shown the benefits of decoupling business logic from aspects such as authentication, authorization, security, transaction support, threading model, instantiation model, encoding, and transport mechanism.  In Juval Lowy's Windows Communication Framework (WCF) seminar, I was exposed to the idea of our software tools and runtime environments evolving to allow us to utilize these functionalities in business application without even doing anything additional.  Juval reiterated that WCF is not just about web service and explained many of the benefits that you would get for using WCF even on an application that does not span CPUs.  These benefits include fault tolerance, fault screening (or formal fault contracts), contract first development, and the benefit of a thought out framework that provides separation of concerns for many aspects of enterprise software development.

At PDC at the end of October, Microsoft announced Azure, Oslo, and Dublin.  So Azure, or the "cloud", will let you deploy and run your production applications easily and supposedly allow them to dynamically scale up on-the-fly as demand warrants.  I heard this maybe being accomplished by dynamically spawning new virtualized servers from software and data that are stored in a massive partitioned and redundant sql server cluster (or I may have dreamt all this).  Oslo is the hybrid (both visual (Quadrant) and textual) programming environment for creating and using custom Domain Specific Languages (DSL) and Dublin is a SQL server based repository and runtime environment for the resulting Oslo DSL programs and data structures.  The DSLs are written in Mgrammer ("Mg") and the modeling language itself is just called "M".  There is a silverlight video from MS on http://modelsremixed.com/ that shows the history of "modeling", starting with prehistoric times.  In it, you will notice that one of the process models that they show is comprised of a component with the tiny logo that reads "Wcf" in its top left corner.

So that is a lot of new information to absorb.... but what does this all mean?  Will we all really be orchestrating business process workflows written in "vertical" DSLs?  Where does BPEL fit in?  Is this Microsoft's killer-app ESB?

http://msdn.microsoft.com/en-us/oslo/default.aspx

 

 

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: , , ,

ASP.Net | C# | Windows

SOAP interoperability problem with .Net consuming Axis ???

by martin 7. November 2008 23:21

It seems that the auto generated proxy classes for SOAP (Webreferences) seem to require the root element of the response SOAP body to be fully qualified by namespace by default.  One trick to overcome this that worked for me was to use wsdl.exe to create editable classes rather than using webreference.  Then I was able to remove the ResponseNameSpace attribute from the System.Web.Services.Protocols.SoapDocumentMethodAttribute attribute annotation.  This seem to allow the temporary infrastructure xml deserializer class to work correctly by making the call to XmlReader.IsStartElement return true for Axis generated SOAP responses that do not specify a namespace at all.

wsdl.exe /language:CS /out:CustomWebServiceProxy.cs  AxisServiceWsdl.wsdl 
( /namespace:MyAppNameSpace ) 

You can also remove the System.Diagnostics.DebuggerStepThroughAttribute attribute annotations so that you can step into (F-11 key) the runtime generated proxy code to see and debug the serializer and deserializer in action.  This comes in very useful when you are receiving a valid soap response over the network but your return object is null upon returning back from the webservice call.  I had to do this when all I was getting was null and had no error messages to grasp at.

 

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: , ,

C# | Java

Welcome

Please contact me if you have a great idea for a project and need technical expertise in designing, developing, or integrating a custom software solution. 

Recent Comments

Comment RSS