Hosting Article

ByAlexia Pamelov

Cheap Windows Hosting Tutorial – How to URL Rewrite your PrestaShop to Work with ASPHostPortal Hosting?

CheapWindowsHosting.com | Best and cheap PrestaShop hosting. It’s been a long and frustrating time for all those that have had a terrible time making an attempt to figure out and get help with the errors occurring when enabling Friendly URL’s in Prestashop. i actually had an equivalent problem for quite a while before finding solutions. The problem at hand is usually the .htaccess file settings preventing Prestashop from exercise various permissions once handling the files it needs on a web host.

Another common problem is obtaining an error 500 message. This could be caused by a global setting configured by your host in which sometimes they’re unwilling to change due to their security protocols used. Assuming your hosting provider uses a Linux based system(nearly always the case for standard hosting needs), you should be able to test the below modification to your .htaccess file in your website’s main directory.

Add to your “.HTACCESS” file, the following lines of code:

# URL rewriting module activation
RewriteEngine on
RewriteCond %{REQUEST_METHOD} !^(TRACE|TRACK|GET|POST|HEAD)$
RewriteRule .* - [F]
RewriteBase /
Options +FollowSymLinks

# URL rewriting rules
RewriteRule ^([a-zA-Z0-9-]*)/([0-9]+)\-([a-zA-Z0-9-]*)\.html(.*)$ product.php?id_product=$2$4 [L,E]
RewriteRule ^([0-9]+)\-([a-zA-Z0-9-]*)\.html(.*)$ product.php?id_product=$1$3 [L,E]
RewriteRule ^([0-9]+)\-([a-zA-Z0-9-]*)(.*)$ category.php?id_category=$1 [QSA,L,E]
RewriteRule ^content/([0-9]+)\-([a-zA-Z0-9-]*)(.*)$ cms.php?id_cms=$1 [QSA,L,E]
RewriteRule ^([0-9]+)__([a-zA-Z0-9-]*)(.*)$ supplier.php?id_supplier=$1$3 [QSA,L,E]
RewriteRule ^([0-9]+)_([a-zA-Z0-9-]*)(.*)$ manufacturer.php?id_manufacturer=$1$3 [QSA,L,E]

# Catch 404 errors
ErrorDocument 404 /404.php 

 

If you are experiencing a 500 error with Prestashop, you may have issues with your web hosting php.ini settings. Some web hosting allow you to make modifications to this file and some don’t. ASPHostPortal.com prides itself in providing Full Trust web hosting with a rare combination of unmatched reliability, quality and affordability.

ASPHostPortal.com’s edge is derived through unparalleled company management and a culture of employee driven initiatives. With their fully support on Microsoft Windows and PrestaShop in their Windows Server, ASPHostPortal.com is the best choice to host your Prestashop 1.6.1.1 hosting. They are so confident in their hosting services they will not only provide you with a 30 days money back guarantee, but also they give you a 99.9% uptime guarantee. Their Prestashop 1.6.1.1 hosting plan is starting from $5.00 /mo. 

Normally you would never need to override any php.ini settings. Your exact issue may vary and you should contact your host for troubleshooting. Make sure you clear your browser’s cookies if you don’t notice any change. Also go to the sitemap module and update it just to be safe.

The Results should take place as soon as your website says that your settings have been saved. Check your product pages and everything should be alright. With one exception. Some people can’t get the proper URL to show up under “Recently Viewed” viewed items. I’m pretty sure you can just add another line in the

ReWriteRule

List and use the name of the recentlyviewed php file and match it like the others and it should work. I haven’t verified adding this rule yet, but you can always revert your settings if an issue is caused. I hope this worked for everyone. If you are new to Prestashop or webhosting in general and need an installation or assistance, I can help you for a non mandatory donation. For free! 
ByAlexia Pamelov

Cheap Windows ASP.NET Tutorial – Tips Run external .NET Program from RAM Memory

CheapWindowsHosting.com | Run external app directly from RAM. You can load the specific file into a Byte [] Array with a StreamReader () or even download it from WEB via a direct link provided.

The point of this technique is to maintain anonymity to a fragile file, thus leaving no chance to a reverse engineer to crack the details.

Also note, to keep the variables such as the one referencing the MethodInfo() on a Class basis. You then should Dispose() or set to Nothing these variables at the FormClosing() Event to prevent memory leak.

programmer vs artist

Tips Run external .NET Program from RAM Memory

Dim method As System.Reflection.MethodInfo
Sub Run
        Dim bb() As Byte = IO.File.ReadAllBytes("file.exe")

        Try
            Dim a As System.Reflection.Assembly = System.Reflection.Assembly.Load(bb)

           'or a = Reflection.Assembly.Load(New WebClient().DownloadData("https://...."))
            method = a.EntryPoint
            If (Not method Is Nothing) Then

                Dim o As Object = a.CreateInstance(method.Name)
                method.Invoke(o, Nothing)

            'if your app receives parameters
            'method.Invoke(o, New Object() {New String(){"Hello}})
            Else
                Throw New NullReferenceException("method is null.")
            End If

        Catch ex As Exception
            MsgBox(ex.Message & vbCrLf & "File length: = " & bb.Length.ToString)
        End Try
End Sub

If your app is WinForms and not ConsoleApplication, then follow the steps below:

Your external application needs to start from a Main() Sub to be compatible with this. Otherwise, change the solution property of your external app:

  • Disable ApplicationFramework
  • Add new module to your project (Module1)
  • Select ‘STARTUP OBJECT’ Module1
  • Add this code to Module1
Public Sub Main()
     Application.Run(New Form1)
     'Form1 is your first WinForm that your app displays
End Sub

 or if your app receives parameters:

Public Sub Main(ByVal args As String())
     Application.Run(New Form1)
     'Form1 is your first WinForm that your app displays
End Sub

 I hope this post helpful for you 🙂

ByAlexia Pamelov

Several Reason Why Drupal is The Best CMS For SEO

CheapWindowsHosting.com | Drupal, the open source content management system (CMS) that runs WhiteHouse.gov, MTV Europe, and The Economist, is a very powerful system that can be used for large, complex sites, and it’s the best platform that exists today for SEO. I’ve seen clients triple their traffic within a few weeks of switching from a lesser platform. Drupal’s built-in tools for automating SEO on massive amounts of content, along with granular control that gives you absolute power over every single site element, put it head and shoulders above the rest, including Joomla and WordPress. Additionally, Drupal is the most scalable, configurable system, and major improvements in usability will soon shorten the learning curve for new users and developers.

drupal-search-engine-optimization-seo-services-atlanta

Here’s why Drupal is the best CMS for SEO:

  1. Search engine optimized URLs. Drupal gives you complete control over URL structure. Each item of content created in Drupal (called a node) can be given a custom URL, called a URL alias. You can even set it to automatically generate user- and search engine-friendly URLs based on content type (blog post, page, user), title of the post, keyword, date, time, or any other information related to the node. In WordPress, you are generally limited to one type of permalink URL for all posts. You can override it, but it’s much less specific than Drupal’s URL aliases. For years, Joomla was lacking in search engine-friendly URLs and the ability to fix them. It now offers a built-in “search engine-friendly” functionality, but it lacks the functionality and control over the URL’s parameters.
  2. Custom content types and views. Without having to write any code, you can use the content construction kit (CCK) and view modules to create new content types and create advanced custom views for those types. Common examples include news stories, blog posts, albums, books, and tutorials, all of which can be created and displayed in a variety of ways. While most content management systems require additional written code for creating these types, no programming knowledge is required to do them in Drupal. To make it even more search engine-friendly, it’s simple to create content silos using a free add-on called Views Attach. Create an automated query to create a list of relevant content and attach it to any other piece of content – all with a point-and-click interface.
  3. Ease of editing and revisions. Even the most professional companies make mistakes. Recently I found two spelling errors on CNN.com’s home page, including the word “errors” (it was spelled “erros” for about an hour before the mistake was corrected). Drupal’s built-in version control allows you to save new versions of your Web pages every time they are edited. This gives you the ability to revert back to old versions at any time. Want to try a new marketing message on your site? Type it in. Didn’t work? Revert to the previous page. Snap.
  4. The organizational wizardry of taxonomy. Drupal has a very powerful, built-in taxonomy (categorization) system that allows you to organize and tag content with keyword-rich terms. While care should be taken that each Drupal “vocabulary” be limited to certain content types, it is an infinitely flexible system. For example, you can use free tagging for types of content like blogs or products, while your news or tutorial sections might have a list of categories that can only be selected from a dropdown that is defined by the webmaster. You can also have hierarchical categories, with single or multiple parent categories. But don’t get crazy and deep with it. It’s a good rule of thumb that no page of content is more than three clicks from the home page. The closer the node is to the home page, the more important Google thinks it is, and the higher that individual page will rank. Drupal’s advanced taxonomy features, combined with CCK and views, also allow you to rank for long-tailed keywords that make up a thorough SEO campaign.
  5. Multiple user management. Drupal is almost as well-known for its community as it is for being easily optimized. That’s because Drupal was designed for community-based websites, and has a strong user role and access control functionality. There are no limits to the user roles and access levels you can create and customize – for example, “anonymous visitor,” “authenticated user,” “editor,” “webmaster,” “admin,” and “moderator.” You can also keep the advanced user management features turned off – like if you have multiple blogs – and enable them later when your site grows.
  6. Page titles. The page title is the single most important on-page thing you can do to improve the SEO of your website. Page titles, the line of text in the HTML of a Web page that summarizes what that page is about, act as the welcome mat for your website. Page titles:
    • Tell visitors that they are in the right place
    • Display in the browser title bar
    • Hold important keywords so that your page can be properly categorized by Google and other search engines
    • Display whenever someone bookmarks your site
    • Are often used by search engines as the heading of the search result

    Drupal can generate a page title automatically by using the site name and site slogan of the front page and the node title for individual nodes, but for more complex content, you may want to rearrange the automated page title for SEO purposes. Drupal’s page title module gives you full control over your page titles throughout your site. You can define a pattern that will create search engine-optimized titles automatically as you create new content, or take control by writing your own page titles anywhere you can create content.

  7. Better integration with Google Analytics. Have you ever wondered how much your own clicking around and working on your website skews your analytics data? Not if you have a properly configured Drupal site. Using the free Google Analytics module for Drupal, you can dynamically show and hide analytics code based on several factors, including if the user is logged in as an admin. You can even not track certain sections of your site, not track certain user types (like people logged in as company employees), and cache the Google Analytics code locally, which will speed up your page load times. All within Drupal. No programming required. For free.
  8. Passionate and active community. Drupal has a large community of users and developers who are very active and passionate about the CMS. More than 650,000 user accounts have been created on Drupal.org, and more than 2,000 people have registered developer accounts. You can find hundreds of community-contributed modules that help make Drupal a better experience. Drupal forums offer support and you can find other Drupal users in Drupal Groups.
  9. Free as in beer. Unlike other platforms, Drupal modules (what we call plug-ins, add-ins, or widgets – modular pieces of code that you can easily add to your site) are free. That’s right. You don’t need a license or even a credit card to install any of the functionality that I’ve mentioned in this article. Just go to Drupal.org, click on the “download” tab, and grab anything you need.
  10. Getting started with Drupal SEO is easy. Just download the Drupal SEO checklist module, drop it into your sites/all/modules folder on your server, and turn it on from the modules admin page. Go through the simple, step-by-step instructions, and you’re well on your way to the best SEO experience you’ve ever had on a CMS.

Simpan

ByAlexia Pamelov

Cheap Windows ASP.NET Hosting Tutorial – 10 Standards on Choosing an ASP.NET Web Host

CheapWindowsHosting.com | In this article can save you a lot of time if you are troubled by looking for a suitable ASP.NET web host now. Based on a series of ASP.NET reviews and self-experiences of our editors, we have concluded top 10 important standards on how to choose an ASP.NET web host to help you make an easy decision.

10fcf5_68f3111291564bb19bb3833f5a885da3

ASP.NET is a kind of application framework, which is developed by Microsoft to build dynamic web pages, web applications and web services. It is set up on the Common Language Runtime so that users can write ASP.NET with any supported .NET language. Choosing a web host can be a very important access if you want to run ASP.NET successfully. The following items are the top 10 standards on how to choose a trusted web host for ASP.NET we have summed up.

Top 10 Standards on Choosing an ASP.NET Web Host

[su_box title=”10 Standars on choosing ASP.NET ” style=”soft” box_color=”#e0b754″]

[su_service title=”NO.1 Windows Server Edition” icon=”icon: soundcloud” icon_color=”#a9522b”]

Windows server edition should be considered if you want to get along well with your ASP.NET hosting. It is the operating system of your Windows. In general, the newest edition is the first choice. Because newer Windows server edition can offer more features than the old one. Now usually the edition of 2010 and 2008 R2 are preferred.[/su_service]

[su_service title=”NO.2 MSSQL Server” icon=”icon: soundcloud” icon_color=”#a9522b”]

MSSQL is a database system invented by Microsoft Inc. It is used to store and retrieve data as required by other applications. Usually there are 5 versions widely used in web hosting industry including MSSQL 2000, 2005, 2008, 2008 R2 and 2012. So far, the best suitable version for ASP.NET hosting is MSSQL 2012.

[/su_service]

[su_service title=”NO.3 .NET Framework Version” icon=”icon: soundcloud” icon_color=”#a9522b”]

The .NET Framework is a kind of software framework which has a large library offering language interoperability among several various programming language. Therefore, the supported .NET Framework version is an important factor on choosing an ASP.NET web host. The widely used versions are 2.0, 3.5 SP1 and 4.5 , 5,

[/su_service]

[su_service title=”NO.4 ASP.NET MVC Version” icon=”icon: soundcloud” icon_color=”#a9522b”]

MVC implies model-view-controller. ASP.NET MVC is a web application framework which carries on model-view-controller pattern. ASP.NET MVC allows software developers to build a web application as a composition of three roles: Model, View and Controller, thereby allowing each component to be easily tested independently. The three widely used ASP.NET MVC versions are 2.0, 3.0, and 4.0.

[/su_service]

[su_service title=”NO.5 ASP.NET Hosting Trust Level” icon=”icon: soundcloud” icon_color=”#a9522b”]

The trust level allows applications run with limited permission to ensure the environment secure. The trust levels of ASP.NET hosting are Full, High, Medium, Low and Minimal. Usually Full Trust is more expected than the others, because it is the most flexible configuration for running websites.

[/su_service]

[su_service title=”NO.6 Control Panel” icon=”icon: soundcloud” icon_color=”#a9522b”]

When comes to the control panel of ASP.NET hosting, we usually prefer Plesk and WebSitePanel, because they are really reliable and also widely used in ASP.NET hosting. They have beautiful and concise interfaces which make the control panel to be very user-friendly. We recommend both the two to you.

[/su_service]

[su_service title=”NO.7 Dedicated Application Pool” icon=”icon: soundcloud” icon_color=”#a9522b”]

Application pool on one server is usually shared by many websites. If the memory limit is reached, then the application pool will stop working and restart. So in order to avoid always being troubled by this problem, it is necessary to pay attention to whether your web host offers the dedicated application pool or not.

[/su_service]

[su_service title=”NO.8 ASP.NET Hosting Uptime” icon=”icon: soundcloud” icon_color=”#a9522b”]

It may lead the websites lose lots of visitors if the downtime of a web host is very long. Almost every web host guarantees 99.9% uptime, but actually only a few of them meet their commitments based on our research in the past months. WinHost is a reliable one, its uptime is usually wonderful, and sometimes it even can reach 100.00%.

[/su_service]

[su_service title=”NO.9 ASP.NET Hosting Loading Speed” icon=”icon: soundcloud” icon_color=”#a9522b”]

People all don’t like waiting, so the loading time also can influence the visitor numbers. A poor loading speed has a negative effect on customer conversion. Usually the disk storage of the hardware, the network, over-selling server and many other factors can affect loading speed.

[/su_service]

[su_service title=”NO.10 the Knowledge and Experience of Technical Support” icon=”icon: soundcloud” icon_color=”#a9522b”]

If you are an non-technical person, some problems and difficulties may appear in your operation process, so a knowledge support team can be really necessary. Besides, if the web host is experienced with ASP.NET, it can also offer a worry free and convenient service for you.

[/su_service]

[/su_box]

ByAlexia Pamelov

Cheap Windows ASP.NET Hosting – Improve ASP.NET 5 Website Performance

CheapWindowsHosting.com | This article give you some of the best tips to improve your ASP.NET Website performance. Writing an ASP.NET application is relatively easy with the use of Rapid Application Development controls however it is just not enough to use. You should use each component wisely to get performance benefit to your ASP.NET Website. Remember that 80-90% of page load time spent on downloading all components like HTML, CSS, Script files, images, flash. Rather than looking for re-designing application architecture you should first try to organize your static contents. Below are some easy tips which helps you to achieve a bigger reduction in response times.

HTTP compression

Make sure HTTP compression is turned On. HTTP compression is a algorithm which removes extra space, redundancy from file and produce clean output. It generates smaller size and reduce weight of file than original representation. The outcome of this is reduced bandwidth and time to load page.

Although the support for compression is a feature of all modern browsers you should enable and configure or implement custom compression feature.

You can configure httpCompression tag under system.webServer in ASP.NET Web.config file or Enable HttpCompression feature in IIS.

You can also implement HttpModule to remove space and return compressed output. However it includes runtime cost to implement custom logic to remove unwanted space and redundancy. You can compress your physical files using GZipStream before deploy to production server.

Below is sample code to compress your aspx file.

private void CompressFile(string srcPath, string tarPath)
{
    using(FileStream srcStream = File.OpenRead(srcPath))
    {
        using(FileStream tarStream = File.OpenWrite(tarPath));
        {
            using(GZipStream cStream = new GZipStream(srcStream,
            CompressMode.Compress))
            {
            byte[]data = new byte[srcStream.Length];
            srcStream.Read(data, 0, data.Length);
            tarStream.Write(data, 0, data.Length);
            }
        }
    }
}

Set CacheControlMaxAge

Set CacheControlMaxAge property in Web.config file. It caches static contents like image, css, js files for particular duration. One year is recommended settings.

Below Web.config setting shows you how to configure caching for static contents

<system.webServer>
 <staticcontent>
     <clientCache cacheControlMode="UseExpires" 
           httpExpires="Tue, 30 June 2015 03:14:07 GMT"/>
 </staticcontent>
 </system.webServer>

Configure MiniProfiler

Get MiniProfiler from GitHub or use Nuget package manager and configure for your site. It is profiling library developed by StackExchange team which helps to monitor your Website performance. You can see detail execution time. Do not give an access to end user and once your testing is done remove configuration.

Recommended ASP.NET 5 Hosting [su_button url=”http://asphostportal.com/ASPNET-5-Hosting” style=”stroked” background=”#eab912″]Click Here[/su_button]

Data Controls Paging

For your Data controls like GridView, DataGrid, Repeater UI controls, make sure you are using custom or database level paging. The built in feature of control’s paging is very heavy and expensive as it has to get all the records (no matter how big is your resultset) from database and then filter it at client side as per current page number and pagesize.

When you implement custom paging you provide required page index and page size to database and database returns filtered rows as per input values. So it reduces the required bandwidth and loading time for GridView.

Client side input validations

For rich user experience it is necessary to validate user input on client side using JavaScript or jQuery. You can also use RegEx expression to make sure input data is in valid format. This provides quick feedback and makes page more responsive. Also you should provide easy to understand error messages to users.

Although client side validations are quick and responsive, do not avoid server side validations as client side validations easy to break.

Reduce data sent across the network

Reducing amount of data sent across the network can improve your application performance significantly. You can achieve this by below things

1. Combine script and css files: Try to combine all script files in single file, it reduce required number of requests to load page. If you are using any third party script file, you can copy its content to your single script file. It will save DNS look up time.

If you can not combine all scripts in one file, try to make it for one file for one domain script (e.g. make a one script file for all scripts referring from jQuery website). It reduces DNS lookup time.

Apply same tips for css files.

2. Minify script and css files: You should minify your script and css files to reduce its size. Minification will remove spaces from script or css files and replace long keyword with small characters. You can use this tool for minification.

3. Script reference: Use script references at the bottom of the page because async downloads halt when script reference is reached. Stylesheet and images can be download in async.

4. Async Scripts: Below code allows you to download script files asynchronously.

<script async src="slow.js"></script>

If clients browsers are old. This can be use for script and css files.

<script type="text/javascript">
    var link = document.createElement("link");
    link.type = "text/css"; link.rel = "stylesheet";
    link.href = "Styles/Site.min.css"; 
    document.getElementsByTagName("head")[0].appendChild(link)</script>

Content Delivery Network

Use Content Delivery Network(CDN) for hosting images and script files. These files can be cached and reduce load on server.

A content delivery network (CDN) is a bunch of web servers shared across multiple locations to deliver content more efficiently to users. Depending on user’s location and measure of network proximity server is selected for delivering content. It look for server with the fewest network hops or the server with the quickest response time.

The users location in respect to location has an impact on page load time. Deploying your content to geographically dispersed server or near to your most intended website audience.

Recommended ASP.NET 5 Hosting [su_button url=”http://asphostportal.com/ASPNET-5-Hosting” style=”stroked” background=”#eab912″]Click Here[/su_button]

 

ByAlexia Pamelov

Cheap Windows ASP.NET Hosting – How to Diagnostics in ASP.NET Core 1.0

CheapWindowsHosting.com | Cheap and reliable windows ASP.NET hosting. In this post we will Using Diagnostics in ASP.NET MVC 6 (Core 1.0), we will see how to easily sort out coding issue in a sample application.

The ASP.NET Core 1.0 release (currently in RC1) provides several new features as well as improvements to existing features. One such very useful feature is Diagnostics. ASP.NET Core a.k.a ASP.NET 5 simplifies diagnostics. In this article, we will go through the Diagnostics feature and see how to implement it in an ASP.NET MVC 6 application.

Implementing Diagnostics in ASP.NET MVC 6

This application is implemented using Visual Studio 2015 and ASP.NET Core 1.0.

  • Step 1: Open Visual Studio 2015 and create a new ASP.NET Web Application from Add New Project window. Click on OK and select Empty from ASP.NET 5 Templates. Click on OK to create the project.
  • Step 2: In this project, open the project.json file and add the following dependencies in the dependencies section
"Microsoft.AspNet.Mvc": "6.0.0-rc1-final",
"Microsoft.AspNet.Mvc.TagHelpers": "6.0.0-rc1-final",
"Microsoft.AspNet.StaticFiles": "1.0.0-rc1-final",
"Microsoft.AspNet.Tooling.Razor": "1.0.0-rc1-final",
"Microsoft.Extensions.CodeGenerators.Mvc": "1.0.0-rc1-final",
"Microsoft.Extensions.Configuration.FileProviderExtensions": "1.0.0-rc1-final",
"Microsoft.Extensions.Configuration.Json": "1.0.0-rc1-final"

This will add the necessary references in the project.

  • Step 3: In the project, add a Models folder and in this folder add ModelClasses.cs. Add the following code in this class file
using System.Collections.Generic;
namespace ASPNET_Core_Diagnistics.Models
{
    public class Employee
    {
        public int EmpNo { get; set; }
        public string EmpName { get; set; }
    }
    public class EmployeesDatabase : List<Employee>
    {
        public EmployeesDatabase()
        {
            Add(new Employee() { EmpNo = 1, EmpName = "A" });
            Add(new Employee() { EmpNo = 2, EmpName = "B" });
            Add(new Employee() { EmpNo = 3, EmpName = "C" });
            Add(new Employee() { EmpNo = 4, EmpName = "D" });
            Add(new Employee() { EmpNo = 5, EmpName = "E" });
            Add(new Employee() { EmpNo = 6, EmpName = "F" });
        }
    }
    public class DataAccess
    {
        public List<Employee> Get()
        {
            return new EmployeesDatabase();
        }
    }
}

The above code contains the entity class of name Employee and the EmployeesDatabase class contains some Employee records in it. The DataAccess class contains Get() method and returns EmployeesDatabase class instance.

  • Step 4: In this folder, add a new folder of name Services. In the Services folder, add the class file of name Services. Add the following code in it
using ASPNET_Core_Diagnistics.Models;
using System.Collections.Generic;
 
namespace ASPNET_Core_Diagnistics.Services
{
    public interface IService<T> where T :class
    {
        IEnumerable<T> Get();
    }
 
    public class EmployeeService : IService<Employee>
    {
        DataAccess ds;
        public EmployeeService(DataAccess d)
        {
            ds = d;
        }
        public IEnumerable<Employee> Get()
        {
            return ds.Get();
        }
    }
}

The above code contains an interface of name IService<T> where T is the type. The EmployeeService implements IService interface. The constructor of EmployeeService is injected with the DataAccess object.

  • Step 5: In the same project, add a Controllers folder and in this folder add a MVC Controller Class using Add > New Item > MVC Controller class. By default, the name of the controller class is HomeController, rename it to EmployeeController.
  • Step 6: In the Startup.cs we need to define the required configuration. We will use the inbuilt dependency injection feature of ASP.NET Core 1.0. Add the following code in the ConfigureServices() method of the Startup.cs class
public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
    services.AddSingleton<IService<Employee>, EmployeeService>();
}
Step 7: To use MVC we need to define routing for the application, add the following code in the Configure() method of the Startup class
public void Configure(IApplicationBuilder app)
{
    app.UseIISPlatformHandler();
    app.UseStaticFiles();
    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Employee}/{action=Index}/{id?}");
    });
}
  • Step 8: Now add a new folder of name Views to the project. In this folder add a new sub-folder of name Employee. In the Views folder, add a new MVC View Imports Page and add the following code in it
@using ASPNET_Core_Diagnostics;
@using ASPNET_Core_Diagnostics.Models;
@addTagHelper "*, Microsoft.AspNet.Mvc.TagHelpers"

This will be used to execute new asp- attribute in MVC Views.

Step 9: In the Employee subfolder of Views folder, add a new MVC View of name Index.cshtml and add the following markup code in it

@model IEnumerable<ASPNET_Core_Diagnostics.Models.Employee>
@{
    ViewData["Title"] = "Index";
}
 
<h2>Index</h2>
<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.EmpNo)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.EmpName)
        </th>
        <th></th>
    </tr>
 
    @foreach (var item in Model)
    {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.EmpNo)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.EmpName)
            </td>
        </tr>
    }
</table>
  • Step 10: Running the application

Run the application, the following result will be displayed

aspnet-error-500

This shows a generic Error 500, let us find out the exact error. We can do this by using Microsoft.AspNet.Diagnostics. Add this namespace in the Startup.cs. In the Configure() method add the following code (highlighted)

public void Configure(IApplicationBuilder app,IHostingEnvironment environment)
{
    app.UseIISPlatformHandler();
    if (string.Equals(environment.EnvironmentName, "Development", StringComparison.OrdinalIgnoreCase))
    {
        app.UseDeveloperExceptionPage();    
    }
    app.UseStaticFiles();
    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Employee}/{action=Index}/{id?}");
    });
 
}

The above code uses an if statement to check the EnvironmentName, this is used to verify the current mode in which the application is running. Currently we are using development mode. The UseDeveloperException() extension method is used to render the exception during the development mode.

Run the application and the following result will be displayed:

exception-page

This shows the stack trace error. In our scenario it shows the Object reference is not set to an instance of object. It shows that the foreach loop is not working. This is the problem of the Index() action method of the EmployeeController. Change the code as following

public class EmployeeController : Controller
{
    IService<Employee> _service;
    public EmployeeController(IService<Employee> srv)
    {
        _service = srv;
    }
    // GET: /<controller>/
    public IActionResult Index()
    {
        var Emps = _service.Get();
        return View(Emps);
    }
}

We are injecting the IService<Employee> in the EmployeeController constructor. The Index() action method is calling the Get() method of the IService.

Run the following application, the following result will be displayed

aspnet-diagnostics-dataaccess

The above error shows the Unable to resolve the DataAccess error. To resolve this, let’s verify the code of EmployeeService class. In the constructor, we are passing the dependency of DataAccess but we have not registered it in the ConfgureServices() method. Add the following code in the ConfgureServices() method.

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
    services.AddScoped(typeof(DataAccess));
    services.AddSingleton<IService<Employee>, EmployeeService>();
}

We have added the DataAccess as a dependency in the application.

 

Simpan

ByAlexia Pamelov

Cheap WordPress Hosting Tutorial – 15 Easy Ways To Speed Up your WordPress

WordPress is a great platform. One weakness that it suffers from, however, is it can be quite slow.

CheapWindowsHosting.com | In this quick post, I’ll cover all of the best ways that I’ve found to consistently speed up WordPress.

Why Site Speed Is Important

When a person lands on your site for the first time, you only have a few seconds to capture their attention to convince them to hang around.

Get ready to lose sleep at night: according to a report by the Microsoft Bing search team, a 2-second longer delay in page responsiveness reduced user satisfaction by 3.8%, increased lost revenue per user by 4.3%, and a reduced clicks by 4.3%.

If your site takes too long to load, most people are gone, lost before you even had a chance.

Not only that, but Google now includes site speed in it’s ranking algorithm. That means that your site’s speed effects SEO, so if your site is slow, you’re now losing visitors from impatience and reduced rankings in search engines. Yikes.

Let’s fix that.

designer-developer

How To Speed Up WordPress

As a side note, these are not ordered by importance or any criteria, I’ve just gathered everything I’ve learned about speeding up page loads on WordPress and compiled them here.

I guarantee that using even a few will help speed up your site.

1. Choose a good host

When starting out, a shared host might seem like a bargain (“Unlimited page views!”). It comes at another cost: incredibly slow site speed and frequent down time during high traffic periods.

If you plan on publishing popular stuff, you’re killing yourself by running your WordPress site on shared hosting.

The stress of your site going down after getting a big feature is enough to create a few early gray hairs: don’t be a victim, invest in proper hosting.

The only WordPress host I continually recommend is…

ASPHostPortal.com

ASPHostPortal is a rising star in ASP.NET hosting field. Since its establishment, the company has gained more and more attention from users and authorities in hosting industry because of its cost-effectiveness, high-performance and excellent technical support.

The company has four cheap and reliable WordPress hosting plans. Host One, Host Two, Host Three and Host Four, in total The original prices of the plans are $1.00/mo , $5.00/mo, $9.00/mo and $14.00/mo severally. It is clear that ASPHostPortal does provide competitive pricing.

2. Start with a solid framework/theme

You might be surprised to here this, but the Twenty Fifteen “framework” (aka the default WP theme) is lightweight and quite speedy.

That’s because they keep the “guts” simple; compare that to bloated frameworks which have tons of features that you will never use, slowing your site to a crawl.

From my experience, the fastest loading premium framework is definitely the Thesis Theme Framework. It surpasses the basic WordPress themes by being far easier to customize.

It’s an incredibly solid framework that won’t slow you down with excess plugins or custom edits. Make the changes right from the theme and avoid bloat, hoorah!

3. Use an effective caching plugin

WordPress plugins are obviously quite useful, but some of the best fall under the caching category, as they drastically improve page loads time, and best of all, all of them on WP.org are free and easy to use.

By far my favorite, bar none, is W3 Total Cache, I wouldn’t recommend or use any other caching plugin, it has all of the features you need and is extremely easy to install and use.

Simply install and activate, and what your page load faster as elements are cached.

4. Use a content delivery network (CDN)

All of your favorite big blogs are making use of this, and if you are into online marketing using WordPress (as I’m sure many of my readers are) you won’t be surprised to here that some of your favorite blogs like Copyblogger are making use of CDN’s.

Essentially, a CDN, or content delivery network, takes all your static files you’ve got on your site (CSS, Javascript and images etc) and lets visitors download them as fast as possible by serving the files on servers as close to them as possible.

I personally use the Max CDN Content Delivery Network on my WordPress sites, as I’ve found that they have the most reasonable prices and their dashboard is very simple to use (and comes with video tutorials for setting it up, takes only a few minutes).

There is a plugin called Free-CDN that promises to do the same, although I haven’t tested it.

5. Optimize images (automatically)

Yahoo! has an image optimizer called Smush.it that will drastically reduce the file size of an image, while not reducing quality.

However, if you are like me, doing this to every image would be beyond a pain, and incredibly time consuming.

Fortunately, there is an amazing, free plugin called WP-SmushIt which will do this process to all of your images automatically, as you are uploading them. No reason not to install this one.

6. Optimize your homepage to load quickly

This isn’t one thing but really a few easy things that you can do to ensure that your homepage loads quickly, which probably is the most important part of your site because people will be landing there the most often.

Things that you can do include:

  • Show excerpts instead of full posts
  • Reduce the number of posts on the page (I like showing between 5-7)
  • Remove unnecessary sharing widgets from the home page (include them only in posts)
  • Remove inactive plugins and widgets that you don’t need
  • Keep in minimal! Readers are here for content, not 8,000 widgets on the homepage
Overall, a clean and focused homepage design will help your page not only look good, but load quicker as well.

7. Optimize your WordPress database

I’m certainly getting a lot of use out of the word “optimize” in this post!

This can be done the very tedious, extremly boring manual fashion, or…

You can simply use the WP-Optimize plugin, which I run on all of my sites.

This plugin lets you do just one simple task: optimize the your database (spam, post revisions, drafts, tables, etc.) to reduce their overhead.

I would also recommend the WP-DB Manager plugin, which can schedule dates for database optimization.

8. Disable hotlinking and leeching of your content

Hotlinking is a form of bandwidth “theft.” It occurs when other sites direct link to the images on your site from their articles making your server load increasingly high.

This can add up as more and more people “scrape” your posts or your site (and especially images) become more popular, as must do if you create custom images for your site on a regular basis.

Place this code in your root .htaccess file:

disable hotlinking of images with forbidden or custom image option
RewriteEngine on
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?sparringmind.com [NC]
RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?google.com [NC]
RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?feeds2.feedburner.com/sparringmind [NC]
RewriteRule \.(jpg|jpeg|png|gif)$ – [NC,F,L]

You’ll notice I included my feed (from FeedBurner), you’ll need to replace it with your feed’s name, otherwise your images won’t appear correctly there.

9. Add an expires header to static resources

An Expires header is a way to specify a time far enough in the future so that the clients (browsers) don’t have to re-fetch any static content (such as css file, javascript, images etc).

This way can cut your load time significantly for your regular users.

You need to copy and paste the following code in your root .htaccess file:

ExpiresActive On
ExpiresByType image/gif A2592000
ExpiresByType image/png A2592000
ExpiresByType image/jpg A2592000
ExpiresByType image/jpeg A259200

The above numbers are set for a month (in seconds), you can change them as you wish.

10. Adjust Gravatar images

You’ll notice on this site that the default Gravatar image is set to… well, nothing.

This is not an aesthetic choice, I did it because it improves page loads by simply having nothing where there would normally be a goofy looking Gravatar logo or some other nonsense.

Some blogs go as far to disable them throughout the site, and for everyone.

You can do either, just know that it will at least benefit your site speed if you set the default image (found in “Discussion”, under the settings tab in the WordPress dashboard) to a blank space rather than a default image.

11. Add LazyLoad to your images

LazyLoad is the process of having only only the images above the fold load (i.e. only the images visible in the visitor’s browser window), then, when reader scrolls down, the other images begin to load, just before they come into view.

This will not only speed you page loads, it can also save bandwidth by loading less data for users who don’t scroll all the way down on your pages.

To do this automatically, install the jQuery Image Lazy Load plugin.

12. Control the amount of post revisions stored

I saved this post to draft about 8 times.

WordPress, left to its own devices, would store every single one of these drafts, indefinitely.

Now, when this post is done and published, why would I need all of those drafts stored?

That’s why I use the Revision Control plugin to make sure I keep post revisions to a minimum, set it to 2 or 3 so you have something to fall back on in case you make a mistake, but not too high that you clutter your backend with unnecessary amounts of drafted posts.

13. Turn off pingbacks and trackbacks

By default, WordPress interacts with other blogs that are equipped with pingbacks and trackbacks.

Every time another blog mentions you, it notifies your site, which in turn updates data on the post. Turning this off will not destroy the backlinks to your site, just the setting that generates a lot of work for your site.

For more detail, read this explanation of WordPress Pingbacks, Trackbacks and Linkbacks.

14. Replace PHP with static HTML, when necessary

This one is a little bit advanced, but can drastically cut down your load time if you are desperate to include page load speeds, so I included it.

I’d be doing this great post injustice if I didn’t link to it for this topic, as it taught me how to easily do this myself, in a few minutes.

So go there and check it out, it wrote it out in plainer terms than I ever could!

15. Use CloudFlare

This is similar to the section above on using CDN’s, but I’ve become so fond of CloudFlare since I discussed it in my best web analytics post that I’ve decided to include it separately here.

To put it bluntly, CloudFlare, along with the W3 Total Cache plugin discussed above, are a really potent combination (they integrate with each other) that will greatly improve not only the speed, but the security of your site.

Both are free!

Thanks for reading 🙂 I hope this article helpful for you

ByAlexia Pamelov

Cheap Windows Drupal Tutorial – How To Migrate update for Drupal 8.1.2

CheapWindowsHosting.com | Best and cheap Drupal 8.1.2 hosting.  We’ll discuss the biggest core API change, then how moving to 8.1.2 affects various use cases.

Migrations are now plugins

You may recall that the migration support in core is experimental – that is, it is still open to backwards-compatibility-breaking changes. There is a big one in 8.1.2 – migrations themselves are now plugins rather than configuration entities. This reduces technical debt, in the form of migration-specific infrastructure that’s now being handled by standard core features. Specifically, the plugins themselves serve the function that migration templates did in 8.0.x – they provide default configuration for migrations which require additional configuration (in particular, a database connection) to become runnable. In addition, the migration system’s home-grown builder system (used to generate, say, bundle-specific migrations from one generic node template) is now replaced by standard plugin derivatives.

The lack of configuration entities, however, presents challenges for general-purpose migration tools. One is that there is now no direct core support for persisting configuration changes for the plugins – any configuration (such as a database connection) injected into a migration plugin is only applied at runtime, and without a standard method of persisting that configuration a general-purpose tool (such as the drush commands in migrate_tools) has no way of knowing what to inject or how. Likewise, we have the goal of developing tools for creating migrations from scratch through a UI, and the core migration approach of plugin configuration provided by YAML files within a module isn’t dynamic enough for this – again, we need a dynamic way to persist the configuration.

Migrate_easily_from_a_non_Drupal_platform_to_Drupal_8
Another issue is discovery – a tool like drush migrate-status wants to show you all “relevant” migrations (migrations which have been fully configured and are runnable), but with core full of migration plugins which aren’t relevant in most cases (and there’s virtually no case where they would all be relevant) simply discovering all the plugins and instantiating them doesn’t work. The irrelevant plugins throw a variety of exceptions, some during the initial discovery (making them difficult to handle) – perhaps worse, some give no indication at discovery or instantiation time so cannot be filtered out without hardcoded knowledge.

At this point the cleanest answer I could come up with to the discovery problem was a registration process – an explicit way to mark a migration as eligible to be managed by the tools. And one means of “registering” a migration is to create a configuration entity for it, which (compared to a pure registration implementation like migration in Drupal 7 had) has the advantage of addressing the configuration persistence issues as well. So, that’s what I’ve done.

The migrate_plus module now defines a Migration configuration entity akin to that which was in core in 8.0.x – but cleaner. You’ll find that unlike 8.0.x Migration entities, which contained a huge amount of functionality, the migrate_plus 8.1.x Migration entity class consists of pretty much nothing but annotation and schema – a much cleaner use of the configuration entity system. The migration functionality is contained within the core Migration plugin class. So, how does the entity relate to the plugin? Let’s look first at how the core migration plugins are defined.

  • The migrate module in core implements MigrationPluginManager (provided as the plugin.manager.migration service). This plugin manager uses the YamlDirectoryDiscovery class to provide the plugin configuration – basically, it tells the discovery class to look in each enabled modules’ migrations directory (preferred) or migration_templates directory (for backwards compatibility) to find YAML files defining migration plugins. Thus, if you ask that service for all plugins it manages, you get a list corresponding to each enabled module’s migrations/*.yml and migration_templates/*.yml files.
  • In migrate_plus, I’ve introduced an alternative MigrationConfigEntityPluginManager (provided as the plugin.manager.config_entity_migration service). This plugin manager uses a custom ConfigEntityDiscovery class, which will find all configuration entities of the specified entity type (this class is, by the way, fully general) and create migration plugins using that configuration. These configuration entities may originate at a module’s installation time (from the config/install directory), or be generated by a UI or drush tool.

So, it sounds like we’ve got two different kinds of migration plugins now, right? No, not really – what we have is two distinct means of providing migration plugins with their configuration. For comparison’s sake:

MigrationPluginManager

  • Configuration comes from YAML files in a module’s migrations or migration_templates directory.
  • May be incomplete (requiring runtime injection of required configuration such as a database connection).
  • Cannot be managed by migrate_tools – needs a specialized runner (e.g., migrate_drupal_ui for the core upgrade process) to inject required configuration.
  • Appropriate for module-defined migrations which require further configuration to be run, or which are completely hard-coded (no need to edit the configuration with UI tools, for example).

MigrationConfigEntityPluginManager

  1. Configuration comes from configuration entities in the site’s active configuration (which may originate from a module’s config/install, or be generated dynamically).
  2. Is assumed to be complete – the plugin should be able to be instantiated and run without any runtime injection.
  3. Can be managed by migrate_tools.
  4. Appropriate for migrations generated by tools, or module-provided migrations which you want to have editable.

Straight Drupal upgrades

If you’re looking to simply upgrade your Drupal 6 or Drupal 7 site to Drupal 8 as-is, the big news here is that the upgrade UI (formerly part of the migrate_upgrade contrib module) is now in core as the migrate_drupal_ui module. It works the same as it did previously – provide your database credentials and source of your public files and go. It should be noted that the previous support for rolling back or performing incremental migrations after an initial upgrade has been removed – the premise is that rather than doing a rollback, you should expect to reinstall Drupal 8 and rerun the upgrade from scratch. The contrib migrate_upgrade module still provides the migrate-upgrade drush command (as well as migrate-upgrade-rollback).

Custom Drupal migrations

While the plan is to eventually provide UI tools to make it easy to customize Drupal-to-Drupal migration paths (omit a content type here, map an old field to a differently-named new one there, etc.), in the meantime people have to use drush migrate-upgrade –configure-only to tweak their upgrade paths. More details on this workflow will follow – for the moment, the main thing to be aware of is that (after a period of absence) –configure-only is back and can be used to generated configuration entities which you can then edit to your specific needs.

Implementing Upgrade Paths for Contrib Modules

Because the new migration plugin manager reads the migration_templates directory for backward compatibility (and because the source/process/destination plugins have not changed), in most cases contrib modules implementing upgrade paths should not need to make any changes. The main issue would be in the rare case where you were using builder plugins, which are now gone and should be replaced by derivers instead. See the change record for more details.

General Custom Migrations

If you are implementing other migration scenarios, you’ll need to make the following changes to your migration modules for 8.1.2:

  • If in 8.0.x you were implementing migrations by providing .yml files in config/install, you’ll need to rename those files from migrate.migration.* to migrate_plus.migration.* (because it is now the contrib migrate_plus module rather than the core migrate module which implements migration configuration entities).
  • If you were previously using migration groups, please note that they are now first-class properties of the migration entity. So, you can replace
third_party_settings:
   migrate_plus:
     migration_group: beer

    with

migration_group: beer

Previously you could omit migration_dependencies in migrations with no dependencies, but the core plugin is now a stickler for seeing an empty array. So, in this case you’ll need to add

migration_dependencies: {}

Going forward

There’s still a fair amount of work being done to fill in the gaps in the core migration support (particularly for upgrades from D6/D7). Hopefully we can remove the experimental label from the migration system for Drupal 8.1.2.

In the contrib space, migrate_upgrade 8.x-2.0.beta1 (or 8.x-2.x-dev) is the release to use with Drupal 8.1.2 I will be releasing beta versions of migrate_plus and migrate_tools shortly. Once those are out, the main foci of my community time will be:

  • Core issues (I haven’t been much involved on that side lately as I’ve been bringing the contrib side up-to-date with 8.1.x).
  • Finally getting started on the D8 version of migrate_d2d, so we have proper tools for general Drupal-to-Drupal migrations.
  • Consolidated XML/JSON (and other file-based) source plugins. I got these basically working a few months ago, but there’s still a fair amount of fleshing out to do.
ByAlexia Pamelov

Cheap Windows SQL Server Hosting Tutorial – SQL Server 2016 New Features

CheapWindowsHosting.com | Cheap and reliable SQL Server 2016 hosting. SQL Server 2016 is the newest release of Microsoft’s enterprise data platform. SQL Server has grown far beyond its roots as a simple relational database platform into a true enterprise level data platform. SQL Server 2016 continues to provide core relational database services as well as analysis service for BI, integration services for ETL and reporting Services for creating and distributing reports and more. With the SQL Server 2016 release, Microsoft has heightened SQL Server’s performance, security and availability technologies as well as embraced big data, analytics and mobility.

2016-03-10_0838

You can leverage SQL Server 2016 to build, deploy and manage solutions that can be hosted either on premise or on the cloud. Note that as of this writing, SQL Server 2016 is still in its CTP.

Unlike the previous versions of SQL Server, this version is not directly focussed on Azure support. Rather, the software giant now wants to have a common code base for on premise and databases that are hosted on the Azure cloud. If you recall, SQL Server 2014 provided a platform for hybrid cloud that enabled you can to build, deploy and manage your databases that reside both on premise as well as in the cloud.

So what’s new?

sql2016-620x350

Some of the new features and enhancements in this release of SQL Server include the following:

  • Always Encrypted Data security has always been a major concern. SQL Server 2016 comes in with the Always Encrypted feature that when enabled, protects your data in the SQL Server database using encryption. In using this feature, access to the encrypted sensitive data can be made only by the application that accesses the data stored in the SQL Server 2016 database. The application that has the encryption key can have access to the data — this encryption key (it’s a master key stored in your system) is never passed to SQL Server.

“Note that the process of encryption and decryption of data is performed at the database driver level, and the database owners or the database administrators don’t have access to the unencrypted data at all. To improve performance, only sensitive data is encrypted. The non-sensitive columns, i.e. the primary key, are not encrypted. Incidentally, SQL Server 2016 provides support for two modes of encryption — deterministic and random. While in the former you can get the same value when you encrypt the sensitive data multiple times, in the latter you would get different values each time you encrypt your sensitive data. Both of these strategies have pros and cons, though”.

  • Always On The Always On feature (first introduced in SQL Server 2012) has been enhanced to facilitate high availability and disaster recovery of data. Support for DTC (Distributed Transaction Coordinator) and round-robin load balancing has been introduced in SQL Server 2016.
  • Native JSON support JSON is a standardized data exchange format widely in use these days. SQL Server 2016 provides support for JSON imports and exports. Support for parsing and storing JSON is in-built in SQL Server 2016.
  • Stretch Database When the Stretch Database (also known as Stretch DB) feature is enabled for one or more tables of your local database, SQL Server 2016 can dynamically archive data in a secure manner from your local SQL Server database onto the Azure SQL database hosted in the cloud. Hence this version of SQL Server facilitates seamless migration of your data to Microsoft Azure sans any downtime.
  • Hekaton enhancements The In-Memory OLTP engine that was introduced with SQL Server 2014 helps you to create in-memory tables and then perform I/O operations against them in memory for lower latency and improved performance. Note that Hekaton is another name for the In-Memory OLTP engine in SQL Server. Performing I/O operations against these in-memory tables result in faster reads and writes as your application can read from and write to the memory much faster compared to disk reads and writes.
  • Support for in-database analytics with R-integration SQL Server 2016 provides support for advanced analytics to facilitate a deeper insight into your data. This is the first version of Microsoft’s flagship database product to have an integrated support for Revolution R for statistical analysis of your data.
ByAlexia Pamelov

Cheap Windows ASP.NET Tutorial – Steps for Session InProc Mode to Session ASP.NET State Server

CheapWindowsHosting.com | Cheap and reliable ASP.NET State server. ASPHostPortal.com is Microsoft No #1 Recommended Windows and ASP.NET Spotlight Hosting Partner in United States. Microsoft presents this award to ASPHostPortal.com for the ability to support ASP.NET State server Service for session.

ahp new

Many articles are discussing about advantages of using Session StateServer or SQLServer over InProc Mode.  One basic reason why I choose StateServer Mode is when your website is running on Third Party Hosting than you will notice that Session Timeout can occur anytime depends on load of traffic on your server.

If your website has large number of visitors and session timeout can cause problem, It is better to change Session Mode Session=”InProc” to Session=”StateServer”.

Main Advantage of Session StateServer (Best to choose while hosting on third party server)

  • Session is persistent and reliable.
  • Avoid Session Timeout due to Memory shortage on server (IIS Setting).

Main Disadvantage

  • Poor Performance compare to Session=”InProc”
  • Session_End Event would not fire.

Now lets understand
Steps for changing Session InProc Mode to Session StateServer Mode.

Step 1:  Start Asp.net State Service

  1. Go to Control Panel > Administrative Tools > Services 
  2. Select Asp.Net State Service.
  3. Right Click on Asp.net State Service and choose start from popup menu.

service1

Start1

If you forget to Start Service you will receive following error.

Server Error in '/' Application.
Unable to make the session state request to the session state server. Please ensure that the ASP.NET State service is started and that the client and server ports are the same.  If the server is on a remote machine, please ensure that it accepts remote requests by checking the value of HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\aspnet_state\Parameters\AllowRemoteConnection.  If the server is on the local machine, and if the before mentioned registry value does not exist or is set to 0, then the state server connection string must use either 'localhost' or '127.0.0.1' as the server name.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Web.HttpException: Unable to make the session state request to the session state server. Please ensure that the ASP.NET State service is started and that the client and server ports are the same.  If the server is on a remote machine, please ensure that it accepts remote requests by checking the value of HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\aspnet_state\Parameters\AllowRemoteConnection.  If the server is on the local machine, and if the before mentioned registry value does not exist or is set to 0, then the state server connection string must use either ‘localhost’ or ‘127.0.0.1’ as the server name.

Step 2:  Change Session Mode in Web.Config File

sessionState mode="StateServer"
            stateConnectionString="tcpip=127.0.0.1:42424"
            cookieless="false"
            timeout="120"/>

Note: You can adjust timeout minutes based on your requirement.  Let the tcpip server to be localhost i.e. 127.0.0.1.  Most webhosting company uses these settings unless you have different IP for StateServer and  You are not required to change Port Number.

Step 3: Make All Object Serializable

You should make all object in your website to serializable.

Note: To take advantage of Session StateServer or SQLServer or Custom Mode, object needs to be serialized.

Example:  If your project contains class files for creating DAL (Data Access Layer), you should append Serializable to every class definition in order to make class Serializable.

Understanding Serialization in C#

Class Department

{
        long   _deptId;
        string _deptName;
        
        public long DeptId
        {
               get {   return _deptId; }
               set {  _deptId = value; }                  
         }

        public string DeptName
        {
               get {   return _deptName; }
               set {  _deptName = value; }                  
         }
}

IMPORTANT While doing Serialization
Remember SQLConnection cannot be serialized.
 
You might receive following error if you don’t handle this situation.

Unable to serialize the session state. In 'StateServer' and 'SQLServer' mode, ASP.NET will serialize the session state objects, and as a result non-serializable objects or MarshalByRef objects are not permitted. The same restriction applies if similar serialization is done by the custom session state store in 'Custom' mode.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Web.HttpException: Unable to serialize the session state. In ‘StateServer’ and ‘SQLServer’ mode, ASP.NET will serialize the session state objects, and as a result non-serializable objects or MarshalByRef objects are not permitted. The same restriction applies if similar serialization is done by the custom session state store in ‘Custom’ mode.

So to handle this situation you need to do following thing

  • Mark SQLConnection Object as NonSerialized
    NonSerialized] protected SqlConnection _mainConnection;
  • Mark your Class as Serializable and derive from IDeserializationCallback
    Example:
Class Department: IDeserializationCallback

{
        long   _deptId;
        string _deptName;
        
        public long DeptId
        {
               get {   return _deptId; }
               set {  _deptId = value; }                  
         }

        public string DeptName
        {
               get {   return _deptName; }
               set {  _deptName = value; }                  
         }

        //Create this Method Inside your Class
       void IDeserializationCallback.OnDeserialization(object sender)
        {
            //Recreate your connection here
            _mainConnection = new SqlConnection();
            _mainConnection.ConnectionString =
                    ConfigurationSettings.AppSettings["connStr"].ToString();           
        }
}

 I hope this article helpful for you. Happy coding 🙂

Simpan

Simpan

Simpan