Our Recommendation

Showing posts with label Weblogs. Show all posts
Showing posts with label Weblogs. Show all posts

Sunday, December 19, 2010

ASP.NET 4 0-ScriptManager Enhancement part-enable CAN property. (Weblogs @ ASP.NET)

ASP.NET 4.0 was a major step forward in programming. Microsoft has done incredible work performance. One of them is property can enable in asp.net 4.0 script manager. Say that it explore in detail. As you all know, Microsoft is providing a network delivery content for all the Ajax script that is used by Microsoft Ajax and any version of jQuery and JQuery UI. This property can enable script manager will retrieve all the script that can automatically. Developer does not have to worry about. As you know generation browsers are like IE8 and Firefox creates a new thread for each JS or CSS include in the Web page where they come from the CDN (content delivery network). Therefore, it will be largely step towards it. Let us take an example to explore things. I take a simple example that will demonstrate the use of this. I pray a TextBox and a button. The button click event will update the text box text property. I used to use Microsoft Ajax update panel. For this first I needed a script manager so I took the script manager and I set its property EnalbleCdn = true. So without publish any return after return only the portion that are required. I putted the text box in the control panel to update content model and I created the trigger back asynchronous post for the button click event. It will therefore updated the text in the text box without creating a post back. Let's look at how I created. Here is simple HTML to do so.

Now, I'm going to create a click event that will change the text in the text box '. Here is a code to do this.

protected void btnHelloWorld_Click (object sender, EventArgs e) {txtHelloWorld.Text = "Hello World";}

It is running let's with Ctrl + F5, and it will be displayed in the browser firefox as follows.

ScriptManager4.0, ASP.NET 4.0 Enhacement

Now see us his point of view source to see how things will look like. Here is a screenshot display source.

ViewSource

As you can see its extracting all JS Microsoft Ajax Content delivery network. Isn't that much. You just activate property CAN = true and it will still work. It is the power of asp.net 4.0. Hope you liked it. Stay tuned over 2 side.

Saturday, December 18, 2010

ASP.NET MVC 3: code implicit and explicit nuggets with knife (Weblogs @ ASP.NET)

This is another in a series of posts I’m doing that cover some of the new ASP.NET MVC 3 features:


In today’s post I’m going to discuss how Razor enables you to both implicitly and explicitly define code nuggets within your view templates, and walkthrough some code examples of each of them. 


ASP.NET MVC 3 ships with a new view-engine option called “Razor” (in addition to the existing .aspx view engine).  You can learn more about Razor, why we are introducing it, and the syntax it supports from my Introducing Razor blog post.


Razor minimizes the number of characters and keystrokes required when writing a view template, and enables a fast, fluid coding workflow. Unlike most template syntaxes, you do not need to interrupt your coding to explicitly denote the start and end of server blocks within your HTML. The Razor parser is smart enough to infer this from your code. This enables a compact and expressive syntax which is clean, fast and fun to type.


For example, the Razor snippet below can be used to iterate a collection of products and output a

    list of product names that link to their corresponding product pages:


    image


    When run, the above code generates output like below:


    image


    Notice above how we were able to embed two code nuggets within the content of the foreach loop.  One of them outputs the name of the Product, and the other embeds the ProductID within a hyperlink.  Notice that we didn’t have to explicitly wrap these code-nuggets - Razor was instead smart enough to implicitly identify where the code began and ended in both of these situations. 


    Razor does not define its own language.  Instead, the code you write within Razor code nuggets is standard C# or VB.  This allows you to re-use your existing language skills, and avoid having to learn a customized language grammar.


    The Razor parser has smarts built into it so that whenever possible you do not need to explicitly mark the end of C#/VB code nuggets you write.  This makes coding more fluid and productive, and enables a nice, clean, concise template syntax.  Below are a few scenarios that Razor supports where you can avoid having to explicitly mark the beginning/end of a code nugget, and instead have Razor implicitly identify the code nugget scope for you:


    Property Access


    Razor allows you to output a variable value, or a sub-property on a variable that is referenced via “dot” notation:


    image


    You can also use “dot” notation to access sub-properties multiple levels deep:


    image


    Array/Collection Indexing:


    Razor allows you to index into collections or arrays:


    image


    Calling Methods:


    Razor also allows you to invoke methods:


    image


    Notice how for all of the scenarios above how we did not have to explicitly end the code nugget.  Razor was able to implicitly identify the end of the code block for us.


    The below algorithm captures the core parsing logic we use to support “@” expressions within Razor, and to enable the implicit code nugget scenarios above:

    Parse an identifier - As soon as we see a character that isn't valid in a C# or VB identifier, we stop and move to step 2 Check for brackets - If we see "(" or "[", go to step 2.1., otherwise, go to step 3  Parse until the matching ")" or "]" (we track nested "()" and "[]" pairs and ignore "()[]" we see in strings or comments) Go back to step 2 Check for a "." - If we see one, go to step 3.1, otherwise, DO NOT ACCEPT THE "." as code, and go to step 4 If the character AFTER the "." is a valid identifier, accept the "." and go back to step 1, otherwise, go to step 4 Done!

    Differentiating between code and content


    Step 3.1 is a particularly interesting part of the above algorithm, and enables Razor to differentiate between scenarios where an identifier is being used as part of the code statement, and when it should instead be treated as static content:


    image


    Notice how in the snippet above we have ? and ! characters at the end of our code nuggets.  These are both legal C# identifiers – but Razor is able to implicitly identify that they should be treated as static string content as opposed to being part of the code expression because there is whitespace after them.  This is pretty cool and saves us keystrokes.


    Razor is smart enough to implicitly identify a lot of code nugget scenarios.  But there are still times when you want/need to be more explicit in how you scope the code nugget expression.  The @(expression) syntax allows you to do this:


    image


    You can write any C#/VB code statement you want within the @() syntax.  Razor will treat the wrapping () characters as the explicit scope of the code nugget statement.  Below are a few scenarios where we could use the explicit code nugget feature:


    Perform Arithmetic Calculation/Modification:


    You can perform arithmetic calculations within an explicit code nugget:


    image


    Appending Text to a Code Expression Result:


    You can use the explicit expression syntax to append static text at the end of a code nugget without having to worry about it being incorrectly parsed as code:


    image


    Above we have embedded a code nugget within an element’s src attribute.  It allows us to link to images with URLs like “/Images/Beverages.jpg”.  Without the explicit parenthesis, Razor would have looked for a “.jpg” property on the CategoryName (and raised an error).  By being explicit we can clearly denote where the code ends and the text begins.


    Using Generics and Lambdas


    Explicit expressions also allow us to use generic types and generic methods within code expressions – and enable us to avoid the <> characters in generics from being ambiguous with tag elements.


    We have used code nuggets within HTML attributes in several of the examples above.  One nice feature supported by the Razor code editor within Visual Studio is the ability to still get VB/C# intellisense when doing this.


    Below is an example of C# code intellisense when using an implicit code nugget within an href=”” attribute:


    image


    Below is an example of C# code intellisense when using an explicit code nugget embedded in the middle of a src=”” attribute:


    image


    Notice how we are getting full code intellisense for both scenarios – despite the fact that the code expression is embedded within an HTML attribute (something the existing .aspx code editor doesn’t support).  This makes writing code even easier, and ensures that you can take advantage of intellisense everywhere.


    Razor enables a clean and concise templating syntax that enables a very fluid coding workflow.  Razor’s ability to implicitly scope code nuggets reduces the amount of typing you need to perform, and leaves you with really clean code.


    When necessary, you can also explicitly scope code expressions using a @(expression) syntax to provide greater clarity around your intent, as well as to disambiguate code statements from static markup.


    Hope this helps,


    Scott


    P.S. In addition to blogging, I am also now using Twitter for quick updates and to share links. Follow me at: twitter.com/scottgu

Thursday, December 16, 2010

model jQuery with ASP.NET MVC (Weblogs @ ASP.NET)

In my three previous blogs, I showed how to use templates in your ASPX Web site.

Introduction to jQuery templates - tmpl() template(), tmplItem (jQuery) model - TemplatesjQuery {supported the tags}

Now, I am going to show a concrete example that you can use in your everyday work developing applications with ASP.NET MVC and jQuery.

In this example I'll use pubs database so I retrieves the values from the authors table. To access the data, I use the Entity Framework.

Say pass along every step of the scenario:

1. Create the new ASP.NET MVC Web application

2. Add the new view to the home folder but step select a master page and add the controller for your view

3 BODY code in the HTML code



Authors of pubs




As you can see in the body we do as a single tag H1 and a div with id authorsList where we will add the database.

4 Now I created the pubs model which is linked to the publication database, and I chose only the authors table in my EDMX model. You can use your own database.

5. Then, to create a JsonResult method will get the database data and serialize JSON string.

public JsonResult GetAuthors()
{
pubsEntities pubs = new pubsEntities();
authors of var = pubs.authors.ToList ();
return Json (authors, JsonRequestBehavior.AllowGet).
}

Therefore, I am creating an instance of the object of pubsEntities and get all the authors in the authors list. And then returning the list of the authors by JSON serialization in Json method. JsonRequestBehaviour.AllowGet parameter is used to GET the client queries are allowed. By default in ASP.NET MVC 2 get is not allowed by the security with JSON hijacking problem.

6. Then, to create AJAX jQuery function that calls the GetAuthors method. We will use jQuery method $.getJSON.

Once the web page is downloaded, the method will be called. The first parameter of $. getJSON() is the url string in our case, the method name. The second parameter (which, in the example, is the empty string) is the key value pairs will be send to the server, and the third function is the callback function or the result will be returned by the server.

Inside the callback function, we have code that makes the data model that has id # authorsTemplate and adds it to the element that has # authorsList.

7. The model of jQuery

As you can see, I have tags containing fields (au_lname, au_fname…, etc.) that corresponds to the table in EDMX model which is the same as in the database.

One thing more than noted here is that I printMessage function (state) which is called inside the tag of ${expression/function/field}.

Function printMessage

Therefore, if the State is "CA" impression "is the author of California" else "the author is not California"

HERE IS THE COMPLETE ASPX CODE



Sample database: jQuery templates


    

    



Authors of pubs



Thus, in the complete sample, you also have the CSS style I use for my page output.

Here's the final result displayed on the web page screen printing:

You can download the full source, including examples presented in my previous blog posts on jQuery templates and presentation PPT my last session, I got to the local .NET UG meeting at the following DOWNLOAD LINK.

Let me know your comments.

With respect,
Hajan

Tuesday, December 14, 2010

ASP.NET MVC 3 version Release Candidate 2 release (Weblogs @ ASP.NET)

Microsoft has shipped Release Candidate 2 for ASP.NET MVC 3 version. You can download the ASP.NET MVC 3 Release Candidate 2 here. If you have installed Visual Studio Service Pack 1 Beta, you must install ASP.NET MVC 3 RC 2. Otherwise, it stops the IntelliSense feature in ASP.NET MVC 3 RC1 knife views.

Here are some new changes in ASP.NET MVC 3 RC 2.

Added Html.Raw MethodRenamed "Controller.ViewModel" property and ownership of "View" to "ViewBag" class "ControllerSessionStateAttribute" to "SessionStateAttribute" fixed "RenderAction" method to provide explicit values for the renamed template binding priority

You will find details of ScottGu post blog Announces ASP.NET MVC 3 (Release Candidate 2)

Monday, December 13, 2010

The perfect DotNetNuke Christmas present (Weblogs @ ASP.NET)

Is that you are racking your brain tries to achieve this DotNetNuke person in your life? If so, I have just the solution!

You can buy them my book! DotNetNuke 5 user guide: take advantage of your Web site in and running! It is perfect for the love of your life DotNetNuke.

DotNetNuke 5 User's Guide: Get Your Website Up and Running (Wrox Programmer to Programmer)

If you buy a copy and want to sign, I'll even offer to sign if sent you to me. Please be sure to include postal charges in both directions. You may not able to do for me and go back in time for Christmas, but the signature can occur at any time.

You can send it to:

DotNetNuke Corporation
c/o Chris Hammond
155, Rue Bovet, Suite 201
San Mateo, CA 94402

You may not be able talk to my co-author Patrick Renner offering the same service, although you will need to contact him at http://www.patrickrenner.com/ asking!

It sits on to Amazon and discover book, be sure to get your orders in time for Christmas!

ADIOS blogs (Weblogs @ ASP.NET)

Monday, December 13, 2010 12 H 18 kashyapa I was blogging about Weblogs.asp.net for some time now. I do remember when in fact I got a tie-up for weblogs. I think it was MS Joe - Joe Stagner way back somewhere in 2005 or some time around this time (I don't remember the exact dates) had opened a blog weblogs.asp.net space. I remember sending an email to him and I had got blogs away from myself.So space has been a great platform start for me. After nearly a decade in the industry (this is my nine years in the industry) I finally realized that I too can write and I was recently passionate about writing. So far I have 15 posts under my belt and close to the 5 speaking sessions.I community have been recently enjoying writing and the community of the things that I have decided to have my own identity on the web. Yes, I bought my own domain, and I took place one hosting to my own blog. My new web identity would be 2 domains under my name - http://www.kashyapas.com/ http://www.lohithgn.com/. I will be writing interrupt the weblogs.asp.net and will be full-time to weblogs.asp.net RSS was redirected to my new site http://www.kashyapas.com/.My. For anyone who had subscribed to my RSS feed will always receive content updated my new site.So fall into my new House and let me know your feedback.As I say always - code with passion and Happy coding! Filed under: .NET, community, community news

SQL Server Express and VS2010 Web Application .mdf errors (Weblogs @ ASP.NET) file

I have installed SQL Server 2008 and SQL Server 2008 Express on my new Windows 7 development environment with Visual Studio 2010. I could obtain SQL Server 2008 to work correctly, but I could not express .mdf database for the sample web application projects without receiving the error below:


Unable to generate an instance of SQL Server user due to a failure in starting the process for the user instance. The connection will be closed.


For example, I was creating an ASP.NET Web application. When I ran the application and attempt to register a new user, I received an error:


 


I muddled by many daunting trials I wore it while I tried to determine if the problem was due to the "patch incompatibility" necessary with SQL Server 2008 and Windows 7, or if it was due to SQL Server Express is installed correctly, or VS2010 arrrgggh! Needless to say that many of reinstalls many products made prior to the conclusion of the forum post below (and the fix was simple!):


http://forums.ASP.NET/t/1377174.aspx

Unable to generate an instance of SQL Server user due to a failure in starting the process for the user instance. The connection will be closed.

The highest position proposed delete directory SQLEXPRESS and rebooting, I did. It should be noted, my path was quite different from that recommended in the above post. I used the file manager to find "SQLEXPRESS".


C:\Users\Nannette\AppData\Local\Microsoft\Microsoft SQL Server Data\SQLEXPRESS

After reboot, I received another error: the specific instance or network error has occurred in establishing a connection to SQL Server. The server is not found or was not available. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Shared Memory provider, error: 40 - could not open a connection to SQL Server) One of the above post readers suggested patch below:

Go to: Control Panel--> > Services administrative tools


right-click the service SQL Server (SQLEXPRESS) then Properties-> Then GoTo Logon tab-> select the local system account option-> apply-> OK

Note in my Windows 7 install administration tools displayed in the Control Panel, so I had to find "Admin" from the Panel to the Administrative Tools icon. When I arrived, my local system account was already setup, what was not my problem.

However, by taking these steps I found the SQL Server Express has been set to automatic but has not started. This is why I started it.

I then returned to my web application and I was able to open the file ASPNETDB.MDF in my VS2010 environment, and I was able to run the application and register a new user! No more errors! Can be of your dreams in ASP.NET! Nannette Thacker

Deployable dependencies in Visual Studio 2010 beta SP1 (Weblogs @ ASP.NET)

A new feature that comes with Visual Studio 2010 beta SP1 is supported for deployment references. Reference deployment means that you can include all DLL - s to a deployment package to ensure that your application has all the assemblies that it must operate with it in the deployment package. In this posting I'll show you how to use the dependencies of deployment.

When I open my ASP.NET web application I have new option for reference when I right click on my web project: Add deployment Dependencies…

Visual Studio 2010 SP1 Beta: Add deployable dependencies

If you select it you'll see dialog where you can select the dependencies you want to add to your package project.

Visual Studio 2010 SP1 Beta: Select deployable dependencies

When the packets you need are selected click OK. Visual Studio adds the new folder to your project called _bin_DeployableAssemblies.

Visual Studio 2010 SP1 Beta: Deployable references for RazorScreenshot on the right shows the list assemblies added to the ASP.net pages and knife. All DLL - s required to run ASP.NET MVC 3 knife view engine are here. I don't know if NuGet.Core.dll is required in the production, but it is added, then let it be.

I tried to deploy my ASP.NET MVC project that uses the Windows azure knife after the addition of deployable references to my project.

Deployment went fine and the web role instance started without any problems. The only reference DLLs, that as local was the System.Web.mvc. All knife tricks came with deployable dependencies.

Visual Studio support deployable dependencies is great, because this way component providers can build definitions also components assemblies that are loaded dynamically executing will be in the deployment package.

Sunday, December 12, 2010

The challenge with HTML5 - in images (Weblogs @ ASP.NET)

I love working with Web technologies and look forward to new features HTML5 poised ultimately at the table (which can be used today). After being the battle of the layer at the time by the div versus IE4 and Netscape 4 I think that we are directed on this road reconstituted to browsers implement features differently. I spent a lot of research time and playing around HTML5 examples and features (mainly because we are already witnessing the demand for training on HTML5) and there are many great things there that will truly revolutionize web applications we know. However, just browsers did it again and many people outside of the development world does really feel a need to update their browser if it works reasonably well, Mum and dad come to mind) so that there will be some time.

There is a nice http://www.HTML5Test.com test site through various features of HTML5 and notes how even though they are supported. They test for everything and are very clear on this subject on the site:

"HTML5 test result is only an indication of how your browser supports standard and related upcoming HTML5 specifications." It does not attempt to test all the new features offered by HTML5 or trying to test the functionality of each feature it does not detect. Despite these shortcomings, we hope to quantify the level of support to users and web developers will get an idea of how hard browser manufacturers are working on the improvement of their browsers and the web as a platform for development.

The score is calculated by testing for the many new features of HTML5. Each feature is worth one or more points. Apart from the main specification HTML5 and other specifications established W3C HTML Working Group, this test also provides points for support related projects and specifications. Some of these specifications were originally part of the HTML5, but are now developed by other W3C working groups. WebGL is also part of this test despite do not in development by the W3C, because it extends element HTML5 canvas with a 3d context.

The test also gives points bonus for supporting audio codecs and video and SVG or MathML incorporation in a simple HTML document. These tests do count towards the total score because HTML5 specifies audio not required nor video codec. Also SVG and MathML are not required by HTML5, the specification States only to the rules for how this content must be nested inside a single HTML file.

Please note that put to the test specifications are still in development and may change prior to receive an official status. In the future new tests are added for parts of the specification which are currently still missing. The maximum number of points that can be marked is 300 at the moment, but it is a moving target. »

It looks like their tests have not been updated since June, but figures are quite stressful as a developer because it means I am going to do a lot of browser sniffing to assume that a particular feature is available for use. That very different step of what we do today as many browser sniffing say you? I would have to disagree, because HTML5 need to a whole new level. In today's world, we have libraries such as jQuery (my personal favorite), prototype, script.aculo.us, YUI Library MooTools, script etc that handle the heavy lifting for us. Until these libraries manage all HTML5 key features available it will be a challenge. Some features like tables are fairly well supported in most major while other features such as audio and video are hit browsers or fail depending on what codec you want to use. Run the tests yourself to see what goes and what fails for different browsers. You can also view the results of compliance HTML5 test following http://test.w3.org/html/tests/reporting/report.htm (a work in progress).

The following table lists scores than HTML5Test site returned for different browsers, that I installed on my desktop and laptop. A specific list to run tests and features supported are given when you access the site. Note that I went ahead and tested the beta version of IE9 and it was almost as good as I expected it, but it is not officially that I expect that number is going to change much.

Am opposed to HTML5 from these tests? Of course not - I'm actually really excited what it offers.  However, I try to be realistic and feel it will definitely add a new level of headaches in the process of developing Web application having been's something like this many years ago. On the reverse, developers who are able to target a specific browser (generally intranet applications) or controlling cross-browser issues will release some fairly soft applications. See http://html5gallery.com/ for a blow to look at some more advanced sites out there that use HTML5. See also Microsoft together to showcase IE9 http://www.beautyoftheweb.com site.

Dynamic ViewBag in ASP.NET MVC 3 - RC 2 (Weblogs @ ASP.NET)

Earlier today Scott Guthrie announced the ASP.NET MVC 3 - Release Candidate 2. I installed the new version right after the announcement, since I'm looking forward to see the new features. Among the other cool features included in this release candidate, there is a new ViewBag dynamic Views that can be used to pass data controllers as well as you use ViewData dictionary []. What is great and beautiful ViewBag (despite the name) is that its a dynamic type, which means that you can dynamically get/set values and add any number of additional fields without the need of strongly typed classes.


To see the difference, take a look at the following examples.


Example - in ViewData


Controller

public ActionResult Index()
{
The list of colors = new list ();
Colors.Add ("Red");
Colors.Add ("green");
Colors.Add ("Blue");

ViewData ["listColors"] = colors.
ViewData ["dateNow"] = DateTime.Now.
ViewData ["name"] = "Hajan".
ViewData ["age"] = 25;


Back to View().
}



View (ASPX see Engine)



My name is
<%: ViewData["name"] %>,
<%: ViewData["age"] %>years old.

    
I love the following colours:




    <% foreach (var color in ViewData["listColors"] as List){ %>


  • <%: color %>

  • <% } %>



<%: ViewData["dateNow"] %>


(I know the code might look more like own knife display engine, but few important right? point)


Example - using ViewBag


Controller

public ActionResult Index()
{
The list of colors = new list ();
Colors.Add ("Red");
Colors.Add ("green");
Colors.Add ("Blue");

ViewBag.ListColors = color. //Colors is list
ViewBag.DateNow = DateTime.Now.
ViewBag.Name = "Hajan".
ViewBag.Age = 25;
Back to View().
}


You can see the difference?


View (ASPX see Engine)



My name is
<%: ViewBag.Name %>,
<%: ViewBag.Age %>years old.

    
I love the following colours:




    <% foreach (var color in ViewBag.ListColors) { %>


  • <%: color %>

  • <% } %>





<%: ViewBag.DateNow %>


In my example, now I must cast ViewBag.ListColors list ViewBag is dynamic! On the other hand the ViewData ["key"] is object.


I would like to note that if you use ViewData ["ListColors"] = color;in your controller, you can retrieve the view to ViewBag.ListColors.


In both cases is

Saturday, December 11, 2010

Announcing ASP.NET MVC 3 (Release Candidate 2) (Weblogs @ ASP.NET)

Earlier today the ASP.NET team shipped the final release candidate (RC2) for ASP.NET MVC 3.  You can download and install it here.


Today’s RC2 release is the near-final release of ASP.NET MVC 3, and is a true “release candidate” in that we are hoping to not make any more code changes with it.  We are publishing it today so that people can do final testing with it, let us know if they find any last minute “showstoppers”, and start updating their apps to use it.  We will officially ship the final ASP.NET MVC 3 “RTM” build in January.


Today’s ASP.NET MVC 3 RC2 release works with both the shipping version of Visual Studio 2010 / Visual Web Developer 2010 Express, as well as the newly released VS 2010 SP1 Beta. 


This means that you do not need to install VS 2010 SP1 (or the SP1 beta) in order to use ASP.NET MVC 3.  It works just fine with the shipping Visual Studio 2010.  I’ll do a blog post next week, though, about some of the nice additional feature goodies that come with VS 2010 SP1 (including IIS Express and SQL CE support within VS) which make the dev experience for both ASP.NET Web Forms and ASP.NET MVC even better.


Today’s ASP.NET MVC 3 RC2 build contains many bug fixes and performance optimizations.  Our latest performance tests indicate that ASP.NET MVC 3 is now faster than ASP.NET MVC 2, and that existing ASP.NET MVC applications will experience a slight performance increase when updated to run using ASP.NET MVC 3.


In addition to bug fixes and performance optimizations, today’s RC2 build contains a number of last-minute feature tweaks and “fit-n-finish” changes for the new ASP.NET MVC 3 features.  The feedback and suggestions we’ve received during the public previews has been invaluable in guiding these final tweaks, and we really appreciate people’s support in sending this feedback our way. 


Below is a short-list of some of the feature changes/tweaks made between last month’s ASP.NET MVC 3 RC release and today’s ASP.NET MVC 3 RC2 release:


jQuery updates and addition of jQuery UI


The default ASP.NET MVC 3 project templates have been updated to include jQuery 1.4.4 and jQuery Validation 1.7. 


We are also excited to announce today that we are including jQuery UI within our default ASP.NET project templates going forward.  jQuery UI provides a powerful set of additional UI widgets and capabilities.  It will be added by default to your project’s \scripts folder when you create new ASP.NET MVC 3 projects.


Improved View Scaffolding


The T4 templates used for scaffolding views with the Add-View dialog now generates views that use Html.EditorFor instead of helpers such as Html.TextBoxFor. This change enables you to optionally annotate models with metadata (using data annotation attributes) to better customize the output of your UI at runtime.


The Add View scaffolding also supports improved detection and usage of primary key information on models (including support for naming conventions like ID, ProductID, etc).  For example: the Add View dialog box uses this information to ensure that the primary key value is not scaffold as an editable form field, and that links between views are auto-generated correctly with primary key information.


The default Edit and Create templates also now include references to the jQuery scripts needed for client validation.  Scaffold form views now support client-side validation by default (no extra steps required).  Client-side validation with ASP.NET MVC 3 is also done using an unobtrusive javascript approach – making pages fast and clean.


[ControllerSessionState] –> [SessionState]


ASP.NET MVC 3 adds support for session-less controllers.  With the initial RC you used a [ControllerSessionState] attribute to specify this.  We shortened this in RC2 to just be [SessionState]:


image


Note that in addition to turning off session state, you can also set it to be read-only (which is useful for webfarm scenarios where you are reading but not updating session state on a particular request).


[SkipRequestValidation] –> [AllowHtml]


ASP.NET MVC includes built-in support to protect against HTML and Cross-Site Script Injection Attacks, and will throw an error by default if someone tries to post HTML content as input.  Developers need to explicitly indicate that this is allowed (and that they’ve hopefully built their app to securely support it) in order to enable it.


With ASP.NET MVC 3, we are also now supporting a new attribute that you can apply to properties of models/viewmodels to indicate that HTML input is enabled, which enables much more granular protection in a DRY way.  In last month’s RC release this attribute was named [SkipRequestValidation].  With RC2 we renamed it to [AllowHtml] to make it more intuitive:


image


Setting the above [AllowHtml] attribute on a model/viewmodel will cause ASP.NET MVC 3 to turn off HTML injection protection when model binding just that property.


Html.Raw() helper method


The new Razor view engine introduced with ASP.NET MVC 3 automatically HTML encodes output by default.  This helps provide an additional level of protection against HTML and Script injection attacks.


With RC2 we are adding a Html.Raw() helper method that you can use to explicitly indicate that you do not want to HTML encode your output, and instead want to render the content “as-is”:


image


ViewModel/View –> ViewBag


ASP.NET MVC has (since V1) supported a ViewData[] dictionary within Controllers and Views that enables developers to pass information from a Controller to a View in a late-bound way.  This approach can be used instead of, or in combination with, a strongly-typed model class.  The below code demonstrates a common use case – where a strongly typed Product model is passed to the view in addition to two late-bound variables via the ViewData[] dictionary:


image


With ASP.NET MVC 3 we are introducing a new API that takes advantage of the dynamic type support within .NET 4 to set/retrieve these values.  It allows you to use standard “dot” notation to specify any number of additional variables to be passed, and does not require that you create a strongly-typed class to do so. 


With earlier previews of ASP.NET MVC 3 we exposed this API using a dynamic property called “ViewModel” on the Controller base class, and with a dynamic property called “View” within view templates.  A lot of people found the fact that there were two different names confusing, and several also said that using the name ViewModel was confusing in this context – since often you create strongly-typed ViewModel classes in ASP.NET MVC, and they do not use this API. 


With RC2 we are exposing a dynamic property that has the same name – ViewBag – within both Controllers and Views.  It is a dynamic collection that allows you to pass additional bits of data from your controller to your view template to help generate a response.  Below is an example of how we could use it to pass a time-stamp message as well as a list of all categories to our view template:


image


Below is an example of how our view template (which is strongly-typed to expect a Product class as its model) can use the two extra bits of information we passed in our ViewBag to generate the response.  In particular, notice how we are using the list of categories passed in the dynamic ViewBag collection to generate a dropdownlist of friendly category names to help set the CategoryID property of our Product object. 


image


The above Controller/View combination will then generate an HTML response like below. 


image 


Output Caching Improvements


ASP.NET MVC 3’s output caching system no longer requires you to specify a VaryByParam property when declaring an [OutputCache] attribute on a Controller action method.  MVC3 now automatically varies the output cached entries when you have explicit parameters on your action method – allowing you to cleanly enable output caching on actions using code like below:


image


In addition to supporting full page output caching, ASP.NET MVC 3 also supports partial-page caching – which allows you to cache a region of output and re-use it across multiple requests or controllers.  The [OutputCache] behavior for partial-page caching was updated with RC2 so that sub-content cached entries are varied based on input parameters as opposed to the URL structure of the top-level request – which makes caching scenarios both easier and more powerful than the behavior in the previous RC.


@model declaration does not add whitespace


In earlier previews, the strongly-typed @model declaration at the top of a Razor view added a blank line to the rendered HTML output. This has been fixed so that the declaration does not introduce whitespace.


Changed "Html.ValidationMessage" Method to Display the First Useful Error Message


The behavior of the Html.ValidationMessage() helper was updated to show the first useful error message instead of simply displaying the first error.


During model binding, the ModelState dictionary can be populated from multiple sources with error messages about the property, including from the model itself (if it implements IValidatableObject), from validation attributes applied to the property, and from exceptions thrown while the property is being accessed.


When the Html.ValidationMessage() method displays a validation message, it now skips model-state entries that include an exception, because these are generally not intended for the end user. Instead, the method looks for the first validation message that is not associated with an exception and displays that message. If no such message is found, it defaults to a generic error message that is associated with the first exception.


RemoteAttribute “Fields” -> “AdditionalFields”


ASP.NET MVC 3 includes built-in remote validation support with its validation infrastructure.  This means that the client-side validation script library used by ASP.NET MVC 3 can automatically call back to controllers you expose on the server to determine whether an input element is indeed valid as the user is editing the form (allowing you to provide real-time validation updates).


You can accomplish this by decorating a model/viewmodel property with a [Remote] attribute that specifies the controller/action that should be invoked to remotely validate it.  With the RC this attribute had a “Fields” property that could be used to specify additional input elements that should be sent from the client to the server to help with the validation logic.  To improve the clarity of what this property does we have renamed it to “AdditionalFields” with today’s RC2 release.


ViewResult.Model and ViewResult.ViewBag Properties


The ViewResult class now exposes both a “Model” and “ViewBag” property off of it.  This makes it easier to unit test Controllers that return views, and avoids you having to access the Model via the ViewResult.ViewData.Model property.


You can download and install the ASP.NET MVC 3 RC2 build here.  It can be installed on top of the previous ASP.NET MVC 3 RC release (it should just replace the bits as part of its setup).


The one component that will not be updated by the above setup (if you already have it installed) is the NuGet Package Manager.  If you already have NuGet installed, please go to the Visual Studio Extensions Manager (via the Tools –> Extensions menu option) and click on the “Updates” tab.  You should see NuGet listed there – please click the “Update” button next to it to have VS update the extension to today’s release.


If you do not have NuGet installed (and did not install the ASP.NET MVC RC build), then NuGet will be installed as part of your ASP.NET MVC 3 setup, and you do not need to take any additional steps to make it work.


We are really close to the final ASP.NET MVC 3 release, and will deliver the final “RTM” build of it next month.  It has been only a little over 7 months since ASP.NET MVC 2 shipped, and I’m pretty amazed by the huge number of new features, improvements, and refinements that the team has been able to add with this release (Razor, Unobtrusive JavaScript, NuGet, Dependency Injection, Output Caching, and a lot, lot more).  I’ll be doing a number of blog posts over the next few weeks talking about many of them in more depth.


Hope this helps,


Scott


P.S. In addition to blogging, I am also now using Twitter for quick updates and to share links. Follow me at: twitter.com/scottgu

Friday, December 10, 2010

Visual Studio 2010 Service Pack 1 Beta release (Weblogs @ ASP.NET)

Microsoft has released beta version of Visual Studio 2010 Service Pack 1. The beta version of Visual Studio 2010 Service Pack 1 comes with a licence alive go.

Here are links to download Visual Studio 2010 Service Pack 1

The beta version of SP1 is delivered with a few bugs and also provides new functionality. Here are some of the new functionality is provided with Visual Studio 2010 Service Pack 1

HTML5 schema SupportIIS Express SupportSQL Compact Edition 4 ToolingSilverlight 4 tools Visual Studio 2010

If you have ASP.NET MVC 3 or installed, SP1 breaks IntelliSense functionality in views of knife. This fix in the version of ASP.NET MVC 3 RC 2 and will be release soon.

A simple article DotNetNuke module c# with VB.NET source (Weblogs @ ASP.NET)

The Conference connections DotNetNuke last month I provided a course advanced the development of the DotNetNuke module as a training session prior to the Conference. This training covered more details on how to implement some of the latest on the DotNetNuke platform for custom modules, mainly ContentItem integration features and characteristics of the taxonomy.

Course, I've created a module for DotNetNuke, very basic section at the end of the account it appoint DNNSimpleArticle. Course, I created a c# and VB.net module version. Offer course I cleaned up things a little more in the module and downloaded everything tonight at CodePlex http://dnnsimplearticle.codeplex.com. Please read the full blog ticket for further details on the module and a few warnings (this module is not supported, use at your own risk)

The Conference connections DotNetNuke last month I provided a course advanced the development of the DotNetNuke module as a training session prior to the Conference. This training covered more details on how to implement some of the latest on the DotNetNuke platform for custom modules, mainly ContentItem integration features and characteristics of the taxonomy.

Course, I've created a module for DotNetNuke, very basic section at the end of the account it appoint DNNSimpleArticle. Course, I created a c# and VB.net module version. Offer course I cleaned up things a little more in the module and downloaded everything tonight at CodePlex http://dnnsimplearticle.codeplex.com.

Keep in mind a few things before that I'm going to talk about the features of the module.

This module is not supported! (use at your own risk) This module is free. This module is released under the same license MIT DotNetNuke is allowed. This module has seen a limited trial, use at your own risk Winking smile this module was compiled against DNN 5.5.1, will not install and run on an older version without recompiling. The initial version c# and VB.NET code but future versions will probably only be released by c#.

Here is a brief summary of the module. This is a very basic module for creating articles (title, description and body) and has the ability to assign articles with DotNetNuke taxonomy functionality. It also provides simple SEO features by setting the title of the HTML page, description and keywords when an individual article is loaded into the view mode.

This module provides the following features

Create and display items displays a paged articles what articles list get created DNN ContentItems categorization provided by DNN SEO feature article taxonomy display providing HTML title, Meta Description and Meta-keyword loaded dynamically controls ArticleList and the ArticleView functionality based on ArticleId list displays categories below querystring parameter ArticleDisplay, this list of links to the SearchResults page article in the category parameter TAG to display in the list. Compiled against DNN 5.5.1 (if you want to run against an older version, you need to recompile) uses MSBuild to automated packaging (requires http://msbuildtasks.tigris.org/ MSBuildTasks) (see this blog for a little info/video on the msbuild ticket)

I am running the module on a DNN Web site I recently http://www.sccaforums.com/ installation, it brings new cover page for the moment. There are of course still of some things that can be drawn for the module and with this site in General, also but it works well and have been indexed quite well by engines search within two weeks, that he was executed it.

I will be blogging in the next days with more details on this Web site in particular, as it is a recent conversion CommunityServer DotNetNuke platform. I have another project codeplex for SQL scripts used in the conversion process. The blog will be talking about the process and we hope that provide some guidance for those interested in converting a CommunityServer DNN Web site.

Back to the well module: you can download the first version (labelled V00.00.03) from Codeplex.

Class-level validation of the model with EF code first and ASP.NET MVC 3 (Weblogs @ ASP.NET)

Earlier this week the data team released the CTP5 build of the new Entity Framework Code-First library. 


In my blog post a few days ago I talked about a few of the improvements introduced with the new CTP5 build.  Automatic support for enforcing DataAnnotation validation attributes on models was one of the improvements I discussed.  It provides a pretty easy way to enable property-level validation logic within your model layer.


You can apply validation attributes like [Required], [Range], and [RegularExpression] – all of which are built-into .NET 4 – to your model classes in order to enforce that the model properties are valid before they are persisted to a database.  You can also create your own custom validation attributes (like this cool [CreditCard] validator) and have them be automatically enforced by EF Code First as well.  This provides a really easy way to validate property values on your models.  I showed some code samples of this in action in my previous post.


DataAnnotation attributes provides an easy way to validate individual property values on your model classes. 


Several people have asked - “Does EF Code First also support a way to implement class-level validation methods on model objects, for validation rules than need to span multiple property values?”  It does – and one easy way you can enable this is by implementing the IValidatableObject interface on your model classes.


IValidatableObject.Validate() Method


Below is an example of using the IValidatableObject interface (which is built-into .NET 4 within the System.ComponentModel.DataAnnotations namespace) to implement two custom validation rules on a Product model class.  The two rules ensure that:

New units can’t be ordered if the Product is in a discontinued state New units can’t be ordered if there are already more than 100 units in stock

We will enforce these business rules by implementing the IValidatableObject interface on our Product class, and by implementing its Validate() method like so:


image


The IValidatableObject.Validate() method can apply validation rules that span across multiple properties, and can yield back multiple validation errors. Each ValidationResult returned can supply both an error message as well as an optional list of property names that caused the violation (which is useful when displaying error messages within UI).


Automatic Validation Enforcement


EF Code-First (starting with CTP5) now automatically invokes the Validate() method when a model object that implements the IValidatableObject interface is saved.  You do not need to write any code to cause this to happen – this support is now enabled by default.


This new support means that the below code – which violates one of our above business rules – will automatically throw an exception (and abort the transaction) when we call the “SaveChanges()” method on our Northwind DbContext:


image


In addition to reactively handling validation exceptions, EF Code First also allows you to proactively check for validation errors.  Starting with CTP5, you can call the “GetValidationErrors()” method on the DbContext base class to retrieve a list of validation errors within the model objects you are working with.  GetValidationErrors() will return a list of all validation errors – regardless of whether they are generated via DataAnnotation attributes or by an IValidatableObject.Validate() implementation. 


Below is an example of proactively using the GetValidationErrors() method to check (and handle) errors before trying to call SaveChanges():


image


ASP.NET MVC 2 included support for automatically honoring and enforcing DataAnnotation attributes on model objects that are used with ASP.NET MVC’s model binding infrastructure.  ASP.NET MVC 3 goes further and also honors the IValidatableObject interface.  This combined support for model validation makes it easy to display appropriate error messages within forms when validation errors occur. 


To see this in action, let’s consider a simple Create form that allows users to create a new Product:


image


We can implement the above Create functionality using a ProductsController class that has two “Create” action methods like below:


image


The first Create() method implements a version of the /Products/Create URL that handles HTTP-GET requests - and displays the HTML form to fill-out.  The second Create() method implements a version of the /Products/Create URL that handles HTTP-POST requests - and which takes the posted form data, ensures that is is valid, and if it is valid saves it in the database.  If there are validation issues it redisplays the form with the posted values. 


The razor view template of our “Create” view (which renders the form) looks like below:


image


One of the nice things about the above Controller + View implementation is that we did not write any validation logic within it.  The validation logic and business rules are instead implemented entirely within our model layer, and the ProductsController simply checks whether it is valid (by calling the ModelState.IsValid helper method) to determine whether to try and save the changes or redisplay the form with errors. The Html.ValidationMessageFor() helper method calls within our view simply display the error messages our Product model’s DataAnnotations and IValidatableObject.Validate() method returned. 


We can see the above scenario in action by filling out invalid data within the form and attempting to submit it:


image


Notice above how when we hit the “Create” button we got an error message.  This was because we ticked the “Discontinued” checkbox while also entering a value for the UnitsOnOrder (and so violated one of our business rules). 


You might ask – how did ASP.NET MVC know to highlight and display the error message next to the UnitsOnOrder textbox?  It did this because ASP.NET MVC 3 now honors the IValidatableObject interface when performing model binding, and will retrieve the error messages from validation failures with it.


The business rule within our Product model class indicated that the “UnitsOnOrder” property should be highlighted when the business rule we hit was violated:


image


Our Html.ValidationMessageFor() helper method knew to display the business rule error message (next to the UnitsOnOrder edit box) because of the above property name hint we supplied:


image


ASP.NET MVC and EF Code First enables you to keep your validation and business rules in one place (within your model layer), and avoid having it creep into your Controllers and Views. 


Keeping the validation logic in the model layer helps ensure that you do not duplicate validation/business logic as you add more Controllers and Views to your application.  It allows you to quickly change your business rules/validation logic in one single place (within your model layer) – and have all controllers/views across your application immediately reflect it.  This help keep your application code clean and easily maintainable, and makes it much easier to evolve and update your application in the future.


EF Code First (starting with CTP5) now has built-in support for both DataAnnotations and the IValidatableObject interface.  This allows you to easily add validation and business rules to your models, and have EF automatically ensure that they are enforced anytime someone tries to persist changes of them to a database. 


ASP.NET MVC 3 also now supports both DataAnnotations and IValidatableObject as well, which makes it even easier to use them with your EF Code First model layer – and then have the controllers/views within your web layer automatically honor and support them as well.  This makes it easy to build clean and highly maintainable applications.


You don’t have to use DataAnnotations or IValidatableObject to perform your validation/business logic.  You can always roll your own custom validation architecture and/or use other more advanced validation frameworks/patterns if you want.  But for a lot of applications this built-in support will probably be sufficient – and provide a highly productive way to build solutions.


Hope this helps,


Scott


P.S. In addition to blogging, I am also now using Twitter for quick updates and to share links. Follow me at: twitter.com/scottgu