DennyDotNet

Awesome ASP.NET C# and other cool coding stuff

About the author

Denny Ferrassoli
Developer at Casting Networks. MCP / .NET
E-mail me Send mail
Add to Technorati Favorites

Recent posts

Recent comments

Authors

Categories

None


Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2010

Execute a Delegate with a Timeout

Was browsing through Gustavo Duarte's "Lock Down SQL Server 2005" blog and came across a link for "Generic C# code for executing a delegate with a timeout."

It's a very useful snippet of code and reuseable.

Here's the method signature: 


ExecuteWithTimeout<T>(this Func<T> delegateToRun, TimeSpan timeout)

If the execution takes longer than timeout a TimeoutException will occur.

Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Posted by Denny on Wednesday, February 13, 2008 8:44 AM
Permalink | Comments (0) | Post RSSRSS comment feed

Generating a Case Statement in LINQ to SQL

LINQ is so much fun and makes things so much easier to accomplish. It's also gaining quite a bit of acceptance and it's evolving too with things like: LINQ to JavaScript and LINQ to JSON. I've been playing with LINQ quite a bit and recently I needed to generate a CASE statement with LINQ to SQL. It was fairly easy to accomplish since LINQ is so darn cool! Here is what I came up with:


var gimmeh_gimmeh =
 from t in db.sc_Timeslots
 where (t.starttime.Minute % 5 == 0) || (t.starttime.Minute % 10 == 0)
 select new
 {
  t.id,
  t.starttime,
  interval = (t.starttime.Minute % 5 == 0) ? "5 Minutes" : "10 Minutes"
 };

The line: "interval = ..." generates a CASE statement as shown below.


SELECT [t0].[id], [t0].[starttime],
    (CASE
        WHEN (DATEPART(Minute, [t0].[starttime]) % @p4) = @p5 THEN CONVERT(NVarChar(10),@p6)
        ELSE @p7
     END) AS [interval]
FROM [dbo].[sc_Timeslot] AS [t0]
WHERE ((DATEPART(Minute, [t0].[starttime]) % @p0) = @p1) OR ((DATEPART(Minute, [t0].[starttime]) % @p2) = @p3)

You can have multiple CASE statements or even concat them like so:


  interval = ((t.starttime.Minute % 5 == 0) ? "5 Minutes" : "10 Minutes") + ((t.id == 1) ? " (Master ID)" : "")

Which will generate the Case statement below (hey I'm starting to rhyme):


    (CASE
        WHEN (DATEPART(Minute, [t0].[starttime]) % @p4) = @p5 THEN CONVERT(NVarChar(22),@p6)
        ELSE @p7 + (
            (CASE
                WHEN [t0].[id] = @p8 THEN @p9
                ELSE CONVERT(NVarChar(12),@p10)
             END))
     END) AS [interval]

You can also nest the CASE statements... but I think by now you're clever enough to figure that out on your own.

Enjoy!

kick it on DotNetKicks.com
Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Tags: ,
Posted by Denny on Friday, February 08, 2008 5:04 AM
Permalink | Comments (4) | Post RSSRSS comment feed

LINQ to SQL: LoadFromPost

Holy rectal regions... This has been a crazy two weeks. Yes my site was down and yes it's finally back up now (have you noticed yet?). I have been quite busy lately - I moved my blog, as well as a few other sites, onto a Virtual Private Server (on AppliedI.net - they really kick ass) you can get free setup by using the coupon code: ZILCH.

Anyways... I'm happy to announce I won the LinqDev.com contest with my LINQ to XML RSS reader code (I'll post that later). I received a copy of HALO 3 Legendary Edition as well as 3 Apress books (really cool!). Big thanks to Joseph C. Rattz Jr. the author of "Pro LINQ: Language Integrated Query in C# 2008" (Amazon). If you're interested in LINQ get this book, seriously.

So anyways, I've been playing with LINQ and loving it! I was playing with a sample form I generated a while back and got caught up writing a LoadFromPost<t> function. For any of you who have ever used SubSonic you're probably aware of the LoadFromPost method. I decided to try and port it to LINQ to SQL (kinda) as well as play with Reflection since I have never really dipped into it before. Is it a good peice of code? I don't know... performance...? I don't know... I built it just to see what I could do with LINQ and Reflection... Nifty at best ;) If you have any comments, suggestions, fixes, tweaks, ideas, etc... feel free to post a comment.

LoadFromPost basically looks at your Request.Form collection and tries to match up any field names with the corresponding name in the <t> object. Only puplic properties are searched and of course you cannot set an EntitySet type so those are also avoided.

I did have to borrow some code from Peter Johnson (link in the code) to get this working properly. The problem is that Convert.ChangeType does not work with nullable types. Peter's code allows converting of nullable types, this makes it worth it even if you don't like the LoadFromPost method.


 public t LoadFromPost<t>( bool catchException )
 {
  NameValueCollection formPost = HttpContext.Current.Request.Form;

  // Create new instance of t type
  t obj = Activator.CreateInstance<t>();

  // Filter: do not include any EntitySet properties
  IEnumerable<PropertyInfo> pic = obj.GetType().GetProperties().Where( p => !p.PropertyType.Name.Contains( "EntitySet" ) );

  // Iterate through valid properties
  foreach( PropertyInfo pi in pic ) {
   string propname = pi.Name.ToLower();
   bool matchFound = false;

   // Iterate through form values
   foreach( string s in formPost.AllKeys ) {
    if( matchFound ) break;

    string formname = s.ToLower();

    if( formname.EndsWith( "_" + propname ) || formname.EndsWith( "$" + propname ) || formname.Equals( propname ) ) {
     // Match - set value
     string fval = (formPost[s].Length == 0) ? null : formPost[s];
     matchFound = true;

     try {
      pi.SetValue( obj, ChangeType( fval, pi.PropertyType ), null );
     } catch( Exception ex ) {
      if( catchException ) throw ex;
     }
    }
   }
  }

  return obj;
 }

 /// <summary>
 /// Returns an Object with the specified Type and whose value is equivalent to the specified object.
 /// </summary>
 /// <param name="value">An Object that implements the IConvertible interface.</param>
 /// <param name="conversionType">The Type to which value is to be converted.</param>
 /// <returns>An object whose Type is conversionType (or conversionType's underlying type if conversionType
 /// is Nullable&lt;&gt;) and whose value is equivalent to value. -or- a null reference, if value is a null
 /// reference and conversionType is not a value type.</returns>
 /// <remarks>
 /// This method exists as a workaround to System.Convert.ChangeType(Object, Type) which does not handle
 /// nullables as of version 2.0 (2.0.50727.42) of the .NET Framework. The idea is that this method will
 /// be deleted once Convert.ChangeType is updated in a future version of the .NET Framework to handle
 /// nullable types, so we want this to behave as closely to Convert.ChangeType as possible.
 /// This method was written by Peter Johnson at:
 /// http://aspalliance.com/author.aspx?uId=1026.
 /// </remarks>
 public static object ChangeType( object value, Type conversionType )
 {
  // Note: This if block was taken from Convert.ChangeType as is, and is needed here since we're
  // checking properties on conversionType below.
  if( conversionType == null ) {
   throw new ArgumentNullException( "conversionType" );
  } // end if

  // If it's not a nullable type, just pass through the parameters to Convert.ChangeType

  if( conversionType.IsGenericType &&
    conversionType.GetGenericTypeDefinition().Equals( typeof( Nullable<> ) ) ) {
   // It's a nullable type, so instead of calling Convert.ChangeType directly which would throw a
   // InvalidCastException (per http://weblogs.asp.net/pjohnson/archive/2006/02/07/437631.aspx),
   // determine what the underlying type is
   // If it's null, it won't convert to the underlying type, but that's fine since nulls don't really
   // have a type--so just return null
   // Note: We only do this check if we're converting to a nullable type, since doing it outside
   // would diverge from Convert.ChangeType's behavior, which throws an InvalidCastException if
   // value is null and conversionType is a value type.
   if( value == null ) {
    return null;
   } // end if

   // It's a nullable type, and not null, so that means it can be converted to its underlying type,
   // so overwrite the passed-in conversion type with this underlying type
   NullableConverter nullableConverter = new NullableConverter( conversionType );
   conversionType = nullableConverter.UnderlyingType;
  } // end if

  // Now that we've guaranteed conversionType is something Convert.ChangeType can handle (i.e. not a
  // nullable type), pass the call on to Convert.ChangeType
  return Convert.ChangeType( value, conversionType );
 }

Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Posted by Denny on Wednesday, February 06, 2008 9:20 AM
Permalink | Comments (2) | Post RSSRSS comment feed