0

Kirstin Juhl

Posted by David Starr on Oct 5, 2009 in Dotnet  | View Original Article
 

I am a former engineer who writes code. I did Toyota Operating System, Kanban, and Lean in my factories a decade ago, and am fascinated by its use in software development today. You can take the girl out of the factory, but you cannot take the engineer out of the girl, and so I approach everything in life as a problem to solved or optimized. Including software development. I strive to be a craftsman.

I am a mom, and I take lessons from parenthood into my work everyday.

Tags:

 
0

Private Extension Methods

Posted by K. Scott Allen on Oct 5, 2009 in Dotnet  | View Original Article
 

I spent a few hours on a failed experiment recently, but one concept that outlived the spike was how to make use of private extension methods. By private I mean the extension methods have a private access modifier and are only visible inside of a single class.

Sounds pointless, right?

Consider the code in the following class that is attempting to build multiple script tags out of the names of JavaScript files embedded as resources in an assembly.

public static class ScriptHelper
{
    public static string AsyncUploadScripts(this HtmlHelper helper)
    {
        var scriptNames = new string[] 
        {
            "Baz.Biz.js",
            "Bar.Foo.js",
            "Foo.Bar.js"
        };

        return scriptNames
            .Select(name =>
                _manager.GetWebResourceUrl(typeof(ScriptHelper), name))
            .Select(url => String.Format("... src='{0}' ...", url))
            .Aggregate(new StringBuilder(),
                       (sb, tag) => sb.Append(tag),
                        sb => sb.ToString());                          
    }

    // ...
}

That LINQ query is not pretty. Something with ON ERROR GOTO statements would be easier on the eyes.

I thought it would be nice if I could have descriptive names for the operations being performed. But, I didn’t want to create new extension methods for use outside the query.

Fortunately, extension methods as static private members work well inside the same class.

public static class ScriptHelper
{
    public static string AsyncUploadScripts(this HtmlHelper helper)
    {            
        var scriptTags = GetScriptResourceNames()
                            .MapNamesToResourceUrls()
                            .MapUrlsToScriptTags()
                            .CombineScriptTags();
        return scriptTags;                                              
    }

    static string CombineScriptTags(this IEnumerable<string> tags)
    {
        return tags.Aggregate(new StringBuilder(),
                    (sb, tag) => sb.Append(tag),
                    sb => sb.ToString());  
    }

    static IEnumerable<string> MapUrlsToScriptTags(
                                    this IEnumerable<string> urls)
    {
        return urls.Select(url =>
            String.Format("... src='{0}' ...", url));
    }

    static IEnumerable<string> MapNamesToResourceUrls(
                                    this IEnumerable<string> names)
    {
        return names.Select(name =>
                _manager.GetWebResourceUrl(typeof(ScriptHelper), name));
    }

    static IEnumerable<string> GetScriptResourceNames()
    {
        return new string[]
        {               
            "Baz.Bif.js",
            "Foo.Bar.js",
            "Zak.Wak.js",
        };            
    }

    // ...

The code is now in the junk pile, but the idea will stick with me forever … or at least until I switch to something else.

 
0

Flash on Devices

Posted by Rich Tretola on Oct 5, 2009 in Flex  | View Original Article
  Flash on Iphone: Flash Professional CS5 will enable you to build applications for iPhone and iPod touch using ActionScript 3. These applications can be delivered to iPhone and iPod touch users through the Apple App Store.* http://labs.adobe.com/technologies/flashcs5/appsfor_iphone/ http://www.youtube.com/watch?v=kusXgPAmMLw Flash10 on...

Tags: , , ,

 
0

Video: New CodeRush Plugin To Collapse Long Methods

Posted by Mehul Harry (Developer Express) on Oct 5, 2009 in ASP.Net, Dotnet  | View Original Article
 

Check out this short seven minute CodeRush plugin screencast with Rory Becker. The screencast explains:

  • What is DX_CollapseFromEnd?
  • How do you use it?
  • How was it built?

Rory is not just an avid fan of CodeRush but he’s an extraordinary plugin developer too. Not only has he developed several plugins but also goes the extra mile to help others learn about CodeRush and refactoring.

Click the image below and watch the full screencast. Then drop me and Rory a line below with your thoughts.

Video: CodeRush Plugin - Collapse From End

Tags: , , , ,

 
0

Flash Catalyst Beta 2: New Features

Posted by Chris Griffith on Oct 5, 2009 in Flex  | View Original Article
  With the release of the Flash Catalyst Beta 2, the public gets its next look at Adobe’s rapid prototyping tool. The application has continued to mature since the last release. Here is a brief rundown of some of the features...

Tags: , ,

 
0

Mastering CSS Coding: Getting Started

Posted by Soh Tanaka on Oct 5, 2009 in CSS, Design & Graphics  | View Original Article
 

  

Mastering CSS Coding: Getting Started (via @smashingmag) -

CSS has become the standard for building websites in today’s industry. Whether you are a hardcore developer or designer, you should be familiar with it. CSS is the bridge between programming and design, and any Web professional must have some general knowledge of it. If you are getting your feet wet with CSS, this is the perfect time to fire up your favorite text editor and follow along in this tutorial as we cover the most common and practical uses of CSS.

Overview: What We Will Cover Today

We’ll start with what you could call the fundamental properties and capabilities of CSS, ones that we commonly use to build CSS-based websites:

  1. Padding vs. margin
  2. Floats
  3. Center alignment
  4. Ordered vs. unordered lists
  5. Styling headings
  6. Overflow
  7. Position

Once you are comfortable with the basics, we will kick it up a notch with some neat tricks to build your CSS website from scratch and make some enhancements to it.

  1. Background images
  2. Image enhancement
  3. PSD to XHTML

1. Padding vs. Margin

Most beginners get padding and margins mixed up and use them incorrectly. Practices such as using the height to create padding or margins also lead to bugs and inconsistencies. Understanding padding and margins is fundamental to using CSS.

What Is Padding and Margin?

Padding is the inner space of an element, and margin is the outer space of an element.

The difference becomes clear once you apply backgrounds and borders to an element. Unlike padding, margins are not covered by either the background or border because they are the space outside of the actual element.

Take a look at the visual below:

Box Model

Padding/Margin Values
Margin and padding values are set clockwise, starting from the top.

Practical example: Here is an <h2> heading between two paragraphs. As you can see, the margin creates white space between the paragraphs, and the padding (where you see the background gray color) gives it some breathing room.

Box Model - Example

Margin and Padding Values

In the above example of the heading, the values for the margin and padding would be:

margin: 15px 0 15px 0;
padding: 15px 15px 15px 15px;

To optimize this line of code further, we use an optimization technique called “shorthand,” which cuts down on repetitive code. Applying the shorthand technique would slim the code down to this:

margin: 15px 0; /*--top and bottom = 15px | right and left = 0 --*/
padding: 15px; /*--top, right, bottom and left = 15px --*/

Here is what the complete CSS would look like for this heading:

h2 {
background: #f0f0f0;
border: 1px solid #ddd;
margin: 15px 0;
padding: 15px;
}

Quick Tip

Keep in mind that padding adds to the total width of your element. For example, if you had specified that the element should be 100 pixels wide, and you had a left and right padding of 10 pixels, then you would end up with 120 pixels in total.

100px (content) + 10px (left padding) + 10px (right padding) = 120px (total width of element)

Margin, however, expands the box model but does not directly affect the element itself. This tip is especially handy when lining up columns in a layout!

Additional resources:

2. Floats

Floats are a fundamental element in building CSS-based websites and can be used to align images and build layouts and columns. If you recall how to align elements left and right in HTML, floating works in a similar way.

According to HTML Dog, the float property “specifies whether a fixed-width box should float, shifting it to the right or left, with surrounding content flowing around it.”

Float

The float: left value aligns elements to the left and can also be used as a solid container to create layouts and columns. Let’s look at a practical situation in which you can use float: left.

Float to Create Layouts

The float: right value aligns elements to the right, with surrounding elements flowing to the left.

Quick tip: Because block elements typically span 100% of their parent container’s width, floating an element to the right knocks it down to the next line. This also applies to plain text that runs next to it because the floated element cannot squeeze in the same line.

Floating right bug

You can correct this issue in one of two ways:

  1. Reverse the order of the HTML markup so that you call the floated element first, and the neighboring element second.
    Floating right fix
  2. Specify an exact width for the neighboring element so that when the two elements sit side by side, their combined width is less than or equal to the width of their parent container.
    Floating right fix

Internet Explorer 6 (IE6) has been known to double a floated element’s margin. So, what you originally specified as a 5-pixel margin becomes 10 pixels in IE6.

Double Margin Bug - IE6

A simple trick to get around this bug is to add display: inline to your floated element, like so:

.floated_element {
float: left;
width: 200px;
margin: 5px;
display: inline; /*--IE6 workaround--*/
}

Additional resources:

3. Center Alignment

The days of using the <center> HTML tag are long gone. Let’s look at the various ways of center-aligning an element.

Horizontal Alignment

You can horizontally align text elements using the text-align property. This is quite simple to do, but keep in mind when center-aligning inline elements that you must add display: block. This allows the browser to determine the boundaries on which to base its alignment of your element.

.center {
text-align: center;
display: block; /*--For inline elements only--*/
}

To horizontally align non-textual elements, use the margin property.

The W3C says, “If both margin-left and margin-right are auto, their used values are equal. This horizontally centers the element with respect to the edges of the containing block.”

Horizontal alignment can be achieved, then, by setting the left and right margins to auto. This is an ideal method of horizontally aligning non-text-based elements; for example, layouts and images. But when center-aligning a layout or element without a specified width, you must specify a width in order for this to work.

To center-align a layout:

.layout_container {
margin: 0 auto;
width: 960px;
}

To center-align an image:

img.center {
margin: 0 auto;
display: block; /*--Since IMG is an inline element--*/
}

Vertical Alignment

You can vertically align text-based elements using the line-height property, which specifies the amount of vertical space between lines of text. This is ideal for vertically aligning headings and other text-based elements. Simply match the line-height with the height of the element.

Line-height

h1 {
font-size: 3em;
height: 100px;
line-height: 100px;
}

To vertically align non-textual elements, use absolute positioning.

The trick with this technique is that you must specify the exact height and width of the centered element.

With the position: absolute property, an element is positioned according to its base position (0,0: the top-left corner). In the image below, the red point indicates the 0,0 base of the element, before a negative margin is applied.

By applying negative top and left margins, we can now perfectly align this element both vertically and horizontally.

Absolute Position

Here is the complete CSS for horizontal and vertical alignment:

.vertical {
width: 600px; /*--Specify Width--*/
height: 300px; /*--Specify Height--*/
position: absolute; /*--Set positioning to absolute--*/
top: 50%; /*--Set top coordinate to 50%--*/
left: 50%; /*--Set left coordinate to 50%--*/
margin: -150px 0 0 -300px; /*--Set negative top/left margin--*/
}

Related articles:

4. Ordered vs. Unordered Lists

An ordered list, <ol>, is a list whose items are marked with numbers.

An unordered list, <ul>, is a list whose items are marked with bullets.

By default, both of these list item styles are plain and simple. But with the help of CSS, you can easily customize them.

To keep the code semantic, lists should be used only for content that is itemized in a list-like fashion. But they can be extended to create multiple columns and navigation menus.

Customizing Unordered Lists

Plain bullets are dull and may not draw enough attention to the content they accompany. You can fix this with a simple yet effective technique: remove the default bullets and apply a background image to each list item.

Here is the CSS for custom bullets:

ul.product_checklist {
list-style: none; /*--Takes out the default bullets--*/
margin: 0;
padding: 0;
}
ul.product_checklist li {
padding: 5px 5px 5px 25px; /*--Adds padding around each item--*/
margin: 0;
background: url(icon_checklist.gif) no-repeat left center; /*--Adds a bullet icon as a background image--*/
}

Custom List Items

Resources for list items:

Using Unordered Lists for Navigation

Most CSS-based navigation menus are now built as lists. Here is a breakdown of how to turn an ordinary list into a horizontal navigation menu.

HTML: begin with a simple unordered list, with links for each list item.

<ul id="topnav">
<li><a href="#">Home</a></li>
<li><a href="#">Services</a></li>
<li><a href="#">Portfolio</a></li>
<li><a href="#">About</a></li>
<li><a href="#">Contact</a></li>
</ul>

CSS: we remove the default bullets (as we did when we made custom bullets) by specifying list-style: none. Then, we float each list item to the left so that the navigation menu appears horizontal, flowing from left to right.

ul#topnav {
list-style: none;
float: left;
width: 960px;
margin: 0; padding: 0;
background: #f0f0f0;
border: 1px solid #ddd;
}
ul#topnav li {
float: left;
margin: 0; padding: 0;
border-right: 1px solid #ddd;
}
ul#topnav li a {
float: left;
display: block;
padding: 10px;
color: #333;
text-decoration: none;
}
ul#topnav li a:hover {
background: #fff;
}

Additional resources:

5. Styling Headings

The heading HTML tag is important for SEO. But regular headings can look dull. Why not spice them up with CSS and enjoy the best of both worlds?

Once you have the main styling properties set for your headings, you can now nest inline elements to target specific text for extra styling.

Styling Headings

Your HTML would look like this:

<h1><span>CSS</span> Back to Basics <small>Tips, Tricks, &amp; Practical Uses of CSS</small></h1>

And your CSS would look like this:

h1 {
font: normal 5.2em Georgia, "Times New Roman", Times, serif;
margin: 0 0 20px;
padding: 10px 0;
font-weight: normal;
text-align: center;
text-shadow: 1px 1px 1px #ccc; /*--Not supported by IE--*/
}
h1 span {
color: #cc0000;
font-weight: bold;

}
h1 small {
font-size: 0.35em;
text-transform: uppercase;
color: #999;
font-family: Arial, Helvetica, sans-serif;
text-shadow: none;
display: block; /*--Keeps the small tag on its own line--*/
}

Additional typography-related resources:

6. Overflow

The overflow property can be used in various ways and is one of the most useful properties in the CSS arsenal.

What Is Overflow?

According to W3Schools.com, “the overflow property specifies what happens if content overflows an element’s box.”

Take a look at the following examples to see how this works.

Overflow

Visually, overflow: auto looks like an iframe but is much more useful and SEO-friendly. It automatically adds a scroll bar (horizontal, vertical or both) when the content within an element exceeds the element’s box or boundary.

The overflow: scroll property works the same but forces a scroll bar to appear regardless of whether or not the content exceeds the element’s boundary.

And the overflow: hidden property masks or hides an element’s content if it exceeds the element’s boundary.

Quick tip: have you ever had a parent element that did not fully wrap around its child element? You can fix this by making the parent container a floated element.

In some cases, though, floating left or right is not a workable solution — for example, if you want to center-align the container or do not want to specify an exact width. In this case, use overflow: hidden on your parent container to completely wrap any floated child elements within it.

Overflow

Additional resources:

7. Position

Positioning (relative, absolute and fixed) is one of the most powerful properties in CSS. It allows you to position an element using exact coordinates, giving you the freedom and creativity to design out of the box.

You have to do three basic things when using positioning:

  1. Set the coordinates (i.e. define the positioning of the x and y coordinates).
  2. Choose the right value for the situation: relative, absolute, fixed or static.
  3. Set a value for the z-index property: to layer elements (optional).

With position: relative, an element is placed in its natural position. For example, if a relatively positioned element sits to the left of an image, setting the top and left coordinates to 10px would move the element just 10 pixels from the top and 10 pixels from the left of that exact spot.

Relative positioning is also commonly used to define the new point of origin (the x and y coordinates) of absolutely positioned nested elements. By default, the base position of every element is the top-left corner (0,0) of the browser’s view port. When you give an element relative positioning, then the base position of any child elements with absolute positioning will be positioned relative to their parent element — i.e. 0,0 is now the top-left corner of the parent element, not the browser’s view port.

Relative Position

An element with a value of position: absolute can be placed anywhere using x and y coordinates. By default, its base position (0,0) is the top-left corner of the browser’s view port. It ignores all natural flow rules and is not affected by surrounding elements.

The base position of an element with a position: fixed value is also the top-left corner of the browser’s view port. The difference with fixed positioning is that the element will be fixed to its location and remain in view even when the user scrolls up or down.

The z-index property specifies the stack order of an element. The higher the value, the higher the element will appear.

Think of z-index stacking as layering. Check out the image below for an example:

z-index

Additional resources:

Adding Flavor With CSS

Now that you understand the basics, step up your game by adding a bit of flavor to your CSS. Below are some common techniques for enhancing and polishing your layout and images. We’ll also challenge you to create your own website from scratch using pure CSS.

9. Background Images

Background images come in handy for many visual effects. Whether you add a repeating background image to cover a large area or add stylish icons to your navigation, the property makes your page come to life.

Note, though, that the default print setting excludes the background property. When creating printable pages, be mindful of which elements have background images and include image tags.

Using Large Backgrounds

With monitor sizes getting bigger and bigger, large background images for websites have become quite popular.

Check out this detailed tutorial by Nick La of WebDesigner Wall on how to achieve this effect:

Large Backgrounds in Web Design

Also be sure to read the article on Webdesigner Depot about the “Do’s and Don’ts of Large Website Backgrounds.”

Text Replacement

You may be aware that not all standard browsers yet support custom fonts embedded on a website. But you can replace text with an image in various ways. One rather simple technique is to use the text-indent property.

Most commonly seen with headings, this technique replaces structured HTML text with an image.

h1 {
background: url(home_h1.gif) no-repeat;
text-indent: -99999px;
}

You may sometimes need to specify a width and height (as well as display: block if the element is inline).

.replacethis {
background: url(home_h1.gif) no-repeat;
text-indent: -99999px;
width: 100%;
height: 60px;
display: block; /*--Needed only for inline elements--*/
}

Articles on text replacement:

CSS Sprites

CSS Sprites is a technique in which you use background positioning to show only a small area of a larger single background image (the larger image being actually multiple images laid out in a grid and merged into one file).

CSS Sprites

CSS Sprites are commonly used with icons and the hover and active states of images that have replaced links and navigation items.

CSS Sprites

Why use CSS Sprites? CSS Sprites save loading time and cut down on CSS and and HTTP requests. To learn more about CSS Sprites, check out the resources below!

Articles on CSS Sprites:

10. Image Enhancement

You can style images with CSS in various ways, and some designers have made a lot of effort to create very stylish image templates.

One simple trick is the double-border technique, which does not require any additional images and is pure CSS.

Double Border Technique

Your HTML would look like this:

<img class="double_border" src="sample.jpg" alt="" />

And your CSS would look like this:

img.double_border {
border: 1px solid #bbb;
padding: 5px; /*Inner border size*/
background: #ddd; /*Inner border color*/
}

Nick La of WebDesigner Wall has a great tutorial on clever tricks to enhance your images. Do check it out!

CSS Sprites

11. PSD to HTML

Now that you have learned the fundamentals of CSS, it’s time to test your skill and build your own website from scratch! Below are some hand-picked tutorials from the best of the Web.

Conclusion

Developing a strong foundation early on is critical to mastering CSS. Given how fast Web technology advances, there is no better time than now to get up to speed on the latest standards and trends.

Hopefully, the techniques we’ve covered here will give you a head start on becoming the ultimate CSS ninja. Good luck, stay hungry and keep learning!

About the Author

Soh Tanaka is a Los Angeles-based Web designer and blogger who recently launched a CSS Gallery called Design Bombs. For more front-end Web development tutorials, check out his Web design blog or follow him on Twitter, @SohTanaka.

(al)


© Soh Tanaka for Smashing Magazine, 2009. | Permalink | 22 comments | Add to del.icio.us | Digg this | Stumble on StumbleUpon! | Tweet it! | Submit to Reddit | Forum Smashing Magazine
Post tags:

 
0

Fun with Func<T,TResult> Delegates, Events and Async Operations

Posted by Rick Strahl on Oct 5, 2009 in C#, Dotnet  | View Original Article
 

Func<T> has been in .NET for a while, but with the arrival of LINQ it’s moved into the limelight as main performer that makes Lambda expressions work. Func<T> is basically a generic delegate that makes it extremely easy to create all sorts of custom delegate signatures without having to explicitly implement the delegates separately.

Events

How often have you lamented the fact that you have to create a custom delegate for an event that needs to fire a method that uses non-typical event arguments? Traditionally you had to create the method and also create a delegate that matched the signature which is a bit verbose at best. Typical event setup code looks something like this:

public event delInvoiceCalculation CalculateTax;
public delegate decimal delInvoiceCalculation(wws_Invoice invoice);
       
public virtual decimal OnCalculateTax(wws_Invoice invoice)
{
    if (CalculateTax != null)   
        return CalculateTax(entity);
    
    return invoice.Tax;
}

You have to declare a separate delegate and provide the appropriate signature to match the event function that should be called.

Using Func<T> this code can be made a bit cleaner by removing the extra delegate. Here’s another implementation for a similar method using the same signature but using Func<T> or more specifically in this example, Func<T,TResult>

public event Func<wws_Invoice,decimal> CalculateHandling;
public virtual decimal OnCalculateHandling(wws_Invoice invoice)
{
    // TODO: provide logic here
    if (CalculateHandling != null)
        return CalculateHandling(invoice);

    return invoice.Handling;
}

Func<T> simplifies the event signature a bit by removing the explicit delegate declaration and instead using the generic Func<T,TResult> implementation that allows you to create a custom delegate signature directly on the event. Not only does it save a little bit of code typing, but I also find this easier to see what’s going because it is more explicit in a single statement compared the first snippet where delegate and event declaration are separate (and often completely separated physically because the delegate is reused by multiple events).

Func<T> is a generic function signature/delegate and it works by implementing a delegate by way of its generic parameters. The last generic parameter provided is always the type of the return value (decimal above). Any preceeding generic parameters (up to 4 in Func<T>’s overloads) become the types of input parameters. In this case my signature is for Func<T,TResult> where T is my invoice entity and TResult is bool.

In this respect:

Func<wws_Invoice,decimal>

is equivalent to:

public delegate decimal delInvoiceCalculation(wws_Invoice invoice);

except it doesn’t have to be explicitly declared.

Func<T> in LINQ

Delegates are generally easy to understand but it’s one of those features we don’t use all that often and so it’s easy to forget how they work and what we need them for. Well we know LINQ is full of them – most LINQ operators like .Where() and OrderBy() and Select() to name a few all rely on Func<T> signatures for Lambda expressions. Between Func<T> delegate signatures and lamda expressions statements like this:

Context.wws_Items.Where( itm => itm.Sku == sku );

become possible and quite readable once you get over the initial weirdness of the => operator. What you’re looking at in the Where clause is actually an implemenation of Func<T,bool>:

.FuncTWhere

The input parameter is the the enumerable type (wws_Item from the List<wws_Item> and the return value is bool. The return value is inferred by the compiler and so only the input parameter is used (itm =>) in the lambda expression’s left side. Func<T> is a key feature to make LINQ workable using terse code.

Note that if you use LINQ to SQL or LINQ to Entities Func<T> based parameters to any LINQ commands require an Expression wrapper that wraps the Func<T> expression. This is because these tools delay executing the expressions until a later point in time when the expressions are parsed into some other format (SQL command, Entity SQL or whatever the expression engine uses).

This actually tripped me up yesterday and was what got me on to writing up this content. In my business layer I have basic CRUD operations including the ability to load entities without running a full LINQ command. There’s a base implementation that takes a LINQ expression as a parameter that is passed to a LINQ .Where() method that executes the actual query. At first I passed a Func<T> argument but I quickly found out that this doesn’t actually work – the result from the LINQ to SQL query always returned null. The reason: It’s not an expression that was passed but just a predicate.

I had to make sure the method was declared correctly using an Expression and the correct code that works looks like this:

protected virtual TEntity LoadBase(Expression<Func<TEntity, bool>> whereClauseLambda)
{
    SetError();

    try
    {
        TContext context = Context;

        // If disconnected we'll create a new context
        if (Options.TrackingMode == TrackingMode.Disconnected)
            context = CreateContext();

        Entity = Context.GetTable<TEntity>().Where(whereClauseLambda).SingleOrDefault();

        if (Entity != null)
            OnLoaded(Entity);                

        return Entity;
    }
    catch (InvalidOperationException)
    {
        // Handles errors where an invalid Id was passed, but SQL is valid
        SetError("Couldn't load entity - invalid key provided.");
        Entity = null;
        return null;
    }
    catch (Exception ex)
    {
        // handles any other sql errors                
        Entity = null;
        SetError(ex);
    }

    return null;
}

This makes it super easy to create custom load methods that all use the common LoadBase method and so inherit its behavior. in most cases it becomes as trivial as this:

/// <summary>
/// Loads an individual item by sku
/// </summary>
/// <param name="sku"></param>
/// <returns></returns>
public wws_Item LoadBySku(string sku)
{
    return this.LoadBase(itm => itm.Sku == sku);
}

which is pretty nice and consistent.

Easy Async

Here’s another useful example of how Func<T> can make life a lot easier. For example, kicking off an async delegate with Func<T> becomes a single line operation which makes it a snap to turn just about any operation into an async operation like this async update routine:

public void LogSnippetViewAsync(string snippetId, string ipAddress, string userAgent)
{
    Func<string, string, string, bool> del = this.LogSnippetView;
    del.BeginInvoke(snippetId, ipAddress, userAgent, null, null);
}

public bool LogSnippetView(string snippetId, string ipAddress, string userAgent)
{
    if (string.IsNullOrEmpty(userAgent))
        return false;

    userAgent = userAgent.ToLower();

    if (!(userAgent.Contains("mozilla") || !userAgent.StartsWith("safari") ||
        !userAgent.StartsWith("blackberry") || !userAgent.StartsWith("t-mobile") ||
        !userAgent.StartsWith("htc") || !userAgent.StartsWith("opera")))
        return false;

    this.Context.LogSnippetClick(snippetId, ipAddress); // stored proc

    return true;
}

Here’s Func<T1,T2,T3,TResult> is used to specify 3 parameters (3 strings) and a return value of bool. del is the Delegate declaration and we’re pointing it at the LogSnippetView method to execute. Then BeginInvoke is called to asynchronously launch the method so it runs in the background on a thread pool thread.

Again, using Func<T> avoids having to explicitly declare a delegate separately and instead you can directly declare the delegate signature via Func<T> inline which is easier to read and understand – at least to me.

Sometimes it’s the little things that make life easier and Func<T> is one of those.

© Rick Strahl, West Wind Technologies, 2005-2009
Posted in CSharp  LINQ  
kick it on DotNetKicks.com

Tags:

 
0

Find & Compare PHP, CSS, JavaScript and Ruby Frameworks

Posted by W3Avenue Team on Oct 5, 2009 in CSS, Javascript, PHP  | View Original Article
 

Bestwebframeworks is a website where you can find and review different frameworks for PHP, CSS, JavaScript and Ruby Frameworks. Descriptive icons allows you to compare features with a glance. Each framework offers a description with a possibility to add a review or download the framework.

This website can be really useful for a lot of new developers who usually struggle when it comes to picking right framework. Since the site is fairly new, only few reviews are available at the time of this post. Hopefully with passage of time people will share their experiences to help other make the right decision.

You can visit Bestwebframeworks here: http://www.bestwebframeworks.com/

Similar Posts:

Tags: ,

Copyright © 2010 Answer My Query All rights reserved. Maintained by Orange Brains .