Monthly Archives: May 2009

Telerik’s Scheduler Recurrence Capabilities

For those using Telerik’s RadScheduler control, I explained about the options that the scheduler uses to recur by:  http://dotnetslackers.com/articles/aspnet/Understanding-Teleriks-Scheduler-Recurrence.aspx  I don’t know if the latest release has changed some of these settings, but this article was up to date as of the previous 2008.3 release.  The scheduler uses a unique convention to identify recurring appointments within the scheduler control, and I give an overview of the various features.  Once you have an understanding of these features, using the scheduler control becomes easier.


For instance, one of the weird things about the control is how it keeps track of modifications to recurring appointments.  The recurrence string stores a list of excluded dates; these dates block appointments from showing on the calendar.  In addition, the API for the scheduler creates a new entry for modified instances of the recurring appointment (when changing a single instance within the scheduler).  I hope this article can help you understand the recurrence features the scheduler provides.


I also provide an overview of the control here:  http://dotnetslackers.com/articles/aspnet/Using-Teleriks-Scheduler-Component.aspx

Multithreading: queuing work items

As we’ve seen in the last post of the series, we can use the thread pool for scheduling several “types” of asynchronous operations and to amortize the penalty we pay when we need to create extra threads. In fact, I’d say that most operations should be performed by using a thread from the thread pool.

Today we’re going to look at one of the operations we can perform on thread pool: queuing work items. Interacting with the CLR managed thread pool can be accomplished through one of the several static methods of the ThreadPool class. For queing work items, we can use one of two methods: QueueUserWorkItem or UnsafeQueueUserWorkItem.

public static bool QueueUserWorkItem(WaitCallback callBack);
public static bool QueueUserWorkItem(WaitCallback callBack,
                                                                             object state);
public static bool UnsafeQueueUserWorkItem(WaitCallback callBack,
                                                                                 object state);

According to Joe Duffy’s excellent book, you should disregard the return value because failures will always be communicated through exceptions (I did check the docs and they don’t mention what false means :),,)

The main difference between the two is that the latest does not capture the ExecutionContext when you queue the work item (which means that it won’t also be used when the callback you pass is invoked). Both methods allow you to pass a reference to some object which will get passed to the callback when its processed.

Even though QueueUserWorkItem is more “secure” than the UnsafeQueueWorkItem (due to the fact that the context is captured and flowed – since the SecurityContext is part of the ExecutionContext, this means that you cannot elevate privileges by queuing work items on the thread pool), it’s also true that QueueUserWorkItem is slower than UnsafeQueueWorkItem (due to the overhead imposed by capturing and restoring the context).

When using a thread from the pool, it’s important to understand a few points:

  • you don’t control the thread that will invoke your callback;
  • the pool has only background threads. This means that they won’t keep a process running when the main thread exits. If you need to ensure that, then you need to create a thread by hand (ie, you need to use the Thread class);
  • Don’t forget the clean up before ending your work (especially if you’ve set cultures and other stuff). Even though these might get cleaned, there are some that won’t (ex.: TLS state – which, btw, you shouldn’t be using).

Enough talk…let’s see some code:

static void Main(string[] args) {
Console.WriteLine("Main thread Id: {0}",
             Thread.CurrentThread.ManagedThreadId);
  var evt = new ManualResetEvent(false);
  ThreadPool.QueueUserWorkItem( state => {
       Console.WriteLine("Thread Id: {0}",
                      Thread.CurrentThread.ManagedThreadId);
       Thread.Sleep(2000);
       Console.WriteLine("FInishing work");
       evt.Set();
     });
     evt.WaitOne();
     Console.WriteLine("Ending program");
}

The QueueUserWorkItem method expects a WaitCallback delegate which looks like this:

public delegate void WaitCallback(object state);

The state parameters will only contain a valid value when you use the overload which receives an object parameter. As you can see, the code is pretty similar to the one you had when we created threads “by hand”.

The most important detail of the previous code is synchronization! If we didn’t wait on the event, we wouldn’t really see much because the process would terminate before the secondary thread would have a chance to end (since pool’s threads are background threads, they don’t keep the process alive when all foreground threads have ended running).

And that’s it for today. Keep tuned for more on the thread pool.

VS 2010 color scheme patch

If you enjoy dark themes and love VS 2010, then you know you’re into trouble. The problem is that VS looses the dark background after being closed and you need to go to the options, fonts and colors and then apply the current settings (which still have the correct color) again.

The good news is that is no longer necessary. You just need to install the background patch extension from the VS gallery.

thanks for the fix guys!

Some Excellent FireFox/Firebug Tools/Addons

I’ll probably come back and update this post, but I wanted to post some excellent addons or tools that can be used with Firefox/Firebug, available here:


10 Firefox Add-Ons for Web Designers: http://www.10voltmedia.com/blog/2009/05/10-firefox-add-ons-for-web-designers/


10 Firefox Extensions for Web Analytics: http://www.thomsonchemmanoor.com/10-firefox-extensions-for-web-analytics.html


FireAtlas, an ASP.NET AJAX utility: http://fireatlas.chesnaistechnologies.com/

Downloading .NET reflector

Not sure on how I should classify this, but I’d say that getting this error in 2009 from a page served by a company like redgate is incredible! Today I needed to download reflector, so I went to redgate’s site and chose the download option. When you do that, you’ll be redirected to a page that asks for name and email. Since I was in a hurry, I’ve just hit several keys in the keyboard and ended up introducing this:

error1

Notice the < on the email…then, clicking the download free copy produced the following result:

error2

fantastic, right?

YUI Compressor in Visual Studio

I needed to be able to compress my JavaScript files, and I like to use the YUI compressor to do this.  Found an even easier way to do this using Visual Studio, by creating an external tool as mentioned in this blog:  http://blog.lavablast.com/post/2009/05/YUI-Compressor-for-Visual-Studio.aspx


Also, there is an option for an MS build task: http://www.coderjournal.com/2008/05/how-to-create-a-yui-compressor-msbuild-task/


Really cool, very helpful.

Book Review: Pro JavaScript Design Patterns



Normal
0




false
false
false

EN-US
X-NONE
X-NONE








































































































































































<!–
/* Font Definitions */
@font-face
{font-family:Wingdings;
panose-1:5 0 0 0 0 0 0 0 0 0;
mso-font-charset:2;
mso-generic-font-family:auto;
mso-font-pitch:variable;
mso-font-signature:0 268435456 0 0 -2147483648 0;}
@font-face
{font-family:”Cambria Math”;
panose-1:2 4 5 3 5 4 6 3 2 4;
mso-font-charset:0;
mso-generic-font-family:roman;
mso-font-pitch:variable;
mso-font-signature:-1610611985 1107304683 0 0 159 0;}
@font-face
{font-family:Calibri;
panose-1:2 15 5 2 2 2 4 3 2 4;
mso-font-charset:0;
mso-generic-font-family:swiss;
mso-font-pitch:variable;
mso-font-signature:-1610611985 1073750139 0 0 159 0;}
/* Style Definitions */
p.MsoNormal, li.MsoNormal, div.MsoNormal
{mso-style-unhide:no;
mso-style-qformat:yes;
mso-style-parent:”";
margin-top:0in;
margin-right:0in;
margin-bottom:10.0pt;
margin-left:0in;
line-height:115%;
mso-pagination:widow-orphan;
font-size:11.0pt;
font-family:”Calibri”,”sans-serif”;
mso-ascii-font-family:Calibri;
mso-ascii-theme-font:minor-latin;
mso-fareast-font-family:Calibri;
mso-fareast-theme-font:minor-latin;
mso-hansi-font-family:Calibri;
mso-hansi-theme-font:minor-latin;
mso-bidi-font-family:”Times New Roman”;
mso-bidi-theme-font:minor-bidi;}
p.MsoListParagraph, li.MsoListParagraph, div.MsoListParagraph
{mso-style-priority:34;
mso-style-unhide:no;
mso-style-qformat:yes;
margin-top:0in;
margin-right:0in;
margin-bottom:10.0pt;
margin-left:.5in;
mso-add-space:auto;
line-height:115%;
mso-pagination:widow-orphan;
font-size:11.0pt;
font-family:”Calibri”,”sans-serif”;
mso-ascii-font-family:Calibri;
mso-ascii-theme-font:minor-latin;
mso-fareast-font-family:Calibri;
mso-fareast-theme-font:minor-latin;
mso-hansi-font-family:Calibri;
mso-hansi-theme-font:minor-latin;
mso-bidi-font-family:”Times New Roman”;
mso-bidi-theme-font:minor-bidi;}
p.MsoListParagraphCxSpFirst, li.MsoListParagraphCxSpFirst, div.MsoListParagraphCxSpFirst
{mso-style-priority:34;
mso-style-unhide:no;
mso-style-qformat:yes;
mso-style-type:export-only;
margin-top:0in;
margin-right:0in;
margin-bottom:0in;
margin-left:.5in;
margin-bottom:.0001pt;
mso-add-space:auto;
line-height:115%;
mso-pagination:widow-orphan;
font-size:11.0pt;
font-family:”Calibri”,”sans-serif”;
mso-ascii-font-family:Calibri;
mso-ascii-theme-font:minor-latin;
mso-fareast-font-family:Calibri;
mso-fareast-theme-font:minor-latin;
mso-hansi-font-family:Calibri;
mso-hansi-theme-font:minor-latin;
mso-bidi-font-family:”Times New Roman”;
mso-bidi-theme-font:minor-bidi;}
p.MsoListParagraphCxSpMiddle, li.MsoListParagraphCxSpMiddle, div.MsoListParagraphCxSpMiddle
{mso-style-priority:34;
mso-style-unhide:no;
mso-style-qformat:yes;
mso-style-type:export-only;
margin-top:0in;
margin-right:0in;
margin-bottom:0in;
margin-left:.5in;
margin-bottom:.0001pt;
mso-add-space:auto;
line-height:115%;
mso-pagination:widow-orphan;
font-size:11.0pt;
font-family:”Calibri”,”sans-serif”;
mso-ascii-font-family:Calibri;
mso-ascii-theme-font:minor-latin;
mso-fareast-font-family:Calibri;
mso-fareast-theme-font:minor-latin;
mso-hansi-font-family:Calibri;
mso-hansi-theme-font:minor-latin;
mso-bidi-font-family:”Times New Roman”;
mso-bidi-theme-font:minor-bidi;}
p.MsoListParagraphCxSpLast, li.MsoListParagraphCxSpLast, div.MsoListParagraphCxSpLast
{mso-style-priority:34;
mso-style-unhide:no;
mso-style-qformat:yes;
mso-style-type:export-only;
margin-top:0in;
margin-right:0in;
margin-bottom:10.0pt;
margin-left:.5in;
mso-add-space:auto;
line-height:115%;
mso-pagination:widow-orphan;
font-size:11.0pt;
font-family:”Calibri”,”sans-serif”;
mso-ascii-font-family:Calibri;
mso-ascii-theme-font:minor-latin;
mso-fareast-font-family:Calibri;
mso-fareast-theme-font:minor-latin;
mso-hansi-font-family:Calibri;
mso-hansi-theme-font:minor-latin;
mso-bidi-font-family:”Times New Roman”;
mso-bidi-theme-font:minor-bidi;}
.MsoChpDefault
{mso-style-type:export-only;
mso-default-props:yes;
mso-ascii-font-family:Calibri;
mso-ascii-theme-font:minor-latin;
mso-fareast-font-family:Calibri;
mso-fareast-theme-font:minor-latin;
mso-hansi-font-family:Calibri;
mso-hansi-theme-font:minor-latin;
mso-bidi-font-family:”Times New Roman”;
mso-bidi-theme-font:minor-bidi;}
.MsoPapDefault
{mso-style-type:export-only;
margin-bottom:10.0pt;
line-height:115%;}
@page Section1
{size:8.5in 11.0in;
margin:1.0in 1.0in 1.0in 1.0in;
mso-header-margin:.5in;
mso-footer-margin:.5in;
mso-paper-source:0;}
div.Section1
{page:Section1;}
/* List Definitions */
@list l0
{mso-list-id:873612049;
mso-list-type:hybrid;
mso-list-template-ids:654726366 67698689 67698691 67698693 67698689 67698691 67698693 67698689 67698691 67698693;}
@list l0:level1
{mso-level-number-format:bullet;
mso-level-text:ď‚·;
mso-level-tab-stop:none;
mso-level-number-position:left;
text-indent:-.25in;
font-family:Symbol;}
ol
{margin-bottom:0in;}
ul
{margin-bottom:0in;}
–>



/* Style Definitions */
table.MsoNormalTable
{mso-style-name:”Table Normal”;
mso-tstyle-rowband-size:0;
mso-tstyle-colband-size:0;
mso-style-noshow:yes;
mso-style-priority:99;
mso-style-qformat:yes;
mso-style-parent:”";
mso-padding-alt:0in 5.4pt 0in 5.4pt;
mso-para-margin-top:0in;
mso-para-margin-right:0in;
mso-para-margin-bottom:10.0pt;
mso-para-margin-left:0in;
line-height:115%;
mso-pagination:widow-orphan;
font-size:11.0pt;
font-family:”Calibri”,”sans-serif”;
mso-ascii-font-family:Calibri;
mso-ascii-theme-font:minor-latin;
mso-hansi-font-family:Calibri;
mso-hansi-theme-font:minor-latin;}


When you read the book, “Pro JavaScript Design Patterns” from Ross Harmes and Dustin Diaz, it’s clear that Ross and Dustin have a strong understanding of JavaScript, its strengths, and its limitations.  JavaScript has a lot of stengths, in that it supports dynamic typing at runtime, public and private typing of members, flexible coding style , and existing support of class/object development.  Its weaknesses, such as support for other constructs, like explicit namespaces or interface support, the writers attempt to make up for by showing potential workarounds to the issue.

The first three chapters setup some of the more complex topics: flexibility and mutability of objects, dynamic typing, structuring of classes and how to assign methods to an object’s prototype.  Another important subject is the differentiation between public and private members, and how these members are scoped and accessed in the class’s instance.

Speaking of classes, there are a couple of different ways to setup class definitions and inheritance.  The first option is prototypical inheritance, where the derived class inherits the members of the base class.  Other options are mixin classes, using a helper method to copy over class definitions from one object to another.  This book, with great detail, discusses the differences between the two options.

The book continues to discuss the following design patterns, and implements in full JavaScript.  The concepts in the first four chapters, discussed above, are reused in the design pattern process.  Each chapter highlighted below has an explanation, example (or several), guide on when to implement, pros, cons, and summary.

·         Singleton Pattern – While not following the
exact traditional pattern that you would see in other server-based environments,
like the .NET framework, the Singleton pattern implemented in JavaScript
provides a central accessible object to the application.  The book also covers the subject of lazy instantiation and brancing of internal members (one example cited was to vary method implementation by browser).

·         Chaining – More commonly seen in the JQuery
library, chaining is the creation of a central object that gets returned from
every method call.  Within the prototype of every (or at least most) method is a call to return that same object.  This way, the object can call one method after the other, after the other, in a more convenient fashion.

·         Factory Pattern – The factory pattern provides a
way to create the correct object using some sort of identifier (string, enum,
object, etc.).  The factory pattern instantiates an object that inherits from the same base class type, and thus the factory is responsible for its instantiation.

·         Bridge Pattern – This pattern bridges multiple
classes together that implement a similar functionality.  It’s a way to break out logical components into different objects, and follow more closely the Singular Responsibility pattern.

·         Composite Pattern – This pattern requires that a
particular set of objects all implement the same interface,regardless of whether
a specific function is used within that object or not.  The pattern is made up of leaf elements (elements at the bottom of the structure), and composite elements (which have one or more composite/leaf elements).  The example used to illustrate this pattern is displaying of individual elements (textboxes and such), versus displaying composite elements.

·         Façade Pattern – The façade pattern simplifies
common tasks by grouping them into a parent function.  For example, there are various nuances in JavaScript that vary by browser.  The façade pattern facilitates working around these nuances by creating a central object with a method that checks browser type, and calls the correct method.  From then on, the developer has to call this one method, instead of handling the various JavaScript nuances.

·         Adapter Pattern – The adapter pattern provides a
common interface across disparate interfaces that provide differing
implementations.  For instance, suppose you had to integrate various web service implementations.  Each implementation would have a different implementation; the adapter pattern can accommodate this by providing one common interface, which this object then interacts with the web service.

·         Decorator Pattern – The decorator pattern can be
used to modify the behavior of its target.  Decorators can be strung together to continually alter its behavior in some way, providing that each decorator alters the object appropriately.  The chapter also explains what to watch out for when implementing this pattern, such as the order the patterns are created and processed.

·         Flyweight Pattern – This pattern provides a
caching to reuse commonly used elements, to make the underlying processes run
faster.  The system would first check the cache to see if the object exists before instantiating it.

·         Proxy Pattern – A proxy provides access control
to its underlying object’s methods calls.  It implements the same methods as its target, and can be a way to optimize usage of resources (especially expensive ones).  This isn’t necessarily related to just security in this regard.  There are three types of proxies: virtual proxy, remote proxy, and protection proxy. 

·         Observer Pattern – The observer pattern uses
subscribers and publishers.  The publisher publishes to its subscriber that some event happened, and the subscriber can react to it in some way.  One approach is through the use of a delegate that the publisher can call.

·         Command Pattern – A command is some action that
occurs within the application.  A command provides a specific interface that varying command objects implement.  The command can then be executed and perform its underlying action: this may be copy, paste, undo, or other operations.

·         Chain of Responsibility Pattern – The chain of
responsibility pattern is similar to some of the above patterns: it uses a
chaining approach, which consists of firstly the sender, followed by a series
of receivers that will process or ignore the request. It’s a complex design
pattern that the book describes very well.


Most of the chapters are explained very well; some of the examples didn’t make the most sense to me as I didn’t fully grasp some of the patterns.  It’s clear the authors know a lot more about design patterns than I do.  However, don’t let that detract you from the book because reading it again and trying it out yourself will help you to grasp the fundamentals.  Alternatively, most of the examples are clear, concise, and to the topic at hand.


The book is a small book, consisting of many chapters (nicely broken out so I was able to do one a day).  It has a lot of power to the punch for its size, which makes it a great book, and a great overview of design patterns in the JavaScript world, a world much different than most server-based languages.


Multithreading: introducing the thread pool

Until now, we’ve been starting threads by creating instances of the System.Threading.Thread class in the samples. Thread creation isn’t cheap! If we’re creating a thread just to run a small task, then the thread’s creation might completely outweigh the advantage of running such a small task.

In most cases, instead of creating new threads, we should simply run those tasks on one of the threads maintained on the thread pool that is automatically created for all managed processes. Even though the most used operation is queuing a task in the thread pool, you can also:

  • use the pool to run a task when IO completes;
  • run a (possible recurrent) task at a specific time;
  • execute a task when a kernel object is signaled.

The global CLR thread pool maintains two “sub-pools”. One is used for IO and the other is used for the remaining possible options mentioned above. By default, there is one pool per process and the IO “sub-pool” will contain a maximum of 1000 threads, while the other “sub-pool” (aka worker pool) contains a maximum of 250 threads.

wow! wtf? so many threads? Yes, that’s the maximum number you’ll get per process.However, when the process starts, there aren’t really any threads on the pool ,,)ie, both “sub-pools” are empty. Threads are created as needed (ie, while new task are queued on the thread pool) until the specified minimum number of threads is reached.

Notice that threads might not be immediately created for work items that are queued on the thread pool. When the minimum number of threads is reached, the thread pool will throttle the creation of other threads (meaning, it won’t immediately create new threads per task that is queued on the thread pool). In these cases, the thread pool will create a new thread as needed from 30 to 30 seconds if all the predefined minimum number of threads are all busy doing work.

When a thread ends its work, it returns to thread pool where it waits for more work. If the current number of waiting threads is greater than the minimum specified, then those additional threads will be terminated.

And that’s it for this post. We’ll be returning to this topic in the next posts.

Protected: Using condition variables

There is no excerpt because this is a protected post.

Multithreading: condition variables

There are times when a thread needs to wait  for a specific condition to be true. Since this condition tends to involve shared state, then you know that you must use some sort of synchronization to ensure proper update of the data used by the condition. When we looked at kernel objects, we’ve seen that there was a method (SignalAndWait) that you can use to signal a kernel object and wait on another atomically. This is good and helps with those nasty race conditions that might occur if you have to signal one object and wait on another.

Now, when you use the sync primitives (CLR locks and reader/writer locks), we stop having access to the kernel objects used by those high level primitives! This means that we’re back to the race condition when we need to, for instance, exit a critical section and set an event. And this is the problem that condition variables solve.

In .NET, condition variables have first class support, through the Monitor’s Wait and Pulse methods. Calling the static Wait method results in releasing the lock on an object and blocking the current thread until it reacquires that lock (in practice, this means that the thread that called Wait goes into the waiting queue of that object). When the method returns, it will have reacquired the lock (something that is only possible when another thread calls the Pulse or PulseAll method).

It’s important to understand that you can only call Wait over an object for which the calling thread owns the lock (failing to respect this results in a SynchronizationLockException being thrown). The same is true for the Pulse and PulseAll methods. In practice, this means that Wait,Pulse and PulseAll methods must be invoked from within  a lock block!

Notice that since the Wait method needs to reacquire the lock,it will block until it achieves that purpose (even if you use one of overloads that expect a timeout). This means that you’ll have to use the return values to check if the wait ended before the specified timeout (in which case, true is returned).

As we’ve said, you need to signal a condition by calling the Pulse/PulseAll methods. This is the only way to unblock a thread that has gone into the waiting queue of an object. On the next post, we’ll see a practical example of how to use this feature. Keep tuned!

Recent Comments