Amazon.com Widgets February 2010

WilliaBlog.Net

I dream in code

About the author

Robert Williams is an internet application developer for the Salem Web Network.
E-mail me Send mail
Code Project Associate Logo
Go Daddy Deal of the Week: 30% off your order at GoDaddy.com! Offer expires 11/6/12

Recent comments

Archive

Authors

Tags

Disclaimer

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


Use lambda expressions to aggregate values into a delimited string

Let's say you need to aggregate one value from each object in a list into a single string. For Example, you want to send an e-mail to a set of customers. This requires a string with the email addresses seperated by a semicolon (;). The following code will create a generic List of Books, and provide a method ListAllEmails() that will print the delimited list of emails to the console window:

 

namespace ConsoleApplication1

{

    using System;

    using System.Collections.Generic;

    using System.Linq;

 

    public class Lambdas

    {

        /// <summary>

        /// Define the Book Class

        /// </summary>

        public class Book

        {

            public string Title { get; set; }

            public string Author { get; set; }

            public double Price { get; set; }

            public string EmailAddress { get; set; }

        }

 

        public List<Book> Books { get; private set; }

 

        public Lambdas()

        {

            // Create a new list of Books

            Books = new List<Book> {

                new Book { Title = "Pro ASP.Net MVC Framework", Author = "Steven Sanderson", Price = 49.99, EmailAddress = "steve@nospam.com" },

                new Book{ Title = "Pro Silverlight 2 in C# 2008", Author = "Matthew MacDonald", Price = 49.99, EmailAddress = "Matthew@nospam.com" },

                new Book{ Title = "Pro VB 2008 and the .Net 3.5 Platform", Author = "Andrew Troelsen", Price = 59.99, EmailAddress = "Andrew@nospam.com" }

            };

        }

 

        /// <summary>

        /// Creates a semicolon (;) delimited list of email addresses

        /// </summary>

        public void ListAllEmails()

        {

            Console.WriteLine(this.Books.Select(b => b.EmailAddress).Aggregate((items, item) => items + "; " + item));

            // output= "steve@nospam.com; Matthew@nospam.com; Andrew@nospam.com"

        }

    }

}

 

The Select Method selects the EmailAddress for each Book. The Aggregate method builds a list of the items based on the lambda expression. Notice that this did not require any additional code to ensure there is no extra semi-colon at the beginning or end of the list, which is often required when using a loop to concatenate text.

 

Note: Be careful when using the Aggregate method because it is very inefficient on large numbers of strings. Consider using the String Join method instead.

 

In VB, the lambda would look like this:

 

   Console.WriteLine(Books.Select(Function(b) b.EmailAddress).Aggregate(Function(items, item) items & "; " & item))

 

You can also filter the list of email addresses. For Example, suppose you want to send an email to all the authors who sell their books for under $50, telling them that you think you can sell their next book for $59.99:

 

        /// <summary>

        /// Creates a semicolon (;) delimited list of email addresses where the price of the book is under $50

        /// </summary>

        public void ListSomeEmails()

        {

            Console.WriteLine(this.Books.Where(b => b.Price < 50).Select(b => b.EmailAddress).Aggregate((items, item) => items + ", " + item));

            // output= "steve@nospam.com, Matthew@nospam.com"

        }

 

Let's take this one step further. Suppose you wanted to create a comma separated list of values and replace the last comma with " and", so that a single item would be "item1", two items would be "item1 and item2", three items would be "item1, item2 and item3", etc.

 

        /// <summary>

        /// Creates a comma delimited list of email addresses and replaces the last comma with " and "

        /// </summary>

        public void ListEmailsAsSmartCsv()

        {

            string csv = this.Books.Select(b => b.EmailAddress).Aggregate((items, item) => items + ", " + item);

            Console.WriteLine(Regex.Replace(csv, @",\s([^,]+)$", " and $1"));

            // output= "steve@nospam.com, Matthew@nospam.com and Andrew@nospam.com"

        }

 

 


Tags:
Categories: ASP.Net | C# | VB
Posted by Williarob on Friday, February 26, 2010 9:44 AM
Permalink | Comments (0) | Post RSSRSS comment feed

Buy your next car in Europe

How would you like a free trip to Europe? If you are thinking of buying a German or Swedish car, consider taking delivery of the car at the auto maker's factory, and the savings could pay for your trip. Several auto makers not only promise hefty discounts on the price of the car, they thow other goodies into the deal, from a night's stay at a luxury hotel to roundtrip airfare for two from the U.S. The automakers - Audi, BMW, Mercedes-Benz, Porsche and Volvo - offer such perks because they have learned that European delivery programs build brand loyalty. When customers pick up their cars, they receive VIP treatment that includes escorted tours of the factories.

So how much can you save? Using a couple of Audi sedans as examples, around $1,600 on an A4 to some $3700 on an A8. The more expensive the car, the more you'll save. Here are some specifics:

  • Audi gives a five percent discount off most models' MSRP, plus one night's hotel stay and a meal at the automaker's restaurant on delivery day.
  • BMW gives seven percent off MSRP, plus two-for-one airfare on Lufthansa and a meal.
  • Mercedes-Benz gives seven percent off MSRP, two-for-one airfare on Lufthansa, one night's hotel stay and a meal.
  • Porsche offers no factory discount but it does give one night's hotel stay and lunch at the factory dining room.
  • Volvo gives eight percent off MSRP, airfare for two on Scandinavian Arilines, one night's hotel stay and a meal.

Make the trip a vacation, and with your own car, you avoid the costs of rental cars and ground transportation while you travel Europe. Each automaker provides temporary European registration, car insurance for two weeks or more, shipping to the U.S., and U.S. Customs and port clearance, all at no extra charge. You then pick up your car at the local dealer after it arrives in the U.S.

And the catch? Expect to initiate the process two to four months before your trip to Europe. And once you've finished your European excursion, expect another two months or so before you can fetch the car from your local dealer. You'll also have to time your delivery to avoid factory holidays - Europeans tend to take a lot of them.

Source: "Buying a Car in Europe", by Peter Bohr, AAA World magazine (March / April 2010)


Tags:
Posted by on Friday, February 26, 2010 8:17 AM
Permalink | Comments (0) | Post RSSRSS comment feed

Taking P90X to the next level.

First let me start by saying that I think the P90X Workout system is great. The workouts are intense, effective and fun (at least once you are finally fit enough to do them - the first time I tried the Plyometrics Jump training I barely made it through the warm up and I'll admit I still don't look forward to it). However, I believe the system works best for people who are trying to lose a little weight and add some definition, rather than those of us who are already slim and trying to add 10 lbs or more of muscle. Having said that, if you follow the program closely and watch what you eat, you certainly will gain some muscle - my arms were noticeably bigger after 90 days and my body fat had dropped from around 14% to 7%, while my body weight remained the same.

About 5 months after I started the P90X program it became apparent to me, that all the exercises relying heavily on the use dumbbells added significantly more muscle than the workouts that rely more on body weight and gravity alone (such as Chest and Back which is mostly just push ups and pull ups). Sure my chest was toned and more than a little sore after these workouts, even after 90 days, but growth was minimal. Push ups can only take you so far, especially when you only weigh 150 lbs. Since I have a gym membership, I took the standard Chest and Back, and the Chest, Shoulders, Triceps workouts and replaced most of the push ups with exercises that can be done at the gym using the machines and free weights, and immediately felt that I had taken P90X to the next level. Here is my new Chest and Back Workout:

Date:          
Warm Up, Stretch, Std Push-Ups (25) 25 25 25 25 25
Wide Front Pull-Ups          
Incline Press (Barbell, 2 sets 8-12) R______W_______
R______W_______
R______W_______
R______W_______
R______W_______
R______W_______
R______W_______
R______W_______
R______W_______
R______W_______
Reverse Grip Chin-Ups          
Incline Press (Dumbbell, 2 sets 8-12) R______W_______
R______W_______
R______W_______
R______W_______
R______W_______
R______W_______
R______W_______
R______W_______
R______W_______
R______W_______
Closed Grip Overhand Pull-ups          
Bench Press (Barbell, 2 sets 8-12) R______W_______
R______W_______
R______W_______
R______W_______
R______W_______
R______W_______
R______W_______
R______W_______
R______W_______
R______W_______
Heavy Pants R______W_______ R______W_______ R______W_______ R______W_______ R______W_______
Bench Press (Dumbbell, 2 sets 8-12) R______W_______
R______W_______
R______W_______
R______W_______
R______W_______
R______W_______
R______W_______
R______W_______
R______W_______
R______W_______
Lawnmowers R______W_______ R______W_______ R______W_______ R______W_______ R______W_______
Decline Bench Press (Dumbbell or barbell, 2 sets 8-12) R______W_______
R______W_______
R______W_______
R______W_______
R______W_______
R______W_______
R______W_______
R______W_______
R______W_______
R______W_______
Back Flies R______W_______ R______W_______ R______W_______ R______W_______ R______W_______
Decline Push-Ups (Max Reps/25) R_______________ R_______________ R_______________ R_______________ R_______________
Elbows-out Lawnmowers R______W_______ R______W_______ R______W_______ R______W_______ R______W_______
Incline Press (Machine, 2 sets 8-12) R______W_______
R______W_______
R______W_______
R______W_______
R______W_______
R______W_______
R______W_______
R______W_______
R______W_______
R______W_______
Supermans 5 5 5 5 5
Bench Press (Machine, 2 sets 8-12) R______W_______
R______W_______
R______W_______
R______W_______
R______W_______
R______W_______
R______W_______
R______W_______
R______W_______
R______W_______
CHEST & BACK          
           

Download this as an Excel Spreadsheet:

Chest & Back.xls (24.00 kb)

And here is my new Chest, Shoulders, Triceps workout:

Date:          
Warm Up, Stretch, Std Push-Ups (25) 25 25 25 25 25
In & Out Shoulder Flys R______W_______ R______W_______ R______W_______ R______W_______ R______W_______
Chair Dips R_______________ R_______________ R_______________ R_______________ R_______________
Incline Press (Barbell, 2 sets 8-12) R______W_______
R______W_______
R______W_______
R______W_______
R______W_______
R______W_______
R______W_______
R______W_______
R______W_______
R______W_______
Deep Swimmer's Press R______W_______ R______W_______ R______W_______ R______W_______ R______W_______
Overhead Tricep Extensions R______W_______ R______W_______ R______W_______ R______W_______ R______W_______
Incline Press (Dumbbell, 2 sets 8-12) R______W_______
R______W_______
R______W_______
R______W_______
R______W_______
R______W_______
R______W_______
R______W_______
R______W_______
R______W_______
Scarecrows R______W_______ R______W_______ R______W_______ R______W_______ R______W_______
Lying Tricep Extensions R______W_______ R______W_______ R______W_______ R______W_______ R______W_______
Bench Press (Barbell, 2 sets 8-12) R______W_______
R______W_______
R______W_______
R______W_______
R______W_______
R______W_______
R______W_______
R______W_______
R______W_______
R______W_______
Y-Presses R______W_______ R______W_______ R______W_______ R______W_______ R______W_______
Side-Leaning Tricep Extensions R______W_______ R______W_______ R______W_______ R______W_______ R______W_______
Bench Press (Dumbbell, 2 sets 8-12) R______W_______
R______W_______
R______W_______
R______W_______
R______W_______
R______W_______
R______W_______
R______W_______
R______W_______
R______W_______
Weighted Circles R______W_______ R______W_______ R______W_______ R______W_______ R______W_______
Throw the Bomb R______W_______ R______W_______ R______W_______ R______W_______ R______W_______
Decline Bench Press (Dumbbell or barbell, 2 sets) R______W_______
R______W_______
R______W_______
R______W_______
R______W_______
R______W_______
R______W_______
R______W_______
R______W_______
R______W_______
Pour Flys (straight arms, out to sides, pour) R______W_______ R______W_______ R______W_______ R______W_______ R______W_______
Front-to-Back Tricep Extensions R______W_______ R______W_______ R______W_______ R______W_______ R______W_______
Incline Press (Machine, 2 sets 8-12) R______W_______
R______W_______
R______W_______
R______W_______
R______W_______
R______W_______
R______W_______
R______W_______
R______W_______
R______W_______
Two-Angle Shoulder Flys R______W_______ R______W_______ R______W_______ R______W_______ R______W_______
Two-Arm Tricep Kickbacks R______W_______ R______W_______ R______W_______ R______W_______ R______W_______
Bench Press (Machine, 2 sets 8-12) R______W_______
R______W_______
R______W_______
R______W_______
R______W_______
R______W_______
R______W_______
R______W_______
R______W_______
R______W_______
CHEST, SHOULDERS & TRICEPS      
           

Chest Shoulders & Triceps.xls (24.50 kb)

I think the Back and Biceps and the Shoulder, Biceps, Triceps workouts are great as they are, just keep upping the weight whenever you can, and every once in a while (to maintain that "Muscle confusion" - and this applies to the chest workouts too), start at the bottom of your worksheet and work you way up. This will help you avoid or break through a plateau. For example, the last exercise in the Back & Biceps workout is the strip set curl, which for 90 days was always last on the list and my muscles were always pretty cooked by the time I got there. By doing the workout in reverse, this is the first exercise and your muscles are fresh, you'll be able to start with at least 5 lbs more than normal and all of the exercises on the bottom half of your workout sheet will show improvement. (After 6 months of following the worksheets in order I was struggling to improve since my body was used to the movements by now. After doing it in reverse, my body ached the next day in a way it hadn't for quite some time and 2 weeks later when I came to do it again in the right order, I was finally able to up the weights on almost all the exercises. Just be sure to mark on the sheet that you did it backwards that week.

I have been using these new worksheets for 6 weeks now, and I have gained another 3 lbs of muscle, most of it on my chest.


Categories: P90X | Fitness
Posted by Williarob on Thursday, February 25, 2010 6:44 AM
Permalink | Comments (0) | Post RSSRSS comment feed

How to update multiple tables using T-SQL

Lets say you have a database made up of many tables. All of those tables have a field called "DateCreated" which cannot be null, but at the time the tables were created, you didn't think to set a default value for the field. Now you could open each table in design mode and set the default value manually, but here is an easier way:

The syntax to set a default value looks like this:

ALTER TABLE [table-name]
ADD CONSTRAINT constraint-name DEFAULT default-value FOR column-NAME;

While quicker that opening each table in design view this still only allows you to set the default value for a single table at a time. However, we can write some simple SQL that will generate a complete SQL Script for us:

SELECT 'ALTER TABLE [' + sysobjects.NAME +
'] ADD CONSTRAINT DF_' + sysobjects.NAME + '_DateCreated DEFAULT getdate()
FOR DateCreated;' from sysobjects inner join syscolumns on
sysobjects.id = syscolumns.id
inner join systypes on
syscolumns.xtype = systypes.xtype
WHERE syscolumns.NAME = 'DateCreated'

Run that query and each row returned will contain an Alter Table statement for each table. Simply highlight all the rows returned, then copy and paste them to a new query and run it. The SysObjects table contains one row for each object (table, column, constraint, default, log, rule, stored procedure, and so on) created within a database. This means you could write a query to update the sysobjects table directly and make this even easier, but if you mess up the sysobjects table your database could be trashed so use caution if you go that route.


Categories: SQL Server
Posted by Williarob on Friday, February 19, 2010 1:35 PM
Permalink | Comments (0) | Post RSSRSS comment feed