ASP.NET 4.5 Hosting BLOG

Tutorial and Articles about ASP.NET 4.0 and the latest ASP.NET 4.5 Hosting

ASP.NET MVC SignalR Hosting - ASPHostPortal.com :: Create a Real-Time Message Board Making use of ASP.Net MVC 5, SignalR 2, and KnockoutJS

clock October 28, 2014 06:05 by author Ben

Have you ever questioned how Facebook sends you notifications the instant you receive a new information, friend request, or remark? Does the customer constantly look for new events? Doesn’t that consume a whole lot of memory within the user’s side? What sort of pressure does that place on Facebook’s servers?


 

Due to HTMl five as well as the support of web sockets in modern browsers, this performance can be achieved with out over-taxing the user or even the server. Leveraging a library like SignalR for .NET or Socket.IO for Node.js, most of the very hard perform around working with web sockets is already completed to suit your needs.

On this tutorial, we’re planning to build a real-time concept board, very similar to Facebook. Although this will not be something you should model and drive to manufacturing as-is, it could supply you with the fundamental groundwork for creating your own personal real-time net application.

Let's Start

Start the Project - Initial, begin a new ASP.Net MVC 5 project from Visual Studio 2013. You can title it what ever you want, but I named the undertaking “MessageBoardTutorial”. Make sure you place a checkmark close to "Web API".


Get dependencies with NuGet - Let’s go on and get downloading our required libraries out of the best way. We can get every thing with NuGet, saving us plenty of your time. Within the Remedy Explorer, right-click around the project name and click on “Manage NuGet Packages…” from the context menu.

Initial, you'll want to update all the packages presently set up to their newest variations. Be aware that because MVC 4, all the MVC libraries are bin deployed, so you will need to update them when commencing a fresh undertaking. On the still left, simply click on “Updates->nuget.org” and also you will see each of the offers that must be up-to-date. Just click on on “Update All” and allow NuGet do its thing.


When that's done, near the window. Open up the Package Supervisor Console in Tools > NuGet Package Manager > Package Manager Console. We must set up a few a lot more deals for this tutorial. Run the subsequent commands to set up the deals we need for this tutorial.

PM> Install-Package EntityFramework
PM> Install-Package Microsoft.AspNet.SignalR
PM> Install-Package Moment.js
PM> Install-Package KnockoutJS

NuGet will put in several dependencies that SignalR 2 needs. Additionally, you will get yourself a good tiny readme.txt. Feel free to read this, but we are going to be covering this listed here also.

The Front End

We are going to now truly commence coding. The Layout - First, we've got to go into the structure file and simplify issues somewhat - we don't truly require the responsive menu for this tutorial. Open /Views/Shared/_Layout.cshtml. It ought to now search such as this, assuming you failed to modify the default directories:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title</title>
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")
</head>
<body>
    <div class="container body-content">
        @RenderBody()
    </div>
 
    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/bootstrap")
    @RenderSection("scripts", required: false)
</body>
</html>

Edit the Home Controller and Index View - We will only need a single controller and view for this software. Inside the Remedy Explorer, open Controllers > HomeController and take away all Steps except for Index.

Now, open up the Index check out and just delete every thing. If you are a neat freak like me, truly feel totally free to eliminate another views inside the Views > Home.

Edit the View - Under is the see for your application. In case you are new to KnockoutJS, a few of this may appear unfamiliar. I will clarify a lot more when we get to the JavaScript inside the up coming section. Just be aware that wherever the thing is a "data-bind" attribute, the component is joined into a JS worth we are tracking with Knockout.

We're mostly using regular CSS courses from Bootstrap. Bootstrap gives us a quick way to incorporate a responsive grid framework for our view. The still left column includes our "login" type and also the proper the information board itself.

@{
    ViewBag.Title = "Land of Ooobook";
}
 
<div class="jumbotron">
    <h1>Land of Ooobook</h1>
    <p>Candy Kingdom's Social Network</p>
</div>
 
<div class="container">
    <div class="row">
        <div class="col-md-4">
            <form class="pad-bottom" data-bind="visible: !signedIn(), submit: signIn">
                <div class="form-group">
                    <label for="username">Sign In</label>
                    <input class="form-control" type="text" name="username" id="username" placeholder="Enter your userame" />
                </div>
                <button type="submit" class="btn btn-primary">Sign In</button>
                <br />
            </form>
 
            <div data-bind="visible: signedIn">
                <p>You are signed in as <strong data-bind="text: username"></strong></p>
            </div>
        </div>
        <div class="col-md-8">
            <div data-bind="visible: notifications().length > 0, foreach: notifications">
                <div class="summary alert alert-success alert-dismissable">
                    <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
                    <p data-bind="text: $data"></p>
                </div>
            </div>
 
            <div class="new-post pad-bottom" data-bind="visible: signedIn">
                <form data-bind="submit: writePost">
                    <div class="form-group">
                        <label for="message">Write a new post:</label>
                        <textarea class="form-control" name="message" id="message" placeholder="New post"></textarea>
                    </div>
                    <button type="submit" class="btn btn-default">Submit</button>
                </form>
            </div>
 
            <ul class="posts list-unstyled" data-bind="foreach: posts">
                <li>
                    <p>
                        <span data-bind="text: username" class="username"></span><br />
                    </p>
                    <p>
                        <span data-bind="text: message"></span>
                    </p>
 
                    <p class="no-pad-bottom date-posted">Posted <span data-bind="text: moment(date).calendar()" /></p>
 
                    <div class="comments" data-bind="visible: $parent.signedIn() || comments().length > 0">
                        <ul class="list-unstyled" data-bind="foreach: comments, visible: comments().length > 0">
                            <li>
 
                                <p>
                                    <span class="commentor" data-bind="text: username"></span>
                                    <span data-bind="text: message"></span>
                                </p>
                                <p class=" no-pad-bottom date-posted">Posted <span data-bind="text: moment(date).calendar()" /></p>
                            </li>
                        </ul>
 
                        <form class="add-comment" data-bind="visible: $parent.signedIn, submit: addComment">
                            <div class="row">
                                <div class="col-md-9">
                                    <input type="text" class="form-control" name="comment" placeholder="Add a comment" />
                                </div>
                                <div class="col-md-3">
                                    <button class="btn btn-default" type="submit">Add Comment</button>
                                </div>
                            </div>
                        </form>
                    </div>
                </li>
            </ul>
        </div>
    </div>
 
</div>
 
@section scripts {
    <script src="~/Scripts/moment.js"></script>
    <script src="~/Scripts/jquery.signalR-2.0.3.min.js"></script>
    <script src="~/signalr/hubs"></script>
    <script src="~/Scripts/knockout-3.1.0.js"></script>
    <script src="~/Scripts/board.js"></script>
}

Add a bit of CSS - We have a few custom CSS classes on top of what Bootstrap provides. Currently, /Content/Site.css is in your style bundle. Open it and replace everything above the validation helper classes with this:

.pad-bottom {
    margin-bottom: 10px;
}
 
.no-pad-bottom {
    margin-bottom: 0;
}
 
.new-post {
    background-color: #c9e0fc;
    padding: 15px 10px;
}
 
.username {
    font-weight: bold;
    color: #ff6a00;
}
 
.commentor {
    font-weight: bold;
    color: #004bff;
}
 
.posts li .date-posted {
    font-size: 12px;
    font-style: italic;
}
 
.posts li {
    border-bottom: 1px solid #CCC;
    padding: 15px 0;
}
 
.posts li:first-child {
    border-top: 1px solid #CCC;
}
 
.posts .comments {
    background-color: #efefef;
    margin-top: 10px;
    padding: 10px;
    padding-left: 30px;
}
 
.posts .comments li {
    padding-top: 10px;
    border: 0;
}
 
form.add-comment  {
    margin-top: 10px;
    margin-bottom: 10px;
}

The JavaScript

Create a script - In the Scripts directory, make a new script called board.js. This script will contain the client-side logic for the application.

Edit the script - Let's begin with our script.

A message board is made of posts and comments to those posts. Let's define those objects.

var post = function (id, message, username, date) {
    this.id = id;
    this.message = message;
    this.username = username;
    this.date = date;
    this.comments = ko.observableArray([]);
 
    this.addComment = function (context) {
        var comment = $('input[name="comment"]', context).val();
        if (comment.length > 0) {
            $.connection.boardHub.server.addComment(this.id, comment, vm.username())
            .done(function () {
                $('input[name="comment"]', context).val('');
            });
        }
    };
}
 
var comment = function (id, message, username, date) {
    this.id = id;
    this.message = message;
    this.username = username;
    this.date = date;
}

A submit has an observable variety of remarks. This enables it in order that when new remarks come in, it's immediately displayed within the view.

We've outlined our submit and remark objects. Now let's define our view design that is the glue from the application.

var vm = {
    posts: ko.observableArray([]),
    notifications: ko.observableArray([]),
    username: ko.observable(),
    signedIn: ko.observable(false),
    signIn: function () {
        vm.username($('#username').val());
        vm.signedIn(true);
    },
    writePost: function () {
        $.connection.boardHub.server.writePost(vm.username(), $('#message').val()).done(function () {
            $('#message').val('');
        });
    },
}
 
ko.applyBindings(vm);

We have an observable array of posts (which have an observable array of remarks). We even have an observable assortment of notifications, which inform customers of latest posts or comments on their posts. Our view model tracks the username and if a user is signed in. Finally, a view design can include techniques.

Next, we've a way for loading posts, which is known as when the web page hundreds and the user connects into a SignalR hub. The posts are loaded from the Net API controller which we are going to make later. Each and every submit is additional to the observable assortment of posts. Each and every from the post's feedback are added to the comments observable variety of the submit. This really is a really verbose method of performing this, but I wanted to make it distinct what was happening right here.

function loadPosts() {
$.get('/api/posts', function (data) {
    var postsArray = [];
    $.each(data, function (i, p) {
        var newPost = new post(p.Id, p.Message, p.Username, p.DatePosted);
        $.each(p.Comments, function (j, c) {
            var newComment = new comment(c.Id, c.Message, c.Username, c.DatePosted);
            newPost.comments.push(newComment);
        });
 
        vm.posts.push(newPost);
        });
    });
}

The rest of the script has to do with SignalR connections and methods. We'll get back to that later. Below is the entire board.js script.

var post = function (id, message, username, date) {
    this.id = id;
    this.message = message;
    this.username = username;
    this.date = date;
    this.comments = ko.observableArray([]);
 
    this.addComment = function (context) {
        var comment = $('input[name="comment"]', context).val();
        if (comment.length > 0) {
            $.connection.boardHub.server.addComment(this.id, comment, vm.username())
            .done(function () {
                $('input[name="comment"]', context).val('');
            });
        }
    };
}
 
var comment = function (id, message, username, date) {
    this.id = id;
    this.message = message;
    this.username = username;
    this.date = date;
}
 
var vm = {
    posts: ko.observableArray([]),
    notifications: ko.observableArray([]),
    username: ko.observable(),
    signedIn: ko.observable(false),
    signIn: function () {
        vm.username($('#username').val());
        vm.signedIn(true);
    },
    writePost: function () {
        $.connection.boardHub.server.writePost(vm.username(), $('#message').val()).done(function () {
            $('#message').val('');
        });
    },
}
 
ko.applyBindings(vm);
 
function loadPosts() {
    $.get('/api/posts', function (data) {
        var postsArray = [];
        $.each(data, function (i, p) {
            var newPost = new post(p.Id, p.Message, p.Username, p.DatePosted);
            $.each(p.Comments, function (j, c) {
                var newComment = new comment(c.Id, c.Message, c.Username, c.DatePosted);
                newPost.comments.push(newComment);
            });
 
            vm.posts.push(newPost);
        });
    });
}
 
$(function () {
    var hub = $.connection.boardHub;
    $.connection.hub.start().done(function () {
        loadPosts(); // Load posts when connected to hub
    });
 
    // Hub calls this after a new post has been added
    hub.client.receivedNewPost = function (id, username, message, date) {
        var newPost = new post(id, message, username, date);
        vm.posts.unshift(newPost);
 
        // If another user added a new post, add it to the activity summary
        if (username !== vm.username()) {
            vm.notifications.unshift(username + ' has added a new post.');
        }
    };
 
    // Hub calls this after a new comment has been added
    hub.client.receivedNewComment = function (parentPostId, commentId, message, username, date) {
        // Find the post object in the observable array of posts
        var postFilter = $.grep(vm.posts(), function (p) {
            return p.id === parentPostId;
        });
        var thisPost = postFilter[0]; //$.grep returns an array, we just want the first object
 
        var thisComment = new comment(commentId, message, username, date);
        thisPost.comments.push(thisComment);
 
        if (thisPost.username === vm.username() && thisComment.username !== vm.username()) {
            vm.notifications.unshift(username + ' has commented on your post.');
        }
    };
});

The Data Layer - We will be making use of Entity Framework as well as the Code First sample for our straightforward info layer.

Inside the Models directory, develop a brand new C# class referred to as MessageBoard.cs. Our data designs are little, and in our scenario we'll just place them in a single file alongside with all the data context.

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity;
using System.Linq;
using System.Web;
 
namespace MessageBoardTutorial.Models
{
    public class MessageBoardContext : DbContext
    {
        public DbSet<Post> Posts { get; set; }
        public DbSet<Comment> Comments { get; set; }
    }
 
    public class Post
    {
        [Key]
        public int Id { get; set; }
        public string Message { get; set; }
        public string Username { get; set; }
        public DateTime DatePosted { get; set; }
        public virtual ICollection<Comment> Comments { get; set; }
    }
 
    public class Comment
    {
        [Key]
        public int Id { get; set; }
        public string Message { get; set; }
        public string Username { get; set; }
        public DateTime DatePosted { get; set; }
        public virtual Post ParentPost { get; set; }
    }
}

Although the actual database doesn't yet exist, it will likely be produced if the application deems it essential. Should you maintain your internet.config unchanged, it's going to develop it within your LocalDB instance of SQL Server Specific.

The API

The script requirements a technique to get in touch with to get the posts to the concept board. Whilst we could just tack a technique on to our HomeController that would try this, we can equally as effortlessly create an ASP.Web Internet API controller which will fetch and immediately convert the posts into a JSON format.

Create the API Controller - In the Solution Explorer, right click on the Controllers directory and click on Add > Web API Controller Class (v2) in the context menu. Add a new Web API controller and call it PostsController.cs

Write the API
- Replace the code with the below. Our API will simply return a JSON or XML-serialized array of all of the posts and comments on the message board when a client calls http://[yoursite]/api/posts.

using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net;
    using System.Net.Http;
    using System.Web.Http;
    using MessageBoardTutorial.Models;
 
    namespace MessageBoardTutorial.Controllers
    {
        public class PostsController : ApiController
        {
            private MessageBoardContext _ctx;
            public PostsController()
            {
                this._ctx = new MessageBoardContext();
            }
 
            // GET api/<controller>
            public IEnumerable<post> Get()
            {
                return this._ctx.Posts.OrderByDescending(x => x.DatePosted).ToList();
            }
        }
    }
</post></controller>

Handle circular references - If you look at our data models, a Post contains a virtual collection of comments, and a Comment contains a virtual Post that refers to the comment's parent. This circular reference will freak out Web API's serialization method. To solve this, just add the following line of code to the Register method in the WebApiConfig class located at App_Start/WeApiConfig.cs
   
config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling =
    Newtonsoft.Json.ReferenceLoopHandling.Ignore;

Circular references will now be ignored.

Implementing the SignalR Hub

SignalR provides a relationship between clientele and also the server. Clients connect to a SignalR Hub. The Hub can then contact client-side occasions on a single, some, or all related clients. The Hub tracks which consumers are linked to it. This can be the center of real-time net programs. Within our case, a client generates a fresh submit or comment, which phone calls a method around the Hub. The Hub then calls a method on all of the message board's connected users that inserts the brand new submit or remark.

In a nutshell, the awesomeness of SignalR is that it may call JavaScript capabilities on any browser linked to it. The outdated assemble is clientele could only get in touch with server-side features. This type of functionality could only be achieved via long-polling (a customer working an infinite loop that calls a server method).


Newer browsers connect to hubs via HTML 5 web sockets. For older browsers, there are long-polling and "forever frame" fallbacks.

Map the hubs - In order for SignalR to begin and for the web application to map the connection hubs, we must create an OWIN startup class. Lucky for us, this just involves a couple of clicks and a line of code. Right-click on the solution and add a new item. Find the OWIN Startup Class template. Name this file "Startup.cs". Now, you just have to add one line of code in the Configuration method to map the hubs.

using System;
using System.Threading.Tasks;
using Microsoft.Owin;
using Owin;
 
[assembly: OwinStartup(typeof(MessageBoardTutorial.Startup))]
 
namespace MessageBoardTutorial
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.MapSignalR();
        }
    }
}

Create the Hub - Make a new directory in the root of your project called Hubs. Now, right-click on this new directory and click on Add > New Item... in the context menu. Create a new SignalR Hub Class called BoardHub.cs.


Replace the code in the file with the below:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.AspNet.SignalR;
using MessageBoardTutorial.Models;
 
namespace MessageBoardTutorial.Hubs
{
    public class BoardHub : Hub
    {
        public void WritePost(string username, string message)
        {
            var ctx = new MessageBoardContext();
            var post = new Post { Message = message, Username = username, DatePosted = DateTime.Now };
            ctx.Posts.Add(post);
            ctx.SaveChanges();
 
            Clients.All.receivedNewPost(post.Id, post.Username, post.Message, post.DatePosted);
        }
 
        public void AddComment(int postId, string comment, string username)
        {
            var ctx = new MessageBoardContext();
            var post = ctx.Posts.FirstOrDefault(p => p.Id == postId);
 
            if (post != null)
            {
                var newComment = new Comment { ParentPost = post, Message = comment, Username = username, DatePosted = DateTime.Now };
                ctx.Comments.Add(newComment);
                ctx.SaveChanges();
 
                Clients.All.receivedNewComment(newComment.ParentPost.Id, newComment.Id, newComment.Message, newComment.Username, newComment.DatePosted);
            }
        }
    }

}

The Hub contains a method for writing a new post and a method for writing a new comment. Both methods are called from the client and ultimately call client-side methods for connected users.

For example, the writePost client-side method is called when a user writes a new post:

writePost: function () {
    $.connection.boardHub.server.writePost(vm.username(), $('#message').val()).done(function () {
        $('#message').val('');
    });
},

This method calls the WritePost method on the Hub. After the new post is added to the database, the Hub then calls the receivedNewPost method on all connected clients.

Clients.All.receivedNewPost(post.Id, post.Username, post.Message, post.DatePosted);

From BoardHub.cs

hub.client.receivedNewPost = function (id, username, message, date) {
    var newPost = new post(id, message, username, date);
    vm.posts.unshift(newPost);
 
    // If another user added a new post, add it to the activity summary
    if (username !== vm.username()) {
        vm.notifications.unshift(username + ' has added a new post.');
    }
};

From board.js

The Hub sends info about the new submit to this client method, which then helps make a brand new Publish JavaScript object and adds it to the starting from the view model's posts observable array. This new post is instantaneously displayed for all related customers since Knockout is observing this array. A brand new notification can also be produced for all customers other than the creator of the new publish.

Adding a remark follows the same pattern, although the client callback method differs marginally:

hub.client.receivedNewComment = function (parentPostId, commentId, message, username, date) {
    // Find the post object in the observable array of posts
    var postFilter = $.grep(vm.posts(), function (p) {
        return p.id === parentPostId;
    });
    var thisPost = postFilter[0]; //$.grep returns an array, we just want the first object
 
    var thisComment = new comment(commentId, message, username, date);
    thisPost.comments.push(thisComment);
 
    if (thisPost.username === vm.username() && thisComment.username !== vm.username()) {
        vm.notifications.unshift(username + ' has commented on your post.');
    }
};

The ID of the parent post of the comment is sent to the client, which then adds the new comment to the comments observable array of the post

Finally, let us run this point

Now you can construct and operate the project! Ooo is in dire need of a social community.

Go on and open up two browser windows and "log in" as a various person on every. Recognize how once you include a submit in a single window, it instantaneously is additional towards the other window in addition to a notification. Now, the Ice King can annoy princesses on-line too! Effectively, possibly that is not all that good.




ASP.NET 4.5.1 Hosting with ASPHostPortal.com :: How to Increase The Overall Performance of ASP.NET 4.5.1 in your App

clock October 1, 2014 07:23 by author Ben

ASP.NET is really a framework for creating net applications created by Microsoft. Initially the technologies. NET is the successor of ASP which is also a computer software product from Microsoft. With .NET ASP gives a platform for developers to design and create dynamic websites and net portals.



You will find certain items that ought to be regarded as when improving the performance from the application in developing a net application. Here are a few of the tips to improve the performance of ASP.NET 4.5.1:

Turn off Session State
Disable session state if you do not need, as this can improve the all round efficiency. By default the session state is always active. However, you'll be able to disable session state for any specific pages.

Turn off Tracing
If tracing is enabled, tracing will add a whole lot of overhead in producing applications. Though tracing is actually a useful function inside the development because it enables developers to track and trace application sequence, tracing may be turned off, unless you want to monitor the trace logging.

Avoid Page Validation Server (Steer clear of Server-side Validation)
Within this case, must be attempted use of client-side validation, not the server side. Server-side validation will consume a lot of sources around the server which can have an effect on application efficiency.

Stay away from Exceptions (Avoid Exceptions)
Exceptions may be 1 of the biggest resource eater which resulted within the lower of web applications and windows applications. Therefore, it is much better to prevent the use and handling of exceptions which can be not beneficial.

Avoid frequent connections for the database (Steer clear of Frequent Calls to Database)
Connections are frequently made for the database can devote time response and resources (resources). This can be avoided by utilizing batch processing. Producing the minimum database connection as a connection is opened and not closed, may cause efficiency slowdown.

Stay away from utilizing Recursive Functions and Nested Loops
To improve application performance, attempt to always steer clear of utilizing nested loops and recursive functions simply because these functions consume a whole lot of memory.

Turn off the View State

In ASP.NET, the default view state will probably be active and will slow down the website. So if you don't use a kind postback, it's much better to disable view state.

Use Caching
Web page caching could be employed to get a particular period of time and towards the required duration will not visit the server and are served from the cache. In the case of static internet pages and dynamic, Partial Caching [Fragment Caching] may be utilized to break into a couple of pages a user control.



ASP.NET 4.5.2 Hosting with ASPHostPortal.com :: Responsive Layout Using Bootstrap in ASP.NET

clock September 22, 2014 13:29 by author Kenny

ASP.NET Responsive Layout using Bootstrap

In this article we will explain about how to design responsive layout using bootstrap in your ASP.NET site. ASP.NET is an open source server-side Web application framework designed for Web development to produce dynamic Web pages. It was developed by Microsoft to allow programmers to build dynamic web sites, web applications and web services.

ASP.NET Responsive Layout:

Responsive Web design is the approach that suggests that design and development should respond to the user's behavior and environment based on screen size, platform and orientation. The practice consists of a mix of flexible grids and layouts, images and an intelligent use of CSS media queries.

Why You Need Responsive Web Design?

Every people open website on mobile device, tablet device and desktop on different-different size that time our website layout is not good looking so web designer design the different-different website for different-different devices for good look and feel website so that process is very time taken. So reduce that process invent to “Responsive Layout” word.

Pillar of Responsive Layout:

1. Fluid Grids:

The general practice in web design is to employ fixed width layouts. It means that the page and its constituent elements have a fixed size and width and positioned around the center. Liquid layouts offer us a greater advantage with the increasing number of devices with web access. A liquid layout expands with the page.

2. Flexible Images:

Web page text is fluid by default: as the browser window narrows, text reflows to occupy the remaining space. Images are not naturally fluid: they remain the same size and orientation at all configurations of the viewport, and will be cropped if they become too large for their container. This creates a problem when displaying images in a mobile browser: because they remain at their native size, images may be cut off or displayed out-of-scale compared to the surrounding text content as the browser narrows.

3. Media Queries:

Fluid grid layouts are very important for responsive web development, but there are other issues to consider. If the width of the device becomes too narrow, like in a small mobile phone, the website design can fall apart. This is where media queries come in. These media queries are based in CSS3 and allow us to not only target the particular device classes but physical characteristics of the device which is rendering the web site.

Add these four files:

<link href="~/Content/bootstrap-3.1.1-dist/css/bootstrap.min.css" rel="stylesheet" />
<link href="~/Content/blog.css" rel="stylesheet" />
<script src="~/scripts/jquery-2.1.0.min.js"></script>
<script src="~/scripts/bootstrap-3.1.1-dist/js/bootstrap.min.js"></script>

Example:

Html Code

<header class="navbar navbar-inverse navbar-fixed-top bs-docs-nav" role="banner">
    <div class="container">
        <div class="navbar-header">
            <button class="navbar-toggle" type="button" data-toggle="collapse" data-target=".bs-navbar-collapse">
                <span class="sr-only">Toggle Navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
            @Html.ActionLink("Brand", "Index", "Home", null, new { @class = "navbar-brand" })
        </div>
        <nav class="collapse navbar-collapse bs-navbar-collapse" role="navigation">
            <ul class="nav navbar-nav">
                <li class="active">@Html.ActionLink("Home", "", "")</li>
                <li>@Html.ActionLink("Article", "", "")</li>
                <li>@Html.ActionLink("Blog", "", "")</li>
                <li>@Html.ActionLink("Forum", "", "")</li>
                <li>@Html.ActionLink("Interview", "", "")</li>
                <li class="dropdown">
                    <a class="dropdown-toggle" data-toggle="dropdown" href="#" id="themes">Themes <span class="caret"></span></a>
                    <ul class="dropdown-menu" aria-labelledby="themes">
                        <li><a href="../default/">Default</a></li>
                        <li class="divider"></li>
                        <li><a href="../david/">David</a></li>
                        <li><a href="../lily/">Lily</a></li>
                        <li><a href="../jasmine/">Jasmine</a></li>
                    </ul>
                </li>
            </ul>
            <ul class="nav navbar-nav navbar-right">
                <li>@Html.ActionLink("Sign Up", "", "")</li>
                <li>@Html.ActionLink("Login", "", "")</li>
                <li>
                    <form class="navbar-form navbar-left" role="search">
                        <div class="form-group">
                            <input type="text" class="form-control" placeholder="Search">
                        </div>
                    </form>
                </li>
            </ul>
        </nav>
    </div>
</header>
<div class="container">
    <br />
    <br />
    <div class="row">
        <img src="~/Content/Images/Sample1.png" class="banner" />
    </div>
    <br />   
    <div class="row">
        <div class="col-md-4">
            <img src="~/Content/Images/mobile-devlopment.png" />
        </div>
        <div class="col-md-8">
            <p>

Web page text is fluid by default: as the browser window narrows, text reflows to occupy the remaining space. Images are not naturally fluid: they remain the same size and orientation at all configurations of the viewport, and will be cropped if they become too large for their container. This creates a problem when displaying images in a mobile browser: because they remain at their native size, images may be cut off or displayed out-of-scale compared to the surrounding text content as the browser narrows.

 </p>
        </div>
    </div>
    <br />
    <br />
    <div class="well">
        <div class="row">
            <div class="col-md-6">
                <label>First Name</label>
                <input type="text" />
            </div>
            <div class="col-md-6">
                <label>Last Name</label>
                <input type="text" />
            </div>
        </div>
        <br />
        <div class="row">
            <div class="col-md-6">
                <label>Email ID</label>
                <input type="text" />
            </div>
            <div class="col-md-6">
                <label>Country</label>
                <select>
                    <option>---Select---</option>
                    <option>USA</option>
                    <option>UK</option>
                    <option>Netherland</option>
                    <option>Hongkong</option>
                </select>
            </div>
        </div>
        <br />
        <div class="row">
            <div class="col-md-6">
                <label>State</label>

                <select>
                </select>
            </div>
            <div class="col-md-6">
                <label>City</label>
                <select>
               </select>
            </div>
        </div>
        <br />
        <div class="row">
            <div class="col-md-6">
                <label>Zip Code</label>
                <input type="text" />
            </div>
            <div class="col-md-6">
                <label>Contact No</label>
                <input type="text" />
            </div>
        </div>
        <br />
        <div class="row">
            <div class="col-md-12 text-right">
                <input type="button" value="Submit" class="btn btn-info" />
                <input type="button" value="Clear" class="btn btn-info" />
            </div>
        </div>
    </div>
    <br />
    <br />
</div>

Blog.css

Img
{
    width: auto;
    max-width: 100%;
}
.banner {
    width:100%;
    height:250px;

}
input[type='text'],select {
    width:100%;
    height:30px;
}
@media screen and (min-width: 100px) and (max-width:750px) {
    .banner {
        display:none;
    }
}



ASP.NET 4.5.2 Hosting with ASPHostPortal :: How to Publish and Deploy an ASP.NET Application in IIS

clock September 16, 2014 12:08 by author Kenny

Simple Way to Publish and Deploy an ASP.NET Application in IIS

ASP.NET is an open source server-side Web application framework designed for Web development to produce dynamic Web pages. It was developed by Microsoft to allow programmers to build dynamic web sites, web applications and web services. While Internet Information Services (IIS, formerly Internet Information Server) is an extensible web server created by Microsoft for use with Windows NT family. IIS supports HTTP, HTTPS, FTP, FTPS, SMTP and NNTP.

In this post, we will describe you how to publish and deploy your ASP.NET application in IIS. Actually it is so simple thing, you can publish your web application to the File System and copy paste all the files to your server. After that, you can add a new website from IIS. If you are not sure what files you should include, it's better to choose 'All files in the project' from the Package/Publish Web. Otherwise choose 'Only files needed to run this application'. You can set this by right clicking on the web application in the solution explorer and choosing 'Package/Publish Settings'.

Right click on your project in the solution explorer and choose 'Publish'. From the dialog box, as the publish method, choose 'File System'. And choose some directory as the Target Location.

You can add the website by right clicking on the 'Sites' in IIS.

Then give a name to your site and select the Physical path from where you copied the site folder

Best and Cheap ASP.NET Hosting

Are you looking for best and cheap ASP.NET Hosting? Look no further, ASPHostPortal.com is your ASP.NET hosting home! Start your ASP.NET hosting with only $1.00/month. All of our .NET hosting plan comes with 30 days money back guarantee, so you can try our service with no risk. Why wait longer?



ASP.NET 4.5.2 Hosting with ASPHostPortal.com :: SEO Tips for Your ASP.NET Site

clock August 23, 2014 09:42 by author Kenny

Here are 7 tips on SEO for your ASP.NET website:

A Microsoft server-side Web technology. ASP.NET takes an object-oriented programming approach to Web page execution. Every element in an ASP.NET page is treated as an object and run on the server. An ASP.NET page gets compiled into an intermediate language by a .NET Common Language Runtime-compliant compiler.

Page Titles

Page titles between tags is one important thing that many fail to practice in SEO. When a search is made in Google, these titles show up as links in the result. So that explains its importance. The common mistake among website owners is giving the same title for all pages. Page titles drive traffic to your site, hence it is important to have a proper title to attract visitors. Adding titles is not as hard as you imagine. If you have a product catalog use your product name as title. You can also choose to give a different title that is related to your product.

Meaningful URL

URLs that are long with query parameters do not look neat and it is difficult for the visitor to remember. Instead use formatted URLs for your static pages. URL which has a meaning explains the content in your website. Although experts agree with using an URL that has query parameters, it is better to have a meaningful URL. Components like UrlRewritingNet can be used for this purpose. Mapping support in URL is offered by IIS7 which has plenty of features.

Structure of the Content

Content without a structure is not possible.  You will have titles, headings, sub headings, paragraphs and others. How would you emphasize some quotes or important points in your content? If you follow the below mentioned steps, the structure of your content will be semantically correct.

  • Divide long stories or parts using headings. Short paragraphs make more sense to the readers. Use tags to bring beauty to your content.
  • If you want to emphasize an important point or quote, place them between tags.

Visitors can create structured content if you use FCKEditor and the like. Integrating these to your website is not complex.

Clean the Source Code

Don’t panic, it is advisable to clean up the source code and minimize the number of codes. The following simple steps will assist you in cleaning the source code: You can use

  • External stylesheets and not inline CSS
    • js files instead of inline JavaScript
  • HTML comments is not encouraged
  • Avoid massive line breaking
  • Avoid using viewstate when not required

The relation between the content and the code (JavaScript, HTML, CSS) determines the ranking of your website. Smaller source codes help build a strong relation.

Crawlable Site

Do not use

  • Silver or flash light for menus or to highlight information
  • Menus based on JavaScript
  • Menus based on buttons
  • Intro-pages

Do use

  • Simple tags wherever possible
  • Sitemap
  • “Alt” for images
  • RSS

Test the Site

What happens to the requests that are sent when the site is slow? Sometimes requests are sent by robots and if they are unable to connect to your site continuously, they drop the site from their index. Enable your site to respond fast to requests even during peak hours. Moreover, visitors don’t like to visit slow sites. Use the various tools available and conduct the stress test for your site. Perform this and locate all the weak parts of the site. Fix them so that your site gets indexed. 

Test the AJAX site

Spiders can only run a few parts of your AJAX website because they don’t run JavaScripts. Spiders can only analyze the data and hence they remain invisible to robots. The AJAX sites do not get indexed which does not help in search engine optimization. To make the site spider friendly, try and keep away from initial content loading into the JavaScript. You can also follow this only for pages that you like to index.  Make it easy for robots so that they can navigate. Try this simple trick to see how your AJAX site will appear to the robots. Disable JavaScript from the browser and visit your AJAX site. You can view the pages which robots will index.



ASP.NET 4.5.2 Hosting with ASPHostPortal.com :: Token Based Authentication using ASP.NET Web API 2, Owin, and Identity.

clock July 22, 2014 09:26 by author Kenny

In this article, we are going to explain about Token Based Authentication using ASP.NET Web API 2, Owin, and Identity. As you know that a token is a piece of data created by server, and contains information to identify a particular user and token validity. The token will contain the user's information, as well as a special token code that user can pass to the server with every method that supports authentication, instead of passing a username and password directly.

What is Token Based Authentication?

Token-based authentication is a security technique that authenticates the users who attempt to log in to a server, a network, or some other secure system, using a security token provided by the server. An authentication is successful if a user can prove to a server that he or she is a valid user by passing a security token. The service validates the security token and processes the user request. After the token is validated by the service, it is used to establish security context for the client, so the service can make authorization decisions or audit activity for successive user requests.

The general concept behind a token-based authentication system is simple. Allow users to enter their username and password in order to obtain a token which allows them to fetch a specific resource - without using their username and password. Once their token has been obtained, the user can offer the token - which offers access to a specific resource for a time period - to the remote site.

What is ASP.NET Web API 2, Owin, and Identity?

This article is about Token Based Authentication using ASP.NET Web API 2, Owin, and Identity. ASP.NET Web API is a framework that makes it easy to build HTTP services that reach a broad range of clients, including browsers and mobile devices. ASP.NET Web API is an ideal platform for building RESTful applications on the .NET Framework. ASP.NET Identity is the reworked, flexible replacement for the old membership system that has been around since ASP.NET 2.0. ASP.NET Identity is more well designed and flexible than the old membership system and uses Owin middleware components for external logins such as Facebook, Google and Twitter.

Building the Back-End API

Step 1: Creating the Web API Project

Now create an empty solution and name it “AngularJSAuthentication” then add new ASP.NET Web application named “AngularJSAuthentication.API”, the selected template for project will be as the image below. Notice that the authentication is set to “No Authentication” taking into consideration that we’ll add this manually.

Step 2: Installing the needed NuGet Packages:

Now we need to install the NuGet packages which are needed to setup our Owin server and configure ASP.NET Web API to be hosted within an Owin server, so open NuGet Package Manger Console and type the below:

Install-Package Microsoft.AspNet.WebApi.Owin -Version 5.1.2

Install-Package Microsoft.Owin.Host.SystemWeb -Version 2.1.0

The  package “Microsoft.Owin.Host.SystemWeb” is used to enable our Owin server to run our API on IIS using ASP.NET request pipeline as eventually we’ll host this API on Microsoft Azure Websites which uses IIS.

Step 3: Add Owin “Startup” Class

Right click on your project then add new class named “Startup”. We’ll visit this class many times and modify it, for now it will contain the code below:
using Microsoft.Owin;
using Owin;
using System;
using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Http;

[assembly: OwinStartup(typeof(AngularJSAuthentication.API.Startup))]

namespace AngularJSAuthentication.API

{

    public class Startup

    {

        public void Configuration(IAppBuilder app)

        {

            HttpConfiguration config = new HttpConfiguration();

            WebApiConfig.Register(config);

            app.UseWebApi(config);

        }

    }

}

What we’ve implemented above is simple, this class will be fired once our server starts, notice the “assembly” attribute which states which class to fire on start-up. The “Configuration” method accepts parameter of type “IAppBuilder” this parameter will be supplied by the host at run-time. This “app” parameter is an interface which will be used to compose the application for our Owin server.

The “HttpConfiguration” object is used to configure API routes, so we’ll pass this object to method “Register” in “WebApiConfig” class.

Lastly, we’ll pass the “config” object to the extension method “UseWebApi” which will be responsible to wire up ASP.NET Web API to our Owin server pipeline.

Usually the class “WebApiConfig” exists with the templates we’ve selected, if it doesn’t exist then add it under the folder “App_Start”. Below is the code inside it:

    public static class WebApiConfig
    {
       public static void Register(HttpConfiguration config)
        {
            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

           var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First();

            jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
        }
}

Step 4: Delete Global.asax Class

No need to use this class and fire up the Application_Start event after we’ve configured our “Startup” class so feel free to delete it.

Step 5: Add the ASP.NET Identity System

After we’ve configured the Web API, it is time to add the needed NuGet packages to add support for registering and validating user credentials, so open package manager console and add the below NuGet packages:

Install-Package Microsoft.AspNet.Identity.Owin -Version 2.0.1

Install-Package Microsoft.AspNet.Identity.EntityFramework -Version 2.0.1

The first package will add support for ASP.NET Identity Owin, and the second package will add support for using ASP.NET Identity with Entity Framework so we can save users to SQL Server database.

Now we need to add Database context class which will be responsible to communicate with our database, so add new class and name it “AuthContext” then paste the code snippet below:

public class AuthContext : IdentityDbContext<IdentityUser>
    {
        public AuthContext()
            : base("AuthContext")
            }

As you can see this class inherits from “IdentityDbContext” class, you can think about this class as special version of the traditional “DbContext” Class, it will provide all of the Entity Framework code-first mapping and DbSet properties needed to manage the identity tables in SQL Server.

Step 6: Add Repository class to support ASP.NET Identity System

Now we want to implement two methods needed in our application which they are: “RegisterUser” and “FindUser”, so add new class named “AuthRepository” and paste the code snippet below:

    public class AuthRepository : IDisposable
    {
        private AuthContext _ctx;

        private UserManager<IdentityUser> _userManager;
        public AuthRepository()
        {
            _ctx = new AuthContext();
            _userManager = new UserManager<IdentityUser>(new UserStore<IdentityUser>(_ctx));
        }

        public async Task<IdentityResult> RegisterUser(UserModel userModel)
        {
          IdentityUser user = new IdentityUser
            {            UserName = userModel.UserName
            };
            var result = await _userManager.CreateAsync(user, userModel.Password);
            return result;
        }
        public async Task<IdentityUser> FindUser(string userName, string password)
        {
        IdentityUser user = await _userManager.FindAsync(userName, password);
            return user;
        }
        public void Dispose()
        {
            _ctx.Dispose();
            _userManager.Dispose();
        }
}

Step 7: Add our “Account” Controller

Now it is the time to add our first Web API controller which will be used to register new users, so under file “Controllers” add Empty Web API 2 Controller named “AccountController” and paste the code below:

[RoutePrefix("api/Account")]
    public class AccountController : ApiController
    {
          private AuthRepository _repo = null;
          public AccountController()
        {
           _repo = new AuthRepository();
        }
        // POST api/Account/Register
        [AllowAnonymous]
        [Route("Register")]
        public async Task<IHttpActionResult> Register(UserModel userModel)
        {
         if (!ModelState.IsValid)
            {
              return BadRequest(ModelState);
            }
            IdentityResult result = await _repo.RegisterUser(userModel);
            IHttpActionResult errorResult = GetErrorResult(result);
            if (errorResult != null)
            {
              return errorResult;
            }
              return Ok();
        }
        protected override void Dispose(bool disposing)
        {
           if (disposing)
            {
              _repo.Dispose();
            }
            base.Dispose(disposing);
        }
        private IHttpActionResult GetErrorResult(IdentityResult result)
        {
          if (result == null)
            {
             return InternalServerError();
            }
            if (!result.Succeeded)
            {
              if (result.Errors != null)
                {
                  foreach (string error in result.Errors)
                    {
                     ModelState.AddModelError("", error);
                    }
                }
                if (ModelState.IsValid)
                {
                // No ModelState errors are available to send, so just return an empty BadRequest.
                    return BadRequest();
                }
                return BadRequest(ModelState);
            }
            return null;
        }
}

Step 8: Add Secured Orders Controller

Now we want to add another controller to serve our Orders, we’ll assume that this controller will return orders only for Authenticated users, to keep things simple we’ll return static data. So add new controller named “OrdersController” under “Controllers” folder and paste the code below:

[RoutePrefix("api/Orders")]
    public class OrdersController : ApiController
    {
     [Authorize]
        [Route("")]
        public IHttpActionResult Get()
        {
         return Ok(Order.CreateOrders());
        }
    }
    #region Helpers
    public class Order
    {
   public int OrderID
     {
      get;
      set;
     }
        public string CustomerName
         {
           get;
           set;
         }
        public string ShipperCity
        {
          get;
          set;
      }
        public Boolean IsShipped
       {   
         get;
         set;
      }
        public static List<Order> CreateOrders()
        {
         List<Order> OrderList = new List<Order>
            {
                new Order {OrderID = 10248, CustomerName = "Taiseer Joudeh", ShipperCity = "Amman", IsShipped = true },
                new Order {OrderID = 10249, CustomerName = "Ahmad Hasan", ShipperCity = "Dubai", IsShipped = false},
                new Order {OrderID = 10250,CustomerName = "Tamer Yaser", ShipperCity = "Jeddah", IsShipped = false },
                new Order {OrderID = 10251,CustomerName = "Lina Majed", ShipperCity = "Abu Dhabi", IsShipped = false},
                new Order {OrderID = 10252,CustomerName = "Yasmeen Rami", ShipperCity = "Kuwait", IsShipped = true}
            };
            return OrderList;
        }
   }
    #endregion

Step 9: Add support for OAuth Bearer Tokens Generation

Till this moment we didn’t configure our API to use OAuth authentication workflow, to do so open package manager console and install the following NuGet package:

Install-Package Microsoft.Owin.Security.OAuth -Version 2.1.0

After you install this package open file “Startup” again and call the new method named “ConfigureOAuth” as the first line inside the method “Configuration”, the implemntation for this method as below:

public class Startup
    {
    public void Configuration(IAppBuilder app)
        {
          ConfigureOAuth(app);
                    //Rest of code is here;
        }
        public void ConfigureOAuth(IAppBuilder app)
        {
          OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
            {
                AllowInsecureHttp = true,
                TokenEndpointPath = new PathString("/token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
                Provider = new SimpleAuthorizationServerProvider()
            };
            // Token Generation
            app.UseOAuthAuthorizationServer(OAuthServerOptions);
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
        }}

Step 10: Implement the “SimpleAuthorizationServerProvider” class

Add new folder named “Providers” then add new class named “SimpleAuthorizationServerProvider”, paste the code snippet below:

public class SimpleAuthorizationServerProvider : OAuthAuthorizationServerProvider
    {
      public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
  context.Validated();
        }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
       {
   context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
            using (AuthRepository _repo = new AuthRepository())
            {
   IdentityUser user = await _repo.FindUser(context.UserName, context.Password);
                if (user == null)
                {context.SetError("invalid_grant", "The user name or password is incorrect.");
                    return;
                }
         }
            var identity = new ClaimsIdentity(context.Options.AuthenticationType);
            identity.AddClaim(new Claim("sub", context.UserName));
            identity.AddClaim(new Claim("role", "user"));
            context.Validated(identity);
        }
    }

Step 11: Allow CORS for ASP.NET Web API

First of all we need to install the following NuGet package manger, so open package manager console and type:

Install-Package Microsoft.Owin.Cors -Version 2.1.0

Now open class “Startup” again and add the highlighted line of code (line 8) to the method “Configuration” as the below:

public void Configuration(IAppBuilder app)
        {
            HttpConfiguration config = new HttpConfiguration();
            ConfigureOAuth(app);
            WebApiConfig.Register(config);
            app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
            app.UseWebApi(config);        }

Step 12: Testing the Back-end API

Assuming that you registered the username “Taiseer” with password “SuperPass” in the step below, we’ll use the same username to generate token, so to test this out open your favorite REST client application in order to issue HTTP requests to generate token for user “Taiseer”. For me I’ll be using PostMan.



ASPHostPortal Web Hosting Announces Release of New Free 7 Days ASP.NET MVC 5.2 Hosting

clock June 6, 2014 07:48 by author Ben

Windows and ASP.NET hosting specialist, ASPHostPortal.com, has announced the availability of new hosting plans that are optimized for the latest update of the ASP.NET MVC  technology. The ASP.NET MVC 5.2 Release Candidate is now available to developers for immediate download. ASP.NET MVC 5.2 is the latest update to Microsoft's popular MVC (Model-View-Controller) technology - an established web application framework. This package contains the runtime assemblies for ASP.NET MVC. ASP.NET MVC gives you a powerful, patterns-based way to build dynamic websites that enables a clean separation of concerns and that gives you full control over markup. ASP.NET MVC 5.2  brings bootstrap into the default MVC template, authentication filters, filter overrides and attribute routing.  Attribute Routing on ASP.NET MVC 5.2 now provides an extensibility point called IDirectRouteProvider, which allows full control over how attribute routes are discovered and configured.

ASPHostPortal.com - a cheap, constant uptime, excellent customer service, quality and also reliable hosting provider in advanced Windows and ASP NET technology. ASPHostPortal.com hosts its servers in top class data centers that is located in United States to guarantee 99.9% network uptime. All data center feature redundancies in network connectivity, power, HVAC, security, and fire suppression. All hosting plans from ASPHostPortal.com include 24×7 support and 30 days money back guarantee.

“We pride ourselves on offering the most up to date Microsoft services. We're pleased to launch this product today on our hosting environment” said Dean Thomas, Manager at ASPHostPortal.com. “We have always had a great appreciation for the products that Microsoft offers. With the launched of ASP.NET MVC 5.2 hosting services, we hope that developers and our existing clients can try this new features. Now, you don’t need to spend a lot of money to get ASP.NET MVC 5.2 hosting.”

For more information about new ASP.NET MVC 5.2, please visit http://asphostportal.com/ASPNET-MVC-52-Hosting.

As a leading hosting provider, ASPHostPortal.com offers a comprehensive range of services including domain name registrations, servers, online backup solutions and dedicated web hosting. ASPHostPortal.com is well placed to deliver a high quality service.

About ASPHostPortal.com:

ASPHostPortal.com is a hosting company that best support in Windows and ASP.NET-based hosting. Services include shared hosting, reseller hosting, and sharepoint hosting, with specialty in ASP.NET, SQL Server, and architecting highly scalable solutions. As a leading small to mid-sized business web hosting provider, ASPHostPortal.com strive to offer the most technologically advanced hosting solutions available to all customers across the world. Security, reliability, and performance are at the core of hosting operations to ensure each site and/or application hosted is highly secured and performs at optimum level.



ASP.NET MVC 5.1.2 Hosting with ASPHostPortal.com :: Loading a Knockoutjs Model from a ASP.NET MVC Controller Using AJAX

clock May 21, 2014 11:51 by author Kenny

Knockout.js is a javascript library that allows us to bind html elements against any data model. It provides a simple two-way data binding mechanism between your data model and UI means any changes to data model are automatically reflected in the DOM(UI) and any changes to the DOM are automatically reflected to the data model.

Based on ASP.NET, ASP.NET MVC allows software developers to build a web application as a composition of three roles: Model, View and Controller. The MVC model defines web applications with 3 logic layers: The business layer (Model logic),The display layer (View logic),The input control (Controller logic).

This article will demonstrate how to load a KnockoutJS view model from a C# controller using ajax in an ASP.NET MVC project. I’m just going to jump straight into the code for this sample.  To get started we need to create a new action in the controller.  For the purposes of this sample this action will return a randomly populated Person object (see the previous articles for the definition) so that we can see the content changing.  Here is the action:

public class SampleController : Controller
{
    public ActionResult AjaxModelLoading()
    {
        Person model = CreateRandomModel();
        if (Request.IsAjaxRequest())
        {
            return new JsonNetResult(model);
        }
        return View(model);
    } 
    private static Person CreateRandomModel()
    {
        Random random = new Random();
        string[] firstNames = { "Billy", "Kevin", "Michael", "Steve" };
        string[] lastNames = { "Jordan", "Smith", "Wild", "Walker" };
        string firstName = firstNames[random.Next(firstNames.Length)];
        string lastName = lastNames[random.Next(lastNames.Length)]; 
        return new Person
        {
            FirstName = firstName,
            LastName = lastName,
            EmailAddress = string.Format("{0}@{1}.com", firstName, lastName),
            PhoneNumber = random.Next(int.MaxValue).ToString("D10"),
            DateOfBirth = DateTime.Today.AddYears(random.Next(-50, -10))
        };
    }
}


This action creates the Person object and then detects if the HTTP request was made using ajax.  If it was then it serializes the model as JSON and if it is a standard HTTP request it returns the view.  This is a handy technique for implementing a simple refresh of data in the view without retrieving all the HTML from the server again.

On line 9 you can see that I have not used the standard ASP.NET JSON serializer.  Instead I went with my own ActionResult which makes use of JSON.NET to give myself more control over the generated JSON.  For reference the code for my JsonNetResult class is below:
public class JsonNetResult : ActionResult
{
  
    private const string ContentType = "application/json"; 
    private readonly object data;
    private readonly Formatting formatting;
    private readonly JsonSerializerSettings serializerSettings; 
    public JsonNetResult(object data)
    {
        this.data = data;
        formatting = Formatting.None;
        serializerSettings = new JsonSerializerSettings
       {
            ContractResolver = new CamelCasePropertyNamesContractResolver()
        };
    }
    public override void ExecuteResult(ControllerContext context)
    {
        HttpResponseBase response = context.HttpContext.Response;
        response.ContentType = ContentType;
        if (data != null)
        {
            JsonTextWriter writer = new JsonTextWriter(response.Output) { Formatting = formatting };
            JsonSerializer serializer = JsonSerializer.Create(serializerSettings);
            serializer.Serialize(writer, data);
            writer.Flush();
       }
    } 
    public object Data
    {
        get { return data; }
    }
}


Next we need to create the KnockoutJS view model to bind to the view.
var AjaxModelLoading = function(url) {
    var self = this;
    self.isLoaded = ko.observable(false);
    self.isLoading = ko.observable(false); 
    self.getRandomModel = function () {
        self.isLoading(true);
        self.isLoaded(false);
 
        // Setting a timeout so the loading text is visible in the sample
        setTimeout(function() {
            $.ajax(url, {
                type: "GET",
                cache: false,
            }).done(function(data) {
                ko.mapping.fromJS(data, {}, self);
                self.isLoaded(true);
                self.isLoading(false);
            });
        }, 1000);
    };
};


This view model defines a function which will be used to handle a click event from the view in order to refresh the data. It also does some basic state management to determine if the content has been loaded or is in the process of loading.  I have put in a short delay between the click in the view and executing the ajax request in order to make the loading state management more apparent for the sample.

Lastly we need to create the view.
@model Quickstart.Web.Models.Person 
@section scripts
{
    <script type="text/javascript" src="/Scripts/ViewModels/AjaxModelLoading.js"></script>
    <script type="text/javascript">
        var viewModel = new AjaxModelLoading("@Url.Action("AjaxModelLoading")");
        ko.applyBindings(viewModel); 
        viewModel.getRandomModel();
    </script>
}
 
<h2>Ajax Model Loading Sample</h2>

<div data-bind="if: isLoading()">
    Loading...
</div>
 
<div data-bind="if: isLoaded()">
    <div>
        <label>First Name:</label>
        <input type="text" data-bind="value: firstName"/>
    </div>
 
    <div>
        <label>Last Name:</label>
        <input type="text" data-bind="value: lastName"/>
    </div>

    <div>
        <label>Email Address:</label>
        <input type="text" data-bind="value: emailAddress"/>
    </div>
 
    <div>
        <label>Phone Number:</label>
        <input type="text" data-bind="value: phoneNumber"/>
    </div>
 
    <div>
        <label>Date of Birth:</label>
        <input type="text" data-bind="value: dateOfBirth"/>
    </div>
</div>
<a href="#" data-bind="click: getRandomModel">Get random person</a>



ASP.NET MVC 5 Hosting - with ASPHostPortal.com :: How to Rendering ASP.NET MVC 1.0, 2.0 RC, 3 and 4 Razor Views to String

clock March 14, 2014 07:44 by author Diego

The ASP.NET MVC Razor implementation is closely tied to ASP.NET and MVC and the View template (WebViewPage class) includes a few MVC-specific features as well as back references to the controller. In other words MVC Razor is designed with MVC in mind. With Razor, you can create a custom Razor Engine that can be used in any .NET environment. Razor is the best view engine available for MVC as its much cleaner and easy to write and read. This view engine is compatible with unit testing frameworks. In this article, I will demonstrate how you can render ASP.NET MVC Razor Views in ASP.Net MVC 1.0, 2.0 RC, 3 and 4 .
Basically, all you do is create a fake HttpContext for the view to render itself.  This is an extensions method of the HtmlHelper that processes a partial view through the default MVC view engine and then renders it to the response stream.

Thisworks on ASP.NET MVC 1.0 (changing Headers on the original HttpResponse doesn't throwthe "Server cannot set content type after HTTP headers have been sent"exception).
/// <summary>Renders a view to string.</summary>
public static string RenderViewToString(this Controller controller, string viewName, object viewData) {


Create memory writer.

var sb = new StringBuilder();
var memWriter = new StringWriter(sb);


Create fake http context to render the view.

    var fakeResponse = new HttpResponse(memWriter);
    var fakeContext = new HttpContext(HttpContext.Current.Request, fakeResponse);
    var fakeControllerContext = new ControllerContext(
        new HttpContextWrapper(fakeContext),
        controller.ControllerContext.RouteData,
        controller.ControllerContext.Controller);
    var oldContext = HttpContext.Current;
    HttpContext.Current = fakeContext;
  Use HtmlHelper to render partial view to fake context.
    var html = new HtmlHelper(new ViewContext(fakeControllerContext,
        new FakeView(), new ViewDataDictionary(), new TempDataDictionary()),
        new ViewPage());
    html.RenderPartial(viewName, viewData);
Restore context.
    HttpContext.Current = oldContext;  
    //Flush memory and return output
    memWriter.Flush();
    return sb.ToString();}
Fake IView implementation used to instantiate an HtmlHelper.
public class FakeView : IView {
    #region IView Members
    public void Render(ViewContext viewContext, System.IO.TextWriter writer) {
        throw new NotImplementedException();
    }    #endregion
}

In ASP.NET MVC 2.0 RC, the code changes a bit because we have to pass in the StringWriter used to write the view into the ViewContext:
Use HtmlHelper to render partial view to fake context.

//...
var html = new HtmlHelper(
    new ViewContext(fakeControllerContext, new FakeView(),
        new ViewDataDictionary(), new TempDataDictionary(), memWriter),
    new ViewPage());
html.RenderPartial(viewName, viewData);
//...

In MVC 3 you can used this code :
public static string RazorRender(Controller context, string DefaultAction)
{
string Cache = string.Empty;
System.Text.StringBuilder sb = new System.Text.StringBuilder();
System.IO.TextWriter tw = new System.IO.StringWriter(sb);
RazorView view_ = new RazorView(context.ControllerContext, DefaultAction, null, false, null);
view_.Render(new ViewContext(context.ControllerContext, view_, new ViewDataDictionary(), new TempDataDictionary(), tw), tw);
Cache = sb.ToString();
return Cache;
}
public static string RenderRazorViewToString(string viewName, object model)
        {
ViewData.Model = model;
using (var sw = new StringWriter())
            {
var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
var viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
viewResult.View.Render(viewContext, sw);
return sw.GetStringBuilder().ToString();
}
}
public static class HtmlHelperExtensions
        {
public static string RenderPartialToString(ControllerContext context, string partialViewName, ViewDataDictionary viewData, TempDataDictionary tempData)
            {
ViewEngineResult result = ViewEngines.Engines.FindPartialView(context, partialViewName);
if (result.View != null)
                {
StringBuilder sb = new StringBuilder();
using (StringWriter sw = new StringWriter(sb))
                    {
using (HtmlTextWriter output = new HtmlTextWriter(sw))
                        {
ViewContext viewContext = new ViewContext(context, result.View, viewData, tempData, output);
result.View.Render(viewContext, output);
}
}
return sb.ToString();

}
return String.Empty;
            }
        }

This code worked in MVC 4 :
public string RenderRazorViewToString(string viewName, object model) {
    ViewData.Model = model;
    using (var sw = new StringWriter()) {
        var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
        var viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
        viewResult.View.Render(viewContext, sw);
        viewResult.ViewEngine.ReleaseView(ControllerContext, viewResult.View);
        return sw.GetStringBuilder().ToString();
    }
}

I hope you will enjoy this Article, and I hope you will refer this article for your need. Stay tuned and stay connected for more technical updates with ASPHostPortal



ASP.NET MVC 5 Hosting - with ASPHostPortal.com :: What are Differences ViewBag, ViewData and TempData in Asp.Net MVC 5 ?

clock March 12, 2014 05:49 by author Diego

In Asp.Net MVC 5 (Model-View-Controller) there are three options ViewBag, ViewData, and TempData to pass small amount of data from controller to view. In this article i am going to explain what is ViewBag, ViewData and TempData and their use in Asp.Net MVC 5.

A. ViewData & ViewBag objects.
ViewData
is a dictionary object that you put data into, which then becomes available to the view.It is an in-built dictionary object that is derived from ViewDataDictionary class that can be accessed and set with string type key values. It is a used to pass data from Controller to View. ViewData's value become null if redirection occur because its life lies only during current request.

Key points to remember about ViewData.

  • ViewData is a dictionary of objects that is derived from ViewDataDictionary class and accessible using strings as keys.
  • ViewData requires typecasting for complex data type and it is recommended to check for null values to avoid error.
  • ViewData is used to pass small amount of data from controller to view, so it helps to maintain data when moving from controller to view.
  • ViewData has short life i.e.  Its value becomes null when redirection occurs because its life lies only during current request. This is because the aim of ViewData is to provide a way to transfer/pass data from controllers and views.
  • ViewData is faster than ViewBag.

ViewData Example.
In View:

@ViewData["Name"]

ViewBag is dynamic object, meaning we can add properties to it in the controller, and read them later in the view. Its value becomes null when redirection occurs because its life lies only during current request. This is because the aim of ViewBag is to provide a way to transfer/pass data from controllers and views.

ViewBag Example:
In View:

@ViewBag.Name

Similarities between ViewBag & ViewData :
Both the ViewData and ViewBag objects are great for accessing extra data (i.e., outside the data model), between the controller and view. Since views already expect a specific object as their model, this type of data access to extra data, MVC implements it as a property of both views and controllers, making usage and access to these objects easy. Helps to maintain data when you move from controller to view. Used to pass data from controller to corresponding view. Short life means value becomes null when redirection occurs. This is because their goal is to provide a way to communicate between controllers and views. It’s a communication mechanism within the server call.

Difference between ViewBag & ViewData:

  • ViewData is a dictionary of objects that is derived from ViewDataDictionary class and accessible using strings as keys.
  • ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0.
  • ViewData requires typecasting for complex data type and check for null values to avoid error.
  • ViewBag doesn’t require typecasting for complex data type.

B. TempData Object.The problem with the ViewData and ViewBag for transferring data from controller to view is that the data is only alive for current request. The data is lost if a redirection takes place i.e. if one Action redirects to another action. But when we need to persist the data between actions/redirection then asp.net MVC offers another dictionary object called TempData for that purpose. It is derived from TempDataDictionary and created on top of session. It will live till the redirected view is fully loaded. “TempData”  Helps to maintain data when you move from one controller to other controller or from one action to other action.The benefit is that if you have a chain of multiple redirections it won’t cause TempData to be emptied the values will still be there until you actually use them, then they clear up after themselves automatically.

When to use TempData in ASP.NET MVC ?
Example condition :

I came across this problem where I had a basic list of items and for each if these items I wanted to add a delete action on my controller. I wanted to add some error checking around the delete action so if someone attempted to modify the URL and enter a incorrect parameter into my controller, I wanted to redirect back to the previous controller and notify the user of this mistake. Take this example. I have a Product Controller and the Index Action and View lists all of the products. I have a delete action on the Product Controller which checks if the productId parameter is valid and then removes the product and redirects to the Index action using the RedirectToAction method.

The solution :
When validating the productId, if its NOT valid simply add a new key/value to the TempData object and call the RedirectToAction method. TempData stores data for short periods of time for the current and next HTTP request. In your index view, you can check to see if your key/value pair exists and display a error message. If you refresh the page, you will notice the data from the TempData will be gone. Remember to use RedirectToAction where possible as this is more friendly with Unit Testing rather than using the HttpResponse redirect method.

I hope you have got what is ViewBag, ViewData and TempData in Asp.Net MVC and I hope you will refer this article for your need. Stay tuned and stay connected for more technical updates.



Cheap ASP.NET 4.5 Hosting

We’re a company that works differently to most. Value is what we output and help our customers achieve, not how much money we put in the bank. It’s not because we are altruistic. It’s based on an even simpler principle. "Do good things, and good things will come to you".

Success for us is something that is continually experienced, not something that is reached. For us it is all about the experience – more than the journey. Life is a continual experience. We see the Internet as being an incredible amplifier to the experience of life for all of us. It can help humanity come together to explode in knowledge exploration and discussion. It is continual enlightenment of new ideas, experiences, and passions


Author Link


 

Corporate Address (Location)

ASPHostPortal
170 W 56th Street, Suite 121
New York, NY 10019
United States

Tag cloud

Sign in