European ASP.NET MVC Hosting

BLOG about Latest ASP.NET MVC Hosting and Its Technology - Dedicated to European Windows Hosting Customer

ASP.NET MVC Hosting - HostForLIFE.eu :: Dynamic am-Charts In ASP.NET MVC

clock July 30, 2019 12:17 by author Peter

Here, we will learn about creating dynamic am-charts in ASP.NET MVC 5. Charts are very useful for seeing how much work is done in any place in a short period of time.

Prerequisites

  • Basic knowledge of jQuery.
  • Data from which we can generate the charts.

Create a new project in ASP.NET MVC
We are going to use the following jQuery libraries provided by amCharts.
<script src="https://www.amcharts.com/lib/4/core.js"></script>    
<script src="https://www.amcharts.com/lib/4/charts.js"></script>     
<script src="https://www.amcharts.com/lib/4/plugins/forceDirected.js"></script>    
<script src="https://www.amcharts.com/lib/4/themes/animated.js"></script> 
    

We are going to use the dummy API for the chart data.
https://api.myjson.com/bins/zg8of

Open the View -> Home -> Index.cshtml and write the code for generating the chart.
@{    
ViewBag.Title = "AM Chart Demo";    
}    

<div id="chartData"></div>    

@Scripts.Render("~/bundles/jquery")    

<script src="https://www.amcharts.com/lib/4/core.js"></script>    
<script src="https://www.amcharts.com/lib/4/charts.js"></script>    
<script src="https://www.amcharts.com/lib/4/plugins/forceDirected.js"></script>    
<script src="https://www.amcharts.com/lib/4/themes/animated.js"></script>    

<script>    
$(document).ready(function () {    
$.ajax({    
    url: 'https://api.myjson.com/bins/zg8of',    
    method: 'GET', success: function (data) {    
        generateChart(data);    
    }, error: function (err) {    
        alert("Unable to display chart. Something went wrong.");    
    }    
});    

function generateChart(data, iteration = 0) {    
    var dates = [];    
    var newData = [];    
    var gr = [];    

    function groupBy(array, f) {    
        var groups = {};    
        array.forEach(function (o) {    
            var group = JSON.stringify(f(o));    
            groups[group] = groups[group] || [];    
            groups[group].push(o);    
        });    
        return Object.keys(groups).map(function (group) {    
            return groups[group];    
        })    
    }    
    var result = groupBy(data, function (item) {    
        return ([item.Name]);    
    });    
    $.each(result, function (a, b) {    
        var d1 = b.map(function (i) {    
            return i.Month;    
        });    
        $.extend(true, dates, d1);    
    });    
    $.each(dates, function (a, b) {    
        var item = {    
            sales_figure: b    
        };    
        $.each(result, function (i, c) {    
            el = c.filter(function (e) {    
                return e.Month == b;    
            });    
            if (el && el.length > 0) {    
                item[c[i].Name.toUpperCase()] = el[0].Sales_Figure;    
                if (gr.filter(function (g) {    
                    return g == c[i].Name.toUpperCase();    
                }).length <= 0) {    
                    gr.push(c[i].Name.toUpperCase());    
                }    
            }    
        });    
        if (Object.keys(item).length > 1) newData.push(item);    
    });    
    $chartData = $('#chartData');    
    var am_el = $('<div id="dc-' + iteration + '" class="col-md-12 col-xs-12 card-item">');    
    am_el.append($('<div class="lgnd col-md-12 col-xs-12 bb2"><div id="l-' + iteration + '" class="col-md-12 col-xs-12"></div></div>'));    
    am_el.append($('<div id="c-' + iteration + '" class="col-md-12 col-xs-12" style="min-height:250px ; margin-left: -8px;">'));    
    $chartData.html(am_el);    
    var chart = am4core.create("c-" + iteration, am4charts.XYChart);    
    am4core.options.minPolylineStep = Math.ceil(newData.length / 50);    
    am4core.options.commercialLicense = true;    
    am4core.animationDuration = 0;    
    chart.data = newData;    
    var categoryAxis = chart.xAxes.push(new am4charts.CategoryAxis());    
    categoryAxis.dataFields.category = "sales_figure";    
    categoryAxis.renderer.minGridDistance = 70;    
    categoryAxis.fontSize = 12;    
    var valueAxis = chart.yAxes.push(new am4charts.ValueAxis());    
    valueAxis.fontSize = 12;    
    valueAxis.title.text = "Sales Figure";    
    chart.legend = new am4charts.Legend();    
    chart.legend.position = "top";    
    chart.legend.fontSize = 12;    
    var markerTemplate = chart.legend.markers.template;    
    markerTemplate.width = 10;    
    markerTemplate.height = 10;    
    var legendContainer = am4core.create("l-" + iteration, am4core.Container);    
    legendContainer.width = am4core.percent(100);    
    chart.legend.parent = legendContainer;    
    var legendDiv = document.getElementById("l-" + iteration);    

    function resizeLegendDiv() {    
        legendDiv.style.height = chart.legend.measuredHeight + "px";    
        legendDiv.style.overflow = "hidden";    
    }    
    chart.legend.events.on('inited', resizeLegendDiv);    
    chart.colors.list = [am4core.color("#0D8ECF"), am4core.color("#FF6600"), am4core.color("#FCD202"), am4core.color("#B0DE09"), am4core.color("#2A0CD0"), am4core.color("#CD0D74"), am4core.color("#CC0000"), am4core.color("#00CC00"), am4core.color('#ffd8b1'), am4core.color("#990000"), am4core.color('#4363d8'), am4core.color('#e6194b'), am4core.color('#3cb44b'), am4core.color('#ffe119'), am4core.color('#f58231'), am4core.color('#911eb4'), am4core.color('#46f0f0'), am4core.color('#f032e6'), am4core.color('#bcf60c'), am4core.color('#fabebe'), am4core.color('#008080'), am4core.color('#e6beff'), am4core.color('#9a6324'), am4core.color('#fffac8'), am4core.color('#800000'), am4core.color('#aaffc3'), am4core.color('#808000'), am4core.color('#ffd8b1'), am4core.color('#000075')] $.each(gr, function (l, d) {    
        var series = chart.series.push(new am4charts.LineSeries());    
        series.dataFields.valueY = d;    
        series.name = d;    
        series.dataFields.categoryX = "sales_figure";    
        series.tooltipText = "{name}: [bold]{valueY}[/]";    
        series.strokeWidth = 2;    
        series.minBulletDistance = 30;    
        series.tensionX = 0.7;    
        series.legendSettings.labelText = "[bold]" + "{name}";    
        var bullet = series.bullets.push(new am4charts.CircleBullet());    
        bullet.circle.strokeWidth = 2;    
        bullet.circle.radius = 3;    
        bullet.circle.fill = am4core.color("#fff");    
        var bulletbullethover = bullet.states.create("hover");    
        bullethover.properties.scale = 1.2;    
        chart.cursor = new am4charts.XYCursor();    
        chart.cursor.behavior = "panXY";    
        chart.cursor.snapToSeries = series;    
    });    
    chart.scrollbarX = new am4core.Scrollbar();    
    chartchart.scrollbarX.parent = chart.bottomAxesContainer;    
}    

});    
</script>  
 

Output

 

 



ASP.NET MVC Hosting - HostForLIFE.eu :: Install MVC 4 in Visual Studio 2010

clock June 28, 2019 09:43 by author Peter

We can develop MVC applications in Visual Studio 2010. Visual Studio 2010 includes MVC 2 by default. We can also install both MVC 3 and MVC 4 in Visual Studio 2010. In this article, I go through step-by-step how to install MVC 4 in Visual Studio 2010.

ASP.NET MVC 4 includes all features of MVC 3 and also includes the following:

  • The ASP.NET Web API is a framework for building and consuming HTTP services that can reach a broad range of clients, including browsers, phones, and tablets. The ASP.NET Web API is great for building services that follow the REST architectural style, plus it supports RPC patterns.
  • ASP.NET Web Pages and the new Razor syntax provide a fast, approachable, and lightweight way to combine server code with HTML to create dynamic web content.
  • Web Optimization is a framework for bundling and minifying scripts and CSS files.
  • NuGet, a free, open source developer focused package management system for the .NET platform is intended to simplify the process of incorporating third-party libraries into a .NET application during development.

Step 1: Download and Install Visual Studio 2010 Service Pack 1

Visual Studio 2010 SP1 is required to use MVC 4 in Visual Studio 2010 so we need to install it on our machine then install MVC 4. We can download it from the Microsoft Download Center and go through the following link.
http://www.microsoft.com/en-in/download/details.aspx?id=23691

We download the "VS10sp1-KB983509.exe" file and click on it and follow the steps as given in the process. But it is a web platform install so we need an internet connection to install VS SP1. If we want to install VS SP1 without an internet connection then we need to download the ISO file of VS SP 1. We can download the ISO file for VS SP1 from the same link under Install Instructions. Its size is 1.48 GB (1,590,734,349 bytes).


After installation of VS 2010 SP 1 we wil proceed to install MVC 4.

Step 2: Download MVC 4
We can download MVC 4 from the Microsoft Download Center and go through the following link:
http://www.microsoft.com/en-us/download/details.aspx?id=30683


Click on the "Download" button and the download will start within 30 seconds.

Step 3: Run MVC 4
Now we have the MVC 4 set up file ("AspNetMVC4Setup.exe") to install MVC 4. Double-click on it and it runs.

Accept the License Agreement and click on "Install".

The screen above takes several minutes so don't click on cancel or close window. After a successful installation, we get a success message on the installation screen.


Step 4: Check whether the install was successful
Now we will create a new project from Visual Studio 2010.
Go to "File" -> "New" -> "Project...".

We are notified that the MVC 4 template is ready to be used in Visual Studio 2010 so MVC 4 is successfully installed and ready to use.



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: HTTP Verbs In MVC 5

clock June 18, 2019 12:12 by author Peter

In this article, I will explain the concept of HTTP verbs in MVC 5. I will also explain the various types of HTTP verbs in MVC 5 and how it works in the project.

What is HTTP?

  • HTTP stands for hypertext transfer protocol.
  • This protocol works while working with a client-server application.
  • This protocol provides communication between the client and the server.

HTTP provides methods (verbs) for the actions performed on a response. HTTP verbs are used on an action method. HTTP provides the following main verbs.

  • Get
  • Post
  • Put
  • Delete

HTTP Get
This verb is used to get existing data from the database. In HttpGet, data travels in the URL only. To use the HttpGet method, we use HttpGet attribute on the Action method. It is also the default HTTP verb.

Example
domain.com/student/GetStudent/1
domain.com/student/GetStudent?studentid=1


[HttpGet] 
public object GetStudent(int studentid) 

   // code here 


HTTP Post

This verb is used while we have to create a new resource in the database. In HttpPost, data travels in the URL and body. To use HttpPost method, we use HttpPost attribute on the Action method.

Example
domain/student/Studentsave


Body - Json body
[HttpPost] 
public object Studentsave(studentclass obj) 



HTTP Put

This verb is used while we have to update an existing resource in the database. In HttpPut, the data travels in the URL and body. To use HttpPut method, we use HttpPut attribute on the Action method.

Example
domain.com/student/studentupdate/1

Body- Json body
[HttpPut] 
public object Studentupdate(int studentid ,Studentclass objVM) 



HTTP Delete
This verb is used while we have to delete the existing resources in the database. In HttpDelete, data travels in the URL and body. To use HttpDelete, we use HttpDelete attribute on the Action method.

Example

domain.com/student/studentdelete/1

[HttpDelete]   
public object Studentupdate(int studentid)   
{   
}  
HostForLIFE.eu ASP.NET MVC 6 Hosting
European best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.

 

 



ASP.NET MVC 6 Hosting Germany - HostForLIFE.eu :: How to Create RSS feeds in ASP.NET MVC?

clock April 26, 2019 11:01 by author Peter

ASP.NET MVC 6 Hosting  is the technology that brought me to Microsoft and the west-coast and it’s been fun getting to grips with it these last few weeks. Last week I needed to expose RSS feeds and checked out some examples online but was very disappointed. If you find yourself contemplating writing code to solve technical problems rather than the specific business domain you work in you owe it to your employer and fellow developers to see what exists before churning out code to solve it.

The primary excuse (and I admit to using it myself) is “X is too bloated, I only need a subset. I can write that quicker than learn their solution.” but a quick reality check:

1. Time – code always takes longer than you think

2. Bloat – indicates the problem is more complex than you realize

3. Growth – todays requirements will grow tomorrow

4. Maintenance – fixing code outside your business domain

5. Isolation – nobody coming in will know your home-grown solution

The RSS examples I found had their own ‘feed’ and ‘items’ classes and implemented flaky XML rendering by themselves or as MVC view pages.

If these people had spent a little time doing some research they would have discovered .NET’s built in SyndicatedFeed and SyndicatedItem class for content and two classes (Rss20FeedFormatter and Atom10FeedFormatter )  to handle XML generation with correct encoding, formatting and optional fields. All that is actually required is a small class to wire up these built-in classes to MVC.

using System;
using System.ServiceModel.Syndication;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Xml;
namespace MyApplication.Something
{
    public class FeedResult : ActionResult
    {
        public Encoding ContentEncoding { get; set; }
        public string ContentType { get; set; }
        private readonly SyndicationFeedFormatter feed;
        public SyndicationFeedFormatter Feed{
            get { return feed; }
        }
        public FeedResult(SyndicationFeedFormatter feed) {
            this.feed = feed;
        }
        public override void ExecuteResult(ControllerContext context) {
            if (context == null)
                throw new ArgumentNullException("context");
            HttpResponseBase response = context.HttpContext.Response;
            response.ContentType = !string.IsNullOrEmpty(ContentType) ? ContentType : "application/rss+xml";
            if (ContentEncoding != null)
                response.ContentEncoding = ContentEncoding;
            if (feed != null)
                using (var xmlWriter = new XmlTextWriter(response.Output)) {
                    xmlWriter.Formatting = Formatting.Indented;
                    feed.WriteTo(xmlWriter);
                }
        }
    }
}

In a controller that supplies RSS feed simply project your data onto SyndicationItems and create a SyndicationFeed then return a FeedResult with the FeedFormatter of your choice.

public ActionResult NewPosts() {
    var blog = data.Blogs.SingleOrDefault();
    var postItems = data.Posts.Where(p => p.Blog = blog).OrderBy(p => p.PublishedDate).Take(25)
        .Select(p => new SyndicationItem(p.Title, p.Content, new Uri(p.Url)));
    var feed = new SyndicationFeed(blog.Title, blog.Description, new Uri(blog.Url) , postItems) {
        Copyright = blog.Copyright,
        Language = "en-US"
    };
    return new FeedResult(new Rss20FeedFormatter(feed));
}

This also has a few additional advantages:

1. Unit tests can ensure the ActionResult is a FeedResult

2. Unit tests can examine the Feed property to examine results without parsing XML

3. Switching to Atom format involved just changing the new Rss20FeedFormatter to Atom10FeedFormatter.

HostForLIFE.eu ASP.NET MVC 6 Hosting
European best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: How to Get Lookup Data in ASP.NET MVC 6?

clock April 12, 2019 12:28 by author Peter

In this article, I will explain about getting lookup dataa into you view ASP.Net MVC 6. This is a super common problem I encounter when building ASP.net MVC applications. I have a form that has a drop down box. Not only do I need to select the correct item from the edit model to pick from the drop down but I need to populate the drop down with the possible values.

Over the years I've used two approaches to doing this. The first is to push into the ViewBag a list of values in the controller action. That looks like
public ActionResult Edit(int id){ 
    var model = repository.get(id);

    ViewBag.Provinces = provincesService.List();

    return View(model);
}
Then in the view you can retrieve this data and use it to populate the drop down. If you're using the HTML helpers then this looks like

@Html.DropDownListFor(x=>x.province, (IEnumerable<SelectListItem>)ViewBag.Provinces)
This becomes somewhat messy when you have a lot of drop downs on a page. For instance consider something like

public ActionResult Edit(int id){ 
  var model = repository.get(id);

    ViewBag.Provinces = provincesService.List();
    ViewBag.States = statesService.List();
    ViewBag.StreetDirections = streetDirectionsService.List();
    ViewBag.Countries = countriesService.List();
    ViewBag.Counties = countiesService.List();

    return View(model);
}

The work of building up the data in the model becomes the primary focus of the view. We could extract it to a method but then we have to go hunting to find the different drop downs that are being populated. An approach I've taken in the past is to annotate the methods with an action filter to populate the ViewBag for me. This makes the action look like

[ProvincesFilter]
[StatesFilter]
[StreetDirectionsFilter]
[CountriesFilter]
[CountiesFilter]
public ActionResult Edit(int id){ 
  var model = repository.get(id);
  return View(model);
}

One of the filters might look like

public override void OnActionExecuting(ActionExecutingContext filterContext) 
{
    var countries = new List<SelectListItem>();
    if ((countries = (filterContext.HttpContext.Cache.Get(GetType().FullName) as List<SelectListItem>)) == null)
    {
        countries = countriesService.List();
        filterContext.HttpContext.Cache.Insert(GetType().FullName, countries);
    }
    filterContext.Controller.ViewBag.Countries = countries;
    base.OnActionExecuting(filterContext);
}

This filter also adds a degree of caching to the request so that we don't have to keep bugging the database.

Keeping a lot of data in the view bag presents a lot of opportunities for error. We don't have any sort of intellisense with the dynamic view object and I frequently use the wrong name in the controller and view, by mistake. Finally building the drop down box using the HTML helper requires some nasty looking casting. Any time I cast I feel uncomfortable.

@Html.DropDownListFor(x=>x.province, (IEnumerable<SelectListItem>)ViewBag.Provinces)
Now a lot of people prefer transferring the data as part of the model; this is the second approach. There is nothing special about this approach you just put some collections into the model.

I've always disliked this approach because it mixes the data needed for editing with the data for the drop downs which is really incidental. This data seems like a view level concern that really doesn't belong in the view model. This is a bit of a point of contention and I've challenged more than one person to a fight to the death over this very thing.

So neither option is particularly palatable. What we need is a third option and the new dependency injection capabilities of ASP.net MVC open up just such an option: we can inject the data services directly into the view. This means that we can consume the data right where we retrieve it without having to hammer it into some bloated DTO. We also don't have to worry about annotating our action or filling it with junk view specific code.

To start let's create a really simple service to return states.

public interface IStateService 
{
    IEnumerable<State> List();
}

public class StateService : IStateService 
{
    public IEnumerable<State> List() {
        return new List<State>
        {
            new State { Abbreviation = "AK", Name = "Alaska" },
            new State { Abbreviation = "AL", Name = "Alabama" }
        };
    }
}

Umm, looks like we're down to only two states, sorry Kentucky.

Now we can add this to our container. I took a singleton approach and just registered a single instance in the Startup.cs.

services.AddInstance(typeof(IStateService), new StateService()); 
This is easily added the the view by adding

@inject ViewInjection.Services.IStateService StateService

As the first line in the file. Then the final step is to actually make use of the service to populate a drop down box:

<div class="col-lg-12"> 
        @Html.DropDownList("States", StateService.List().Select(x => new SelectListItem { Text = x.Name, Value = x.Abbreviation }))
</div> 

That's it! Now we have a brand new way of getting the data we need to the view without having to clutter up our controller with anything that should be contained in the view.

HostForLIFE.eu ASP.NET MVC 6 Hosting
European best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.

 



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: Easiest Way to Make CheckBox

clock March 29, 2019 11:53 by author Peter

In this article I show you, how easy it is to make a CheckBox on ASP.NET. The use of radio buttons and checkboxes using ASP.Net programming where the function of the radio button is choosing just one selection with a circle that is a point in the middle if we choose it. While the checkbox is square shaped that there is a tick if selected. To create a function of the radio button. We will explain below:

  • First you must create a project by choosing ASP.Net which is in the File> New Project> Other Languages> Visual C #> Web> Select Empty ASP.Net Web Application.
  • Fill in the name and click OK aspproject05
  • Right Click On aspproject05 in the top right corner select ADD> New Item> Web Form. And give CheckBox.aspx as a name.
  • Next create a CheckBox, button, label by entering this code is in the <div>

<asp:CheckBox ID="chkNews" Text="Do you want to get more update ?" runat="server" />
<br />
<asp:Button ID="btnSubmit" Text="Submit" runat="server" OnClick="btnSubmit_Click" /> <hr/>
<asp:Label ID="lblResult" runat="server" />


Code Description:

<Asp: CheckBox ID = "chkNews" Text = "Do you want to get more update ?" runat = "server" />
This script serves as the manufacture CheckBox with ID named chkNews, which says Do you want to get more update? sent or received by the server.

<br />
This script is used to create a new line

<Asp: Button ID = "btnSubmit" Text = "Submit" runat = "server" OnClick = "btnSubmit_Click" />
This script is used to manufacture the ID button button named btnSubmit, that says Submit sent to the server to have an action Click if the button is clicked.

<Asp: Label ID = "lblResult" runat = "server" />

This script serves to create a label with name ID lblResult the printed blanks to be sent to the server.


When you're done simply double-Click button and type in the code below:

lblResult.Text = chkNews.Checked.ToString ();


Code Description:

LblResult.Text = chkNews.Checked.ToString ();

The above code serves as outputan of chkBerita when checked or not displayed by a label that berID lblResult that are boolean. This means that when we press the button without us tick checkbox section will appear on labels False lblResult whereas if we check the CheckBox and pressing the button it will show True.

HostForLIFE.eu ASP.NET MVC Hosting
European best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: ASP.NET MVC Request Life Cycle

clock March 12, 2019 09:39 by author Peter

If you have worked on ASP.NET MVC, you must be familiar with how when you type in an URL, the appropriate controller is chosen, and the action fired. Today we will dig a little deeper within the MVC request life cycle. Before we start discussing its life cycle, let's briefly understand the concept of HttpHandlers and HttpModules.

Handlers are responsible for generating the actual response in MVC. They implement the IHttpHandler class and only one handler will execute per request. On the other hand, HttpModules are created in response to life cycle events. Modules can, for example, be used for populating HttpContext objects. A request can use many modules. These classes derive from IHttpModule. We are now ready to learn about the MVC Request Life Cycle. The MVC life cycle can be briefly demonstrated as below,


When a request is fired for the first time, the Application_Start method in the Global.asax file is called. This method calls the RegisterRoutes method as below,
    public class MvcApplication : System.Web.HttpApplication 
        { 
            protected void Application_Start() 
            { 
                AreaRegistration.RegisterAllAreas(); 
                FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); 
                RouteConfig.RegisterRoutes(RouteTable.Routes); 
                BundleConfig.RegisterBundles(BundleTable.Bundles); 
            } 
        } 



RegisterRoutes method stores the routes defined in that method, in a static collection in the Routetable class.
Each route has an HttpHandler defined for it. In our case above, the MapRoute method defines the HttpHandler.
Next, the URLRoutingModule is called. It matches the request route with the routes defined in the route table. It calls the GetHttpHandler method which returns an instance of an MVCHandler.

The MVCHandler calls the ProcessRequest method. The controller execution and initialization happens inside this method. ProcessRequest calls ProcessRequestInit, which uses ControllerFactory to select an appropriate controller based on the supplied route. The ControllerFactory calls the Controller Activator which uses the dependency resolver to create an instance of the controller class.

Once the controller is created its Execute method is called.

Now comes the point where the action must be executed. The execute method in the controller calls the ExecuteCore method which calls the InvokeAction method of ActionInvoker. Action Invoker determines which action must be selected based on certain conditions, depending upon the methods available, their names and the action selectors used for them.

Once the action is selected, Authentication & Authorization filters are fired next.
Once the action passes through the authentication and authorization filter checks, the model binding takes place. The information needed for the action to execute is gathered in this step.

OnActionExecuting action filters are fired next. Once the OnActionExecuting filters are executed a response for the action is generated. The thing to note here is that the response is generated at this stage, but not executed.

Next, the OnActionExecuted filters are executed.  Once all the filters have finished executing, the response is finally executed in the ExecuteResult method which is called from the InvokeActionResult by the ActionInvoker. If the response is a view or a partial view, the ViewEngine will render it, else it will be handled appropriately. The ExecuteResult will find the appropriate view using FindView or FindPartialView method. This method will search for the view in specific locations and then render it. This is the final step in generating the response.

If you would like to further dig into the MVC request life cycle, I would highly recommend Alex Wolf’s pluralsight course by the same name.

HostForLIFE.eu ASP.NET MVC 6 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.



European ASP.NET MVC Hosting :: How to Integrate Your ASP.NET MVC with Paypal

clock March 5, 2019 08:27 by author Scott

PayPal is an online payment service that allows you to pay for purchases, receive payments, or to send and receive money. To receive these services, a person must submit various financial details to PayPal, such as credit card number, transmission can be done by mail. Thereafter, transactions are conducted without having to disclose financial details, an email address and a password is sufficient.

for more information about business please visit official Paypal Website for business or https://developer.paypal.com/webapps/developer/docs/integration/direct/log-in-with-paypal/detailed/

In this tutorial we propose to integrate the PAYPAL  e-commerce payment solution.

So, we are using Visual studio C# and ASP.NET MVC4 (for more information about ASP.NET MVC please take a look at  http://www.asp.net/mvc/tutorials/mvc-4/getting-started-with-aspnet-mvc4/intro-to-aspnet-mvc-4

Ready ? Lets start our tutorial :

1. Open Visual studio 2012 or later and Create your Project

2.  Choose ASP.NET MVC4 Template Projet, Internet Application and Razor ViewEngine

 

3. Expand Model folder and Create a new Model named PayPalModel to hold PayPal payment parameters

Try it 

public class PayPalModel
{
public string cmd { get; set; }
public string business { get; set; }
public string no_shipping { get; set; }
public string @return { get; set; }
public string cancel_return { get; set; }
public string notify_url { get; set; }
public string currency_code { get; set; }
public string item_name { get; set; }
public string amount { get; set; }
public string actionURL { get; set; }

public PayPalModel(bool useSandbox)
{
this.cmd = “_xclick”;
this.business = ConfigurationManager.AppSettings[“business”];
this.cancel_return = ConfigurationManager.AppSettings[“cancel_return”];
this.@return = ConfigurationManager.AppSettings[“return”];
if (useSandbox)
{
this.actionURL = ConfigurationManager.AppSettings[“test_url”];
}
else
{
this.actionURL = ConfigurationManager.AppSettings[“Prod_url”];
}
// We can add parameters here, for example OrderId, CustomerId, etc….
this.notify_url = ConfigurationManager.AppSettings[“notify_url”];
// We can add parameters here, for example OrderId, CustomerId, etc….
this.currency_code = ConfigurationManager.AppSettings[“currency_code”];
}
}

4. Create a Paypal Controller

Try it :

public class PayPalController : Controller
{
public ActionResult RedirectFromPaypal()
{
return View();
}

public ActionResult CancelFromPaypal()
{
return View();
}

public ActionResult NotifyFromPaypal()
{
return View();
}

public ActionResult ValidateCommand(string product, string totalPrice)
{
return View();
}
}

5. Now Create a Partial View (ValidateCommand.csHtml)  to use our Model.  Do not forget that all fields must be of type hidden

try it :

@model PaypalMVC.Models.PayPalModel

<body>
<form id=”hiddenform” [email protected]>
@Html.HiddenFor(model => model.cmd)
@Html.HiddenFor(model => model.business)
@Html.HiddenFor(model => model.no_shipping)
@Html.HiddenFor(model => model.@return)
@Html.HiddenFor(model => model.cancel_return)
@Html.HiddenFor(model => model.notify_url)
@Html.HiddenFor(model => model.currency_code)
@Html.HiddenFor(model => model.item_name)
@Html.HiddenFor(model => model.amount)
</form>

<p style=”text-align: center”>
<h3>
Connecting to Paypal , please wait …

</h3>
</p>
</body>
@Scripts.Render(“~/bundles/jquery”)

<script type=”text/javascript” language=”javascript”>
$(this.document).ready(function () {
var form = $(“form”);
form.submit();
});
</script>

6. Now finish our ValidateCommand action of PayPalController

try it :

public ActionResult ValidateCommand(string product, string totalPrice)
{
bool useSandbox = Convert.ToBoolean(ConfigurationManager.AppSettings[“IsSandbox”]);
var paypal = new PayPalModel(useSandbox);

paypal.item_name = product;
paypal.amount = totalPrice;
return View(paypal);
}

7. Next finish our partialView by adding a jquery code to auto submit our form. The necessary scripts are  Jquery-{version}.js and    Jquery-{version}.min.js. Here we are used  @Scripts.Render(“~/bundles/jquery”)  to include all Jquery scripts.  A more better practice will be to export all javascript functions to external file but the submit function must be called just after displaying hidden field of our form

8. The next step is to create our checkOut form that dispays product name , Quantity, price and Total :

So expand View folder , expand Home folder and open index.csHtml file. Replace its contents by the following

try it : 

@{
ViewBag.Title = “Home Page”;
}
@using (Html.BeginForm(“ValidateCommand”, “PayPal”))
{
<div>
<table >
<tr>
<td>
product Name:
</td>
<td>
<input type=”text” name=”product” value=”Visual Studio 2013″ readonly />
</td>
</tr>
<tr>
<td>
Total Price:
</td>
<td>
$<input type=”text” name=”totalPrice” value=”14800″ readonly />
</td>
</tr>
<tr>
<td>
</td>
<td>
<input type=”submit” name=”btnConfirm” value=”Check Out with Paypal” />
</td>
</tr>
</table>
</div>
}

9. we are at the end. Our final step is to update the web.config file with the appropriate settings

10. Let’s test and run the application

 

11. Confirm payment by clicking on button Check Out With PayPal, then you will be redirected to the payment page 

We have this page error because, we have not yet an valid account.

Now it time to create a test account by following this link https://developer.paypal.com/webapps/developer/docs/classic/lifecycle/ug_sandbox/#accounts

12. Open Web.config file and update business value with your test account 

 

13. So run again your application. Confirm or Cancel , etc…

Hope this tutorial helps you. 

 



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: Create A Password Protected PDF In MVC

clock February 19, 2019 10:37 by author Peter
Sometimes, we need to create a PDF file that opens only when the users put in a password when prompted. Let us see how to create a password-protected PDF file in MVC.

First, let's open Visual Studio and create a new project. We need to select the ASP.NET Web application type.

Select Web API as the template and in the "Add folders and core references" section, we need to select MVC and Web API. Click on "Change Authentication" on the right side pane and select "No Authentication".

 

In the web.config file, let us define one key named Filepath and use it in our code. The PDF file must be present there.

It is good to change the key's value when it's placed in web.config.
<appSettings> 
     <add key="FilePath" value="Anil\PDF\LDEPRD9.pdf"/> 
 </appSettings> 


Add the below code to the Home Controller.
string FilePath = ConfigurationManager.AppSettings["FilePath"].ToString(); 
public ActionResult DownloadFile() 

    try 
    { 
        byte[] bytes = System.IO.File.ReadAllBytes(FilePath); 
        using (MemoryStream inputData = new MemoryStream(bytes)) 
        { 
        using (MemoryStream outputData = new MemoryStream()) 
        { 
        string PDFFilepassword = "123456"; 
        PdfReader reader = new PdfReader(inputData); 
        PdfReader.unethicalreading = true; 
PdfEncryptor.Encrypt(reader, outputData, true, PDFFilepassword, PDFFilepassword, PdfWriter.ALLOW_SCREENREADERS);
        bytes = outputData.ToArray(); 
        Response.AddHeader("content-length", bytes.Length.ToString()); 
        Response.BinaryWrite(bytes); 
        return File(bytes, "application/pdf"); 
       } 
      } 
    } 
    catch (Exception ex) 
    { 
        throw ex; 
    } 


string PDFFilepassword = "123456";   
PdfReader reader = new PdfReader(inputData);   
PdfReader.unethicalreading = true;   
PdfEncryptor.Encrypt(reader, outputData, true, PDFFilepassword, PDFFilepassword, PdfWriter.ALLOW_SCREENREADERS); 


In the PDFFilepassword variable, you can set anything as password - the file name, PAN card number, or you can validate the entered value against the values stored in the database.

In Route.config, we can define the default route with the Controller And ActionName.

Run the website and enter http://localhost:49744/Home/DownloadFile. 

Here, Home is the controller name and DownloadFile is the action name. 

It shows the following Password prompt.

 

After entering the right password and successful authentication, the PDF file will get opened.

HostForLIFE.eu ASP.NET MVC 6 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: Server Sent Events In ASP.NET MVC

clock February 15, 2019 08:14 by author Peter

In some Web Applications, we need to show real time data to the end users, which means if any changes occur (new data available) in the Server, it needs to show an end user. For instance, you are doing chat in Facebook in one tab of your Browser. You opened another tab in the same Browser and send a message to the same user (with whom, you are doing chat in the previous chat). You will see that message will appear in both the tabs and it is called real-time push.

In order to accomplish the functionality, mentioned above, the client sends interval basis AJAX requests to the Server to check, if the data is available or not. ServerSentEvents(SSE) API helps ensure the Server will push the data to the client when the data is available in the Server.

What are Server Sent Events?
SSE is an acronym and stands for Server Sent Events. It is available in HTML5 EventSource JavaScript API. It allows a Web page to get the updates from a Server when any changes occurs in the Server. It is mostly supported by the latest Browsers except Internet Explorer(IE).

Using code
We are going to implement a requirement like there is a link button and click on it and it displays current time each second on an interval basis.
In order to achieve the same, we need to add the following action in HomeController. It sets response content type as text/event-stream. Next, it loops over the date and flushes the data to the Browser.
    public void Message() 
    { 
        Response.ContentType = "text/event-stream"; 
     
        DateTime startDate = DateTime.Now; 
        while (startDate.AddMinutes(1) > DateTime.Now) 
        { 
            Response.Write(string.Format("data: {0}\n\n", DateTime.Now.ToString())); 
            Response.Flush(); 
     
            System.Threading.Thread.Sleep(1000); 
        } 
         
        Response.Close(); 
    }


Once we are done with the Server side implementation, it's time to add the code in the client side to receive the data from the Server and displays it.

First, it adds a href link, which calls initialize() method to implement SSE. Second, it declares a div, where the data will display. Thirdly, it implements Server Sent Events(SSE) through JavaScript with the steps, mentioned below.
    In the first step, it checks whether SSE is available in the Browser or not. If it is null, then it alerts to the end user to use other Browser.
    In the second step, if SSE is available, then it creates EventSource object with passing the URL as a parameter. Subsequently, it injects the events, mentioned below.

        onopen- It calls when the connection is opened to the Server
        onmessage- It calls when the Browser gets any message from the Server
        onclose- It calls when the Server closes the connection.

    <a href="javascript:initialize();" >Click Me To See Magic</a> 
    <div id="targetDiv"></div> 
     
    <script> 
         
        function initialize() { 
            alert("called"); 
     
            if (window.EventSource == undefined) { 
                // If not supported 
                document.getElementById('targetDiv').innerHTML = "Your browser doesn't support Server Sent Events."; 
                return; 
            } else { 
                var source = new EventSource('../Home/Message'); 
     
                source.onopen = function (event) { 
                    document.getElementById('targetDiv').innerHTML += 'Connection Opened.<br>'; 
                }; 
     
                source.onerror = function (event) { 
                    if (event.eventPhase == EventSource.CLOSED) { 
                        document.getElementById('targetDiv').innerHTML += 'Connection Closed.<br>'; 
                    } 
                }; 
     
                source.onmessage = function (event) { 
                    document.getElementById('targetDiv').innerHTML += event.data + '<br>'; 
                }; 
            } 
        } 
    </script>


Output

Here, we discussed about SSE(Server Sent Events). It is very important API available in HTML5. It helps to push data from the Server to the client when any changes occurs in the Server side. If you want to use a bidirectional communication channel, you can use HTML5 Web Sockets API. The disadvantage of SSE is it is Browser dependent. If the Browser doesn't support SSE, then the user can't see the data, but it is easy to use it. You can also use SignalR for realtime pushing the data to the end user.

HostForLIFE.eu ASP.NET MVC 6 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.

 



About HostForLIFE

HostForLIFE is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2019 Hosting, ASP.NET 5 Hosting, ASP.NET MVC 6 Hosting and SQL 2019 Hosting.


Month List

Tag cloud

Sign in