Pages

Wednesday, January 28, 2009

Constructors in C#

I found this very interesting article from skeet .Enjoy while learning ;)

In the C# newsgroup, there was recently (at the time of writing) a discussion about various aspects of constructors. This page provides most of the important bits about how I believe constructors work in C#, including references to the language specification to back them up. If you disagree with anything in this page, I ask you to follow the language specification link to the appropriate section. If you then believe I'm incorrectly interpreting the spec, please mail me with details. The ECMA spec and the MS spec are identical as far as I've seen, apart from how they number their sections. I'll give links to both so you can use whichever you feel more comfortable with. In fact,

A little terminology...

The C# language spec refers to two types of constructors: instance constructors and static constructors. This page only deals with instance constructors, and I'll just call them constructors for short. That's what most people understand by the term "constructor" anyway. Static constructors are the equivalent of static initializers in Java - they give the code which is executed when a class is first used.

What is a constructor?

(ECMA) (MS).
To quote the spec, "An instance constructor is a member that implements the actions required to initialize an instance of a class." That's actually a pretty good description on its own. A constructor is invoked when you use the "new" operator, or use the various methods of reflection to create an instance of a class.

What do constructors look like?

A constructor looks very much like a method, but with no return type and a name which is the same as the name of the class. (The modifiers you can use with a constructor are slightly different, however - see the spec for more information about that.) Here's a short class to use as an example:

public class MySimpleClass
{
public MySimpleClass(int x)
{
Console.WriteLine(x);
}
}

This class has a single constructor, which takes an int as a parameter, and prints that int's value to the console.

Constructor Initializers


Now, in fact, there's something else going on here, which is hidden by the compiler. The above is actually equivalent to:

public class MySimpleClass
{
public MySimpleClass(int x)
: base()
{
Console.WriteLine(x);
}
}

(ECMA) (MS).
Note the base() bit. That's saying which other constructor should be invoked before any of the rest of the code in the constructor runs. Every constructor of every class other than plain object does this, either explicitly or implicitly. There are two forms of constructor initializer - one which calls a base class constructor (as above) and one which calls another constructor from this class, using the this (...) syntax. There must always be a "chain" of constructors which runs constructors all the way up the class hierarchy. Every class in the hierarchy will have a constructor invoked, although some of those constructors may not explicitly appear in the code. (See the section on default constructors, later.) The parameters (if any) within the brackets of base(...) or this(...) are passed as the parameters to the invoked constructors. They can be the parameters given in the constructor declaration, but don't have to be. Here's an example:

public class MyBaseClass
{
public MyBaseClass(int x)
: base() // Invoke the parameterless constructor in object
{
Console.WriteLine("In the base class constructor taking an int, which is " + x);
}
}

public class MyDerivedClass : MyBaseClass
{
public MyDerivedClass()
: this(5) // Invoke the MyDerivedClass constructor taking an int
{
Console.WriteLine("In the derived class parameterless constructor.");
}

public MyDerivedClass(int y)
: base(y + 1) // Invoke the MyBaseClass constructor taking an int
{
Console.WriteLine("In the derived class constructor taking an int parameter.");
}

public MyDerivedClass(string x)
: base(10) // Invoke the MyBaseClass constructor taking an int
{
Console.WriteLine("In the derived class constructor taking a string parameter.");
}
}

With the above code, a bit of code saying new MyDerivedClass(); would invoke the MyDerivedClass parameterless constructor, which would in turn invoke the MyDerivedClass constructor which takes an int parameter (with 5 as that parameter value), which would in turn invoke the MyBaseClass constructor which takes an int parameter (with 6 as that parameter value). Note that the specified constructor is run before the constructor body, so the result of new MyDerivedClass(); would be the following output on the console:

In the base class constructor taking an int, which is 6
In the derived class constructor taking an int parameter.
In the derived class parameterless constructor.

Not all constructors in the hierarchy need to be invoked (as demonstrated above - the constructor taking a string parameter is not invoked at all when you do new MyDerivedClass();) but as I said earlier, there must be at least one constructor invoked in each class in the hierarchy.

Default constructor initializers


(ECMA) (MS), second paragraph.
Any constructor which doesn't have a constructor initializer has one provided for it by the compiler. The initializer is of the form base() - in other words, a call to the base class's parameterless constructor. You'll get a compile-time error if you don't provide a constructor initializer and the base class doesn't have an accessible parameterless constructor. (Note, however, that it may have one without you putting one in yourself - see the next section.)

Default constructors


(ECMA) (MS)
If you don't specify any constructors at all, a default constructor is provided by the compiler. This default constructor is a parameterless constructor with no body, which calls the parameterless constructor of the base class. In other words:

public class MySimpleClass
{
int someMemberVariable;
}

.. is exactly equivalent to:

public class MySimpleClass
{
int someMemberVariable;

public MySimpleClass() : base()
{
}
}

Following from the previous section, this means that if the base class has no accessible parameterless constructor (including a default one), you get a compile-time error if the derived class doesn't have any constructors - because the default constructor will implicitly try to call a parameterless constructor from the base type.

If the class is abstract, the default constructor provided has protected accessibility; otherwise it has public accessibility.

Instance variable initializers


(ECMA) (MS)
When a member variable declaration also has an assignment, that's called a variable initializer. All the variable initializers for a class are implicitly run directly before the invocation of whichever base class constructor is invoked. (Note that this is a change from a previous version of the page, where I believed that they were invoked after the base constructor, as they are in Java.) Here's a simple example of instance variable initializers:

public class MySimpleClass
{
int someMemberVariable = 10;

public MySimpleClass()
{
Console.WriteLine("someMemberVariable={0}", someMemberVariable);
}
}

The output of the above is 10 when a new instance is created, whereas without the instance variable initializer, it would be 0 (the default value for instance variables of type int). Demonstrating the difference between Java and C# in terms of when the instance variable initializers are run requires calling an overridden method from the base class constructor. This is a really bad idea - wherever possible, only call non-virtual methods from constructors, and if you absolutely must call a virtual method, document very carefully that it is called from the constructor, so that people wishing to override it are aware that their object may not be in a consistent state when it is called (as their own constructor won't have run yet). Here's an example:

public class MyBaseClass
{
public MyBaseClass ()
{
Console.WriteLine (this.ToString());
}
}

public class MyDerivedClass : MyBaseClass
{
string name="hello";

public MyDerivedClass : base()
{
Console.WriteLine (this.ToString());
}

public override string ToString()
{
return name;
}
}

When a new instance of MyDerivedClass is created in C#, the output is:

hello
hello

The first line is hello because the instance variable initializer for the name variable has run directly before the base class constructor. The equivalent code in Java syntax would output:

null
hello

Here the first line is null because the instance variable initializer for the name variable only runs directly after the base class constructor has returned (but before ToString is called for the second time).

Constructors are not inherited


(ECMA) (MS), second paragraph from the bottom.
Constructors are not inherited. In other words, just because a base class has a constructor taking a certain list of parameters doesn't mean that a derived class has a constructor taking that list of parameters. (It can, by providing one itself, but it doesn't inherit it from the base class.) To demonstrate this, here's an example which doesn't compile:

public class MyBaseClass
{
public MyBaseClass(int x)
{
}
}

public class MyDerivedClass : MyBaseClass
{
// This constructor itself is okay - it invokes an
// appropriate base class constructor
public MyDerivedClass()
: base(5)
{
}

public static void Main()
{
new MyDerivedClass(10);
}
}

Here, we try to invoke a constructor for MyDerivedClass which takes an int parameter. There isn't one, however, as constructors aren't inherited. The MyBaseClass constructor which takes an int parameter can be invoked by a constructor in MyDerivedClass (as is shown by the parameterless MyDerivedClass constructor) but isn't actually inherited. Removing the "10" from the above code would make it compile and run with no problems - the parameterless MyDerivedClass constructor would be invoked, and that would in turn invoke the MyBaseClass constructor taking an int parameter, with 5 as that parameter value.

Some people have said that they would rather constructors were inherited, making the language act as if all derived classes had constructors with all the parameter lists from the constructors from the base class, and just invoking them with the parameters provided. I believe this would be a very bad idea. Take, for instance, the FileInfo class. You must logically provide a filename when constructing a FileInfo instance, as otherwise it won't know what it's meant to be providing information on. However, as object has a parameterless constructor, constructors being inherited would then mean that FileInfo had a parameterless constructor. Some have suggested that this could be fixed by allowing you to "override" the parameters you didn't want invoked as private, but this goes against the idea that you should never be able to override anything to give it more restrictive access, and also means that class developers would have to change their code every time a new constructor was added to a base class.

Original article can be found here

Sunday, January 25, 2009

Microsoft Web Platform Download link

Start now by downloading the Microsoft Web Platform

Design, develop, and deliver Web solutions for your business. All the tools, technologies and server solutions necessary to create satisfying Web experiences.

 

  • The Microsoft Web Platform Installer v 1.0

It's comprehensive: A single installer to obtain and update the software necessary to build and run a complete Web Solution on the Microsoft Web Platform. For free

Download it now

 

  • The Microsoft Web Application Installer (BETA)

It's compatible: This installer gives you the ability to build and run PHP applications in a high-performance and reliable way alongside ASP.NET with IIS 7.0 Fast CGI. Choose from these applications:

  1. DotNetNuke
  2. Drupal
  3. Gallery
  4. Graffiti CMS
  5. osCommerce
  6. phpBB
  7. WordPress

Download it now

 

Source: Microsoft

Friday, January 23, 2009

Tip/Trick: How to Register User Controls and Custom Controls in Web.config

Have fun reading this tip and trick from Scottgu.

I've been including this technique in my ASP.NET Tips/Tricks talks the last year, but given how many people are always surprised by its existence I thought it was worth a dedicated tip/trick post to raise the visibility of it (click here to read other posts in my ASP.NET Tips/Tricks series).

Problem:

In previous versions of ASP.NET developers imported and used both custom server controls and user controls on a page by adding <%@Register%> directives to the top of pages like so:

<%@ Register TagPrefix="scott" TagName="header" Src="Controls/Header.ascx" %>
<%@ Register TagPrefix="scott" TagName="footer" Src="Controls/Footer.ascx" %>
<%@ Register TagPrefix="ControlVendor" Assembly="ControlVendor" %>

<html>
<
body>
    <
form id="form1" runat="server">
        <
scott:header id="MyHeader" runat="server" />
    </
form>
</
body>
</
html>

Note that the first two register directives above are for user-controls (implemented in .ascx files), while the last is for a custom control compiled into an assembly .dll file.  Once registered developers could then declare these controls anywhere on the page using the tagprefix and tagnames configured.

This works fine, but can be a pain to manage when you want to have controls used across lots of pages within your site (especially if you ever move your .ascx files and need to update all of the registration declarations.

Solution:

ASP.NET 2.0 makes control declarations much cleaner and easier to manage. Instead of duplicating them on all your pages, just declare them once within the new pages->controls section with the web.config file of your application:

<?xml version="1.0"?>

<
configuration>

<
system.web>

<
pages>
<
controls>
<
add tagprefix="scottgu" src="~/Controls/Header.ascx" tagname="header"/>
<
add tagprefix="scottgu" src="~/Controls/Footer.ascx" tagname="footer"/>
<
add tagprefix="ControlVendor" assembly="ControlVendorAssembly"/>
</
controls>
</
pages>

</
system.web>

</
configuration>

You can declare both user controls and compiled custom controls this way.  Both are fully supported by Visual Studio when you use this technique -- and both VS 2005 Web Site Projects and VS 2005 Web Application Projects support them (and show the controls in WYSIWYG mode in the designer as well as for field declarations in code-behind files).

One thing to note above is the use of the "~" syntax with the user-controls.  For those of you not familiar with this notation, the "~" keyword in ASP.NET means "resolve from the application root path", and provides a good way to avoid adding "..\" syntax all over your code.  You will always want/need to use it when declaring user controls within web.config files since pages might be using the controls in different sub-directories - and so you always need to resolve paths from the application root to find the controls consistently.

Once you register the controls within the web.config file, you can then just use the controls on any page, master-page or user control on your site like so (no registration directives required):

<html>
<
body>
<
form id="form1" runat="server">
<
scott:header id="MyHeader" runat="server" />
</
form>
</
body>
</
html>

Hope this helps,

Scott

P.S. Special thanks to Phil Haack who blogged about this technique as well earlier this month (for those of you who don't know Phil, he helps build the very popular SubText blog engine and has a great blog).

Thursday, January 22, 2009

Proven Software Uncovers Profitable

I find this tool very useful in my previous project. If you are the SEOptimizer in your company, I think you'll gonna like Market Samurai. Here are some of the features of this tool.

Receive Accurate, Up-To-Date Data on Keyword Traffic, Target Profitable Markets with Pin-Point Accuracy, Uncover Previously-Undiscovered Niche Marketing Goldmines, Perform In-Depth Analysis on Markets and Niches, Discover the Specific Keywords Used by Your Customers, Avoid the Time-Consuming "Grunt-Work" of Market Research, Avoid Tyre-Kickers by Laser-Targeting "Buy" Keywords And Much, Much More.

You can donwload their trial version here.

Tuesday, January 20, 2009

ASP.NET Open Source Projects

Here are some links to ASP.NET Open Source Projects. I found a list that I thought would be helpful in enabling a developer to find everything that he/she needs bundled up in one page to quicken his/her projects. Hope these will be helpful to everyone.

Blogs

Content Management Systems

Controls/Toolkits/Frameworks

Forums

Starter Kits

Wikis

Miscellaneous

Additional Projects

 

Original post can be found here: http://wiki.asp.net/

Friday, January 9, 2009

How to make a Flash movie with a transparent background

Often times we encountered this problem. Like in my situation before. I created a menu using jQuery plugin Superfish and added some flash animation at the bottom of the top menu. The problem is: whenever I navigate the menu, the flash animation overlapping it. Wondering how did I solve this issue? Here is how:

The background of a Flash movie can be set to transparent. This allows the background color or image of the HTML page that contains the Flash movie to show through and allows the layering of Flash content with DHTML content.

Preparing the HTML page to make the Flash movie transparent

Three methods of creating an HTML page with the correct code are outlined below.

Publishing from Flash

The HTML for a Flash movie can be created using the Publish Settings feature in Flash. The Publish Settings dialog box provides an option to affect the WMODE setting. The options selected in the Publish Settings will be added to the HTML source code automatically:

  1. Choose File > Publish Settings. Select the HTML tab.
  2. Choose "Transparent" in the WMODE setting to make the Flash movie's background disappear in browsers which support this feature.
  3. Publish the document.

 

Using Dreamweaver

Follow the below steps, and Dreamweaver will insert the correct HTML code automatically.

  1. In Dreamweaver, insert the Flash movie into an HTML page.
  2. Select the Flash movie in the Design View.
  3. In the Properties panel, choose Parameters.
  4. For the Parameter, enter "wmode" (without quotes). For the Value, enter "transparent".
  5. Save the document. The HTML page is complete.

 

Editing HTML code manually

To edit an existing HTML page, add the WMODE parameters to the HTML code.

  1. Add the following parameter to the OBJECT tag:
    <param name="wmode" value="transparent">



  2. Add the following parameter to the EMBED tag:
    wmode="transparent"




Read the original post on http://kb.adobe.com/

Thursday, January 8, 2009

MVC - Views without Code-Behind Files by ScottGu

Based on feedback from a lot of people, we've decided to make a change so that MVC view files by default do not have code-behind files. This change helps to reinforce the purpose of views in a MVC world (which are intended to be purely about rendering and to not contain any non-rendering related code), and for most people eliminates unused files in the project:

With the ASP.NET MVC Beta, developers could eliminate the code-behind file by using the CLR syntax for generic types in a view's inherits attribute, but that CLR syntax is (to put it mildly) pretty undiscoverable and hard to use.  The ASP.NET MVC team was able to combine a few extensibility features already in ASP.NET to now enable the standard VB/C# language syntax within the inherits attribute with the ASP.NET RC build:

One other nice benefit of not using a code-behind file is that you'll now get immediate intellisense when you first add them to the project.  With the beta you had to do a build/compile immediately after creating a view in order to get code intellisense within it.  The RC makes the workflow of adding and immediately editing a view compile-free and much more seamless.

Top-Level Model Property on Views

With previous builds of ASP.NET MVC, you accessed the strongly typed model object passed to the view using the ViewData.Model property:

The above syntax still works, although now there is also a top-level "Model" property on ViewPage that you can use:

This property does the same thing as the previous code sample - its main benefit is that it allows you to write the code a little more concisely.

HTML/AJAX Helpers Now Enable Expression Syntax

One of the requests a few people have asked for is the ability to use strongly-typed expression syntax (instead of using strings) when referring to the Model when using a View's HTML and AJAX helper objects.

With the beta build of ASP.NET MVC this wasn't possible, since the HtmlHelper and AjaxHelper helper classes didn't expose the model type in their signature, and so people had to build helper methods directly off of the ViewPage<TModel> base class in order to achieve this.  The ASP.NET MVC RC build introduces new HtmlHelper<TModel> and AjaxHelper<TModel> types that are exposed on the ViewPage<TModel> base class.  These types now allow anyone to build strongly-typed HTML and AJAX helper extensions that use expression syntax to refer to the View's model.

For example, I could build a (very simple) strongly-typed "TextBox" helper method using the code below:

And then use it within any of my views to bind against a Product model object like so:

Visual Studio will provide full intellisense for the strongly-typed expression syntax when working against the View's model in the source editor in this way:

Note: the HTML helper extensions in the core ASP.NET MVC V1 assembly will still use the existing (non-expression based) syntax.  We are then planning to add expression-based versions to the MVCFutures assembly. You can of course also add your own helper methods (using either strings or strongly-typed expressions).  All of the built-in helper methods can also optionally be removed (because they are extension methods) if you want to replace or override them with your own.

Scaffolding Support

The ASP.NET MVC RC build includes automatic "UI scaffolding" support when creating views using the new ASP.NET MVC "Add View" command inside Visual Studio.  The scaffolding support enables the automatic generation of views against any .NET type or object - meaning it can work against POCO classes, LINQ to SQL, LINQ to Entities, NHibernate, SubSonic, LLBLGen Pro, or any other object model. The scaffolding engine uses reflection to retrieve the public shape of a View's model type, and then passes it to a scaffolding template to populate appropriate markup based on it within the view being created.

For example, assume we have a ProductsController class and want to create an "Edit" action on it to display an edit view of a particular Product.  Using the RC build we can right-click within our "Edit" action method and choose the "Add View" context menu command like so:

Within the "Add View" dialog we can then indicate that we are passing a "Product" type to our View:

We can indicate that we want an "Empty" view template created (like above), or indicate that we want VS to automatically scaffold a form "Edit" view for the Product object we are supplying:

If we choose the "Edit" template VS will automatically generate a file for us that has the appropriate HTML and validation helpers to create an editable form view:

We can then run the application and immediately get edit UI:

We can then go in and change the generated edit.aspx file however we want to tweak/customize it. 

One of the really nice things about the scaffolding system we are shipping is that it is implemented using Visual Studio's built-in T4 code generation system (Scott Hanselman has a nice post about this here).  The "List", "Edit", "Create" and "Details" templates we ship with ASP.NET MVC can all be completely customized or replaced with T4 templates of your own (or downloaded from the ASP.NET MVC Design Gallery). So if you have your own particular way of creating HTML, or want to use custom HTML helpers (for example: strongly-typed expression based ones) you can update the default templates and the scaffolding system will use them going forward. 

We are planning to enable the templates to be overriden both on a machine-wide level, as well as on a per-project level (so that you can check-in application-specific scaffolding templates under source control and share them across a team).

MSBuild Task for Compiling Views

By default when you do a build on an ASP.NET MVC project it compiles all code within the project, except for the code within view files.  With the ASP.NET MVC Beta you had to roll your own MSBuild task if you wanted to compile the views.  The ASP.NET MVC RC build now includes a built-in MSBuild task that you can use to include views as part of the project compilation process.  This will verify the syntax and code included inline within all views and master pages for the application, and give you build errors if it encounters any problems.

For performance reasons we don't recommend running this for quick compiles during development, but it is convenient to add to particular build configuration profiles (for example: staging and deployment) and/or for use with Build or CI (continuous integration) servers.

Other ASP.NET MVC Release Candidate features coming

Above is a short list of some of the view-specific functionality coming with the release candidate build. 

There are many other features and requests coming with the RC as well including: IDataErrorInfo support to enable models to surface validation error messages, as well as richer error validation extensibility to enable you to use your own approach to surface model validation errors to ModelBinders (the IDataErrorInfo support is built on top of this); new FileResult and JavaScriptResult ActionResult types (allowing you to more easily download files as well as executable JavaScript to browsers); built-in jQuery -vsdoc intellisense support; refactored AccontController support to enable easier unit testing and extensibility with form login scenarios; a variety of project template improvements, more extensibility everywhere; lots of bug fixes; and a few other cool features I'll blog about later once the RC is out.

We'll be releasing the ASP.NET MVC Release Candidate in January.  Our plan is to have that build be ASP.NET MVC V1 API and feature-complete and have zero known bugs.  We'll give people a short period to upgrade to it, give it a good tire-kicking, and report any last minute issues they find.  We'll then ship the official V1 release shortly after that (so not far off now).

Hope this helps,

Scott

Read the original post on http://weblogs.asp.net/scottgu/

Tuesday, January 6, 2009

CodeSmith just released it's 5.0.5 version

Hot on the heels of their previous update, their steadfast developers have completed CodeSmith 5.0.5 and it is now available for download.

With this update, the CodeSmith MySQLSchemaProvider now supports more data types, and extended properties. It also uses both generics and .Net2.0 best practices. They have also added Designer Support for ViewColumnSchema and ViewColumnSchemaCollection.
They have made various other minor changes and resolved the following bugs:

· Fixed a bug where CodeSmith Studio becomes unresponsive when Schema Explorer tries connecting to an off line database when other applications are active.

· Fixed a bug where a NullReferenceException would be thrown in the Schema Explorer when calling InvokeRequired.

· Fixed a rare bug where an InvalidOperationException might be thrown when starting up CodeSmith.

· Fixed a bug where a BadCrcException and ZipException would occur on start up.

If you have technical questions, contact them at support@codesmithtools.com

If you aren’t already saving time and development costs with CodeSmith, try it today or contact them at CodeSmith Tools with any questions.