Imagine. Create. Deploy. - 1105 Mediapdf.1105media.com/VSMMag/2013/Jan.pdf · Download your 30-day...

37
Download your 30-day trial at www.DevExpress.com Imagine. Create. Deploy. Inspired? So Are We. Inspiration is all around us. From beautiful screens on the web to well-designed reports. New devices push the development envelope and asks that we consider new technologies. The latest release, DevExpress 12.2, delivers the tools you need to build the multi-channel solutions you can imagine: Windows 8-inspired applications with live tiles perfect for Microsoft Surface, multi-screen iOS and Android apps. It’s all possible. Let’s see what develops.

Transcript of Imagine. Create. Deploy. - 1105 Mediapdf.1105media.com/VSMMag/2013/Jan.pdf · Download your 30-day...

Page 1: Imagine. Create. Deploy. - 1105 Mediapdf.1105media.com/VSMMag/2013/Jan.pdf · Download your 30-day trial at Imagine. Create. Deploy. Inspired? So Are We. Inspiration is all around

Download your 30-day trial at www.DevExpress.com

Imagine. Create. Deploy.Inspired? So Are We.Inspiration is all around us. From beautiful screens on the web to well-designed reports. New devices push the development envelope and asks that we consider new technologies. The latest release, DevExpress 12.2, delivers the tools you need to build the multi-channel solutions you can imagine: Windows 8-inspired applications with live tiles perfect for Microsoft Surface, multi-screen iOS and Android apps. It’s all possible. Let’s see what develops.

Untitled-1 1 12/7/12 10:27 AM

Page 2: Imagine. Create. Deploy. - 1105 Mediapdf.1105media.com/VSMMag/2013/Jan.pdf · Download your 30-day trial at Imagine. Create. Deploy. Inspired? So Are We. Inspiration is all around

Trending

UPPLUS

New T-SQL FunctionsIntegrating SharePoint

Web PartsOne App, Two

Windows Platforms

JAN

UARY

201

3

Volu

me

23, N

o. 1

VisualStudioMagazine.com

The Visual Studio Magazine second annual Salary Survey shows that developers continue to make gains.

Page 3: Imagine. Create. Deploy. - 1105 Mediapdf.1105media.com/VSMMag/2013/Jan.pdf · Download your 30-day trial at Imagine. Create. Deploy. Inspired? So Are We. Inspiration is all around

Untitled-1 1 10/30/12 3:37 PM

Page 4: Imagine. Create. Deploy. - 1105 Mediapdf.1105media.com/VSMMag/2013/Jan.pdf · Download your 30-day trial at Imagine. Create. Deploy. Inspired? So Are We. Inspiration is all around

VisualStudioMagazine.com · January 2013 · VISUAL STUDIO MAGAZINE 1

6

January 2013 // Volume 23 // No. 1

Keith Ward, Editor in Chief, Visual Studio Magazine

{ F R A M E W O R K S }

Building on 20122012 is behind us, and it was a monumental year in terms of Microsoft product releases. That likely means 2013 will be a bit of a breather year for Redmond, at least in terms of creating new products.

It hardly means Microsoft can rest, however. Here are the major things I’d recommend the company do, both with some of its new offerings and internally:■ First and foremost, get the people

reading this column to write apps for Windows 8 and Windows Phone 8. Nothing is more important than creating a thriving app ecosystem for Windows 8/Windows RT/Windows Phone 8. The mobile revolution is built on the foundation of apps, and more is better. Both iOS and Android are approaching a million apps for their smartphones and tablets. Obviously, Microsoft won’t match those fi gures anytime soon, but the stated goal from one executive of 100,000 apps in the Windows Store by the end of January would be a fabulous start.

■ Convince the public and enterprise that laptops and desktops aren’t even close to dead. Tablets and smartphones have all the momentum right now and, because of that, the majority of press coverage. But there’s still a lot you can’t do with them. Microsoft needs to stay strong in this crucial space, and not just accept Steve Jobs’ oft-repeated mantra that we’re in the post-PC era. There’s room for everyone at this party.

■ Retain employees. This is overlooked, but crucial. Too many big-time executives have left (headed by Steven Sinofsky), creating a leadership vacuum. Microsoft needs to recruit or promote great replacements, and do everything it can to keep them around to provide consistent, innovative vision.

COVE

R IL

LUST

RATI

ON

BY

SHU

TTER

STO

CK.C

OM

/VSM

STA

FF

FEATURES6 Salaries on the Rise for Visual Studio Developers

Our second annual salary survey indicates that experience pays off for Microsoft software professionals.BY KATHLEEN RICHARDS

LANGUAGE LAB20 PRACTICAL .NET Integrating Web Parts: Providers, Filters and More

Creating connectable Web Parts is a good thing for you and your users—and the default interfaces that come with SharePoint form the architecture you should use to create those Web Parts. BY PETER VOGEL

26 MOBILE CORNER One App, Two Platforms

Although Windows 8 and Windows Phone share the same core, building an app for both isn’t as easy as you might think.BY NICK RANDOLPH

30 ON VB 4 New T-SQL Functions

The latest version of SQL Server expands its capabilities. Here are four new things developers can do with it. BY SAM NASR

DEPARTMENTS2 Letters to the Editor

4 DevInsights VSTOOLBOX

VSToolbox: Generating Documents with DynamicPDF for .NET PAGE 4

COLUMNS1 Frameworks BY KEITH WARD

32 Redmond Review B Y ANDREW J. BRUST

Page 5: Imagine. Create. Deploy. - 1105 Mediapdf.1105media.com/VSMMag/2013/Jan.pdf · Download your 30-day trial at Imagine. Create. Deploy. Inspired? So Are We. Inspiration is all around

2 VISUAL STUDIO MAGAZINE · January 2013 · VisualStudioMagazine.com

Keep Those Errors ComingWe rounded up readers’ development misadventures for the December 2012 cover story, “Dev Disasters—Why They Happen, How to Overcome Them” (VisualStudioMagazine.com/ Disasters1212). No surprise, when projects go horribly wrong, it’s entertaining—as long as it’s not happening to you!

Great stuff! IMO, you can leave out the code snips—the last thing I want to do is search the author’s code for bugs when I have my own to debug. Just articulate the problem, those stories are way more entertaining ...

Name Withheld , Posted Online

Please keep the Dev Disasters column going!! I love reading these stories! Excellent stuff!!!

Name Withheld, Posted Online

Try This ExtensionVSM Tools Editor Peter Vogel hates making changes to working code. He shared another method in his Dec. 3, 2012, .NET Tips and Tricks blog, “Extend Classes Without Changing Code” (VisualStudioMagazine.com/Vogel120312).

Thanks! I never knew this existed. It seems like it would best be used where source code isn’t available (purchased DLL, for example). If source is available, I would add the method to the base class. If you don’t want to risk an expansion of changes to the original source, you can use a separate source fi le and make it a partial class.

Name Withheld, Posted Online

Visual Studio Magazine wants to hear from you! Send us your thoughts about recent stories, technology updates or whatever’s on your mind. E-mail us at [email protected] and be sure to include your first and last name, city and state. Please note that letters may be edited for form, fit and style. They express the views of the individual authors, and do not necessarily reflect the views of the VSM editors or 1105 Media Inc.

Letters For 2013, we’ll be in Orlando, Fla., Las Vegas, Chicago and at Microsoft HQ.

Go to VSLive.com for details.

VisualStudioMagazine.comJanuary 2013 • Volume 23 • No. 1

Editorial StaffEditor in Chief Keith Ward

Executive Editor Kathleen RichardsGroup Managing Editor Wendy Hernandez

Associate Managing Editor Katrina Carrasco

Tools Editor Peter Vogel

Contributing EditorsAndrew J. Brust, Ian Davis, Mickey Gousset,

Joe Kunk, Mark Michaelis, John Papa, Nick Randolph, Patrick Steele, Eric Vogel

Art StaffCreative Director Scott Shultz

Art Director Joshua GouldProduction Staff

Director, Print Production Jenny Hernandez-AsandasProduction Coordinator Serena Barnes

Online/Digital MediaSr. Director, Online Media Becky Nagel

Executive Editor, New Media Michael DomingoSite Administrator Shane Lee

Designer Rodrigo Muñoz

Advertising/SalesVP/Group Publisher Matt Morollo

Regional Sales Manager Chris KourtoglouNational Accounts Director William Smith

National Account Manager/ Danna VedderMicrosoft Account Manager

President Henry AllainVP, New Content Initiatives Doug Barney

Sr. Director of Marketing Michele Imgrund& Audience Engagement

Director of Online Marketing Tracy Cook

President & Neal Vitale Chief Executive Offi cer

Senior Vice President Richard Vitale & Chief Financial Offi cer

Executive Vice President Michael J. Valenti

Vice President, Christopher M. Coates Finance & Administration Vice President, Erik A. Lindgren

Information Technology & Application Development Vice President, David F. Myers

Event Operations

Chairman of the Board Jeffrey S. Klein

REACHING THE STAFFStaff may be reached via e-mail, telephone, fax, or mail. A list of editors and contact information is also available online at VisualStudioMagazine.com. E-mail: To e-mail any member of the staff, please use the following form: [email protected] Offi ce (weekdays, 9:00 a.m. - 5:00 p.m. PT)Telephone 949-265-1520; Fax 949-265-15284 Venture, Suite 150, Irvine, CA 92618Framingham Offi ce (weekdays, 9:00 a.m. - 5:00 p.m. ET)Telephone 508-875-6644; Fax 508-875-6633600 Worcester Road, Suite 204, Framingham, MA 01702Corporate Offi ce (weekdays, 8:30 a.m. - 5:30 p.m. PT)Telephone 818-814-5200; Fax 818-734-15229201 Oakdale Avenue, Suite 101, Chatsworth, CA 91311

Visual Studio MagazineThe opinions expressed within the articles and other contents herein do not necessarily express those of the publisher.

ID Statement Visual Studio Magazine (ISSN 1537-002X) is published monthly by 1105 Media, Inc., 9201 Oakdale Avenue, Ste. 101, Chatsworth, CA 91311. Periodicals postage paid at Chatsworth, CA 91311-9998, and at additional mailing offi ces. Complimentary subscriptions are sent to qualifying subscribers. Annual subscription rates payable in U.S. funds for non-qualifi ed subscribers are: U.S. $35.00, International $60.00. Annual digital subscription rates pay-able in U.S. funds for non-qualifi ed subscribers are: U.S. $25.00, International $25.00. Subscription inquiries, back issue requests, and address changes: Mail to: Visual Studio Magazine, P.O. Box 2166, Skokie, IL 60076-7866, email [email protected] or call toll free (888) 768-8759, fax number 847-763-9564. International calls 847-763-9135. POSTMASTER: Send address changes to Visual Studio Magazine, P.O. Box 2166, Skokie, IL 60076-7866. Canada Publica-tions Mail Agreement No: 40612608. Return Undeliverable Canadian Addresses to Circulation Dept. or XPO Returns: P.O. Box 201, Richmond Hill, ON L4B 4R5, Canada.

Copyright Statement © Copyright 2013 by 1105 Media, Inc. All rights reserved. Printed in the U.S.A. Reproductions in whole or part prohibited except by written permission. Mail requests to “Permissions Editor,” c/o Visual Studio Magazine, 230 California St. Suite 302, San Francisco, CA 94111.

Legal Disclaimer The information in this magazine has not undergone any formal testing by 1105 Media, Inc. and is distributed without any warranty expressed or implied. Implementation or use of any information contained herein is the reader’s sole responsibility. While the information has been reviewed for accuracy, there is no guarantee that the same or similar results may be achieved in all environments. Technical inaccuracies may result from printing errors and/or new developments in the industry.

Corporate Address 1105 Media, 9201 Oakdale Ave. Ste 101, Chatsworth, CA 91311 www.1105media.com

Media Kits Direct your Media Kit requests to Matt Morollo, VP Publishing, 508-532-1418 (phone), 508-875-6622 (fax), [email protected]

Reprints For single article reprints (in minimum quantities of 250-500), e-prints, plaques and posters contact:PARS International Phone: 212-221-9595 E-mail: [email protected] www.magreprints.com/QuickQuote.asp

List Rental This publication’s subscriber list, as well as other lists from 1105 Media, Inc., is available for rental. For more information, please contact our list manager, Merit Direct. Phone: 914-368-1000; E-mail: [email protected]; Web: www.meritdirect.com.

Page 6: Imagine. Create. Deploy. - 1105 Mediapdf.1105media.com/VSMMag/2013/Jan.pdf · Download your 30-day trial at Imagine. Create. Deploy. Inspired? So Are We. Inspiration is all around

Untitled-2 1 12/5/12 11:20 AM

Page 7: Imagine. Create. Deploy. - 1105 Mediapdf.1105media.com/VSMMag/2013/Jan.pdf · Download your 30-day trial at Imagine. Create. Deploy. Inspired? So Are We. Inspiration is all around

4 VISUAL STUDIO MAGAZINE · January 2013 · VisualStudioMagazine.com

VSToolbox

BY PETER VOGELceTe Software DynamicPDF Core Suite for .NET consists of two libraries for you to use at runtime: Generator for dynamically creating PDF documents, and Merger for merging, splitting and filling PDF documents. The ReportWriter and Designer generate PDF reports.

The classes that make up the DynamicPDF Generator for .NET allow you to generate documents up to 2GB in size from code (C# and Visual Basic) in both desktop and Web-based applications. The following code is all that’s necessary to create a one-page PDF document with a single TextBox, and then write it to a file:

Dim doc As Document = New Document()

Dim pag As New Page

Dim txta As New TextArea(

"Hello World!", 10, 20, 50, 15, Font.TimesRoman, 12)

pag.Elements.Add(txta)

doc.Pages.Add(pag)

Dim fs As New FileStream("C:\NewFile.pdf",

FileMode.Create)

fs.Write(doc.Draw(), 0, doc.Draw().Count)

fs.Close()

Printing APIIn an ASP.NET application, the Document object’s DrawToWeb method lets you output the document to the current WebForm. The DrawToBitmap method lets you generate output that could be displayed in an Image control. ceTe PrintManager gives you a server-side API for sending documents directly to printers. Unfortunately, it’s not included in the suite.

Generator supports templates, which allow you to specify repeatable content for headers and footers in documents with multiple pages. However, using Generator to create highly formatted documents from scratch—which could be very code-intensive—doesn’t reflect the typical

business case of creating new editions of standard documents.

DynamicPDF Merger for .NET is the real jewel in the crown because it allows you, from code, to take an existing PDF document and either append or modify it. With Merger, you can create PDF documents in a page-formatting tool, and then use them as templates for creating new editions of those documents.

PDF ReportsWhile there’s nothing wrong with the included ReportWriter, it doesn’t yet have all the features of the dominant reporting tools in this area. The main benefit of the DynamicPDF ReportWriter is that output is directly translated into a PDF file.

The Enterprise edition of the DynamicPDF Core Suite for .NET offers additional chart types plus support for bar codes, prepress, archiving and encryption, among other features. Pricing is on both a per-user and per-server basis. You can buy the individual suite components separately but, if you’re going to purchase any two of the packages,

you might as well buy the Core Suite. The Professional and Enterprise versions of the suite provide a Help library that integrates with Visual Studio and several sample applications (though “Getting Started” tutorials appear to be included only for Generator).

ceTe Software DynamicPDF Core Suite for .NET provides many of the tools that a shop generating PDF documents would need, with only one significant hole: the suite doesn’t address printing documents. And while there’s nothing wrong with the suite, many shops might find DynamicPDF Merger for .NET, by itself, more useful. VSM

Peter Vogel is the Visual Studio Magazine tools editor and a principal at PH&V Information Services, specializing in ASP.NET development.

Dy

nam

icP

DF

fo

r .N

ET

</DevInsight>

ceTe Software DynamicPDF Designer, which is included in the Core Suite, enables you to create report formats to use with the DynamicPDF ReportWriter.

DynamicPDF Core Suite for .NET

ceTe SoftwareWeb: dynamicpdf.comPhone: 800-631-5006Price: $899 for DynamicPDF Core Suite Professional server license; $1,599 developer licenseQuick Facts: A suite of tools for working with PDF documents, including a report writerPros: Excellent set of APIs for creating PDF documents, giving you three tools for the price of twoCons: For many shops, one of the components—Merger—will stand above the rest

Generating Documents with DynamicPDF for .NETA useful set of tools for creating PDF documents dynamically from code.

Page 8: Imagine. Create. Deploy. - 1105 Mediapdf.1105media.com/VSMMag/2013/Jan.pdf · Download your 30-day trial at Imagine. Create. Deploy. Inspired? So Are We. Inspiration is all around

Untitled-1 1 5/10/12 12:20 PM

Page 9: Imagine. Create. Deploy. - 1105 Mediapdf.1105media.com/VSMMag/2013/Jan.pdf · Download your 30-day trial at Imagine. Create. Deploy. Inspired? So Are We. Inspiration is all around

6 VISUAL STUDIO MAGAZINE · January 2013 · VisualStudioMagazine.com

VSM COVER STORY

When we conducted our first Salary Survey in November 2011, the results were encouraging. Our data indicated that software development in Visual Studio offered great pay, reasonable perks and fairly high career satisfaction despite an uncer-tain economy that showed only muted signs of recovery. This year’s survey, which took place in mid-November, showed similar results.

The economy hasn’t improved, and momentous changes are roiling the technology industry as consumers embrace tablets and mobile devices. The release of Windows 8 in late October didn’t have an immediate positive impact, and available hardware from fewer manufacturers than first announced threatened the holiday selling season. Still, in the wake of momentous changes facing Redmond, .NET software development remains one of the best careers in 2013, according to our polling and other surveys.

We polled software development professionals who subscribe to Visual Studio Magazine and related eNewsletters. More than 1,000 U.S.-based developers participated in the survey and filled out the online questionnaire.

Similar to last year’s findings, almost three-quarters (73 percent) of VSM Salary Survey respondents are college graduates with a four-year degree or higher level of education. The majority of respondents are software veterans; 70 percent have worked in application development or programming for at least a decade, with 49.3 percent logging 15 years or more. More than 96 percent of respondents are at least 30 years old.

Survey respondents also report lengthy careers working with Microsoft technologies, although many are involved in cross-platform development, according to our findings. Indeed, 78.5 percent of those surveyed have held a job that involves working with Microsoft products and technologies for a decade or more. On average, survey respondents have worked for 12.5 years with the Microsoft technology stack. Only 10.6 percent have developed software using Microsoft products and technologies for five years or less. IL

LUST

RATI

ON

BY

RYAN

ETT

ER

Our second annual salary survey indicates that experience pays off for Microsoft software professionals. BY KATHLEEN RICHARDS

SALARIES on the RISE for VISUAL STUDIO DEVELOPERS

Page 10: Imagine. Create. Deploy. - 1105 Mediapdf.1105media.com/VSMMag/2013/Jan.pdf · Download your 30-day trial at Imagine. Create. Deploy. Inspired? So Are We. Inspiration is all around

VisualStudioMagazine.com · January 2013 · VISUAL STUDIO MAGAZINE 7

VSM COVER STORY

What’s Changed in a YearThe average base salary in the November 2012 survey is $94,381, not including bonuses and additional compensation. That’s a bit higher than the average salary ($92,754) reported in November 2011. Male respondents, who account for 86.6 percent of those surveyed in 2012, report a higher base salary on average—$96,079—than females ($85,035).

Half of the reported salaries in 2012 fall below $90,000, down from the $92,000 median salary derived from our November 2011 survey results. The median salary for respondents working with Microsoft products and technologies that have five years or less of experience is $76,000. Software development professionals with 10 or more years under their belts earn a median salary of $92,700. The national median for software developers in the United States in December, according to self-reported data from glassdoor.com, was $75,000.

About one-third (33.8 percent) of VSM survey respondents say their annual base salaries, not including bonuses, fall into the six-figure range ($100,000 or more). Almost 7 percent (6.9 percent) report base salaries of $150,000 or more. On the other end of the scale, 10.3 percent indicate annual base salaries of $54,999 or less.

The biggest takeaway in our first annual salary survey was that 59 percent of respondents reported higher salaries in the last 12 months. For 2012, that number remains fairly steady at 60.3 percent. This could be interpreted as good news that higher wages have continued for the majority of survey respondents despite uncertainty in the economic climate and a looming fiscal cliff (at the time of the survey) that may have caused some companies to reduce capital spending. The rise in pay is expected to continue—62.8 percent of those sur-veyed predict their base salaries will increase in the next 12 months.

The news wasn’t all good, however. Almost 30 percent (29.7 percent) of those surveyed saw no change in their average base salaries in 2012, and roughly 10 percent (9.7 percent) indicated a salary decrease compared to the previous year.

As our November 2011 survey clearly showed—the results of which were published in January 2012—the type of organization that developers work for influences average base salaries. Those findings were verified in the most-recent poll. Survey respondents who work for an independent software vendor (11.2 percent) report the highest average salary, at $103,553. Those who work for consulting firms, training companies and systems integrators (17.5 percent) also fall into the six-figure range on average, with a comparable $103,216, not including bonuses and additional com-pensation. The majority of survey respondents, however, work for corporate IT/IS (43.3 percent), with an average base salary of $93,422. Those employed by state and federal government, the education sector and nonprofits (17.9 percent) earn less, reporting $78,685 on average.

In addition to the type of organization, compensation ranges are affected by industry, location, and company size and annual revenue. About one-quarter of VSM survey respondents work in organizations with $10 million or less in annual revenues. Another 21 percent are employed by billion-dollar companies with annual revenues of $1 billion or more. The rest fall somewhere in between (see the chart,

“Where You Work Based on Business Income,” p. 8). The average salaries presented here more accurately reflect urban

pay scales; some 22.5 percent of survey respondents work in cities (200,000 to 500,000 residents), and 41.7 percent are based in major metropolitan areas (more than 500,000 residents).

Our survey data also indicates a direct correlation between hours worked and higher base salaries. The 29 percent of survey

respondents who estimate that they work 30 to 40 hours per week have an average base salary of $87,600. Another 29 percent, who say they work 41 to 45 hours per week, have an average base salary of $90,212. The 40 percent of respondents who work 46 hours or more per week move into the six-figure range. The top 4.8 percent, who clock 61 hours or more during an average workweek, have an average base salary of $111,238.

Moonlighting isn’t a huge source of income for the majority of our survey respondents; only 9.6 percent earn $10,000 or more outside their primary employment. Close to 70 percent (67.7) report no dollar compensation for work outside of their primary employ-ment. Of the rest, 6.4 percent earn up to $1,000; another 10 percent earn $1,000 to $4,999; and 6.3 percent fall in the range of $5,000 to $9,999.

Job titles don’t always offer an accurate description of what a role entails, but after our second annual survey, we’re seeing clear cor-relations between job titles and compensation. Like last year, a little more than one-quarter of those surveyed (25.7 percent) list their primary job function as programming, software engineering or appli-cation development. The programmer/analysts report an average base salary of $74,682, and software engineer/application developers earn more on average, with a base salary of $86,868. Salaries move into the six-figure range when senior status is achieved; the 15.6 percent of respondents who say their primary role is senior software engineer/senior developer have an average base salary of $102,030.

Another finding from our 2012 survey: senior software engineers and developers earn more on average than team leaders and IT managers. The 5.6 percent who describe their job as development manager/team lead earn $95,579 on average. The 12.8 percent of respondents who classify their primary function as IT management report an average base salary of $97,458.

The anomaly is the drop in salary for the 4.2 percent who catego-rize their role as database administrator/developer. The average base salary for database administrator/developer is $80,213 in 2012, compared to $91,276 in 2011.

VSM Salary Survey respondents who characterize their primary role as software architect (11.5 percent) earn on average $118,971. In our 2011 survey CIOs accounted for 2 percent of respondents (2.5), with a reported average salary of $109,117. In our 2012 survey, CIOs represent 2.1 percent of respondents, with an average base salary of $118,804. Job titles that had so few takers that we couldn’t analyze the salary data include UI/UX specialist, mobile developer and game developer.

More MoneyAs we noted last year, by and large it’s a good time to be a developer. Average base salaries for Visual Studio-focused developers in the $90,000 range—including increases for 60 percent of respondents—were encouraging.

Well more than half of our survey respondents (60.3 percent) received salary increases in the last 12 months. Almost one-quarter of those respondents (23.5 percent) report asking for more money. More than 10 percent (15.3 percent) were offered a salary hike as an incentive to remain with their employers. The majority of salary increases were less than $10,000, however. Only 10 percent (9.7 percent) received salary increases of $10,000 or more, with 3 percent (2.6 percent) reporting raises of $20,000 or more. And 20 percent (20.2 percent) received increases of $1,999 or less. Not surprisingly, 6.4 per-cent of respondents whose salary decreased over the last 12 months indicate that their base pay was cut as a result of budget reductions.

Page 11: Imagine. Create. Deploy. - 1105 Mediapdf.1105media.com/VSMMag/2013/Jan.pdf · Download your 30-day trial at Imagine. Create. Deploy. Inspired? So Are We. Inspiration is all around

8 VISUAL STUDIO MAGAZINE · January 2013 · VisualStudioMagazine.com

Salary SurveyCOVER STORY

.NET Development Still RulesLanguages Used for Development Projects in the Last 12 Months

C#

Visual Basic .NET

JavaScript

XML/XSLT

C/C++

PHP/Python/Perl

XAML

F#

Ruby

HTML/CSS

Java

Objective-C

Other

66.7%

45.6%

48.2%

35.4%

27.8%

18.6%

17.4%

1.5%

4.6%

56.2%

29.7%

7.6%

8.9%

Who Took the Survey?

Where You Work Based on Business IncomeOrganization’s Approximate Annual Revenue

Less than $1 million

$1 million to $5 million

$100 million to $499 million

$10 billion to $24.9 billion

$5 million to $10 million

$500 million to $999 million

$25 billion to $49.9 billion

$10 million to $49 million

$1 billion to $4.9 billion

$50 billion or more

Don’t know

$50 million to $99 million

$5 billion to $9.9 billion

Government/educational/religious/nonprofi t institution

11.6%

7.3%

7.4%

4.0%

6.5%

4.4%

1.9%

8.8%

7.7%

3.6%

6.5%

4.5%

10.6%

15.3%

$96,079Avg. Base Salary

$85,035Avg. Base Salary

86.6%13.4%

Average Salary, Male vs. Female

Is Your Salary Higher or Lower than Last Year?

60.6%

9.7%

29.7% No Change

Median Age: 46

Long-Term Employees: 42.9% reported 10 years or more with current employer

Male vs. Female: 8:1 Education: 73 percent have a 4-year degree or higher

Average Years in Microsoft Development: 12.5

Visual Studio Professionals: 44% use Visual Studio 2010 Professional/.NET Framework 4 as their primary development environment, 25.1% use Visual Studio 2008 Professional/.NET Framework 3.5

Teamwork: 23.1% use Visual Studio 2010 Ultimate/Team Foundation Server 2010. 8.8% use Visual Studio 2012 Ultimate/Team Foundation Server 2012

Job Security:

Only 4.3% have been laid off in the last 12 months.

Page 12: Imagine. Create. Deploy. - 1105 Mediapdf.1105media.com/VSMMag/2013/Jan.pdf · Download your 30-day trial at Imagine. Create. Deploy. Inspired? So Are We. Inspiration is all around

The next generation of inspiring tools. Today.

Copyright 1998-2012 Developer Express Inc. All rights reserved. All trademarks are property of their respective owners.

Download your 30-day trial atwww.DevExpress.com

Now you think - game on!! The new tools in 12.2 help you envision and create engaging applications for the Web that can be accessed by mobile users on the go. And, with our Windows 8 XAML and JS tools you will begin to create highly interactive applications that address your customer needs today and build next generation touch enabled solutions for tomorrow.

You used to think "Impossible"

Your Apps, Any Device

Untitled-1 1 12/6/12 11:10 AM

Page 13: Imagine. Create. Deploy. - 1105 Mediapdf.1105media.com/VSMMag/2013/Jan.pdf · Download your 30-day trial at Imagine. Create. Deploy. Inspired? So Are We. Inspiration is all around

10 VISUAL STUDIO MAGAZINE · January 2013 · VisualStudioMagazine.com

Salary SurveyCOVER STORY

In spite of the relatively high paychecks, many developers still believe that they lag behind their peers when it comes to salary. Almost half (49.3 percent) think they have lower gross earnings than others in the same field, and 34.9 percent believe wages are about the same.

About 15.9 percent of respondents feel they have higher sala-ries than their peers. Of those who indicate higher salaries, roughly 10 percent (9.6) believe the higher wages are likely linked to certification titles. The uncertainty—or pessimism—has increased slightly when comparing this data with the responses in our 2011 survey. In that poll, one-fifth of respondents (20.8 percent) percent believed that their salaries or gross earnings were higher compared to others in the same field; 45.6 percent thought they earned less; and 33.5 percent viewed their wages as comparable to their fellow developers.

Additional CompensationDevelopers’ monetary compensation packages often extend beyond base salaries. More than half of those surveyed (52.7 percent) received bonuses during the last 12 months, up from 48.8 percent in our 2011 findings. About 19 percent of the bonuses are estimated in the $1,000 to $4,999 range. Roughly 11 percent fall into the $5,000 to $9,999 range, and 13 percent of respondents earned bonuses of $10,000 or more.

How are those bonuses calculated? Roughly one-third of survey respondents indicate that their monetary bonuses are the result of a combination of factors, typically company profitability and per-sonal performance. However, 28.2 percent of the bonuses are based on company profitability only—up from 23.6 percent in 2011. And 14.3 percent are based strictly on personal performance. Other ways bonuses are calculated, according to respondents, include years of service, project overtime, one week’s salary, attendance, Christmas bonuses, company politics and even “whims.” Local, state and federal government employees rely on their respective committees and legislative bodies for bonuses and wage increases.

“Local government typically feels IT makes more than it should,” gripes one respondent.

While raises and bonuses remained steady year-over-year for the majority of developers, according to our findings, the benefits offered by primary employers show a downward trend. Retirement programs appear to have tightened up, with 65 percent of companies offering 401(k) programs in 2012 compared to 67.2 percent in 2011. Similarly, 15.8 percent of employers offer 401(k) benefits without company contribution, down from 17.5 percent in last year’s survey. College education reimbursement also appears to have dropped, with 33.2 percent reporting it as a benefit in 2012 compared to 36.2 percent the previous year. However, 13.1 percent of respondents report profit sharing in November 2012, compared with 10.7 percent the previous year. Stock options (8.7 percent) and stock purchase pro-grams (14.1 percent) also show an upward trend.

MethodologyWe invited subscribers to Visual Studio Magazine, as well as the .NET Insight and Redmond Developer eNewsletters, to participate in our second annual Salary Survey of Microsoft professional software developers. The online survey was opened to qualified participants on Nov. 16 and closed on Nov. 23, with participation from 1,031 readers. —K.R.

Best Technologies for Job Security/Retention

Visual Studio/.NET Framework

ASP.NET

HTML/JavaScript

Windows 8/WinRT

82.0%

51.6%

Other 6.0%

54.6%

20.6%

Windows Phone 11.7%

SQL Server (any version)

Windows XP

SharePoint (any version)

Microsoft Offi ce (any version)

Windows Azure/SQL Azure

Windows 7

65.3%

7.6%

30.8%

25.6%

14.7%

25.4%

Additional Compensation More than Half Still on Track for Bonuses

Last 12 monthsNext 12 months

None

$1,000 - $4,999

Up to $1,000

$5,000 - $9,999

47.2%45.4%

19.1%18.4%

9.3%10.1%

11.2%12.0%

$10,000 - $14,999

$20,000 or more

$15,000 - $19,999

4.8%6.5%

5.5%5.1%

2.8%2.6%

Hiring Outlook

Expect to Hire Developers in the Next 12 Months

38.7% 35.8% 25.5%

31.9% 53.0% 15.1%

Using More Contractors in 2012 in Place of Full-Time Hires

Page 14: Imagine. Create. Deploy. - 1105 Mediapdf.1105media.com/VSMMag/2013/Jan.pdf · Download your 30-day trial at Imagine. Create. Deploy. Inspired? So Are We. Inspiration is all around

Untitled-2 1 9/13/12 12:51 PM

Page 15: Imagine. Create. Deploy. - 1105 Mediapdf.1105media.com/VSMMag/2013/Jan.pdf · Download your 30-day trial at Imagine. Create. Deploy. Inspired? So Are We. Inspiration is all around

12 VISUAL STUDIO MAGAZINE · January 2013 · VisualStudioMagazine.com

Salary SurveyCOVER STORY

Most Increases Higher than ExpectedIncrease in Base Salary

In the last 12 months Expected in the next 12 months

Up to $999

8.0%7.4%

$2,000 to $2,999

14.7%13.7%

$1,000 to $1,999

12.2%14.7%

$3,000 to $3,999

9.0%13.7%

$4,000 to $4,999

4.2%6.0%

$5,000 to $9,999

7.1%12.0%

$10,000 to $14,999

5.2%3.4%

$15,000 to $19,999

1.9%0.9%

$25,000 to $29,999

1.0%0.2%

$20,000 to $24,999

0.9%0.5%

Expect no increase in salary

28.8%28.6%

$30,000 or more

1.5%1.2%

Expect a decrease in salary

5.4%1.6%

Salary by Role in Your OrganizationWhat Best Describes Your Role in Your Organization?

$ = Avg. Base Salary

11.2%$103,553

43.3%$93,422

17.5%$103,21617.9%

$78,685

Work for a solution provider (consulting

fi rms, training companies,

systems integrators)

Work for an

independent software

vendor

Work for corporate IT/IS

Work for government/education/nonprofi t

Self-employed

9.8%$102,642

Salary by LocationMajor Metropolitan Area

Atlanta

Boston

Minneapolis

New York

$99,865

$110,833

Houston $88,748

Indianapolis $93,131

Kansas City

Los Angeles

$86,594

$99,244

$86,106

Phoenix $93,453

San Diego $98,685

$100,244

San Francisco

Washington, D.C.

Seattle

$121,321

$95,717

$114,190

Denver

Chicago

Dallas/Ft. Worth

$104,910

$93,473

$99,839

Avg. Base Salary

Experience Pays

Base Salary (avg.)

2012

$92,754

2013

$94,381

Median Salary

2012

$92,000

2013

$90,000

Salary by EducationLevel of Education Completed

$87,322

$90,236

$103,951

$77,808

$101,754

$91,646

Graduated high school

Attended some college

Master’s degree

Graduated 2-year college

Doctoral degree

Graduated 4-year college

Post-grad study/no degree

1.4%

15.0%

28.0%

10.6%

3.0%

33.9%

8.1% $96,601

Avg. Base Salary

Page 16: Imagine. Create. Deploy. - 1105 Mediapdf.1105media.com/VSMMag/2013/Jan.pdf · Download your 30-day trial at Imagine. Create. Deploy. Inspired? So Are We. Inspiration is all around

SpreadsheetGear

Toll Free USA (888) 774-3273 | Phone (913) 390-4797 | [email protected]

SpreadsheetGear

SpreadsheetGear 2012Now Available

WPF and Silverlight controls,

to XPS, improved

2012 support and more.

Excel Reporting for ASP.NET, WinForms, WPF and Silverlight

Forms, WPF or Silverlight

Free30 Day

Trial

Performance Spreadsheet Components

Excel Compatible Windows Forms, WPF and Silverlight Controls

Forms, WPF and

Excel Dashboards, Calculations, Charting and More

charts, and models in Excel or the SpreadsheetGear

NEW!

www.SpreadsheetGear.com

Untitled-3 1 11/30/12 11:25 AM

Page 17: Imagine. Create. Deploy. - 1105 Mediapdf.1105media.com/VSMMag/2013/Jan.pdf · Download your 30-day trial at Imagine. Create. Deploy. Inspired? So Are We. Inspiration is all around

14 VISUAL STUDIO MAGAZINE · January 2013 · VisualStudioMagazine.com

Salary SurveyCOVER STORY

Salary by Microsoft Technology ExpertiseWhat Is Your Primary Area of Technology Expertise (Have Product Knowledge and Work with on a Regular Basis)?

$94,748

$97,290

$97,840

$83,541

$103,188

17.5%

19.8%

12.2%

7.3%

$90,68221.6%

$90,20614.3%

4.9%

n/a n/a

ASP.NET

.NET Framework

SQL Server

Offi ce

SharePoint

Silverlight

Visual Studio

Windows

Avg. Base Salary

Time vs. Money: Salary by Hours WorkedAverage Hours Worked per Week for Employer

Less than 20 $48,800

20-29 $63,500

30-39 $87, 698

40 $87,865

41-45

1.0%

0.8%

46-50 $100,50523.3%

3.0%

51-55 $105,2897.4%

56-60 $100,1565.1%

61 or more $111,2384.8%

25.8%

29.0% $90,212

Base SalaryResponse %

Benefits Trend Downward in 2013?Additional Compensation Plans and Benefits Your Company Offers

401(k) 65.7%401(k) without company contribution 15.8%

Bonuses 42.7%Car allowance 4.6%

College education reimbursement 33.2%Expense account 11.4%

High-speed home Internet connection 9.8%Paid life insurance 47.9%

Paid medical/dental 50.5%Paid technical conference attendance 23.7%

Paid certifi cation exams 18.8%Paid training 37.9%

Practice equipment (computers, switches, etc.) 15.7%Profi t-sharing 13.1%

Sabbatical (one month or longer) 3.2%Software for personal use 16.7%

Stock option program 8.7%Stock purchase program 14.1%

Not applicable 8.0%

Salary by Job TitleWhat’s Your Primary Job Function?

$118,971

$96,801

$63,797

$74,682

$80,213

$72,800

$87,681

$95,579

$97,458

$100,864

$116,286

$109,117

$82,594

$86,848

Software Architect

Software Designer

Web Services Architect/Developer

Programmer/Analyst

Database Administrator/Developer

Test/Quality Assurance

Technical Lead (Non-Supervisory)

Development Manager (Team Lead)

IT Management

Product Manager, Software

Research and Development

Chief Information Offi cer

Trainer

Software Engineer/Application Developer

Senior Software Engineer/Senior Developer

11.5%

2.9%

1.8%

14.6%

4.2%

1.4%

4.5%

5.6%

12.8%

1.6%

1.2%

2.5%

1.4%

11.1%

15.6% $102,030

Avg. Base Salary

Expect to Be Working in Visual Studio/.NET in 5 YearsYES89%NO11%

Page 18: Imagine. Create. Deploy. - 1105 Mediapdf.1105media.com/VSMMag/2013/Jan.pdf · Download your 30-day trial at Imagine. Create. Deploy. Inspired? So Are We. Inspiration is all around

COVER STORYCOVER STORY

Medical and dental benefits remain largely unchanged. Half of the survey respondents (50.5 percent) receive medical and dental benefits, compared with 51.8 percent in 2011.

About 70 percent (69.6 percent) of survey respondents indicate they’re eligible for three weeks or more of paid vacation in 2012 and close to that number (65.9 percent) plan to use 75 percent or more of their paid vacation.

Hiring TrendsThe majority of VSM Salary Survey respondents have been devel-oping with Microsoft products and technologies for more than 10 years. And a large percentage have remained with the same employer: 42.9 percent indicate primary employment with their current orga-nizations for a decade or more, and 23.8 percent of that group have been working for the same organization for more than 15 years.

About 16 percent (15.7 percent) of those surveyed expect to change employers in the next 12 months. If you’re planning to switch jobs, the 2012 survey indicates some positive trends. Almost 40 percent (38.7 percent) of survey respondents indicate that their primary employers expect to hire developers in the next 12 months. About 60 percent (58.4 percent) of survey respondents have some role in managing their organization’s IT budget. Of that group, 26.3 percent are influential decision makers, and 11.6 percent make the final decisions. IT budgets also remained steady. According to survey respondents, 43.5 percent of IT budgets remained the same year-over-year, 29.3 percent increased and 27.2 percent faced cuts.

At the same time, 31.9 percent of respondents indicate that their primary employers are using more contractors in place of full-time hires. Most people aren’t worried, however; 86.5 percent expect outsourcing and contractors to have no impact on their jobs in 2013. Indeed, job security doesn’t appear to be an issue for the majority of respondents. Only 4.3 percent have been laid off in the last 12 months, although 7.7 percent anticipate losing their jobs to outsourcing or contractors in the next year.

Five-Year OutlookAlmost 90 percent of respondents indicate that they anticipate working in Visual Studio and .NET development in five years. Last year’s survey produced similar results (89.7 percent). Career satis-faction with the Microsoft development profession remains high among those surveyed—26.1 percent say they wouldn’t do anything else, and 50.9 percent are generally satisfied with their careers. The other 20.3 percent of respondents are largely neutral about their career, but just 2.7 percent are unfulfilled or wish they were doing something else.

Concerns about the future of .NET development weren’t really raised by survey respondents this year. Compared to other industries, software development in Visual Studio offers opportunities for continued financial gain and career satisfaction. Optimism for the future remains bright: 62.8 percent of survey respondents expect their salaries to increase this year, and 34.2 percent expect them to stay the same. Just 3 percent think they’ll make less in 2013. VSM

Kathleen Richards is the executive editor of Visual Studio Magazine. Follow her on Twitter at Twitter.com/RichardsKath.

GO ONLINEGo to VisualStudioMagazine.com/SalarySurvey to see more Salary Survey results and charts.

Page 19: Imagine. Create. Deploy. - 1105 Mediapdf.1105media.com/VSMMag/2013/Jan.pdf · Download your 30-day trial at Imagine. Create. Deploy. Inspired? So Are We. Inspiration is all around

LET US HEAR YOU CODE

Intense Take-Home Training for Developers, Software Architects and Designers

YOURR BAACKKSTAGGE PAASS TTO TTHHE MICROOSOFFT PLLATFFORMM

PRODUCED BYSUPPORTED BY

magazine

Untitled-3 2 12/6/12 11:35 AM

Page 20: Imagine. Create. Deploy. - 1105 Mediapdf.1105media.com/VSMMag/2013/Jan.pdf · Download your 30-day trial at Imagine. Create. Deploy. Inspired? So Are We. Inspiration is all around

vslive.com/lasvegas

Everyone knows all the *really* cool stuff happens behind the scenes. Get an all-access look at the Microsoft Platform and practical, unbiased, developer training at Visual Studio Live! Las Vegas.

las vegas MARCH25-29, 2013

MGM Grand Hotel & Casino

Register before January 30 and save $400!Use Promo Code LVJAN

SUPER EARLY BIRD SPECIAL

TURN THE PAGE FOR MORE EVENT DETAILS

Topics will include:ASP.NETAzure / Cloud ComputingCross-Platform MobileData ManagementHTML5 / JavaScriptSharePoint / Of ce 365SQL ServerWindows 8 / WinRTWPF / SilverlightVisual Studio 2012 / .NET 4.5

Untitled-3 3 12/6/12 11:36 AM

Page 21: Imagine. Create. Deploy. - 1105 Mediapdf.1105media.com/VSMMag/2013/Jan.pdf · Download your 30-day trial at Imagine. Create. Deploy. Inspired? So Are We. Inspiration is all around

YOURR BAACKKSTAGGE PAASS TTO TTHHE MICROOSOFFT PLLATFFORMM

CODE WITH .NET ROCKSTARS AND LEARN HOW TO MAXIMIZE THE DEVELOPMENT CAPABILITIES OF VISUAL STUDIO AND .NET DURING 5 ACTION-PACKED DAYS OF PRE- AND POST-CONFERENCE WORKSHOPS, 70+ SESSIONS LED BY EXPERT INSTRUCTORS AND KEYNOTES BY INDUSTRY HEAVYWEIGHTS.

Bonus Las Vegas Content! Developer Deep Dives on sharepoint andSQL server – brought to you by:

ASP.NETSessions Include:

25 Tips and Tricks for the ASP. NET Developer

From 0 to Web Site in 60 Minutes with Web Matrix

Building Single Page Web Applications with HTML5, ASP. NET MVC4 and Web API

Azure / Cloud ComputingSessions Include:

Bringing Open Source to Windows Azure: A Match Made in Heaven

Elevating Windows Azure Deployments

Workshop: Services – Using WCF and ASP.NET Web API

Cross-Platform MobileSessions Include:

Sharing up to 80% of code building Mobile apps for iOS, Android, WP 8 and Windows 8

iOS Development Survival Guide for the .NET Guy

Building Multi-Platform Mobile Apps with Push Noti cations

Data Management Sessions Include:

Busy Developer's Guide to MongoDB

Busy Developer's Guide to Cassandra

LINQ performance and Scalability

HTML5 / JavaScriptSessions Include:

jQuery Fundamentals

Tips for building Multi-Touch Enabled Web Sites

Build Speedy Azure Applications with HTML 5 and Web Sockets Today

DEEP DIVE:SharePoint / Of ce 365Sessions Include:

Building Your First SharePoint 2013 Application Using Visual Studio 2012

Getting Started with Microsoft Of ce 365 SharePoint Online Development

Workshop: SharePoint 2013 Developer Boot Camp

DEEP DIVE: SQL Server Sessions Include:

SQL Server Data Tools

Big Data-BI Fusion: Microsoft HDInsight & MS BI

Workshop: SQL Server 2012

Visual Studio 2012 / .NET 4.5Sessions Include:

Mastering Visual Studio 2012

Design for Testability: Mocks, Stubs, Refactoring, and User Interfaces

Workshop: ALM with Visual Studio 2012 and Team Foundation Server 2012

TWindows 8 / WinRTSessions Include:

New XAML controls in Windows 8

Cross Win8/WP8 Apps

Workshop: Build a Windows 8 Application in a Day

WPF / SilverlightSessions Include:

Building Extensible XAML Client Apps

Migrating from WPF or Silverlight to WinR

TRACKS & SESSIONS

Untitled-3 4 12/6/12 11:37 AM

Page 22: Imagine. Create. Deploy. - 1105 Mediapdf.1105media.com/VSMMag/2013/Jan.pdf · Download your 30-day trial at Imagine. Create. Deploy. Inspired? So Are We. Inspiration is all around

CONNECT WITH VISUAL STUDIO LIVE!

twitter.com/vslive – @VSLive

facebook.com – Search “VSLive”

linkedin.com – Join the “VSLive” group!

las vegas MARCH25-29, 2013

Scan the QR code to register or for more event details.

Register at vslive.com/lasvegas

Use Promo Code LVJAN

“The Visual Studio Live! event is an electrifying moment for a software developer. It’s one of the few places where I can bond with other developers, share memorable moments, and just have an amazing time doing what we love — coding. The event has defi nitely surpassed my expectations.”Tim Moore, Software Engineer, Civil Air Patrol

“Well organized, lots of sessions to choose from and a wonderful location. Money well spent!”Rakesh R. Naidu, Software Developer, USAC

“The quality of presenters has been exceptional.”Matthew Hubbell, Developer, DieBold, Inc.

“Since leaving the industry in 2003 to join the ranks of academia it has been a strug-gle to maintain contact with the pulse of platform and tool evolution. VSLive is an ideal way to be totally immersed in an environment that provides a ‘rapid’ recharge of all the latest news & technologies from a user-centric viewpoint. I get more in one week at VSLive than I can get from a full three months of research over summer break.”Robert Logan, Assistant Professor, Kent State University

THE REVIEWS ARE IN! HERE’S WHAT SOME PAST ATTENDEES HAD TO SAY ABOUT VISUAL STUDIO LIVE! . . .

Untitled-3 5 12/6/12 11:38 AM

Page 23: Imagine. Create. Deploy. - 1105 Mediapdf.1105media.com/VSMMag/2013/Jan.pdf · Download your 30-day trial at Imagine. Create. Deploy. Inspired? So Are We. Inspiration is all around

20 VISUAL STUDIO MAGAZINE · January 2013 · VisualStudioMagazine.com

</Language Lab>YO U R CO D E S O U R C E

IN THIS SECTION: Practical .NET · 20 // Mobile Corner · 26 // On VB · 30 /////////////

Integrating Web Parts: Providers, Filters and MoreCreating connectable Web Parts is a good thing for you and your users—and the default interfaces that come with SharePoint form the architecture you should use to create those Web Parts.BY PETER VOGEL

In my last column (VisualStudioMagazine.com/Vogel1212), I covered how you can create your own consumer Web Parts to pull data from the Web Parts that come with SharePoint—the Web Parts that SharePoint generates for every List in your site, for instance. This column is going to extend that column by

looking at how to create a provider Web Part, starting with a filtering Web Part that, again, uses one of the default interfaces in SharePoint. A filtering Web Part allows users to enter selection criteria to filter the data displayed in a SharePoint-generated List Web Part.

Here’s my point: You should be going beyond creating consumer Web Parts that use the default interfaces, and be creating provider Web Parts that implement those interfaces. The default interfaces, which you should implement and use in your Web Parts, will create an architecture that will allow users to assemble complex applications from simple parts. Creating a provider Web Part to use with your consumer Web Part isn’t hard to do, provided you take advantage of the default SharePoint interfaces.

Creating a FilterFor instance: a user drags a List onto a Web Part page. Now the user wants to be able to filter that List down to some specific set by selecting an appropriate filtering Web Part. You just need the right interface in your Web Part. The first step, using Visual Studio 2010, is to add a Web Part to a SharePoint project. Once you’ve added the Web Part (which can be a Visual Web Part), have it implement the Microsoft.SharePoint.WebPartPages.ITransformable-FilterValues interface, like this (I’ve included some Imports directives to simplify some code coming up later):

Imports Microsoft.SharePoint.WebControls

Imports Microsoft.SharePoint.WebPartPages

Imports System.Collections.ObjectModel

Public Class FilterWebPart

Inherits WebPart

Implements ITransformableFilterValues

As with any other “connectable” Web Part, you need a connection method—this method tells SharePoint that your Web Part can be connected to other Web Parts. Unlike the Web Parts discussed

earlier, a filtering Web Part is a provider, so its connection method must return a reference to your Web Part. The connection method must be decorated with the correct attribute (ConnectionProvider), and the return type of the method must be a SharePoint interface that holds the methods and properties the two Web Parts will use to communicate. For a filtering Web Part, that interface is ITransformableFilterValues. Here’s an example:

<ConnectionProvider("Percentage")> _

Public Function MyFilterConnection() As ITransformableFilterValues

Return Me

End Function

The ITransformableFilterValues interface adds, among other members, three read-only properties to your Web Part: AllowAllValue, AllowEmptyValue and AllReadOnlyValues. For now, just have those properties return True so that you can concentrate on the two more-interesting properties in the interface: ParameterName and ParameterValues.

Your ParameterValues method must return a ReadOnlyCollection of values to be used to filter the List. To create that collection, first create a List of strings, add your filter value to the List, then instantiate the ReadOnlyCollection, passing the List. This example hardcodes a value into a List before using it to create a ReadOnlyCollection:

Public ReadOnly Property ParameterValues _

As System.Collections.ObjectModel.ReadOnlyCollection(Of String) _

Implements ITransformableFilterValues.ParameterValues

Get

Dim lst As New List(Of String)

lst.Add("ALFKI")

Dim roc As New ReadOnlyCollection(Of String)(lst)

Return roc

End Get

End Property

When the user connects your filter Web Part to a SharePoint List Web Part, the user will be presented with a dialog that includes a DropDownList of all of the columns in the List Web Part. The name that you return from the ParameterName property will be displayed in this dialog, but fundamentally, users can select any column they want to use with your filter. That doesn’t mean the ParameterName column is useless, but it does mean that you should use it to provide the user with helpful advice, as in this example:

Public ReadOnly Property ParameterName _

As String _

Implements ITransformableFilterValues.ParameterName

Get

Return "Filter on Customer Ids"

End Get

End Property

{ PRACTICAL .NET }

Sh

areP

oin

t W

eb P

arts

Page 24: Imagine. Create. Deploy. - 1105 Mediapdf.1105media.com/VSMMag/2013/Jan.pdf · Download your 30-day trial at Imagine. Create. Deploy. Inspired? So Are We. Inspiration is all around

ement1); areaSeries Add(seriesElement2); areaSeries Add(seriesElement3); // Add series to the plot area plotArea Series Add(areaSeries); //page Elements Add( new LayoutGrid() ); // Add the page elements to the page AddEAement1); areaSerieies.AAdd(se(s rriesElement2t2); a) reaSeries.AdA d(seriesElement3); // Add series to the plot area plotArea.Series.Add(areaSeries); //page.Elemenem ts.Add( ddd( new ne LaLayyoutGrid() ); // A/ dd the page elements to the page AddEA

s, 240, 0); AddEAN1AN 3SupSup5(pa5(p ge.Elemeentnts, 480, 0); AdddUPCVersionA(page.Elemene ts, 0, 135); AddUPCVersionASup2(page.Elements, 240, 135); AdddUPCddUPCd CVerssionAionAo Sup5((page.Elemennts, t 480, 135); AddEAN8(page.Elements, 0,

.Elements, 480, 2270);; AddddUUPCVersionE(papage.Elementts, 0, 405); AddUPCVersionESuE p2(page.Elements, 240, 405); AddUPCVersionESup5(pageage.Ele.Elelemmments, 4s, 48800, 4405); // AAdd the page toe t the document document.Pages.Add(pa

CaptionAndRectanga lee(elemeements, “EAN/JA/JAN 13 Bar Codde”, x, y, 204, 99); BarCode barCode = new Ean13(“123456789012”, x, y + 21); barCode.ode.X +=X +X +=X + ((2004 -4 - baarCoode.GettSymbolWidth()h ) / 2; elements.Add(barCode); } private vovo

dRectangle(elemente s,, “EANEAN/JAN 13 Bar Car Code, 2 digit supplement”, x, y, 204, 99); BarCode barCode = new Ean13Sup2(“12 234556789678 0121212”, 2”, x, yy + 2+ 211); 1); barCoode.XX += (204 - barCode.GetSymbolWidth()) / 2; elements.Add((barC

ts, float x, float yy) { A{ AddCaCaptionAndRectanangle(elements, “EAN/JAN 13 Bar Code, 5 5 digit supplement”, x, y, 204, 99); BaB rrCodee barrCode == new Ean13SupS 5(“12345678901212345”, x, y + 21); ba

s.Add(barCode); } } pprivate te vooid AddUPCVPCVersiers onA(Group elements, float x, float y) {Add{ CaptionAndRectangle(elements, “, UPC VersVersVersVersion ionoi A Baar Cr Coode”, x, y,y, 204, 99);; BarCoode barCode = new UpcVersionA(“12345678901”, xx, y +

s.Add(barCode); } } pprivate te vooid AddUPCVPCVersiers onASup2(Group elements, float x, floato y) { AddCaptionAndRectangle(elementm ““UPCC Version E Bar Code, 2 digit supplement”, x, y, 204, 94 9); BarCoode od

21) ; barCode.X ++= (2= ( 04 - barba Code.GeetSymbymbolWidth()) / 2; elements.Add(barCode); e } private void AddUPCVersionASSSSuup5(up5(u Group elements,n float x, flfloaflo t VV

digit supplement”,t” xx, y, 22004, 99); BarCodeCode bbarCode = new UUpcVep rsionASuAS p5(“12343 567890112345”, x, y + 21); bbarCarCode.Xde.X += (204 - barCode.GetSymboom lWidth()) / 22; eelele

t x, float y) { AddCapdCaptionnAndRAnd ectangle(eleelemments, “EAN/JANN 88 Bar Code”,de”, xx, y, 204, 0 99); BarCode barCode = nnew Eew Ean8(an8(n8n8 “1 2345670”, x, y + 21); OpenFileileDiala og fileDie aloogoglo =

g.Filter = “Adobeob PDPDF fileess (*.pdf)|*.pdf|Alll FileFiles (*.*)|*.*”; if (fileDieD alog.SShowDiialog() == DialogResult.OK) { { pdfVpdfVf ieweewer.OpOpr.OpOpen (fifileDialogalog.FilleName, “”); } SaveveFileDialog saveFaveFileileDDialoog = neneww Sav

Dialog.Filter == “AdoAdobe PPDF fiDF files (*.pdff)|*.pdpdf|A|All Files (*.*)|*.*”;”; iff (saveFFileDialolog.Showh Dialog() ==DialoalogResgResRee ult..OK)OK) OK) { pdfVfVView .SSaveAsve (sav(saveFieFileDia

printer = pdfViewViewer.Per rinterr; pprinter.PriintWiW thDialog(); } elsee { MesssageBox.SShoww(“Please opeopen a n a fifile to pto p rintrinrint”)”); }OpenFin le DDialoog fileDieD alogalog = new OpenFileDDialog(); fileDiaDialog.og Tittle = e e = e “Opepen File Dl

les (*.*)|*.*|Addobe Pe PDF files es (*.p*.pdf)|*.pdddf”; if i (fifileDialog.ShowwDialalog() === DialogResult.ult OK) { { DynaDynamicPDFVDFVDFVDFViewiewewerClass test e = neew DynammiccPDFViewerClass((); PPDFPrinter ter pprinp ter er r = te= ttet st.OpenFFileFo

= File.ReadAAllByteBytes(@”C:\M:\MyDyDoc.pdff””); //u// sing System.Runntimme.Inttent ropServicces;GCHaGCHandlendledd gch=GCH= CHaananddla e.Aloc(conteents, GCHandleTTypee.Pinnedd); ) IIntntPtrPtr cooncontentsIntPtr = g

tents.Lengthh, “”);“”); A AddCaCaptioonAndReReectanglan ee(pageElementts, “BBBookkmark k Pagee E Elemelemeent:”nt:”, x,, y);; pa pagaapageEeEleemeents.Add(newtesw t Bookmookmaark(“Bookmarked TextTextt”, x + 55, y , y, yy ++ 2+ 20+ , pap rentre OutlO ine)); p) a

215, 10, Fonnt.TTimemesRomanma , 1010)); } prprrriivate vooid AddCiirclercle(GGro(G up paageElemeennnts,nts floafloat x,x floafloat yt y)t y) { / { /////Add/Add/A ss a circlt to the pap ge Eleemenmentenents AddCapdCapCaCadCaptiont AndRdRectae

Add(new Cirrcle(x e(x ++ 112.5f5f, y ++ 50f, 1007.5f, 300f, RgbColoolor.RRRed, RgbbbColor.Bor.Bluee,lue 2, LineL eStyylylly e.DaDae shLaLs rge))); } pprivate void AdA d FormatteeddTexxtAreea(Groupp paageElements, flofl aat x, fl float yy)) { ) // A// AAdds dds a fofoa rmatted textte a

mic</i><b>PDFPDF</b>/b>&tm; GGenerator vvv666.0 6 for ..NETNET has has a forrmattted ttetext arrea pea paaage a “ + “ “ele“ele“eleeeemmmentm . ThThis prroviddes rich fororm m atting ssuppupport for texext that appap eears in the doocumment. You have “ + “+ “compcompletlete conco trolol ove ovevever 8 r paragraph

left indentattionn, rigrighht indenentation, aligliggnnment, allollowing orphaaan linnes, aand whwhite ite “ + “spa“spaacece ppce pprereservata ion; 6 foont propropeerties: e <fonont fat f ce=’=’Timemes’>s’>font facece, <//fontt><font ppoinntSize=’6’>font “ + “s+ “size, </font>ont><fonont cocoocoot lor=lor=’FF0000’00’>c

2 line prpropertieses: le leading, ag ndd leaddinngg type.ype. TText can also be rootateeed.</d.</< p>”;p> FFororo mattmattmm edeedTeedTeTeextArx ea fformaormattedTTextAreArea = nnew FormattedTextTex Areare (formattat edHHtmll, x + 5, yy + 20, 215, 60, FonttFammily.Helveelvetictica, 9, fffalalsse);se);se);sssse) // // Sets the i

ddCaptionAAndReRectanct gle(e(pagepageElemeenntsnts, “F, “Fororrmarmattedtte TextT Areeae Page ElElemenement:”,t:”,,, x, y); y); y)y AddCAdddCddCA aptionAnAndReectangnglele(pageElements, “Formatm tedTextAx rea OverOv flflow TText:”, x x + 2279, y); pageElementments.Add(foormarmattedTTTextAxttAAtArea)r ; // CrCrer ate

tArea overflowFoowFormatrm tedTdTextAArea == foormamatteddTdt extArea.GettOveerflowwwFormatmatteddTTexextAxx rea(rerea(re x + x 28284, y +y 200); pageElements.Add(overflowFormattedTextAArea)); } pprivate vooid AddImage(Group p pagpageElementsents, float t x, flo, at yy) { ) { // // A/ dd

ents, “Imagee PagePage Elementen :”, xx, y); IImmagemage imaaage =ge new Imaage(SServvever.Mr.MapPattatth(“.h(“.“ ./I./Im./ agesages/DPDDFLogL o..png”), x + 112.5f, y + 50f, 0.24f); // Image is ssizzed and centeredd inn the rectangle immage.age SetBoundunds(21s(215, 5, 65 0); 0) image.VAVAAlign

ge); } privatte void oid AAddLabela (Group pp ppageageElememments, float x, flfloat y) { /// A/ Adds as aa llabel tel t to tht e pappap gegeElemenementts AddCaptionAndRectangle(pageElemenm ts, “LabLa el & PPageNummbeeringLabel Page EElemments:”, x,x, y); y) striing g laabelTextxt = = “= ““Lab

aain page numbumberinering: %%CP%%CP%%% ofof %%%T%%TP%%% pages.”; LLabel le abbel = nnew LLLew Laabel(labbelTeelTeeelTexxt, x + 5, y5 ++ 12, 220, 80, Font.TimesRoman, 12, Texe tAlign.C.Centter); label.Annglee = 8; PageNumbeeringgLabel pagepageNumLNumLabelab = nnnewew Pw Page

, 12, TeextAlxtAligign.CentC er); paga eEleementntntss.Ad.Addd(paageNumLabel));); p paggeElemenments.Addddd(d(label)); } } privprpp ate voidoid A AddLine(Group pageElements, float x, floao t y) { /// Addds aa line to thethe pageElements AdddCCaptionAndRAndRRectanngleglen (pagpag( a eeElemments

+ 5,+ y ++ 20, x + 220, y + 8080, , 3, RRgbbColor.Gr.G eeen)); pageElemmementss.n Add(d(d new w Linee(x ++ 22 2200, yy ++ 20, x + 5,+ 5, y + 80, 3, RgbColor.Green)); } private void AdddLLink((Grouup pageEElemments, float x, floaat yy) { // Adds ads a link toto thethhe pagp eEleEleemen

ynynamicPDF.com.m ”; AAddCaddCaptioptionAAnddnAndRectanglan e((pageElementts, “LLink PaPagege Elemment:nt:”, xx, y);y); LLabel llabela = new Label(text, x + 5, y + 20, 215, 80, font, 12,2 RggbCoolor.Blue)e); laabel.Underline = true;rue Link link =k = newnew LLinnk(x k(x ++ 5,5, y y ++ 20,

on(o “httpp://www.dynnamicppddf.coomm””))); pageEeElemments..Add(Ad labbeel);l); ppagepagpageElementsnts.AAdd(link); k) } prp ivatee void AddPath(Group pageElements, float x, float y) { // AAdds a path to the pageElemeents ceeTe.DynamicamicicPPDPDF.PagegeElemlemlements.PatP h

20,0 RgbgbbColor.Blue, RgbCRgbCoolor.RRedd, 22, LineStyeS lee.Solidd, true); pathhh.Su.SubbPaths.A.Adddd(new Lw LineSineSubPaubPath(x + 215, y + 40)); path.SubPaths.Add(new CurveToSToSubPPathh(x + 1+ 08, y + 80, x + 160,, y ++ 800)); path.SubSubPSubPathssssh .AAAd.Add(new(ne CurveS

ectecctanglangle(pageElemeents, “P“Path Ph Paage ge Element:””, x, yy);) pageEEleEleEE meentss.AdAdd(pad(path));th } pprivaate ve vooid AAddRectangle(Group pageElements, float x, float y) ororderede ddList = ordeo redLedList.GetOverFlowLo List((xx + x 5, y + 2+ 22000); AddCddCCCA aptiapa oonAndRect

2222 55, 1110); page.Eleements.Ats.Add(odd(ordrdrderr edList); x == 0; 0; y +=y ++=y + 118881 ; // CCCreaate e aan unorrderede lisist UnUnordderedList unorderedList = new Unoro deredList(x + 5, y +y + 220, 4400, 900, Font.Ht.Helvetica, 10); uuunoorderredListst.Itte.I ms.Amms Am dd(“ddd(“FruiFruFFFrFruF tss”); unorder

eree ies(); pieSeries.DaataLababel = da; plotArea.Seeriesess.AAd.Add(pieSSSeriesss);es ppieSeries.Elemelementss.AddAdd(27,7, “Website A”); pieSeries.Elements.Add.Ad (19, “Website e B”)); pieSerrieses.Elementmen s.Add(21, “WWebssite CC”); pieSpieSSerieeririees.Elemeneemmee ts[0s[0].Color = a

sess.Elemments[2].Color = auttogradient3;”unoro derreder ddSubLList2 == unoorderedList.Items[ms 1].SubLubLissts.AAddUnorderedSubList(); unorderedSubLu ist2.Items.Add(“dd(“Pottato”); unu ordeeredSubList2.Itemmms.A.Add(d(“Beaansansea ”);;; UUUnorU dereree dSubSu List subU

dSuedd bList(); subUnoUnorderedSubList.Items.As.AAdd(““d Lime”); subUUnorddereedSubList.Itemtems.Ads.Add(“Od(“Orangrange”);e” Unorderd edSubList sus bUnorderd edSue bList2 = unnorddereedSubLisLi t.Items[ms 1].SubLists.s.AddUAAddUd norrdereddeddSubLSubLbList(st ); ssubUnbUnu oorderedSe ub

na”aa ); UUnorderederedSubList subUnordo erededSubLSu ist3st3 = uunnorderredSubLSubList2.Itet ms[00].Su.SubLisLists.As.AddUnd orderedSSubList(); subUnoU rderedSudSubList3.Items.AAdd((“Swweet Potao to”)); UUnorderedSredSubLubLiL st sst ubUUnordrdeeredSdSredSdSubList4 st4st = ununorderedSu

ubLSuSu ist444.Ite.Items.Am dd(“String Bean”n”); s; subUnbUnordeereedSubbList4..Itemms.Addd(“Lima BeanBean”); subUsubUnnorderedSubList4.Items.Add(“Kidney Bean”e ); x += 279; pagpage.EElemenntts.Addd(unorderedListst); u); ; nordno eredreddLisst = = uunordn ereddreddLisst..GetG Overv Flo

e.e.Elemeentsen , “Unordered List Page Ege Elemment On verflverflow:””, x, y,, 2255, 110); page.Elemementsents.AddAdd(un(unorderedList); } private void AddTextFt ield(Group pageEeElemlemennts, flfloaat x, flooatt y) { TextFFielddield txt = new Tew extFextFieldeld(“txtfnafnaaame”,meme”,me”, x +x + 20, 20, y + y +

tteaa dTeextArea(formattedHtml, x ++ 5, 5 y ++ 20, 202 215,15 60, FontFFamilyy.Heelvetica, 9, ffalse)se ; /// SetSets ths the ine dent property formattedTextArea.Style.Paragraph.IndeIn nnt = 1188; AddCaptCap ionAndRendRectanaa gle(eg pagepageep ElemElemE ents, “FFormamormattedttedtedtedTeTextArearea P

atteatat dTeextArea Overflow TeeText:”, x + 27 9, y9, y); p; pageEgeElements.AAdd(formformattedTextAArea); a) // CCreatea ee an overflow formatted text area for the overflow text FoFormmattedTtedTextAxt reaMMaxaxLeLengthngth = 9 = 9= 9; txtxtxtxxt1.B1.Bordeded rCorColor =r = RgbCololoColoor.Br.BBlaack; txttxt1.Ba1 Ba

MaMMM ximuum Lengthgth”; p; ageEEgeEElemeements.nts.Add(Add(txttxt1); TTextFex ieldd txt2 = neew TeextField(“txxtf2namename”, xx + 3+ 30, y + 30, 150, 40); txt2.DefaultValue = “This is a TexxtFtFieldd whiichh goees tototot the nexxt lit liline ine iif thff t e text et et xceexceeds wds wididth”; ”; ttxt2.xt2.xt2xt2 MMMultMu iLinLine = e =

RgRR bCooolor.AliceBlueBluee; txt2.T2. oolTip == “M“Multiline”; ppageEElemennts.AAdd(ttxt2); AddCapCaptiont AndRAndRecctangle(pageElements, “TextField Form Page Element:”, x, x, y, 50450444, 8585); }; } prri vate voioidd AddComCCC boFibo eld(Group pap pageElgeElemeemenene ttts, ts float x, fl

, , y + 4000, 150,, 20 20)20); c; cb.Boro derCd olor = RgbColorr.BBlack; cb.BaackggrounndColor = RgbCRgbColoro .AliAliceBceBlue; cb.Font = Font.Helvetica; cb.FontSize = 12; cb.Itemsem .AAdd(“(“It(( em 1m 1”); ; ccb.IItemste .Add(“It““Item 2em 2”); ”); cb.Icb.Itemsems.Add(“Item 3em 3”)); cb.IItems

aaabbble”b ].SSeSeSeleleclected = true; cb.Edb itable = true; cb.ToToololTip = “Editable Coe Combo Box””; pa; pageElgeE emements.Add(cb); ComboBox cb1 = new ComboBox(“cmb1namame”, x + 303,030 y +y + 4440 40, 150, 200); c); cb1.Bb1.Bb1 ordeorderColrColoor = Rgbg Coloor.Blr.Br Br B ack;ack cb1.Bac

.F..FFFontontSize = 12; cb1.Items.Add(“Item 1”); cb1.Items.AAdd(“Item 2em 2”); ccb1.Items.Add((“Itemem 3”); cb1.Items.Add(“Item 4”); cb1.Items.Add(“Non-Editable”);”); cb111.Items[“NNon-Eon-Editable”].Selecteccc ed =ed = tru true; ce; cb1 Eb1.EEditable e = fa= f lse;se cb1.ToolT

eerrter.Coonvert(“http://www.google.com”, “Output.pdf”));Convverteer.Coonvert(GetDocD PathPath(“Do(“D cumentA.rtf”), “Output.pdf”);System.Diagnostics.Process..s SStartt(“Ot(“ uutpuutpuutputt.pdf”);”); AsyncCoConvernverrtter t aConaConvertverter =e newe AsyncCncConnverter(); aC

vveerted); aConverter.ConversionError += new ConversiionErroorEvventHHandler(aConveerteer_ConversionError); aConverter.Convert(@”C:\temp\DocumentA.rtA f””””, f , f @”C:C \temte p\OuO tputtputA.pdA.pdf”);f”); aCo aCoa nverter.Convert(ert @”C:\teme p\Dop\D cumentB

\Doc\D ummentC.rtf”, @”C :\temp\OutputC.pdf”); aConverrter.Coonverrt(“hhttp://www.yahoo.coo.com”, @”C:\Temp\yahoo.pdf”); ConvC ersionOptions ops optiontions = nneewnew new ew Conversise onOpOptiontionoo s(72s(720, 70, 720, 72, 7 true); ceTe.DynaDynamicPm DF.CDF.Conveon rsiorsion Con.Co

outpou ut.pdf”, optionso ); ceTe.DynamicPDF.Conversion.CConveerter.ConvCon ert(“C:\\temp\\\Documocument2.docx”, “C:\\temp\\op\ utput.pdf”, optiptoptioptiop ons)ons); s; stringing sampleHple tml m = “<“<htmlhtml><bo><bob dydy><p>This is s a very simplee HTMLHTMLHTHT strstrs ing iningin inclincincincludinud ng a g a g TT

( g[] g )

{{

pp

gg g ( p p )

[ ]

[ ]

pp y y yyp

HighhSecuSec rity securiturity y new w HighhSecuurityy(“OOwnerPassword”, “U“ serPassword”)

yy ppy

ees y yy

p

( p p )

pag p ( p pp )

p ()

}

Untitled-1 1 9/8/11 11:56 AM

Page 25: Imagine. Create. Deploy. - 1105 Mediapdf.1105media.com/VSMMag/2013/Jan.pdf · Download your 30-day trial at Imagine. Create. Deploy. Inspired? So Are We. Inspiration is all around

22 VISUAL STUDIO MAGAZINE · January 2013 · VisualStudioMagazine.com

You can return multiple values in your filter Web Part GetValues method (in which case you should return True from the AllowMultipleValues property). However, I’ve never found a SharePoint-generated List Web Part that uses anything other than the first value in the collection. If you don’t want to filter the List—that is, if you want to show all the values—just return nothing or null from ParameterValues (and, no, the returning True or False from AllowAllValue or AllowEmptyValue doesn’t make any difference in the SharePoint-generated Lists, either). Of course, if you create your own Web Part to use with your filter Web Part, you can implement these options, as I’ll discuss later.

Creating an IWebPartTable ProviderIn last month’s column, I introduced consumer and provider Web Parts by creating both kinds of Web Parts using a custom interface that I defined. But later in that column, I suggested it was more useful to create consumer Web Parts using the default interfaces because it would enable users to integrate your consumer Web Parts with the SharePoint-generated Web Parts.

Once you start creating consumers with the default interfaces, it makes sense—when creating your own provider Web Parts—to implement those default interfaces (the more, the better) in your provider Web Parts. That way, users have the maximum flexibility in assembling your custom Web Parts. So what does a provider that supports filtering and implements multiple default interfaces look like?

The provider I’ll use as my example uses ADO.NET to extract Order data from the Northwind database and dump it into a typed DataTable, using a custom FillBy method on the DataSet holding the DataTable (see VisualStudioMagazine.com/Vogel100912 for more on DataSets). Using a DataTable simplifies some programming required to fully support the default interfaces, as you’ll see. I’ve created this provider as a Visual Web Part; to facilitate communication between the “code-only” component of my Web Part (where most of my code goes) and the User Control component (which will handle displaying data to the user), in the code-only part of the Web Part I manage the DataSet through a property:

Private _nwTB As New Northwind.OrdersDataTable

Public Property nwTB As Northwind.OrdersDataTable

Get

Return _nwTB

End Get

Set(value As Northwind.OrdersDataTable)

_nwTB = value

End Set

End Property

Initially, I’ll have this Web Part implement just the IWebPart-Table interface:

<ToolboxItemAttribute(false)> _

Public Class OrderProvider

Inherits WebPart

Implements IWebPartTable

The IWebPartTable interface requires two members: Schema (which returns a collection of PropertyDescriptors for the data supplied by my Web Part) and GetTableData (which accepts a reference to a callback method in the consumer Web Part). Using an ADO.NET DataTable makes it easy to return a collection of PropertyDescriptors for each column in the Schema property—just use the GetProperties method of the TypeDescriptor class, passing a reference to the table’s DefaultView to get the collection:

Public ReadOnly Property Schema _

As System.ComponentModel.PropertyDescriptorCollection _

Implements IWebPartRow.Schema

Get

Return TypeDescriptor.GetProperties(nwTB.DefaultView(0))

End Get

End Property

When the consumer calls the provider GetTableData method and passes a reference to one of its methods, I simply store the reference to use later:

Dim tcb As TableCallback

Public Sub GetTableData(callback As TableCallback) _

Implements IWebPartTable.GetTableData

tcb = callback

End Sub

Finally, I need a method decorated with the ConnectionProvider attribute to mark my Web Part as a provider that supports the IWebPartTable interface. In the attribute, I provide some text for the SharePoint UI to display (“All Data”), give the connection a unique name (“ConnectionPointIWebPartTable”) to allow me to have multiple connection methods in one Web Part, and specify that multiple Web Parts can connect to this point because … well, why not? That method looks like this:

<ConnectionProvider("All data", _

"ConnectionPointIWebPartTable", AllowsMultipleConnections:= True)> _

Public Function MyConsumerMethodForAllData() As IWebPartTable

Return Me

End Function

Supporting FilteringTo make filtering the orders from another Web Part possible, I first need to add a method decorated with the ConnectionConsumer attribute and, in that method, save the filtering parameter passed to the method by the filter Web Part in some field. That’s what this code does:

Dim fvi As WebPartPages.ITransformableFilterValues

<ConnectionConsumer("Customer ID", _

"FilteringConsumerCustomerID", AllowsMultipleConnections:=True)> _

Public Sub MyFilterConnection( _

tfv As WebPartPages.ITransformableFilterValues)

fvi = tfv

End Sub

Now it’s time to write the code in the provider to retrieve the data and put it in the DataTable. The following code first looks in the Session object for the DataSet and, if the DataSet isn’t there,

Sh

areP

oin

t W

eb P

arts

</Language Lab>

{ PRACTICAL .NET }

A filtering Web Part allows users to enter selection criteria to filter the data displayed in a SharePoint-generated List Web Part.

Page 26: Imagine. Create. Deploy. - 1105 Mediapdf.1105media.com/VSMMag/2013/Jan.pdf · Download your 30-day trial at Imagine. Create. Deploy. Inspired? So Are We. Inspiration is all around

WINDOWS FORMS | WPF | ASP.NET

WWW.TEXTCONTROL.COM

US +1 877 - 462 - 4772EU +49 421 - 4270671 - 0

Reuse MS Word documents or templates as your reporting templates.

Easy database connection with master-detail nested blocks.

Powerful, programmable template designer with full sources for Visual Studio®.

Integrate dynamic 2D and 3D charting to your reports.

Create print-ready, digitally signed Adobe PDF and PDF/A documents.

tables, columns, images, headers and footers and more.

FLOW TYPE LAYOUTREPORTING

Untitled-2 1 12/7/12 10:48 AM

Page 27: Imagine. Create. Deploy. - 1105 Mediapdf.1105media.com/VSMMag/2013/Jan.pdf · Download your 30-day trial at Imagine. Create. Deploy. Inspired? So Are We. Inspiration is all around

24 VISUAL STUDIO MAGAZINE · January 2013 · VisualStudioMagazine.com

{ PRACTICAL .NET }

Sh

areP

oin

t W

eb P

arts

</Language Lab>

the code creates the DataSet and adds it to the Session object. That process starts by instantiating the TableAdapter:

nwTB = CType(HttpContext.Current.Session("CustomerData"), _

NorthwindDS.OrdersDataTable)

If nwTB Is Nothing Then

Dim nwtba As New NorthwindDSTableAdapters.OrdersTableAdapter

If there’s no filtering Web Part attached to the provider, the code just calls the GetData method on the TableAdapter to get all the orders:

If fvi Is Nothing Then

nwTB = nwtba.GetData

Else

If there’s a filtering Web Part connected, I make a simplifying assumption—the provider won’t accept multiple filter values and, furthermore, I’ll throw an exception if the filtering Web Part provides multiple values:

Dim parm As String

If fvi.AllowMultipleValues = True OrElse _

fvi.ParameterValues.Count > 1 Then

Throw New SPException("Multiple values not allowed")

End If

The next set of code retrieves the filter value from the filtering Web Part ParameterValues property. In addition to retrieving the value from the ParameterValues property, the code checks for various conditions that mean all the Orders are to be retrieved (and throws an exception if those conditions are met but the filtering Web Part doesn’t support the “All” value):

Dim parm As String

If fvi.ParameterValues Is Nothing OrElse _

fvi.ParameterValues.Count = 0 OrElse _

fvi.ParameterValues(0) Is Nothing Then

If fvi.AllowMultipleValues = False Then

Throw New SPException("A value must be provided")

End If

parm = "All"

Else

parm = fvi.ParameterValues(0)

End If

The final step is to retrieve data using the parameter (or retrieve all the data) and put the data in the DataTable in the Session object. This code assumes that if the filter value is set to “All” but the “All” value isn’t permitted, then “All” must be a CustomerID. The custom FillBy method I added to the DataSet accepts a CustomerID and retrieves the Orders for the Customer with that ID:

If (fvi.AllowAllValue = True And _

parm = "All") Then

nwTB = nwtba.GetData

Else

nwTB = nwtba.GetDataByCustomerID(parm)

End If

With the DataTable now loaded with data, I put the DataTable in the Session object for next time (I’ve omitted the code to retrieve data if the consumer’s filter value changes):

HttpContext.Current.Session("CustomerData") = nwTB

Once this provider Web Part has retrieved its data, it should pass the data to any connected consumer Web Part. Passing the data consists of calling the callback method in the consumer that was passed to the provider Web Part after the consumer was connected. In the IWebPartTable interface, the consumer’s callback method accepts a single parameter defined of type Collection. The DataTable Rows collection works here because, as a collection of DataRows, the Rows collection is compatible with the parameter definition for the consumer method. Code like this checks for a consumer and calls its method if connected:

If tcb IsNot Nothing Then

tcb(nwTB.Rows)

End If

The simplest place to put all this code is “as late as possible” in the Web Part lifecycle. For this example, I overrode the Web Part OnPreRender method, which is automatically executed after virtually all the other code in the Web Part, and put the code there. As you’ll see, I’m going to centralize all the data-access code and communication with the consumers in this method.

Adding IWebPartRowTo support another interface, you just need to have the class implement the interface and add another ConnectionProvider method that returns that interface. That’s what this method does for the IWebPartRow interface:

Public Class OrderProvider

Inherits WebPart

Implements IWebPartTable

Implements IWebPartRow

<ConnectionProvider("Current Row", _

"ConnectionPointIWebpartRow", _

AllowsMultipleConnections:=True)> _

Public Function MyConsumerMethodForSelectedRow() As IWebPartRow

Return Me

End Function

The IWebPartRow interface, like the IWebPartTable interface, gives the consumer Web Part the ability to pass a reference to a callback method in the consumer Web Part to the provider by calling a method in the provider. The method in the provider is called GetRowData; all you have to do in that method is accept the reference to the consumer’s callback method and store it until you need to pass the consumer some data:

Dim rcb As RowCallback

Public Sub GetRowData(callback As RowCallback) _

Implements IWebPartRow.GetRowData

rcb = callback

End Sub

Because the IWebPartRow interface passes a row selected by the user in the provider Web Part to the consumer Web Part, the provider Web Part will typically have a UI that displays the data the provider retrieved and lets the user select a row.

You should be going beyond creating consumer Web Parts that use the default interfaces, and be creating provider Web Parts that implement those interfaces.

Page 28: Imagine. Create. Deploy. - 1105 Mediapdf.1105media.com/VSMMag/2013/Jan.pdf · Download your 30-day trial at Imagine. Create. Deploy. Inspired? So Are We. Inspiration is all around

VisualStudioMagazine.com · January 2013 · VISUAL STUDIO MAGAZINE 25

{ PRACTICAL .NET }

1/2Isl. Ad F.P.O

There are lots of ways to create that UI, but the easiest way for me was to create my provider as a Visual Web Part and then drag an ASP.NET GridView onto the UserControl. I set the GridView AutoGenerateSelectButton property to True, to generate a column with a LinkButton in it that allows the user to select a row in the GridView. I also specified in the GridView DataKeyNames property that the OrderId field must be tracked for each row in the GridView.

To link the GridView in the UserControl to the data retrieved in the code-only part of my Visual Web Part, I first need to retrieve a reference to the UserControl Parent and then cast the reference to the type of the code-only portion of my WebPart:

Dim parentWebPart As OrderProvider

Protected Sub Page_Load(ByVal sender As Object, _

ByVal e As EventArgs) Handles Me.Load

parentWebPart = CType(Parent, OrderProvider)

End Sub

I used this code in the UserControl PreRender event to move the data into the GridView from the property I set up in the code-only part of the Web Part:

Me.GridView1.DataSource = parentWebPart.nwTB

Me.GridView1.DataBind()

The final step in the UserControl is to add this code to the GridView Selected-IndexChanged event to call a method in the code-only part of the Web Part when the user selects a row. I pass the method the OrderId for the selected row:

parentWebPart.MarkRow( _

Me.GridView1.SelectedDataKey)

In the method called from my User-Control, I don’t pass the selected row to any connected consumer. Instead, in the method called from my UserControl, all I do is retrieve the OrderId passed from the UserControl and store it in a variable:

Dim RowKey As String = String.Empty

Public Sub MarkRow(key As DataKey)

RowKey = key.Value

End Sub

I use that value in the OnPreRender method where I’m putting the rest of my data-access code. In the OnPreRender method, I check to see if the variable has a value in it. If it does (and if I have a consumer connected through my IWebPartRow interface), I find the matching row in the DataSet and call the method I received from the consumer, passing the row:

If RowKey <> String.Empty AndAlso _

rcb IsNot Nothing Then

Dim selectedRows() As DataRow

selectedRows = nwTB.Select("OrderId=" & RowKey)

rcb(selectedRows(0))

End If

And there it is: a custom provider Web Part that supports both filtering and

integrating with consumers, using either the IWebPartTable or IWebPartRow interface. By leveraging the default SharePoint interfaces, you can create truly interoperable Web Parts that will empower your users to create the applications that they need. VSM

Peter Vogel is a principal in PH&V Information Services, specializing in ASP.NET development with expertise in SOA, XML, database and UI design. His most recent book (“rtfm*,” PH&V Information Services, 2008) is on writing effective user manuals, and his blog on technical writing can be found at rtfmphvis.blogspot.com.

Page 29: Imagine. Create. Deploy. - 1105 Mediapdf.1105media.com/VSMMag/2013/Jan.pdf · Download your 30-day trial at Imagine. Create. Deploy. Inspired? So Are We. Inspiration is all around

26 VISUAL STUDIO MAGAZINE · January 2013 · VisualStudioMagazine.com

Win

dow

s 8

&

Win

dow

s P

hon

e

</Language Lab>

One App, Two PlatformsAlthough Windows 8 and Windows Phone share the same core, building an app for both isn’t as easy as you might think.BY NICK RANDOLPH

Windows 8 and Windows Phone 8 are finally here. In this article, I’ll look at key similarities and differences between developing applications for these two new platforms.

I’ll start by taking a look at what it means to build for a Windows device. With the rapid adoption of touch-based computing,

there’s a need for traditional forms-based interfaces to evolve, making them more touch-friendly.

Don’t Start Me UpOne such transition is the rather dramatic departure from a Start button, arriving at an entire Start screen. Those already familiar with Windows Phone will recognize the Live Tile concept and immediately feel at home. Live Tiles are not simply application shortcuts; they’re about displaying a snapshot or status of each application, or part of an application.

The immediate question that developers ask is whether it’s possible to build a single application that works across both Windows and Windows Phone. In theory, this sounds like a great idea, but the reality is that, when executed, it leads to an awful experience.

Take, for example, what happens if you run an iPhone version of an application on an iPad. Despite the ability to magnify it to fill the screen, the experience isn’t anything like an application specifically designed for an iPad. Currently, there are three resolutions developers have to target for Windows Phone. This means applications can be heavily optimized for these resolutions without having to worry about how the app scales to different form factors.

Windows 8, by comparison, does have to cater to varying screen sizes, from the smallest screens (1024x768) to much larger screens (no upper limit). This in itself can be a daunting task. Luckily, a number of the controls available in the SDK lend themselves well to building scalable applications.

Both Windows 8 and Windows Phone have multiple orientations that developers can choose to handle within their application. For Windows Phone, support for different device orientations can be handled at a page level. It’s entirely opt-in, with portrait being the default for most applications.

Windows 8 applications, on the other hand, can opt out of supporting certain orientations at an application level, with landscape being the default for most applications. But they’re also required to support Snapped mode, where the application is docked to one edge of the screen. It’s important to note that dealing with orientations alone will increase the complexity of development and testing of a Windows 8 application, compared to a Windows Phone application.

Choosing a LanguageApplications for Windows Phone are written natively in C++. Managed applications are written with Silverlight for Windows Phone (for instance, XAML + C# or Visual Basic .NET), or with an HTML-wrapper technology such as PhoneGap for HTML/JavaScript/CSS-style applications. Windows 8, re-architected from the ground up, allows you to write apps using C++, C#/Visual Basic .NET or HTML/JavaScript/CSS. If you’re looking to maintain a compatible code base across both platforms, you’ll probably want to go down the XAML + C#/Visual Basic .NET path.

Silverlight and Windows Presentation Foundation (WPF) developers will be familiar with the separation of design (XAML) from the code (C#/Visual Basic .NET). There are some subtle inconsistencies between the XAML used by Windows Phone and Windows 8 that will prevent you from using the same XAML across both applications.

In addition to considering how the individual screens are laid out, you also need to consider the navigation path and interaction model throughout the application. Windows Phone incorporates a hardware back button, making it easy for users to back out of the current screen. There’s no such requirement for Windows applications, which means that if you’re not careful, the user might get lost.

Lifecycle ConsiderationsYou also need to consider the different entry points and the overall lifecycle of the application. When building a Windows Phone application, you must consider the effects of tombstoning, where your application might need to resume from a not-running state. This isn’t the case with Windows 8 applications, although you do still need to deal with suspended states. Both platforms support being entered via a push notification, but Windows 8 also allows entry via the Search or Share charms.

There’s an argument to be made for creating a Windows 8/Windows Phone 8 app that can reuse a single codebase, but this isn’t as easy as it sounds, due partially to historical reasons. Windows Phone is an almost direct derivative of Silverlight for the desktop. Windows 8 has been re-engineered as a better, quicker and more reliable platform (for example, asynchronous operations have been used for operations that can block or take a finite amount of time to execute).

Although there’s an overlap of commonalities between the platforms, the incompatibilities range from simple namespace changes to big differences in the way certain operations are performed. If you want to build one application that works on both platforms, I’ll present four ways to architect your code that maximize the reuse between your apps.

Reuse Strategy No. 1: Portable Class LibrariesThe concept of a portable class library (PCL) stems from the fact that both platforms intersect over a large set of common types. If your code—and other libraries it might rely on—only uses this

{ MOBILE CORNER }

Page 30: Imagine. Create. Deploy. - 1105 Mediapdf.1105media.com/VSMMag/2013/Jan.pdf · Download your 30-day trial at Imagine. Create. Deploy. Inspired? So Are We. Inspiration is all around

Untitled-1 1 10/11/11 11:43 AM

Page 31: Imagine. Create. Deploy. - 1105 Mediapdf.1105media.com/VSMMag/2013/Jan.pdf · Download your 30-day trial at Imagine. Create. Deploy. Inspired? So Are We. Inspiration is all around

28 VISUAL STUDIO MAGAZINE · January 2013 · VisualStudioMagazine.com

{ MOBILE CORNER }

subset of the Microsoft .NET Framework, you can generate a PCL that can simply be referenced by both Windows 8 and Windows Phone applications.

When working with a PCL, you might notice limitations imposed by the need to work across multiple platforms. For instance, there’s a lack of support for Tasks, which impacts the async/await keywords. A workaround for this is to add the Microsoft.Bcl.Async NuGet package.

Reuse Strategy No. 2: Conditional Code BlocksThe next three alternatives involve including the code files in both Windows 8 and Windows Phone projects. As such, they’re not mutually exclusive; it’s a matter of selecting the best or most appropriate technique for your scenario.

The first is to use conditional code blocks to effectively hide parts of the code file, based on the platform for which it’s being compiled. By default, Windows Phone applications define WINDOWS_PHONE, and Windows 8 applications define NETFX_CORE. For example, the following code includes a different namespace, depending on which platform it’s being built for:

#if NETFX_CORE

using Windows.UI.Xaml.Media.Imaging;

#else

using System.Windows.Media.Imaging;

#endif

While this appears to be relatively simple to follow, it quickly becomes unmanageable if used for large blocks of code. It’s hard to identify which code is platform-specific versus common code.

Reuse Strategy No. 3: InheritanceOne option for making it easier to separate common code from platform-specific code is the use of inheritance. With this model, the common code would reside in the base class, with platform-specific code being added to a sub-class.

The code in the sub-class can belong to two cases: The first is where additional functionality has been added for a particular platform (for instance, sending an SMS on Windows Phone). The second is where a function needs to be implemented in a platform-specific manner (for example, file access). In the second case, it might be that the base class defines an abstract method, requiring its completion in the sub-class, like this:

public abstract class MainPageViewModel : NotifyBase,IViewModel

{

protected abstract void DisplayPicture();

}

public class WinMainPageViewModel : MainPageViewModel,

ISupportsDesignTimeDataViaCode

{

protected override void DisplayPicture()

{

// Implementation to display picture on Windows

}

}

Reuse Strategy No. 4: Partial Classes and MethodsAn alternative to using inheritance is to use partial classes and methods. Partial classes were originally introduced to allow developers to add supplementary code to classes that had been

generated (either by a designer or some other code generator). By placing the code in a separate file, it wasn’t overwritten the next time the code generator was run.

This same technique can be used to separate out common code and platform-specific code, as in this example where the LoadFolders method is implemented in a separate file:

public partial class DataSource:IDataSource {

public async Task<IEnumerable<IFolder>> RetrieveFolders(IFolder root) {

... // Other logic

var folders = await LoadFolders(root);

... // Other logic

return folders

}

}

public partial class DataSource {

private async Task<IEnumerable<IFolder>> LoadFolders(IFolder root) {

...

}

}

There’s also the concept of partial methods. In this, the method signature can be defined alongside the common code, and the implementation can reside in a different file. However, there are restrictions on the method signature, such as having a void return type, which can make it ineffective for the purposes of separating out platform-specific code.

When you’re trying to work out which of these reuse patterns to use, it’s helpful to look at the APIs exposed by the different platforms. Some, such as the accelerometer, have an API that’s almost identical; others are significantly different and can impact the way you structure your code (for example, the camera capture task for Windows Phone applications).

Data BindingIt’s worth revisiting the way data binding works across both platforms. A common pattern used across Silverlight, WPF, Windows Phone and now Windows 8 is Model-View-ViewModel (MVVM). At its root, MVVM is all about data binding and how you can separate the data and logic from the way the data’s rendered.

As you think through how you’re going to reuse code between the two platforms, you should be focusing on how much of the model and view model you can reuse. As mentioned earlier, the view will—and should—be different between the two platforms. By reusing the model and view model, you’ll end up with both a high level of reuse and a similar application structure and navigation model.

It Gets EasierIn this article I’ve touched on some of the similarities and differences between the Windows 8 and Windows Phone 8 platforms. The similarities will grow because both platforms share a common core, and over time we can expect it to become even easier to build applications that target both platforms. VSM

Nick Randolph runs Built to Roam, a consulting company that specializes in training, mentoring and assisting other companies in building mobile applications. With a heritage in rich client applications for both the desktop and a variety of mobile platforms, Randolph presents, writes and educates on the Windows Phone platform.

</Language Lab>W

ind

ows

8 &

W

ind

ows

Ph

one

Page 32: Imagine. Create. Deploy. - 1105 Mediapdf.1105media.com/VSMMag/2013/Jan.pdf · Download your 30-day trial at Imagine. Create. Deploy. Inspired? So Are We. Inspiration is all around

vslive.com

VISUAL STUDIO LIVE! IS COMING TO A CITY NEAR YOU

Get an all-access look at the Microsoft Platform and practical, unbiased Developer training at Visual Studio Live!. Pick your tour dates and join .NET rockstars for a week of educational sessions, workshops and networking events.

HTML5 | Windows 8 | Visual Studio/.NET | Mobile | WPF/ Silverlight

There are FOUR tour dates / l ocations to choose from – pick your favorite and prepare to solve your development challenges in 2013! Scan the QR code

to register or for more event details.

PRODUCED BYSUPPORTED BY

magazine

YOURR BBACKSTTAGEE PPASS TTO THEE MICCROSOOFTT PPLATFFORM

PICK YOUR TOUR DATES

Untitled-1 1 11/26/12 11:14 AM

Page 33: Imagine. Create. Deploy. - 1105 Mediapdf.1105media.com/VSMMag/2013/Jan.pdf · Download your 30-day trial at Imagine. Create. Deploy. Inspired? So Are We. Inspiration is all around

30 VISUAL STUDIO MAGAZINE · January 2013 · VisualStudioMagazine.com

SQ

L

Dev

elop

men

t

</Language Lab>

4 New T-SQL FunctionsThe latest version of SQL Server expands its capabilities. Here are four new things developers can do with it.BY SAM NASR

SQL Server 2012 was released last April, making it the 11th major release of the product. Every new version has delivered new functionality that should excite developers, and this release is no different. With the latest release of SQL Server, Microsoft produced 14 new T-SQL

functions. These functions can be separated into four different categories, as seen in Table 1.

These functions will be demonstrated using the “SELECT” statement, so no specific database structure is needed. They can be executed against any database, in a stored procedure or other scripts, just like all other T-SQL statements. Here, I’ll discuss conversion functions and the first date and time function. An online companion article will detail the other date and time functions and discuss logical and string functions.

1. PARSE PARSE is a T-SQL function that transforms a string expression into a date/time or number type. It accepts two parameters and an optional third parameter for culture. The syntax for the statement is PARSE (string_value AS data_type [USING culture]). Here’s a typical usage scenario:

select Parse ('03042011' as float) AS NewResult

NewResult

3042011

Use caution when using the culture parameter. In the following example, both statements are identical, except for the culture:

select Parse ('08-18-2011' as datetime2 using 'en-US') AS NewResult

NewResult

2011-08-18 00:00:00.0000000

select Parse ('08-18-2011' as datetime2 using 'en-AU') AS NewResult

Msg 9819, Level 16, State 1, Line 1

Error converting string value '08-18-2011' into data type datetime2 using

culture 'en-AU'.

Using 08-18-2011 is valid for the U.S. culture, but the same date will produce an error if rendered in an Australian format, because Australian culture requires a date to have the day followed by the month.

“08” is a valid day, but “18” isn’t a valid month, causing the error.Using PARSE requires the CLR. This means a user can’t remote

in to another SQL Server machine without having the CLR installed and executing the PARSE command. This function is used only for converting strings to date/time or numeric types. It’s highly suggested by the Microsoft team to use CAST or CONVERT for other type conversions.

The transform patterns are limited by styles listed in the CLR in System.Globalization.NumberStyles and DateTimeStyles enumerations, dictating the characters allowed and different patterns for the end result. For more information on transform patterns, see “NumberStyles Enumeration” in the MSDN Library at bit.ly/N9tuaz.

2. TRY_CONVERTThe TRY_CONVERT function converts an expression to a specified data type. The syntax format is TRY_CONVERT (data_type [(length) ], expression [, style]). It’s similar to PARSE, but with a few differences. First, it allows conversion to any data type. Second, it will return a NULL if not successful. However, it will return an error when the cast is explicitly not permitted. Last, it doesn’t allow for the use of culture, but it does have an optional third parameter for Style. An example of this can be seen in the following code snippet, which converts a string containing date information into a datetime2 data type:

select TRY_CONVERT(datetime2, '08/18/2012') as NewResult

NewResult

2012-08-18 00:00:00.0000000

The following code shows a scenario when TRY_CONVERT will return a NULL:

select TRY_CONVERT(datetime2, '99/99/9999') as NewResult

NewResult

NULL

As seen in the first code sample, a string can be converted to a datetime2 type. However, if the string expression contains an invalid date, TRY_CONVERT will return a NULL.

The TRY_CONVERT function also allows for use of styles as an optional third parameter. Style differs from culture because it shows how the end result of the date will be displayed, not just the alignment of month and day. You can see this in Listing 1 (opposite page). For more information on Styles, see “CAST and CONVERT (Transact-SQL)” in the MSDN Library at bit.ly/QpiYxO.

3. TRY_PARSENext on the list of new T-SQL functions is TRY_PARSE. The function syntax is TRY_PARSE (string_value AS data_type [USING culture]). This is similar to the PARSE function, except that it returns NULL if the value isn’t a valid representation of the data type, where PARSE Function raises an error. Traditionally,

{ O N V B }

Conversion Functions1. PARSE2. TRY_CONVERT3. TRY_PARSE

Logical Functions11. CHOOSE12. IIF

Date and Time Functions4. DATEFROMPARTS5. DATETIME2FROMPARTS6. DATETIMEFROMPARTS7. DATETIMEOFFSETFROMPARTS8. EOMONTH9. SMALLDATETIMEFROMPARTS10. TIMEFROMPARTS

String Functions13. CONCAT14. FORMAT

Table 1. 14 New T-SQL Functions

Page 34: Imagine. Create. Deploy. - 1105 Mediapdf.1105media.com/VSMMag/2013/Jan.pdf · Download your 30-day trial at Imagine. Create. Deploy. Inspired? So Are We. Inspiration is all around

VisualStudioMagazine.com · January 2013 · VISUAL STUDIO MAGAZINE 31

SQ

L

Dev

elop

men

t

{ O N V B }

any function name in the Microsoft .NET Framework starting with “Try_” usually indicates it will return a NULL, not an error, if the expression can’t be evaluated. The following code shows a typical TRY_PARSE usage scenario:

SELECT TRY_PARSE('08/18/2012' AS datetime2 USING 'en-US') AS NewResult

NewResult

2012-08-18 00:00:00.0000000

Here, the difference of TRY_PARSE can be seen (I used the same parameters used for PARSE, but got different results):

select TRY_PARSE ('08-18-2011' as datetime2 using 'en-US') AS NewResult

NewResult

2011-08-18 00:00:00.0000000

select TRY_PARSE ('08-18-2011' as datetime2 using 'en-AU') AS NewResult

NewResult

NULL

The first statement in here yields the same results as its counterpart in the first PARSE sample. However, the second statement yields a NULL, not an error, because the string expression isn’t a valid Australian date.

4. DATEFROMPARTSThe next category of the new T-SQL functions contains date and time functions. There are seven new date/time functions.

The first of these is DATEFROMPARTS. This function is used to return a date value for separate integer values of year, month and day. The function’s syntax is DATEFROMPARTS (year, month, day).

DATEFROMPARTS is capable of being remoted only to SQL Server 2012 or later. Unlike other functions previously mentioned, all parameters are required, and it doesn’t accept a style or culture parameter. All values must be valid date values, or it will return an error. If a NULL value is passed for any of the parameters, it will return NULL.

The following code shows correct usage of the DATEFROM-PARTS function (note how it returns the date type):

SELECT DATEFROMPARTS (2012, 8, 18) AS NewDateValue

NewDateValue

2012-08-18

When invalid parameters are used, the results look like this: SELECT DATEFROMPARTS (NULL, 8, 18) AS NewDateValue

NewDateValue

NULL

SELECT DATEFROMPARTS (1985, 13, 26) AS NewDateValue

Msg 289, Level 16, State 1, Line 1

Cannot construct data type date, some of the arguments have values which

are not valid.

Note that DATEFROMPARTS returns NULL when any or all of the parameters are NULL. However, it returns an error if any of the date fields are invalid (for instance, month=13).

Look for the next installment of this article online. VSM

Sam Nasr has been a software developer since 1995 and has obtained MCAD, MCTS and MCT certifications. He develops software, teaches, writes articles and speaks on various topics in the Microsoft .NET Framework. Nasr is also the leader for the Cleveland C#/Visual Basic .NET User Group and Cleveland WPF User Group, and is the INETA mentor for Ohio. He can be reached at [email protected].

GO ONLINE Go to VisualStudioMagazine.com/Nasr0113 to read about more T-SQL functions and to download the sample code.

Listing 1. Using TRY_CONVERT with the Style parameter.

select TRY_CONVERT(varchar(50), '08/18/2012', 1) as NewResultNewResult09/08/12

select TRY_CONVERT(varchar(50), '08/18/2012', 2) as NewResultNewResult12.09.08

select TRY_CONVERT(varchar(50), '08/18/2012', 3) as NewResultNewResult08/09/12

select TRY_CONVERT(varchar(50), '08/18/2012', 4) as NewResultNewResult08.09.12

select TRY_CONVERT(varchar(50), '08/18/2012', 5) as NewResultNewResult08-09-12

There are seven new date/time functions.

Page 35: Imagine. Create. Deploy. - 1105 Mediapdf.1105media.com/VSMMag/2013/Jan.pdf · Download your 30-day trial at Imagine. Create. Deploy. Inspired? So Are We. Inspiration is all around

32 VISUAL STUDIO MAGAZINE · January 2013 · VisualStudioMagazine.com

I’ve always been impressed by Microsoft’s dedication to bringing new technologies to its developers, while making those technologies available through existing interfaces and within existing skill sets. For an example, you can go back to the 1990s, when Microsoft brought Visual Basic (and Visual Basic developers) to Web browser and server development. You can also look at more recent offerings, such as building RESTful services with the new ASP.NET Web API, or even the development of Windows Store applications using HTML and JavaScript.

The data side has followed this paradigm, too. There’s been churn of data-access APIs over the years, but each one has been impressively versatile. DAO worked for Access and ODBC. ADO worked with Exchange message stores almost as easily as it did with SQL Server. And today LINQ works with everything, including business objects, Internet data feeds, client/server databases and even directory services.

What’s next on the data frontier? Microsoft will take us into the world of in-memory transactional databases and big data. And if you know how to write code and queries against SQL Server, then you already have the necessary skills to play there.

New Technologies, Same DatabaseAt the PASS Summit in Seattle this past November, Microsoft announced two new projects: Hekaton and PolyBase. Hekaton is a transactional (rather than analytical) in-memory database technology for the next major version of SQL Server. PolyBase integrates Hadoop into the upcoming release of SQL Server Parallel Data Warehouse edition. What’s in it for developers? The same Transact SQL (T-SQL) language and data-access APIs used with SQL Server today will work with both of these new technologies.

Hekaton will allow database administrators (many of whom are also developers these days) to design tables to be loaded into memory, where they can then be queried and updated. Hekaton won’t be a standalone product—in fact, in-memory tables and disk-based tables will exist side-by-side in the same SQL Server databases. Applications that query them will in many cases be able to do so agnostically, with developers not even having to know which type of table they’re working with.

PolyBase will also allow for the creation of special tables, but these will have a physical basis in fi les stored in the Hadoop Distributed File System (HDFS). Because the data in these fi les will behave like physical tables in SQL Server, developers can query them with T-SQL (not MapReduce code), and even join them to conventional tables in their queries.

In the case of both Hekaton and PolyBase, existing developers with existing skill sets will be almost immediately qualifi ed to build new applications that take on very different workloads, for a different world of data.

Should I Stay or Should I Go Now?I fi rst started working with SQL Server in 1994. It astounds me how a technology that I became familiar with nearly 20 years ago is still so useful today. Is that a bad thing? SQL Server has acquired layers of features over the years as new technologies have appeared on the scene, much as a rental apartment accumulates layers of paint with each new tenant. In the latter case, there’s always the temptation to scrape off the paint, go down to the brick and apply the new paint there—or just move somewhere new.

Some SQL Server developers have moved on to places like MongoDB, DynamoDB or Hadoop. And just as some people dream of owning a mansion, some developers may hope to land work with SAP HANA, an exclusively in-memory database that certainly doesn’t come cheap.

But many are happy to stay in their old house, adding extensions, upgrading the wiring and maybe even redecorating once in a while. So it is with many SQL Server pros who keep reinvesting in that platform. They’re spared the expense of “moving,” and they get to know the ins and outs of their “home” really well—though they do lose out on the adventure of going somewhere new.

Businesses value savings and experience. Avoiding new recruit-ment or massive retraining, preventing a change of vendors and the procurement adjustments that go with that, and maintaining the continuum of older applications with newer ones are good things for customers. Microsoft knows this well. And while the industry’s attention is almost exclusively focused on the client OS and devices, it loses touch with the importance of back-end technology to platform strength and stability. Microsoft must focus on both. On the server side, it’s doing very well. VSM

Andrew J. Brust is founder and CEO of Blue Badge Insights, an analysis, strategy and advisory firm serving Microsoft customers and partners. Brust is also a Microsoft regional director and MVP; an advisor to the New York Technology Council; and coauthor of “Programming Microsoft SQL Server 2008” (Microsoft Press, 2008). A frequent speaker at industry events, Brust is co-chair of the Visual Studio Live! family of conferences and a contributing editor to Visual Studio Magazine.

Data Platform Innovation, Without Disruption

BY ANDREW J. BRUST

</Redmond Review>

Page 36: Imagine. Create. Deploy. - 1105 Mediapdf.1105media.com/VSMMag/2013/Jan.pdf · Download your 30-day trial at Imagine. Create. Deploy. Inspired? So Are We. Inspiration is all around

Untitled-4 1 11/30/12 11:37 AM

Page 37: Imagine. Create. Deploy. - 1105 Mediapdf.1105media.com/VSMMag/2013/Jan.pdf · Download your 30-day trial at Imagine. Create. Deploy. Inspired? So Are We. Inspiration is all around

WHAT IF DEVELOPING FOR HUNDREDS OF SERVERS WAS AS EASY AS ONE?

IT IS...MEET FATCLOUD

The next generation cloud enabled application platform for .NET is here. For a free three-node developer download visit FATCLOUD.COM.

Untitled-1 1 12/3/12 3:31 PM