Site: http://msmvps.com/blogs/luisabreu/default.aspx Link: http://msmvps.com/blogs/luisabreu/rss.aspx
by luisabreu via LA.NET [EN] on 1/27/2010 10:20:27 AM
Now that you understand what attached properties are, we’re in the position to look at what is needed for creating attached properties. Since we’re building custom code, we do really need to rely in the RegisterAttached method (of the DependencyProperty class). Creating a new attached properties means doing the following: adding a static DependencyProperty field to the class; using the RegisterAttached method for creating the field which is used as a store for the dependency property; ...
[ read more ]
by luisabreu via LA.NET [EN] on 1/21/2010 10:23:10 AM
One of the things I’ve mentioned in the previous posts is that the value of a dependency property at runtime can be influenced by several “providers”. That means that there needs to be some sort of order which governs the way providers affect the final value of a dependency property (this order is known as precedence list). The final value of a dependency property at runtime is obtained after all the items in the following list have been evaluated by the presented order: Default value; St ...
by luisabreu via LA.NET [EN] on 1/20/2010 2:31:22 PM
As I’ve said before, dependency properties introduce several advantages over the traditional CLR properties. However, there might some gotchas associated with their use from XAML. As we’ve seen, dependency properties are defined through static fields and exposed through .NET properties for easy consume from C#/VB code (as we’ve seen, getting and setting the value of the property is achieved through the GetValue/SetValue methods inherited from the DependencyObject class). If you’re coming to Silv ...
by luisabreu via LA.NET [EN] on 1/18/2010 12:36:21 PM
In the previous post, I’ve talked a little bit about dependency properties and on how they’re defined. One of the advantages of using those properties is value inheritance. Take a look at the following snippet: <UserControl x:Class="Tests.MainPage" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" FontSize="30"> <StackPanel> <TextBlock FontSize=&q ...
by luisabreu via LA.NET [EN] on 1/18/2010 10:31:06 AM
The dependency property concept was introduced by WPF 1.0 for exposing rich functionality from XAML. Dependency properties support several features exposed by Silverlight (styling, animation and data binding, for instance). Unfortunately, they also increase the complexity associated with property definition. Dependency properties values at runtime depend on several things. For instance, it could depend on an animation which continuously changes the value of a property or it could depend on the v ...
by luisabreu via LA.NET [EN] on 1/5/2010 10:55:50 PM
[Update: added the missing web.config changed required to make it work] ASP.NET has been performing some sort of validation on user input for ages. For instance, I guess that most of us know that there is a list of chars which can’t be introduced in a textbox (ex.: <) in order to help protect our pages against vulnerabilities. Now, this validation is lazy and is performed against the data passed through the request (even though the user input validation is the most know validation, it’s also ...
by luisabreu via LA.NET [EN] on 11/16/2009 9:16:53 PM
You can’t really do it any other way: we must understand XAML before going on (at least, its basic features). In this post, we’ll start looking at XAML and at how we can use it to define the UI of our Silverlight user controls. So, the big question: what is XAML? To me, XAML (which, btw, means Extensible Application Markup Language) is a declarative language which you can use to define and initialize objects. Notice that XAML isn’t Silverlight specific. If my memory is correct, it was introduced ...
by luisabreu via LA.NET [EN] on 10/29/2009 3:19:34 PM
Ok, I think this title might have caught your attention! (at least, that’s what I’m hopping for!). This post is a direct consequence of another discussion with a friend regarding the use of the DataView control. He told me something like this: “well, DataViews are cool…can’t deny it…but it’s only for listing items and that means it’s only usable for grids…” Aha! That is not correct. And to show him that he was wrong, we’ve settled in a challenge (not as interesting as top gear’s challenges, but ...
by luisabreu via LA.NET [EN] on 10/29/2009 12:16:22 PM
Today I was a little bit surprised when I was asked if we really needed the global:: qualifier. If you’ve been doing C# for some time, the answer is (absolutely) yes. However, things might not be so clear for a beginner (btw, the question was asked in the context of auto-generated by VS which used it to qualify the name of a base class). The best way to understand it is to write a quick sample where you might really need to use this qualifier: class Test { public void SayHi() { Cons ...
by luisabreu via LA.NET [EN] on 10/29/2009 10:20:34 AM
Yesterday I’ve ended up receiving an interesting question regarding the code I’ve used in the posts which explain how to get data from a remote web service. The question was: how do we adapt the data returned from the web service before it is used by the DataView for rendering its HTML? This is an interesting question. Fortunately, the answer is not really complicated. To illustrate this problem and its solution, we’ll start by going back to the Person class we’ve introduced in the server ...
by luisabreu via LA.NET [EN] on 10/28/2009 3:38:15 PM
In the previous posts, we’ve seen how to configure the DataView control so that it gets the data from a remote web service. In this post, we’ll see how we can take advantage of the fetchParameters to pass info to the web service. The idea is simple: we’ll update the previous sample so that it renders a table with clickable headers used for sorting the displayed data. Sorting the data will be done on the server. This means we need to start updating the server side code so that the web service met ...
by luisabreu via LA.NET [EN] on 10/28/2009 11:37:25 AM
Until now, we’ve been using static data to feed all the DataView controls we’ve been using in the MS AJAX series. Today we’ll see how we can configure the control so that it automatically gets data returned from a web service call. To get things started, we’ll start by introducing the server side code for the WCF service: [ServiceContract(Namespace = "")] [AspNetCompatibilityRequirements( RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] public class PeopleServ ...
by luisabreu via LA.NET [EN] on 8/13/2009 2:32:01 PM
Since I’ve been digging into JQuery, I though that it would also be a good idea to write a little bit more about Javascript. In my (limited) experience, I’ve met many developers who say that they really know Javascript and that it’s a really simple language. The problem is that they have lots of trouble in understanding and explaining the basic concepts/feature of the language. I’m not really a Javascript expert, but I guess that sharing several of the gotchas I’ve tripped along the way won’t do ...
by luisabreu via LA.NET [EN] on 7/6/2009 8:25:34 PM
[Update: Brad detected a flaw in the code: I had forgotten to initialize the _initialized field. Thanks!] [Update2: Brad detected another flaw in the code: return _instance must be outside the if. Thanks!] In the previous post we’ve seen how we can use the C# volatile keyword to guarantee that those nasty load-load reordering stay away from our code. As I’ve said before, we can also use the static Thread.VolatileRead or Thread.VolatileWrite for having more control over the way fences are appli ...
by luisabreu via LA.NET [EN] on 7/6/2009 8:53:16 AM
In the last post, I’ve showed you some code I’ve written in the past and asked if there was anything wrong with it. Here’s the code again: class Lazy { private SomeObject _object; private Object _locker = new Object(); public SomeObject SomeObject { get { if (_object == null) { lock (_locker) { if (_object == null) { _object = new SomeObject(); } } } return _object; } } } Here’s main idea (for the double-ch ...
by luisabreu via LA.NET [EN] on 7/5/2009 8:51:51 PM
Today we’re only going to talk about the volatile keyword. The volatile keyword can be used on the declaration of a field, transforming it into a volatile field. Currently, you can only annotate a field with this keyword if it is: a reference type; a pointer type (unsafe code); one of the following types: sbyte, byte, short, ushort, int, uint, char, float or bool; an enum with a base type of byte, sbyte, short, ushort, int or uint. As we’ve seen, volatiles ensures that proper ...
by luisabreu via LA.NET [EN] on 7/4/2009 3:31:44 PM
In the last posts we’ve been poking around memory models, memory fences and other interesting things that might lead to the so called lock free programming. Before keep looking at how we can use those features from our C# code, I’d like to add one more example that shows how the interlocked operations might help you in the real world. Do you recall our implementation of the IAsyncResult interface? At the time, we’ve used a lock for ensuring proper access and initialization of our manual reset ...
by luisabreu via LA.NET [EN] on 7/3/2009 2:28:13 PM
In the last post, we’ve talked about memory fences. Today we’re going to keep looking at this topic, but we’re turning our attention to coding, ie, we’re going to talk about the options we have to add fences to our classes. In .NET, things are relatively straightforward. Whenever we use one of the interlocked methods we’ve met in the past, we’re adding a full fence to our code. Locking will also end up using full fences. As you can see, you’re already using full fences in several places. ...
by luisabreu via LA.NET [EN] on 7/3/2009 12:58:22 PM
A few posts back, we’ve introduced the concept of load and store reordering. As we’ve seen, reordering operations exist as a way of improving performance and can be introduced on several levels (starting at compilation time and ending at runtime when the processor executes the instructions). We saw that even though things can get chaotic quickly, there are some guarantees we can hold on to when writing multithreaded code. One of those guarantees is that all platforms respect a specific memory mo ...
by luisabreu via LA.NET [EN] on 7/2/2009 2:45:30 PM
In the previous post, we’ve started looking at interlocked operations. As we’ve seen, interlocked operations are great at what they do but they won’t be usable in all scenarios (ie, don’t think that they’ll solve all your locks problems). To show how things might go awry when using interlocks, I’ll reuse a great example written by Raymond Chen a few years ago (I’m updating it to C#): class Program { private static Object _lock = new Object(); public static Int64 InterlockedMultiply( ...
by luisabreu via LA.NET [EN] on 7/2/2009 11:58:04 AM
As we’ve seen in the previous post, most processors give us important insurances regarding memory loads and stores. However, even though those insurances are important and can be used in several scenarios, the truth is that they aren’t enough for all real world tasks. Fortunately, most processors also offer a group of interlocked operations which enable atomic compare and swap scenarios. These operations rely on hardware and interprocess synchronization. Notice that these operations aren’t as s ...
by luisabreu via LA.NET [EN] on 6/29/2009 9:55:28 AM
Until now, we’ve been busy talking a look at several interesting topics associated with multithreading programming. As we’ve seen, one of the most problematic areas in multithreaded programs is sharing state across multiple threads. As we’ve seen in several posts along this series, we can use a critical regions for ensuring that shared state is accessed by one thread at a time. In other words, using a critical region ensures that access to shared state is serialized leading to correctness of the ...
by luisabreu via LA.NET [EN] on 6/25/2009 10:27:34 AM
In the last posts of the series, we’ve been looking at many important features related to GUIs and multithreading. Today, we’re going to wrap up this topic with the BackgroundWorker class. The previous posts are really targeted at library developers. The truth is that having to implement the EAP pattern to have asynchronous behavior is simply too much work. Interact with the SynchronizationContext object to have asynchronous behavior is really too cumbersome and involves too much boilerp ...
by luisabreu via LA.NET [EN] on 6/24/2009 11:34:12 AM
In the last posts, we’ve taken a look at how synchronization contexts help marshal work across threads. Today we’re going to talk about two classes (which we’ve already met in the past when we implemented the EAP) that abstract even further the use of synchronization contexts: I’m talking about the AsyncOperationManager and AsyncOperation classes. Let’s start with the AsyncOperationManager class. The AsyncOperationManager is a simple helper class with very few lines of code in it, as you can se ...
by luisabreu via LA.NET [EN] on 6/23/2009 11:14:07 AM
In the previous post, we’ve started looking at synchronization contexts. In this post, we’ll take a close look at the widows forms custom synchronization context. Whenever you run a windows form app, you might end up interacting with the WindowsFormsSynchronizationContext. The constructor of this class is responsible for getting a reference to the GUI thread so that it can then create a control which will be used for marshalling the results back to the UI thread. With a valid reference to a con ...
by luisabreu via LA.NET [EN] on 6/23/2009 10:08:22 AM
In the last post, we’ve seen how to marshal back the results obtained on a secondary thread so that controls are updated on the GUI thread. Today we’re going to start looking at synchronization contexts. Synchronization contexts are abstractions for marshalling between threads. In other words, they abstract those scenarios where you cannot call a method from the current thread and need to make sure that the method is executed on a specific thread (as we’ve seen, GUIs fall in this kind of scenari ...
by luisabreu via LA.NET [EN] on 6/22/2009 7:26:37 PM
In the last post, we’ve see that multithreading is almost a necessity in GUIs. We’ve also seen that there are some gotchas associated with it: a control can only be updated from the GUI thread. In practice, this means that we’ll need to marshal back the results to the main thread when they’re ready. In .NET, the Windows Forms introduces the ISynchronizeInvoke interface for performing that kind of operation: public interface ISynchronizeInvoke { IAsyncResult BeginInvoke(Delegate method, objec ...
by luisabreu via LA.NET [EN] on 6/21/2009 12:52:17 PM
In the latest posts, we’ve seen how to implement the event based asynchronous (EAP). When we introduced at the main features of the EAP, I’ve said that you should use this pattern when the consumers of your classes are GUIs programmers. Since we’ve already learned lots of things about EAP, now it’s probably a good time for starting to look at asynchronous programming and GUIs. GUIs are probably one of the areas which will get the most from multithreading. To understand why, we need to make a sm ...
by luisabreu via LA.NET [EN] on 6/20/2009 12:06:54 PM
I know that I’ve said that the next post of the series would be on how to support several asynchronous tasks. However, I was reminded by a friend that I didn’t had any post on how to support the optional progress info feature. So, I decided to take a small detour today and we’ll see how we can modify our class so that it is able to report progress back to the user. As we’ve seen, progress is exposed through an event named ProgressChanged, of type ProgressChangedEventHandler (notice that if you ...
by luisabreu via LA.NET [EN] on 6/18/2009 9:45:36 PM
Today we’re going to improve the code we’ve started writing yesterday: we’re adding canceling support. As you might recall, in our last post we’ve built a simple class which supports a single asynchronous operation at a time. Since we only support one asynchronous operation at a time and we can only start one asynchronous operation from our class, then we only need to add a parameterless CancelAsync method. Here’s how you might implement the CancelAsync method: public void CancelAsync() { & ...
by luisabreu via LA.NET [EN] on 6/17/2009 9:38:35 PM
In the last post of the series, we’ve taken a look at the main features offered by the event based pattern. Today, we’re going to look at how we can implement that pattern. We’re going to start small and we’re going to reuse the IAsyncResult sample for showing how you can implement this pattern. As we’ve seen in the previous post, we need to (at least) add a method (named XXXAsync) that will start the asynchronous operation and an event (named XXXCompleted) that will fire . In practice, this me ...
by luisabreu via LA.NET [EN] on 6/16/2009 3:53:29 PM
After my last post on C# 4.0, I’ve had an interesting exchange of tweets with Thomas Johansen about the usefulness of the code I’ve shown. As Thomas points out, knowing the type means that you should always cast it to that type so that you work with strongly typed verification (ie, compile time checking). In practice, what he’s saying is that example is completely useless because if you know the type of the object you’re creating, then you should always cast it to that type before using it. I d ...
by luisabreu via LA.NET [EN] on 6/16/2009 9:06:24 AM
In the last posts we’ve looked at several details associated with the use of the APM pattern. Today we’re going to start looking at the second pattern for doing asynchronous work: the event based asynchronous pattern. This pattern was introduced with .NET 2.0 and it targets components that are going to be used in GUIs. In other words, if you’re building components that are going to be used by developers that build GUIs, then you should prefer this pattern instead of the APM. To implement this ...
by luisabreu via LA.NET [EN] on 6/15/2009 9:37:30 PM
According to the C# futures site , C# 4.0 is all about dynamic programming. In practice, the idea is to ease the burden that the C# programmer must bear when interacting, for instance, with objects from dynamic languages or with COM objects (notice the docs mention other kind of objects, but these types should be enough for introducing the main ideas). In an old blog entry, I’ve already covered two of the new features: named parameters and optional parameter. Today we’re going to pick up where ...
by luisabreu via LA.NET [EN] on 6/15/2009 10:47:05 AM
Today we’re going to wrap up our study of the APM pattern by seeing how we can implement the IAsyncResult interface. For those that can’t remember, here’s the interface API again: public interface IAsyncResult{ object AsyncState { get; } WaitHandle AsyncWaitHandle { get; } bool CompletedSynchronously { get; } bool IsCompleted { get; } } As we’ve seen in the previous post, we can encapsulate all the asynch ...
by luisabreu via LA.NET [EN] on 6/14/2009 8:42:50 PM
Now that we’ve looked at the available waiting options for the APM pattern, it’s time to start digging on its internals. This post is all about understanding the work of the BeginXXX and EndXXX methods (which isn’t much, as we’ll see). As we’ve seen in previous posts, the BeginXXX method is responsible for kicking off the asynchronous processing. In theory, you’d expect it to create an IAsyncResult which will be responsible for: executing the synchronous action in a different thread (probab ...
by luisabreu via LA.NET [EN] on 6/10/2009 12:35:51 PM
In this post, we’ll take a look at the last option we can use for the rendezvous phase of the APM pattern. This last option is based on the continuation passing style principle. In practice, this means that we need to wrap up the work that should be performed after the async task ends in a closure and pass it to the BeginXXX method. There are some cases where this might not be a viable option. After all, having to pack everything that is needed into a closure so that it can be executed on the c ...
by luisabreu via LA.NET [EN] on 6/10/2009 11:09:46 AM
In this post we’re going to take a look at how we can use polling to see if an asynchronous task has completed. As we’ve seen, the IAsyncResult instance returned from the BeginXXX method (that started an asynchronous task) has an IsCompleted property that returns true when the task is completed. In practice, this means that you can use this property for polling the status of the task. For instance, here’s some based on the previous example that relies on this property: var request = WebR ...
by luisabreu via LA.NET [EN] on 6/9/2009 9:25:06 PM
Today, we’re going to keep looking at the available options waiting for the conclusion of an asynchronous task started through the APM model. In this post we’re going to see how we can use the WaitHandle which we can get through the IAsyncResult’s AsyncWaitHandle property. After getting a valid reference to it, you can do what you normally do with handles: make the thread wait until it gets signaled. You might say: “dude, what’s the difference between this approach and the previous one?” And I ...
by luisabreu via LA.NET [EN] on 6/9/2009 9:49:40 AM
Before getting started, I’d like to say that I don’t really use friend assemblies much. However, there are times where using friend assemblies is a must and in those cases, you might end up getting into the problem I had. For starters, you need to use the InternalsVisibleToAttribute to signal a friend assembly. In my case, I’ve added something like this: [assembly: InternalsVisibleTo("Sra.Core.Entities.Repositories")] Since I tend to sign my assemblies, I’ve ended up getting this err ...
by luisabreu via LA.NET [EN] on 6/9/2009 9:07:33 AM
As we’ve seen, one of the available options is blocking the thread by calling the EndXXX method directly. This might be a good option when you only need to do one or two small tasks and then you need to wait until the asynchronous operation is completed. In practical terms, this option won’t be usable in many scenarios. However, I’d say that this is the easiest of the four available options because you practically don’t need to make any changes to the existing synchronous algorithm you might be ...
by luisabreu via LA.NET [EN] on 6/8/2009 8:50:47 AM
In the last post, we’ve started looking at oldest asynchronous pattern of the .NET framework: the APM model. Today, we’re going to list the available options for waiting to the completion of an asynchronous operation started through a framework that implements APM pattern. After kicking off an asynchronous operation, we have four available options: we can block the thread until work is completed by calling the EndXXX method directly. This is a good approach when we have a couple of extra th ...
by luisabreu via LA.NET [EN] on 6/8/2009 7:54:38 AM
In the last post, we’ve started looking at the APM model used by the .NET framework. Today we’re going to talk about the role played by the IAsyncResult interface. Currently, the IAsyncResult interface has the following members: public interface IAsyncResult { object AsyncState { get; } WaitHandle AsyncWaitHandle { get; } bool CompletedSynchronously { get; } bool IsCompleted { get; } } The AsyncState prop ...
by luisabreu via LA.NET [EN] on 6/7/2009 8:35:56 PM
Today we’re going to keep looking at multithreading on the .NET framework and we’re going to start talking about the oldest async model you’ll find in the .NET framework: the APM (asynchronous programming model). You might be asking why you need an asynchronous programming model and why shouldn’t you use the threads or thread pool directly. The APM is one of two parallel modes (we’ll leave the event based pattern for future posts) we’re going to look at and it can be seen as a pattern for letti ...
by luisabreu via LA.NET [EN] on 6/5/2009 11:36:04 AM
Now that we’ve ended our study of the thread pool, you know that we’ve got two ways of spanning new threads for performing work in parallel: we can manage the thread lifetime by using the Thread class directly or we can rely on thread pool for managing threads for us. Since there are options, you might be wondering which option you should choose for your code. Once more, there’s really no definitive answer: it all depends on your scenario. If I had to give an answer to that, I’d say that most o ...
by luisabreu via LA.NET [EN] on 6/4/2009 1:10:12 PM
When we started looking at how we could use the thread pool for asynchronous work, I (only!) mentioned three options: 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. There is still another option: you can also rely on the thread pool’s I/O completion support and write code that runs a callback – aka completion callback - on a thread from the pool in response to the end of an asynchronou ...
by luisabreu via LA.NET [EN] on 6/3/2009 11:20:24 AM
Yesterday we’ve looked at the theory behind registered waits (btw, there were some errors on that post, but I think I’ve corrected them now). Today, we’re going to look at some code. Let’s see what happens when we use a ManualResetEvent for waiting on: class DumbHandle : WaitHandle { } static void Main(string[] args) { var evt = new ManualResetEvent(false); var counter = 0; var registerWait = ThreadPool.RegisterWaitForSingleObj ...
by luisabreu via LA.NET [EN] on 6/2/2009 10:29:55 PM
In this post, we’re going to keep looking on how we can reuse the thread pool’s threads for executing specific tasks. This post is all about registered waits. A registered wait allows us to specify a callback that will be invoked when a predefined kernel object is signaled. In .NET, we register a wait callback through one of the several static overloads of the RegisterWaitForSingleObject method. Here’s one of those overloads: public static RegisteredWaitHandle RegisterWaitForSingleObject( ...
by luisabreu via LA.NET [EN] on 6/1/2009 1:11:03 PM
As we’ve seen, we can also use the thread pool for executing a (possible recurring) task at a specific time. To do that, we need to take a look at the Timer class. Initializing a timer is done through one of its constructors: public Timer(TimerCallback callback); public Timer(TimerCallback callback, object state, int dueTime, int period); public Timer( TimerCallback callback, object state, long dueTime, long period); public Timer( TimerCallback call ...
by luisabreu via LA.NET [EN] on 6/1/2009 11:55:23 AM
In the last post, we’ve seen how we could use the thread pool for queuing work items that will be executed in one of the existing threads maintained on the default thread pool. As we’ve seen, there’s no way to say “wait for the executing actions” without using one of the synchronization kernel objects we’ve met in previous posts. In that last post, I’ve queued one work item and used a ManualResetEvent for waiting until the work is completed. A friend of mine asked me what’s the best option for ...
by luisabreu via LA.NET [EN] on 5/28/2009 9:01:32 PM
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 sta ...
by luisabreu via LA.NET [EN] on 5/27/2009 6:48:27 PM
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 ...
by luisabreu via LA.NET [EN] on 5/27/2009 5:52:08 PM
A few posts ago, we’ve seen how we could create a producer/consumer stack. Let’s update the example for using condition variables. Here’s the code: class ConcurrentStack<T> { private readonly Object _locker = new Object(); private readonly Stack<T> _stack = new Stack<T>(); public void Push(T element) { lock (_locker) { ...
by luisabreu via LA.NET [EN] on 5/27/2009 3:01:54 PM
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 h ...
by luisabreu via LA.NET [EN] on 5/26/2009 10:45:28 AM
In the previous posts, we’ve seen how we can use monitors and any CLR object for getting a critical region. Whenever you need to get a critical region, using a CLR lock for ensuring proper access. However, there will be times when, for instance, you’ll have much more reads than writes. In these cases, using a lock is still correct, but it is not the best way to get good performance. This is where the reader/writer locks enter. When using these type of locks, a thread will have to specify the t ...
by luisabreu via LA.NET [EN] on 5/25/2009 6:57:30 PM
In the previous post we’ve taken a quick peek at how we can use the CLR lock primitive. In this post we’re going to talk about some interesting things you might need to know when you work with these locks. According to Joe’s reference, the CLR locks use some spinning internally before waiting on a kernel object. Unfortunately, there’s really no way for you to change the time it spins (if you’re a C/C++ programmer, you probably know that you can control the amount of spinning time before waiting) ...
by luisabreu via LA.NET [EN] on 5/25/2009 10:34:29 AM
When we looked at the kernel objects, we’ve seen that we could use a mutex to achieve critical regions. Whenever we need to build a critical section, we should use the CLR locks instead of relying directly on mutexes. In .NET, any object can be used as a lock when you need to build a critical section. Entering the critical section is achieved through the static Monitor.Enter method. When you’re done, you should call the static Monitor.Exit method. Here’s a quick example: var locker = new Objec ...
by luisabreu via LA.NET [EN] on 5/24/2009 8:03:49 PM
In the latest posts, we’ve taken a look at several kernel objects which we can use for data and control synchronization. Today we’re going to start looking at the synchronization primitives. These structures should always be used (whenever possible, of course) instead of the kernel objects we’ve met in previous posts. Why? Because they’re cheaper. Why cheaper? well, the truth is that the kernel objects we’ve looked at in previous posts will always incur in kernel transitions (needed for accessi ...
by luisabreu via LA.NET [EN] on 5/22/2009 10:12:47 AM
In the last post, we’ve talked about several methods that allow us to wait on one or more kernel objects until they transition into the signaled state. Today we’re going to take a look at the last method (exposed by the WaitHandle class) that we can use for waiting on an object: the SignalAndWait method. You can use one of the overloads of this method when you need to signal an existing kernel object and wait on another one until it gets into the signaled state. The coolest thing about this meth ...
by luisabreu via LA.NET [EN] on 5/21/2009 1:26:46 PM
Until now, we’ve seen how we can wait on several synchronization kernel objects until a specific condition is met. All the examples we’ve seen ended up using the simple WaitOne method.Today we’re going to take a look at the other “waiting” methods inherited from the base WaitHandle class: WaitAny and WaitAll. You’ll need these static methods whenever you need to wait on several kernel objects. WaitAll will only unblock when all objects have reached the signaled state; WaitAny will unblock when ...
by luisabreu via LA.NET [EN] on 5/20/2009 11:08:52 AM
Ok, now that we’ve seen the basic kernel synchronization objects that you can use in .NET programming, I guess that it’s a good time to talk about how we can wake up a waiting thread without signaling the kernel object on which the thread is waiting for. In .NET, any blocked thread can be awakened by calling the Thread.Interrupt method. For instance, take a look at the following example, where we create a thread and then make it go to sleep: var anotherThread = new Thread(() => { ...
by luisabreu via LA.NET [EN] on 5/19/2009 5:25:51 PM
[If you’ve just seem a one post sentence, then you’re probably seeing the first Luna’s post :) . She has just managed to publish a one line post while I was checking what was on the TV:)] In the previous post, we’ve taken a quick glance at how we can use the ManualResetEvent. At the time, I did promise another example which might better illustrate its use. So, let’s suppose that we have a class that needs to perform a lengthy operation to initialize a field. Using a ManualResetEvent might be ju ...
by luisabreu via LA.NET [EN] on 5/19/2009 9:17:31 AM
Yesterday we’ve taken a peek at the AutoResetEvent. Today, we’re going to keep looking at kernel objects and we’ll see how we can use the ManualResetEvent for synchronization purposes. I guess that the easiest way to show them doing some work is by going straight to the code. Yesterday we’ve taken a look at a really dumb sample that showed the behavior of the AutoResetEvent class. Today, we’re porting (sort of) that sample so that it uses the ManualResetEvent class: using (var evt = new Manual ...
by luisabreu via LA.NET [EN] on 5/18/2009 1:31:15 PM
After the introductory theory associated with events, it’s time to take a look at how we can use an AutoResetEvent for synchronizing access to a protected resource. The first thing we need to do to start using an AutoResetEvent is getting a reference to a valid instance of this type. We can get one by calling one of the constructors or one of the several overloads of the OpenExisting method: //create new public EventWaitHandle(bool initialState, EventResetMode mode); public EventWaitHandle ...
by luisabreu via LA.NET [EN] on 5/18/2009 12:08:14 PM
I’ve already posted about this topic in the past. However, it looks like there are still some people which don’t take full use of this new (ok, not so new anymore!") cool feature. In my opinion, extension methods are great and they end up simplifying (a lot) the code we need to write. If you’ve been following this blog, I guess that there aren’t any doubts on my position regarding NH use (you should use it whenever you need a good ORM). Unfortunately, there will always be scenarios where y ...
by luisabreu via LA.NET [EN] on 5/18/2009 9:13:50 AM
Windows OS offers two kinds of events: auto and manual-reset events. As you might expect by now, any event can be in a signaled or non-signaled state (after all, both of these events are kernel objects). Instead of using signaled and non-signaled terms, you’ll probably hear the words set and reset when talking about these states. The main difference between auto and manual-reset events relies on the fact that an auto-reset event will automatically reset itself. Notice also that when you use an ...
by luisabreu via LA.NET [EN] on 5/17/2009 2:14:02 PM
In the previous post we’ve seen several concepts associated with semaphore usage. In this post we’re going to see some code that shows how to use this synchronization kernel object. Creating a new semaphore is accomplished through one of the existing constructors: public Semaphore(int initialCount, int maximumCount); public Semaphore(int initialCount, int maximumCount, string name); public Semaphore(int initialCount, int maximumCount, string name, out bool createdNew); public Semaphore( ...
by luisabreu via LA.NET [EN] on 5/15/2009 2:18:28 PM
This post is all about theory…you’ve been warned :) Semaphores have different usage semantics than mutexes. A thread can perform two operations over a semaphore: you can run a put or a take. Internally, the semaphore maintains a count of the numbers of takes and puts through the use of a counter: whenever a thread tries to take take from a semaphore, it will succeed and decrement the counter *if*, at that moment, the counter is bigger than 0. Putting performs the reverse operation. Both operati ...
by luisabreu via LA.NET [EN] on 5/15/2009 10:43:07 AM
In the previous post, we’ve looked at some important features provided by the Mutex kernel object. Today we’re going to keep looking at mutexes and we’ll take a look at how we can create named mutexes and use them for synchronizing access to shared state. true that using kernel objects has costs: when you wait, you’ll always incur in a context switch, which really translates into several “wasted” CPU instructions. But it’s also true that it facilitates other scenarios that the other high level ...
by luisabreu via LA.NET [EN] on 5/14/2009 10:36:40 AM
Ok, now that we understand the basics of waiting on a kernel object, it’s time to keep going and start looking at some code (hurray!). Today we’re going to take a look at the mutex kernel object. In .NET, a mutex kernel object is represented by an instance of type Mutex. As we’ve seen yesterday, the Mutex type sublcasses the WaitHandle type. In practice, we use mutexes to build critical regions, ie, to delimit certain regions of code so that they can only be executed by a thread at a time ...
by luisabreu via LA.NET [EN] on 5/13/2009 10:09:42 PM
After a short break, I’m back for more on multithreading. In the last post, we’ve talked a little bit about synchronization. Today we’re going to keep talking about it and we’re going to take a quick look at how we can use kernel objects for synchronizing access to shared resources or to control the execution of a specific code zone. Initially, I though in going straight to the high level synchronization structures, but since they might end up delegating in these kernel objects, I thought that a ...
by luisabreu via LA.NET [EN] on 5/7/2009 8:44:11 PM
As we’ve been seeing, ensuring proper isolation of data is a good thing for allowing a system to scale and for easing multithreaded programming. In the last post, we’ve seen that we can use the stack for ensuring that each thread gets its own space for saving items without worrying with concurrent writes/reads. At this time, it’s important to understand that most problems we’ll face in multithreaded apps don’t involve scenarios where several threads read a shared value. In other words, if we’ve ...
by luisabreu via LA.NET [EN] on 5/6/2009 10:14:36 AM
In the last post of the series we’ve seen that all threads have a “private” stack (which you can easily configure when you create a new thread or by using the editbin.exe utility, when you need to change the stack size of the main thread). As I said, most (if not all) interactions we have with the stack will be “defined” by the compiler (I’m thinking about the general managed apps we write daily). However, we can also use the thread’s stack explicitly from our code. This might help you when you ...
by luisabreu via LA.NET [EN] on 5/5/2009 9:18:51 AM
Ok, it seems like I’ve missed a couple of interesting classes defined on the SharpArch.Web assembly in my last post. It’s time to fix this and today we’re going to talk about the MvcValidationAdapter and the ValidatableModelBinder classes. Let’s get started with the MvcValidationAdapter class… As you know, S#arp has its own validation thing. We also know that MVC has some validation support into it. The MvcValidationAdapter exists for letting you easily map S#arp validation errors into the MVC ...
by luisabreu via LA.NET [EN] on 5/4/2009 2:06:24 PM
In the last post, we’ve made a quick introduction to the concept of a thread. Today we’re going to keep talking about threads, but we’re going to start looking at some code. As we’ve seen, all processes have (at least!) one thread that is automatically created whenever the process starts running. We’ve also seen that it’s possible to create other (secondary) threads. Today we’ll see how we can do that in managed code. In managed code, a thread is represented by an instance of the type System.Th ...
by luisabreu via LA.NET [EN] on 4/30/2009 9:06:31 AM
Today we’re going to keep looking at the internals of the SharpArch.Web assembly and we’ll take a quick peek at the JsonNetResult class. This is a custom ActionResult class which you can use if you need to return JSON serialized by the Json.NET serializer to the client. As you recall, custom ActionResult classes are supposed to override the ExecuteResult method in order to write the response that is sent back to the client. In this case, the code for that method is really simple: it ...
by luisabreu via LA.NET [EN] on 4/29/2009 12:41:16 PM
This is the second book I have read in multithreading programming (the first was the exceptional Concurrent Programming in Windows, by Joe Duffy). As I've said in the past, this is a topic which really interests me and that's why I gladly accepted a free copy from Packt for review. As you can see from its title, this is (essentially) a beginners book. It's full of code snippets and instructions of where to put that code (where you’re supposed to build demo projects by following the s ...
by luisabreu via LA.NET [EN] on 4/29/2009 12:26:07 PM
Today we’ll keep looking at the SharpArch.Web assembly and we’ll take a quick look at the TransactionAttribute. TransactionAttribute is an ActionFilterAttribute which intercepts the ActionExecuting and ActionExecute exceptions for starting and ending a transaction. Here’s the code for that class: public class TransactionAttribute : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext filterContext) { ...
by luisabreu via LA.NET [EN] on 4/27/2009 7:36:47 PM
In this post we’re going to start looking at the goodies available on the SharpArch.Web assembly introduced by the S#arp framework. This assembly contains several helpers which you can reuse in your ASP.NET MVC projects. In this post, we’re concentrating on the WebSessionStorage class. I’m not sure if you remember it, but we talked about the ISessionStorage a few days ago. As we saw, this interface is used for managing the storage of a session along a specific time. Here’s the interface again, ...
by luisabreu via LA.NET [EN] on 4/27/2009 1:44:30 PM
In the last post I promise that we’d talk about the EntityDuplicateChecker and that’s what we’re going to look at today. As we’ll see, this class is used by the custom NH validators that you can find in the SharpArch.Core.NHibernateValidator. The EntityDuplicateChecker implements the IEntityDuplicateChecker, which looks like this: public interface IEntityDuplicateChecker { bool DoesDuplicateExistWithTypedIdOf<IdT>( ...
by luisabreu via LA.NET [EN] on 4/26/2009 4:25:22 PM
After a small detour into the NH Validator framework (and yes, it was really a small detour since we didn’t see how it integrates really well with NH and other frameworks nor how we can create custom validation rules), in this post we’re going back to our study of the S#arp framework. Today, we’re going to take a deep dive into some of the helper classes that are baked into the SharpArch.Data assembly. We’ll start by looking at the Repository.cs file. This file contains two classes: RepositoryW ...
by luisabreu via LA.NET [EN] on 4/26/2009 10:15:38 AM
One of the nice things you can do to improve the code we’ve seen in the previous post is define the validation rules in an external assembly. By doing this, you can change your rules without having to recompile the assembly that contains the domain objects. To illustrate this, we’ll change the example presented in the last post. The first thing we’ll do is create a new class library assembly to host our Student class. I’m calling it OO and changing the default namespace of the Student class: n ...
by luisabreu via LA.NET [EN] on 4/22/2009 8:51:30 AM
Today we’re going to keep looking at the SharpArch.Core assembly and try to understand its default support for repositories. Before going on, I guess that it’s a good idea to take a detour and talk a little bit about repositories. One of the problems we (developers) face in most applications is that most of the time we’re so worried with infrastructure code that we loose the so needed domain perspective. As we’ve seen in previous posts, we’ll have two basic type of objects: entities and value ob ...
by luisabreu via LA.NET [EN] on 4/20/2009 9:07:02 PM
Today we’re going to keep looking at the S#arp architecture and we’re going to talk about the existing interfaces and base classes that let you work with entities. Before going on, I guess that we should define the concept of entity. According to Eric Evans’ DDD book, you’ll find that “Some objects are not defined primarily by their attributes. They represent a thread of identity that runs through time and often across distinct representations. Sometimes such an object must be matched with anoth ...
by luisabreu via LA.NET [EN] on 4/19/2009 5:28:33 PM
Today we’re going to keep looking at the S#arp framework and we’re going to take a look at how we can reuse the classes introduced by the framework to add validation to an object. Before going on, it’s important to keep in mind that validation is a topic which might generate lots of discussion. For instance, there are lots of people which say that we should never let an object reach an invalid state (a position I’ve been liking a lot lately). Others say that it’s perfectly OK to let an e ...
by luisabreu via LA.NET [EN] on 4/18/2009 8:59:25 PM
If you’ve been involved with DDD, you have surely built several value objects. But what is a value object? Eric Evans defines it (in his seminal work) as being an object which doesn’t have a conceptual identity and that is used for describing a characteristic of a thing. As always, there really isn’t any good rule for identifying value objects since it all depends on the *context* (some objects will be value objects in a context and entities in another). In practice, value objects are immutabl ...
by luisabreu via LA.NET [EN] on 4/18/2009 8:45:19 PM
This marks the beginning of a new series. I’ve already written about it in the past, but I thought that now would be a good idea to go back and take a deep dive on the existing code. What is the S#arp? Here’s the official definition: “Pronounced "Sharp Architecture," this is a solid architectural foundation for rapidly building maintainable web applications leveraging the ASP.NET MVC framework with NHibernate.” As you can see, it focus on two areas which are dear to my heart: DDD and ...
by luisabreu via LA.NET [EN] on 3/24/2009 10:17:22 PM
Ok, here we are again for another episode on the inner workings of the MVC futures assembly. Today, we’re going to take a look at the HtmlHelper extension methods defined on the ViewExtension class. The current release of this class introduces two (static extension) methods which you can use to execute an action “in-place” during the current request: RenderRoute: this method lets you pass a RouteValueDictionary which is added to a RouteData object. Then, the method uses an auxiliary handler ...
by luisabreu via LA.NET [EN] on 3/14/2009 11:20:55 AM
As you know, C# supports the concepts of references and value types. Most of the time, reference types tend to be presented as some sort of synonym for a memory address. I’ve seen it everywhere and I’ve used that analogy too when trying to help others to understand the difference between value types and reference types. Now, this kind of analogy tends to break when you start thinking about the memory model and on how GC works. Say, if reference type is an address, then why do I need to pin it ...
by luisabreu via LA.NET [EN] on 3/7/2009 2:10:43 PM
Update: Andre pointed out that I shouldn’t be calling this a postback because this isn’t posting any data back to the server. And yes, he’s right. Oh well, now it’s too late to change the title so I’ll leave it just like that. So, if you’re reading this, keep in mind that in this post postback should be read as async request to the server] Today we’re going to take a look at the last interesting feature which is available on the AJAX MVC helpers: running a partial postback by clicking on a hype ...
by luisabreu via LA.NET [EN] on 3/3/2009 10:44:47 PM
In the last post we’ve already seen one way to add AJAX to an MVC app: using the AJAX JQuery methods in order to get a JsonResult from the server. In this post we’re going to take a look an another approach: using the MVC AJAX helpers (which are based on the MS client AJAX API) for submitting all the forms’ fields and refreshing a specific zone on the page (ok, if you know ASP.NET AJAX, you can say that this is "”AJAX a la UpdatePanel” :)). Before going on, you should keep in mind that I do ...
by luisabreu via LA.NET [EN] on 3/3/2009 11:16:46 AM
After a few days without talking about ASP.NET MVC, it’s time to resume my study of the platform. Today we’re going to look at a special ActionResult type: the JsonResult class. You can use this specific ActionResult type for returning JSON from a controller’s action method. This class offers three public properties: ContentEncoding: as you can suspect, you can pass an Encoding object that should be used for encoding the response returned from the server; ContentType: used for specifying ...
by luisabreu via LA.NET [EN] on 2/6/2009 10:38:32 AM
In the last post we’ve seen how we can use the AuthorizeAttribute for authorizing a specific request. At the time, I’ve forgot to mention one detail regarding authorization. Besides using the AuthorizeAttribute or creating your own custom attribute for deciding who can access a specific action method, you can also create your custom authentication code by overriding the OnAuthorization method that your controller inherits from ControllerBase. This might be a good option when you want to reuse yo ...
by luisabreu via LA.NET [EN] on 2/5/2009 2:06:49 PM
Today we’ll keep looking at the MVC framework and will see how the you can integrate authentication and authorization in your MVC applications. As we all know, authorization and authentication are different things, but they’re “connected”. I say this because whenever you need to decide if a user can execute a specific operation (ie, whenever you think in authorization), the first thing you need to ensure is that you “know” who the current user is (ie, you have already authenticated the user). T ...
by luisabreu via LA.NET [EN] on 2/4/2009 11:03:04 AM
In the one of the latest's posts, we’ve seen how we can use the AcceptVerbsAttribute to limit the valid HTTP methods that can be used for requesting the execution of an action method. Today we’ll take a closer look at how these items are used at runtime (ie, we’ll see how they are used internally by the platform). Lets start by looking at the ActionMethodSelectorAttribute class. In the RC version, it’s really a simple abstract class with only one method: [AttributeUsage(Attribut ...
by luisabreu via LA.NET [EN] on 2/3/2009 12:41:28 PM
A few days ago I’ve talked about how you could use the helpers to generate dropdowns and listboxes. As I’ve said, you need to build a collection of SelectListItems in order to build these controls. What I didnt’ mentioned at the time was that there is an easy way to convert a custom collection (ie, something which implements IEnumerable<T> interface) into a collection of SelectListItems. To do that, just instantiate the SelectList (or MultiSelectList, if you’re working with listboxes and w ...
by luisabreu via LA.NET [EN] on 2/3/2009 10:44:27 AM
The AcceptVerbsAttribute was introduced in a previous release of the framework and its main objective is to let restrict an action method to certain HTTP method(s) (PUT, POST, etc). So, lets reuse the default web site that is created from the ASP.NET MVC and change the About action method default so that it can only be used through a post request. To achieve this, you only need to add the AcceptVerbsAttribute to the method: [AcceptVerbs("post")] public ActionResult About() { ...
by luisabreu via LA.NET [EN] on 2/2/2009 2:36:36 PM
Yesterday I’ve presented the main properties and methods of the TagBuilder class. Today, we’re going to reuse those ideas and build an extension method that renders an image inside an anchor (unfortunately, the image helper methods are defined in the futures assembly and the current release of the anchors won’t let you pass HTML for its content). Before going on, I’d like to say two things: This isn’t going to be a complete example. What I mean by this is that I’m going to pick up a general ...
by luisabreu via LA.NET [EN] on 1/15/2009 3:15:58 PM
Even though it exists for a long time, there are still some guys which are surprised whenever they see something like this: global::System.Console.WriteLine( “Hello” ); what is that global:: thing over there? Well, it’s there for saying that search for the System.Console class should start at the global namespace. You’ll need this kind of thing whenever you have types/namespaces that hide the global ones. The documentation on MSDN explains all these concepts really well, so I’ll just redirect ...
by via LA.NET [EN] on 12/2/2008 10:33:25 AM
While I was reading the Essential Windows Communication Foundation book (from Addision Wesley), I found the following code (on a transaction required for a WCF service context): [OperationBehavior(TransactionScopeRequired = true, TransactionAutoComplete = true)] public void Transfer( String from, String to, double amount){ try { Withdraw(from, amount); Deposit( to, amount); } catch(Exception ex){ ...
by luisabreu via LA.NET [EN] on 11/12/2008 10:43:41 PM
Today we’re going to keep looking at Code Contracts. Until now, I’ve been concentrating essentially in presenting its use and mentioning how great it is to have static analysis (ie, have something that goes through your code at compile time and detects several places which might breaking existing contracts). Today it’s time to take a look at the advantages associated with its use at runtime. You’ll get runtime “support” (lets call it this, ok?) whenever you define the CONTRACTS_FULL constant on ...
by luisabreu via LA.NET [EN] on 11/10/2008 9:21:40 PM
After several failed tries, I finally managed to configure my home PC so that it runs the Server 2008 image (with the first preview of .NET 4.0) and just with a reasonable enough delay. Ok, since I'm finishing writing a book on C# 3.0 (with my good friend Paulo), I thought that I should start by looking at C# 4.0. As has been said, C# 4.0 will be mostly on dynamic programming features. To start my study, I've just picked a random feature: named parameters. The first thing I've notic ...
by luisabreu via LA.NET [EN] on 11/8/2008 12:09:08 PM
Before using Code Contracts, you’ll probably already written several lines of validation code for testing requirements on your methods. I’ll keep using the Person class to illustrate some code that you might have before using the Code Contracts library. So, in the past, you might have something like this: public class Person { private String _firstName; private String _lastName; ...
by luisabreu via LA.NET [EN] on 11/7/2008 8:52:40 PM
[Update: I’ve changed the code so that the contract class implements the interface explicitly. This is required for getting static analysis. One more thing: the first release of the project has a bug and even if you implement the interface explicitly, you won’t get static analysis.] One of the interest things Code Contracts lets you do is define additional contracts on your interfaces. To achieve this, you need to add a “dumb” class which implements that interface and add the required con ...
by via LA.NET [EN] on 11/6/2008 9:57:05 PM
In this post we’ll keep looking at how Code Contracts can really help you improve your code. Today, we’ll see how one can use fields and out parameters in contracts. Lets start with fields. Ok, the title is a little misleading…you can use fields in your contract. But what happens when you need to define a contract on an private field from a public method? Well, lets think about this for a minute…your clients must check for values so that they won’t break the contract. If you’re specifying a cont ...
by via LA.NET [EN] on 11/6/2008 9:18:01 PM
In my first post about Code Contracts I’ve mentioned that in my machine static analysis wasn’t picking up those evident scenarios where the code was breaking the predefined contracts. Today I’ve got the confirmation on the PEX forum (which, btw, is the place where you should post your questions regarding this framework while we don’t have a discussion place for this framework). ...
by via LA.NET [EN] on 11/6/2008 9:01:34 PM
Today I’ll keep writing about the new Code Contracts framework and we’ll see how we can use the write contracts that validate method return values and “old” values. Lets start with method return values… As you might expect, you’re able to refer to return values on your postconditions. To show you the kind of thing you’ll be writing, we will start by changing the class we presented yesterday and we’ll add a BirthDate property to it: class Student{ private DateTime _birthDate; public DateTim ...
by luisabreu via LA.NET [EN] on 11/6/2008 2:13:29 PM
One of the things that I’ve needed to do in the past is filter a sequence of items and then execute a specific method over each of those filtered instances. The Enumerable class introduces several methods, but it doesn’t have any that lets me pass an Action<T> that is invoked over each instance of an IEnumerable<T>. So, what you tipically end up doing is something like this: var filteredItems = existingItems.Where( item => … ); foreach( var item in filteredItems ){ it ...
by luisabreu via LA.NET [EN] on 11/5/2008 9:51:45 PM
Yesterday I was really excited after finding out that we’ll finally have a library for performing Design By Contract verifications on our code. Ok, the runtime validations could already be simulated by writing some code (I’ve already written several helpers classes in my current applications), but the truth is that the Code Contracts library adds static verification and will enable you to catch several errors during compilation. I believe this is more than enough for you to be interested in this ...
by luisabreu via LA.NET [EN] on 10/30/2008 9:44:21 AM
One of the things that we’ll have in C# 4.0 is covariance/contravariace working on generics…I mean, sort of. Why do I say sort of? Well, because you’ll have to use the identifiers in and out for explicitly stating if you’ll be having covariance or contravariance and you can’t use them at the some time. Charlie Calvert has a good post on this subject, so you should read it before we go on. Don’t get me wrong: having this basic support is better than having none, but I expected a little more from ...
by luisabreu via LA.NET [EN] on 10/24/2008 1:38:02 PM
If you’re a NHibernate user, you’ve surelly heard about the Fluent NHibernate, a project that allows you to define the mappings by using a fluent API. I didn’t really had the time for testing it until yesterday. Why did I only tested it yesterday? Simple: because I had to perform some major refactorings on the current project I’m working and that meant having to go through the XML mappings files and changing all those damn properties by hand. Yes, it was the perfect excuse for introducing the fl ...
by via LA.NET [EN] on 10/20/2008 9:08:00 PM
I think that adding verifiability to the language would be great. MS Research has been working on Spec# for some time now, but it seems like it’s always behind the current C# release (for instance, the current version works against C# 2.0, but who wants to go back after using C# 3.0? Not me…). Yes, in the current release you can try to apply some of the features introduced by Design by Contract, but you’ll only get a limits subset of what Spec# gives you (and you’ll only be able to do runtime v ...
by luisabreu via LA.NET [EN] on 10/20/2008 2:20:53 PM
One of the things I’ve been using lately is FxCop. It’s really an interesting tool and I’ve corrected several API problems on my classes after starting using it. In fact, I’ve only found two problems until now: Interface explicit implementation Incorrect spelling of names Ok, let’s start by problem number 1. Here’s the code I’m using: public class Something: ISomething{ void ISomething.DoSomething(){ DoSomething(); } protected virtual ...
by via LA.NET [EN] on 9/24/2008 11:31:31 AM
Much has been said about extension methods. Some love it; others see them as evil. Good discussions have been made on when to use them (and when not to use them). Greg Young had a good post on when you might want to use them whenever you control the code of a class (btw, that is good advice that I have been using in my projects with lots of success). Lately, I’ve been using extension methods for improving an existing API. Let me give you an example. In these last months, I’ve been writing lot ...
by luisabreu via LA.NET [EN] on 7/15/2008 10:24:41 PM
Yes, it's one of those posts where you either agree or disagree completely :) Anyway, after having a 15 minutes discussion with my friend Paulo (which, btw and as usual, disagrees with me) yesterday at 1AM, I've decided to write this post. The problem: MS recommends that variable names shouldn't have any sort of prefix like the _ or m_. And what do I think? Well, I don't like! And I will only use that it my boss say something like: "hey, you must use that or we stop paying ...
by luisabreu via LA.NET [EN] on 7/8/2008 8:17:49 AM
Ok, so you already know the answer, right? That’s why the String class has the Contains method. And it will work until you need to explicitly need to use a different StringComparison option than the one that is used by default. If like me, you know that Reflector is your friend, then you can just open it and see how the Contains method is implemented. Basically, what you need is a new extension method that looks like this: public static class StringExtensions { ...
by luisabreu via LA.NET [EN] on 6/20/2008 10:37:01 AM
I’m still not understanding why it won’t give me a warning when I create an internal class with a public method. Here’s an example: class MyInternalClass{ public void Test(){} //no compiler warning } Ok, at the end of the day, Test is really an “internal” method since the acessibility of a member can never be greater than the one of its containing type. But why can’t I get at least a warning? In this case, setting the method type to internal should be the “m ...
by luisabreu via LA.NET [EN] on 5/30/2008 2:39:50 PM
Well, not really... As you surely know, you cannot have mutiple inheritance in .NET. That really sucks. Yes, I agree that multiple inheritance might bring several problems but when applied correctly, it really helps. Don't believe me? Ok, take a look at WTL. Back to .NET...Since we can't use multiple inheritance, we end up defining several interfaces and injecting classes that implement the generic boilerplate code for those interfaces. With Windsor (or any other existing containe ...
by luisabreu via LA.NET [EN] on 5/17/2008 11:01:24 PM
Now that we know the basics, it's time to see how we can use this new API with LINQ. In this post, we'll start by seeing how we can filter an XML document and then we'll how easy it is to transform an existing XML tree into a different one. Lets start by defining an existing XML tree (we'll simply reuse the tree from the previous example): var xml = new XElement( "clients", ...
by luisabreu via LA.NET [EN] on 5/8/2008 9:39:20 PM
One of the things you might need doing is changing the contents of an existing XML tree. As you might expect, this is possible with the new LINQ To XML API. Lets start with the existing XML tree presented on one of the latests posts. I'm just putting it here again so that you don't have to open another window if you're interested in following the rest of the post. var xml = new XElement( "clients",   ...
by luisabreu via LA.NET [EN] on 5/7/2008 9:41:46 PM
In the last post of the series, we've seen how easy it is to navigate along the axis with the new LINQ To XML API. At the time, I've promised another post on how to use XPath to navigate along the XML tree. That's the objective of today's post. If you look carefully at the XElement class (or at its base, XNode), you'll see that there really isn't any method that expects an XPath expression. So, your first reaction might be thinking that XPath queries aren't supported ...
by luisabreu via LA.NET [EN] on 5/1/2008 8:48:26 PM
In the previous posts I've presented some of the basic features introduced by the new LINQ To XML API. Today, we'll keep digging and I'll show you several options available for working with XML documents. As we've seen in the other day, documents are represented by instances of the XDocument class. You'll really need to use a XDocument when you need to load a DTD or when you need to add a processing instruction. Lets suppose you need to apply a XSL stylesheet to your XML tree ...
by luisabreu via LA.NET [EN] on 4/29/2008 10:11:36 PM
In the previous post I've talked about some of the classes you'll find in this new API. Today we'll see how easy it is to create a new XML document with the new API. Most of the time, you'll end up working with the XElement or XAttribute classes. Lets start with an existing XML tree: <clients> <client id="1"> <name>Luis</name> <address> <street>Some place</stre ...
by luisabreu via LA.NET [EN] on 4/28/2008 9:21:11 PM
I've just started doing some LINQ To XML and I can assure you that the new API is really great! Just take a look at the new Object Model introduced by the System.XML.Linq assembly: Today I'll just cover the basics (really a quick presentation of the most important elements you can find in the new API), but I'm thinking on writing more posts on this subject. XObject is the top base element introduced by this new XML API. It's main objective is to let you add annotations to any e ...
by luisabreu via LA.NET [EN] on 4/26/2008 11:29:05 AM
.NET 2.0 introduced Nullable value types. As you surely know by now, you cannot set a value type to null. Here's an example: Int32 myVar = null; //error: myVar cannot be set to null This can be easily solved by transforming myVar into a Nullable type: Nullable<Int32> myVar = null; If you prefer, you can apply the ? suffix to the variable type: Int32? myVar = null; Nullable value types are great when, for instance, you're getting a value from a table's column and that column can ...
by luisabreu via LA.NET [EN] on 4/16/2008 12:47:41 PM
[Update: Thanks to Mike for uncovering a bug on the sample. It should be IDummy.Increment and not Dumy.Increment. Thanks Mike and now I think it should compile without any problems.] In these last days I've been reading the C# spec and you can say that I've been re-discovering it :) If you really think about it, I think that it's fair to say that most people will only use the basic features of the language. And since many things work as they should (ie, they work in a logical manner) ...
by luisabreu via LA.NET [EN] on 1/2/2008 2:43:38 PM
I'll just start by wishing you all a great 2008! Now, to what used to be a somewhat philosophical question: should you use this to reference a member of your class in your code? Ex: should you write this.CallInstanceMethod() ? Ok, in pre-C# 3.0, I'd say NO. With the current release, I'm saying maybe! Why? Simple: extensions methods. To call them, you must always pass a reference to the type, which means that if you're calling an extension method from a class method (which is a sc ...
by luisabreu via LA.NET [EN] on 11/7/2007 10:46:30 PM
As I've said in previous entries, I'm updating my ASP.NET 2.0 book to the new version. One of the controls that will be added to the platform is the LinqDataSource control. The control will let you perform any LINQ expression against any IEnumerable data source. Scott Guthrie has already a cool post that shows how to use the control over a LINQ to SQL model. What I wanted was to use the control against a collection of objects. If you've used the control, you know that it requires yo ...
by luisabreu via LA.NET [EN] on 11/5/2007 12:31:44 PM
In these last days, I've been looking at LINQ. I'm still not sure if this will help me build applications easily or if the new features introduced on the C# language are making it a lot more complex than it should be (when I make up my mind, I'll let you know :)). Anyway, LINQ brings us some cool things and that's why I'm taking a look at it. before delving into LINQ, we should understand the new features of the C# language that support it. Today I'm going to write about ...
by luisabreu via LA.NET [EN] on 9/24/2007 11:19:15 PM
[Update: Paulo was not impressed with this post but he didn't want to point it out in the comments. Next time, don't be shy :) He thinks I should drop the old sytax and write thread-safe code. As always, he's right. Let's be clear: if you're creating a new EventHandler event type, just use the generic EventHandler<T> type. You'll write less and achieve the same thing. Another thing: if you're writing multithreaded apps - for instance, Windows Forms apps - then d ...
by luisabreu via LA.NET [EN] on 9/17/2007 10:23:56 PM
Properties are strange beasts...in fact, when you access a property, you're really calling a method. Let's start with a simple example that shows a "parameterless property": public class Person{ public String Name; private String _address; public String Address { get { return _address; } set { _address ...
by luisabreu via LA.NET [EN] on 9/10/2007 10:46:52 PM
Well, today it's all about delegates! If you're looking for an intro on the subject, then there's already several articles out there (this one by Chris Sells is good way to start). This pos tries to explain what happens when you compile a delegate from C# code. Ok, so lets start with a quick delegate definition that I'll be using in this post to explain how things work: public void delegate SayHi(string name); If you use reflector and look at IL, you'll see something si ...
by luisabreu via LA.NET [EN] on 9/7/2007 8:55:34 AM
According to the C# specification, an enum is "a distinct set of value types that declares a set of named constants.". When you program in C#, you declare an enum through the enum keyword. Here's a quick example: public enum Permission{ Read, Write} When you build this code, you'll get the following IL: .class public auto ansi sealed E extends [mscorlib]System.Enum{ .field public static literal valuetype Livro.E ...
by luisabreu via LA.NET [EN] on 9/6/2007 11:39:45 AM
but only because the language is a CLS compatible language. In C#, a type have several many methods with the same name provided they have different set of parameters. This feature is called overloading. The C# standard bases its overload concept on the notion of signature. In C#, the signature of a method is formed by its name and its parameter set. Notice that the return type of a method isn't included on its signature! The following list exemplifies this concept: void Method();void Method( ...
by luisabreu via LA.NET [EN] on 9/5/2007 8:43:20 PM
[Update. My friend Paulo thinks I should be more specific on this and so I'm updating my example so that it works in the correct context - ie, when declaring the variables on a block] It depends. The main objective of the new operator is to allocate the necessary space in the managed heap for maintaining an instance of specific reference type. As it's well known, the next lines produce similar results: struct MyValueType{ public Int32 _field;} void SomeMethod(){ MyValue ...
by luisabreu via LA.NET [EN] on 9/3/2007 9:56:04 PM
(that's what someone asked me today) And the answer is...yes and no. I've went to the specs to confirm my thoughts and according to it, the order declaration matters only in the following scenarios: fields: the way you put your fields in the class specifies the order in which they're initialized; local variables must be initialized before they are used; for enumerations, the order is important if you don't specify its constant values explicitly. 1 and 3 are relatively obvious, b ...
by luisabreu via LA.NET [EN] on 7/3/2007 7:10:09 AM
[Update: I must have been drinking when i wrote this :) It should be local domain because you cannot get objects from a remote host through the BrowserHttpWebRequest] These 2 just made me loose +45 minutes: 1. if you're using the BrowserHttpWebRequest to download files from a remote domain, then make sure you're testing your page from a web server (the internal server that comes with VS works, but you'll start getting the object is not on the correct state exception -or something lik ...
by luisabreu via LA.NET [EN] on 6/21/2007 10:58:45 AM
Well, it ended up being easier than I though. You have two options: use the glyphs object or download the font using a downloader object and then associate it with the TextBlock object that has the text you want to show. There are already two excellent posts that show these options: a cool glyph explorer: http://geekswithblogs.net/WynApseTechnicalMusings/archive/2007/05/08/112335.aspx The textblock approach: http://blogs.msdn.com/webnext/archive/2007/05/18/silverlight-textblock-and-asian-fonts. ...
by luisabreu via LA.NET [EN] on 6/20/2007 10:40:56 AM
You can use the initParams property of the Siverlight control to pass aditional infomation during the creation of the control. There's already a property which should let you get it from managed code:StartupArguments. Unfortunately, it wil always return an empty string in the current release: WebApplication.Current.StartupArguments Yasser suggested a workaround for the current version untill we get a new release that lets us get the value correctly. His idea was to call a ...
by luisabreu via LA.NET [EN] on 6/15/2007 7:02:58 PM
Simple: call one of the overloads of the static Submit methods exposed by the HtmlPage class: HtmlPage.Submit(); HtmlPage.Submit( "formId" ); If you only have a form on you're page, then using the first option is the way to go. if you have several forms, you need to specify the id of the form you're submiting and you need the second overload. Simple, right? ...
by luisabreu via LA.NET [EN] on 6/12/2007 10:43:58 PM
Yesterday I talked about calling a traditional ASMX web service from your Silverlight app. Today, I'll be talking about WCF services. As I've said yesterday, in the current release, you only have tool support for getting a proxy to an ASMX web service (well, at least I've tried getting a web reference to a WCF service and it simply didn't work - maybe i'm doing something wrong). However, nothing prevents you from creating your own proxy to make the call to a WCF se ...
by luisabreu via LA.NET [EN] on 5/22/2007 2:44:19 PM
The 3.5 beta version of the .NET platform lets us use JSON as the serialization format used by a web service call. The best of all is that this means that we can now call a web service from an ASP.NET AJAX page. To do this, you need to add some entries to your configuration file (on the server side). Getting a proxy on the client side is a simple as adding a service reference through the ScriptManager control. Lets start by seeing the service code (which was generated by adding a new WCF se ...
by luisabreu via LA.NET [EN] on 5/14/2007 6:14:46 PM
In the last post, I've talked about the DynamicList control. Today, we'll keep going and I'll be presenting the new DynamicDetails control. You shouldn't be surprised to hear that this control will use a DetailsView to present a record at a time to the user. Almost everything I've said regarding the DynamicList control, is true when we use this control. There are some differences, though, as we'll see in the next paragraphs. When using this control, the columns presented ...
by luisabreu via LA.NET [EN] on 5/13/2007 10:24:50 PM
[After talking with my friend JPC, I think I should change the title of these posts After all, aspx pages are DYNAMIC pages!] During this post, I'll use the tables I've created in the last post about dynamic pages. Today, we're going to take a look at the DynamicList control. We'll start by creating a new dynamic page, called Students.aspx (note that the name of the page is important. it's used to map the current page to a table maintained in the database), and after dr ...
by luisabreu via LA.NET [EN] on 4/26/2007 5:19:39 PM
After installing the Silverlight templates, I've started learning it by trying to build a new button control (the choice may seem strange, but currently Silverlight doesn't have any controls). Well, if you create a new project based on the template, you'll see that it already has code that reproduces the basic behavior of a button. After looking at the code, I thought that most of the button's behavior could be built directly from XAML (at least, that's what i thought th ...
by luisabreu via LA.NET [EN] on 4/20/2007 6:31:01 PM
Mike Taulty has produced some cool videos on LINQ. here's the current list: Introduction to LINQ to SQL A tour around the data context Mapping .NET types to relational schema Tools for generating mapping information Inserting Data Keep them coming please! ...
by luisabreu via LA.NET [EN] on 3/21/2007 10:44:42 PM
The AJAXToolkit introduces a Timespan class that lets you do some interesting things with time intervals. After looking at the class (which is defined on the datetime.js file, inside the common folder), it's obvious that it tries to mimic the Timestamp class of the .NET platform. The good news is that you'll be right at home if you have any experience with that class :) You can create a new timespan in several ways. Lets start with the constructor. Internally, the class defines several auxiliary ...
by luisabreu via LA.NET [EN] on 3/7/2007 4:14:50 PM
Today I was asked to measure the duration of the partial (or async) postback request. Since we didn't need to measure everything (ie, the packaging of the field forms), I've built a simple page that might help you getting that info. The idea is to handle the initializeRequest event (which happens after the fields of the form have been packed) and the endRequest event. Here's the js code I've used: <script type="text/javascript"> Sys.WebForms.PageRequestManager.getInstance().add ...
by luisabreu via LA.NET [EN] on 3/7/2007 3:17:03 PM
As we all know, it's possible to reuse the ASP.NET authentication services and perform the authentication of the credentials of a user from the client side by using the Sys.Service._AuthenticationService class (a global object is inserted in all AJAX pages - Sys.Service.AuthenticationService - which you can use to login or logout a user). By default, this client class makes a specific web service call which AJAX knows how to handle in the server side (btw, the internal AuthenticationSe ...
The content of the postings is owned by the respective author. CSharpFeeds is not responsible for the contents of the postings. This site is automatically generated and cannot be reviewed for abusive content. If you find abusive content on CSharpFeeds, please contact us. Designated trademarks and brands are the property of their respective owners. All rights reserved.