블로그 이미지
Sunny's

calendar

1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31

Notice

2010. 12. 7. 11:24 MSSQL

SQL Azure를 사용해 보신 분들을 아시겠지만,
Server Explorer에 SQL Azure DB가 등록이 안됩니다.

아마도 Visual Studio 2010 정식 버전 나오고 나면, Azure SDK 등에서 기본으로 지원할지도 모르겠지만,
현재는 어떤 능자가 구현해 놓은 SQL Azure Explorer를 통해서 VS2010 Beta에서 손쉽게
SQL Azure DB를 사용하실 수 있습니다.

다운로드

최신버전을 아래 링크에서 다운로드 받으실 수 있습니다.
http://sqlazureexplorer.codeplex.com/


사용법

다운로드하시면 확장자가 vsix인 파일입니다.
이것은 VS2010에서부터 지원하는 Add-in 포맷입니다.
MEF(Managed Extensibility Framework)를 공부하시면 손쉽게 만들 수 있다고 하니,
관심있으신 분들은 고고씽!

일단 설치가 되었으면, Visual Studio 2010에서 [Tools-SQL Azure Explorer]를 실행합니다.



그러면 작은 창 하나가 생깁니다.



사이드에 있는 다른 Explorer들과 사이좋게 지내라고 잘 Docking 시킵니다.
그리고 상단 CommandBar를 보시면 Connection Properties란 것이 있습니다.
클릭하세요!



그러면 Connection Property들을 입력할 수 있는 창이 뜹니다.



여기 입력하는 정보들은 Window Azure 포탈의 SQL Azure 탭에서 확인하실 수 있습니다. 



여기서 Login 아이디 적을 때에 주의하셔야 할 점은 위 그림의 빨간 숫자를 잘 봐주세요.
username@servername으로 입력해 주셔야 하는데 [2번]@[1번] 이렇게 입력해 주시면 됩니다.
다 입력하셨으면 확인 버튼을 꾸욱!

주의) 접속이 안되면서 IP 주소를 운운하는 경우는 SQL Azure에서 Firewall 설정에
본인의 IP가 허가되지 않은 경우이니 Add Rule을 통해 추가하세요.




그러면 아래처럼 SQL Azure의 DB와 User 정보를 읽어오면서 사용이 가능한 상태가 됩니다.



아직 기능들 중 GUI를 지원하는 것들이 별로 없어서 강력하지는 않지만, 점점 강력해지겠죠.
현재는 데이터 조회정도의 용도로 사용하면 좋습니다.

강력한 관리를 위해서는 SQL Server 2008 R2 November CTP에 포함되어 있는 
SQL Server Management Studio를 사용하시면 됩니다.

posted by Sunny's
2010. 7. 30. 10:59 .NET Framework

Earlier this week the Visual Studio team released updated VS 2010 Keyboard Shortcut Posters.  These posters are print-ready documents (that now support standard paper sizes), and provide nice “cheat sheet” tables that can help you quickly lookup (and eventually memorize) common keystroke commands within Visual Studio.

image

This week’s updated posters incorporate a number of improvements:

  • Letter-sized (8.5”x11”) print ready versions are now available
  • A4-sized (210x297mm) print ready versions are now available
  • The goofy people pictures on them are gone (thank goodness)

The posters are in PDF format – enabling you to easily download and print them using whichever paper size is in your printer.

Download the Posters

You can download the VS 2010 Keybinding posters in PDF format here.

Posters are available for each language.  Simply look for the download that corresponds to your language preference (note: CSharp = C#, VB = VB, FSharp = F#, CPP = C++). 

Hope this helps,

Scott

출처 : http://weblogs.asp.net/scottgu/archive/2010/07/29/visual-studio-2010-keyboard-shortcuts.aspx

posted by Sunny's
2010. 7. 20. 18:33 .NET Framework


The initial Visual Studio Productivity Power Tools release included a bunch of really useful productivity enhancements – including a much faster “Add Reference” dialog, lots of code editor additions and enhancements, and some nice IDE improvements around document tab management.  You can learn more about these features in my previous blog post.

VS 2010 Productivity Power Tools Update

Yesterday we shipped an update to the VS 2010 Productivity Power Tools which adds some nice new features and enhancements.

If you already have the VS 2010 Productivity Power Tools installed, you can update it to the latest release by choosing Visual Studio’s “Tools->Extension Manager” menu command.  This will bring up the VS 2010 Extension Manager – which allows you to browse and download new extensions.  If you click the “Updates” tab on the left-hand side of the dialog it also allows you to see any updates that are available for extensions you already have installed within your IDE.

Simply click the “Update” button for the Productivity Power Tools extension and it will download and install an update for it:

image

If you don’t already have the VS 2010 Productivity Power Tools installed, you can download and install it here.

Sean has a nice blog post that describes all of this week’s productivity power tool updates and additions.  Below are a few of the highlights:

Tools Options Support

The top feature request with the productivity power tools has been to have the ability to turn on/off individual features and extensions it provides. 

With last month’s release you couldn’t easily turn individual features on and off.  Starting with this week’s update you can use Tools->Options within VS 2010, and use a new Productivity Power Tools section to easily enable/disable each feature individually:

image

In addition to enabling/disabling individual features, you can also tweak/edit their settings (including color schemes and behavior).

Solution Navigator

Solution Navigator is a new VS 2010 tool window provided with this week’s update.  It acts like an enhanced Solution Explorer.  It merges functionality from Solution Explorer, Class View, Object Browser, Call Hierarchy, Navigate To, and Find Symbol References all into one tool window – and is pretty darn cool.  Here are just two scenarios of how you can take advantage of it:

File + Class Explorer in One

You can use the “Solution Navigator” to browse your project just like you would with the standard “Solution Explorer” tool window today.  Except instead of ending with only file sub-nodes, you can now expand them to see classes as well as individual methods and members within them. Clicking on one of the sub-nodes will navigate you immediately to the appropriate code block within the code editor.

For example, below we’ve expanded the \Controllers folder within an ASP.NET MVC project and drilled into the AccountController.cs file – which has a AccountController class within it.  We can now drill into that class within the “Solution Navigator” to see a listing of all of its members – and double-click any of them to jump to it within the code editor:

image

Filter Solution

You might have noticed the search box that is at the top of the Solution Navigator above.  You can search within it to quickly filter your solution view. 

For example, below I’ve entered the string “Log” – which causes the “Solution Navigator” to automatically filter to only show those files and members that contain the word “Log” in their names (everything else is hidden within the explorer).  Notice below how my filtered views displays a “view template” file named “LogOn.cshtml”, the three “LogXYZ” methods within my AccountController class, the LogOnModel class within the AccountModels.cs file, and several tests within my test project whose names contain Log:

image

You can double click any of the filtered files or members to immediately navigate to it within the code editor.

Quick Access

Quick Access is a new VS 2010 tool window that allows you to quickly search for and execute common tasks within the IDE.  Ever wondered where a particular menu command is located?  Or ever struggled to find a specific option within the Tools->Options dialog?  Just enter it within Quick Access and it will help you locate it:

image

Clicking any of the items within the list will execute the command, or take you to the appropriate place in the IDE where it lives (in the case of Tools->Options settings):

image

Above I searched for “format” and brought up all the tools->options format settings.  Clicking the “Text Editor->C#->Formatting->New Lines” item within the list opens up the Tools-Options dialog to that exact option location.

Summary

I’ve only touched on a few of the improvements with this week’s update.  Read Sean’s blog post for even more details on the updates and improvements.

If you haven’t installed the free VS 2010 Productivity Power Tools, I highly recommend doing so – I think you’ll find some useful extensions that you’ll like.  If you already have last month’s release installed, you can easily update it to this week’s release to take advantage of even more cool features – as well as benefit from bug fixes and performance improvements.

Hope this helps,

Scott
출처 : http://weblogs.asp.net/scottgu/archive/2010/07/19/vs-2010-productivity-power-tools-update-with-some-cool-new-features.aspx

posted by Sunny's
2010. 5. 7. 10:05 .NET Framework

 

This is the twenty-third in a series of blog posts I’m doing on the VS 2010 and .NET 4 release.

Today’s blog post covers some of the extensibility improvements made in VS 2010 – as well as a cool new "PowerCommands for Visual Studio 2010” extension that Microsoft just released (and which can be downloaded and used for free).

[In addition to blogging, I am also now using Twitter for quick updates and to share links. Follow me at: twitter.com/scottgu]

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

posted by Sunny's
2010. 5. 7. 10:04 ASP.NET

ASP.NET

ASP.NET MVC

  • Code Snippets for ASP.NET MVC 2 in VS 2010: Raj Kaimal documents some of the new code snippets for ASP.NET MVC 2 that are now built-into Visual Studio 2010.  Read this article to learn how to do common scenarios with fewer keystrokes.

Visual Studio 2010

  • SharePoint Development with VS 2010: Beth Massi links to a bunch of nice “How do I?” videos that that demonstrate how to use the SharePoint development support built-into VS 2010.

  • Using the WPF Tree Visualizer in VS 2010: Zain blogs about the new WPF Tree Visualizer supported by the VS 2010 debugger.  This makes it easier to visualize WPF control hierarchies within the debugger.

  • TFS 2010 Power Tools Released: Brian Harry blogs about the cool new TFS 2010 extensions released with this week’s TFS 2010 Power Tools release.

  • What is New with T4 in VS 2010: T4 is the name of Visual Studio’s template-based code generation technology.  Lots of scenarios within VS 2010 now use T4 for code generation customization. Two examples are ASP.NET MVC Views and EF4 Model Generation.  This post describes some of the many T4 infrastructure improvements in VS 2010.

Hope this helps,

Scott

posted by Sunny's
2010. 5. 7. 10:03 .NET Framework

This is the twenty-second in a series of blog posts I’m doing on the VS 2010 and .NET 4 release.

I’ve already covered some of the code editor improvements in the VS 2010 release.  In particular, I’ve blogged about the Code Intellisense Improvements, new Code Searching and Navigating Features, HTML, ASP.NET and JavaScript Snippet Support, and improved JavaScript Intellisense.  Today’s blog post covers a small, but nice, editor improvement with VS 2010 – the ability to use “Box Selection” when performing multi-line editing.  This can eliminate keystrokes and enables some slick editing scenarios.

[In addition to blogging, I am also now using Twitter for quick updates and to share links. Follow me at: twitter.com/scottgu]

Box Selection

Box selection is a feature that has been in Visual Studio for awhile (although not many people knew about it).  It allows you to select a rectangular region of text within the code editor by holding down the Alt key while selecting the text region with the mouse.  With VS 2008 you could then copy or delete the selected text.

VS 2010 now enables several more capabilities with box selection including:

  • Text Insertion: Typing with box selection now allows you to insert new text into every selected line
  • Paste/Replace: You can now paste the contents of one box selection into another and have the content flow correctly
  • Zero-Length Boxes: You can now make a vertical selection zero characters wide to create a multi-line insert point for new or copied text

These capabilities can be very useful in a variety of scenarios.  Some example scenarios: change access modifiers (private->public), adding comments to multiple lines, setting fields, or grouping multiple statements together.

Great 3 Minute Box-Selection Video Demo

Brittany Behrens from the Visual Studio Editor Team has an excellent 3 minute video that shows off a few cool VS 2010 multi-line code editing scenarios with box selection (note: enable your speakers as there is audio during the demo):

 

Watch it to learn a few ways you can use this new box selection capability to optimize your typing in VS 2010 even further:

Hope this helps,

Scott

posted by Sunny's
2009. 7. 21. 14:33 .NET Framework

Fast Forward: Visual Studio 2010 and .NET 4.0

This blog entry is all about Visual Studio 2010 and introduces some startup code to play with WPF and the Task Parallel Library.

Here is a rough outline about what this blog entry:

You will learn about:
(1) How to install Visual Studio 2010 and where to watch a video about it
(2) Basic Intro to the Microsoft Concurrency Web Site
(3) What is the whole point of parallel programming efforts
(4) MSDN Article is a good starting point
(5) Concurrency Samples to download and learn
(6) How to start task based threads with Task.Factory.StartNew()
    - Working with ParallelExtensionsExtras (thread-safe data structures)
    - var orders = new ObservableConcurrentCollection<PizzaOrder>();
(7) How to work with XAML (for WPF and Silverlight Apps)
    - How to work with Data Templates, DataContext Objects, and ItemsControls
    - Embedding User Controls into Canvas objects for custom GUI development

 

image_thumb12

If you haven’t done it yet, please start it now

Yes, to maximize the use of this blog, you should follow along. Learn how to install Visual Studio, then do it.

image_thumb15

Remember, Start by installing Visual Studio 2010 

 image_thumb3

Intro - Why Interesting

This is one of the oldest problems in computer science. Humankind is working hard to figure this out, but it is a real challenge.Thinking in terms of doing two or things at once is natural in our day to day lives, but somehow when we start righting code, we think sequential. Good engineers always solve problems one step at a time.

But we are at a crossroads today. The fastest clock speeds are limited to around 3 GHz.

If you aren’t learning about parallelism you are throwing away CPU. There are built in things into the OS and the .NET Framework that try to use your multi-core CPUs. However, everything from kernel mode device drivers to user mode business applications require intelligent use of parallel programming.

image_thumb32

The Big Picture Visual Studio 2010

You can think of the Task Parallel Library as a generic set of parallel capabilities, whereas PLINQ focuses on database (or object) manipulation.

image_thumb38

Parallelism and Concurrency Architecture

.NET Parallel Programming Architecture

 

Hazim Shafi, Principal Architect, Microsoft Corporation tells us the following:

Parallelism is about performance

Step 1: Understand your goals

Step 2: Measure existing performance

Step 3: Performance tuning

  Starts with sequential version

Step 4: Identify opportunities for parallelism

 

Hide latency

Speed up CPU bound phases

Step 5: Express parallelism

Step 6: Tune

Here is a good article on MSDN Magazine

image_thumb34

http://msdn.microsoft.com/en-us/magazine/cc163329.aspx#S1

 Many brilliant people are working on these things

OS resource management, a concurrency runtime, programming models, language extensions, libraries, and tools, which will make it simpler for both native and managed code developers. It is about making manycore architectures simple and accessible to the broad developer community.

Parallel Technologies in Microsoft Visual Studio 2010

Microsoft Visual Studio 2010 leads the first wave of developer tools to simplify the mainstream transition to parallel software development. Learn about Microsoft’s approach to parallel computing and the parallel technologies available in Visual Studio 2010.

What is so darn difficult about threading or concurrency?

· How to express and exploit fine-grain concurrency

· How to coordinate parallel access to shared state

· How to test and debug for correctness and performance

Traditional approaches to threading are difficult

Handling locks, semaphores, and other synchronization mechanisms is difficult, and might thus not be familiar with concepts such as deadlocks or race conditions.

Is it really harder than regular old sequential programming?

Writing programs that express and exploit fine-grain concurrency is inherently more difficult than writing sequential programs because of the extra concepts the programmer must manage and the additional requirements parallelism places on the program.

When I (Bruno) was a field engineer…

I had to fly to customer locations and use WinDBG to find unintended interactions between threads that share memory (“data races”) and the difficulties of locating and fixing such problems should they exist within a program.

The preferred thread debugging tool at Microsoft

Wikipedia says this: WinDbg is a multipurpose debugger for Microsoft Windows, distributed on the web by Microsoft. It can be used to debug user mode applications, drivers, and the operating system itself in kernel mode. It is a GUI application, but has little in common with the more well-known, but less powerful, Visual Studio Debugger.

They are right – that’s what it does.

Task Parallel Library is one option from Microsoft

image_thumb35

Think Sets

LINQ is a set-at-a-time programming model for expressing computations and places an emphasis on specifying what needs to get done instead of how it is to be done. That is perfect for parallelism. It turns out that query languages lend themselves a beautiful to parallelization.  For example, one core could be reading the index, another core could be used to sort the results, and perhaps a third core can be used for some sort of regular expression parsing or syntax within the given language.

Examples of Upcoming Technologies

Task Parallel Library, PLINQ

Upcoming releases of Visual Studio 2010 and .NET 4.0 will include support that allows you to execute for and foreach loop iterations in parallel with only small alterations to your code. Similarly, you can use a parallel version of LINQ to help boost the performance of your queries.

image_thumb39

 

  There are a lot of great samples

image71[1]

image11 

 

image_thumb11[1]

There are a lot of interesting demos here.

 image_thumb41[1]

image

Let’s take a look at AcmePizza

It is a WPF app that shows how to populate a user interface in a background thread. This allows the user to continue to interact with the application.

Watch the video and you can see how update the user interface in the background while the user can interact with other elements on the screen.

What you are supposed to notice

That you can have the GUI updating the main application window while the user can continue to interact with the application by hitting the command button with the caption “Process Next Order”

image_thumb2

Notice in the application above, orders above are streaming into the application as new tickets. But the user can still hit the “Process Next Order” button.

What you should learn

How to create a user interface that do two things at once, allowing the end user to continue to work as other things are being done. Watch this video and see that the main window is updating. Yet we can still click “Process Next Order”
image15

We are talking about “tasks,” not threads

This sample code provides a great starting point for learning WPF and the task parallel library. I will start by talking about the high level data structures. From there we will discuss other architectural decisions that were made for this application.  The main point of understanding this application is for the task of parallel library. 

image_thumb1

 

The code below illustrates the following. <ItemsControl displays an array of PizzaOrders. When this application starts, it populates the m_orders array with a bunch of random PizzaOrder objects. The window object will display these PizzaOrder objects by using the <ItemsControl>. The <ItemsControl> is a child of the window object. The <ItemsControl> will go to it's parent DataContext object, which is the window object. So when the <ItemsControl> needs to render the interface, it effectively uses the m_orders array.

image_thumb2[1]

Line 9 Data Template used in <ItemsControl> in Window1.xaml
Lines 10 - 17 The Canvas that represents our pizza order.
image_thumb11
Lines 18 – 46 These data triggers are used to update the user interface based on conditions. For example, if the pizza order is a delivery, hten color the canvas pink.

If the Order Source is the Internet, then use internetsource.ico as the file.

Here is the application object that illustrates these data template triggers.

   1:  <Application x:Class="AcmePizza.App"
   2:      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
   3:      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
   4:      xmlns:local="clr-namespace:AcmePizza"
   5:      StartupUri="Window1.xaml">
   6:      <Application.Resources>
   7:          <!--A reusable data template when binding to a collection of pizza orders.  this template is used in both the main window and 
   8:          current order window, where it is scaled larger-->
   9:          <DataTemplate x:Key="PizzaOrderTemplate">
  10:              <Canvas Width="200" Height="200">
  11:                  <Rectangle x:Name="orderRectangle" RadiusX="6" RadiusY="6" Width="200" Height="200" Fill="LightBlue" Opacity="60"/>
  12:                  <TextBlock Margin="10,10,0,0" Text="Phone:"/>
  13:                          <TextBlock Margin="50,10,0,0" FontWeight="Bold"  Text="{Binding Path=PhoneNumber}"/>
  14:                          <local:PizzaSizeCircle x:Name="pizzaSize" Canvas.Right="5" Canvas.Bottom="5" PizzaSize="17"/> 
  15:                          <Image x:Name="sourceIcon" Source="phonesource.ico" Canvas.Left="5" Canvas.Bottom="5"/>
  16:                          <ItemsControl Canvas.Top="40" Canvas.Left="30" ItemsSource="{Binding Path=Toppings}"/>
  17:                      </Canvas>
  18:              <DataTemplate.Triggers>
  19:                  <DataTrigger Binding="{Binding Path=IsDelivery}" Value="true">
  20:                      <DataTrigger.Setters>
  21:                          <Setter Property="Fill" TargetName="orderRectangle" Value="Pink"/>
  22:                      </DataTrigger.Setters>
  23:                  </DataTrigger>
  24:                  <DataTrigger Binding="{Binding Path=Size}" Value="11">
  25:                      <DataTrigger.Setters>
  26:                          <Setter Property="PizzaSize" TargetName="pizzaSize" Value="11"/>
  27:                      </DataTrigger.Setters>
  28:                  </DataTrigger>
  29:                  <DataTrigger Binding="{Binding Path=Size}" Value="13">
  30:                      <DataTrigger.Setters>
  31:                          <Setter Property="PizzaSize" TargetName="pizzaSize" Value="13"/>
  32:                      </DataTrigger.Setters>
  33:                  </DataTrigger>
  34:                  <DataTrigger Binding="{Binding Path=Source}" Value="{x:Static Member=local:OrderSource.Internet}">
  35:                      <Setter Property="Source" TargetName="sourceIcon" Value="internetsource.ico"/>
  36:                  </DataTrigger>
  37:                  <DataTrigger Binding="{Binding Path=Source}" Value="{x:Static Member=local:OrderSource.Phone}">
  38:                      <Setter Property="Source" TargetName="sourceIcon" Value="phonesource.ico"/>
  39:                  </DataTrigger>
  40:                  <DataTrigger Binding="{Binding Path=Source}" Value="{x:Static Member=local:OrderSource.Fax}">
  41:                      <Setter Property="Source" TargetName="sourceIcon" Value="faxsource.ico"/>
  42:                  </DataTrigger>
  43:                  <DataTrigger Binding="{Binding Path=Source}" Value="{x:Static Member=local:OrderSource.WalkIn}">
  44:                      <Setter Property="Source" TargetName="sourceIcon" Value="walkinsource.ico"/>
  45:                  </DataTrigger>
  46:              </DataTemplate.Triggers>
  47:          </DataTemplate>
  48:      </Application.Resources>
  49:  </Application>

 

XAML Programming

You may have noticed that the canvas embeds user control to represent the pizza size. The pizza size is represented by an ellipse and a text box.  We change the diameter of the ellipse based on data triggers.

Its the job of our user controls to represent the pizza size. Notice the “Orange” “Ellipse” below, whose width we can change based on the pizza size being ordered. Note that we just have a grid with an ellipse and a textblock.

image_thumb31[1] 

Here is the code for UserControl

    <!--A user control that changes the appearance of a circle (and text label)
    based on the specified pizza size-->
<UserControl x:Class="AcmePizza.PizzaSizeCircle"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Height="Auto" Width="Auto">
    <Grid x:Name="layoutRoot" Height="75" Width="75">
        <Ellipse x:Name="circle" Width="75" Height="75" Fill="Orange"/>
        <TextBlock x:Name="label" VerticalAlignment="Center" HorizontalAlignment="Center" Text="17" FontSize="20" Foreground="White"/>
    </Grid>
</UserControl>

Our code-behind is as follows:

Line 9 The property “PizzaSize”. This backed by a dependency property, which manages a callback event called PizzaSizeChangedCallBack.
Line 27 - 56

If PizzaSize changed to 11, 13, or 17, then alter the diameter, change the label's text, so that the user control resizes and reflects the new pizza diameter (pizza size) correctly.

 

Notice on line 58 we define a DependencyProperty that is backed with a property and a “changed” event. Note that when some code changes the “PizzaSize” property, code will run from line 29 to 55.

The callback event gives you access to the actual PizzaSizeCircle object whose size was changed, which then allows you to make additional changes to it, like adjusting the label text and other visually oriented control attributes. The point here is that if someone changes the size of the pizza, we need to make various other changes to the graphical interface. That's why you see the width and the height of the circle being changed to different diameters.

It is the magic of dependency properties that make this possible.

Dependencies properties are needed because we need to enforce the circle redraw. If a data trigger changes the size of the pizza, then we’ll need to draw a smaller or bigger circle. A dependency property connects all the plumbing together. The entire code-behind looks like this:
 
   1:  namespace AcmePizza
   2:  {
   3:      /// <summary>
   4:      /// Interaction logic for PizzaSizeCircle.xaml
   5:      /// </summary>
   6:      public partial class PizzaSizeCircle : UserControl
   7:      {
   8:   
   9:          public PizzaSizeCircle()
  10:          {
  11:              InitializeComponent();
  12:          }
  13:   
  14:          public int PizzaSize
  15:          {
  16:              get
  17:              {
  18:                  return (int)this.GetValue(PizzaSizeProperty);
  19:              }
  20:              set
  21:              {
  22:                  this.SetValue(PizzaSizeProperty, value);
  23:           
  24:              }
  25:          }
  26:   
  27:          static void PizzaSizeChangedCallBack(DependencyObject property, DependencyPropertyChangedEventArgs args)
  28:          {
  29:              var control = (PizzaSizeCircle)property;
  30:              switch ((int)args.NewValue)
  31:              {
  32:                  case 11:
  33:                      control.circle.Width = 30;
  34:                      control.circle.Height = 30;
  35:                      control.layoutRoot.Width = 30;
  36:                      control.layoutRoot.Height = 30;
  37:                      control.label.Text = "11";
  38:                      break;
  39:                  case 13:
  40:                      control.circle.Width = 50;
  41:                      control.circle.Height = 50;
  42:                      control.layoutRoot.Width = 50;
  43:                      control.layoutRoot.Height = 50;
  44:                      control.label.Text = "13";
  45:                      break;
  46:                  case 17:
  47:                      control.circle.Width = 75;
  48:                      control.circle.Height = 75;
  49:                      control.layoutRoot.Width = 75;
  50:                      control.layoutRoot.Height = 75;
  51:                      control.label.Text = "17";
  52:                      break;
  53:                  default:
  54:                      throw new ArgumentOutOfRangeException();
  55:              }
  56:          }
  57:   
  58:          public static readonly DependencyProperty PizzaSizeProperty =
  59:              DependencyProperty.Register("PizzaSize", typeof(int), typeof(PizzaSizeCircle),
  60:              new UIPropertyMetadata(17, new PropertyChangedCallback(PizzaSizeChangedCallBack)));
  61:          
  62:      }
  63:  }

 

  The data template triggers are defined inside of our application object.  Notice, for example, that we modify the pizzasize.  Pizza size has been implemented as a dependency property.  For the DependencyProperty callback event we make  other modifications to the user control if the pizzasize changes.  For example, we may wish to make the circular graphic display a wider diameter on the screen.

DataTemplate.Triggers
  if IsDelivery = true, then pink rectangle
  if Size = 11, then pizzasize = 11
  if Size = 13, then pizzasize = 13
  if Source = OrderSource.Internet, then sourceIcon = internetsource.ico
  if Source = OrderSource.Phone, then sourceIcon = phonesource.ico
  if Source = OrderSource.Fax, then sourceIcon = faxsource.ico
  if Source = OrderSource.WalkIn, then sourceIcon = walkinsource.ico

 

image19

Our project is a combination of objects. Since we are modeling a pizzeria, the business objects related to processing pizza orders.  These data structures below represent both the business layer, the UI layer, and other useful enumerations.

Let’s start with our main window. Most of the time you will want the grid interface. Notice below we have a two row grid. The second row of the grid will hold incoming pizza orders. As you can see from the diagram below, the first row of the grid is used to display the name of the pizza company (Acme), an image of a smiling slice of pizza, a button to allow the user to process the next order, and the label “current orders.”

Our user interface is mostly a grid with a small amount of controls We have two rows, and two columns in this grid.
Window Properties Notice we have some events wired up. I see the “Window_Loaded” event. The main window starts “Maximized.”

image_thumb4

A simple two row, two column grid. The first row has a couple of textblocks, an image, and a command button,  which reads “Process Next Order.”

All the important action is in row 2of the grid. This is where wehave the <ItemsControl>.The <ItemsControl> is the way we display PizzaOrders in the main window. The <ItemsControl> allows us to link to a data source. And that data source that we link to is a thread safe data structure that 4 threads populate. Each thread represents a source of a PizzaOrder. For example, PizzaOrders can come from the internet, fax, phone, or WalkIn.

The ItemsControl will allow us to display a collection of user controls, where each user control contains a pizza order. 

 

To be more accurate the pink pizza order in the image below is really just a canvas. The UserControl is the lower right graphic of the pink canvas (the orange circle below), which displays the PizzaSize, and whose size changes in diameter based on the size of the pizza. This example leverages data triggers and dependency properties to control the way graphic elements appear on the screen.

 

image_thumb7

Here is where the task library begins. Notice the method calls:

Task.Factory.StartNew() with some lambda expressions. The window loaded event below essentially spawns off four tasks. Each of these fourth tasks generates random pizza orders 10 times. It is these random pizza orders that Kidd added to the ItemsControl collection. Random number generators are used to create pizza orders.

        private void Window_Loaded(object sender, EventArgs e)
        {
            // launch four threads that mimic various sources
            Task.Factory.StartNew(() => { OrdererThread(OrderSource.Fax); });
            Task.Factory.StartNew(() => { OrdererThread(OrderSource.Internet); });
            Task.Factory.StartNew(() => { OrdererThread(OrderSource.Phone); });
            Task.Factory.StartNew(() => { OrdererThread(OrderSource.WalkIn); });
        }

The execution sequence (not including the user clicking “Process Next Order”)

OrdererThread is spun off of the task factory 4 ways.

We would expect that Fax, Internet, Phone, WalkIn gets passed to OrdererThread.

Each of those threads generates a random order.

GenerateRandomOrder() just gets randomly called.
Window_Loaded
OrdererThread , Order Source = Internet
OrdererThread , Order Source = Fax
GenerateRandomOrder(), Order Source = Fax
GenerateRandomOrder(), Order Source = Internet
OrdererThread , Order Source = Phone
GenerateRandomOrder(), Order Source = Phone
GenerateRandomOrder(), Order Source = Fax
GenerateRandomOrder(), Order Source = Internet
OrdererThread , Order Source = WalkIn
GenerateRandomOrder(), Order Source = WalkIn
GenerateRandomOrder(), Order Source = Phone
GenerateRandomOrder(), Order Source = Fax
GenerateRandomOrder(), Order Source = Phone
GenerateRandomOrder(), Order Source = WalkIn

 

How does GenerateRandomOrder() get called?

Remember, 4 threads are spun off. Each of the threads generates 10 random orders as follows:

        private void OrdererThread(OrderSource source)
        {
            System.Diagnostics.Debug.WriteLine("OrdererThread " + ", Order Source = " + source.ToString());
 
            for ( int i = 0; i < 10; ++i )
            {
                // submit random order
                m_orders.TryAdd( GenerateRandomOrder(source));
                // sleep for a random period
                Thread.Sleep(ConcurrentRandomNumberGenerator.Next(1000, 4001));
            }
        }

I added a Debug.WriteLine() to profile the code execution. But notice that the “for()” loop executes a random order 10 times. The thread then sleeps randomly for 1 to 4 seconds.

How the main user interface gets updated

Recall the “m_orders” variable.

image_thumb9

Notice the special data structure that derives from IProducerConsumerCollection, called ObservableConcurrentCollection. Notice that ultimately we assign to:

this.DataContext = orders;

Understanding DataContext is Key

DataContext is how our user interface gets updated. That’s the beauty of WPF – you just assign to the DataContext and everything follows through with minimal code behind.

image_thumb101

By looking at the XAML, we can see how some of it gets built. First, the second row in the grid spans 2 columns. Next, the <ItemsControl> is in the second row of the grid.

<ItemsControl x:Name="ordersList" ItemsSource="{Binding}" ItemTemplate="{StaticResource PizzaOrderTemplate}"
                      Grid.Row="1" Grid.ColumnSpan="2" VerticalAlignment="Top" Margin="0,0,0,0">
 
  <ItemsControl.ItemsPanel>
 
      <ItemsPanelTemplate>
          <WrapPanel/>
      </ItemsPanelTemplate>
 
  </ItemsControl.ItemsPanel>
 
  <ItemsControl.ItemContainerStyle>
 
      <Style>
          <Setter Property="Control.Width" Value="205"/>
          <Setter Property="Control.Height" Value="205"/>
          <Setter Property="Control.Margin" Value="2.5"/>
      </Style>
 
  </ItemsControl.ItemContainerStyle>
 
</ItemsControl>
 

How to add the post-its to the main window?

These are the pizza orders that populate our main window. The layout and how these colored post-it notes appear on the window is largely defined in App.xaml.. the use of DataTemplates makes this possible. Because App.xaml has somewhat of a global scope, the look and feel of these pizza orders can be used elsewhere in the program.

 

image_thumb11

 

Here is how this works.

 

<ItemsControl x:Name="ordersList" ItemsSource="{Binding}" ItemTemplate="{StaticResource PizzaOrderTemplate}"

image_thumb13

Notice the Canvas allows us to do some absolute positioning. DataTriggers later control the attributes of the canvas, such as the color, the size of the pizza, the graphic image in the lower left corner, which can be a phone, internet, fax, walk-in etc.

posted by Sunny's
prev 1 next