Navigation

Friday, February 25, 2011

Productivity Power Tools introduces Find, Organize Imports for VB, Enhanced Scrollbar, Middle-Click Scrolling and more!

MS has released an updated version of the productivity power tools.

http://blogs.msdn.com/b/visualstudio/archive/2011/02/22/productivity-power-tools-introduces-find-organize-imports-for-vb-enhanced-scrollbar-middle-click-scrolling-and-more.aspx

Resetting Your Extensions for the Last Time!

We've heard a great deal of feedback on how each update of the Productivity Power Tools re-enables all of the extensions when it installs. If you are careful about installing the Power Tools via the extension manager or as long as an instance of Visual Studio is running, this version of the Productivity Power Tools will be the last which resets the extensions.

Please note: If you are running Visual Studio 2010 SP1 (Beta) that you will need to uninstall previous versions of the Productivity Power Tools prior to upgrading due to a change in the digital signature for the Power Tools

Find

There are many different ways to find within Visual Studio (Incremental Search, Quick Find, Find in Files, Find Toolbar, etc) and it often isn’t clear which is the best for a given task or worse these options even exist.  The find dialog itself also can obstruct code and jump around while users are searching. Our solution to these problems is the new Find extension. In the screenshot below, you will see that we’ve turned the quick find & incremental search experiences into a find pop-up that is available at top right hand corner of the editor. After hitting, Ctrl+I or Ctrl+F, it simply highlights the find results as you type.  From this small but powerful pop-up, you have access to most of the Quick Find functionality such as replace, options to match case and added support for matching .NET Regular Expressions!

Release notes:

  • As an extension, it was only possible to implement these changes for the code editor. You still must use Quick Find for searching in designers and other non-editor tabs. 
  • .NET Regular expressions are only available in the Find extension. Find in Files will continue to use VS Regular expressions
  • Feel free to email us your feedback: VSFindFeedback@microsoft.com

Enhanced Scrollbar

We’ve been looking into ways that we can improve the experience of navigating through code files.  Our solution is the source map which has three modes that will allow you to more easily see the interesting artifacts in your files (edits, breakpoints, bookmarks, errors, warnings etc) and make it easy for you to navigate between them.  The default mode is the “scroll bar only mode” which overlays icons onto the standard scrollbar to allow for viewing of these artifacts.  In the source map mode, we’ve replaced the default scroll bar allow you to click on any item on the scrollbar to navigate directly to it. This source map mode also provides a preview of the part of the document as you hover.  Finally, we have the detailed source map mode, which allows you to get a zoom out view of your entire file.  You can switch between any of these modes by right-clicking on the scroll bar or going to Tools Options>Productivity Power Tools>Source Map where we have a host of other options that you can configure.

Middle-Click Scrolling

The ability to do middle click scrolling in Visual Studio 2010 has been a top request from our beta customers that we weren’t quite able to get into the release. With this extension you can press down on your scroll wheel and the move the mouse to quickly scroll through your document!

Organize Imports for Visual Basic

As part of theco-evolution strategy for Visual Basic and C#, we continue to bring the best features from each language experiences to the other. With Organize Imports for Visual Basic we’ve added yet another feature to that list.  From the context menu, it allows you to sort the imports logically and remove the ones that aren’t being used.

Add Reference Support for Multi-Targeting

“How come I can’t add a reference to System.Web?”  Many users have scratched their heads trying to figure out why certain dlls aren’t showing up in the Add Reference dialog. The confusion has been caused by the logic in the Add Reference dialog which filters out assemblies that are not valid on the .NET Client Profile which many of Visual Studio templates target by default.  The Productivity Power Tools solution is to grey out the assemblies which are not available in the current framework profile. When you try to add them, it will automatically prompt you to re-target to a profile of the same framework which does support them.

Options in HTML Cut/Copy

Productivity Power Tool users have asked for the ability to tweak the html format which gets copied to the clipboard and with the release you now have the ability to customize that to suite your needs.  Simply go to Tools Options>Productivity Power Tools> HTML Copy

This release of the extension also fixes the commonly reported bug where Cut/Copy occasionally fail which was fixed in VS 2010 SP1 Beta but was present in the October release of the Productivity Power Tools.

Tuesday, December 07, 2010

Great Collection of Free Microsoft eBooks

Here are some great free Microsoft eBook offers from the last few months.
Free ebook: Moving to Microsoft Visual Studio 2010 http://blogs.msdn.com/b/microsoft_press/archive/2010/09/13/free-ebook-moving-to-microsoft-visual-studio-2010.aspx
Free ebook: Introducing Microsoft SQL Server 2008 R2 http://blogs.msdn.com/b/microsoft_press/archive/2010/04/14/free-ebook-introducing-microsoft-sql-server-2008-r2.aspx
Petzolds Programming Windows Phone 7 http://download.microsoft.com/download/5/0/A/50A39509-D015-410F-A8F2-A5511E5A988D/Microsoft_Press_ebook_Programming_Windows_Phone_7_PDF.pdf
Free ebook: Own Your Future: Update Your Skills with Resources and Career Ideas from Microsoft http://blogs.msdn.com/b/microsoft_press/archive/2010/03/03/free-ebook-own-your-future-update-your-skills-with-resources-and-career-ideas-from-microsoft.aspx
Free ebook: Understanding Microsoft Virtualization Solutions (Second Edition) http://blogs.msdn.com/b/microsoft_press/archive/2010/02/16/free-ebook-understanding-microsoft-virtualization-r2-solutions.aspx
Free ebook: Introducing Windows Server 2008 R2 http://blogs.msdn.com/b/microsoft_press/archive/2009/10/20/free-ebook-introducing-windows-server-2008-r2.aspx
Free ebook: Deploying Windows 7, Essential Guidance http://blogs.msdn.com/b/microsoft_press/archive/2009/10/16/free-e-book-deploying-windows-7-essential-guidance.aspx

Friday, December 03, 2010

How to use IIS Compression with Web Services

Using IIS compression with web services is a simple way to provide better performance for your services.  This article will detail implementing this solution in IIS6 and IIS7.

First, you need to ensure that the web service proxy in your application has the following property set to true;

Dim myService as new localhost.service1
myService.EnableDecompression = True

This will ensure that your application takes advantage of the compression.

 

Second, you need to configure IIS compression on your server.  To do this ensure that you have the following installed;image

Then turn compression on in the IIS management console;

image

Then create a bat file in C:\inetpub\AdminScripts and place the following lines of code into the bat file;

IISreset.exe /stop
cscript.exe adsutil.vbs set w3svc/filters/compression/parameters/HcDoDynamicCompression true
cscript.exe adsutil.vbs set w3svc/filters/compression/parameters/HcDoStaticCompression true
cscript.exe adsutil.vbs set W3Svc/Filters/Compression/GZIP/HcFileExtensions "htm" "html" "txt" "ppt" "xls" "xml" "pdf" "xslt" "doc" "xsl" "htc" "js" "css"
cscript.exe adsutil.vbs set W3Svc/Filters/Compression/DEFLATE/HcFileExtensions "htm" "html" "txt" "ppt" "xls" "xml" "pdf" "xslt" "doc" "xsl" "htc" "js" "css"
cscript.exe adsutil.vbs set W3Svc/Filters/Compression/GZIP/HcScriptFileExtensions "asp" "dll" "exe" "aspx" "asmx" "ashx"
cscript.exe adsutil.vbs set W3Svc/Filters/Compression/DEFLATE/HcScriptFileExtensions "asp" "dll" "exe" "aspx" "asmx"
cscript.exe adsutil.vbs set W3Svc/Filters/Compression/DEFLATE/HcScriptFileExtensions "asp" "dll" "exe" "aspx" "asmx"
cscript.exe adsutil.vbs set W3Svc/Filters/Compression/DEFLATE/HcDynamicCompressionLevel "9"
IISreset.exe /restart

This will enable compression on your web service.

The following tool is a easy free application that allows you to compare the difference in your application communication between compressed and uncompressed communications of xml data.

http://devolutions.net/products/TCP-Spy-Net.aspx

image

Thursday, November 18, 2010

How to update a large SQL tables without killing the server!

Often I have the need to update a very large (>1 million rows) and a simple sql statement like this takes a long time;

update mytable set myfield = getdate() where myfield is null

This statement provides better performance (if you have triggers on the table disabling them if you can provides better performance also);

DISABLE trigger [dbo].[myTrigger] ON  [dbo].[myTable];
go
SET ROWCOUNT 10000

WHILE 1=1
BEGIN
UPDATE myTable
SET myField = GETDATE()
WHERE myField is null
IF @@ROWCOUNT = 0 BREAK

END
go
enable trigger [dbo].[myTrigger] ON  [dbo].[myTable];
go

By changing the “Set RowCount” value you can tune the statement as needed.

Wednesday, November 17, 2010

Must have Visual Studio Tools

Below are a list of must have Visual Studio Tools.  They are all free and from Microsoft!
Visual Studio 2010 Feature Packs http://msdn.microsoft.com/en-us/vstudio/ff655021.aspx
Feature Packs enable you to extend Visual Studio 2010 with capabilities that enhance and complement the existing tools.
Visual Studio 2010 Feature Pack 2 (MSDN Subscribers Only) Cumulative feature pack that extends testing, code visualization and modeling capabilities in Visual Studio 2010.
Testing features:
Use Microsoft Test Manager to capture and playback action recordings for Silverlight 4 applications.
Create coded UI tests for Silverlight 4 applications with Visual Studio 2010 Premium or Visual Studio 2010 Ultimate.
Edit coded UI tests using a graphical editor with Visual Studio 2010 Premium or Visual Studio 2010 Ultimate.
Use action recordings to fast forward through manual tests that need to support Mozilla Firefox 3.5 and 3.6.
Run coded UI tests for web applications using Mozilla Firefox 3.5 and 3.6 with Microsoft Visual Studio 2010 Premium or Visual Studio 2010 Ultimate.
Code visualization and modeling features (requires Visual Studio 2010 Ultimate):
Use the Generate Code command to generate skeleton code from elements on UML class diagrams. You can use the default transformations, or you can write custom transformations to translate UML types into code.
Create UML class diagrams from existing code.
Explore the organization and relationships in C, C++, and ASP.NET projects by generating dependency graphs.
Import elements from UML sequence diagrams, class diagrams, and use case diagrams as XMI 2.1 files that are exported from other modeling tools.
Create links and view links from work items to model elements.
Create layer diagrams from C or C++ code and validate dependencies.
Write code to modify layer diagrams and to validate code against layer diagrams.

Productivity Power Tools http://visualstudiogallery.msdn.microsoft.com/en-us/d0d33361-18e2-46c0-8ff2-4adea1e34fef
A set of extensions to Visual Studio Professional (and above) which improves developer productivity. In this third major release of the Power Tools we have made significant improvements to the Solution Navigator and the Tab Well to address our top customer requests.
PowerCommands for Visual Studio 2010 http://visualstudiogallery.msdn.microsoft.com/en-us/e5f41ad9-4edc-4912-bca3-91147db95b99
PowerCommands 10.0 is a set of useful extensions for the Visual Studio 2010 adding additional functionality to various areas of the IDE. Visit the VSX Developer Center at http://msdn.com/vsx for more information about extending Visual Studio.

Thursday, November 11, 2010

How to determine if a table has changed in SQL

Often you need to know if a sql tables data has changed.  The change can be a new row, deleted row or updated row.  To determine if a row has changed you can use the following command that will return a checksum identifying a change to the table.
SELECT CHECKSUM_AGG(BINARY_CHECKSUM(*)) FROM <table name> WITH (NOLOCK);
You can also use a where clause.  For example get the checksum on just part of the table.

 

CHECKSUM

Returns the checksum value computed over a row of a table, or over a list of expressions. CHECKSUM is intended for use in building hash indices.
Syntax
CHECKSUM ( * | expression [ ,...n ] )
Arguments
*
Specifies that computation is over all the columns of the table. CHECKSUM returns an error if any column is of noncomparable data type. Noncomparable data types are text, ntext, image, and cursor, as well as sql_variant with any of the above types as its base type.
expression
Is an expression of any type except a noncomparable data type.
Return Types
int
Remarks
CHECKSUM computes a hash value, called the checksum, over its list of arguments. The hash value is intended for use in building hash indices. If the arguments to CHECKSUM are columns, and an index is built over the computed CHECKSUM value, the result is a hash index, which can be used for equality searches over the columns.
CHECKSUM satisfies the properties of a hash function: CHECKSUM applied over any two lists of expressions returns the same value if the corresponding elements of the two lists have the same type and are equal when compared using the equals (=) operator. For the purpose of this definition, NULL values of a given type are considered to compare as equal. If one of the values in the expression list changes, the checksum of the list also usually changes. However, there is a small chance that the checksum will not change.
BINARY_CHECKSUM and CHECKSUM are similar functions: they can be used to compute a checksum value on a list of expressions, and the order of expressions affects the resultant value. The order of columns used in the case of CHECKSUM(*) is the order of columns specified in the table or view definition, including computed columns.
CHECKSUM and BINARY_CHECKSUM return different values for the string data types, where locale can cause strings with different representation to compare equal. The string data types are char, varchar, nchar, nvarchar, or sql_variant (if its base type is a string data type). For example, the BINARY_CHECKSUM values for the strings "McCavity" and "Mccavity" are different. In contrast, in a case-insensitive server, CHECKSUM returns the same checksum values for those strings. CHECKSUM values should not be compared against BINARY_CHECKSUM values.
Examples
Using CHECKSUM to build hash indices
The CHECKSUM function may be used to build hash indices. The hash index is built by adding a computed checksum column to the table being indexed, then building an index on the checksum column.
-- Create a checksum index.
SET ARITHABORT ON
USE Northwind
GO
ALTER TABLE Products 
ADD cs_Pname AS checksum(ProductName)
CREATE INDEX Pname_index ON Products (cs_Pname)


The checksum index can be used as a hash index, particularly to improve indexing speed when the column to be indexed is a long character column. The checksum index can be used for equality searches.


/*Use the index in a SELECT query. Add a second search 
condition to catch stray cases where checksums match, 
but the values are not identical.*/
SELECT * 
FROM Products
WHERE checksum(N'Vegie-spread') = cs_Pname
AND ProductName = N'Vegie-spread'


Creating the index on the computed column materializes the checksum column, and any changes to the ProductName value will be propagated to the checksum column. Alternatively, an index could be built directly on the column indexed. However, if the key values are long, a regular index is not likely to perform as well as a checksum index.


See Also


BINARY_CHECKSUM


CHECKSUM_AGG








Reference; http://msdn.microsoft.com/en-us/library/aa258245%28SQL.80%29.aspx

WP7 Samsung Focus USB Tethering support

If you have a WP7 Samsung Focus from AT&T you can use the device as a tethered USB modem.
1.  Open phone dial pad
2.  dial “##634#”
3.  Hit send, this will install a diagnostic app in your application directory for future access.
4.  When the diagnostics interface comes up dial “*#7284#”
5.  You will see the “Micro USB Test” screen options for Zune Sync, Modem tethered call and modem USD Diag.  Select modem tethered. 
6.  Restart phone
7.  Connect your phone to your computer via the USB
8.  The drivers will be installed via the device USB.
9.  Locate the modem on your computer and change the settings to prompt for user name and these values;
           number            *99***1#
           user name        WAP@CINGULARGPRS.COM
           password         CINGULAR1

****WARNING; USE THIS HACK AT YOUR OWN RISK****



Getting Started with Windows Phone

If your looking at getting started developing applications on the Windows 7 Phone platform here are some links to get you started;
Getting Started with Windows Phone (MSDN)http://msdn.microsoft.com/en-us/wp7trainingcourse_wp7gettingstarted_unit.aspx
Silverlight for Windows Phone; http://msdn.microsoft.com/en-us/wp7trainingcourse_wp7silverlight_unit.aspx
Get Started with Silverlight for Windows Phone Video; http://www.silverlight.net/learn/videos/all/get-started-with-silverlight-for-windows-phone/
MCSD Magazine Getting Started with Windows Phone Development Tools; http://msdn.microsoft.com/en-us/magazine/gg232764.aspx
Windows Phone 7 Training Course; http://msdn.microsoft.com/en-us/wp7trainingcourse.aspx

Microsoft SQL Server Denali CPT1 Released!

The SQL server team at MS just released the first CPT of the next version of SQL Server code named Denali.
A few of the areas that the team focused on were;
· Enhanced mission-critical platform: An enhanced highly available and scalable platform through the new SQL Server AlwaysOn for greater flexibility in achieving increased availability and data protection and new Column-Based Query Accelerator for huge performance gains in data warehousing.
· Developer and IT Productivity: A new unified development experience for data developers called SQL Server Developer Tools code-named “Juneau”, new beyond relational enhancements including FileTable for file storage within the SQL Server database, easier of use delivered via SQL Server AlwaysOn, data integration tools and features such as security & supportability.
· Pervasive Insight: Expand the reach of BI to business users via Project code-name “Crescent”, a highly interactive, web-based data exploration and visualization tool built on the breakthrough analytical performance of the VertiPaq technology. Meanwhile, holistic data integration and management tools through enhanced Master Data Services and new Data Quality Services will help ensure organizations can deliver the right data to the right users at the right time.
· Select capabilities of the new integrated high availability solution, SQL Server code-named “Denali” AlwaysOn, including availability groups, single active secondary for offloading read-only workloads and multi-site clustering
· Flexible server roles to allow administrators to create custom roles for ease separation of duties
· Simplified development and standardized deployment, configuration and management for SQL Server Integration Services
· Column-Based Query Accelerator will help dramatically increase query performance ~10x and reduce performance tuning through interactive experiences with data for near instant response times and streamlined setup which removes the need to build summary aggregates.
You can download the CPT at; http://www.microsoft.com/downloads/en/details.aspx?FamilyID=6a04f16f-f6be-4f92-9c92-f7e5677d91f9&displaylang=en
Reference
http://www.microsoft.com/sqlserver/en/us/product-info/future-editions.aspx
http://blogs.technet.com/b/dataplatforminsider/archive/2010/11/10/microsoft-dives-deeper-into-sql-server-code-named-denali-the-next-version-of-sql-server.aspx

Thursday, November 04, 2010

SQL Server Compact Toolbox

SQL Server Compact Toolbox add-in for Visual Studio 2010. Supports both version 3.5 and 4.0 of SQL Server Compact.
Adds several features to help your SQL Server Compact development efforts:
- Script tables, including data
- Script entire schema, optionally with data, both of SQL Server Compact and SQL Server 2005 or later databases
- Import to SQL Server Compact from a SQL Server 2005/2008 database or a CSV file
- Migrate from SQL Server Compact to SQL Server and SQL Azure
- Basic, free form query execution
- Parse SQL scripts
- Display graphical estimated execution plan
- Generate detailed DGML files for visualizing table columns and relationships (requires VS 2010 Premium or higher to view)
- Create and manage Merge Replication subscriptions

For support, full source code, a standalone version for 4.0 and feedback, go to:http://sqlcetoolbox.codeplex.com

For users not having Visual Studio 2010 Pro or higher installed, an add-in for 3.5 with similar functionality for the free SQL Server 2008 Management Studio Express and also command line versions  are available  here:http://exportsqlce.codeplex.com

New in version 1.6:
- Export to SQL Azure
- Launch the Toolbox directly from Server Explorer!
- Beta testing of Db Diff (scripting of database differences)
- other bug fixes, see http://sqlcetoolbox.codeplex.com/SourceControl/list/changesets

alt

alt

alt

alt

Tuesday, November 02, 2010

Silverlight is dead! Long live Silverlight!

While I was registered and packed for PDC10, I was sidelined by being behind on a critical project and a wife with a broken foot the day I was suppose to fly to SEA.  My disappointment in missing the event is only surpassed by the controversy over Silverlight/HTML5.

Did Microsoft do a poor job presenting there strategy or did we do a poor job listening?  I think a little of both.

My team and I have invested a lot in the Silverlight stack and plan on continuing for some time.  Below are some links to articles, blogs and such that I think address the confusion head on and reinforce my idea that Silverlight is here to stay.  At the same time HTML is undergoing dramatic changes that we need to keep a close eye on.

Bob Muglia on Microsoft's Silverlight Strategy, http://jpda.me/cw8p3r

Time Heuer’s Blog, http://jpda.me/9hljn0

Mary Joe Foley, http://jpda.me/aTIpCi

Steve Ballmer on PDC, http://jpda.me/aHy3qE

Scott Guthrie; The state of Silverlight, http://jpda.me/cW9dfx

Blog post on silverlight, http://jpda.me/apsNHd

Silverlight, HTML5 and your future blog post, http://jpda.me/cCzyHo

Friday, October 08, 2010

NuPack - Package Management System for the .NET platform Released

NuPack is a free, open source developer focused package management system for the .NET platform intent on simplifying the process of incorporating third party libraries into a .NET application during development.


There are a large number of useful 3rd party open source libraries out there for the .NET platform, but for those not familiar with the OSS ecosystem, it can be a pain to pull these libraries into a project.

NuPack is a free open source package manager that makes it easy for you to find, install, and use .NET libraries in your projects. It works with all .NET project types (including, but not limited to, both ASP.NET Web Forms and ASP.NET MVC).

NuPack enables developers who maintain open source projects (for example, projects like Moq, NHibernate, Ninject, StructureMap, NUnit, Windsor, RhinoMocks, Elmah, etc) to package up their libraries and register them with an online gallery/catalog that is searchable.  The client-side NuPack tools – which include full Visual Studio integration – make it trivial for any .NET developer who wants to use one of these libraries to easily find and install it within the project they are working on.

NuPack handles dependency management between libraries (for example: library1 depends on library2). It also makes it easy to update (and optionally remove) libraries from your projects later. It supports updating web.config files (if a package needs configuration settings). It also allows packages to add PowerShell scripts to a project (for example: scaffold commands). Importantly, NuPack is transparent and clean – and does not install anything at the system level. Instead it is focused on making it easy to manage libraries you use with your projects.

NuPack is itself an open-source project.  The Outercurve Foundation (formerly CodePlex Foundation) today announced the acceptance of the NuPack project to the ASP.NET Open Source Gallery.  Developers - both inside and outside Microsoft – will contribute features, bug fixes and patches to NuPack.

Our goal with NuPack is to make it as simple as possible to integrate open source libraries within .NET projects.  It will be supported in all versions of Visual Studio.  You can start using the first developer preview of it today.

Let’s take ELMAH as an example. It’s a fine error logging utility which has no dependencies on other libraries, but is still a challenge to integrate into a project. These are the steps it takes:

  1. Find ELMAH
  2. Download the correct zip package.
  3. “Unblock” the package.
  4. Verify its hash against the one provided by the hosting environment.
  5. Unzip the package contents into a specific location in the solution.
  6. Add an assembly reference to the assembly.
  7. Update web.config with the correct settings which a developer needs to search for.


And this is for a library that has no dependencies. Imagine doing this for NHibernate.Linq which has multiple dependencies each needing similar steps. We can do much better!
NuPack automates all these common and tedious tasks for a package as well as its dependencies. It removes nearly all of the challenges of incorporating a third party open source library into a project’s source tree. Of course, using that library properly is still up to the developer.
Here's a small sampling of what NuPack can do:

To get started using NuPack, you’ll need Visual Studio 2010 installed. NuPack is implemented as a Visual Studio Extension (VSIX). Download the latest release and double click on the NuPack.Tools.vsix file to launch the NuPack Visual Studio Extension Installer.

Visual Studio Extension Installer

Launching the Add Package Reference Dialog

There are two ways to interact with the package manager:

  • The Add Package Reference Dialog GUI, which gets you started quickly and easily.
  • The Powershell based Package Console, for when you need more power and tools.

Let’s start with the Add Package Reference dialog.

1. First, create a new VB.NET or C# application in Visual Studio.

By pure random chance, I’ve chosen to create an ASP.NET MVC 2 application.

2. Right click on the References node within the Solution Explorer and select the Add Package Reference menu option.

MvcApplication10 - Microsoft Visual Studio (Administrator) This will bring up the Add Package Reference dialog, seen here (click for larger).

Add Package Reference

The dialog allows you to page through the list of available NuPack packages as well as perform searches against the list of online package. The list of packages is being pulled from an ATOM feed, which can be configured using the Settings button.

Installing a Package

Installing a package is very easy now that we have the dialog up and running.

1. Find the package.

You can either page through the results, or use the search feature. In the Search Online box, type in “elmah”. You should see the following filtered view.

Add Package Reference (2)

2. Double click the Elmah entry.

That’s it! Behind the scenes, NuPack added the Elmah assembly into a subfolder of your solution, added an assembly reference to that assembly, and also modified your Web.config file with minimal settings to get you started. You’ll probably want to change those settings for a real application.

But you are all set to start using and programming against ELMAH. Visit /elmah.axd within your project to try it out.

Using the Package Console

For those who prefer using the keyboard, NuPack also includes a PowerShell based console for managing packages. The console enables a feature that isn’t available via the Add Package Reference dialog as you’ll see.

To get to the Package Console window, select the View | Other Windows | Package Manager Console menu option.

Start Page - Microsoft Visual Studio (Administrator)

1. Listing available Packages (List-Package)

Use the List-Package command to list available packages as seen in the screenshot. Note that you get intellisense within the console so if you type List and hit tab, you’ll see a list of options.

Package Manager Console - Microsoft Visual Studio (Administrator)

This queries the package source and lists the available packages. The nice thing about using PowerShell is that it provides a powerful way of filtering and composing commands. For example, if I only want to list the Id and Description, I can pipe the command to the select command List-Package | select Id, Description

2. Installing a package (Add-Package)

To install a package, run the Add-Package command and specify the Id.

MvcApplication8 - Microsoft Visual Studio (Administrator)

The package will be installed to the default project (specified in the console). You can use the –Project flag to explicitly specify the project.

The console also supplies Intellisense for the package Id.

MvcApplication8 - Microsoft Visual Studio (Administrator) (3)3. Installing new Console Commands

Earlier, I mentioned that the package console enables a feature that’s not available in the dialog. The feature in question is the ability for a package to contain tools which add new commands to the console.

For example, if you install the prototype Mvc-Scaffold package, a new Add-MvcView command is now available to be called from the console.

MvcApplication8 - Microsoft Visual Studio (Administrator) (5)

This provides a powerful way of extending and automating Visual Studio. In the future, this package might contain commands for completely scaffolding a web application from an object model or a database.

 

Scott Guthrie has posted a good blog on the topic as has Scott Hanselman.

NuPack – Open Source Package Manager for .NET

NuPack is a free open source package manager that makes it easy for you to find, install, and use .NET libraries in your projects. It works with all .NET project types (including, but not limited to, both ASP.NET Web Forms and ASP.NET MVC).

NuPack enables developers who maintain open source projects (for example, projects like Moq, NHibernate, Ninject, StructureMap, NUnit, Windsor, RhinoMocks, Elmah, etc) to package up their libraries and register them with an online gallery/catalog that is searchable.  The client-side NuPack tools – which include full Visual Studio integration – make it trivial for any .NET developer who wants to use one of these libraries to easily find and install it within the project they are working on.

NuPack handles dependency management between libraries (for example: library1 depends on library2). It also makes it easy to update (and optionally remove) libraries from your projects later. It supports updating web.config files (if a package needs configuration settings). It also allows packages to add PowerShell scripts to a project (for example: scaffold commands). Importantly, NuPack is transparent and clean – and does not install anything at the system level. Instead it is focused on making it easy to manage libraries you use with your projects.

NuPack is itself an open-source project.  The Outercurve Foundation (formerly CodePlex Foundation) today announced the acceptance of the NuPack project to the ASP.NET Open Source Gallery.  Developers - both inside and outside Microsoft – will contribute features, bug fixes and patches to NuPack.

Our goal with NuPack is to make it as simple as possible to integrate open source libraries within .NET projects.  It will be supported in all versions of Visual Studio.  You can start using the first developer preview of it today.

A Simple NuPack Scenario – Enabling ELMAH

As a simple example to show off what NuPack enables – let’s assume we are working on a brand new ASP.NET application and want to use the popular open-source “ELMAH” library to log and report errors with our site.  To install ELMAH today, you’d need to manually download it, unzip it, add a reference to your project, make sure you have source control bindings for the library setup correctly, and update the web.config file of your application to include the Elmah HttpModule entries.  All doable – but a little tedious.

With NuPack installed, you can simply open the new “Package Manager Console” that NuPack enables inside VS and type “Add-Package elmah” within it:

image

Typing "Add-Package elmah” causes NuPack to check an online feed to locate the Elmah library, download it, add a reference of it to your current project, and automatically add the appropriate Elmah registration entries within your application’s web.config file:

image

And now we have Elmah setup and installed for our project, and error report logging enabled.  No additional manual steps required to make it work.

Learn More About NuPack

Check out the following links to learn more about NuPack and some of the many scenarios it enables:

.NET and Open Source

We think NuPack will be a fundamental component of the .NET stack going forward.  It will encourage more .NET developers to use open-source libraries.  Having a standard package manager integrated into millions of copies of Visual Studio will hopefully also encourage the creation of more open source projects with .NET.

 

References

http://nupack.codeplex.com/

http://weblogs.asp.net/scottgu/archive/2010/10/06/announcing-nupack-asp-net-mvc-3-beta-and-webmatrix-beta-2.aspx

http://www.hanselman.com/blog/IntroducingNuPackPackageManagementForNETAnotherPieceOfTheWebStack.aspx

Wednesday, October 06, 2010

MVC in VB.NET Explained – An Introduction Written So You Can Understand It

If your new to MVC (Model, view, controller) and need a simple yet complete introduction to the topic this is a great article bu Dan Mabbut with About.com. (http://jpda.me/d06VCT).

MVC in VB.NET Explained, An Introduction Written So You Can Understand It.

In the beginning, there was Input-Process-Output. Everything since then is just more details.

That's literally true. The original computer, Eniac, input data about artillery, processed it, and spit out gunnery tables. But they soon learned that it could do so much more. They used it for computations necessary to create the first Hydrogen Bomb. (What would we do without war to underwrite invention?)

The way to understand MVC is to realize that it's just the latest detail on Input-Process-Output. Except that now, it's called Model-View-Controller. Model is Input, View is the Output, and Controller is Process. Sort of. Most authorities recommend that you put your "process" in "Model" and let "Controller" simply act as a switching function. But we're getting ahead of ourselves.

Although I'll be covering the same ground again, I've written several short articles about MVC:

Sorting Through the New Toys - MVC (April 28, 2010)

MVVM - A Fad or The Future? (May 27, 2010)

My new book, Pro ASP.NET 4 in VB 2010 also has a chapter about MVC where much more advanced concepts are explained, such as using MVC to create web pages based on an Entity Data Model generated from a database.

If you're a VB.NET programmer (and I assume that you are), then you now have your mind wrapped around something called the "event driven model". Just like MVC, programming this model depends on having a clear mental image of what the software does automatically and what you have to add. The key to doing MVC is to shift gears to a different mental image. So, let's consider event driven programming for just a second so we can contrast it with MVC.

When you write the standard "Hello World" program using event driven programming, you typically put a Button and a Label on a Form. When the Button is clicked, .NET creates an "event" called the "click event". Your task as a programmer is to anticipate that event and write the code that inserts a String into the Text property of a Label control.


Public Class Form1
Private Sub Button1_Click(
ByVal sender As System.Object,
ByVal e As System.EventArgs
) Handles Button1.Click
Label1.Text = "Hello World"
End Sub
End Class


The key here is that nothing works unless .NET generates that magical "event" that triggers the execution of your code. MVC is like that. You anticipate things that MVC does and then just insert your code into the right places to make the resulting system do what you want it to do. But you don't code for "events" anymore. (Well ... you can. But then you're working in parallel with MVC. MVC will allow you to insert event driven programming. But that works "on top of MVC" rather than being part of it. When learning MVC, the first thing to do is banish event driven programming from your mind.)



That's why the three circle diagram of MVC is used so much. (I've illustrated the first article linked above with the standard version.) Those three circles are the part that happens "automagically" and where you need to think about putting your code. Unfortunately, it's nowhere near as simple as Windows Forms, as we will see.



To see what the difference is, we're going to code a "Hello World" app using MVC from the ground up. That last part is important. Nearly every other example you will see on the web starts with a runable MVC shell app that is just modified. On the next page, we code an MVC app using the empty app template and add everything we need manually so you can understand what's there and why.



Step 1



You might already have VB.NET 2010 Express fired up and ready to go. Not so fast! Microsoft has chosen not to put any MVC templates in VB.NET Express. Right now, it's exclusively an ASP.NET web technology. So you have to have Visual Web Developer 2010 Express downloaded and fired up instead. (Fortunately, also free.) Or the full Visual Studio 2010 which can do anything.



Fundamentally, MVC is a "design pattern" and you could implement it by simply following the pattern and coding your own classes. I mention this because somebody will inevitably write in and tell me that "we don' need no steekin' templates". (Apologies to Treasure of the Sierra Madre.) Fundamentally, you could also code your own programs with nothing more than the vbc compiler and Notepad, too. We're talking about what's reasonable here.



So fire up Visual Web Developer 2010 Express and select New Project. Under Visual Basic and the Web subheading, you will see two likely templates:




  • ASP.NET MVC 2 Web Application


  • ASP.NET MVC 2 Empty Web Application



The first one is the one usually used. You can create a new project using that template and run it unchanged to get something like this:



--------

Click here to display the illustration.


--------



There's a lot going on there! And it's all included in the app. Here's the Solution Explorer view of the app:



--------

Click here to display the illustration.


--------



All of the code in those files fit together in an intricate interlocking scheme. Get one parameter out of place and it doesn't run. It's a lot easier to start with an app that already runs and then add, change, and delete to get what you want. But you don't learn as much, so we're going to start with an empty MVC app. When you do that, you get this result:



--------

Click here to display the illustration.


--------



Quite a difference. The error, by the way, is one of the most common ones that you will see as you learn to code using MVC. But all of the necessary pieces are still there. They just don't have the code to fit together anymore. That's what we're going to add. (But I'll still have to sprinkle "programmer pixie dust" in a few places before it will run.)



Step 2



Let's start at the data end: Models. In a realistic business app, the Models folder contains the code to interface with a database or some other source of data. Much of the actual processing takes place in the Models because an underlying philosophy of MVC is complete isolation of function. MVC gurus call this the "Single Responsibility Principal". The other parts of MVC, Controllers and Views, should not know or care where the data comes from. In a real world app, globalization, validation, authorization ... anything necessary to get the data ... will be found here.



In our little "Hello World" app, we only have one piece of data: the string "Hello World!" To add that to the Models folder, right-click the Models folder and add a class named HelloDataModel.vb. Here's the code that goes in this file:




Namespace MVCHelloWorld.Models
Public Class HelloDataModel
' The data: A Hello World string
Public Property theHello As String = "Hello World!"
End Class
End Namespace


It looks pretty simple because it's just one class containing one property. But it's not quite that simple because MVC ties together with names and all the names have to be present and match before it works. So, for example, you will find that you use the Namespace keyword a lot. In Windows Forms, you can pretty much ignore it most of the time. In a realistic app, much of the actual work is done by attributes that are used to decorate the classes. For example, in the boilerplate AccountModel file for the non-empty MVC app, the Password property is decorated with four attributes:




<Required()> _
<ValidatePasswordLength()> _
<DataType(DataType.Password)> _
<DisplayName("Password")> _
Public Property Password() As String
...


Often, these attributes have to be supported by other classes that you code. And so on and so on ...



On the next page, we code the heart of MVC, the controller.



Next, let's look at the controller. You can add a file named HelloController.vb to the Controller's folder by right-clicking the Controllers folder and selecting Add. Once you get the boilerplate in place, modify it as shown here:




Namespace MVCHelloWorld.Models
Public Class HelloController
Inherits System.Web.Mvc.Controller
Public Function Greet() As ActionResult
Dim theHelloGreeting As New HelloDataModel
ViewData("Message") =
theHelloGreeting.theHello
Return View()
End Function
End Class
End Namespace


The first thing to notice is that we use the same Namespace that we used in the Models. This won't always be the case. In MVC, things are organized into logical categories using namespaces. You could have several in your program.



The second thing to notice is that this class inherits System.Web.Mvc.Controller. That's where the class gets most of its core functionality. Controllers do things that you won't expect coming from a Windows Forms background because those functions are built into the parent.



And the third thing to notice is that the end product of this class is an ActionResult named Greet. The ActionResult types in the non-empty MVC app are named Index and About. The standard CRUD (Create-Read-Update-Delete) functions are all ActionResults in a real world app. List is an ActionResult. The controller classes usually don't do anything. They just decide what gets done next as a result of what they're passed. This one decides that displaying a greeting should be done next. But it doesn't actually display it. That's done by a view.



Once you have coded the controller, you can also create a view by right-clicking the code in the controller.



--------

Click here to display the illustration.


--------



The Microsoft team has done some good work supporting MVC in their development tools. The linkage between controllers and views is one of the more intricate ways that MVC ties together and they've made it somewhat easier. But the dialog window that is displayed next will still raise a lot of questions if you haven't seen it before.



--------

Click here to display the illustration.


--------



To make things easier, I copied a Master Page from another project and then modified it to remove all the things I wouldn't use. A master page isn't required, but it's a good idea. Here's the page I used:




<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title><asp:ContentPlaceHolder
ID="TitleContent" runat="server" /></title>
<link href="../../Content/Site.css"
rel="stylesheet" type="text/css" />
</head>

<body>
<div class="page">
<div id="main">
<asp:ContentPlaceHolder
ID="MainContent" runat="server" />
</div>
</div>
</body>
</html>


You can see that things are still linking together by name. For example, you'll see the ID MainContent again in the view, which we consider next.



If you used the dialog to create the view, you will notice that both a Hello folder and a Greet.aspx file in the folder have been added for you. The .aspx files in Views aren't normal .aspx files. For one thing, there is no corresponding .vb code behind file. You don't do any processing in Views, so there is no place to put code. I modified the Greet.aspx file to contain this code:




<%@ Page Title="" Language="VB"
MasterPageFile="~/Views/Shared/Site.Master"
Inherits="System.Web.Mvc.ViewPage" %>
<asp:Content ID="Content1"
ContentPlaceHolderID="MainContent" runat="server">
<h1><%=ViewData("Message") %></h1>
</asp:Content>


The ViewData object is just a keyed dictionary. In this case, Message is the key. It was created in the controller. A lot of MVC purists don't like this technique because (they say) the controller shouldn't be doing any processing. Because MVC is still under active development, and there are lots of other flavors other than the Microsoft brand, you'll see this sort of debate if you start reading about it.



You might think that you're finished now. You might be wrong. There's still more plumbing to put in place and on the next page, we complete the app.



The final code we need is in a file that has been there in other ASP.NET applications, but is used a lot more in MVC: Global.asax. Actually, the code is in the partial code-behind class, Global.asax.vb. (There are also sections added to Web.config to make routing work, but you normally don't have to do anything with them, so you can delay figuring out what they do.) The primary thing that is added to Global.asax is routing. This is a critical part of MVC and defines how incoming browser requests are mapped to particular MVC controller actions. Routing instructions are created in a table when the application is started. The Application_Start() subroutine executes another sub:




RegisterRoutes(RouteTable.Routes)


RegisterRoutes actually builds the table with a series of instructions that are helpfully documented in comments in Global.asax along with the default that is used in the non-empty MVC app:




' MapRoute takes the following parameters, in order:
' (1) Route name
' (2) URL with parameters
' (3) Parameter defaults
routes.MapRoute( _
"Default", _
"{controller}/{action}/{id}", _
New With {.controller = "Home",
.action = "Index",
.id = UrlParameter.Optional} _
)


This is why MVC apps don't use normal looking URL's. A typical MVC URL might look like this:




http://myDomain.com/Home/Index/3


The routing table will send this to the Home controller; the Index action; and pass the parameter 3, which is often an index into a database.



Routing instructions in the table are used in sequence. If an earlier table entry satisfies the incoming browser request, then later entries aren't used. You can code these table entries so that multiple requests will "match" table entries for enormous flexibility (and not just a little complexity too). For this reason, you will normally place your routing instructions above the generated entries that are already in Global.asax. In my case, I didn't use a Home controller or an Index action, so I recoded the default this way:




routes.MapRoute(
"Default", "{controller}/{action}",
New With {
.controller = "Hello",
.action = "Greet"
})

So for my app, the "Default" url will call Hello.Greet() with this result:

--------

Click here to display the illustration.


--------



Ta-Da!!!



If you think this is a lot of trouble to display "Hello World!" you're right. The main features of MVC do not include simplicity; they include long term application maintainability, flexible design, and efficient execution. (For example, there are no No ViewState and PostBack events clog up the network.) But it does take some getting used to!

Tuesday, September 28, 2010

LINQ – Language Integrated Query 101

This is a collection of information related to LINQ.  The primary purpose is to provide a reference for getting started with LINQ.

LINQ is a set of extensions to the .NET Framework that encompass language-integrated query, set, and transform operations. It extends C# and Visual Basic with native language syntax for queries and provides class libraries to take advantage of these capabilities.

Language-Integrated Query (LINQ) is an innovation introduced in Visual Studio 2008 and .NET Framework version 3.5 that bridges the gap between the world of objects and the world of data.

Traditionally, queries against data are expressed as simple strings without type checking at compile time or IntelliSense support. Furthermore, you have to learn a different query language for each type of data source: SQL databases, XML documents, various Web services, and so on. LINQ makes a query a first-class language construct in C# and Visual Basic. You write queries against strongly typed collections of objects by using language keywords and familiar operators. The following illustration shows a partially-completed LINQ query against a SQL Server database in C# with full type checking and IntelliSense support.

LINQ query with Intellisense

In Visual Studio you can write LINQ queries in Visual Basic or C# with SQL Server databases, XML documents, ADO.NET Datasets, and any collection of objects that supports IEnumerable or the generic IEnumerable(Of T) interface. LINQ support for the ADO.NET Entity Framework is also planned, and LINQ providers are being written by third parties for many Web services and other database implementations.

You can use LINQ queries in new projects, or alongside non-LINQ queries in existing projects. The only requirement is that the project target .NET Framework 3.5 or later.

A query is an expression that retrieves data from a data source. Queries are expressed in a dedicated query language. Over time, different languages have been developed for different types of data sources, for example, SQL for relational databases and XQuery for XML. This makes it necessary for the application developer to learn a new query language for each type of data source or data format that is supported.

Language-Integrated Query (LINQ) simplifies the situation by offering a consistent model for working with data across various kinds of data sources and formats. In a LINQ query, you are always working with objects. You use the same basic coding patterns to query and transform data in XML documents, SQL databases, ADO.NET datasets and entities, .NET Framework collections, and any other source or format for which a LINQ provider is available. This document describes the three phases of the creation and use of basic LINQ queries.

Three Stages of a Query Operation


LINQ query operations consist of three actions:

  1. Obtain the data source or sources.

  2. Create the query.

  3. Execute the query.

In LINQ, the execution of a query is distinct from the creation of the query. You do not retrieve any data just by creating a query. This point is discussed in more detail later in this topic.

The following example illustrates the three parts of a query operation. The example uses an array of integers as a convenient data source for demonstration purposes. However, the same concepts also apply to other data sources.

' Data source.
Dim numbers() As Integer = {0, 1, 2, 3, 4, 5, 6}

' Query creation.
Dim evensQuery = From num In numbers
                 Where num Mod 2 = 0
                 Select num

' Query execution.
For Each number In evensQuery
    Console.Write(number & " ")
Next

Output:

0 2 4 6

The Data Source


Because the data source in the previous example is an array, it implicitly supports the generic IEnumerable(Of T) interface. It is this fact that enables you to use an array as a data source for a LINQ query. Types that support IEnumerable(Of T), or a derived interface such as the generic IQueryable(Of T), are called queryable types.

As an implicitly queryable type, the array requires no modification or special treatment to serve as a LINQ data source. The same is true for any collection type that supports IEnumerable(Of T), including the generic List(Of T), Dictionary(Of TKey, TValue), and other classes in the .NET Framework class library.

If the source data does not already implement IEnumerable(Of T), a LINQ provider is needed to implement the functionality of the standard query operators for that data source. For example, LINQ to XML handles the work of loading an XML document into a queryable XElement type, as shown in the following example. For more information about standard query operators, see Standard Query Operators Overview.

' Create a data source from an XML document.
Dim contacts = XElement.Load("c:\myContactList.xml")

With LINQ to SQL, you first create an object-relational mapping at design time, either manually or by using the Object Relational Designer (O/R Designer). You write your queries against the objects, and at run-time LINQ to SQL handles the communication with the database. In the following example, customers represents a specific table in the database, and Table(Of TEntity) supports generic IQueryable(Of T).

' Create a data source from a SQL table.
Dim db As New DataContext("C:\Northwind\Northwnd.mdf")
Dim customers As Table(Of Customer) = db.GetTable(Of Customer)

For more information about how to create specific types of data sources, see the documentation for the various LINQ providers. (For a list of these providers, see Language-Integrated Query (LINQ).) The basic rule is simple: a LINQ data source is any object that supports the generic IEnumerable(Of T) interface, or an interface that inherits from it.

NoteNote

Types such as ArrayList that support the non-generic IEnumerable interface can also be used as LINQ data sources. For an example that uses an ArrayList, see How to: Query an ArrayList with LINQ.

The Query


In the query, you specify what information you want to retrieve from the data source or sources. You also have the option of specifying how that information should be sorted, grouped, or structured before it is returned. To enable query creation, Visual Basic has incorporated new query syntax into the language.

When it is executed, the query in the following example returns all the even numbers from an integer array, numbers.

' Data source.
Dim numbers() As Integer = {0, 1, 2, 3, 4, 5, 6}

' Query creation.
Dim evensQuery = From num In numbers
                 Where num Mod 2 = 0
                 Select num

' Query execution.
For Each number In evensQuery
    Console.Write(number & " ")
Next

The query expression contains three clauses: From, Where, and Select. The specific function and purpose of each query expression clause is discussed in Basic Query Operations (Visual Basic). For more information, see Queries (Visual Basic). Note that in LINQ, a query definition often is stored in a variable and executed later. The query variable, such as evensQuery in the previous example, must be a queryable type. The type of evensQuery is IEnumerable(Of Integer), assigned by the compiler using local type inference.

It is important to remember that the query variable itself takes no action and returns no data. It only stores the query definition. In the previous example, it is the For Each loop that executes the query.

Query Execution


Query execution is separate from query creation. Query creation defines the query, but execution is triggered by a different mechanism. A query can be executed as soon as it is defined (immediate execution), or the definition can be stored and the query can be executed later (deferred execution).

Deferred Execution

A typical LINQ query resembles the one in the previous example, in which evensQuery is defined. It creates the query but does not execute it immediately. Instead, the query definition is stored in the query variable evensQuery. You execute the query later, typically by using a For Each loop, which returns a sequence of values, or by applying a standard query operator, such as Count or Max. This process is referred to as deferred execution.

' Query execution that results in a sequence of values.
For Each number In evensQuery
    Console.Write(number & " ")
Next

' Query execution that results in a single value.
Dim evens = evensQuery.Count()

For a sequence of values, you access the retrieved data by using the iteration variable in the For Each loop (number in the previous example). Because the query variable, evensQuery, holds the query definition rather than the query results, you can execute a query as often as you want by using the query variable more than one time. For example, you might have a database in your application that is being updated continually by a separate application. After you have created a query that retrieves data from that database, you can use a For Each loop to execute the query repeatedly, retrieving the most recent data every time.

The following example demonstrates how deferred execution works. After evensQuery2 is defined and executed with a For Each loop, as in the previous examples, some elements in the data source numbers are changed. Then a second For Each loop runs evensQuery2 again. The results are different the second time, because the For Each loop executes the query again, using the new values in numbers.

Dim numberArray() = {0, 1, 2, 3, 4, 5, 6}

Dim evensQuery2 = From num In numberArray
                  Where num Mod 2 = 0
                  Select num

Console.WriteLine("Evens in original array:")
For Each number In evensQuery2
    Console.Write("  " & number)
Next
Console.WriteLine()

' Change a few array elements.
numberArray(1) = 10
numberArray(4) = 22
numberArray(6) = 8

' Run the same query again.
Console.WriteLine(vbCrLf & "Evens in changed array:")
For Each number In evensQuery2
    Console.Write("  " & number)
Next
Console.WriteLine()

Output:

Evens in original array:

0 2 4 6

Evens in changed array:

0 10 2 22 8

Immediate Execution

In deferred execution of queries, the query definition is stored in a query variable for later execution. In immediate execution, the query is executed at the time of its definition. Execution is triggered when you apply a method that requires access to individual elements of the query result. Immediate execution often is forced by using one of the standard query operators that return single values. Examples are Count, Max, Average, and First. These standard query operators execute the query as soon as they are applied in order to calculate and return a singleton result. For more information about standard query operators that return single values, see Aggregation Operations, Element Operations, and Quantifier Operations.

The following query returns a count of the even numbers in an array of integers. The query definition is not saved, and numEvens is a simple Integer.

Dim numEvens = (From num In numbers
                Where num Mod 2 = 0
                Select num).Count()

You can achieve the same result by using the Aggregate method.

Dim numEvensAgg = Aggregate num In numbers
                  Where num Mod 2 = 0
                  Select num
                  Into Count()

You can also force execution of a query by calling the ToList or ToArray method on a query (immediate) or query variable (deferred), as shown in the following code.

' Immediate execution.
Dim evensList = (From num In numbers
                 Where num Mod 2 = 0
                 Select num).ToList()

' Deferred execution.
Dim evensQuery3 = From num In numbers
                  Where num Mod 2 = 0
                  Select num
' . . .
Dim evensArray = evensQuery.ToArray()

In the previous examples, evensQuery3 is a query variable, but evensList is a list and evensArray is an array.

Using ToList or ToArray to force immediate execution is especially useful in scenarios in which you want to execute the query immediately and cache the results in a single collection object. For more information about these methods, see Converting Data Types.

You can also cause a query to be executed by using an IEnumerable method such as the IEnumerable.GetEnumerator method.

The standard query operators are the methods that form the Language-Integrated Query (LINQ) pattern. Most of these methods operate on sequences, where a sequence is an object whose type implements the IEnumerable(Of T) interface or the IQueryable(Of T) interface. The standard query operators provide query capabilities including filtering, projection, aggregation, sorting and more.

There are two sets of LINQ standard query operators, one that operates on objects of type IEnumerable(Of T) and the other that operates on objects of type IQueryable(Of T). The methods that make up each set are static members of the Enumerable and Queryable classes, respectively. They are defined as extension methods of the type that they operate on. This means that they can be called by using either static method syntax or instance method syntax.

In addition, several standard query operator methods operate on types other than those based on IEnumerable(Of T) or IQueryable(Of T). The Enumerable type defines two such methods that both operate on objects of type IEnumerable. These methods, Cast(Of TResult)(IEnumerable) and OfType(Of TResult)(IEnumerable), let you enable a non-parameterized, or non-generic, collection to be queried in the LINQ pattern. They do this by creating a strongly-typed collection of objects. The Queryable class defines two similar methods, Cast(Of TResult)(IQueryable) and OfType(Of TResult)(IQueryable), that operate on objects of type Queryable.

The standard query operators differ in the timing of their execution, depending on whether they return a singleton value or a sequence of values. Those methods that return a singleton value (for example, Average and Sum) execute immediately. Methods that return a sequence defer the query execution and return an enumerable object.

In the case of the methods that operate on in-memory collections, that is, those methods that extend IEnumerable(Of T), the returned enumerable object captures the arguments that were passed to the method. When that object is enumerated, the logic of the query operator is employed and the query results are returned.

In contrast, methods that extend IQueryable(Of T) do not implement any querying behavior, but build an expression tree that represents the query to be performed. The query processing is handled by the source IQueryable(Of T) object.

Calls to query methods can be chained together in one query, which enables queries to become arbitrarily complex.

The following code example demonstrates how the standard query operators can be used to obtain information about a sequence.

Dim sentence = "the quick brown fox jumps over the lazy dog"
' Split the string into individual words to create a collection.
Dim words = sentence.Split(" "c)

Dim query = From word In words
            Group word.ToUpper() By word.Length Into gr = Group
            Order By Length _
            Select Length, GroupedWords = gr

Dim output As New System.Text.StringBuilder
For Each obj In query
    output.AppendLine(String.Format("Words of length {0}:", obj.Length))
    For Each word As String In obj.GroupedWords
        output.AppendLine(word)
    Next
Next

'Display the output
MsgBox(output.ToString())

' This code example produces the following output:
'
' Words of length 3:
' THE
' FOX
' THE
' DOG
' Words of length 4:
' OVER
' LAZY
' Words of length 5:
' QUICK
' BROWN
' JUMPS

Query Expression Syntax


Some of the more frequently used standard query operators have dedicated C# and Visual Basic language keyword syntax that enables them to be called as part of a query expression. For more information about standard query operators that have dedicated keywords and their corresponding syntaxes, see Query Expression Syntax for Standard Query Operators.

Extending the Standard Query Operators


You can augment the set of standard query operators by creating domain-specific methods that are appropriate for your target domain or technology. You can also replace the standard query operators with your own implementations that provide additional services such as remote evaluation, query translation, and optimization. See AsEnumerable(Of TSource) for an example.

References;

Video on getting started with LINQ, ttp://msdn.microsoft.com/en-us/vbasic/bb735955.aspx

Video on writing LINQ, http://msdn.microsoft.com/en-us/library/bb820884(VS.90).aspx

Guy Burstein’s Blog on Like Operators, http://blogs.microsoft.co.il/blogs/bursteg/archive/2007/10/16/linq-to-sql-like-operator.aspx

Guy Burstein’s LINQ blog posts, http://blogs.microsoft.co.il/blogs/bursteg/archive/tags/LINQ/default.aspx

Microsoft LINQ Developer Center, http://msdn.microsoft.com/en-us/netframework/aa904594.aspx

Microsoft LINQ sorting, http://msdn.microsoft.com/en-us/library/bb546145.aspx

Microsoft LINQ filtering, http://msdn.microsoft.com/en-us/library/bb546161.aspx

Microsoft LINQ set operations, http://msdn.microsoft.com/en-us/library/bb546153.aspx

Microsoft LINQ quantifier operations, http://msdn.microsoft.com/en-us/library/bb546128.aspx

Friday, September 24, 2010

Microsoft Visual Basic .Net CPT for Windows Phone Developer Tools Released!

Many of you have asked if Visual Basic can be used to write Windows Phone applications. 

As of today, the answer is "yes!"

Starting today, you can download Microsoft Visual Basic CTP for Windows Phone Developer Tools.  This is a great milestone as it enables our Visual Basic developers to be able to build applications for Windows Phone.

Applications built using the CTP run on both the emulator and the phone. To try the CTP, you'll need the final version of Windows Phone Developer Tools and Visual Studio 2010 Professional or higher. If you don't have Visual Studio 2010 Professional, you can install the free trial of Visual Studio Professional

The CTP includes Visual Studio 2010 project templates, item templates, designer support, emulator support, debugging, and IntelliSense for Visual Basic.  After installing the CTP, Visual Studio 2010 Professional and higher users will find Windows Phone project types for Visual Basic in the New Project Dialog, as you can see below.

Wednesday, September 08, 2010

Resource Refactoring Tool

Microsoft http://resourcerefactoring.codeplex.com/

Resource Refactoring Tool provides developers an easy way to extract hard coded strings from the code to resource files.

Features for Resource Refactoring Tool

  • Works with C#, VB.Net languages. Supports all project types that ships with Visual Studio 2005 including web sites and web application projects.
  • A preview window to show changes.
  • Finds other instances of the text being replaced in the project automatically.
  • Lists existing resources by their similarity level to the text being replaced.
  • Automatically replaces hard coded string with a reference to resource entry.

Quick Start to using Resource Refactoring Tool
  1. Run ResourceRefactor.msi to install. If you have any earlier version please uninstall those versions first and run Visual Studio at least once before installing the new version.
  2. Launch Visual Studio 2005
  3. Open either a VB.Net or C# project
  4. Right click on a hard coded string in a a code window and choose Refactor - Extract to resource. If you don't see the menu item and you had a previous version of Resource Refactoring Tool installed before, you may have to reset the addin by running Visual Studio from Visual Studio 2005 Command Prompt with the following arguments: devenv.exe /resetaddin Microsoft.VSPowerToys.ResourceRefactor.Connect. This should fix the missing menu items.
  5. RefactoringTool-Menu.png
  6. Choose the resource file you want to use and either choose an existing resource or create a new one. After closing the dialog window, string will automatically be replaced with the reference to resource you have chosen.

RefactoringTool-Window.png
Contributing to Resource Refactoring Tool
We're looking for developers to join us in future releases. Check out the current work items at issue tracker.
Feel free to contribute by
  1. Reading Getting Started with Resource Refactoring Tool Development.
  2. Either creating new or finding existing bugs or feature requests you want to work on
  3. Leave a note in the comments that you're going to investigate this bug (until you have developer rights, you won't be able to assign bugs to yourself)
  4. Download the latest sources and create a bug fix
  5. Zip up your changes and post them as an attachment to the work item
  6. Fill out the Project_Assignment_Agreement.TIF form and follow the Assignment Agreement Instructions to send it to us.

Note that by posting your submission to the Issue Tracker, you agree to do so under the CodePlex TOU
Join the Community
There are numerous ways you can participate in the Resource Refactoring Tool community
  • Blog about Resource Refactoring Tool
  • Ask and answer questions regarding Resource Refactoring Tool on the discussions tab
  • Fix bugs or check in new features - see above section