Showing posts with label Visual Basic 10. Show all posts
Showing posts with label Visual Basic 10. Show all posts

20 May, 2010

String.Format("{0}", "formatting string"};


One of the painful things about good old ASP was string formatting, VBScript
simply didn't have anything useful. C# (and VB.Net) do, but MSDN doesn't provide
a quick reference to the formatting options. So here's a quick reference.


To compare string formatting in C# to those in C lets have an example,

char szOutput[256];

sprintf(szOutput, "At loop position %d.\n", i);


sprintf takes an output buffer, a format string and any number of arguments to
substitute into the format string.

The C# equivalent for sprintf is String.Format, which takes a format string and
the arguments. It returns a string, and because you're not passing in a buffer
there's no chance of a buffer overflow.

string outputString = String.Format("At loop position {0}.\n", i);

So why doesn't have the format argument have parameters specifying what data
type you're formatting? The CLR objects have metadata which informs the CLR what
the objects are, and each object has a standard ToString() method which returns
a string representation of that object. Much nicer than C where if you passed
the wrong type of variable into sprintf everything could come crashing down.

The ToString method can accept a string parameter which tells the object how to
format itself. In the call to String.Format , the formatting string is passed
after the position, for example, "{0:##}". The text inside the curly braces is
{argumentIndex[,alignment][:formatString]}. If alignment is positive, the text
is right-padding to fill the specified field length, if it's negative, it's
left-padded.

formatting strings

There's not much formatting that can be applied to a string. Only the padding /
alignment formatting options can be applied. These options are also available to
every argument, regardless of type.


example

output

String.Format("--{0,10}--", "test");

-- test--

String.Format("--{0,-10}--", "test");

--test --


formatting numbers

Number formatting is culture dependant. For
example, formatting a currency string on my laptop will return a result like
£9.99, formatting a currency on a machine set for the US region would return
$9.99.


specifier

type

format

output

(double 1.2345)

output

(int -12345)

c

currency

{0:c}

£1.23

-£12,345.00

d

decimal

(whole number)

{0:d}

System.FormatException

-12345

e

exponent / scientific

{0:e}

1.234500e+000

-1.234500e+004

f

fixed point

{0:f}

1.23

-12345.00

g

general

{0:g}

1.2345

-12345

n

number

{0:n}

1.23

-12,345.00

r

round trippable

{0:r}

1.23

System.FormatException

x

hexadecimal

{0:x4}

System.FormatException

ffffcfc7


custom number formatting



specifier

type

format

output

(double 1234.56)

0

zero placeholder

{0:00.000}

1234.560

#

digit placeholder

{0:#.##}

1234.56

.

decimal point placeholder

{0:0.0}

1234.6

,

thousand separator

{0:0,0}

1,235

%

percentage

{0:0%}

123456%


In addition there is the group separator; this is useful for varying the format,
depending on the value of the parameter passed. For example

String.Format("{0:£#,##0.00;(£#,##0.00);Nothing}", value);


This will output "£1,240.00" if passed 1243.56. It will output the same
format bracketed if the value is negative "(£1,240.00)", and will output the
string "Nothing" if the number is zero.


date formatting


Date formats are very dependant on the culture
information passed. The examples below are shown using the UK culture.


specifier

type

output

(June 8, 1970 12:30:59)

d

Short Date

08/06/1970

D

Long Date

08 June 1970

t

Short Time

12:30

T

Long Time

12:30:59

f

Full date and time

08 June 1970 12:30

F

Full date and time (long)

08 June 1970 12:30:59

g

Default date and time

08/06/1970 12:30

G

Default date and time (long)

08/06/1970 12:30:59

M

Day / Month

8 June

r

RFC1123 date string

Mon, 08 Jun 1970 12:30:59 GMT

s

Sortable date/time

1970-06-08T12:30:59

u

Universal time, local timezone

1970-06-08 12:30:59Z

Y

Month / Year

June 1970


custom date formatting



specifier

type

output

(June 8, 1970 12:30:59)

dd

Day

08

ddd

Short Day Name

Mon

dddd

Full Day Name

Monday

hh

2 digit hour

12

HH

2 digit hour (24 hour)

12

mm

2 digit minute

30

MM

Month

06

MMM

Short Month name

Jun

MMMM

Month name

June

ss

seconds

59

tt

AM/PM

PM

yy

2 digit year

70

yyyy

4 digit year

1970

:

seperator, e.g. {0:hh:mm:ss}

12:30:59

/

seperator, e.g. {0:dd/MM/yyyy}

08/06/1970


There are others, including time zone formatting and so on, but the ones above
are the most commonly used.


culture information


string.format also provides a method which accepts a

CultureInfo
argument, as an IFormatProvider. This is important when trying
to write portable and localisable code, as, for example, month names will change
according to the local culture of the machine you are running on. Rather than
simply call the standard String.Format you should consider always calling the
overloaded culture method. If you don't need to specify a culture you can use
the System.Globalization.CultureInfo.InvariantCulture. This will then default
your formatting to English, as opposed to the culture of the current thread.

22 April, 2010

Visual Basic 2010 Language Enhancements

Introduction

Earlier this month Microsoft released Visual Studio 2010, the .NET Framework 4.0 (which includes ASP.NET 4.0), and new versions of their core programming languages: C# 4.0 and Visual Basic 10 (also referred to as Visual Basic 2010). Previously, the C# and Visual Basic programming languages were managed by two separate teams within Microsoft, which helps explain why features found in one language was not necessarily found in the other. For example, C# 3.0 introduced collection initializers, which enable developers to define the contents of a collection when declaring it; however, Visual Basic 9 did not support collection initializers. Conversely, Visual Basic has long supported optional parameters in methods, whereas C# did not.

Recently, Microsoft merged the Visual Basic and C# teams to help ensure that C# and Visual Basic grow together. As explained by Microsoft program manager Jonathan Aneja, "The intent is to make the languages advance together. When major functionality is introduced in one language, it should appear in the other as well. ... [T]hat any task you can do in one language should be as simple in the other." To this end, with version 4.0 C# now supports optional parameters and named arguments, two features that have long been part of Visual Basic's vernacular. And, likewise, Visual Basic has been updated to include a number of C# features that it was previously missing.

This article explores some of these new features that were added to Visual Basic 2010. Read on to learn more! 

Implicit Line Continuation (It's About Time!)

All programming languages use some character to denote the end of a statement. C-flavored languages (like C#) use the semicolon to mark the end of a statement, whereas the Basic programming language has long used the carriage return. One downside of using the carriage return as the statement delimiter is that it prohibits developers from having a single statement span multiple lines.

Consider the following function declaration:


Public Function ChangePassword(ByVal Username As String, ByVal OldPassword As String, ByVal NewPassword As String) As Boolean

   ...

End Function

We could improve the readability of the function declaration by having each input parameter on its own line. But doing so would confuse the compiler, as it presumes that a carriage return denotes the end of a statement. In the past, Visual Basic allowed for a single statement to be spread over multiple lines by using the line continuation character, an underscore (_). Using the line continuation character we could rewrite the above function declaration to span multiple lines like so:


Public Function ChangePassword(ByVal Username As String, _

                               ByVal OldPassword As String, _

                               ByVal NewPassword As String) As Boolean

   ...

End Function

Note the underscore after the Username and OldPassword input parameters.

Visual Basic 2010 still supports the use of the underscore as an explicit line continuation character, but it also supports implicit line continuation. Thanks to implicit line continuation in VB 2010, you can now continue lines of code on a new line without having to use the underscore character. For example, the above function declaration could be rewritten to omit the underscores, as the below screen shot illustrates.


Look ma, no underscores!


In short, the Visual Basic 2010 compiler allows you to omit the underscore when continuing a statement on the next consecutive line. It's natural to wonder how VB can distinguish between a carriage return that signifies a line continuation and one that signifies the end of a statement. There are certain syntax elements that cannot be used to end a statement and if VB notes a carriage return after one of these it can safely assume that the carriage return is meant as a line continuation character and not as the end of the statement. The following table lists the some of the syntax elements that, when followed by a carriage return, is treated as an implicit line continuation character by the compiler.


After a comma

After an open parenthesis or before a closing parenthesis

After an open curly brace or before a closing curly brace

After an open embedded expression (<%=) or before the close of an embedded expression (%>) within an XML literal

After the concatenation operator (&)

After assignment operators (=, &=, +=, ...)

After binary operators (+, -, And, Or, ...) within an expression

After the Is and IsNot operators

After a member qualifier character (.) and before the member name

For a complete list of the syntax elements as well as for examples of the above syntax elements in use, refer to the Statements in Visual Basic documentation's "Implicit Line Continuation" section.

Auto-Implemented Properties

When creating a class it's quite common to have one or more properties that don't include any logic in their getters or setters; instead, the property serves merely as a mechanism to expose a member variable. Most every Visual Basic developer has written code that looks like the following at some point or another:


Public Class Product

   Private _ProductName As String

   Private _UnitCost As Decimal

   

   Public Property ProductName As String

      Get

         Return _ProductName

      End Get

      Set (ByVal value As String)

         _ProductName = value

      End Set

   End Property



   Public Property ProductName As Decimal

      Get

         Return _UnitCost

      End Get

      Set (ByVal value As Decimal)

         _UnitCost = value

      End Set

   End Property

End Class

Having to write all that boilerplate property code seems redundant and a waste of time. What made it more frustrating was that C# 3.0 introduced auto-implemented properties, which allowed C# developers to create such simple properties with far less syntax. For more information on C#'s auto-implemented properties, consult Auto-Implemented Properties (C# Programming Guide).

The good news is that VB 2010 now has auto-implemented properties! You can turn the above property and private member variable declarations into just two lines of code using this new feature. To use auto-implemented properties use the following syntax:


Property PropertyName As Type

That's all there is to it! The screen shot below shows the much more concise property syntax for the Product class created above. Note how auto-implemented properties allowed us to reduce the property-related lines of code from 18 down to two!


Auto-implemented properties have been added to Visual Basic 2010.

Auto-implemented properties are an example of syntactic sugar - the new syntax makes the code easier to read and write for us developers, but, behind the scenes, it's business as usual. Specifically, the VB compiler automatically converts the auto-implemented property syntax into a private member variable and an expanded property with getters and setters.

One thing to note is that there are some subtle differences between VB's auto-implemented properties and C#'s. C# allows for read-only and write-only auto-implemented properties; it also allows different access methods (public, private, etc.) for the getters and setters. Visual Basic does not provide such flexibility. If you need to define read-only or write-only properties, or need different accessibility levels for the getter and setter, you'll need to use the expanded property definition syntax. However, with Visual Basic's auto-implemented properties you can specify an initial value for the property like so:


Property PropertyName As Type = Initial_Value

The following screen shot shows the syntax to specify an initial value for the ProductName and UnitCost properties in the Person class, namely "Chai" and 4.95, respectively.


Auto-implemented properties can have an initial value specified.

Collection Initializers

Both C# 3.0 and Visual Basic 9 introduced object initializers, which allow developers to declare and assign default values to the new object's properties all in one statement. C# 3.0 also added collection initializers, which allow developers to declare a collection and add elements to it in one statement; unfortunately, VB 9 did not include support for collection initializers. The good news is that collection initializers have been added to Visual Basic 2010!

Prior to VB 2010, creating a collection and specifying its elements required quite a few lines of code. The following code snippet shows the declaration of a List of Integers named Fib that is populated with the first eight Fibonacci numbers:


Dim Fib As New List(Of Integer)



Fib.Add(0)

Fib.Add(1)

Fib.Add(1)

Fib.Add(2)

Fib.Add(3)

Fib.Add(5)

Fib.Add(8)

Fib.Add(13)

Using collection initializers, the above syntax can be greatly compressed. Use the From keyword to specify the collection's initial elements. The following screen shot shows VB 2010 code that uses collection initializers to reduce the sheer volume of code and to improve the code's readability.


Specify the initial elements in a collection using VB 2010's collection initializers.

And, if you like, you can also use implicit line continuation to separate out the initial values on separate lines:


You can use implicit line continuation with the collection initializer syntax.


Conclusion

With it's release of Visual Studio 2010 and the .NET Framework 4, Microsoft has also released the latest versions of its two most popular .NET programming languages: C# and Visual Basic. Over the past couple of years Microsoft has worked to help unify the C# and Visual Basic feature sets and to ensure that these two languages grow together. To this end, Visual Basic has been updated with a number of language enhancements that were previously added to C#, including implicit line continuation, auto-implemented properties, and collection initializers. Conversely, C# has been updated to include a number of VB features that were previously missing. A future article will explore these C# 4.0 additions

13 April, 2010

Visual Studio 2010 and .NET 4 Released

The final release of Visual Studio 2010 and .NET 4 is now available.



Download and Install Today

MSDN subscribers, as well as WebsiteSpark/BizSpark/DreamSpark members, can now download the final releases of Visual Studio 2010 and TFS 2010 through the MSDN subscribers download center.
If you are not an MSDN Subscriber, you can download free 90-day trial editions of Visual Studio 2010.
Or you can can download the free Visual Studio express editions of Visual Web Developer 2010, Visual Basic 2010, Visual C# 2010 and Visual C++. These express editions are available completely for free (and never time out). If you are looking for an easy way to setup a new machine for web-development you can automate installing ASP.NET 4, ASP.NET MVC 2, IIS, SQL Server Express and Visual Web Developer 2010 Express really quickly with the Microsoft Web Platform Installer (just click the install button on the page).

What is new with VS 2010 and .NET 4

Today’s release is a big one – and brings with it a ton of new feature and capabilities.
One of the things we tried hard to focus on with this release was to invest heavily in making existing applications, projects and developer experiences better. What this means is that you don’t need to read 1000+ page books or spend time learning major new concepts in order to take advantage of the release. There are literally thousands of improvements (both big and small) that make you more productive and successful without having to learn big new concepts in order to start using them.
Below is just a small sampling of some of the improvements with this release:
Visual Studio 2010 IDE
Visual Studio 2010 now supports multiple-monitors (enabling much better use of screen real-estate). It has new code Intellisense support that makes it easier to find and use classes and methods. It has improved code navigation support for searching code-bases and seeing how code is called and used. It has new code visualization support that allows you to see the relationships across projects and classes within projects, as well as to automatically generate sequence diagrams to chart execution flow.
The editor now supports HTML and JavaScript snippet support as well as improved JavaScript intellisense. The VS 2010 Debugger and Profiling support is now much, much richer and enables new features like Intellitrace (aka Historical Debugging), debugging of Crash/Dump files, and better parallel debugging. VS 2010’s multi-targeting support is now much richer, and enables you to use VS 2010 to target .NET 2, .NET 3, .NET 3.5 and .NET 4 applications. And the infamous Add Reference dialog now loads much faster.
TFS 2010 is now easy to setup (you can now install the server in under 10 minutes) and enables great source-control, bug/work-item tracking, and continuous integration support. Testing support (both automated and manual) is now much, much richer. And VS 2010 Premium and Ultimate provide much better architecture and design tooling support.
VB and C# Language Features
VB and C# in VS 2010 both contain a bunch of new features and capabilities. VB adds new support for automatic properties, collection initializers, and implicit line continuation support among many other features. C# adds support for optional parameters and named arguments, a new dynamic keyword, co-variance and contra-variance, and among many other features.
ASP.NET 4 and ASP.NET MVC 2
With ASP.NET 4, Web Forms controls now render clean, semantically correct, and CSS friendly HTML markup. Built-in URL routing functionality allows you to expose clean, search engine friendly, URLs and increase the traffic to your Website. ViewState within applications can now be more easily controlled and made smaller. Client IDs rendered by server controls can now be controlled. ASP.NET Dynamic Data support has been enhanced. More controls, including rich charting and data controls, are now built-into ASP.NET 4 and enable you to build applications even faster. New starter project templates now make it easier to get going with new projects. SEO enhancements make it easier to drive traffic to your public facing sites. And web.config files are now clean and simple.
ASP.NET MVC 2 is now built-into VS 2010 and ASP.NET 4, and provides a great way to build web sites and applications using a model-view-controller based pattern. ASP.NET MVC 2 adds features to easily enable client and server validation logic, provides new strongly-typed HTML and UI-scaffolding helper methods. It also enables more modular/reusable applications. The new <%: %> syntax in ASP.NET makes it easier to HTML encode output. Visual Studio 2010 also now includes better tooling support for unit testing and TDD. In particular, “Consume first intellisense” and “generate from usage" support within VS 2010 make it easier to write your unit tests first, and then drive your implementation from them.
Deploying ASP.NET applications gets a lot easier with this release. You can now publish your Websites and applications to a staging or production server from within Visual Studio itself. Visual Studio 2010 makes it easy to transfer all your files, code, configuration, database schema and data in one complete package. VS 2010 also makes it easy to manage separate web.config configuration files settings depending upon whether you are in debug, release, staging or production modes.
WPF 4 and Silverlight 4
WPF 4 includes a ton of new improvements and capabilities including more built-in controls, richer graphics features (cached composition, pixel shader 3 support, layoutrounding, and animation easing functions), a much improved text stack (with crisper text rendering, custom dictionary support, and selection and caret brush options). WPF 4 also includes a bunch of support to enable you to take advantage of new Windows 7 features – including multi-touch and Windows 7 shell integration.
Silverlight 4 will launch this week as well. You can watch my Silverlight 4 launch keynote streamed live Tuesday (April 13th) at 8am Pacific Time. Silverlight 4 includes a ton of new capabilities – including a bunch for making it possible to build great business applications and out of the browser applications. I’ll be doing a separate blog post later this week (once it is live on the web) that talks more about its capabilities.
Visual Studio 2010 now includes great tooling support for both WPF and Silverlight. The new VS 2010 WPF and Silverlight designer makes it much easier to build client applications as well as build great line of business solutions, as well as integrate and bind with data. Tooling support for Silverlight 4 with the final release of Visual Studio 2010 will be available when Silverlight 4 releases to the web this week.
SharePoint and Azure
Visual Studio 2010 now includes built-in support for building SharePoint applications. You can now create, edit, build, and debug SharePoint applications directly within Visual Studio 2010. You can also now use SharePoint with TFS 2010.
Support for creating Azure-hosted applications is also now included with VS 2010 – allowing you to build ASP.NET and WCF based applications and host them within the cloud.
Data Access
Data access has a lot of improvements coming to it with .NET 4. Entity Framework 4 includes a ton of new features and capabilities – including support for model first and POCO development, default support for lazy loading, built-in support for pluralization/singularization of table/property names within the VS 2010 designer, full support for all the LINQ operators, the ability to optionally expose foreign keys on model objects (useful for some stateless web scenarios), disconnected API support to better handle N-Tier and stateless web scenarios, and T4 template customization support within VS 2010 to allow you to customize and automate how code is generated for you by the data designer.
In addition to improvements with the Entity Framework, LINQ to SQL with .NET 4 also includes a bunch of nice improvements.
WCF and Workflow
WCF includes a bunch of great new capabilities – including better REST, activation and configuration support. WCF Data Services (formerly known as Astoria) and WCF RIA Services also now enable you to easily expose and work with data from remote clients.
Windows Workflow is now much faster, includes flowchart services, and now makes it easier to make custom services than before. More details can be found here.
CLR and Core .NET Library Improvements
.NET 4 includes the new CLR 4 engine – which includes a lot of nice performance and feature improvements. CLR 4 engine now runs side-by-side in-process with older versions of the CLR – allowing you to use two different versions of .NET within the same process. It also includes improved COM interop support.
The .NET 4 base class libraries (BCL) include a bunch of nice additions and refinements. In particular, the .NET 4 BCL now includes new parallel programming support that makes it much easier to build applications that take advantage of multiple CPUs and cores on a computer. This work dove-tails nicely with the new VS 2010 parallel debugger (making it much easier to debug parallel applications), as well as the new F# functional language support now included in the VS 2010 IDE. .NET 4 also now also has the Dynamic Language Runtime (DLR) library built-in – which makes it easier to use dynamic language functionality with .NET. MEF – a really cool library that enables rich extensibility – is also now built-into .NET 4 and included as part of the base class libraries.
.NET 4 Client Profile
The download size of the .NET 4 redist is now much smaller than it was before (the x86 full .NET 4 package is about 36MB). We also now have a .NET 4 Client Profile package which is a pure sub-set of the full .NET that can be used to streamline client application installs.
Visual C++
VS 2010 includes a bunch of great improvements for C++ development. This includes better C++ Intellisense support, MSBuild support for projects, improved parallel debugging and profiler support, MFC improvements, and a number of language features and compiler optimizations.




My VS 2010 and .NET 4 Blog Series

I’ve been cranking away on a blog series the last few months that highlights many of the new VS 2010 and .NET 4 improvements. The good news is that I have about 20 in-depth posts already written. The bad news (for me) is that I have about 200 more to go until I’m done! I’m going to try and keep adding a few more each week over the next few months to discuss the new improvements and how best to take advantage of them.
Below is a list of the already written ones that you can check out today:




Stay tuned to my blog as I post more. Also check out this page which links to a bunch of great articles and videos done by others.




VS 2010 Installation Notes

If you have installed a previous version of VS 2010 on your machine (either the beta or the RC) you must first uninstall it before installing the final VS 2010 release. I also recommend uninstalling .NET 4 betas (including both the client and full .NET 4 installs) as well as the other installs that come with VS 2010 (e.g. ASP.NET MVC 2 preview builds, etc). The uninstalls of the betas/RCs will clean up all the old state on your machine – after which you can install the final VS 2010 version and should have everything just work (this is what I’ve done on all of my machines and I haven’t had any problems).
The VS 2010 and .NET 4 installs add a bunch of new managed assemblies to your machine. Some of these will be “NGEN’d” to native code during the actual install process (making them run fast). To avoid adding too much time to VS setup, though, we don’t NGEN all assemblies immediately – and instead will NGEN the rest in the background when your machine is idle. Until it finishes NGENing the assemblies they will be JIT’d to native code the first time they are used in a process – which for large assemblies can sometimes cause a slight performance hit.
If you run into this you can manually force all assemblies to be NGEN’d to native code immediately (and not just wait till the machine is idle) by launching the Visual Studio command line prompt from the Windows Start Menu (Microsoft Visual Studio 2010->Visual Studio Tools->Visual Studio Command Prompt). Within the command prompt type “Ngen executequeueditems” – this will cause everything to be NGEN’d immediately.




How to Buy Visual Studio 2010

You can can download and use the free Visual Studio express editions of Visual Web Developer 2010, Visual Basic 2010, Visual C# 2010 and Visual C++. These express editions are available completely for free (and never time out).
You can buy a new copy of VS 2010 Professional that includes a 1 year subscription to MSDN Essentials for $799. MSDN Essentials includes a developer license of Windows 7 Ultimate, Windows Server 2008 R2 Enterprise, SQL Server 2008 DataCenter R2, and 20 hours of Azure hosting time. Subscribers also have access to MSDN’s Online Concierge, and Priority Support in MSDN Forums.
Upgrade prices from previous releases of Visual Studio are also available. Existing Visual Studio 2005/2008 Standard customers can upgrade to Visual Studio 2010 Professional for a special $299 retail price until October. You can take advantage of this VS Standard to Professional upgrade promotion here.
Web developers who build applications for others, and who are either independent developers or who work for companies with less than 10 employees, can also optionally take advantage of the Microsoft WebSiteSpark program. This program gives you three copies of Visual Studio 2010 Professional, 1 copy of Expression Studio, and 4 CPU licenses of both Windows 2008 R2 Web Server and SQL 2008 Web Edition that you can use to both develop and deploy applications with at no cost for 3 years. At the end of the 3 years there is no obligation to buy anything. You can sign-up for WebSiteSpark today in under 5 minutes – and immediately have access to the products to download.