ASP.NET 4.5 and ASP.NET Core 1 Hosting BLOG

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

ASP.NET 4.5 Hosting - ASPHostPortal :: Timeout in Regular Expressions ASP.NET 4.5

clock December 10, 2015 21:07 by author Jervis

Regular expressions are common forms of parsing a document and get meaning. It has been very popular and most of the people do use it regularly to solve their complex problems.

Lets start by the new Regex Api introduced with the framework. The improvement that has been made is minor yet handy at certain cases. The Regex class of .NET 4.5 supports Timeout. Lets take a look how to work with it.

Lets try to write a simplest RegEx validator to look into it. 

Try
{
    Regex regexpr =
new Regex("[A-Z ]{10}", RegexOptions.Singleline, TimeSpan.FromMilliseconds(1));
    Match mch = regexpr.Match(
"ABHISHEK SUR");
   
if (mch.Success)
        Console.WriteLine(
"Match found");
   
else
        Console.WriteLine(
"Not matched");

}
catch (RegexMatchTimeoutException ex)
{
    Console.WriteLine(
"Regex Timeout for {1} after {2} elapsed. Tried pattern {0}", ex.Pattern, ex.Message, ex.MatchTimeout);
}
catch (ArgumentOutOfRangeException ex)
{
    Console.WriteLine(ex.ToString());
}
finally
{
    Console.ReadKey(
true);
}

Here in the code you can see I simply check a string with a Regular expression. It eventually finds success as Pattern matches the string. Now this code is little different than what we have been doing for last few years. The constructor overload of Regex now supports a Timespan seed, which indicates the timeout value after which the Regular expression validator would automatically generate a RegexMatchTimeoutException. The Match defined within the Regex class can generate timeout after a certain time exceeds.

 You can specify Regex.InfiniteMatchTimeout to specify that the timeout does not occur. The value of InfiniteMatchTimeout is -1ms internally and you can also use Timespan.Frommilliseconds(-1) as value for timespan which will indicate that the Regular expression will never timeout which being the default behavior of our normal Regex class. Regex also supports AppDomain to get default value of the Timeout. You can set timeout value for "REGEX_DEFAULT_MATCH_TIMEOUT" in AppDomain to set it all the way through the Regular expressions being used in the same AppDomain. Lets take a look how it works.

Try
{
    AppDomain.CurrentDomain.SetData("REGEX_DEFAULT_MATCH_TIMEOUT", TimeSpan.FromMilliseconds(2));

    Regex regexpr = new Regex("[A-Z ]{10}", RegexOptions.Singleline);
    Match mch = regexpr.Match("ABHISHEK SUR");
    if (mch.Success)
        Console.WriteLine("Match found");
    else
        Console.WriteLine("Not matched");

}
catch (RegexMatchTimeoutException ex)
{
    Console.WriteLine("Regex Timeout for {1} after {2} elapsed. Tried pattern {0}", ex.Pattern, ex.Message, ex.MatchTimeout);
}
catch (ArgumentOutOfRangeException ex)
{
    Console.WriteLine(ex.ToString());
}
finally
{
    Console.ReadKey(true);
}

Now this works exactly the same as the previous one. Here the Regex constructor automatically checks the AppDomain value and applies it as default. If it is not present, it will take -1 as default which is Infinite TImeout and also if explicitely timeout is specified after the default value from AppDomain, the Regex class is smart enough to use the explicitly set value only to itself for which it is specified. The Regex Constructor generates a TypeInitializationException if appdomain value of Timespan is invalid. Lets check the internal structure.

This is the actual code that runs in background and generates the timeouts. In fact while scanning the string with the pattern, there is a call to CheckTimeout which checks whether the time specified is elapsed for the object. The CheckTimeout throws the exception from itself.

The Constructor sets DefaultMatchTimeout when the object is created taking it from AppDomain data elements.

If you read MSDN thoroughly, it suggests to use Timeouts when specifying the Regular expressions. If the pattern is supplied from external or you are not sure about the pattern that needs to be applied to the string, it is always recommended to use Timeouts. Basically you should also specify a rational limit of AppDomain regex default to ensure no regular expression can ever hang your application.

This is a small tip on the new Regex enhancements introduced with .NET 4.5 recently.  

 



ASP.NET Hosting Tips - ASPHostPortal :: SQLParameters in ASP.NET C#

clock November 16, 2015 22:10 by author Jervis

SqlParameter represents a parameter to a SqlCommand and optionally its mapping to DataSet columns. Parameter names are not case sensitive. 

To initialize a new instance of SqlParameter class, we can use many constructors such as SqlParameter(), SqlParameter(String, SqlDbType), SqlParameter(String, Object), SqlParameter(String, SqlDbType, Int32), SqlParameter(String, SqlDbType, Int32, String). 

SqlParameter() constructor initialize a new instance of SqlParameter class. Sqlparameter(String, SqlDbType) constructor require parameter name and data type. SqlParameter(String, Object) constructor require parameter name and a value of the new SqlParameter. SqlParameter(String, SqlDbtype, Int32) constructor require parameter name, SqlDbType and size. SqlParameter(String, SqlDbtype, Int32, String) constructor require parameter name , SqlDbType, size and the source column name. 

SqlParameter class have many useful properties such as CompareInfo, DbType, Direction, IsNullable, Offset, ParameterName, Precision, Scale, Size, SourceColumn, SqlDbType, SqlValue, TypeName, Value, XmlSchemaCollectionName etc. 

ParameterName property get or set the SqlParameter name. SqlDbType property get or set the SqlDbType (SQL Server specific data type) for the parameter. SqlDbType enumeration values are BigInt, Binary, Bit, Char, Date, DateTime, Decimal, Float, Image, Int, Money, Real, Text, Time, Timestamp etc. SqlParameter Size property get or set the maximum size in bytes of the data within the column. Direction property get or set a value that indicate whether the parameter is input only, output only, bidirectional or a stored procedure return value parameter. Value property get or set the value of parameter. 

The following c# example source code describe you more about SqlParameter in ASP.NET. 

Create a web form name SqlParameterExample.aspx. Now add a GridView control. We populate the GridView control with SqlDataSource Data. But here we filter the data by SqlParameter. In this example we select the NorthWind database Products table data and filter it with SqlParameter product name. The source code of SqlParameterExample.aspx is here.

<%@ Page Language="C#" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<%@ Import Namespace="System.Configuration" %>

<!DOCTYPE html>

<script runat="server">
    protected void Page_Load(object sender, System.EventArgs e) {
        if (!Page.IsPostBack) {
            SqlConnection MyConnection;
            SqlCommand MyCommand;
            SqlDataReader MyReader;
            SqlParameter ProductNameParam;

            MyConnection = new SqlConnection();
            MyConnection.ConnectionString = ConfigurationManager.ConnectionStrings["AppConnectionString1"].ConnectionString;

            MyCommand = new SqlCommand();
            MyCommand.CommandText = "SELECT * FROM PRODUCTS WHERE PRODUCTNAME = @PRODUCTNAME";
            MyCommand.CommandType = CommandType.Text;
            MyCommand.Connection = MyConnection;

            ProductNameParam = new SqlParameter();
            ProductNameParam.ParameterName = "@PRODUCTNAME";
            ProductNameParam.SqlDbType = SqlDbType.VarChar;
            ProductNameParam.Size = 25;
            ProductNameParam.Direction = ParameterDirection.Input;
            ProductNameParam.Value = "CHAI";

            MyCommand.Parameters.Add(ProductNameParam);

            MyCommand.Connection.Open();
            MyReader = MyCommand.ExecuteReader(CommandBehavior.CloseConnection);

            GridView1.DataSource = MyReader;
            GridView1.DataBind();

            MyCommand.Dispose();
            MyConnection.Dispose();
        }
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>SqlParameter example: how to use SqlParameter in asp.net</title>
</head>
<body>
   
<form id="form1" runat="server">
   
<div>
       
<asp:GridView ID="GridView1" runat="server">
       
</asp:GridView>
   
</div>
   
</form>
</body>
</html>

 



ASPHostPortal.com Announces Reliable Zikula 1.4.0 Hosting Service

clock March 12, 2015 09:11 by author Ben


ASPHostPortal.com, the leader of ASP.NET & Windows hosting provider launches Reliable Zikula 1.4.0 Hosting with comprehensive package.


With the Best excellent service, ASPHostPortal.com is one of the primary Windows hosting providers providing good quality provider with quality assistance. Their servers are built using the most current know-how. They're enthusiastic about web hosting and attempt to deliver an outstanding degree of assistance to each customer. Their world wide web hosting options are well suited for tiny to medium-sized weblogs, personal, charity or business websites. Currently, they launch Zikula 1.4.0 Hosting with reliable technology and cost-effective value.

Zikula is an open source site builder that is quick and simple to use. Using a number of themes, plugins, and user-friendly tools, it is a simple and highly flexible method to get your business webpage, online shop, or blog up and running. Zikula is a powerful PHP-based application development framework which has content material management capabilities built-in. The idea is to expose all the functionality of a common Application Improvement Framework, with all the up-and-running ease of a conventional CMS.

This is achieved by constructing Zikula on top of other development frameworks and implementing a modular approach to feature development.

The day has ultimately come, ASPHostPortal.com Announces Reliable Zikula 1.4.0 Hosting. Zikula 1.4.0 has Symfony at it is foundation, which consists of Doctrine. And Zikula 1.4.0 integrates Twitter's Bootstrap 3 and Font Awesome 4 and utilizes jQuery for exciting web user-interfaces and effects.

"Zikula : an OpenSource PHP Application Framework and CMS for the site, No matter what your demands, Zikula can give the solution. Whether it is a big corporate web presence with ecommerce, a little basic blog or a community portal, Zikula can do it all. Zikula is infinitely expandable with modules and plugins that may add the functionality you need. And all with tomorrow's technology. Greatest of all, it really is totally totally free. ASPHostPortal provides you with the support and help you need," said Dean Thomas, Manager at ASPHostPortal.com.

With 7 data centers that located in USA, Europe, Australia and Asia, ASPHostPortal is superior provider in the hosting market place. They supplies Zikula 1.4.0 Hosting only from $5/month with 30 days funds back assure. Furthermore, ASPHostPortal has been awarded as one from the very best hosting firms within the market due to the excellent hosting overall performance this hosting offers. To supply ideal hosting functionality, this company often maintains the server with expert group in ASP.NET Technology. To learn a lot more about Zikula 1.4.0 Hosting, please visit http://asphostportal.com/Zikula-1-4-0-Hosting

About ASPHostPortal.com

ASPHostPortal.com will be the Reliable, Cheap and Recommended Windows & ASP.NET Hosting. ASPHostPortal.com has capability to support the latest Microsoft and ASP.NET technologies, such as: like: WebMatrix, WebDeploy, Visual Studio 2015, .NET 5/ASP.NET 5, ASP.NET MVC 6.0/5.2, Silverlight 6 and Visual Studio Lightswitch. ASPHostPortal include shared hosting, reseller hosting, and sharepoint hosting, with speciality in ASP.NET, SQL Server, and architecting very scalable options. ASPHostPortal.com strives to provide most likely the most technologically advanced hosting solutions obtainable to all customers the world over. Protection, trustworthiness, and efficiency are on the core of hosting operations to create particular each website and software hosted is so secured and performs at the ideal feasible level.




ASPHostPortal.com to Launch New Data Center in Hong Kong

clock November 25, 2014 08:10 by author Ben

ASPHostPortal.com to Start New Data Center in Hong Kong on November 2014

ASPHostPortal is known for credible and loyal hosting solutions. Apart from the reliability in the ASPHostPortal Uptime, which features 99.9 per cent common uptime, ASPHostPortal also provides outstanding data center which displays ASPHostPortal large speed and large overall performance web hosting package deal. Lately, ASPHostPortal.com launch its new Data Center in Hons Kong on November 2014 with space for more than 10.000 physical servers, and allowing customers’ to satisfy their  data residency needs.

The brand new facility will provide consumers and their finish customers with ASPHostPortal.com providers that meet up with in-country info residency needs. It will also complement the existing ASPHostPortal.com Asia (Singapore) Data Center. The Hong Kong Data Center will offer the full variety of ASPHostPortal.com website hosting infrastructure services, which includes bare steel servers, virtual servers, storage and networking.

ASPHostPortal offers the perfect mixture of affordability and dependability. They have an excellent uptime history with numerous months this 12 months boasting a lot more than 99.9% typical uptime. Their hosting bundle displays velocity and efficiency. Their information heart might take significantly from the credit rating for such superb providers. The brand new data center will allow clients to copy or integrate data between Asia Data Center with higher transfer speeds and unmetered bandwidth (at no charge) in between amenities.

“With ASPHostPortal, picking the Data Center area is really a totally free function and alternative to all consumers. The shopper just chooses US, Europe, Asia or Australia. It is straightforward, intuitive and convenient. The choice is totally free, and there will never be any other cost to the person related with this choice,” said Dean Thomas, Manager at ASPHostPortal.com.

Customers that have any questions on the feature and also the choice which is most suitable for his or her functions ought to truly feel totally free to get in touch with ASPHostPortal via their 24/7/365 customer assistance crew. ASPHostPortal may help you select the right choice that will best fit your needs.

To find out more about new data center in Hong Kong, please visit http://asphostportal.com/Hosting-Data-Center-HongKong.

About ASPHostPortal.com:

ASPHostPortal.com is a hosting business that greatest support in Windows and ASP.NET-based hosting. Solutions consist of shared web hosting, reseller hosting, and SharePoint hosting, with specialty in ASP.NET, SQL Server, and architecting very scalable solutions. Like a top little to mid-sized company web hosting provider, ASPHostPortal.com attempt to supply essentially the most technologically advanced hosting options obtainable to all customers across the world. Security, reliability, and efficiency are in the core of web hosting operations to make certain every site and/or software hosted is extremely secured and performs at ideal stage.

 



ASP.NET 4.5 HOSTING - ASPHostPortal.com :: A simple SPA with AngularJs, ASP.NET MVC, Web API and EF

clock November 14, 2014 06:41 by author Mark

Introduction

SPA stands for Single Page Application. Here I will demonstrate a simple SPA with ASP.NET MVC, Web API and Entity Framework. I will show a trainer profile and its CRUD operation using AngularJS, ASP.NET MVC, Web api and Entity Framework.

Step 1: Create a ASP.NET MVC application with empty template

  • Open visual studio, Got to File->New->Project
  • Select Template -> Visual C# -> Web -> ASP.NET MVC 4 Web application and click OK
  • Select Empty Template and Razor as view engine

Step 2: Install required packages

Run the following command in Package Manager Console (Tools->Library Package Manager->Package Manager Console) to install required package. Make sure your internet connection is enabled.

  • PM> Install-Package jQuery
  • PM> Install-Package angularjs -Version 1.2.26
  • PM> Install-Package Newtonsoft.Json
  • PM> Install-Package MvcScaffolding

Step 3: Create Connection String

Create connection string and name DB name as SPADB
    <connectionStrings>
  <add name="SPAContext" connectionString="Data Source=.\sqlexpress;Initial Catalog=SPADB;Integrated Security=SSPI;" providerName="System.Data.SqlClient" />
</connectionStrings>

Step 4: Create model

Create Trainer model
    public class Trainer
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public long Id { get; set; }
    public string Name { get; set; }
    public string Email { get; set; }
    public string Venue { get; set; }
}

Step 5: Create Repository

Create repository for Trainer model.

Run the following command in Package Manager Console (Tools->Library Package Manager->Package Manager Console) to create repository. I used repository pattern for well-structured and more manageable.

PM> Scaffold Repository Trainer

After running the above command you will see SPAContext.cs and TrainerRepository.cs created in Model folder. For well manageability, I create a directory name Repository and put these two files in the Repository folder. So change the namespace as like SPA.Repository instead of SPA.Model. I also create a UnitOfWork for implement unit of work pattern.
The overall folder structure looks like following. 
SPAContext.cs
    public class SPAContext : DbContext
{
    public SPAContext()
        : base("SPAContext")
    {
    }
    // You can add custom code to this file. Changes will not be overwritten.
    //
    // If you want Entity Framework to drop and regenerate your database
    // automatically whenever you change your model schema, add the following
    // code to the Application_Start method in your Global.asax file.
    // Note: this will destroy and re-create your database with every model change.
    //
    // System.Data.Entity.Database.SetInitializer(new System.Data.Entity.DropCreateDatabaseIfModelChanges<SPA.Models.SPAContext>());
    public DbSet<SPA.Models.Trainer> Trainers { get; set; }
    public DbSet<SPA.Models.Training> Trainings { get; set; }
}

TrainerRepository.cs
    public class TrainerRepository : ITrainerRepository
{
    SPAContext context = new SPAContext();
    public TrainerRepository()
        : this(new SPAContext())
    {
    }
    public TrainerRepository(SPAContext context)
    {
        this.context = context;
    }
    public IQueryable<Trainer> All
    {
        get { return context.Trainers; }
    }
    public IQueryable<Trainer> AllIncluding(params Expression<Func<Trainer, object>>[] includeProperties)
    {
        IQueryable<Trainer> query = context.Trainers;
        foreach (var includeProperty in includeProperties)
        {
            query = query.Include(includeProperty);
        }
        return query;
    }
    public Trainer Find(long id)
    {
        return context.Trainers.Find(id);
    }
    public void InsertOrUpdate(Trainer trainer)
    {
        if (trainer.Id == default(long))
        {
            // New entity
            context.Trainers.Add(trainer);
        }
        else
        {
            // Existing entity
            context.Entry(trainer).State = System.Data.Entity.EntityState.Modified;
        }
    }
    public void Delete(long id)
    {
        var trainer = context.Trainers.Find(id);
        context.Trainers.Remove(trainer);
    }
    public void Save()
    {
        context.SaveChanges();
    }
    public void Dispose()
    {
        context.Dispose();
    }
}
public interface ITrainerRepository : IDisposable
{
    IQueryable<Trainer> All { get; }
    IQueryable<Trainer> AllIncluding(params Expression<Func<Trainer, object>>[] includeProperties);
    Trainer Find(long id);
    void InsertOrUpdate(Trainer trainer);
    void Delete(long id);
    void Save();
}

UnitOfWork.cs
public class UnitOfWork : IDisposable
{
    private SPAContext context;
    public UnitOfWork()
    {
        context = new SPAContext();
    }
    public UnitOfWork(SPAContext _context)
    {
        this.context = _context;
    }
    private TrainingRepository _trainingRepository;
 
    public TrainingRepository TrainingRepository
    {
        get
        {
            if (this._trainingRepository == null)
            {
                this._trainingRepository = new TrainingRepository(context);
            }
            return _trainingRepository;
        }
    }
    private TrainerRepository _trainerRepository;
    public TrainerRepository TrainerRepository
    {
        get
        {
            if (this._trainerRepository == null)
            {
                this._trainerRepository = new TrainerRepository(context);
            }
            return _trainerRepository;
        }
    }
    public void Dispose()
    {
        context.Dispose();
        GC.SuppressFinalize(this);
    }
}

Step 6: Add migration

  • Run the following command to add migration
  • PM> Enable-Migrations
  • PM> Add-Migration initialmigration
  • PM> Update-Database –Verbose

Step 7: Create API Controllers

Create Trainers api Controllers by clicking right button on Controller folder and scaffold as follows.

Step 8: Modify Controllers

Now modify the controllers as follows. Here I used unit of work pattern.
    public class TrainersController : ApiController
{
    private UnitOfWork unitOfWork = new UnitOfWork();
    public IEnumerable<Trainer> Get()
    {
        List<Trainer> lstTrainer = new List<Trainer>();
        lstTrainer = unitOfWork.TrainerRepository.All.ToList();
        return lstTrainer;
    }
    //// GET api/trainers/5
    public Trainer Get(int id)
    {
        Trainer objTrainer = unitOfWork.TrainerRepository.Find(id);
        return objTrainer;
    }
    public HttpResponseMessage Post(Trainer trainer)
    {
        if (ModelState.IsValid)
        {
            unitOfWork.TrainerRepository.InsertOrUpdate(trainer);
            unitOfWork.TrainerRepository.Save();
            return new HttpResponseMessage(HttpStatusCode.OK);
        }
        return new HttpResponseMessage(HttpStatusCode.InternalServerError);
    }
    private IEnumerable<string> GetErrorMessages()
    {
        return ModelState.Values.SelectMany(x => x.Errors.Select(e => e.ErrorMessage));
    }
    // PUT api/trainers/5
    public HttpResponseMessage Put(int Id, Trainer trainer)
    {
        if (ModelState.IsValid)
        {
            unitOfWork.TrainerRepository.InsertOrUpdate(trainer);
            unitOfWork.TrainerRepository.Save();
            return new HttpResponseMessage(HttpStatusCode.OK);
        }
        else
            return new HttpResponseMessage(HttpStatusCode.InternalServerError);
    }
    // DELETE api/trainers/5
    public HttpResponseMessage Delete(int id)
    {
        Trainer objTrainer = unitOfWork.TrainerRepository.Find(id);
        if (objTrainer == null)
        {
            return new HttpResponseMessage(HttpStatusCode.InternalServerError);
        }
        unitOfWork.TrainerRepository.Delete(id);
        unitOfWork.TrainerRepository.Save();
        return new HttpResponseMessage(HttpStatusCode.OK);
    }
}

Step 9: Create Layout and Home Controller

Create _Layout.cshtml in Views->Shared folder and create HomeController and create inext view of Home controller by right click on index action and add view. You will see index.cshtml is created in Views->Home
Home Controller
    public class HomeController : Controller
{
    //
    // GET: /Home/
 
    public ActionResult Index()
    {
        return View();
    }
}

_Layout.cshtml
    <html ng-app="registrationModule">
<head>
    <title>Training Registration</title>
</head>
<body>
    @RenderBody()
</body>
</html>
Index.cshtml
    @{
    ViewBag.Title = "Home";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Home</h2>
<div>
    <ul>     
        <li><a href="/Registration/Trainers">Trainer Details</a></li>
        <li><a href="/Registration/Trainers/add">Add New Trainer</a></li>
    </ul>
</div>
<div ng-view></div>

Step 10: Create registrationModule

Create registrationModule.js in Scripts->Application. This is for angularjs routing.
    var registrationModule = angular.module("registrationModule", ['ngRoute', 'ngResource'])
    .config(function ($routeProvider, $locationProvider) {
        $routeProvider.when('/Registration/Trainers', {
            templateUrl: '/templates/trainers/all.html',
            controller: 'listTrainersController'
        });
        $routeProvider.when('/Registration/Trainers/:id', {
            templateUrl: '/templates/trainers/edit.html',
            controller: 'editTrainersController'
        });
        $routeProvider.when('/Registration/Trainers/add', {
            templateUrl: '/templates/trainers/add.html',
            controller: 'addTrainersController'
        });
        $routeProvider.when("/Registration/Trainers/delete/:id", {
            controller: "deleteTrainersController",
            templateUrl: "/templates/trainers/delete.html"
        });
        $locationProvider.html5Mode(true);
    });

Step 11: Create trainerRepository

Create trainerRepository.js in Scripts->Application->Repository. This increase manageability for large application.
    'use strict';
//Repository for trainer information
registrationModule.factory('trainerRepository', function ($resource) {
    return {
        get: function () {
            return $resource('/api/Trainers').query();
        },
        getById: function (id) {
            return $resource('/api/Trainers/:Id', { Id: id }).get();
        },
        save: function (trainer) {
            return $resource('/api/Trainers').save(trainer);
        },
        put: function (trainer) {
            return $resource('/api/Trainers', { Id: trainer.id },
                {
                    update: { method: 'PUT' }
                }).update(trainer);
        },
        remove: function (id) {
            return $resource('/api/Trainers').remove({ Id: id });
        }
    };
});

Step 12: Create trainerController

Create trainerController.js in Scripts->Application->Controllers
    'use strict';
//Controller to get list of trainers informaion
registrationModule.controller("listTrainersController", function ($scope, trainerRepository, $location) {
    $scope.trainers = trainerRepository.get();
});
//Controller to save trainer information
registrationModule.controller("addTrainersController", function ($scope, trainerRepository, $location) {
    $scope.save = function (trainer) {
        trainer.Id = 0;
        $scope.errors = [];
        trainerRepository.save(trainer).$promise.then(
            function () { $location.url('Registration/Trainers'); },
            function (response) { $scope.errors = response.data; });
    };
});

//Controller to modify trainer information
registrationModule.controller("editTrainersController", function ($scope,$routeParams, trainerRepository, $location) {
    $scope.trainer = trainerRepository.getById($routeParams.id);
    $scope.update = function (trainer) {
        $scope.errors = [];
        trainerRepository.put(trainer).$promise.then(
            function () { $location.url('Registration/Trainers'); },
            function (response) { $scope.errors = response.data; });
    };
});
//Controller to delete trainer information
registrationModule.controller("deleteTrainersController", function ($scope, $routeParams, trainerRepository, $location) {
        trainerRepository.remove($routeParams.id).$promise.then(
            function () { $location.url('Registration/Trainers'); },
            function (response) { $scope.errors = response.data; });
});

Step 13: Create templates

Create all.html, add.html, edit.html, delete.html in templateds->trainers folder.
All.html
    <div>
    <div>
        <h2>Trainers Details</h2>
    </div>
</div>
<div>
    <div>
        <table>
            <tr>
                <th>Name </th>
                <th>Email </th>
                <th>Venue </th>
                <th>Action</th>
            </tr>
            <tr ng-repeat="trainer in trainers">
                <td>{{trainer.name}}</td>
                <td>{{trainer.email}}</td>
                <td>{{trainer.venue}}</td>
                <td>
                    <a title="Delete" ng-href="/Registration/Trainers/delete/{{trainer.id}}">Delete</a>
                    |<a title="Edit" ng-href="/Registration/Trainers/{{trainer.id}}">Edit</a>
                </td>
            </tr>
        </table>
    </div>
</div>

Add.html
    <form name="trainerForm" novalidate ng-submit="save(trainer)">
    <table>
        <tbody>
            <tr>
                <td>Trainer Name
                </td>
                <td>
                    <input name="name" type="text" ng-model="trainer.name" required ng-minlength="5" />
                </td>
            </tr>
            <tr>
                <td>Email
                </td>
                <td>
                    <input name="email" type="text" ng-model="trainer.email" />
                </td>
            </tr>
            <tr>
                <td>Venue
                </td>
                <td>
                    <input name="venue" type="text" ng-model="trainer.venue" />
                </td>
            </tr>
            <tr>
                <td class="width30"></td>
                <td>
                    <input type="submit" value="Save" ng-disabled="trainerForm.$invalid" />
                    <a href="/Registration/Trainers" class="btn btn-inverse">Cancel</a>
                </td>
            </tr>
        </tbody>
    </table>
</form>
Edit.html
    <form name="trainerFrom" novalidate abide>
    <table>
        <tbody>
            <tr>
                <td>
                    <input name="id" type="hidden" ng-model="trainer.id"/>
                </td>
            </tr>
            <tr>
                <td>Name
                </td>
                <td>
                    <input name="name" type="text" ng-model="trainer.name" />
                </td>
            </tr>
            <tr>
                <td>Email
                </td>
                <td>
                    <input name="email" type="text" ng-model="trainer.email" />
                </td>
            </tr>
            <tr>
                <td>Venue
                </td>
                <td>
                    <textarea name="venue" ng-model="trainer.venue"></textarea>
                </td>
            </tr>
            <tr>
                <td class="width30"></td>
                <td>
                    <button type="submit" class="btn btn-primary" ng-click="update(trainer)" ng-disabled="trainerFrom.$invalid">Update</button>
                </td>
            </tr>
        </tbody>
    </table>
</form>

Step 14: Add references to the Layout

Modify the _Layout.cshtml to add references
_Layout.cshtml
    <html ng-app="registrationModule">
<head>
    <title>Training Registration</title>
    <script src="~/Scripts/angular.min.js"></script>
    <script src="~/Scripts/angular-resource.min.js"></script>
    <script src="~/Scripts/angular-route.min.js"></script>
    <script src="~/Scripts/jquery-2.1.1.min.js"></script>
    <script src="~/Scripts/Application/registrationModule.js"></script>
    <script src="~/Scripts/Application/Repository/trainerRepository.js"></script>
    <script src="~/Scripts/Application/Controllers/trainersController.js"></script>
</head>
<body>
    @RenderBody()
</body>
</html>

Now run you application and add, delete, modify and get all trainer information. Thanks for your patient! Laughing



ASP.NET 4.5 HOSTING - ASPHostPortal :: Design application layout by bootstrap theme

clock November 12, 2014 06:48 by author Mark

To design layout of your web site is much more cumbersome. But you can easily design your website layout by bootstrap, you can make it responsive also.

Step 1: Create a ASP.NET MVC application with empty template

  • Open visual studio, Got to File->New->Project
  • Select Template -> Visual C# -> Web -> ASP.NET MVC  Web application and click OK
  • Select Empty Template and Razor as view engine

Step 2: Install required packages

  • Run the following command in Package Manager Console (Tools->Library Package Manager->Package Manager Console) to install required package. Make sure your internet connection is enabled.

PM> Install-Package bootstrap

Step 3: Download bootstrap theme

  • Go to http://bootswatch.com/ . Download any theme (bootstrap.css) like below and pest the content in Contents -> bootstrap-main-theme.css file

Step 4: Create a Layout page

  • Create a _Layout.cshtml in Views->Shared folder and add the following references.

_Layout.cshtml

<!DOCTYPE html>
<html>
<head>
    <title>Bootstrap theme test</title>
    <link href="~/Content/bootstrap.min.css" rel="stylesheet" />
    <link href="~/Content/bootstrap-main-theme.css" rel="stylesheet" />
    <script src="~/Scripts/jquery-1.9.1.min.js"></script>
    <script src="~/Scripts/bootstrap.js"></script>
 </head>
<body>  
    <div>
        @RenderBody()
    </div>
</body>
</html>

Step 5: Create HomeController and index view

  • Create HomeController and create index view. Right click on index action of home controller you will see index.cshtml file created in Views->Home folder. Modify the index.cshtml file like following

Index.cshtml

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
 <h2>Home Page</h2>

Step 6: Add Navigation bar

  • If you go the preview of the theme you will see some sample code or documentation. You can customize later. To add navigation bar to the website I modify the _Layout.cshtml like following.

_Layout.cshtml

<!DOCTYPE html>
 <html>
<head>
    <title>Bootstrap theme test</title>
    <link href="~/Content/bootstrap.min.css" rel="stylesheet" />
    <link href="~/Content/bootstrap-main-theme.css" rel="stylesheet" />
    <script src="~/Scripts/jquery-1.9.1.min.js"></script>
    <script src="~/Scripts/bootstrap.js"></script>
 </head>
<body>
    <div class="navbar navbar-inverse">
  <div class="navbar-header">
    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-inverse-collapse">
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
    </button>
    <a class="navbar-brand" href="#">Brand</a>
  </div>
  <div class="navbar-collapse collapse navbar-inverse-collapse">
    <ul class="nav navbar-nav">
      <li class="active"><a href="#">Active</a></li>
      <li><a href="#">Link</a></li>
      <li class="dropdown">
        <a href="#" class="dropdown-toggle" data-toggle="dropdown">Dropdown <b class="caret"></b></a>
        <ul class="dropdown-menu">
          <li><a href="#">Action</a></li>
          <li><a href="#">Another action</a></li>
          <li><a href="#">Something else here</a></li>
          <li class="divider"></li>
          <li class="dropdown-header">Dropdown header</li>
          <li><a href="#">Separated link</a></li>
          <li><a href="#">One more separated link</a></li>
        </ul>
      </li>
    </ul>
    <form class="navbar-form navbar-left">
      <input type="text" class="form-control col-lg-8" placeholder="Search">
    </form>
    <ul class="nav navbar-nav navbar-right">
      <li><a href="#">Link</a></li>
      <li class="dropdown">
        <a href="#" class="dropdown-toggle" data-toggle="dropdown">Dropdown <b class="caret"></b></a>
        <ul class="dropdown-menu">
          <li><a href="#">Action</a></li>
          <li><a href="#">Another action</a></li>
          <li><a href="#">Something else here</a></li>
          <li class="divider"></li>
          <li><a href="#">Separated link</a></li>
        </ul>
      </li>
    </ul>
  </div>
</div>
    <div>
        @RenderBody()
    </div>
</body>
</html>

Now run the application, you will get a nice layout. Thanks for your patient Smile



ASP.NET 4.5 Hosting - ASPHostPortal.com :: How to use Rangevalidator control in ASP.NET 4.5

clock November 7, 2014 06:26 by author Mark

If you want to understand how RangeValidator  control work in ASP.NET 4.5 Now, we will discuss about How to Use Rangevalidator control in ASP.NET 4.5. Rangevalidator control is used to check if the value is within a specified range of values. For example, Rangevalidator can be used to check if the age between 1 until 100.

In the codesnippet below, TextBox txtAge get age of the person. If User fill with any number that isn’t between 1 – 100 the validation fails. The minimum and maximum value for the age is specified by MinimumValue and MaximumValue properties. Since, Age is an integer, the Type is specified as integer. Write the code below:

&lt;asp:TextBox ID="txtAge" runat="server"&gt;&lt;/asp:TextBox&gt;
&lt;asp:RangeValidator ID="RangeValidator1" runat="server"
    ErrorMessage="Age must be between 1 &amp; 100"
    MinimumValue="1" MaximumValue="100"
    ControlToValidate="txtAge" Type="Integer" &gt;
&lt;/asp:RangeValidator&gt;

Properties for Rangevalidator control:

Type – Specifies the data type of the value to check. Data types supported include Currency, Date, Double, Integer and String.

MinimumValue – Minimum value that allowed

MaximumValue – Max value allowed in that field

The Rangevalidator only checks if the data is within the allowed range. If you wanna check for a required field, use RequiredFieldValidator. In the Age field, I am using both RequiredFieldValidator & RangeValidator. In this example I am using the Display property. If the Display property is not set, or, if it is set to static, then the error message will be rendered, with style visibility:hidden. Then the error message will always occupy the gap on the screen even if the validation passes.

<table>
    <tr>
        <td>
            <b>Age</b>
        </td>
        <td>
            :<asp:TextBox ID="txtAge" runat="server" Width="150px">
                </asp:TextBox>
            <asp:RangeValidator ID="RangeValidatorAge" runat="server"
                ErrorMessage="Age must be between 1 & 100"
                MinimumValue="1" MaximumValue="100"
                ControlToValidate="txtAge" Type="Integer"
                ForeColor="Red" Display="Dynamic">
            </asp:RangeValidator>
            <asp:RequiredFieldValidator ID="RequiredFieldValidatorAge"
            runat="server" ErrorMessage="Age is required"
            ControlToValidate="txtAge" ForeColor="Red"
            Display="Dynamic" >
            </asp:RequiredFieldValidator>
        </td>
    </tr>
    <tr>
        <td>
            <b>Date Available</b>
        </td>
        <td>
            :<asp:TextBox ID="txtDateAvailable" runat="server" Width="150px">
            </asp:TextBox>
            <asp:RangeValidator ID="RangeValidatorDateAvailable" runat="server"
                ErrorMessage="Date must be between 01/01/2012 & 31/12/2012"
                MinimumValue="01/01/2012" MaximumValue="31/12/2012"
                ControlToValidate="txtDateAvailable" Type="Date"
                ForeColor="Red">
            </asp:RangeValidator>
        </td>
    </tr>
    <tr>
        <td colspan="2">
            <asp:Button ID="btnSave" runat="server" Text="Save" Width="100px"
                onclick="btnSave_Click" />
        </td>
    </tr>
    <tr>
        <td colspan="2">
            <asp:Label ID="lblStatus" runat="server" Font-Bold="true">
            </asp:Label>
        </td>
    </tr>
</table>

This pushes “Age is Required” error message to the correct. To correct this we’ve got set Display=”Dynamic”. This renders the error message with style display:none. If a tag has this style, it’ll not occupy space when not visible.
Code-Behind page code
:
protected void btnSave_Click(object sender, EventArgs e)
{
    if (Page.IsValid)
    {
        lblStatus.ForeColor = System.Drawing.Color.Green;
        lblStatus.Text = "Data Saved successfully";
    }
    else
    {
        lblStatus.ForeColor = System.Drawing.Color.Red;
        lblStatus.Text = "Validation Failed! Data not saved";
    }
}

Display property is supported by all validation controls

None – Error message not rendered and displayed next to the control. used to show the error message only within the ValidationSummary control

Static – The error message is displayed next to the control if validation fails. space is reserved on the page for the message although validation succeeds. The span tag is rendered with style visibility:hidden

Dynamic – The error message is displayed next to the control if validation fails. space isn’t reserved on the page for the message if the validation succeeds. The span tag is rendered with style display:none.

 

 

 



ASP.NET MVC 5 Hosting - ASPHostPortal :: How to Perform Code First Migration in MVC 5

clock July 16, 2014 08:39 by author Jervis

In today post, I will explain Code Migration in MVC application. This migration helps you to update and change the data model that you’ve created for application and you don't need to re-create or drop your database.

 

How to Apply Code First Migration

The data model in the database usually changes after developing the new application. When the data model changes, it becomes out of sync with the database. We've configured our Entity Framework in the app to drop and recreate the data model automatically. When any type of change is done in the entity classes or in the DbContext class, the existing database is deleted and the new database is created that matches the model and sees it with test data.

When the application runs in production, we do not want to lose everything each time we make changes like adding a column. The Code First Migration solved this problem by enabling the code first to update the database instead of dropping or recreating.

The procedure is following:

1. Disable the Database Initializer in the Web.Config file.

The following is the example:

<!--<contexts>

      <context type="Vag_Infotech.DAL.CollegeDbContext, Vag_Infotech">
        <databaseInitializer type="Vag_Infotech.DAL.CollegeDatabaseInitializer, Vag_Infotech"></databaseInitializer>
      </context>
</contexts>--> 

And also you need to change your Global.asax file:

// Database.SetInitializer(new CollegeDatabaseInitializer()); 

2. Change your database name in your web.config file:

<connectionStrings
  <add name="CollegeDbContext" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=VInfotechNew;Integrated Security=SSPI" providerName="System.Data.SqlClient" />
</
connectionStrings> 

3. Open the Package Manager Console and enter this command:

enable-migration

add-migration InitialCreate 

Then, you will see the solution explorer below:

How to Edit Seed Method

Now, we add new code for updating our data model in this method. When we do not use the migration, the data model is dropped or re-created during the execution of the application each time, but now the data is retained after database changes.

Here are the steps to edit seed method:

1. Modify your configuration.cs file with this code:

namespace Vag_Infotech.Migrations
{
    using System;
    using System.Collections.Generic;
    using System.Data.Entity;
    using System.Data.Entity.Migrations;
    using System.Linq;
    using Vag_Infotech.Models;
 
    internal sealed class Configuration : DbMigrationsConfiguration<Vag_Infotech.DAL.CollegeDbContext>
    {
        public Configuration()
        {
            AutomaticMigrationsEnabled = false;
        }
 
        protected override void Seed(Vag_Infotech.DAL.CollegeDbContext context)
        {
            var New_Students = new List<Student>
            {
                new Student{FirstName="Louis",LastName="Fordsen",
                    EnrollmentDate=DateTime.Parse("2009-07-01")},
                new Student{FirstName="David ",LastName="Roger",
                    EnrollmentDate=DateTime.Parse("2009-07-01")},
                new Student{FirstName="Mike",LastName="Upson",
                    EnrollmentDate=DateTime.Parse("2009-07-05")},
            };
            New_Students.ForEach(ns => context.Students.AddOrUpdate(p => p.LastName, ns));
            context.SaveChanges();
 
            var New_Courses = new List<Course>
            {
                new Course{CourseID=201,Name="MCA",Credit=3,},
                new Course{CourseID=202,Name="M.Sc.IT",Credit=2,},
                new Course{CourseID=203,Name="M.Tech.CS",Credit=2,},
                new Course{CourseID=204,Name="M.Tech.IT",Credit=4,}
            };
            New_Courses.ForEach(ns => context.Courses.AddOrUpdate(p => p.Name, ns));
            context.SaveChanges();
 
            var New_Enrollments = new List<Enrollment>
            {
                new Enrollment{
                    StudentID= New_Students.Single(ns=>ns.FirstName=="Louis").ID,
                    CourseID=New_Courses.Single(nc=>nc.Name=="MCA").CourseID,
                    Grade=StudentGrade.A
                },
                new Enrollment{
                    StudentID= New_Students.Single(ns=>ns.FirstName=="David").ID,
                    CourseID=New_Courses.Single(nc=>nc.Name=="M.Tech.IT").CourseID,
                    Grade=StudentGrade.B
                },
                new Enrollment{
                    StudentID= New_Students.Single(ns=>ns.FirstName=="Mike").ID,
                    CourseID=New_Courses.Single(nc=>nc.Name=="M.Tech.CS").CourseID,
                    Grade=StudentGrade.D
                },
            };
 
            foreach (Enrollment et in New_Enrollments)
            {
                var NewEnrollDb = context.Enrollments.Where(
                    ns => ns.Student.ID == et.StudentID &&
                        ns.Course.CourseID == et.CourseID).SingleOrDefault();
                if (NewEnrollDb == null)
                {
                    context.Enrollments.Add(et);
                }
            }
            context.SaveChanges();
        }
    }
}

In the code above the Seed() takes the context object as an input argument and in the code the object is used to add the entities to the database. We can see how the code creates the collection for the database for each entity type and then saves it by SaveChanges() and adds it through the DbSet property. It is not necessary to call the SaveChanges() after each group of entities.

2. Build the solution

How to Execute the Migration

Here are steps:

1. Enter this command on Package Manager Console:

Update-database

2. Run the application and you’ll see the change



Free Trial Web Deploy 3.5 Hosting :: ASPHostPortal.com Proudly Launches Web Deploy 3.5 Hosting

clock November 1, 2013 10:44 by author Mike

Professional web hosting provider – ASPHostPortal.com proudly announced the integration of the latest Web Deploy 3.5 in all  web hosting plans. We are the first few hosting company that provide ASP.NET hosting plan that support the brand new Web  Deploy 3.5 Hosting.


WebDeploy v3.5 is now available and there are a few features to consider in this minor release:

  1. Load Balancer Support with Session Affinity. 
  2. Encrypting web.config Settings Post-Publish.
  3. App Offline Template.
  4. Seamless integration with IIS Manager (IIS7 and above), Visual Studio (2010 and above) for creating packages and  deploying them onto a machine, both locally and remotely.
  5. Integration with WebMatrix for deploying and downloading web applications.
  6. Seamless integration with the Web Platform Installer to install community web applications simply and easily.
  7. Web application packaging and deployment.
  8. Web server migration and synchronization.
  9. Automatic backup of Web Sites before making any changes.
  10. In addition to the IIS Manager, Visual Studio 10, Web Matrix tasks can be performed using the command-line, PowerShell  Cmdlets or public APIs.

According to ASPHostPortal.com, it's Web Deploy 3.5 offerings are distinguished by their low cost, with many of the hosting  services supporting the technology being of the more expensive variety.
For more information about this topics or have any enquiries related to Web Deploy 3.5 hosting, please visit  http://www.asphostportal.com

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 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 Hosting - ASPHostPortal.com :: Making Your Existing ASP.NET MVC Web Site Mobile Friendly

clock September 26, 2013 05:58 by author Ben

This article will show you the basic mobile features of ASP.NET MVC 4.0. We will make the following changes using CSS and ASP.NET to an existing web site to make it more user-friendly on mobile devices: 

  • Content will fit the small screen 
  • One-direction scrolling either horizontally or vertically but not both 
  • Clean and efficient design 
  • An option to visit the desktop site 


The following is a collage of the various desktop views for the Contact controller.

Responsive Design and Mobile Views

As we saw above, the application uses the default ASP.NET MVC Template. This template uses responsive design techniques using the viewport meta-tag to pick up appropriate CSS styles. The view-port is specified in _Layout.cshtml. It essentially sets the device-width reported by the browser as the width of the content frame.



Using the CSS Media queries in the Site.css, the browser switches UI based on the width of the device


As we can see above, the Media query defines a set of CSS style for width up to 850 pixels. Any width lesser than 850px is considered a mobile view in the default CSS.

With the Responsive Design in place, if we look at the site on a Mobile device, this is how it looks

Except for the Index page, the rest are usable but they look out of place or retro-fitted.

Adding First Class Mobile Support using jQuery Mobile

Now that we’ve seen the limitations for Responsive CSS, let’s explore dedicated Mobile Views and the special MVC ViewSwitcher.

- From Package Manager Console, install the jQuery.Mobile.Mvc package as follows

PM> install-package jQuery.Mobile.MVC

- This installs a host of things including jQuery Mobile UI Themes, a new Configuration file called BundleMobileConfig, a new Controller called ViewSwitcherController, an empty Context file called AddingMobileSupportToMVCContext, _Layout.Mobile.cshtml and _ViewSwitcher.cshtml.


The _ViewSwitcher.cshtml checks if the browser is Mobile browser or not and generates an appropriate link to switch views. ViewSwitcherController uses the value passed to it when user clicks on the View Switcher link and switches to the appropriate view. We’ll see what we mean by Appropriate View in the next section.

_Layout.Mobile.cshtml

As we saw, this partial view was added when we added the jQuery Mobile package. The .Mobile convention is baked into MVC and when the GetOverriddenBrowser().IsMobileDevice returns true, MVC goes and checks for .Mobile.cshtml files and starts rendering them as available. So if you only have the _Layout.Mobile.cshtml and no Index.Mobile.cshtml in your view folder, MVC will fall back on the standard Index.cshtml view while using the _Layout.Mobile.cshtml as the default layout.

This is a VERY powerful mechanism we’ve got here.

It’s worth noting .Mobile is not hardcoded, rather the default. We can have .WP7, .WP8, .Iphone, .Android or any such specially targeted views as we deem required.

With the ViewSwitcher and _Layout.Mobile.cshtml in place, now if we run the application, the Home page and Edit page look as follows. Note only the underlying _Layout page has changed to _Layout.Mobile. No new views have been introduced.

 



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