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

New Open Source Project: BackTypeSharp

BackTypeSharp is a C# library that allows querying of BackType's API (www.backtype.com)

It was written in a fluent manner (or attempted) so that you can easily query BackType for information.

I started BackTypeSharp for a personal project and decided it could be useful to others and so I've decided to share it on CodePlex. I first saw BackType being used on Mashable.com. If you go to any story on Mashable's website and scroll towards the bottom you'll see a section called "Reactions" with comments from people posted via "BackType." A little research on BackType and a few days later I thought the "Reactions" was a neat idea and wanted to implement it into my own project. Since there were no libraries written in .NET to support interaction with the BackType API I created one.

I've used TweetSharp quite a bit and really enjoyed the fluent manner in which you execute requests so I attempted to model BackTypeSharp in a similar manner.

BackTypeSharp is far from a complete library and I will continue to work on it over time. If you'd like to help please feel free to contact me. There are some "tests" in the solution but I have no experience writing unit tests or doing TDD so I wouldn't rely on them. I would love to have someone who is experienced with writing unit tests help. If anything the test project shows how to query and get results using the library.

For more information on BackType you can visit the developer site here: BackType API Documentation

Check out the project on CodePlex here: BackTypeSharp

Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Posted by Denny on Tuesday, September 22, 2009 6:31 AM
Permalink | Comments (1) | Post RSSRSS comment feed

PLINQO: Professional LINQ Objects

If you haven't heard of PLINQO yet then you're missing out. The CodeSmith guys have enhanced the hell out of LINQ to SQL, to name a few features:

  • Entity Clone
  • Entity Detach ** My favorite!
  • Many to Many relationships
  • Auditing
  • Rules
  • Performance Enhancements

In their own words:

  • "In the time that LINQ to SQL has been available, we have been identifying ways to make LINQ to SQL better. We have compiled all of those cool tips and tricks including new features into a set of CodeSmith templates. PLINQO opens the LINQ TO SQL black box giving you the ability to control your source code while adding many new features and enhancements. It's still LINQ to SQL, but better!"

I've been using PLINQO for over a month now and I really like it. It does require a CodeSmith license... BUT you can get a license free!!! Check out the details here.

There's also a great review of PLINQO by Kevin Lawry here. Enjoy!

Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Tags: , ,
Posted by Denny on Sunday, July 05, 2009 3:46 AM
Permalink | Comments (0) | Post RSSRSS comment feed

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

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

SoCal Code Camp!

Just finished RSVP'ing for SoCal Code Camp! It will be held on Jan. 26 and 27 at the University of California Fullerton (UCF). Head over to the website (below) and sign up! Hope to see you there!

From the email:

If you haven't already registered at http://www.socalcodecamp.com for the upcoming Rock & Roll Code Camp to be held in Fullerton - why not take a minute to do it now!?!?

We already have 50 sessions and counting. Many of your favorite speakers are returning to provide you with great new content including Kevin McNeish, Paul Sheriff, Daniel Egan, Michele Leroux Bustamante, Mickey Williams, Woody Pewitt, David McCarter and more! Imagine, many of these internationally known speakers frequent conferences like Tech Ed, PDC, MIX, Dev Connections, VSLive and more! And you get to see them talk for FREE!!!!

There are also some budding new speakers that offer great sessions based on their real world experiences in the local community. You could even be one of them - feel free to add more sessions to the site, we have room for more!

The schedule will be posted one week before Code Camp so you can plan your attack!

Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Posted by Denny on Wednesday, January 16, 2008 5:44 AM
Permalink | Comments (0) | Post RSSRSS comment feed

Animating ASP.NET AJAX Update Panel Updates

Do you dislike the way that ASP.NET AJAX Update Panels update (or replace the content within the update panel)? Is it not flashy and Web 2.0 enough for you? Well fear no more! I've devised a straight-forward script to help you animate your update panel updates. This script uses jQuery (www.jquery.com) to animate the content when an update panel updates. It can easily be modified to use another library such as Scriptaculous. It uses javaScript to override ASP.NET AJAX's _updatePanel method within the PageRequestManager (the method which does the actual replacing of the content).

I've commented the script so you can understand what it's doing:


$(document).ready(
  function() {
      // SAVE the original _updatePanel function for later use.
      var old_prm_updatePanel = Sys.WebForms.PageRequestManager.getInstance()._updatePanel; 

      // Overwrite the original method with our code which will apply animation.
      // (Note: The method signature remains the same)
      Sys.WebForms.PageRequestManager.getInstance()._updatePanel = 
          function(updatePanelElement, rendering) {
              // Using jQuery to hide (animate) the element. Then use the callback function 
              // to load and show the new data. You don't want to update the
              // data beforehand otherwise you'll see your update panel flicker.
              $(updatePanelElement).hide('slow',
                  function() {
                      // Pass the old function and the args
                      loadShowUpdatePanel(old_prm_updatePanel, updatePanelElement, rendering);
                  });
          }
   });
 
function loadShowUpdatePanel(old_prm_updatePanel, updatePanelElement, rendering) {
    // Call the original (old) function with context of Page Request Manager instance.
    // We call the original method so ASP.NET AJAX can do all the necessary actions.
    old_prm_updatePanel.apply(Sys.WebForms.PageRequestManager.getInstance(),
                                                               new Array(updatePanelElement, rendering));

    // using jQuery again to show (animate) the update panel.
    $(updatePanelElement).show('slow');
}

And that's all you need. This script isn't just limited to animating the update panel update either... You can extend this script to do anything you want immediately before and after the new content is displayed. The main difference between this method and using the add_BeginRequest or add_EndRequest methods is the timing. This script will fire exactly before and after the update takes place - This would not be a good place to show a loading screen because the AJAX call has already been made, there's nothing to wait for. Whereas the BeginRequest executes before the AJAX call and EndRequest fires after the update has completed - This would be good to apply a loading screen.

kick it on DotNetKicks.com

Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Posted by Denny on Thursday, November 08, 2007 6:08 PM
Permalink | Comments (3) | Post RSSRSS comment feed

Extending SubSonic ActiveRecord

I was looking to refactor my User Management class to use SubSonic to do all the DAL processing and I decided to take advantage of SubSonic's Partial Classes to extend Extend!upon my "Account" ActiveRecord and merge my User Management class into the partial class. Note: I'm not referring to the AccountCollection object.

To be completely honest I'm not sure if this is the best way to handle this type of thing but thought it would be a fun exercise if nothing else.

SO let me share with you the code. Some of you may look at it and laugh, some may think it's really cool. Either way I'm throwing this out there so that whatever I learn as a result will help me (and hopefully you).

First lets take a look at the Account Partial Class that SubSonic generates:


[Serializable]
public partial class Account : ActiveRecord<Account>
{
 ...
}

Now there's nothing really important here other than the fact that it's a "Partial Class." So moving on let's see how we extend the class with one of our very own methods: LoginUser().

First we'll look at the code:


namespace DAL {
public partial class Account
{
 public void LoginUser()
 {
  this.LastLogin = DateTime.Now;
  this.LoginHash = new Guid().ToString(); 

  HttpCookie c = new HttpCookie( "LoginCookie" );
  c.Expires = DateTime.Now.AddDays( 5.0f );
  c.Values.Add( "lastlogin", this.LastLogin );
  c.Values.Add( "loginhash", this.LoginHash ); 

  this.Save( "app-ext-user" );
  HttpContext.Current.Response.Cookies.Add( c );
 }
}
}

Now what's really important is how our class is defined. Notice that our class is also a "Partial Class" and it has the same class name as the SubSonic generated class. It's also important to note that our class is defined within the same namespace as the SubSonic generated code - leaving out the namespace will not give you access to the Account constructors. Note: My previous code was inheriting from DAL.Account which was not necessary as pointed out by Kevin in the Comments section.

Within our class definition we have created the LoginUser method. This is the method we're creating to extend the Account class - in other words the method did not exist in the original SubSonic generated Account class.

Within the LoginUser method we use "this" to access the object's properties. "this" is pretty cool because it refers to the currently instantiated Account object (including our newly added method). However you should note that using "this" is not required... you can access the properties, methods, etc... simply by their name. (Kevin - Comments)

So we set a few properties: LastLogin and LoginHash, create a cookie, then we use the Save method to save our changes and also add our newly created login cookie to the Cookies collection.

We've now extended the original SubSonic ActiveRecord class with our LoginUser() method. Give it a shot:


Account a = new Account(acctid);
if( a.IsLoaded ) a.LoginUser();

This is a great way to extend a single SubSonic ActiveRecord with well defined functionality.

Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Tags: ,
Posted by Denny on Monday, October 29, 2007 10:15 AM
Permalink | Comments (5) | Post RSSRSS comment feed

SubSonic QueryCommand Object

The QueryCommand object in SubSonic makes writing SQL Commands a whole lot easier and less time consuming. When would you use it? Well sometimes the Query object can't perform complex queries, especially ones involving JOINS. So the QueryCommand is an excellent object to use when you need to run a complex query. Below is an example:


// The SQL (notice I am using parameters: @projectid)
string cmd1 = "SELECT ListName FROM tList a INNER JOIN tMain b ON b.tId = a.tId WHERE a.tId = @projectid";

// The QueryCommand object...
// SubSonic knows which connection to use based on the provider name “Master” which is defined in Web.Config
// Or leave it blank if you have a default provider selected (also defined in Web.Config)
QueryCommand q = new QueryCommand( cmd1, "Master" );

// Set the parameter(s)
q.AddParameter( "projectid", intProjectId, DbType.Int32, ParameterDirection.Input );

// Execute the command
string strValue = Convert.ToString( DataService.ExecuteScalar( q ) );

// You use the DataService object to execute your QueryCommand object.
// There are several methods you can use with the DataService object including:
//
// DataService.ExecuteQuery(...);
// DataService.ExecuteTransaction(...);
// DataService.GetDataSet(...);
// DataService.GetReader(...);

So in 4 lines of code (subtracting comments and breaks) you can run a custom SQL command. Thanks SubSonic!

Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Posted by Denny on Thursday, October 04, 2007 6:43 AM
Permalink | Comments (1) | Post RSSRSS comment feed

Some Interview Questions

Well I've been out on the chopping block lately getting some interviews. The first one sucked, needless to say I was not prepared. Anyways I came across a few interesting interview questions and thought I would share. They're mostly ASP.NET and not specific to any language except for question 1 which is for C#.

#1. Can you implement code in an abstract class?
I came from a VB.NET background and for some reason thought you couldn't (what the hell are interfaces then?? - D'oh!). Yes you can implement code in an abstract class! You can choose which properties and methods should be overridden by using the abstract keyword. The abstract keyword implicitly makes the method or property virtual whereas an interface is always virtual.

#2. Implement a function that will return a corresponding Fibonacci number: Fib(x)
Good old Fibonacci. Try creating a function that will add the sum of the previous 2 numbers. Example:

0 1 2 3 4 5 6  7...
------------------
0 1 1 2 3 5 8 13...

If we passed 6 into Fib(x) it should return 8 because it adds 3 and 5 (the two previous sums). This is a cool function because it can be implemented in about 2 lines of code (in a recursive function)! Try it yourself and then take a look at: http://en.csharp-online.net/Calculate_Fibonacci_number - It took me about 45 minutes to finally see the light, I was always slow at math.

#3. What is the order of Page_Load events if you have a page that uses a Master Page, the Content Page and a User Control? What if the User Control's PageOutput is set to cache the control?
I admit I goofed this one up. The events are as follows: Content Page, Master Page, User Control. And what about caching? The first time the page is loaded the control's Page_Load event will fire. It will not fire any further until it is removed from the cache. So while the User Control is cached the events are only Content Page and then Master Page. That will save you a lot of processing! (Makes sense doesn't it?)

#4. Create a regular expression to match the following: (xxx) xxx-xxxx
Ok, so unless you translate all your favorite books into hexadecimal and read them that way then you probably don't want to touch Regular Expressions. What in the world are all those slashes, squiggly's, dots, parenthesis and what not doing in there!! Well there's a good place to learn: www.regexlib.com and check out the Cheat Sheet. Anyways here's what I came up with (although at the interview I omitted the ^ and $):

^\(\d{3}\)\s\d{3}-\d{4}$

Yes that translates into a phone number :)

More to come... maybe...

Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Tags:
Posted by SuperGhost on Monday, June 18, 2007 3:33 PM
Permalink | Comments (2) | Post RSSRSS comment feed

Interview Questions: What Should I Expect?

I'm expecting an interview within the next few weeks for a position as a C# ASP.NET Developer (Mid-Level). At my current position I do a lot of VB.NET development; however I work with C# extensively at home on personal projects. I feel very confident about my presentation but in preparation would like to get some feedback on what to expect or what to focus on prior to an interview (C# specific). For example what kind of C# specific questions have you run into? What were you being tested for as far as your C# skills? Each company is different, of course, but I would like to hear about some of the experiences you have had.

I have read through Buu Nguyen's recent Interview Questions and this was a great starting point.

I look forward to your comments.

Update (4/30/2007 8:15am): Found a few more resources. This is a really good one http://www.devbistro.com/tech-interview-questions/.NET.jsp and also http://www.techinterviews.com/?cat=9

 

kick it on DotNetKicks.com

Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Tags:
Posted by SuperGhost on Sunday, April 29, 2007 4:00 PM
Permalink | Comments (3) | Post RSSRSS comment feed