Advanced Language Concepts in C# Anonymous Methods

Advanced Language Concepts in C#
Session 4
Last Update: 3/09
David Figge
dfigge@u.washington.edu
Page 1
Copyright (C) 2009 by David Figge. All Rights Reserved.
Where We’re at, Where We’re Going…
Advanced Language Concepts in C#
Last Update: 3/09
Page 2
Copyright (C) 2009 by David Figge. All Rights Reserved.
Class 3 Schedule






Session 1:

Review, Introductions

Language INtegrated Query (LINQ)
Session 2:

More Linq (continued)
Session 3:

Still More Linq (continued)
Session 4:

Creating tables in a Database

Attributes
Session 5:

Relationships and Referential
Integrity
Session 6:

Displaying XML data with DataGrid

Nullable Types

SQL Security Concepts

.Net Security
Last Update: 3/09




Page 3
Session 7:

Class Libraries

Namespaces and Assemblies

Versioning

Global Assembly Cache (GAC)

Extern Aliases
Session 8:

Multi-Threading
Session 9:

Anonymous Methods

Integrating Help

Localization

Windows Setup/Click-Once
Deployment
Session 10:

Final Project
Copyright (C) 2009 by David Figge. All Rights Reserved.
Anonymous Methods
Advanced Language Concepts in C#
Last Update: 3/09
Page 4
Copyright (C) 2009 by David Figge. All Rights Reserved.
Anonymous Methods

Anonymous Methods are simply a way of
specifying code for a method without actually
creating a fully named method




It’s sort of a shortcut way to create (typically
small) functions for one-time use
Specifically, it’s used to specify function code for
a delegate
Anonymous methods are never required, but
many developers find them easier than
creating small functions that are only used in
one place
For an example, recall our PrintProgress
function in our Address program

It’s job was to simply pass on the percentage
printed…
Last Update: 3/09
Page 5
Copyright (C) 2009 by David Figge. All Rights Reserved.
Anonymous
Here weMethods
set the
ProgressChanged delegate to
the PrintProgress
function.
EventArgs
e)
private void btnPrint_Click(object sender,
{
BackgroundWorker printthread = new BackgroundWorker();
printthread.DoWork += Print;
printthread.ProgressChanged += PrintProgress;
printthread.RunWorkerCompleted += PrintCompleted;
printthread.WorkerReportsProgress = true;
printthread.WorkerSupportsCancellation = true;
This is the
original code for
the btnPrint click
event…
The PrintProgress function is a perfect candidate
for an anonymous
It is small and simple,
printform = new frmPrint(printthread);
// function:
Create form
and it’s used//
in only
one place (by the
printthread.RunWorkerAsync();
Callthat
DoWork()
delegate) … so let’s modify it to
// Display form, if ProgressChanged
cancelled say so
be an anonymous method instead…
if (printform.ShowDialog() == DialogResult.Cancel)
MessageBox.Show("Printing Aborted");
}
private void PrintProgress(object sender, ProgressChangedEventArgs e)
{
printform.UpdateProgress(e.ProgressPercentage);
}
Last Update: 3/09
Page 6
Copyright (C) 2009 by David Figge. All Rights Reserved.
Anonymous Methods
Next are
It starts with the keywordIf the function
hadthe
noparameters.
parameters,(The
we names had to
private void btnPrint_Click(object sender,
be
changed
soincluding
they e)
didn’t
delegate. Inside
This says
we’re
using
would
leave
themEventArgs
out
theconflict with the
the
braces
is
the
code
of
the
{
parameters
the btnPrint_Click
function.)
an anonymous
method.
parenthesis
(i.e. … +=of
delegate
{ … }; )
method (makes
sense…),
BackgroundWorker
printthread
= referencing
new BackgroundWorker();
printthread.DoWork
+= Print;
the parameters
sndr and pce.
//printthread.ProgressChanged += PrintProgress;
printthread.ProgressChanged +=
delegate(object sndr, ProgressChangedEventArgs pce)
{
printform.UpdateProgress(pce.ProgressPercentage);
};
printthread.RunWorkerCompleted += PrintCompleted;
printthread.WorkerReportsProgress = true;
and move it here. Notice
printthread.WorkerSupportsCancellation =…true;
the definition of the
So, we remove
the original
printform = new frmPrint(printthread);
// Create
formmethod…
anonymous
printthread.RunWorkerAsync(); // Call DoWork()
code…
// Display form, if cancelled say so
if (printform.ShowDialog() == DialogResult.Cancel)
MessageBox.Show("Printing Aborted");
}
//private void PrintProgress(object sender, ProgressChangedEventArgs e)
//{
//
printform.UpdateProgress(e.ProgressPercentage);
Make Sense?
//}
Last Update: 3/09
Page 7
Copyright (C) 2009 by David Figge. All Rights Reserved.
Anonymous Methods Summary



So, an anonymous method is a nameless method.
Anonymous Methods can be used for any delegate
Allows you to create a single method (used by only one
delegate) instead of having to define a named function.



You can use parameters with delegates


If not, no parenthesis needed
The C# compiler at compile time





Many people feel that this is cleaner and more convenient than a
named method.
Anonymous methods can substituted for delegates as parameters,
return values, and in other situations.
Validates the signature of the delegate—no out parameters
Infers the signature of the anonymous method from the delegate
Confirms that the return type of the delegate is compatible with
the anonymous method
Creates a new delegate that is initialized with a function pointer
to the anonymous method
Anonymous methods are purely a convenience

Questions on
There is no required place where they must be used.
Anonymous Methods?
Last Update: 3/09
Page 8
Copyright (C) 2009 by David Figge. All Rights Reserved.
Localization
Advanced Language Concepts in C#
Last Update: 3/09
Page 9
Copyright (C) 2009 by David Figge. All Rights Reserved.
Localization


Localization is the process of making
an application adapt to and work in
multiple languages and cultures
Visual Studio and .Net make it very
easy to support multiple languages



First, .Net automatically recognizes the
local settings and adapts
Secondly, Visual Studio allows easy
modification of existing forms to support
multiple cultures and languages
Let’s see how this all comes together…
Last Update: 3/09
Page 10
Copyright (C) 2009 by David Figge. All Rights Reserved.
System.Globalization

Localization ultimately boils down to two aspects




Modifying the formatting of numbers, dates, calendars, etc. to
match the region’s customs
Converting the text into the language for the region
The System.Globalization namespace holds information and
classes to support date formats, number formats, calendars
(GregorianCalendar, HebrewCalendar, JapaneseCalendar, etc)
.Net takes the set of preferences based on a user’s language
and cultural habits and breaks them into two pieces



The CultureInfo class represents a culture and defines calendars,
number and date formats, and sorting rules within the culture
The RegionInfo class represents things like currency and use of
the metric system
Note that these are connected but independent


One region can use multiple languages, and one language can be used in
multiple regions
Cultures are given names depending on a language and a country
or region

Last Update: 3/09
en-AU, en-CA, en-GB, en-US covers English in Australia, Canada, the UK,
and the US
Page 11
Copyright (C) 2009 by David Figge. All Rights Reserved.
Localization in Practice

.Net automatically recognizes the culture
and region information for the current
system installation



This means that – if you use .Net’s methods
for number, currency, and DateTime display –
the correct formats will be used automatically
So, unless you’re building a date string by
hand, you don’t really need to worry about
those aspects
The textual language aspects are not as
automatic – you still have to translate the
text you use into other languages

However, incorporating these changes is
made much easier by Visual Studio…
Last Update: 3/09
Page 12
Copyright (C) 2009 by David Figge. All Rights Reserved.
Localization in Visual Studio

Language issues within the app fall into
two categories



Items included within forms
Text referenced from within the code
Text within forms

When you create a form, you automatically
start in the ‘default’ language


This is the language that will be used if you don’t
have specific coverage for the language of the
current region
To add support for another language



Last Update: 3/09
Go to the Form properties
Select another language
Modify the form to support that language
Page 13
Copyright (C) 2009 by David Figge. All Rights Reserved.
Localization in Visual Studio
The images and text you use will
be the “default” value and will
display in all culture/languages
unless
youwith,
override
To begin
start it.
with the
language set to (Default)
Once you have all the default
text and graphics the way you
like it, then move to other
languages…
Last Update: 3/09
Page 14
Copyright (C) 2009 by David Figge. All Rights Reserved.
Localization in Visual Studio
Once you’ve
selected another
language…
Any text/images you
don’tthe
want
change
Change
texttoand
graphics
there isthat
any)language.
can be
to(ifsupport
just left
alone.
Changing
the
size and
location of controls is
acceptable and supported.
Let’s look at my
CountryExample Demo…
Last Update: 3/09
Page 15
Copyright (C) 2009 by David Figge. All Rights Reserved.
Localization in Visual Studio

Culture/Language specific changes



All changes – including text, placement and size
of controls, etc. – are saved in a culture/language
specific ‘satellite’ assembly in a subdirectory (like
fr-FR)
This assembly is automatically loaded when the
culture/language of the machine matches one
that you have
.Net also supports you in localizing strings
used within your code (“string literals”)


To do this, you have to define a table of strings
you’ll use, with language specific versions of each
string.
Here are the steps…
Last Update: 3/09
Page 16
Copyright (C) 2009 by David Figge. All Rights Reserved.
Localization of String Literals

First, save the text being localized into text file
TextStrings.de.txt
Good Day = Guten Tag
Good Night
= Guten Nacht
TextStrings.fr.txt
Goodbye = Auf Weidersehen
Day = Bonjour
Hello =Good
Hallo
Hi = HiGood Night = Bonsoir
Goodbye
= Au Revoir
Bye = Auf
Weidersehen
Hello = Bonjour
Hi = Salut
Bye = Salut

One line per string, key = string



You’ll use the key in your code to load the string
When you do, the string will be loaded and displayed
The default file would be something like
MyStrings.txt, with the Spanish version
Making sense
MyStrings.es-ES.Text, French MyStrings.fr-FR.txt…
so far?
Last Update: 3/09
Page 17
Copyright (C) 2009 by David Figge. All Rights Reserved.
Localization of String Literals

Next, convert these text files into
embeddable resources with resgen



This is a command-line utility with VS
Ex: Resgen TextStrings.txt TextStrings.resx
Finally, add these to your project



Use Add/Existing Item
Build Action sets to Embedded Resource, and
– as the project is built – the strings will be
added to the satellite assembly for that
language
These strings, like other resources, are
accessed in your code by creating a
ResourceManager object…
Last Update: 3/09
Page 18
Copyright (C) 2009 by David Figge. All Rights Reserved.
Localization and String Literals
So you start by creating a ResourceManager object (which
really only needs to be done once per form/program). The
parameters to this constructor
are…
private void btnGreeting_Click(object
sender,
EventArgs e)
{
ResourceManager rm = new
ResourceManager("CountryExample.TextStrings",
Assembly.GetExecutingAssembly());
MessageBox.Show(rm.GetString("Good Day"));
}
The fully qualified name of the resource
Then, it uses the currently executing assembly to locate
you’re trying to access. In this case, the
the resources imbedded
within
it. Sothe
we reference the
So once you
have
imbedded
TestStrings object we created with
ExecutingAssembly
as
the
second
parameter.
ResourceManager
object,(this
youcan
cancontain all the string literals
ResGen
load in a string using
theprogram
GetString()
your
uses.) CountryExample is the
method. The parameter is the keynamespace.
used in the text file.
TextStrings.fr.txt
Good Day = Bonjour
Good Night = Bonsoir
Goodbye = Au Revoir
Last Update: 3/09
Let’s look at
Loading
the Satellite
Strings
Assembliesmake
and code…
sense?
Page 19
Copyright (C) 2009 by David Figge. All Rights Reserved.
Testing Your Localizations

If you wish, you can modify your Main
function (located in Program.cs) to
facilitate testing of your localizations



To do this, you set up the program to accept a
culture/region code (‘language’) as a
parameter
Based on that parameter, you then set the
program to use that language setting
Here’s the code…
Last Update: 3/09
Page 20
Copyright (C) 2009 by David Figge. All Rights Reserved.
Testing Your Localizations
static void Main(string[] args)
{
Application.EnableVisualStyles();
First, you modify it so it can take parameters on
Application.SetCompatibleTextRenderingDefault(false);
the command line.
string culture = "";
if (args.Length == 1)
{
culture = args[0];
}
Application.Run(new Form1(culture));
}
Then, if you pass a parameter, you set a string variable to
equal
that
After that, simply
pass
theculture.
culture string to the form’s
constructor. Here’s how the form’s constructor is
modified…
Last Update: 3/09
Page 21
Copyright (C) 2009 by David Figge. All Rights Reserved.
Testing Your Localizations
First, of course, you modify the constructor to take the
string
parameter
language
If the
culture
string isrepresenting
empty, that the
means
you are using the computer’s
settings (in which
case you don’t change anything). Otherwise…
public Form1(string
culture)
{
if (culture != "")
{
CultureInfo ci = new CultureInfo(culture);
// set culture for formatting
Thread.CurrentThread.CurrentCulture = ci;
// set culture for resources
Create a new CultureInfo object based on the =
specified
Thread.CurrentThread.CurrentUICulture
ci;
language string (again, like fr-CA for French in Canada)
} The culture information is actually associate with a thread (in this case,
the main thread for the program). The two places that need to be set
properly
are the
formattings
(like
date
displays) – which is
InitializeComponent();
…and
by setting
theinternal
UI-based
settings (like
the
language
by setting
used in thedone
formhere
– which
is donethe
byCurrentCulture…
setting the
}
At this point,CurrentUICulture.
your program should be using
the language settings you specified.
Questions on
Localization?
Last Update: 3/09
Page 22
Copyright (C) 2009 by David Figge. All Rights Reserved.
Adding Help
Advanced Language Concepts in C#
Last Update: 3/09
Page 23
Copyright (C) 2009 by David Figge. All Rights Reserved.
Adding Help to Applications


I want to talk briefly about the process
of integrating help into an application
I’m going to discuss adding “simple”
help

Adding full help files to an application is
not a small task, and is beyond the scope
of this class
Last Update: 3/09
Page 24
Copyright (C) 2009 by David Figge. All Rights Reserved.
Displaying Help

To use automatic ‘F1’ type help for
controls…


Add a HelpProvider control to your form
For each control in the form set the
HelpString property to the text you want
displayed



When F1 is pressed, a ‘tooltip’ window will pop up
with that string
The HelpKeyword and HelpNamespace (a
property of the HelpProvider) can be used to
display a full-sized Help window if you have a
compiled (*.chm) help file.
Let’s add F1 help to a field on our Address
program…
Last Update: 3/09
Page 25
Copyright (C) 2009 by David Figge. All Rights Reserved.
Displaying Help
Questions on
adding help?
Last Update: 3/09
Page 26
Copyright (C) 2009 by David Figge. All Rights Reserved.
Setup / Publish
Advanced Language Concepts in C#
Last Update: 3/09
Page 27
Copyright (C) 2009 by David Figge. All Rights Reserved.
Publishing Your App


After you’ve got your app working, it’s
all localized, and help is integrated, it’s
time for deployment!
You have two primary choices


Deploy using a Windows Setup program
Use the Publish capability to create a
single-click deployment package
Last Update: 3/09
Page 28
Copyright (C) 2009 by David Figge. All Rights Reserved.
Option 1: Using Windows Setup

To use a Windows Setup program

Add a new project to your solution


Use the Setup Wizard (in the Other Project
Types/Setup and Deployment)




It sets up the Setup project with the default values
Be sure to select the project in Solution Explorer and
make sure the properties are set properly
Right-click on the Application Folder and add
your assembly to the setup list


That’s the best place maintenance-wise
It also detects dependencies you need
When you build the setup project (not normally
done on Build Solution), a setup file is produced
that leads the user through installation
Pretty easy, huh?
Last Update: 3/09
Page 29
Copyright (C) 2009 by David Figge. All Rights Reserved.
Option 2: Using Publish

To publish (deploy via one click)



The Publish Wizard creates a one-click easy installation
file


Go to the Publish tab on the Project Properties
Start the Publish wizard
This can be executed from a disk, or downloaded from a
web site
From the wizard…

Select where to publish the app



Select if this is installed from a Web site, a network location,
or a CD/DVD
You can specify a location where the program can check
for updates as the user installs it


Normally you will place the installation file into a subdirectory of
your app (but can be a Web site or FTP site)
So you could put new, updated install on a web/FTP site that
would be checked on installation
Select where to publish the app
Last Update: 3/09
Page 30
Copyright (C) 2009 by David Figge. All Rights Reserved.
The Publish Wizard

When finished, it produces a simple
installation file complete with setup




It installs it (no interaction required)
Puts it into the Program menu and Control
Panel/Programs
Pretty cool, huh!
Let me show you by running the
publishing wizard on my Address
program…
Questions on
Setup?
Last Update: 3/09
Page 31
Copyright (C) 2009 by David Figge. All Rights Reserved.
End of Session 4
(You Made It!)
Advanced Language Concepts in C#
Last Update: 3/09
Page 32
Copyright (C) 2009 by David Figge. All Rights Reserved.