ASP.NET 4.0 Hosting & ASP.NET 4.5 Hosting BLOG

BLOG about ASP.NET 4.5 Hosting, ASP.NET 4.0 Hosting and .NET 4.5 Framework and its Capabilities

ASP.NET MVC 4 Hosting :: Working with HTML5 Chart Helper Extension for ASP.NET MVC 4

clock September 11, 2012 06:41 by author Administrator

With the introduction of ASP.NET MVC, the traditional ‘Control’ model of GUI component development went away. Instead it was replaced with the more Web 2.0 style JavaScript and jQuery plugin extensibility model. Nevertheless, adding incremental features to existing HTML components was always required and towards this end Microsoft introduced the HtmlHelper and helper extensions. Helper extensions are .NET extension methods that return a string. Typically, this string is formatted HTML content.


 
In our sample today we create an extension that renders a bar chart on HTML5 Canvas. It can be bound to a data source from the server side or be assigned data source from the client side.

Building a Html Helper Extension

Html Helper extensions are easy to build. Just follow the steps below to create our helper skeleton.

Step 1: We start with an MVC project and pick the Blank template.

Note we could pick a class library project template too and add package references as follows (via the Nuget package manager as follows)

a. PM> install-package Microsoft.AspNet.Mvc
b. Add reference to System.Web.dll from the ‘Add References’ dialog for the project

Step 2: Add a static class called ChartExtensions. Extension methods, by design, have to be defined in Static classes.

Step 3: Next add a static method Chart whose first parameters is this HtmlHelper and subsequent parameters are values required for rendering the chart.



a. The dataSource is a list of integer arrays. For the example we have assumed a two dimensional array would be provided as a data source. We can make it more sophisticated by making it an array of objects and binding to different properties of the object.
b. xTitle: The text to be displayed on the x-axis.
c. yTitle: The text to be displayed on the y-axis.

Step 4: Next we setup two methods, one to convert the dataSource to JSON and the other to generate the required HTML.



a. The GetDataSourceFromIntArray method uses the System.Web.Helpers’ Json static class to convert the input data source into a Json String. This string is assigned to a variable called arrDataSource and the whole string is returned.
b. The SetupHtml method implements the rendering logic

Step 5: Using TagBuilder to build the Html: ASP.NET provides us with the TagBuilder class that has helper methods to help create HTML elements easily. We use the TagBuilder to create our HTML layout as follows

<div>
<canvas …> … </canvas>
<script …> … </script>
<noscript> … </noscript>
</div>

The actual code is as follows


a. As seen above, the TagBuilder object has an Attributes collection to which we can add the HTML attributes we need. To set text between the opening tag and closing tag, we use the SetInnerText. However unlike an XmlTextWriter, we can’t nest tags. To nest tags we simply assign the string representation of the TagBuilder to the InnerHtml of the parent TagBuilder. So the ‘container’ Tag Builder has the <div> that encapsulates the Canvas and the Script tags.
b. We have created a 400x600 canvas area. The chartName parameter is used for the id of the canvas element.
c. For now we have an empty SetupScript method. This method will eventually build the JavaScript required to render the bar graph.
d. The <noscript> tag holds the message to display when JavaScript is not enabled on the browser.
e. Point to note is the HtmlString object that is returned. The HtmlString is a special object that indicates to the Razor view engine that it should not Html Encode this string any further. If we use string instead of HtmlString, the Razor engine automatically Html Encodes the string and we see the markup as text instead of rendered Html.

Step 6: The SetupScript method: The setup script method has the JavaScript that actually renders the chart on the canvas. The original code is borrowed (with permission) from this project. A demo for it is available here. We have to make the following changes so that it accepts any data source instead of the fixed data source assigned to it in the demo. We have also updated the code to use the strings passed in for x-axis and y-axis labels. Beyond this the animation and rendering code is pretty much the same.

a. The variable initialization change

Earlier we had a hard-coded array of strings that was rendered on the canvas. Now we have the Json string that is created from the data source that was passed to the helper.
b. Changes to the barChart() method to set data source on the client side.

In the barChart method we earlier had no parameters and the elementId was hard-coded, now we use the value that’s passed into the helper.
We also pass a data parameter that is assigned to the data source of the graph.
c. Changes in drawMarkers() method to use the values passed into the helper for the x-axis and y-axis label

d. Changes to handle two-dimensional array of points instead of one-dimensional array of comma separated strings.


In the original code, the data source is an array of strings. Each element in the array has two comma separated values, represent the year (at index-0) and number of hits (at index-1). We have updated our data source to be a two-dimensional array and hence we don’t need to do a string split to get the value. We directly access the value using appropriate indexes. This change is at three places in the code. One of them is shown above.

With these changes in place our Chart, HtmlHelper is ready to be tested in an ASP.NET Web Application

Integrating the Custom Helper in a MVC Web Application

With our Helper all set, we add an MVC Web Application to our solution and call it DotNetCurry.HtmlHelpers.WebHarness. We use the Internet template that gives us a default Index.cshtml to put our Helper in. The following steps guide us through the integration effort

Step 1: Add Reference to the HtmlHelper project.

Step 2: Add a Model class in the Models folder.


This is our view model that will hold the data to be rendered in the Graph.

Step 3: Update the HomeController to create and pass sample data model.



As seen above, we create an instance of our ViewModel class and add some test data into it. We pass this data on to the Index view, where the HtmlHelper will use it.

Step 4: Update the Index.cshtml markup to use the helper

 

The changes in Index.cshtml highlighted above, from top to bottom are as follows

a. Declare the model to be used in the page.
b. Add using to include the custom HtmlHelper
c. Added the HtmlForm inside which we use our Chart Helper extension. We give it an id=’sampleChart’, pass it the Model.Data and provide the labels for the x and y axes.
d. Finally in the jQuery document ready function, we initialize the chart by calling the barChart() method.
e. Our final effort looks as follows.

 
To change the graph change the data set coming from the controller.

That brings us to the end of this tutorial. We round off with some of the improvements possible.

Possible Improvements

1. Update the script to be able to bind to any Json object.
2. Use jQuery plugin syntax so that more than one helper can be created per page.
3. Allow more flexibility like passing parameters for bar colors, size of chart etc.
4. Allow multiple data sources to show comparison side by side.
5. Add more chart types like Pie etc.

Conclusion

Though they sound esoteric HtmlHelper extensions is a rather simple mechanism to inject rich functionality in a componentized way in ASP.NET MVC applications. We converted an existing HTML5 chart, originally created using plain HTML5 and JavaScript into a Chart HtmlHelper with very little code. For large projects, HtmlHelpers are a neat way to encapsulate small pieces of re-usable UI functionality
       

 



ASP.NET 4.5 Hosting :: Working with Asynchronous Operations in ASP.NET 4.5 Web Forms

clock September 4, 2012 06:28 by author Administrator

 

Introduction

Asynchronously running code can improve the overall performance and responsiveness of your web application. In ASP.NET 4.5 web forms applications you can register asynchronous methods with the page framework. The ASP.NET page framework and .NET 4.5 asynchronous programming supports then executes the operations in asynchronous fashion. This article shows how this can be done.

NOTE: This article discusses how asynchronous operations can be used in ASP.NET web forms applications. Read Working with Asynchronous Operations in ASP.NET MVC to learn how asynchronous operations can be programed in ASP.NET MVC applications.

If you are looking to host your ASP.NET 4.5 website, you can check out ASPHostCentral.com

 


Example Scenario

Consider that you have a web application that needs to call two ASP.NET Web API services namely Customer and Product. These services return Customer and Product data from the Northwind database respectively. Now, assume that each of these services take 5 seconds to complete the data retrieval operation. If you use synchronous mode for calling these services then the total time taken will be 10 seconds. Because the execution will happen sequentially - first Customer service will complete and then Product service will complete.

On the other hand if you invoke these services in asynchronous fashion, the service operations won't block the caller thread. The Customer service will be invoked and control will be immediately returned to the caller. The caller thread will then proceed to invoke the Product service. So, two operations will be invoked in parallel. In this case the total time taken for completing both of the operations will be the time taken by the longest of the operations (5 seconds in this case).

Async, Await, Task and RegisterAsyncTask

Before developing web forms applications that execute asynchronous operations you need to understand a few basic terms involved in the process.

A task is an operation that is to be executed in asynchronous fashion. Such an operation is programmatically represented by the Task class from System.Threading.Tasks namespace.

When an asynchronous operation begins, the caller thread can continue its work further. However, the caller thread must wait at some point of time for the asynchronous operation to complete. The await keyword invokes an asynchronous operation and waits for it to complete.

The async modifier is applied to a method that is to be invoked asynchronously. Such an asynchronous method typically returns a Task object and has at least one await call inside it.

Just to understand how async, await and task are used at code level, consider the following piece of code:

public async Task<MyObject> MyMethodAsync()
{
  MyObject data = await service.GetDataAsync();
  //other operations on data go here
  return data;
}

Here, method MyMethodAsync() is marked with async modifier. By convention, asynchronous method names end with "Async". The MyMethodAsync() returns MyObject wrapped inside a Task instance. Inside the method a remote service is invoked using GetDataAsync(). Since MyMethodAsync() needs to return data retrieved from the service, the await keyword is used to wait till the GetDataAsync() method returns. Once GetDataAsync() returns the execution is resumed and further code is executed. The data is finally returned to the caller.

NOTE:
For a detailed understanding of async, await and Task refer to MSDN dicumentation. Here, these terms are discussed only for giving a basic understanding of the respective keywords.

ASP.NET page framework provides a method - RegisterAsyncTask() - that registers an asynchronous task with the page framework. Tasks registered using the RegisterAsyncTask() method are invoked immediately after the PreRender event. The RegisterAsyncTask() method takes a parameter of type PageAsyncTask. The PageAsyncTask object wraps the information about an asynchronous task registered with a page. The following piece of code shows how they are used:

protected void Page_Load(object sender, EventArgs e)
{
   PageAsyncTask task = new PageAsyncTask(MyMethod);
   RegisterAsyncTask(task);
}

Asynchronous Solution

Now that you are familiar with the basic concepts involved in utilizing asynchronous operations in a web forms application, let's create a sample application that puts this knowledge to use.

Begin by creating two projects - an empty web forms application and an ASP.NET MVC4 Web API application.

Add an Entity Framework Data Model for the Customers and Products tables of the Northwind database. Place the EF data model inside the Models folder.



Add an Entity Framework Data Model for the Customers and Products tables

Add two ApiController classes to the Web API project and name them as CustomerController and ProductController.



Add two ApiController classes

Then add Get() methods to both the ApiController classes as shown below:

public class CustomerController : ApiController
{
    public IEnumerable<Customer> Get()
    {
        Northwind db = new Northwind();
        var data = from item in db.Customers
                    select item;
        System.Threading.Thread.Sleep(5000);
        return data;
    }
}

public class ProductController : ApiController
{
    public IEnumerable<Product> Get()
    {
        Northwind db = new Northwind();
        var data = from item in db.Products
                    select item;
        System.Threading.Thread.Sleep(5000);
        return data;
    }
}

The Get() method of the CustomerController class selects all the Customer records from the Customers table whereas the Get() method of the ProductController class selects all the Product records. For the sake of testing, a delay of 5 seconds is introduced in each Get() method. The Get() methods return an IEnumerable collection of Customer and Product objects respectively.

Now, go to the web forms project and open the code behind file of the default web form. Here, you will write a couple of private methods that invoke the Web API developed previously. These methods are shown below:

public async Task<List<Customer>> InvokeCustomerService()
{
    using (HttpClient client = new HttpClient())
    {
        HttpResponseMessage response = await client.GetAsync("http://localhost:49187/api/customer");
        string json= (await response.Content.ReadAsStringAsync());
        List<Customer> data = JsonConvert.DeserializeObject<List<Customer>>(json);
        return data;
    }
}

public async Task<List<Product>> InvokeProductService()
{
    using (HttpClient client = new HttpClient())
    {
        HttpResponseMessage response = await client.GetAsync("http://localhost:49187/api/product");
        string json = (await response.Content.ReadAsStringAsync());
        List<Product> data = JsonConvert.DeserializeObject<List<Product>>(json);
        return data;
    }
}

The InvokeCustomerService() method invokes the Customer Web API whereas InvokeProductService() method invokes Product Web API. Both the methods essentially use an HttpClient to get data from the respective Web API. Notice that both the methods have async modifier and return a Task instance that wraps the actual return type (List<Customer> and List<Product> respectively). The GetAsync() method of the HttpClient object is an asynchronous method. Call to the GetAsync() is marked using the await keyword so that further statements are executed only when GetAsync() returns. The GetAsync() method accepts a URL of the respective Web API. Make sure to change the port number as per your development setup. The GetAsync() method returns an HttpResponseMessage object. The actual data is then retrieved using ReadAsStringAsync() method of the Content property. The ReadAsStringAsync() will return data as a JSON string. This JSON data is converted into a .NET generic List using DeserializeObject() method of the JsonConvert class. The JsonConvert class comes from the Json.NET open source componenet. You can download Json.NET here.

The InvokeCustomerService() and InvokeProductService() methods are called inside another private method GetDataFromServicesAsync() as shown below:

private async Task GetDataFromServicesAsync()
{
    Stopwatch stopWatch = new Stopwatch();
    stopWatch.Start();
    var task1 = InvokeCustomerService();
    var task2 = InvokeProductService();
    await Task.WhenAll(task1, task2);

    List<Customer> data1 = task1.Result;
    List<Product> data2 = task2.Result;           

    stopWatch.Stop();
    Label2.Text = string.Format("<h2>Retrieved {0} customers and {1} products in {2} seconds.</h2>",                                  data1.Count, data2.Count, stopWatch.Elapsed.TotalSeconds);
}

As shown above, GetDataFromServicesAsync() is also marked as async and returns a Task instance. Inside, a StopWatch class from System.Diagnostics namespace is used to find the time taken by both of the operations to complete. InvokeCustomerService() and InvokeProductService() methods are then called. The returned Task instance is stored in task1 and task2 variables respectively. The WhenAll() method of Task class creates another Task that completes when all the specified tasks are complete. In this case it creates a Task that completes after complition of task1 and task2. Actual data returned by the respective Web API is retrieved using the Result property of the respective Task objects. The time taken to complete the operation is measured by the StopWatch and is displayed in a Label.

The next step is to register GetDataFromServicesAsync() with the page framework. This is done using the RegisterAsyncTask() method as shown below:

protected void Page_Load(object sender, EventArgs e)
{
    RegisterAsyncTask(new PageAsyncTask(GetDataFromServicesAsync));
}

As you can see, Page_Load event handler registers an asynchronous task using RegisterAsyncTask() method. The RegisterAsyncTask() method accepts an instance of PageAsyncTask. The PageAsyncTask instance in turn wraps the GetDataFromServicesAsync() method created earlier.

The final step is to set Async attribute of the @Page directive to true:

<%@ Page Async="true" Language="C#" CodeBehind="WebForm1.aspx.cs" ... %>

The Aync attribute of the @Page directive indicates that this web form will be executed in asynchronous fashion. Web forms that use RegisterAsyncTask() method must set the Async attribute to true, otherwise an exception is raised at runtime.

This completes the application and you can test it by running the web forms application. The following figure shows a sample run of the web form:

 
A sample run of the web form

Though the code doesn't show the synchronous execution of the Web API operations, for the sake of better understanding the above figure shows time taken for synchronous as well as asynchronous execution. Recollect that both the Get() methods sleep for 5 seconds and hence the synchronous execution takes approximately 10 seconds. However, the asynchronous execution takes approximately 5 seconds. As you can see the asynchronous operation improves the overall performance of the application.

Summary

Using async and await keywords you can create operations that run asynchronously. Such asynchronous tasks can be registered with the page framework using RegisterAsyncTask() method. Registered tasks run immediately after the PreRender event of the web form. Asynchronous operations can improve the overall performance and user responsiveness of a web application.



ASPHostCentral.com - Windows Server 2012 Hosting

clock August 30, 2012 08:23 by author Administrator


ASPHostCentral.com
 proudly supports the latest Windows Server 2012 on all our newest servers. You can certainly run and deploy your project on our highly-secured Windows Server 2012 environment instantly! 


Windows Server 2012 Essentials 

An ideal server for small businesses, Windows Server 2012 Essentials (formerly known as Windows Small Business Server Essentials) provides a powerful and flexible solution that helps protect your business data while allowing you to access the information you need from virtually anywhere using almost any device. Windows Server 2012 Essentials supports the applications you need to run your business and also helps you to quickly connect to additional cloud-based applications and services to extend your server’s functionality. 

Benefits 

Small organizations want to focus on their core business, not on managing an IT infrastructure. Windows Server 2012 Essentials can help to minimize the time, effort, and money that you spend on IT. 

Windows Server 2012 Essentials provides you and your employees highly secure access to your company’s data and applications so that you can be productive—even when you’re not in the office—and offers you the flexibility to make technology decisions based on your individual business needs. 

With Windows Server 2012 Essentials, you can: 

- Protect and secure your business. The server’s intuitive user experience and powerful data protection features, such as full client PC backup, can simplify your life and help you focus on your core business.
- Access your resources from virtually everywhere using almost any device. Empower your remote workforce with the freedom to work where and when they choose with an Internet connection and web browser.
- Leverage the power and flexibility of cloud-based services on your terms. Windows Server 2012 Essentials helps you run your business operations, be more efficient, and enjoy competitive advantages by making it easier than ever to use and manage cloud-based applications and services, on-premise applications, or a combination of both. 



SQL 2012 Hosting with ASPHostCentral.com

clock June 7, 2012 06:57 by author Administrator

ASPHostCentral.com offers the latest SQL Server 2012 database to all our new and existing customers.

You can always start with our
Standard Plan (from @$4.49/month) to have your SQL 2012 database hosted on our environment. Should your requirement changes in the future, you can always request for an upgrade without causing any downtime. Remember, everything is just one-click away from your mouse! So, why wait longer? Please register your interest here.

Microsoft SQL Server 2012?

This latest release of the SQL Server presents new features and improvements that increase the power and efficiency of architects, developers, and administrators who design, develop, and maintain data storage systems

Features of SQL Server 2012 Hosting

SQL Server 2012 delivers several primary benefits:          

Always-On Availability Groups (AAG) - As for some Exchange administrators this feature is very similar to Database Availability Groups (DAG) in Exchange 2010. Configuring SQL 2012 AlwaysOn Availability Groups involves creating and constructing one or more availability groups. An availability group is a global container that defines a set user DBs (availability databases) to fail-over in case of disaster, and a set of database replicas to host multiple copies of each DB. An each group requires at least two replicas exist: the primary replica and one secondary replica.

Always-On SQL Failover Cluster
Failover clusters across subnets - A SQL Server multisubnet failover cluster is a design where all failover cluster node is connected to a different networks or different set of networks. These networks can be in the same physical location or in phsicallydispersed . Clustering across global sites is sometimes referred to as Stretch-clusters. As there is no need for shared storage that all the nodes can access, data should be replicated among the data storage on the multiple networks. With data replication, there is further than one copy of the data available. Therefore, a multi-subnet failover cluster offers a disaster recovery solution in addition to HA

Flexible policy for cluster health detection - In a SQL Server failover-cluster instance, only one node can own the cluster which is sometimes known as a single copy cluster. The client demands are served through this primary node for that failover cluster instance. In the case of a hardware failure, the group ownership is moved to another node in the failover cluster node. In this case the process is called failovering over a cluster

Indirect checkpoints - This new feature offers a database-specific substitute to automatic checkpoints, which are shaped by a server property. An indirect checkpoint implements a new checkpointing formula for the DB Engine. This offers a more accurate assurance of database recovery time in DR event or a failover than is provided by automatic-checkpoints. To guarantee that database recovery does not top allowable downtime for a given db, you can stipulate the maximum acceptable downtime for that database

Our Special SQL 2012 Hosting Complete Features


New Customer - You can start from as low as $4.49/month to start hosting your SQL 2012 on our environment. If you do not have a domain name, please do not worry as we will give you one FREE domain name (worth $14.99/year) if you register for any of our hosting plans for 12 months service(*). We will do our best to help you create your first web presence on the internet and we will continuously support the growth of your business.

Existing Customer - For all existing customers, a migration to a server that supports SQL 2012 is required and hence, a migration and setup fee apply. Starting from 15th April 2012, we have offered the latest SQL Server 2012 version and for clients who registered before this date is required to pay this setup fee. Thank you.


 



.NET MVC 4 Hosting :: New Things to Learn in ASP.NET MVC 4

clock March 28, 2012 06:59 by author Administrator

Introduction

MVC4 is really trying to break new ground in helping developers get to market more quickly and with a product that adheres to the emerging standards of today. A tough thing to ask of any technology, to be sure, but it's making some decent strides in the right direction.

Already the tutorials and blogs posts are popping up quicker than mushrooms on the midden heap. We highlight a few here that you definitely shouldn't miss which deal with key upcoming features...

ASP.NET MVC  4 Hosting

If you are looking for a QUALITY, AFFORDABLE host that supports
ASP.NET MVC 4 Hosting, you can take a look at ASPHostCentral.com

ASP.NET MVC 4 Overview - Part 2

Jon Galloway goes into some significant detail here about some of the changes coming our way in the new version. He talks about the new default templates that come out of the box and the reasoning behind them.

He also talks about the new adaptive rendering taking advantage of CSS media queries and the usage of the viewport meta tag to help improve the mobile user experience. Overall a solid post that will stand the test of time. Check it out...


 

ASP.NET MVC 4 Bundling and Minification

Bundling and Minification of assets have to be two of the most tedious things to setup on a new web project. In this excellent post, David Hayden goes through exactly what you need to do to make the process as seamless as possible in MVC4.

Don't make the mistake of leaving this to the end of the project. You'll have deployment nightmares you didn't dream of and you'll be kicking yourself for not smoothing out the wrinkles. Do it early, and you'll thank yourself everyday for that small mercy...


Micro ORM Data Mapping with PetaPoco and ASP.NET MVC 4

Getting tired of working with the verbosity of Entity Framework classes and mapping? Well, you're not the only one, and in this quality post, Greg Arroyo takes us for a lap around the track using PetaPoco as your Micro ORM in MVC4.

Micro ORMs really are here to stay, and in some ways, more broadly applicable to web applications of today where everyone is trying to keep things more simple. If you haven't tried one yet, take this opportunity to get clued up on these fantastic tools.


ASP.NET MVC 4 Web API Routes and ApiController

Once again David Hayden masterfully takes us through a key piece of architecture that is going to be very important to anyone who will be working with MVC4. He details what seems to be a very slick piece of integration work between the new Web API framework and MVC4, and he throws in some OData queries for good measure.

It's short and sweet, and just enough to get you going, and whet your appetite for how to architect your solutions around your own APIs, allowing for more decoupled designs with less possible points of failure.


Getting started on your first Single Page Application

As with the introduction of any new method now encompassed in a technology, it's best to start with what comes straight from the horse's mouth. This Walkthrough put together by Brad Severtson gives you a great introduction, and leaves the mind boggling as to the possibilities.

If you've ever wanted to build your own Gmail and specifically wanted to do it with MVC, then go ahead, knock yourself out! (no pun intended)..

 



.NET MVC 4.0 BETA Hosting FREE Account is now available at ASPHostCentral.com

clock March 15, 2012 07:33 by author Administrator

ASPHostCentral.com, the leader in ASP.NET and Windows Hosting Provider, proudly announces that we have supported the latest ASP.NET MVC 4.0 BETA Hosting.   

To support Microsoft ASP.NET MVC 4.0 BETA Framework, we gladly inform you that we provide this beta account FREE of charge for a limited time (* terms and conditions apply). 



New Features in ASP.NET MVC 4


This section describes features that have been introduced in the ASP.NET MVC 4: 
- Enhancements to Default Project Templates
- Better Support for Mobile Project Template
- Enhancement in Display Modes
- Mobile Project Template support for VB.NET
- Dependency Injection Improvements    

Terms and Conditions in Using this ASP.NET MVC 4.0 BETA Account
 

The followings are the features you will get under this FREE ASP.NET MVC 4.0 BETA Account: 
- ASP.NET MVC 4.0 Beta Framework
- 1 Website/Domain
- 100 MB disk space
- 100 MB bandwidth
- 50 MB SQL 2008 space
- 24/7 FTP access
- Windows Server 2008 Platform

If you want to participate in this BETA program, there are several rules you need to understand: 

- As this is a beta version, not all the features are available. They may be some issues on this beta framework, which will be fixed upon the full release of ASP.NET MVC 4.0 Framework

 

- ASPHostCentral.com does not guarantee the uptime of the sandbox solution. Additionally, we do not keep/store any backup of your files/accounts

- ASPHostCentral.com does not guarantee rapid response to any inquiries raised by a user

- This free account is only meant for testing. Users should not use it to store a production, personal, e-commerce or any blog-related site

- This free account is used to host any ASP.NET MVC 4.0 beta website only. Any questions that are not related to ASP.NET MVC 4.0 BETA will not be responded. A user shall not host any non-ASP.NET MVC 4.0 site on this free account either

- ASPHostCentral.com reserves full rights to terminate this beta program at any time. We will provide a notification on our Help Desk System prior to the termination of this program

- ASPHostCentral.com reserves full rights to terminate a user account, in which we suspect that there is an abuse to our system

- Once this beta program is terminated, your account will be completely wiped/remove from our system.

- This offer expires on 31st May 2012

If you wish to participate in this FREE ASP.NET MVC 4.0 BETA Program, you must register via https://secure.asphostcentral.com/BetaOrder.aspx


 

 



.NET 4.5 Beta FREE Hosting with ASPHostCentral.com

clock March 14, 2012 08:40 by author Administrator

ASPHostCentral.com, the leader in ASP.NET and Windows Hosting Provider, proudly announces that we will support ASP.NET 4.5 Hosting.

To support Microsoft ASP.NET 4.5 Beta Framework, we gladly inform you that we provide this beta account FREE of charge for a limited time (* terms and conditions apply).


The followings are the features you will get under this FREE ASP.NET 4.5 BETA Account:                

- .NET 4.5 Beta Framework
- 1 Website/Domain
- 100 MB disk space
- 100 MB bandwidth
- 50 MB SQL 2008 space
- 24/7 FTP access
- Windows Server 2008 Platform

 If you want to participate in this Beta program, there are several rules you need to understand:              

- As this is a beta version, not all the features are available. They may be some issues on this beta framework, which will be fixed upon the full release of ASP.NET 4.5 Framework
- ASPHostCentral.com does not guarantee the uptime of the sandbox solution. Additionally, we do not keep/store any backup of your files/accounts
- ASPHostCentral.com does not guarantee rapid response to any inquiries raised by a user
- This free account is only meant for testing. Users should not use it to store a production, personal, e-commerce or any blog-related site
- This free account is used to host any ASP.NET 4.5 beta website only. Any questions that are not related to ASP.NET 4.5 beta will not be responded. A user shall not host any non-ASP.NET 4.5 site on this free account either
- ASPHostCentral.com reserves full rights to terminate this beta program at any time. We will provide a notification on our Help Desk System prior to the termination of this program
- ASPHostCentral.com reserves full rights to terminate a user account, in which we suspect that there is an abuse to our system
- Once this beta program is terminated, your account will be completely wiped/remove from our system.
- For details, please check
http://www.asphostcentral.com/ASPNET-45-Beta-Hosting.aspx
- This offer expires on 31st May 2012

If you want to participate on this FREE ASP.NET 4.5 Beta Program, you must register via https://secure.asphostcentral.com/BetaOrder.aspx

 



ASP.NET 4.5 Hosting :: ASP.NET 4.5 Strongly Typed Data Controls & Model Binding

clock March 8, 2012 07:43 by author Administrator

One pain point that’s dogged WebForm developers for some time is the fact that there haven’t been any strongly typed data controls.  Some of the data controls I’m speaking of include the Repeater, FormView and GridView controls.  They all used templates, which could allow you to specify a view for different operations, such as when you’re editing data compared to adding new data.

When you use these templates today, they’re using late bound expressions to bind the data.  If you’re using the GridView control, or any of the other data controls, you’ll be familiar with the Bind or Eval syntax:

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
      <Columns>
           <asp:TemplateField HeaderText="Name">
                    <ItemTemplate>
                        <asp:Label ID="lblName" runat="server" Text='<%# Bind("Name") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="City">
                     <ItemTemplate>
                        <asp:Label ID="lblCity" runat="server" Text='<%# Bind("Address.City") %>'></asp:Label>
                     </ItemTemplate>
                </asp:TemplateField>
      </Columns>
 </asp:GridView>


One of the problems with late-bound data controls is you’re using a string to represent a property name.  If you make a mistake typing the name, you won’t see the exception until runtime.  It’s much better to catch these errors at compile time.  Thankfully Microsoft has addressed this in ASP.NET 4.5 by implementing strongly typed data controls.

Installation

Before starting any development, you’ll need to install ASP.NET 4.5.  The simplest way to do this is via the Web Platform Installer.  All of the ASP.NET 4.5 articles I’m authoring are developed in Visual Studio 2011 Developer Preview. Here’s the link to get started.

Strongly Typed Data Controls

ASP.NET 4.5 introduces strongly typed data controls in the templates.  A new ModelType property has been added to the data controls, and this allows you to specify the type of object that is bound to the control.

Setting this property will add that type to the data controls Intellisense (an autocomplete function), which means no more typing mistakes!  This removes the need to run the website to see if you’ve made any typing mistakes during development.

In this example, I’ve connected to a Northwind web service.  Using ASP.NET 4.5, I can set the ModelType to Northwind.  If the requirement is for one-way data binding, you can use the Item expression.  Bind("Name") becomes Item.Name.  The same goes for the City property.  Replace Bind("Address.City") with Item.Address.City.

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"            ModelType="WebApplication2.NorthwindService.Supplier">
        <Columns>
            <asp:TemplateField HeaderText="Name">
                <ItemTemplate>
                    <asp:Label ID="lblName" runat="server" Text='<%# Item.Name %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="City">
                <ItemTemplate>
                    <asp:Label ID="lblCity" runat="server" Text='<%# Item.Address.City %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>


For two-way data binding, use Binditem.  So using the example above, data binding to a text box would be like this:

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"            ModelType="WebApplication2.NorthwindService.Supplier">
        <Columns>
            <asp:TemplateField HeaderText="Name">
                <ItemTemplate>
                    <asp:TextBox ID="txtName" runat="server" Text='<%# Binditem.Name %>'></asp:TextBox>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="City">
                <ItemTemplate>
                    <asp:TextBox ID="txtCity" runat="server" Text='<%# Binditem.Address.City %>'></asp:TextBox>
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>

    </asp:GridView>

Intellisense is available, so there’ll be no more mistyped properties you only find out about at runtime.

Model Binding

Model binding focuses on coded data access logic.  Previously if you wanted to display data in the GridView control, you either had to explicitly set the DataSource property and call its DataBind method from the code behind.  Like this example:

protected void Page_Load(object sender, EventArgs e)
{
     var products = GetProducts();
     GridView1.DataSource = products;
     GridView1.DataBind();
}

Alternatively you could use one of the many data source controls to bind the data to the GridView.  Now that model binding is part of ASP.NET, you can explicitly tell the GridView which method to call to retrieve its data by using the SelectMethod property.  Here’s the updated GridView.

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"            ModelType="WebApplication2.NorthwindService.Supplier"
            SelectMethod="GetProducts">
        <Columns>
            <asp:TemplateField HeaderText="Name">
                <ItemTemplate>
                    <asp:Label ID="lblName" runat="server" Text='<%# Item.Name %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="City">
                <ItemTemplate>
                    <asp:Label ID="lblCity" runat="server" Text='<%# Item.Address.City %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>


And in the code behind, here’s the GetProducts method:

public IQueryable<NorthwindService.Supplier> GetProducts()
{
    var service = new NorthwindService.DemoService(new Uri(@"http://services.odata.org/OData/OData.svc/"));
    var suppliers = (from p in service.Suppliers
                             select p);
    return suppliers;
}


This method doesn’t need to be in the code behind. It could live in another class or assembly.  The benefit of returning IQueryable  is that it enables deferred execution on the query, and allows a data-bound control to further modify the query before executing it.  This is useful when you need to implement sorting and paging methods.

I’m excited by the model binding and strongly bound data controls in ASP.NET 4.5.  It has certainly borrowed these ideas and concepts from MVC, so fingers crossed more of them are implemented in upcoming versions



ASP.NET Hosting :: Working with ASP.NET Cookies

clock January 31, 2012 09:53 by author Administrator

 

 

Introduction

Cookies are also known by many names, HTTP Cookie, Web Cookie, Browser Cookie, Session Cookie, etc. Cookies are one of several ways to store data about web site visitors during the time when web server and browser are not connected. Common use of cookies is to remember users between visits. Practically, cookie is a small text file sent by web server and saved by web browser on client machine.

Use of Cookies?

Cookies may be used for authentication, identification of a user session, user's preferences, shopping cart contents, or anything else that can be accomplished through storing text data. Cookies can also be used for travelling of data from one page to another.

Is Cookies Secured?

Well, this question has no specific answers in YES or NO. Cookies could be stolen by hackers to gain access to a victim's web account. Even cookies are not software and they cannot be programmed like normal executable applications. Cookies cannot carry viruses and cannot install malware on the host computer. However, they can be used by spyware to track user's browsing activities.

Using Cookies

Creating/Writing Cookies

There are many ways to create cookies, I am going to outline some of them below:

Way 1 (by using HttpCookies class)
//First Way
HttpCookie StudentCookies = new HttpCookie("StudentCookies");
StudentCookies.Value = TextBox1.Text;
StudentCookies.Expires = DateTime.Now.AddHours(1);
Response.Cookies.Add(StudentCookies);

Way 2 (by using Response directly)
//Second Way
Response.Cookies["StudentCookies"].Value = TextBox1.Text;
Response.Cookies["StudentCookies"].Expires = DateTime.Now.AddDays(1);


Way 3 (multiple values in same cookie)
//Writing Multiple values in single cookie
Response.Cookies["StudentCookies"]["RollNumber"] = TextBox1.Text;
Response.Cookies["StudentCookies"]["FirstName"] = "Abhimanyu";
Response.Cookies["StudentCookies"]["MiddleName"] = "Kumar";
Response.Cookies["StudentCookies"]["LastName"] = "Vatsa";
Response.Cookies["StudentCookies"]["TotalMarks"] = "499";
Response.Cookies["StudentCookies"].Expires = DateTime.Now.AddDays(1);


Reading/Getting Cookies

In the above code, I have used many ways to write or create cookies so I need to write here using all the above ways separately.

For Way 1
string roll = Request.Cookies["StudentCookies"].Value; //For First Way

For Way 2
string roll = Request.Cookies["StudentCookies"].Value;  //For Second Way

For Way 3
//For Multiple values in single cookie
string roll;
roll = Request.Cookies["StudentCookies"]["RollNumber"];
roll = roll + " " + Request.Cookies["StudentCookies"]["FirstName"];
roll = roll + " " + Request.Cookies["StudentCookies"]["MiddleName"];
roll = roll + " " + Request.Cookies["StudentCookies"]["LastName"];
roll = roll + " " + Request.Cookies["StudentCookies"]["TotalMarks"];
Label1.Text = roll;


Deleting Cookies

In the above code, I have used many ways to create or read cookies. Now look at the code given below which will delete cookies.

if (Request.Cookies["StudentCookies"] != null)
{
    Response.Cookies["StudentCookies"].Expires = DateTime.Now.AddDays(-1);    Response.Redirect("Result.aspx");  //to refresh the page
}


Understanding HttpCookie Class It contains a collection of all cookie values.

We do not need to use any extra namespaces for HttpCookies class (we already have used this in Way 1 above), because this class is derived from System.Web namespaces. HttpCookies class lets us work with cookies without using Response and Request objects (we have already used this in Way 2 and Way 3 above).

HttpCookie class has a list of some properties, let us outline them.

    * Domain: It contains the domain of the cookie.
    * Expires: It contains the expiration time of the cookie.
    * HasKeys: It contains True if the cookie has subkeys.
    * Name: It contains the name of the cookie.
    * Path: It contains the virtual path to submit with the cookie.
    * Secure: It contains True if the cookie is to be passed in a secure connection only.
    * Value: It contains the value of the cookie.
    * Values:

Limitations of Cookies

There are following limitations for cookies:
   1. Size of cookies is limited to 4096 bytes.
   2. Total 20 cookies can be used on a single website; if you exceed this browser will delete older cookies.
   3. End user can stop accepting cookies by browsers, so it is recommended to check the users’ state and prompt the user to enable cookies.

Sometimes, the end user disables the cookies on browser and sometimes browser has no such feature to accept cookies. In such cases, you need to check the users’ browser at the home page of website and display the appropriate message or redirect on appropriate page having such message to enable it first. The following code will check whether the users’ browser supports cookies or not. It will also detect if it is disabled too.

protected void Page_Load(object sender, EventArgs e)
{
    if (Request.Browser.Cookies)
    {
        //supports the cookies
    }
    else
    {
        //not supports the cookies
        //redirect user on specific page
        //for this or show messages
    }
}


It is always recommended not to store sensitive information in cookies

 

 

 



ASP.NET 4.5 Hosting :: Model Binding Feature in ASP.NET 4.5

clock November 28, 2011 10:05 by author Administrator

The Good News - In ASP.NET 4.5, we can adopt an approach using which the Model can be directly bound with the DataBound controls and CRUD and pagination operations can be implemented very effectively. It incorporates concepts from the ObjectDataSource control and from model binding in ASP.NET MVC. We will see this shortly. ASP.NET 4.5 is based upon .NET 4.5 and it gets installed once you install Visual Studio 2011 preview. 

Note: If you want to install Visual Studio 2011 preview, you can also use the Windows 8 Developer preview.

In this article I will be explaining a new ASP.NET 4.5 exciting feature called ‘Model Binding with Web Forms’. Up to previous versions, webforms for data-binding used to make use of the ‘Eval’ method. During runtime, calls to Eval makes use of reflection against the currently bound data object and reads value of the member with the given name in Eval method. (Read Why Eval is Evil). Once this value is read the result is displayed in HTML. Although this is easiest way of data-binding, it has limitations like checking the binding name during compilation time etc.

Update: Also check out the second part of this article ASP.NET 4.5: Filtering using Model Binding in ASP.NET Web Forms

In ASP.NET 4.5 the Model Binding has improved. We will be going through the complete model binding feature using the following steps:

- Model binding with Web Forms.
- Value Providers.
- Filtering.
- Performing Update Operations.

For this article I am using Sql Server 2008 R2 and a ‘Company’ database, with following Tables:

Department - DeptNo (int) Primary Key, Dname (varchar(50)),Location (varchar(50)).
Employee - EmpNo (int) Primary Key, EmpName (varchar(50)),Salary (int), DeptNo(int) Forwign Key.

Let’s get started.

Step 1: Open Visual Studio 2011 Developer Preview and create a new Web Application, make sure that the Framework version you select is .NET 4.5. Call this application ‘ASPNET45_ModelBinding’.

Step 2: In this project, add new folders and name them as Model and Department. In the Department folder, add two Web Forms (with master page). Name them as ‘Departments.aspx’ and ‘DepartmentDetails.aspx’.

Step 3: In the Model folder, add a new ADO.NET entity data model and name it as ‘CompanyEDMX.edmx’. In the Wizard, select Company Database and select Department and Employee table. After the completion of wizard, the below result will be displayed:


Step 4: Open the Departments.aspx in the ‘Source’ view and add the Repeater control in it with the Department model bound to it as below.

The above code shows some modified databound features for DataBound controls in ASP.NET 4.5. The Department Model is assigned to the ‘ModelType’ property of the repeater. This property is available to all DataBound controls. This allows us to define the type of data that is bound to the control and also allows to bind properties of the Model inside the control. The above code defines ‘ItemTemplate’ inside the repeater control which refers to the ‘DepartmentDetails.aspx’ by passing DeptNo value using QueryString to it.


Step 5: Go to the Departments.aspx.cs code behind, and write the following code:

The above code sets the datasource property for the repeater control.


Step 6: View the Departments.aspx inside the browser and the following result will be displayed:  
In your OS, observe the lower right corner of the System Tray. Instead of the ASP.NET Development server, ASP.NET 4.5 uses IIS Express as shown below:  





Step 7
: In Step 4, we added the repeater control which has the ItemsTemplate and contains an <a href=””> to navigate to DepartmentDetails.aspx using a query string. This page is designed for displaying details of a particular Department. Open DepartmentDetails.aspx in the ‘Source’ view and add a DetailsView web UI databound control inside it. As explained Step 4, we need to assign the ModelType property of this control to ‘Department’ model.

All those who have used controls like DetailsView or FormView knows that these control are used for performing DML operations. Now to perform DML operations in earlier versions of ASP.NET i.e. from 2.0 to 4.0 we used to make use of ObjectDataProvider and this provider was usually configured using Get,Insert,Update and Delete methods form the source object. However the ASP.NET 4.5 DataBound controls e.g. GridView, FormView, DetailsView etc, exposes the following properties:

- SelectMethod: Used to make call to a method which returns IEnumarable.
- InsertMethod: Used to make call to a method which performs Insert operation.
- UpdateMethod: Used to make call to a method which performs Update operation.
- DeleteMethod: Used to make call to a method which performs Delete operation.

Configure the DepartmentDetails.aspx as shown below:


Step 8: Open the DepartmentDetails.aspx.cs and add the following code in it:    


Now carefully have a look at the above methods. None of these methods make use of any of the UI controls in the user interface. All these methods strictly work on Model objects and this feature drastically reduces additional coding. One more important fact is, if you observe the ‘GetDepartment()’ method, it has defined the ‘DeptNo’ input parameter with the QueryString Value provider. This automatically reads the DeptNo in the QueryString and displays the Department details inside the DetailsView.

Note: In previous versions of ASP.NET we could have done this using Request.QueryString[“DeptNo”]

Step 9: Now open Site.Master and add the following menu item:

<asp:MenuItem NavigateUrl="~/Department/Departments.aspx" Text="Departments"/>

Step 10: Make Default.aspx as a startup page and run the application. You will see the Default.aspx with Department and Employee menu. Once you click on ‘Department’ menu, Departments.aspx will be displayed. Now click on any Department and you will be transferred to ‘DepartmentDetails.aspx’ as below:

The QueryString has the DeptNo and based upon the value of the DeptNo, the DetailsView will display the  Department details. Here you can now test the Update and New (insert) functionality.

Check out the second part of this article ASP.NET 4.5: Filtering using Model Binding in ASP.NET Web Forms

Conclusion: The Model binding feature provides facility to the developers to develop Webforms which can be independent from the Model

 

 

 

 

 

 

 

 



ASP.NET 4.0 & ASP.NET 4.5 Hosting

 

ASPHostCentral is a premier web hosting company where you will find low cost and reliable web hosting. We have supported the latest ASP.NET 4.5 hosting and ASP.NET MVC 4 hosting. We have supported the latest SQL Server 2012 Hosting and Windows Server 2012 Hosting too!

 

Calendar

<<  April 2024  >>
MoTuWeThFrSaSu
25262728293031
1234567
891011121314
15161718192021
22232425262728
293012345

View posts in large calendar

Sign in