Showing posts with label VS 2008. Show all posts
Showing posts with label VS 2008. Show all posts

24 June, 2010

Testing Email Sending

Testing Email Sending: "
Recently I learned a couple of interesting things related to sending emails. One doesnt relate to .NET at all, so if youre a developer and you want to easily be able to test whether or not emails are working correctly in your application without actually sending them and/or installing a real SMTP server on your machine, pay attention. You can grab the smtp4dev application from codeplex, which will listen for SMTP emails and log them for you (and will even pop-up from the system tray to notify you when it receives them) but it will never send them. Heres what the notification looks like:
image
The other interesting tidbit about emails that is specific to .NET is that the MailMessage class is IDisposable. I never realized that before, but I noticed it while reading through the Ben Watsons C# 4 How To book I picked up at TechEd last week (which is done cookbook style and has a ton of useful info in it). Looking at the MailMessages Dispose() method in Reflector reveals that it only really matters if youre working with AlternateViews or Attachments (this.bodyView is also of type AlternateView):
image
All the same, you should get in the habit of wrapping your calls to MailMessage in a using() { } block. Heres some sample code showing how I would typically work with MailMessage:
Bad Example (dont cut and paste and use):
string fromAddress = "nobody@somewhere.com";



string toAddress = "somebody@somewhere.com";



string subject = "Test Message from IDisposable";



string body = "This is the body.";



var myMessage = new MailMessage(fromAddress, toAddress, subject, body);






var myClient = new SmtpClient("localhost");



myClient.Send(myMessage);




And heres how that code would look once its properly set up using IDisposable / using:


Good Example (use this one!):




string fromAddress = "nobody@somewhere.com";



string toAddress = "somebody@somewhere.com";



string subject = "Test Message from IDisposable";



string body = "This is the body.";






using(var myMessage = new MailMessage(fromAddress, toAddress, subject, body))



using(var myClient = new SmtpClient("localhost"))



{



myClient.Send(myMessage);                



}






Note also that SmtpClient is also IDisposable, and that you can stack your using() statements without introducing extra { } when you have instances where you need to work with several Disposable objects (like in this case).


Note that if you run Code Analysis in VS2010 (not sure which version you have to have right click on a project in your solution explorer and look for Analyze Code) you will get warnings for any IDisposable classes youre using outside of using statements, like these:


image




Summary


Sometimes things you dont expect to be Disposable are. Its good to run some code analysis tools from time to time to help find things like this. Visual studio has some nice static analysis built into some versions, or you can use less expensive tools like Fx Cop or Nitriq.

31 May, 2010

ASP.NET: Using pickup directory for outgoing e-mails

ASP.NET: Using pickup directory for outgoing e-mails: "
Sending e-mails out from web applications is very common task. When we are working on or test our systems with real e-mail addresses we don’t want recipients to receive e-mails (specially if we are using some subset of real data9. In this posting I will show you how to make ASP.NET SMTP client to write e-mails to disc instead of sending them out.

SMTP settings for web application

I have seen many times the code where all SMTP information is kept in app settings just to read them in code and give to SMTP client. It is not necessary because we can define all these settings under system.web => mailsettings node.
If you are using web.config to keep SMTP settings then all you have to do in your code is just to create SmtpClient with empty constructor.

var smtpClient = new SmtpClient();

Empty constructor means that all settings are read from web.config file.

What is pickup directory?

If you want drastically raise e-mail throughput of your SMTP server then it is not very wise plan to communicate with it using SMTP protocol. it adds only additional overhead to your network and SMTP server. Okay, clients make connections, send messages out and it is also overhead we can avoid.
If clients write their e-mails to some folder that SMTP server can access then SMTP server has e-mail forwarding as only resource-eager task to do. File operations are way faster than communication over SMTP protocol. The directory where clients write their e-mails as files is called pickup directory.
By example, Exchange server has support for pickup directories. And as there are applications with a lot of users who want e-mail notifications then .NET SMTP client supports writing e-mails to pickup directory instead of sending them out.

How to configure ASP.NET SMTP to use pickup directory?

Let’s say, it is more than easy. It is very easy. This is all you need.

<system.net>
<mailSettings>
<smtp deliveryMethod="SpecifiedPickupDirectory">
<specifiedPickupDirectory pickupDirectoryLocation="c:\temp\maildrop\"/>
</smtp>
</mailSettings>
</system.net>

Now make sure you don’t miss come points:
  1. Pickup directory must physically exist because it is not created automatically.
  2. IIS (or Cassini) must have write permissions to pickup directory.
  3. Go through your code and look for hardcoded SMTP settings. Also take a look at all places in your code where you send out e-mails that there are not some custom settings used for SMTP!
Also don’t forget that your mails will be written now to pickup directory and they are not sent out to recipients anymore.

Advanced scenario: configuring SMTP client in code

In some advanced scenarios you may need to support multiple SMTP servers. If configuration is dynamic or it is not kept in web.config you need to initialize your SmtpClient in code. This is all you need to do.

var smtpClient = new SmtpClient();
smtpClient.DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory;
smtpClient.PickupDirectoryLocation = pickupFolder;

Easy, isn’t it? i like when advanced scenarios end up with simple and elegant solutions but not with rocket science.

Note for IIS SMTP service

SMTP service of IIS is also able to use pickup directory. If you have set up IIS with SMTP service you can configure your ASP.NET application to use IIS pickup folder. In this case you have to use the following setting for delivery method.

SmtpDeliveryMethod.PickupDirectoryFromIis

You can set this setting also in web.config file.

<system.net>
<mailSettings>
<smtp deliveryMethod="PickupDirectoryFromIis" />
</mailSettings>
</system.net>

Conclusion

Who was still using different methods to avoid sending e-mails out in development or testing environment can now remove all the bad code from application and live on mail settings of ASP.NET. It is easy to configure and you have less code to support e-mails when you use built-in e-mail features wisely.

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.

04 May, 2010

Visual Studio 2010 Extension Manager (and the new VS 2010 PowerCommands Extension)

Visual Studio 2010 Extension Manager (and the new VS 2010 PowerCommands Extension): "

Extensibility in VS 2010

VS 2010 provides a much richer extensibility model than previous releases. Anyone can build extensions that add, customize, and light-up the Visual Studio 2010 IDE, Code Editors, Project System and associated Designers.
VS 2010 Extensions can be created using the new MEF (Managed Extensibility Framework) which is built-into .NET 4. You can learn more about how to create VS 2010 extensions from this this blog post from the Visual Studio Team Blog.

VS 2010 Extension Manager

Developers building extensions can distribute them on their own (via their own web-sites or by selling them).
Visual Studio 2010 also now includes a built-in “Extension Manager” within the IDE that makes it much easier for developers to find, download, and enable extensions online. You can launch the “Extension Manager” by selecting the Tools->Extension Manager menu option:
image
This loads an “Extension Manager” dialog which accesses an “online gallery” at Microsoft, and then populates a list of available extensions that you can optionally download and enable within your copy of Visual Studio:
image
There are already hundreds of cool extensions populated within the online gallery. You can browse them by category (use the tree-view on the top-left to filter them). Clicking “download” on any of the extensions will download, install, and enable it.

PowerCommands for Visual Studio 2010

This weekend Microsoft released the free PowerCommands for Visual Studio 2010 extension to the online gallery. You can learn more about it here, and download and install it via the “Extension Manager” above (search for PowerCommands to find it).
The PowerCommands download adds dozens of useful commands to Visual Studio 2010. Below is a screen-shot of just a few of the useful commands that it adds to the Solution Explorer context menus:
image
Below is a list of all the commands included with this weekend’s PowerCommands for Visual Studio 2010 release:

  • Enable/Disable PowerCommands in Options dialog
    This feature allows you to select which commands to enable in the Visual Studio IDE. Point to the Tools menu, then click Options. Expand the PowerCommands options, then click Commands. Check the commands you would like to enable.
    Note: All power commands are initially defaulted Enabled.
  • Format document on save / Remove and Sort Usings on save
    The Format document on save option formats the tabs, spaces, and so on of the document being saved. It is equivalent to pointing to the Edit menu, clicking Advanced, and then clicking Format Document. The Remove and sort usings option removes unused using statements and sorts the remaining using statements in the document being saved.
    Note: The Remove and sort usings option is only available for C# documents. Format document on save and Remove and sort usings both are initially defaulted OFF.
  • Clear All Panes
    This command clears all output panes. It can be executed from the button on the toolbar of the Output window.
  • Copy Path
    This command copies the full path of the currently selected item to the clipboard. It can be executed by right-clicking one of these nodes in the Solution Explorer:
    The solution node; A project node; Any project item node; Any folder.
  • Email CodeSnippet
    To email the lines of text you select in the code editor, right-click anywhere in the editor and then click Email CodeSnippet.
  • Insert Guid Attribute
    This command adds a Guid attribute to a selected class. From the code editor, right-click anywhere within the class definition, then click Insert Guid Attribute.
  • Show All Files
    This command shows the hidden files in all projects displayed in the Solution Explorer when the solution node is selected. It enhances the Show All Files button, which normally shows only the hidden files in the selected project node.
  • Undo Close
    This command reopens a closed document , returning the cursor to its last position. To reopen the most recently closed document, point to the Edit menu, then click Undo Close. Alternately, you can use the CtrlShiftZ shortcut.
    To reopen any other recently closed document, point to the View menu, click Other Windows, and then click Undo Close Window. The Undo Close window appears, typically next to the Output window. Double-click any document in the list to reopen it.
  • Collapse Projects
    This command collapses a project or projects in the Solution Explorer starting from the root selected node. Collapsing a project can increase the readability of the solution. This command can be executed from three different places: solution, solution folders and project nodes respectively.
  • Copy Class
    This command copies a selected class entire content to the clipboard, renaming the class. This command is normally followed by a Paste Class command, which renames the class to avoid a compilation error. It can be executed from a single project item or a project item with dependent sub items.
  • Paste Class
    This command pastes a class entire content from the clipboard, renaming the class to avoid a compilation error. This command is normally preceded by a Copy Class command. It can be executed from a project or folder node.
  • Copy References
    This command copies a reference or set of references to the clipboard. It can be executed from the references node, a single reference node or set of reference nodes.
  • Paste References
    This command pastes a reference or set of references from the clipboard. It can be executed from different places depending on the type of project. For CSharp projects it can be executed from the references node. For Visual Basic and Website projects it can be executed from the project node.
  • Copy As Project Reference
    This command copies a project as a project reference to the clipboard. It can be executed from a project node.
  • Edit Project File
    This command opens the MSBuild project file for a selected project inside Visual Studio. It combines the existing Unload Project and Edit Project commands.
  • Open Containing Folder
    This command opens a Windows Explorer window pointing to the physical path of a selected item. It can be executed from a project item node
  • Open Command Prompt
    This command opens a Visual Studio command prompt pointing to the physical path of a selected item. It can be executed from four different places: solution, project, folder and project item nodes respectively.
  • Unload Projects
    This command unloads all projects in a solution. This can be useful in MSBuild scenarios when multiple projects are being edited. This command can be executed from the solution node.
  • Reload Projects
    This command reloads all unloaded projects in a solution. It can be executed from the solution node.
  • Remove and Sort Usings
    This command removes and sort using statements for all classes given a project. It is useful, for example, in removing or organizing the using statements generated by a wizard. This command can be executed from a solution node or a single project node.
  • Extract Constant
    This command creates a constant definition statement for a selected text. Extracting a constant effectively names a literal value, which can improve readability. This command can be executed from the code editor by right-clicking selected text.
  • Clear Recent File List
    This command clears the Visual Studio recent file list. The Clear Recent File List command brings up a Clear File dialog which allows any or all recent files to be selected.
  • Clear Recent Project List
    This command clears the Visual Studio recent project list. The Clear Recent Project List command brings up a Clear File dialog which allows any or all recent projects to be selected.
  • Transform Templates
    This command executes a custom tool with associated text templates items. It can be executed from a DSL project node or a DSL folder node.
  • Close All
    This command closes all documents. It can be executed from a document tab.

How to temporarily disable extensions

Extensions provide a great way to make Visual Studio even more powerful, and can help improve your overall productivity. One thing to keep in mind, though, is that extensions run within the Visual Studio process (DevEnv.exe) and so a bug within an extension can impact both the stability and performance of Visual Studio.
If you ever run into a situation where things seem slower than they should, or if you crash repeatedly, please temporarily disable any installed extensions and see if that fixes the problem. You can do this for extensions that were installed via the online gallery by re-running the extension manager (using the Tools->Extension Manager menu option) and by selecting the “Installed Extensions” node on the top-left of the dialog – and then by clicking “Disable” on any of the extensions within your installed list:
image

30 April, 2010

Download and Share Visual Studio Color Schemes

Download and Share Visual Studio Color Schemes: "
As developers we often spend a large part of our day staring at code within Visual Studio. If you are like me, after awhile the default VS text color scheme starts to get a little boring.
The good news is that Visual Studio allows you to completely customize the editor background and text colors to whatever you want – allowing you to tweak them to create the experience that is “just right” for your eyes and personality. You can then optionally export/import your color scheme preferences to an XML file via the Tools >>Import and Export Settings menu command.

New website that makes it easy to download and share VS color schemes

Luke Sampson launched the http://studiostyles.info/ site a week ago (built using ASP.NET MVC 2, ASP.NET 4 and VS 2010).
Studiostyles.info enables you to easily browse and download Visual Studio color schemes that others have already created. The color schemes work for both VS 2008 and VS 2010 (all versions – including the free VS express editions):
image
Color schemes are sorted by popularity and voting (you can vote on whether you find each “hot or not”).
You can click any of the schemes to see screen-shots of it in use for common coding scenarios. You can then download the color settings for either VS 2010 or VS 2008:
image
You can also optionally upload color schemes of your own if you have a good one you want to share with others.
If you haven’t visited it yet – check it out: http://studiostyles.info/ And thank you Luke Sampson for building it!