Here are a couple of questions that came up during the Learn to Love Lambdas sessions at recent Code Camps. If you would like to review the session, you can check out the walkthrough and code samples here: Learn to Love Lambdas.
Extension Methods
Question: Could the AddSort() and AddFilter() methods be rewritten as extension methods?
Answer: This question came up during two presentations, so there are at least two people who are curious about this. The answer in this case is no. Let's look at the signuatures of the methods as we created them:
If we wanted to convert these to extension methods, we would need to make these methods "public" (instead of private) and "static" (instead of instance methods). For a quick review of how to create and use extension methods, you can check here: Quick Byte: Extension Methods. The problem is that we cannot make these methods static since they reference specific UI elements on the form. We could do some refactoring and pass in values (for example, the check box true/false values) as parameters. That would allow us to make these methods static; however, this may not be a good idea.
First, I like to reserve extension methods for generic methods that I am planning on re-using. In this case, we have a very specific use case that we are implementing based on UI elements. Second, in making these methods public and static, it exposes them to broader usage than simply as private members of the class. Because these methods are so specific, this may just end up resulting in errors if they are used elsewhere. So, even though it is technically possible to convert these to extension methods, I would not recommend it in this case.
Captured Variables
Question: You metioned that if the callback method grew any larger, you would be tempted to refactor it out into a separate method. How would this affect the captured variable?
Answer: Even if we refactored the method, we would not eliminate the lambda expression itself; we would simply move the body of the lamba to another method. In this case, we could add the captured variable as a parameter, and it would remain available to the separate method.
Here's the refactored code:
Here, you can see that we take the "selPerson" variable (the variable that is captured by the lambda expression) and pass it as a parameter to the "UpdateUI" method. Since the "UpdateUI" method is called within the body of the lambda expression, we still has access to the captured variable which we can pass through to the method. This maintains the same functionality that we have before and allows us to keep the "selPerson" variable as a method-level variable.
Thank you for the great questions. Feel free to drop me a note if you have any more.
Happy Coding!
Saturday, November 20, 2010
Monday, November 15, 2010
BackgroundWorker Session Questions
I want to thank everyone who attended my sessions at the So Cal Code Camp in Los Angeles, CA and at the Desert Code Camp in Chandler, AZ. As I mentioned, I take the questions that come up in my sessions and look into them further. Here's the good news: I have some answers for questions that came up regarding the BackgroundWorker Component. (If you want to take a look at the session walkthrough and code download, you can get them here: Keep Your UI Responsive with the BackgroundWorker Component.)
Passing Additional Data During Progress Updates
Question #1: What is the "UserState" property that shows up in the ProgressChangedEventArgs?
Question #2: Is there a way to pass data from the background thread to the UI thread?
Answer: As you might guess since I grouped these questions together, the UserState property can be used to pass additional information from the background thread to the UI thread during the ProgressChanged event.
As a reminder, we call the ReportProgress method in the background thread which then fires the ProgressChanged event on the UI thread. In the sample code, we used the ReportProgress method that takes a single integer paramter (the percentProgress). But there is an overload that takes both a percentProgress and an additional object parameter called userState. As you might imagine, this will populate the UserState property of our ProgressChangedEventArgs. Let's take a look at updating our application.
First, on the background thread, we will add an additional "update message" where we calculate the progress and call ReportProgress:
This "update message" will contain a string such as "Iteration 45 of 150".
Next, we'll use the new UserState to update the text in our output box:
And here's the output from the running application:
As you can see we have now passed some relevant information from our background thread to our UI thread. It is easy to imagine several uses for this type of behavior. For example, if we were downloading multiple files, we could show the name of the current file in the UI. In addition, since the parameter and UserState are of type "object", we can put anything we want in there, including complex types or collections of complex types.
BackgroundWorker and MVVM
Question: The BackgroundWorker component can be used with WPF and Silverlight. Does this mean that it can be used with MVVM (Model-View-ViewModel)?
Answer: I've thought about this one quite a bit. The question isn't just can the BackgroundWorker be used with MVVM, but whether it makes sense to do so. I've decided that the answer is yes, it does fit in with MVVM.
In the MVVM pattern, the UI elements on the screen (the View) are data-bound to properties and methods in the ViewModel. The ViewModel is responsible for making data from the Model available to the View. In this situation, we would place the BackgroundWorker in the ViewModel. If we were to convert our sample application to MVVM, we could imagine a property for the percent complete that would be bound to the progress bar, and a property for the output that would be bound to the output text box.
The BackgroundWorker would live in the ViewModel and kick off the long running process in the background. When the ProgressChanged event fired (in the ViewModel), it would update the percent complete property (which would in turn update the View due to the data binding). The same would be true of the output property. This would prevent the ViewModel (and the View) from "hanging" while waiting for the long-running process to complete.
MVVM is a much larger topic, and there are a variety of different ways to implement it. But it seems like the BackgroundWorker component may be a useful addition when we are making sure our UI stays responsive.
Again, thank you for the great questions. I hope that I'll see you at one of my sessions in the future.
Happy Coding!
Passing Additional Data During Progress Updates
Question #1: What is the "UserState" property that shows up in the ProgressChangedEventArgs?
Question #2: Is there a way to pass data from the background thread to the UI thread?
Answer: As you might guess since I grouped these questions together, the UserState property can be used to pass additional information from the background thread to the UI thread during the ProgressChanged event.
As a reminder, we call the ReportProgress method in the background thread which then fires the ProgressChanged event on the UI thread. In the sample code, we used the ReportProgress method that takes a single integer paramter (the percentProgress). But there is an overload that takes both a percentProgress and an additional object parameter called userState. As you might imagine, this will populate the UserState property of our ProgressChangedEventArgs. Let's take a look at updating our application.
First, on the background thread, we will add an additional "update message" where we calculate the progress and call ReportProgress:
This "update message" will contain a string such as "Iteration 45 of 150".
Next, we'll use the new UserState to update the text in our output box:
And here's the output from the running application:
As you can see we have now passed some relevant information from our background thread to our UI thread. It is easy to imagine several uses for this type of behavior. For example, if we were downloading multiple files, we could show the name of the current file in the UI. In addition, since the parameter and UserState are of type "object", we can put anything we want in there, including complex types or collections of complex types.
BackgroundWorker and MVVM
Question: The BackgroundWorker component can be used with WPF and Silverlight. Does this mean that it can be used with MVVM (Model-View-ViewModel)?
Answer: I've thought about this one quite a bit. The question isn't just can the BackgroundWorker be used with MVVM, but whether it makes sense to do so. I've decided that the answer is yes, it does fit in with MVVM.
In the MVVM pattern, the UI elements on the screen (the View) are data-bound to properties and methods in the ViewModel. The ViewModel is responsible for making data from the Model available to the View. In this situation, we would place the BackgroundWorker in the ViewModel. If we were to convert our sample application to MVVM, we could imagine a property for the percent complete that would be bound to the progress bar, and a property for the output that would be bound to the output text box.
The BackgroundWorker would live in the ViewModel and kick off the long running process in the background. When the ProgressChanged event fired (in the ViewModel), it would update the percent complete property (which would in turn update the View due to the data binding). The same would be true of the output property. This would prevent the ViewModel (and the View) from "hanging" while waiting for the long-running process to complete.
MVVM is a much larger topic, and there are a variety of different ways to implement it. But it seems like the BackgroundWorker component may be a useful addition when we are making sure our UI stays responsive.
Again, thank you for the great questions. I hope that I'll see you at one of my sessions in the future.
Happy Coding!
Saturday, October 30, 2010
Book Review: C# 4.0 in a Nutshell
A few weeks ago, I finished reading C# 4.0 in a Nutshell: The Definitive Reference by Joseph Albahari & Ben Albahari. I'll start off by saying this is an extremely large "nutshell" (the index starts on page 997), and I spent several months reading it in small pieces. The good news is that it was extremely worthwhile.
I had not read a book dedicated to C# since .NET 1.0 came out. And that was simply to get to know the language. Through the years, I've read numerous .NET books, but mostly focused on a particular technology, not on the C# language itself. So, this was a good chance for me to read up on the language from beginning to end. This helped refresh things that I had learned long ago and forgotten, as well as fill me in on the pieces that I missed over the years, and finally including all of the new features that we got with C# 4.0 including dynamic types, code contracts, and the parallel library.
In the preface, the book itself describes what it is not. It is not a replacement for IntelliSense or on-line help; meaning, it does not have a complete listing of all members of each class. Instead, it gives a good overview of select classes and the primary members that you need to know to utilize those classes. Also, it is not a beginner book or a replacement for tutorials that introduce a new programmer to specific topics.
With that said, I found the book extremely useful. The chapters are well laid-out, and I have found it easy to go back and use this as a reference book for particular topics when needed. Here's a list of the chapters:
One thing that is nice about this book that makes it a complete reference is that it covers parts of the language even if they are no longer the recommended techniques. For example, there is a complete chapter on LINQ to XML. For those of you who have not yet tried LINQ to XML, take a look at it. After trying it, you will never go back to the "old" way of parsing and creating XML documents. With that said, the book also has a chapter on "other" XML technologies. This is important because even if you are not creating new code using these technologies, you may experience existing code that uses them.
There are a number of advanced topics, which further complements the "not a beginner book" statement in the preface. These include things like reflection, the insides of building, signing and deploying assemblies, the security model (such as trusted callers and encryption), and the ins and outs of threading.
The new features in C# 4.0 are covered as well. This includes a full chapter on the parallel library. There were some interesting points that were made here including showing how the order that things happen in the parallel processes is indeterminate. Also, there is a discussion of the various ways of "partitioning" -- helping the parallel library know how to best split up the tasks. (Of course, you can also let the framework take it's best shot at splitting up the tasks, and this will work most of the time.)
Overall, this was an excellent (if extremely long) read. For me, I was reminded of some of the fundamentals of the C# language, I picked up a few tips on things I didn't know existed, and I also learned about the new pieces that were added to the 4.0 version of the language.
I'll recommend this book to intermediate level .NET programmers or experienced programmers who are new to C#. I'll keep this as a reference on my shelf and refer to it frequently.
Happy Coding!
I had not read a book dedicated to C# since .NET 1.0 came out. And that was simply to get to know the language. Through the years, I've read numerous .NET books, but mostly focused on a particular technology, not on the C# language itself. So, this was a good chance for me to read up on the language from beginning to end. This helped refresh things that I had learned long ago and forgotten, as well as fill me in on the pieces that I missed over the years, and finally including all of the new features that we got with C# 4.0 including dynamic types, code contracts, and the parallel library.
In the preface, the book itself describes what it is not. It is not a replacement for IntelliSense or on-line help; meaning, it does not have a complete listing of all members of each class. Instead, it gives a good overview of select classes and the primary members that you need to know to utilize those classes. Also, it is not a beginner book or a replacement for tutorials that introduce a new programmer to specific topics.
With that said, I found the book extremely useful. The chapters are well laid-out, and I have found it easy to go back and use this as a reference book for particular topics when needed. Here's a list of the chapters:
- Introducing C# and the .NET Framework
- C# Language Basics
- Creating Types in C#
- Advanced C#
- Framework Overview
- Framework Fundamentals
- Collections
- LINQ Queries
- LINQ Operators
- LINQ to XML
- Other XML Technologies
- Disposal and Garbage Collection
- Diagnostics and Code Contracts
- Streams and I/O
- Networking
- Serialization
- Assemblies
- Reflection and Metadata
- Dynamic Programming
- Security
- Threading
- Parallel Programming
- Asynchronous Methods
- Application Domains
- Native and COM Interoperability
- Regular Expressions
One thing that is nice about this book that makes it a complete reference is that it covers parts of the language even if they are no longer the recommended techniques. For example, there is a complete chapter on LINQ to XML. For those of you who have not yet tried LINQ to XML, take a look at it. After trying it, you will never go back to the "old" way of parsing and creating XML documents. With that said, the book also has a chapter on "other" XML technologies. This is important because even if you are not creating new code using these technologies, you may experience existing code that uses them.
There are a number of advanced topics, which further complements the "not a beginner book" statement in the preface. These include things like reflection, the insides of building, signing and deploying assemblies, the security model (such as trusted callers and encryption), and the ins and outs of threading.
The new features in C# 4.0 are covered as well. This includes a full chapter on the parallel library. There were some interesting points that were made here including showing how the order that things happen in the parallel processes is indeterminate. Also, there is a discussion of the various ways of "partitioning" -- helping the parallel library know how to best split up the tasks. (Of course, you can also let the framework take it's best shot at splitting up the tasks, and this will work most of the time.)
Overall, this was an excellent (if extremely long) read. For me, I was reminded of some of the fundamentals of the C# language, I picked up a few tips on things I didn't know existed, and I also learned about the new pieces that were added to the 4.0 version of the language.
I'll recommend this book to intermediate level .NET programmers or experienced programmers who are new to C#. I'll keep this as a reference on my shelf and refer to it frequently.
Happy Coding!
Monday, October 25, 2010
Thanks for Coming - SoCal Code Camp Los Angeles
Thank you to everyone who came to my sessions at the SoCal Code Camp this last weekend. And a special thank you to all of you who came to more than one of my sessions. I had a great time doing the presentations and meeting all of you. I hope that you found it worthwhile. As a reminder, the slides, code samples and walkthroughs are available on my website: http://www.jeremybytes.com/Demos.aspx.
I've collected a number of questions that came up and will have answers posted here in the near future. A couple questions even came up in both the Saturday and Sunday sessions, so those will go to the top of the list.
Still coming, I also have a book review for C# 4.0 in a Nutshell by Albahari & Albahari. Short version: excellent book in a gigantic nutshell (over 1,000 pages). I've been a little delayed in getting the review out with my preparation for Code Camp (plus, I started a new job this week). I've started reading my next book: Pro ASP.NET MVC 2 Framework by Steven Sanderson. This has been a great read so far and will most likely end up on my "recommended" list.
In the meantime...
Happy Coding!
I've collected a number of questions that came up and will have answers posted here in the near future. A couple questions even came up in both the Saturday and Sunday sessions, so those will go to the top of the list.
Still coming, I also have a book review for C# 4.0 in a Nutshell by Albahari & Albahari. Short version: excellent book in a gigantic nutshell (over 1,000 pages). I've been a little delayed in getting the review out with my preparation for Code Camp (plus, I started a new job this week). I've started reading my next book: Pro ASP.NET MVC 2 Framework by Steven Sanderson. This has been a great read so far and will most likely end up on my "recommended" list.
In the meantime...
Happy Coding!
Tuesday, September 28, 2010
Upcoming Speaking Engagements
I have several speaking engagements coming up in October and November. If you've always wanted to meet me in person, come on out. I'd love to meet you.
October 19, 2010
ASP.NET SIG - San Diego, CA
http://www.sandiegodotnet.com/
October 23 - 24, 2010
So Cal Code Camp - Los Angeles, CA
http://www.socalcodecamp.com/
November 13, 2010
Desert Code Camp - Chandler, AZ
http://nov2010.desertcodecamp.com/
Hope to see you there!
October 19, 2010
ASP.NET SIG - San Diego, CA
http://www.sandiegodotnet.com/
October 23 - 24, 2010
So Cal Code Camp - Los Angeles, CA
http://www.socalcodecamp.com/
November 13, 2010
Desert Code Camp - Chandler, AZ
http://nov2010.desertcodecamp.com/
Hope to see you there!
Tuesday, September 21, 2010
Learn the Lingo: Design Patterns
You already use Design Patterns but probably don't know it. Observer, Adapter, Iterator, Proxy -- Learning the lingo allows you to better communicate your ideas with other developers. We'll take a look at several GoF patterns that we regularly use without realizing it. Don't know who the GoF is? Read on to find out.
Get It Here
You can get the walkthrough and sample code here: http://www.jeremybytes.com/Demos.aspx.
Direct Links:
Walkthrough (PDF)
Code Download -- Visual Studio 2010
Code Download -- Visual Studio 2008
I'll be presenting this topic at the upcoming So Cal Code Camp, October 23rd and 24th in Los Angeles, CA. Hope to see you there!
Happy Coding!
Get It Here
You can get the walkthrough and sample code here: http://www.jeremybytes.com/Demos.aspx.
Direct Links:
Walkthrough (PDF)
Code Download -- Visual Studio 2010
Code Download -- Visual Studio 2008
I'll be presenting this topic at the upcoming So Cal Code Camp, October 23rd and 24th in Los Angeles, CA. Hope to see you there!
Happy Coding!
Monday, September 20, 2010
So Cal Code Camp - Los Angeles
The So Cal Code Camp is coming to Los Angeles October 23rd & 24th. As always, Code Camp is FREE! It's a great chance to get some training and hook up with other developers / coders / hackers in your area. I'll be presenting several sessions, so it's your chance to see me, too.
Hope to see you there!
Hope to see you there!
Subscribe to:
Posts (Atom)