In this post I’ll show you how to configure your Visual Studio 2010 to step into the source code of .NET Framework 4.0 in 9 easy steps.

  1. Download the 167Mb installer that contains the logic and data required to install Reference Source, .Net 4.0. On the download page table, its named “.Net”, Version: 4.
  2. Execute the installer “Net_4.msi” that you have downloaded in the previous step.
  3. Install it onto a path of your choice. Example “C:\Development\Framework 4 Source
  4. Launch Visual Studio 2010. From the Tools menu, choose Options and open the Debugging node.
  5. Select General, then do the following:
    • Uncheck “Enable Just My Code (Managed only)”
    • Check “Enable source server support”
    • Uncheck “Require source files to exactly match the original version”
    • Optional: Uncheck “Step over properties and operators (Managed only)”
  6. Select Symbols under Debugging.
  7. In the Symbol File Locations box, add the downloaded symbols location: “C:\Development\Framework 4 Source\Symbols
  8. Enter in text box under ‘Cache symbols in this directory’: “C:\Development\Framework 4 Source\Symbols\Cache
  9. That’s it, you can now Step Into .NET source code. Happy sessions!

Technorati Tags: , ,

Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)

PowerSQL dumping tool available

0

I made available a small utility that allows you to script SQL Server data onto sql/txt files. It’s an old tool I used on several real world scenarios and it worked pretty well. It saved me a lot of time on many ocasions.

Although it isn’t finished, I thought of posting it so that you can save some time as well. Feel free to comment and don’t forget: use it at your own discretion.

Some of the features included are:

  • SQL Server 2000 and 2005 support (2008 version’s new datatypes are yet to be added)
  • Lists database tables, stored procedures and views
  • Shows table schema info
  • Dumps SQL Server table data onto configurable sql/txt files
  • Set file size limit
  • File per table option
  • Maximum file size setting allows you to generate several, smaller, files
  • View and Stored Procedure viewer and editor

From the PowerSQL homepage: “Keep in mind that this is a small utility I’ve made for my daily usage, and It’s still buggy, so use it at your discretion. I’ve used it successfully for several times in big production databases, but there’s allways room for error. Leave some feedback if you encounter urgent bugs, I’ll try to fix them. In the meantime I’ll try to get the time to make it a v1…”

Check out PowerSQL Homepage  to download, and don’t forget to leave some feedback.

Technorati Tags: ,

Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)

WPF Input Validation Part 2: Attached property approach

3

 In the previous article I’ve shown how to apply Validation Rules to controls in order to prevent/access user input. In the process, user was warned through a visual change in the target control. It’s the simplistic and direct way of doing validation and works perfectly from the UX point of view. However, from the developer point of view, a better implementation is required to ease the quantity of code needed and to isolate concerns.

The idea is to apply validation rules by means of an attached property, in which the owner would have the reference to the control and its target Dependency Property, and the required logic to add the rule object implicitly.

We’ll assume the WPF window of the previous example and proceed from there. The biggest difference rests is the XAML. The TextBox no longer has a validation rule and, instead, an attached property was added. We’ll discuss it afterwards.

<Window x:Class="ValidationSample2.ValidationWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:Rules="clr-namespace:ValidationSample2"
    Title="ValidationWindow" Height="200" Width="300">
    <Window.Resources>
        <Style x:Key="EditableTextBox" TargetType="TextBox" BasedOn="{StaticResource {x:Type TextBox}}">
            <Setter Property="Background" Value="#DDFFDD" />
            <Setter Property="Validation.ErrorTemplate">
                <Setter.Value>
                    <ControlTemplate>
                        <Border BorderBrush="Red" BorderThickness="2">
                            <AdornedElementPlaceholder />
                        </Border>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
            <Style.Triggers>
                <Trigger Property="Validation.HasError" Value="true">
                    <Setter Property="Background" Value="#FFDDDD"/>
                </Trigger>
            </Style.Triggers>
        </Style>
    </Window.Resources>
    <Grid VerticalAlignment="Center" HorizontalAlignment="Center">
        <StackPanel Name="ValidationPanel" >
            <Label>Validated Text Box:</Label>
            <!-- UpdateSourceTrigger is needed in order to raise property change event on input
            and not on focus, which is the default behavior -->
            <TextBox x:Name="ValidatedTextBox" Width="200"
                     Rules:MandatoryRule.TargetProperty="{x:Static TextBox.TextProperty}"
                     Style="{DynamicResource EditableTextBox}" Text="{Binding Path=MyProperty, UpdateSourceTrigger=PropertyChanged}" />
        </StackPanel>
    </Grid>
</Window>

As you can see, things got much simpler. A single property set is all there is in order to set my mandatory input rule. So how do we do this? It’s pretty simple, actually. I’ve created a static class called MandatoryInput and, as you can see in XAML, I’ve defined the TargetProperty attached property and I’m registering on the static constructor. The essence of this implementation happens when this property’s value changes. Check out the full blown implementation that follows:

#region #using Directives

using System;
using System.Windows;
using System.Windows.Controls;

#endregion

namespace ValidationSample2
{
    public static class MandatoryRule
    {
        #region Dependency Properties

        public static readonly DependencyProperty TargetProperty;

        #region Get/Sets

        public static DependencyProperty GetTargetProperty(UIElement target)
        {
            return target.GetValue(TargetProperty) as DependencyProperty;
        }

        public static void SetTargetProperty(UIElement target, DependencyProperty value)
        {
            target.SetValue(TargetProperty, value);
        }

        #endregion

        #endregion

        #region Constructor

        static MandatoryRule()
        {
            TargetProperty = DependencyProperty.RegisterAttached("Target",
                                                                 typeof (DependencyProperty), typeof (MandatoryRule),
                                                                 new UIPropertyMetadata(null, OnTargetPropertyChanged));
        }

        #endregion

        #region Event handlers

        private static void OnTargetPropertyChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)
        {
            if (!(obj is UIElement))
                throw new InvalidOperationException("Object must be a UI element.");

            SetValidationRule(obj, args.NewValue as DependencyProperty);
        }

        #endregion

        #region Methods

        private static void SetValidationRule(DependencyObject obj, DependencyProperty property)
        {
            if (property == null)
                throw new InvalidOperationException("No Validation DependencyProperty attached.");

            GetRule(obj, property);
        }

        private static void GetRule(DependencyObject obj, DependencyProperty property)
        {
            var control = obj as Control;

            if (!control.IsInitialized)
            {
                RoutedEventHandler callback = null;
                callback = delegate
                               {
                                   control.Loaded -= callback;
                                   SetValidationRule(obj, property);
                               };
                control.Loaded += callback;
                return;
            }

            var expression = control.GetBindingExpression(property);
            if (expression == null)
                throw new InvalidOperationException(
                    "The control's validation property must be bound for the Validator to validate it.");

            var binding = expression.ParentBinding;
            if (binding == null)
                throw new ApplicationException("Property binding expression has no parent binding.");

            ValidationRule mandatoryRule = null;
            foreach (var rule in binding.ValidationRules)
            {
                if (rule is MandatoryInputRule)
                {
                    if (mandatoryRule == null)
                        mandatoryRule = rule as MandatoryInputRule;
                    else
                        throw new InvalidOperationException(
                            "There's more than one MandatoryInputRule in the Binding's ValidationRules.");
                }
            }

            if (mandatoryRule == null)
            {
                mandatoryRule = new MandatoryInputRule();
                binding.ValidationRules.Add(mandatoryRule);
            }
        }

        #endregion
    }
}

As an attached property, I had to create the usual Get[PropertyName] and Set[PropertyName] methods so that these could actually set the values in the control. The idea is for this property to hold the target control’s dependency property we are going to interact with, and upon property change notification, execute our logic.

However, this notification actually  comes in two distinct phases. The first one happens when the XAML is processed by the XAML parser and the last is when it’s actually initialized. As you can see in the code, the GetRule() method is called on such occasions, however, binding data will only be available when the affected control is initialized, so it is crucial to do our work only when. So, on the first phase, since the control isn’t yet initialized, we just set an event handler to execute when control is Loaded. This event handler will call the same SetValidationRule() method who attached it in the first place, but in that point in time, it will proceed all the way to the binding manipulation.

So the trick here is to fetch the BindingExpression on the target DependencyProperty of the affected control. Keep in mind that a BindingExpression is an underlying object that knows the connection between the binding source and the binding target. On the other hand, a Binding is merely a higher level object in the binding mechanism that contains all the information about the binding source and the nature of the binding, and can be shared across several BindingExpression objects.

Moving on, with our BindingExpression, we then get the Binding object and add our validation rule to it, validating duplicates in the process. And that’s all there is to it.

I know this already leverages the implementation and code required, and most people would be comfortable with this, but we still must set UpdateSourceTrigger on the Binding object, otherwise input validation only occurs when the textbox loses focus. Since others, and myself would have a “mission incomplete” kind of feeling, we’ll move on.

At this moment, you may be thinking in changing the value of UpdateSourceTrigger in the GetRule() method, where the binding object is exposed:

(...)
var binding = expression.ParentBinding;
binding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
(...)

 You could indeed to it, and the app would compile just fine. But at runtime you would get the following exception: “Binding cannot be changed after it has been used”. If you think about it, it makes sense, because when a binding is set, the event wiring is created in order for change notifications to go from source to target and vice-versa. So this means that a new binding object must be created, and then set on the target DependencyProperty. The following variant of the GetRule() method exposes this like of thinking:

static void GetRule(DependencyObject obj, DependencyProperty property)
{
    var control = obj as Control;

    if (!control.IsInitialized)
    {
        RoutedEventHandler callback = null;
        callback = delegate
                       {
                           control.Loaded -= callback;
                           SetValidationRule(obj, property);
                       };
        control.Loaded += callback;
        return;
    }

    var expression = control.GetBindingExpression(property);
    if (expression == null)
        throw new InvalidOperationException("The control's validation property must be bound for the Validator to validate it.");

    var binding = expression.ParentBinding;
    if (binding == null)
        throw new ApplicationException("Property binding expression has no parent binding.");

    /*
     * The TextBox.Text property has a default UpdateSourceTrigger value of LostFocus.
     * This means that the text you type into the TextBox does not update the source
     * until the TextBox loses focus. This causes a runtime exception 'Binding cannot
     * be changed after it has been used'. So we must reset the binding.
    */

    if (binding.UpdateSourceTrigger == UpdateSourceTrigger.Default)
    {
        var bind = new Binding() {
                                     Mode = binding.Mode,
                                     UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged,
                                     Path = binding.Path,
                                     BindsDirectlyToSource = binding.BindsDirectlyToSource,
                                     Converter = binding.Converter,
                                     ConverterCulture = binding.ConverterCulture,
                                     ConverterParameter = binding.ConverterParameter,
                                     FallbackValue = binding.FallbackValue,
                                     IsAsync = binding.IsAsync,
                                     NotifyOnSourceUpdated = binding.NotifyOnSourceUpdated,
                                     NotifyOnTargetUpdated = binding.NotifyOnTargetUpdated,
                                     NotifyOnValidationError = binding.NotifyOnValidationError,
                                     StringFormat = binding.StringFormat,
                                     TargetNullValue = binding.TargetNullValue,
                                     UpdateSourceExceptionFilter = binding.UpdateSourceExceptionFilter,
                                     ValidatesOnDataErrors = binding.ValidatesOnDataErrors,
                                     ValidatesOnExceptions = binding.ValidatesOnExceptions,
                                     XPath = binding.XPath
                                 };

        if (binding.ElementName == null && binding.RelativeSource == null)
            bind.Source = control.DataContext;
        else if (binding.Source == null && binding.RelativeSource == null)
            bind.ElementName = binding.ElementName;
        else
            bind.RelativeSource = binding.RelativeSource;

        binding = bind;
    }

    ValidationRule mandatoryRule = null;
    foreach (ValidationRule rule in binding.ValidationRules)
    {
        if (rule is MandatoryInputRule)
        {
            if (mandatoryRule == null)
                mandatoryRule = rule as MandatoryInputRule;
            else
                throw new InvalidOperationException("There's more than one MandatoryInputRule in the Binding's ValidationRules.");
        }
    }

    if (mandatoryRule == null)
    {
        mandatoryRule = new MandatoryInputRule();
        binding.ValidationRules.Add(mandatoryRule);
    }

    BindingOperations.ClearBinding(obj, property);
    BindingOperations.SetBinding(obj, TextBox.TextProperty, binding);
}

I’ve purposefully cloned a binding object and set its properties for better understanding and so that all the previous settings could be persisted, except for the origin of all this, the UpdateSourceTrigger property.

In the next article we’ll come out with an even better approach using a Markup Extension. It’s nothing new, but makes life a bit easier for the developer, and more clean and extensible from an architectural point of view.

In case you missed them, here is the previous article:

Wpf Input Validation Part I – Validation Rules

Technorati Tags: , , ,

Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)

Object, var, dynamic and the DLR Showdown

1

There’s a time when new feature or frameworks arise and you get to know them and immediately grasp that new and useful way of doing things, but there are also times when clarity only comes after a bit of blurriness. From what I’ve read, the new Dynamic type in c# 4.0 is currently one of such cases, when compared to var. I read many developers say “What’s the point?” or “Why do I need this?”. Well, I believe it’s a matter of architectural needs, mixed with coding style. To break this discussion into pieces, and because I feel the force is strong with this one ;-) I found myself with the task of enlightening things up a bit.

In fact, this article hopes to settle the dust on this. I’ve seen a number of articles and posts on the web comparing and debating advantages and disadvantages, but I didn’t find them clear or eligible for training purposes. And even after knowing what each one really represent and allow, their usage and necessity is somewhat cloudy. Specially when it comes to dynamic.

So, to get the discussion started, I believe that we first must make sure we understand the basics of each one of these types, and build our structured thinking from there. You all know the System.Object type. Or its alias, object. Everything in the .Net Framework is an object, right? You can even refer to any type as object, by boxing it like this:

//Boxing
object var1 = 23;

// This will produce a compiler error
object sum = 3 + var1;

Since we specified 23 as var1’s value, it will be inferred and internally assumed as System.Int32. However, adding 3 var1 produces an “Operator ‘+’ cannot be applied to operands of type ‘int’ and ‘object’” compiler error.

This is where var comes in handy. If, instead of object we use the var type, the compiler will infer the underlying type and take it into consideration along the method scope. I say method scope because the var type can only be declared inside a method. So, the following would work:

var var2 = 23;

object sum2 = 3 + var2;

You can see the differences when boxing an Int32 value, but the same kind of difference arises when unboxing. Assigning var1 to an int variable produces a compiler error “Cannot implicitly convert type ‘object’ to ‘int’”, suggesting a cast, while assigning var2 compiles successfully:

// Produces compiler error
int var3 = var1;

// Compiles successfully
int var4 = var2;

var is still statically typed though. The only difference is, for instance, that you don’t need to repeat the type upon initialization:

// Type is specified only once
var x = new Collection();

It’s a nice bonus, but not it’s main purpose. The true purpose behind var is so that we can declare a strongly typed variable without needing to know the name of the variable’s type. This is crucial in order to enable C# 3.0’s anonymous types. You wouldn’t be able to declare a variable of an anonymous type if you always had to include the type name as part of the variable declaration. That’s the main reason var has been added to the language.

In some cases, when software architecture enables you to do so, you also have the advantage of changing return types without producing compilation errors.

Consider the following two classes. Event though they are similar in functionality, they are, nevertheless, different types and so, bound to the usual rules:

public class Human
{
    public int Age { get; set; }

    public string Name { get; set; }
}

public class Dog
{
    public int Age { get; set; }

    public string Name { get; set; }

    public string Breed { get; set; }
}

 

Now, imagine the following method from any given business layer, that returns a new instance of type Human:

public Human GetInstance()
{
     return new Human();
}

And a consumption example:

var o = GetInstance();

o.Name = "Alex";
o.Age = 23;

If, in the future, someone changes GetIntance()’s return type to Dog, you won’t need to change the previous code, because the same rules apply to the new type, since var’s type is implicit. Weird architectural approach, but an advantage to consider nevertheless.

And then there’s the dynamic type. dynamic is a static type, but an object of type dynamic bypasses static type checking. It’s like a type closing the door to the compiler when he knocks asking who’s in. And, as such, you don’t get the usual intellisence information. You’ll simply get the following:

 At compile time, an element that is typed as dynamic is assumed to support any operation. He simply doesn’t know what it is, nor where it comes from. You are in control :)

dynamic var1 = 23;

// Sum operation resolves successfully.
object sum1 = 3 + var1;

// This also works
int var2 = var1;

As you see in the previous snippet, it behaves just like var, but without intellisence. “No intellisence? Why bother then??” – you ask. We’ll get to that shortly. For now, consider the following extended Human class:

public class Human
{
    public int Age { get; set; }

    public string Name { get; set; }

    public void Punch(int intensity)
    {
        Console.WriteLine(string.Format("Punched with {0} strength.", intensity));
    }
}

A typical consumption example would be:

Human h = new Human();
h.Punch(100);

But if we used dynamic, we could do this:

dynamic h = new Human();
h.Punch(100, "Right in the face!");

Even though there’s no corresponding method signature in the Human class, the dynamic type made the compiler became passive, and he didn’t analyze the underlying/resolving type. So the snipped compiles just fine, but resulting in a runtime error later on.

The dynamic type has a broader usage than var. It can be used as a property, field, indexer, parameter, return value, local variable, or type constraint; it can be the target of an explicit conversion and it can be the right side assignment of both is or as operators or typeof argument. The following example demonstrates some of these arguments:

public MainWindow()
{
    InitializeComponent();

    // Prints ".net Brainwork rocks!" to the output window
    Console.WriteLine(ExampleMethod(23));
}

public dynamic ExampleMethod(dynamic number)
{
    dynamic dyn;

    int num = number;
    dyn = (dynamic)num;

    string str = ".net Brainwork rocks!";
    dyn = (dynamic)str;

    return dyn;
}

So what the dynamic type really does is telling the compiler to skip operation analysis and validation at design time, and instead, it resolves the types and operations at runtime. It accomplishes this through a new engine called Dynamic Language Runtime. The dynamic language runtime (DLR) is a new .Net Framework 4.0 runtime environment that adds a set of services for dynamic languages to the common language runtime (CLR). The DLR makes it easier to develop dynamic languages to run on the .NET Framework and to add dynamic features to statically typed languages. IronRuby and IronPython are two examples of languages developed by using the DLR.

Dynamic languages can identify the type of an object at run time, whereas in statically typed languages such as C# you must specify object types at design time.

The purpose of the DLR is to enable a system of dynamic languages to run on the .NET Framework and give them .NET interoperability. The DLR introduces dynamic objects to C# and Visual Basic in Visual Studio 2010 to support dynamic behavior in these languages and enable their interoperation with dynamic languages.

So, all in all, dynamic has an entirely new operation going on. It’s not just a matter of making it easier for developers to produce code or improve its quality, but it’s a new system for dynamic type handling, that improves how the language interacts with external data objects or services, whose types are only known at runtime like COM.

References:

Dynamic Language Runtime Overview – MSDN

Technorati Tags: , ,

Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)

MSXML 4.0 SP3 now available

0

Microsoft released MSXML 4.0 Service Pack 3. MSXML SP3 Core Services are a complete replacement of MSXML 4.0, MSXML 4.0 Service Pack 1 (SP1) and MSXML 4.0 Service Pack 2. MSXML 4.0 SP3 provides a number of security and reliability bug fixes:

Max Element Depth

MSXML4.0 SP3 supports using MaxElementDepth to limit the element depth of an XML document to be loaded into a DOM object. A zero (0) value means no limits on the element depth of an XML document. A non-zero value specifies the maximum depth. The default value for MSXML4.0 SP3 is 5000.

This property helps to avoid denial of service attacks in which a document is submitted that has excessive element depth. Failure to limit the element depth leaves you vulnerable to the exploit where a relatively small XML document can cause denial of service. The MaxElementDepth property mitigates this threat.

If you are concerned about denial of service, you should set this property to a value that allows you to load your documents yet limits depth to a reasonable level.

AllowXsltScript Property for XSLT

AllowXsltScript property is used to enable or disable the element functionality in XLST. This property has security implications. The default value is set to true.

If this property is set to false, attempts to use a stylesheet with scripting will result in a “Security settings do not allow the execution of script code within this stylesheet” error.

AllowDocumentFunction and MaxXMLSize properties are propagated when cloning a node

AllowDocumentFunction and MaxXMLSize are security related properties. MSXML4.0 SP3 propagates the two properties when cloneNode() is called.

ProhibitDTD and MaxXmlSize properties are propagated to the included and imported Style Sheets

MSXML4.0 SP3 starts to propagate ProhibitDTD and MaxXmlSize settings from the main stylesheet to the included and imported style sheets. The same settings will be used on the XSL document and internal documents when resolving includes/imports and document() function during transformation.

line/linepos Error Information for Duplicate Attribute May Change

The line/linepos error report for duplicate attribute may change while the error code remains the same.

line/linepos Information Changed for Well-known Entities

The reported line/linepos information for well-known entities like & may change. Previously the Characters items produced as a result of such entity reference always had the same line/linepos, because they were treated as a separate source file. In MSXML4.0 SP3 these will be reported correctly.

Validate the nonNegativeInteger for schema

MSXML4.0 SP3 will check the validity of large value in attributes of type nonNegativeInteger. This will mitigate Denial of Service attacks when malicious XML source has attributes of type nonNegativeInteger containing large values.

Path information is suppressed in XSD error messages

Prior to MSXML4 SP3, an XSD error message contained path information about the files processed. This might lead to a security problem. In MSXML4.0 SP3, path information is suppressed.

You can download it here.

Technorati Tags: ,

Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)

Applying a Watermark to an image with .NET and GDI+

0

In this article I’ll be showing how to watermark a photo using .NET and, more specifically, GDI+ through the System.Drawing namespace. GDI stands for Graphic Device Interface, and basically consists of a class-based API for C/C++. It enables applications to use graphics and formatted text on both the video display and the printer. Applications based on the Microsoft Win32 API do not access graphics hardware directly. Instead, GDI interacts with device drivers on behalf of applications. In the .NET world, GDI is referred to as GDI+, and developing applications using this technology is now much easier.
I’ll implement a small method to apply a watermark image over a photo. Both photo and watermark image path are passed as parameters, and the final method output is the merge between the two. For this, we will be using the following namespaces:

using System.Drawing;
using System.Drawing.Imaging;

System.Drawing namespace is the .NET graphical manipulation framework, and holds everything we need in order to make fully usage of the GDI API. So, that said, lets’s start by describing what our method will be doing. We start by loading our images based on filepath parameters, define an empty Bitmap canvas for each of them, apply some changes to the watermark Graphic and position it on the photo Bitmap using the left and top parameters.

// Get original image and watermark
Image image = Image.FromFile(originalFilePath);
Bitmap bmpImage = new Bitmap(image);
Image watermark = Image.FromFile(watermarkFilePath);

Image is an abstract class that is implemented by the Bitmap and Metafile classes, and provides general image funtionalities, while Bitmap is a graphic object that contains raw pixel data that we can manipulate.

We will get watermark dimensions to int variables and create a Bitmap object for our watermark, as a copy of the target image.

Bitmap bmpWatermark = image;
bmpWatermark.SetResolution(image.HorizontalResolution, image.VerticalResolution);

And now we must create a graphics object based on our watermark bitmap. We need this to apply some graphical changes to the watermark image, namely, remove the green color areas for transparency. Graphics is an object that allows us to perform drawing operations on a specific device. You’ve probably seen this class as an event argument property of the paint event of any control.

Graphics watermarkGraphic = Graphics.FromImage(bmpWatermark);

Before we can make changes to the watermark image with its graphics object, we must define the color changes themselves. We will do this by creating an ImageAttributes object, and set it to replace the green color with zero color (alpha set to zero). An ImageAttributes object maintains color and grayscale settings for five adjustment categories: default, bitmap, brush, pen, and text.

// Define transparency settings over the watermark image
ImageAttributes imageAttributes = new ImageAttributes();

// Set an array with green color and zero color (alpha = 0)
// The watermark image will be drawn without pixels of the specified color (green)
ColorMap colorMap = new ColorMap();
colorMap.OldColor = Color.FromArgb(255, 0, 255, 0);
colorMap.NewColor = Color.FromArgb(0, 0, 0, 0);
ColorMap[] remapTable = { colorMap };

// Apply color changes. Create array to image Attributes
imageAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap);

float[][] colorMatrixInput = {
    new float[] {1.0f,  0.0f,  0.0f,  0.0f, 0.0f},
    new float[] {0.0f,  1.0f,  0.0f,  0.0f, 0.0f},
    new float[] {0.0f,  0.0f,  1.0f,  0.0f, 0.0f},
    new float[] {0.0f,  0.0f,  0.0f,  0.3f, 0.0f},
    new float[] {0.0f,  0.0f,  0.0f,  0.0f, 1.0f}
        };

ColorMatrix watermarkColorMatrix = new ColorMatrix(colorMatrixInput);

imageAttributes.SetColorMatrix(watermarkColorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);

The ColorMatrix object sets what types of colors (and images) will be affected by the changes. It can be set to change greyscale values, color values or both (default). ColorAdjustType sets the kind of object that will be the subject of change.

Finally we are ready to apply the watermark bitmap over the original image, using our defined image attributes to apply color changes.

// Draw watermark image over its bitmap, using its Graphic object
watermarkGraphic.DrawImage(watermark, new Rectangle(X, Y, watermarkWidth, watermarkHeight), 0, 0, watermarkWidth, watermarkHeight, GraphicsUnit.Pixel, imageAttributes);

image = bmpWatermark;
watermarkGraphic.Dispose();

By the way, X and Y are the upper-left coordinates of the watermark within the image. These are used in a Rectangle object, to specify position and size of the drawn image.

Hope this beginner tutorial can help you develop great things. I’m sure having a lot of fun working with it.

Technorati Tags: ,

Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)

Tip: C# 3.0 Extension Methods

1

Another great feature in c# 3.0 is Extension Methods. Extension Methods are created in a way that allow developers to inject them in other classes as being part of them. This article will provide an example of this.

As you know, the string type has many methods and the length property. But suppose that, for some reason, you wish string objects to have a new method available, say, to add a timestamp on the start of the string. This is where Extension Methods come in handy. An Extension Method that would allow us to do this, is the following:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MyExtenders
{
	public static class Extenders
	{
		public static string ApplyTimestamp(this string text)
		{
			return DateTime.Now.ToLongTimeString() + " -> " + text;
		}
	}
}

I’ve defined my extender method in a namespace chosen by me, called it MyExtenders, and added a class called Extenders to contain it. I’ve named the extender method ApplyTimestamp(), and what it does is to prefix a string with date and time. Remember this method will be available to a string type object, and so, it will target the string object’s value. That’s why ApplyTimestamp has the this keyword, and that’s what makes this feature pump.

Now, for us to be able to use this method in our string objects along our application, we just need to reference the MyExtenders namespace with the using statement, and it will be available in all our string objects:

This is indeed a nice feature.

Technorati Tags:

Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)

Tip: C# 3.0 Partial Methods

0

One other interesting new feature in C# 3.0 are partial methods. Have you ever crossed a partial class with something like:

partial void MyMethod()

Lets see how this can be done and, by using reflector, check out the compiled result.

In our partial class, let’s supose we have this:

namespace Example
{
	public partial class TestClass
	{
		public TestClass()
		{
			// Do something
		}

		partial void MyPartialMethod();
	}
}

Notice the partial void method. This indicates the compiler that the MyPartialMethod() method belongs to this class, but it’s defined somewhere else. So in our other TestClass partial class, we can have something like this:

namespace Example
{
	public partial class TestClass
	{
		partial void MyPartialMethod()
		{
			Console.WriteLine("Mommy this is a partial method!");
		}
	}
}

Interesting huh? This is specially usefull when you have generated code (for instance Linq class Designer) that implements this feature. Finally, when looking through .NET Reflector on the compiled class, what we’ll see is something like this:

namespace Example
{
	public class TestClass
	{
		public TestClass()
		{
			// Do something
		}

		private void MyPartialMethod()
		{
			Console.WriteLine("Mommy this is a partial method!");
		}
	}
}

C# 3.0 is a great software development technological evolution, and I’ll make sure every new bit of tips and tricks ends up on my blog.

Technorati Tags:

Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)

Refactoring tips: Extract Interface

0

In the previous article I’ve given you a little taste on Field Encapsulation on Visual Studio. In this next artiicle I’ll demonstrate how to automatically generate a fully fledged interface from an already defined class with properties and methods in it.

Lets say you have the following TestClass class:

using System;
using System.Collections.Generic;
using System.Text;

namespace Example
{
	class TestClass
	{
		public TestClass()
		{}

		public string ImplementMe()
		{}

		public void ImplementMeToo()
		{}
	}
}

And now let’s say you want to make an interface out of these methods for other classes to implement them. You can do this by going to the Refactor menu group once again and choose “Extract Interface…”.

 This will popup the Extract Interface screen, in which you can select the methods you want to have declared on your interface. Select the methods you want, and click “Ok”:

Then, Visual Studio will automatically create an Interface class file, with the given name and interface methods. Here is the ITestClass.cs code output:

using System;

namespace Example
{
	interface ITestClass
	{
		string ImplementMe();
		void ImplementMeToo();
	}
}

A small example for you to see the big picture…

Technorati Tags:

Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)

Refactoring tips: Field Encapsulation

0

The refactor feature in Visual Studio is great for many tasks, and I’ll show a few of them in this article. This might be old stuff for some, but believe me when I say there are still a lot of folks out there waiting to be enlightened (just need to read some blogs and forums). Encapsulate Field is one of such features of the Visual Studio Refactoring module: If for some reason you can’t or don’t want to use an auto-implemented property, just declare a private field and let Visual Studio generate the Property for you. 

Let’s say you have a private property declaration on your class. Click its name with the right mouse button, go to Refactoring section on the contextual menu and choose “Encapsulate FIeld”:

  

Then, you’ll be shown a preview screen of the output, like this:

 

And, by clicking “Apply”, the final result will be its public counterpart:

In the next article, I’ll demonstrate how to automatically generate a fully fledged interface from an already defined class with properties and methods in it.

Technorati Tags:

Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)
Page 1 of 212Next »

Note: Silverlight, C#, in fact any .NET web development projects is best used with windows hosting than Linux based hosting.