Saturday

MVC Compression: How to use GZIP Compression in ASP.net MVC

Introduction

GZIP compression can help to our website to reduce its bandwidth usage. In this article, we can incorporate GZIP feature in our MVC app. We can enable GZIP header through our website, alternatively we can also enable GZIP through our website IIS. Here describing, how to use GZIP compression in our ASP.net MVC app.

Already Discussed on ASP.Net MVC Security & Performance

Main benefits of GZIP compression are under below:

  • It helps to reduce sizes of our website pages.
  • It helps to increase speed of web pages.
  • It mounts to cost-benefit ratio high.

Namespace:

We need to add two namespaces before to write code of GZIP compression.

using System.Web.Mvc;
using System.IO.Compression;

Code of GZIP Compress under FilterConfig.cs

Write this code under FilterConfig.cs in App_Start folder of your MVC App.

public class CompressAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {

            var _encodingsAccepted = filterContext.HttpContext.Request.Headers["Accept-Encoding"];
            if (string.IsNullOrEmpty(_encodingsAccepted)) return;

            _encodingsAccepted = _encodingsAccepted.ToLowerInvariant();
            var _response = filterContext.HttpContext.Response;

            if (_encodingsAccepted.Contains("deflate"))
            {
                _response.AppendHeader("Content-encoding", "deflate");
                _response.Filter = new DeflateStream(_response.Filter, CompressionMode.Compress);
            }
            else if (_encodingsAccepted.Contains("gzip"))
            {
                _response.AppendHeader("Content-encoding", "gzip");
                _response.Filter = new GZipStream(_response.Filter, CompressionMode.Compress);
            }
        }
    }

Call Compress Attribute in MVC Controller

Now call Compress attribute on your controller action to get done this functionality in your MVC application.

Working Sample:

Here, I am showing statistics of my web page difference between zipped and unzipped webpage.

Unzip Webpage:

unzipped Webpage

Unzip Webpage

Requests 34
Size124 KB
Finish5.33s
DOContentLoaded617 ms
Load689 ms

Gzip Webpage:

Gzip Webpage
Gzip Webpage

Requests 34
Size123 KB
Finish1.36s
DOContentLoaded523 ms
Load582 ms

Finally, you can find difference between unzip and zip web pages. It is very required that your web pages should be Gzip enabled through IIS or visual studio project so that it will increase performance of your web pages in web browser (Chrome, IE, FF, Opera etc.). Here, I have explained how to use GZIP compression in ASP.net MVC app.

[Compress]
public ActionResult Index()
{
    /// write here your logic to pull data from database
    return View();
}

Conclusion

GZIP compression helps to our site pages and other resource files before sending them over to the program. This radically decreases exchange time since the documents are considerably littler. Here, I have explained how to use GZIP compression in asp.net MVC.

Monday

MVC Custom Error: How to implement custom error pages using MVC

Introduction

Custom Error pages can make your MVC application more elegant and informative. I often see many developers more struggles for hours to implement this functionality in ASP.Net MVC application. I’ll throw full light on all aspects how to implement MVC custom error pages. I have here demonstrated very common errors of MVC application as listed below:
  • Not Found: Whenever page is not founmd (MVC 404 Page).
  • Access Denied: Whenever we are trying to access folder (CAS Code Access Security) permissions or someone like same.
  • Internal Server Error: This error is related to internal server error. 
  • Error Occurred: If any other error occurred in our MVC application.
MVC custom error page
MVC custom error page
You may conquers this example very easily, if once you go through also this example because it is extended from the earlier example. If you are already regular reader of Technology Crowds then it is OK.
You may also track Exception code and refer to custom page error in your ASP.Net MVC application.
Namespace Used:

using System.Web.Routing;

Add below code into Global.asax

You are required to add below code into Global.asax page on Application_Error page in your MVC application to get working custom error page.
protected void Application_Error(object sender, EventArgs e)
{
    var httpContext = ((MvcApplication)sender).Context;
    var currentController = " ";
    var currentAction = " ";
    var currentRouteData = RouteTable.Routes.GetRouteData(new HttpContextWrapper(httpContext));

    if (currentRouteData != null)
    {
    if (currentRouteData.Values["controller"] != null && !String.IsNullOrEmpty(currentRouteData.Values["controller"].ToString()))
        {
            currentController = currentRouteData.Values["controller"].ToString();
        }

        if (currentRouteData.Values["action"] != null && !String.IsNullOrEmpty(currentRouteData.Values["action"].ToString()))
        {
            currentAction = currentRouteData.Values["action"].ToString();
        }
    }

    var ex = Server.GetLastError();
    var controller = new ErrorController();
    var routeData = new RouteData();
    var action = "Index";

    if (ex is HttpException)
    {
        var httpEx = ex as HttpException;

        switch (httpEx.GetHttpCode())
        {
            case 404:
                action = "NotFound";
                break;

            case 401:
                action = "AccessDenied";
                break;

            case 500:
                action = "InternalServerError";
                break;
        }
    }

    httpContext.ClearError();
    httpContext.Response.Clear();
    httpContext.Response.StatusCode = ex is HttpException ? ((HttpException)ex).GetHttpCode() : 500;
    httpContext.Response.TrySkipIisCustomErrors = true;

    routeData.Values["controller"] = "Error";
    routeData.Values["action"] = action;

    controller.ViewData.Model = new HandleErrorInfo(ex, currentController, currentAction);
    ((IController)controller).Execute(new RequestContext(new HttpContextWrapper(httpContext), routeData));
}

Error Controller Actions

Here are written controller actions list like Index, NotFound, AccessDenied, InternalServerError etc.
public class ErrorController : Controller
{
    ///     /// Track Common Page Error
    ///     /// 
    [HttpGet]
    public ActionResult Index()
    {
        TempData["error"] = "Error Occurred!";
    return View();
    }
    ///     /// Track Page Not Found Error
    /// 
    /// 
    [HttpGet]
    public ActionResult NotFound()
    {
        TempData["error"] = "Page not Found";
        return View();
    }
    /// 
    /// Track Access Denied
    ///     /// 
    [HttpGet]
    public ActionResult AccessDenied()
    {
        TempData["error"] = "Access Denied";
        return View("Index");
    }

    ///     /// Track Internal Server Error
    ///     /// 
    [HttpGet]
    public ActionResult InternalServerError()
    {
        TempData["error"] = "Internal Server Error";
        return View("Index");
    }
}

Custom Error Razor Views

Below is completely provided code snippet of Razor view engine to display custom error pages to end user. Razor views will remain same to all custom error pages like IndexNotFoundAccessDeniedInternalServerError etc.

@{
    ViewBag.Title = @TempData["error"];
    Layout = null;
}

Error:

@TempData["error"]

Error Description:

@Model.Exception.Message.ToString() @Html.Raw(" ") @Model.ControllerName @Html.Raw(" ") @Model.ActionName

MVC custom error pages

Conclusion

To standardise your ASP.net MVC application, we are all required to customise error pages and show on a particular page with detailed error to make more trustworthy your website in to your online audience. Here, I have lined up all aspects of how to implement custom error pages using MVC application with attached working sample project to setup on your machine to see how it happen in really.

Download Complete Project (visual studio source files)
Download

Saturday

MVC: Sorting Filter in AngularJS using MVC

Introduction

I am here fully explaining how to sorting filtering in AngularJS using MVC application. In my recent article, I have already demonstrated Live Character Count using AngularJS

Sorting Filter in AngularJS using MVC

Thursday

AngularJS: Live Character Count using AngularJS

Introduction

In my earlier article. I have explained all awesome features of AngularJS MVW Framework, now taking over next steps. Here, I am showing how we can live count of text area characters in AngularJS. Revising again main features of AngularJS.
Live Character Count using AngularJS

Tuesday

Fix SQL error: 26 - A network-related error occurred in SQL Server

Introduction

This article explains how to configure an instance of the SQL Server Database Engine to listen on a particular fixed port by utilising the SQL Server Configuration Manager to fix SQL error 26. In my earlier article, I have thoroughly highlighted how to get database tables size in SQL Server. The default example of the SQL Server Database Engine responses (listens) especially on TCP port 1433. Named instances of the Database Engine and SQL Server Compact are arranged for dynamic ports. This implies they select an accessible port when the SQL Server administration is started over. When you are interacting with a named instance through a firewall, configure the Database Engine to listen on a particular port, so that the fitting port can be opened in the firewall.

Friday

Know About Transparent Data Encryption (TDE) in SQL Server

Introduction

The basic purpose of encryption feature ensures the confidentiality of any digital data stored on a system. Also, the data, which is transmitted through the internet or via network of another computer. Encryption brings data in such a state that it becomes very difficult to read or analyse it. It is not possible for a user to access the encrypted data without access to decryption key/password/certificates. In the following section we will learn what is transparent data encryption (TDE) in SQL Server, the method to enable TDE and also, its advantage and disadvantages.

What Is Transparent Data Encryption

SQL Server has various built-in technologies for data protection, and one of the most essential is Transparent Data Encryption. This feature is introduced in SQL Server 2008 and present in all the later versions for bulk encryption at the database file level, which includes logs, data and backup file. Moreover, to fulfil the demands of corporate data security standards, SQL Server provides the option to enable TDE on the database level or at column/cell level. This feature is completely transparent to your application. Users can even use file level encryption, which is provided by Windows for database files. In the following section we will discuss the method to enable Transparent Data Encryption along with the advantage and disadvantages of TDE.

How To Enable Transparent Data Encryption

These are the mentioned steps you need to perform to enable TDE on a database. You can follow these steps only if, you have the permission to create a database master key and certificates in the master database and also, control permissions on the user database.
  • Firstly, you need to create a master key: It is a very symmetrical to the key that is used to create certificates and also, asymmetric keys.
  • Then, obtain or create a certificate protected by the master key: Certificates can be used for the encryption of data directly or to create symmetric keys to encrypt the database.
  • Generate a key of database encryption for the protection by the certificate.
  • Next, set the database to use encryption: Encryption, for tempdb data, is automatically enabled once you enable TDE on any of the user database. This results in the prevention of temporary objects (used by the user database) from leaking to disk unencrypted via tempdb database. System databases other than tempdb cannot currently be encrypted by using TDE.

Transparent Data Encryption (TDE) in SQL Server

It’s very essential to take backup of the keys and certificates. This restores the encrypted database on another instance of SQL Server after restoring the keys or certificates there.
Whenever you try to use a certificate without taking a backup of it, SQL Server gives a warning like this:

The certificate used for encrypting the database encrption key has not been backed up

Pros And Cons Of Transparent Data Encryption

Pros
  • Quite simple to implement.
  • No modification is needed for the application tier.
  • Is invisible to the user.
  • Works with high availability features, such as mirroring, AlwaysOn and log shipping.
Cons
  • Overall database is encrypted not only the data, which is sensitive.
  • There is a small performance impact.
  • File Stream data is not encrypted.
  • Data, which is in motion or held within the application is not encrypted

Conclusion

After considering the need of encryption we have discussed the Transparent data encryption (TDE), which is a feature of SQL Server. We have gone through the process to enable TDE in SQL Server. We have also learned about the advantages and disadvantages of TDE. This article provides a deep understanding of Transparent data encryption in SQL.

Suggested Reading

Thursday

URL Access: How to Prevent Direct URL Access In MVC

Introduction

Here is writing another article to make more secure of your MVC application. I’ll explore all aspects here, how to prevent direct URL access in MVC application. Before to go through this article, you are required to detail about these articles as given below.
  1. Asp.net mvc session management example
  2. Prevent Cross-Site Request Forgery using AntiForgeryToken() in MVC

Namespace Used

To apply this feature into your MVC application is used System.Web.Routing namespace to prevent direct URL access in MVC.
How to Prevent Direct URL Access In MVC

using System.Web.Routing

Apply this feature in FilterConfig.cs file

We have to call this feature under OnActionExecuting of Action filter. We have to apply filter as below written lines to prevent direct URL access in MVC. If we are tempering URL in browser then it will forcibly throw you to Logout action of Home Controller lying under Main area.

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class NoDirectAccessAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if (filterContext.HttpContext.Request.UrlReferrer == null ||
 filterContext.HttpContext.Request.Url.Host != filterContext.HttpContext.Request.UrlReferrer.Host)
        {
     filterContext.Result = new RedirectToRouteResult(new
                               RouteValueDictionary(new { controller = "Home", action = "Logout", area = "Main" }));
        }
    }
}

Prevent Direct Access to Class (Apply on Controller Class)

We can apply NoDirectAccess Attribute to Class and it will follow to all containing methods, if any methods accessed directly under the whole controller. It will throw you specified action (here’s throwing Logout action) like MyWebsiteURL.com/Main/PersonalDetail/Index

[NoDirectAccess]
public class PersonalDetailController : Controller
{
      //
      // GET: /Main/PersonalDetail/
      public ActionResult Index()
      {
          return View();
      }
}

Apply NoDirectAccess Attribute to Action

Alternatively, we can apply NoDirectAccess Attribute to specific Action rather than to whole Controller class. Suppose, we are accessing directly like MyWebsiteURL.com/Main/Home/login

[NoDirectAccess]
public ActionResult Login()
{
   return View();
}

Conclusion

I have here demonstrated all necessary steps to prevent direct URL access in MVC to make our MVC application more secured and robust over internet. These are the healthy features to make our MVC application more reliable across the internet.

Tuesday

MVC Session: Asp.net mvc session management example

Introduction

In this example, showing how to use and validate session (HttpContext.Current.Session) in MVC application. In my earlier article, one of more secured feature to keep up your website healthy cross-site request forgery explained. MVC application has provided us facility to apply filter like
  1.  Authorization 
  2.  Action Filter 
  3.  Result Filter 
  4.  On Error Filter
I am here applying OnActionExecuting filter helps us to manage ASP.net MVC session management whether session is preserving or not, if session is expired, it will not let you access your authorised area and throw away to login area or someone page.
Asp.net mvc session management example

Add below code in FilterConfig.cs under App_Start folder

This code is written under OnActionExecuting in FilterConfig.cs file
public class UserSessionActionFilter : ActionFilterAttribute, IActionFilter
{
    public override void OnActionExecuting(ActionExecutingContext filterContextORG)
    {
        HttpContext ctx = HttpContext.Current;
        if (HttpContext.Current.Session["User"] == null)
        {
            /// this handles session when data is requested through Ajax json
            if (filterContextORG.HttpContext.Request.IsAjaxRequest())
            {
                JsonResult result = new JsonResult { Data = "Session Timeout!" };
                filterContextORG.Result = result;
            }
            else
            {
                /// If session is expired then redirected to logout page which further redirect to login page. 
            filterContextORG.Result = new RedirectResult("~/Main/Home/Logout");
                return;
            }
        }
}

In Global.asax Should register FilterConfig.cs

protected void Application_Start()
{
 AreaRegistration.RegisterAllAreas();
 WebApiConfig.Register(GlobalConfiguration.Configuration);
 FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
 RouteConfig.RegisterRoutes(RouteTable.Routes);
}

Checking Session is expired or not

We have to call action attribute [UserSessionActionFilter] in MVC controller to check whether session is preserving or not. If session is expired it will throw to other page.
[UserSessionActionFilter]
public ActionResult ContactDetail()
{
 return View();
}

Conclusion

This example is showing how to handle session in ASP.net MVC application. This example helps us to asp.net MVC session management example with all required steps.

Suggested Reading

Thursday

Fix Error 9002: Transaction Log Full For SQL Server

Overview of SQL Server Error 9002

Sometimes while working on SQL Server database we come across an error 9002. Which indicates that Transaction log for SQL Server is full. There may be several reasons through which the log file may become very large and run out of space or become full. Transaction log error 9002 generally occur when a log file is full or the disk space in which log file stored is full and cannot expand the log files further. In such circumstances, database remains online, but can only be read and no update operation can be performed. If this error occur while recovery then databases marked as resource pending.

Error 9002 msg:
The log file for database '%*Is' is full. Back up the transaction log for the database to free up some log space.
SQL Server database records all the transactions and the modifications done by each transaction. Transaction log must be regularly truncated to maintain the log space and keep it away from filling up. Some operations can be minimally logged to reduce their impact on transaction log size.
If the error 9002 occurred, when database was in recovery mode then after resolving problem ALTER DATABASE database_name SET ONLINE must be used.

How to Fix SQL Server Error 9002?

Following action can be performed for troubleshooting SQL Server transaction log full Error 9002:
  • Log backup can be done.
  • Log file can be moved to some other disk having sufficient space.
  • Log file size can be increased.
  • Freeing disk space so that the log file may grow automatically.
  • Long running transactions could be killed.
  • Adding a log file to other disk.
However, Transaction log is an essential part of database, which is required to return the database in consistent state if any system failure occurred. That’s why shrinking, deleting or moving transaction log be done after fully understanding the outcome of the action performed.
The above actions performed for troubleshooting t-sql error 9002 described below:

Transaction Log Backup

In case database uses the full or bulk-logged recovery model, and transaction log backup has not been done recently. Then there is need to take recent backup of the transaction log to free some space and supports restoring the database from a specific point. Log backup should be taken frequently to keep the log from filling up again.

Moving Log File to Another Disk

If creating enough space on the disk that containing the log file is not possible, then log file should be moved to some other disk having sufficient space. While moving log file one should never place the log file on a compressed file system. The log file can be moved by using concept of database detach and attach.
sp_detach_db executed to detach database.
sp_attach_db executed to attach database.

Increase Log File Size

As maximum size for log file is two terabytes(TB). So if space available on the disk log file size can be increased. Size can be increased manually to produce a single grow increment in case autogrow disable and a database is online. Also, we can enable autogrow by using ALTER DATABASE statement.

Freeing Disk Space

The disk containing the transaction log file can be freed by deleting or moving some files from that disk to another disk. Freeing the disk space will enlarge the log file automatically on that disc.

Add Log file to Another Disk

A new log file can be added to the database on the different disk by using ALTER DATABASE ADD LOG FILE.

Conclusion

We get to know about SQL Server Transaction Log Error 9002. Error 9002 in SQL Server occurred when the transaction log file is full. While moving or deleting a transaction log file the outcome of the action performed should be kept in mind. Several actions which can be performed to solve this error are discussed briefly.

Suggested Reading

MVC Areas: Organizing an Application using Areas

Introduction

MVC architecture is inherently separated into three separate layers like Model (database), Presentation (UI, View), and Controller (Business layer). Releasing of MVC 2 introduces new feature of Area which provide solid capability to further separate files of file structure. Using with Area, we can define same controller in different areas to make our application more modular, manageable and robust. In this demonstration, I have used two areas Main (Public website) and blog area. In my earlier article, how to stop cross-site request forgery. I am explaining all steps how to organizing an application using areas in MVC.
mvc area

Why We Need MVC Areas

When we need multiple departments to maintain with different controllers even having with the same name in different areas. It makes our application more manageable, easy and maintainable to make our development faster.

Create a New MVC Project

First of all, create a new fresh project of MVC

create new project mvc area

New Project Crated

New project created for playing MVC feature of Area.

new project created

Create a New Area

Let’s now start to create a new area. Right click on project then move to Add >>> Area then provide a new relevant name of area.
Create mvc area

Creating Blog Area

Here typing relevant new area name like “Blog”.
type blog area name

Blog Area Created

Now you can see new created area “Blog” under the project.
Area Blog Created

Blog Area File Registration

You can see a new file crated of Blog Area Registration (BlogAreaRegistration.cs) under blog area.

public override string AreaName
{
    get
    {
 return "Blog";
    }
}

public override void RegisterArea(AreaRegistrationContext context)
{
    context.MapRoute("Blog_default",
        "Blog/{controller}/{action}/{id}",
 new { action = "Index", id = UrlParameter.Optional }
    );
}

Area Registration in Global.asax

Area registration is also done in Global.asax file.
public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
    AreaRegistration.RegisterAllAreas();

        WebApiConfig.Register(GlobalConfiguration.Configuration);
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
    }
} 

Main Area Creation

Next one new main area is crating in this section.
Main blog area created
Area Registration File Created
In the same way, as in blog area a registration file (MainAreaRegistration.cs) is also created.

public class MainAreaRegistration : AreaRegistration
{
 public override string AreaName
        {
        get
        {
            return "Main";
        }
    }

public override void RegisterArea(AreaRegistrationContext context)
    {
        context.MapRoute(
            "Main_default",
            "Main/{controller}/{action}/{id}",
            new { action = "Index", id = UrlParameter.Optional }
        );
    }

Create Home Controller for Main Area

Creating home controller under main area.
Home controller for main area

Create Home Controller For Blog

Alike main area, Home controller is also creating under blog area. Area feature let allow us to create same controller name to make our development more lucrative.
Home controller for blog area

Create View for Both Home controllers of Main & Blog

Here is creating view for Blog and main area.

@{
ViewBag.Title = "Index";
}
<h2>Welcome to Blog Area</h2>
<div> @Html.ActionLink("Back to Main", "Index", "Home", new { area = "Main" }, new { }) </div>
 Main Area View
@{ ViewBag.Title = "Index"; }
<h2>Welcome to Main Area</h2>
<div>
    @Html.ActionLink("Go to Blog", "Index", "Home", new { area = "Blog" }, new { })
</div>

Set Default Area/Controller/Action

Here, you can set your default area, controller and method to launch your application (landing page of your application). Before to set, you need to right click on project and click on properties to navigate on Web tab to set application default page (Area/controller/action).

Area Default Page

or Alternatively can set in RouteConfig.cs

Routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
                namespaces: new[] { "slnMvcArea.Areas.Main.Controllers" }
            ).DataTokens.Add("area","Main");

Now Run your MVC area application

Finally run your MVC app to see how works MVC area feature.

welcome to main area

Navigate to Blog Area

Click on “Go to Blog” to navigate blog area.

welcome to blog area
Now you are on blog area, here is also a link to navigate “Back to Main”.

Conclusion

MVC areas helps us to make more manageable our MVC application to further divides into different files. In each area, we can define same controller like Main area contain “Home” Controller then also other areas can contain same area name “Home”, this code will compile perfectly even we have same controller name in different areas. Thus, it will help us to make large volume of applications with multiple departments so that can build awesome MVC apps with area feature. I tried here to demonstrates all necessary steps to organize an application using areas in MVC app.

Video: This video also demonostrates about Organizing an Application using Areas.

Wednesday

How To Own ASP.Net MVC Page Life Cycle For Free

Introduction

Before to start over to know about MVC complete Life Cycle, it is mandatory to add required namespaces in web.config which are automatically added when we add MVC package in our MVC application. We all know the basic behaviour of MVC is based on HTTP requests. In my recent article, I have already explained how to create amazing charts using MVC.

I have provided all necessary MVC life cycle steps here.
<namespaces> 
<add namespace="System.Web.Helpers">
<add namespace="System.Web.Mvc">
<add namespace="System.Web.Mvc.Ajax">
<add namespace="System.Web.Mvc.Html">
<add namespace="System.Web.Optimization">
<add namespace="System.Web.Routing">
<add namespace="System.Web.WebPages">
</namespaces>

1) We send our request through HTTP to our server.
2) Then request goes through our MVC routing.
3) Our web request sends through Global.asax file where all routes are registered under this file, according to our MVC request then request is forwarded according to matching route.
ASP.Net MVC Page Life Cycle

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    WebApiConfig.Register(GlobalConfiguration.Configuration);
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);
    AuthConfig.RegisterAuth();
    //ModelBinders.Binders.DefaultBinder = new Microsoft.Web.Mvc.DataAnnotations.DataAnnotationsModelBinder();
    AreaRegistration.RegisterAllAreas();
}
4) Route is filled in Route.Config file where our controller, view and parameter (optional) are given to complete our request.

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    routes.MapRoute(
    name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
    );
}
5) After filling the route through Route.config, now request is redirected to our controller.

  public ActionResult Index()
  {
   return View();
  }
6) At the end, Result is shown in a view of MVC controller attribute where all desired information is displayed over here.

@{ ViewBag.Title = "Home"; } 
<!DOCTYPE html> 
<html lang="en"> 
<head> <meta charset="utf-8" /> 
<title>@ViewBag.Title</title> 
<link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" /> 
<meta name="viewport" content="width=device-width" /> 
</head>
 <body> <div> Welcome to Technology Crowds </div> </body> 
</html>

Conclusion

In this article has shown how works MVC life cycle when we request through HTTP in our web browser. Requests, Routing, controller, view, MVC handler (Razor etc) are key components of MVC.

Suggested Reading

Monday

Fix SQL error: 26 - A network-related error occurred in SQL Server

Introduction

This article explains how to configure an instance of the SQL Server Database Engine to listen on a particular fixed port by utilizing the SQL Server Configuration Manager. The default example of the SQL Server Database Engine listens on TCP port 1433. Named instances of the Database Engine and SQL Server Compact are arranged for dynamic ports. This implies they select an accessible port when the SQL Server administration is begun. When you are interfacing with a named instance through a firewall, setup the Database Engine to listen on a particular port, so that the fitting port can be opened in the firewall. Here are given 5 different approaches to get resolution of 26 - A network-related error occurred in SQL Server. In my earlier, I have already explained how to find and delete duplicate values in SQL server.

Error Description:

A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified) (Microsoft SQL Server, Error: -1)

Approach 1: We can run this query to view your TCP endpoints 


SELECT name, protocol_desc, type_desc, state_desc, is_admin_endpoint, port, is_dynamic_port, ip_address FROM sys.tcp_endpoints

tcp endpoints

Approach 2: Here you can check which SQL port is running on your machine.


USE MASTER
GO
xp_readerrorlog 0, 1, N'Server is listening on'
GO

Approach 3: Run below command to check applications listening on ports, try this command on command line:


netstat -ap TCP

Approach 4:


i) Open Immediate Window (Windows + R) on your machine.
ii) Next type %windir%\System32\cliconfg.exe and click on Enter button.
iii) Now a new window will open, left side will show disabled port and right side will show enabled port.
disable tcp ip protocols

iv) Now Select TCP/IP disabled protocols and click on Enable button to add in enabled protocols list.

tcp ip properties

v) Now you will enabled TCP/IP protocols and click on properties, then finally you will see SQL Server port i.e. 1433



sql port 1433

Approach 5: 

  • Start from open your SQL Server Configuration Manager
  • Next click  on "SQL Server Network Configuration" and click on "Protocols for Name".
  • Now right click on TCP/IP, click on properties and make sure it is enabled.
  • Presently Select "IP Addresses" Tab - and-Go to the last passage "IP All".
  • Now enter SQL server port TCP/IP 1433
  • Remove 0 (keep totally blank) from TCP Dynamic Ports property
  • Now restart your SQL Server (Right click on SQL server Management Studio and click restart button).

Conclusion

Here are given 5 different approaches to resolve issue 26 - A network-related error occurred in SQL Server. Hopefully, these approaches would work to all who are looking to resolve issue 26 - A network-related error occurred in SQL Server.

Relevant Reading

SQL Server Schema Corruption Error 211: A Technical Solution

Introduction

The SQL Schema is a logical collection of SQL Objects including the tables, associated with columns, its relevant entries, or other elements. While creating the schema, a user will be able to access the database in more effective manner. However, a situation occurs in SQL server that different errors occurs while accessing it. One such error is SQL server error 211, which occurs when the server table is getting updated. In the following section, we will cover reasons for corruption in the server Schema and then possible solutions to overcome this error.

Problem Statement

Suppose a user tries to update some database tables on his server and meanwhile a schema corruption error message occurs on the system. This error can exist in any version of SQL Server such as Server 2005, 2008 etc.
“Msg: 211, Level 23, State 51, Line 1 Possible schema corruption.
Run DBCC CHECKCATALOG
Msg 0, Level 20, State 0, Line 0”

Reasons Behind SQL Server Error 211

Generally, schema corruption in database evolve very rarely in the SQL Server. When this error took place, a user have to check out the main cause of the error i.e., either via SQL error Log files or some other.
There are multiple reasons where schema gets corrupted and some of them are mentioned below:
  • Due to improper computer activities by server users
  • Sudden software failure leads to Schema corruption
  • Hardware failure is the major issue behind corruption

How to Fix Corruption Error 211 in SQL Server

There are several methods to resolve this server error. A user can choose any one approach to remove or delete the schema corruption which is present within the server. Following are the all possible solutions to fix the error:
  • One of the compatible solution for resolving this error is to restore the backup files of the database. In addition, go through following scenarios that will help you in restoring backup files:
    1. If a user has backup of transaction log, then take a backup of tail-log and restore the latest backup completely with entire transaction logs that are ending with tail-log backup. In such case, the result will become in 0 data loss.
    2. If a user does not have a backup of the transaction log then, develop a new database and import more data as possible or if a user is able to determine culprit table, then drop that table & recreate it.
  • The another approach is to repair entire MDF database file and then, you will have to deploy the database again.
  • The last manual trick is to execute DBCC CHECKCATALOG command on the server screen.
When you will run DBCC command the error will be displayed. Sometimes, much exceptions might occur while executing the Transact-SQL statement through SQL users with dedicated Schema. Make sure, a user will get the suitable suggestion from SQL server database by running DBCC CHECKCATALOG syntax. With the help of this command, users will get to know the location and reason behind the SQL server error 211. However, DBCC CHECKCATALOG signifies no error, but it is not possible at all time.

Alternate Solution to Resolve SQL Server Database Corruption

The most appropriate solution for fixing SQL error code 211 is third party SQL recovery tool. It is safe and secure way to troubleshoot this error with help of following steps:
Step1: Launch SQL Recovery, Add MDF file and press Open button

Step 2: Analyze all your data of the server file and then click on Export button

Step 3: Now, select an option between two i.e., with the only Schema or with Schema & Data for exporting MDF file and click on save to start migration process

Finally, you will be able to get a healthy MDF file with help of this solution and hence, fix SQL server error 211.

Conclusion

Here we are ending with one of the server error, which create hurdle while accessing the SQL Server database. The best possible solutions are also discussed to overcome this possible Corruption Schema error. Well, it is recommended to first restore the backup file of server, if a user is having it. Else, you can go for other solution for resolving SQL server schema corruption error 211.

Suggested Reading

Product Review of Kernel for SQL Server

SQL Server is the well-developed Microsoft entity which provides flexible and correlational data management services to the organizations. Also referred sometimes as MS SQL and Microsoft SQL Server, The SQL Server is basically a set of relational database management service which extensively supports ANSI SQL, which is a standard server language. The SQL server also contains T-SQL, which is its own SQL implementation. Microsoft offers SQL server in different editions with different features and outcomes.
  • Enterprise Edition: Being the most expensive among SQL Servers, the Enterprise edition is meant for large organizations that deal in bulk volume of data every second.
  • Standard Edition: Perfectly designed to act as support for small and medium scale enterprises. It is prefect for medium level data volume.
  • Workgroup Edition: Perfect for startups and very small scale business groups. It is perfectly used for backend database for small webservers.
  • Express Edition: It is a free edition that is meant for distribution as it has limited number of features to be used. This edition is often referred to replace the Access database.
The availability of different editions of SQL Server is not so difficult, but the most common observation in every edition of SQL Server is issues with MDF and LDF files. The entire database of SQL server is saved in Master copy called MDF files. The MDF database files are the primary database file which entails schema and data. The other file format is LDF that maintains Log files. Due to some reasons the MDF files getcorrupt. To fix these MDF files it is important to take required action through some reliable source like Kernel for SQL Server.

Necessity of External Assistance

Kernel for SQL Server is an external agency designed to fix the MDF files that got corrupt due to technical complications. This SQL Server tool is perfect to fix the most notorious SQL-related issues. It includes:
  • MSDTC configuration issues.
  • Non-existent Disaster Recovery Plan.
  • Weak SQL login password.
  • TEMPDB pagelatch contention.
  • System Memory issues.
  • Usage of NOLOCK.
  • Non-scheduled Database Integrity checks.
From being a perfect tool to fix the SQL related issues to being a tool for maintaining the SQL Server, Kernel for SQL Server effectively manages every task assigned to it in a very simple manner. The entire credit goes to the inbuilt algorithm that drives the entire process.

An Intro to Kernel for SQL Server

Designed to fix the MDF file corruption with Auto SQL Version Detection Feature, Kernel for SQL Server haunts the SQL – related issues every time. The QFSCI algorithm takes care of the entire process with a great care for MDF file components. To experience the real functioning of Kernel for SQL Server the evaluation version can be downloaded that works exactly like the licensed version with a limitation of not restoring the recovered MDF files. The performance of this celebrity tool also depends upon the system configuration and supported versions. To eliminate any chance of incompatibility, the tool supports all versions of MS SQL Server, Windows OS and Windows Server. Moreover, prior downloading the evaluation version of the tool, it must be known to the user that the tool perfectly works in the system that comprises Pentium class processor with minimum 64 MB RAM and enough disk space to save results.

What is so special about Kernel for SQL Server?

Ardent features, which were once the dream of SQL Server users are now the reality and that too in the platform which can be easily managed. With user-friendly graphic interface no special training is required nor is any technical background needed. The only thing expected from the user is knowledge of the location of the MDB files and a rough estimate about the SQL repair tool’s working.
The specialty of Kernel for SQL Server lies in its features. These features play significant role in recovering the damaged MDB files:
  • Reveals the SQL Server version automatically.
  • Effective recovery of MDF files.
  • Essentially restores MDF file components like Tables, Index, keys and much more.
  • Dual Saving modes to save the MDF files differently.
  • Provides ‘Preview’ option to view the recovered items to ensure correctness.
  • Maintains data integrity throughout the process.
  • Independent of MDF file size limit.
  • Recovery of multiple MDF files in a single repair cycle.
To explore more about the tool it is suggested to download the trial version of the tool that works alike licensed version with a limitation of not saving the recovered MDF files.

Expanding Every Valuable Feature

  1. Witty Selection of MDF Files: Kernel for SQL Server makes quick selection of MDF files required to be recovered. To make this happen, the user-friendly GUI of the tool is available which can be independently tackled by any naïve user. To initiate it, user has to launch the SQL Recovery software followed by selecting the concerned MDF files. Once it is done the tool is ready to go.

Select Database to Recover

  1. Automatic Selection of SQL Server Version: To know the version of affected MDB files normally user applies conventional techniques but owing to the new technology that is used by external tool it has become very easy to find it out. To make this happen user has to select the concerned EDB file, upload it and tick the box that reads ‘Auto Detect Database Version’. On selection of this feature, your workload remains half and rest is performed by the third-party tool.

    Select SQL Database

  1. Stunning Recovery: The MDB files subjected to recovery are perfectly loaded by the user. With this action the manual support for the tool ends here. Now, following the remaining steps, everything is automated and just needs manual clicks to keep the process on going. On recovery of concerned MDF files, the user’s screen appears as like
Stunning Recovery

  1. Schematic Representation of Recovered Items: SQL Recovery Tool delivers B-tree structure of the recovered MDF file components. The schematic representation of the recovered items clearly makes the way for the user to select the specific file to ensure the correctness in the recovery process. User has to just select the object from the tree prior saving. When selection is made, the requisite content will be displayed on the right pane of the Window.
Schematic Representation of Recovered

  1. Save what is recovered: Post deciding that recovery is perfect, now is the time to get introduced to the stunning saving option. The saving mode gives a choice of saving the recovered files directly to SQL Server or simply to the Batch File.

Saving Mode

  1. Knowing the Performance Capacity: The Performance capacity of Kernel for SQL Server can be witnessed without spending a money or clicking the dialog box for online annual subscription. User has to simply download the evaluation version of the SQL Server recovery tool that has some limited potential to recover the damaged MDF files up to some extent. However, user cannot save any recovered files with it. To do so, the licensed version has to be purchased that facilitates limitless recovery irrespective of the SQL Server version.
  2. Speedy Delivery of License Key: Kernel for SQL Server is known for its outstanding performance. If user is satisfied with the tool’s performance in the evaluation version and is willing to purchase the licensed version of the same, then it can be done by using any of the different payment options like PayPal, Credit/Debit, E-Cheque and Pay Order. Once payment is received, the key of the licensed version is sent through the email to the user. In totality, it merely takes few minutes to procure the license key of the tool.
  3. Round-the-Clock Technical Support: The software is ardent in maintaining the client relationship. It is made possible by allowing technical support to the client whenever needed. Every ticket raised by the user is important for us and it is dealt with a great concern. After providing the required solution, it is conformed if user is facing any issues. The technical follow-up is kept to trace the history of the query that made the client concerned. To gain the online help related to SQL database recovery tool, user can simply log on to https://www.kerneldatarecovery.com/sql-recovery.html

Kernel for SQL Server Provides a Common Stage

Kernel for SQL Server is a center-stage to different versions of MS SQL and other required applications. The single stop solution for affected SQL files is responsible for fixing the SQL database irrespective of the version of its origin. To materialize the claimed capacity, the tool supports all versions of the required programs. This also eliminates all chances of incompatibility issues.
Supported Versions
  • MS SQL Server 2014/2012/2008 R2/2008/2005
  • Windows 10/8.1/8/7/Vista/XP/2000/98/NT/95
  • Windows Server 2012/2008 R2/2008/2003 R2/2003
Where Kernel for SQL Server fits the best?
The SQL Server Recovery tool graciously performs well in the system that comprises:
  • Pentium Processor
  • Minimum 64 MB RAM
  • 50 MB Space for Software Installation, and
  • Some space to save results.
The tool’s performance also depends upon the system configuration; therefore, prior downloading any version of the tool, it is recommended to check the system requirements.

Wednesday

How to find and delete duplicate values in sql server

Introduction

Today, I am writing about how to Find and delete duplicate values in SQL server and delete in our SQL Server database, sometimes data is inconsistent due to not proper relational integrity it results to duplicate rows in corresponding tables. Duplicate records of any database will lead to unstable application and it will not generate information according to end user expectation. I have clarified extremely known SQL Server error SQL Server Error 25 And 87.
SQL duplicate records