Saturday, 22 December 2018

What is Bundling and Minification

Bundling and minification are two techniques you can use in ASP.NET 4.5 to improve request load time. Bundling and minification improve load time by reducing the number of requests to the server and reducing the size of requested assets (such as CSS and JavaScript.)

Bundling is a feature in ASP.NET 4.5 that makes it easy to combine or bundle multiple files into a single file. You can create CSS, JavaScript, and other bundles as single file. Fewer files means fewer HTTP requests and that can improve first page load performance.

JavaScript minification is the process of reducing the size of the JavaScript file, by removing comments, extra white spaces, new line characters and using shorter variable names.

Advantages of JavaScript minification: As the minified JavaScript files are very small, they will be downloaded much faster and consumes less bandwidth. Search engines like Google consider page load time as one of the parameters to rank the pages.

The downside of JavaScript minification is these are harder to read and debug. However, for development and debugging we can use non-minified versions. Just before deployment, minify and use the minified versions on the production environment. 

How to Preventing JavaScript Injection Attacks in MVC application / Cross-site scripting attack / XSS attack

It is a security vulnerability found in Web applications. XSS allows hackers to inject client-side script into Web pages, and later, if that web page is viewed by others, the stored script gets executed. The consequences of XSS may range from a petty nuisance like displaying an alert() box to a significant security risk, like stealing session cookies. 

In MVC [ValidateInput(true)] by default which restricts  and encodes all HTML. This is a security measure in place, to prevent XSS attack. But if for some reason, you want to disablHTMLml encoding you may decorate the Controller Class or Controler Action method [ValidateInput(false)]. At this moment your application is open for an XSS attack. So you need to carefully avoid this attack by designing your application.

You need to tell your application what and all are allowed to encode coming from the request URL.
Let say I want to accept only <b></b> and <u></u> tags. You can design your application 

[HttpPost]
// Input validation is disabled, so the users can submit HTML
[ValidateInput(false)]
public ActionResult Create(Comment comment)
{
    StringBuilder sbComments = new StringBuilder();
    
    // Encode the text that is coming from comments textbox
    sbComments.Append(HttpUtility.HtmlEncode(comment.Comments));
    
    // Only decode bold and underline tags
    sbComments.Replace("&lt;b&gt;", "<b>");
    sbComments.Replace("&lt;/b&gt;", "</b>");
    sbComments.Replace("&lt;u&gt;", "<u>");
    sbComments.Replace("&lt;/u&gt;", "</u>");
    comment.Comments = sbComments.ToString();

    // HTML encode the text that is coming from name textbox
    string strEncodedName = HttpUtility.HtmlEncode(comment.Name);
    comment.Name = strEncodedName;

    if (ModelState.IsValid)
    {
        db.Comments.AddObject(comment);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

    return View(comment);
}

Note: Read MSDN documentation on XSS and it's countermeasures. 

When to User Windows authentication over forms authentication.

When you are building an internal company website (an intranet site) and you want your users to be able to use their standard Windows usernames and passwords when accessing the website use Windows authentication.


If you are building an outwards facing website or Client Facing application where external users need to be authenticated by providing their username/password (an Internet website), use Forms authentication instead.

Authenticating Users with Windows Authentication while deploying an MVC application in production

For a production web application, on the hand, you use IIS as your web server. IIS supports several types of authentication including:

·       Basic Authentication – Defined as part of the HTTP 1.0 protocol. Sends usernames and passwords in clear text (Base64 encoded) across the Internet.
·       Digest Authentication – Sends a hash of a password, instead of the password itself, across the internet.
·       Integrated Windows (NTLM) Authentication – The best type of authentication to use in intranet environments using windows.
·       Certificate Authentication – Enables authentication using a client-side certificate. The certificate maps to a Windows user account.

You can use the Internet Information Services Manager to enable a particular type of authentication. Be aware that all types of authentication are not available in the case of every operating system. Furthermore, if you are using IIS 7.0, you need to enable the different types of Windows authentication before they appear in the Internet Information Services Manager. Open Control Panel, Programs, Programs and Features, Turn Windows features on or off and expand the Internet Information Services node. Select which type of Windows authentication you want to enable. Using Internet Information Services, you can enable or disable different types of authentication. For example, you may disable anonymous authentication and enable Integrated Windows (NTLM) authentication when using IIS.


After you enable Windows authentication, you can use the [Authorize] attribute to control access to controllers or controller actions. This attribute can be applied to an entire MVC controller or a particular controller action.

Authenticating Users with Windows Authentication while developing an MVC application

When you create a new ASP.NET MVC application, Windows authentication is not enabled by default. Forms authentication is the default authentication type enabled for MVC applications. You must enable Windows authentication by modifying your MVC application's web configuration (web.config) file. Find the <authentication> section and modify it to use Windows instead of Forms authentication.

<authentication mode="Windows">
 
</authentication>

When you enable Windows authentication, your web server becomes responsible for authenticating users. Typically, there are two different types of web servers that you use when creating and deploying an ASP.NET MVC application.

First, while developing an MVC application, you use the ASP.NET Development Web Server included with Visual Studio. By default, the ASP.NET Development Web Server executes all pages in the context of the current Windows account (whatever account you used to log into Windows).


The ASP.NET Development Web Server also supports NTLM authentication. You can enable NTLM authentication by right-clicking the name of your project in the Solution Explorer window and selecting Properties. Next, select the Web tab and check the NTLM checkbox. (There may be some minor differences as per the Visual Studio Installed in your local System)

Authenticating Users with Forms Authentication / Role Based Authentication / User Based Authentication

You can use [Authorize] attribute on Controller level or Action Method level to apply forms authentication. When it is applied on Controller level the entire Controller Class is restricted to anonymous users. When it is invoked it will prompt and ask you to validate by providing valid user and password.

When [Authorize] is applied at Action Method level, that method which is decorated with [Authorize] will be restricted to anonymous users and will prompt to enter valid user and password.

You can restrict the forms authentication user level and role level as well. Create some users and their roles.

Apply [Authorize(Users="AG Kumar")] attribute in Action Method. It will allow only the user “AG Kumar” to access that Action Method. Other users are not allowed to access this.

Apply [Authorize(Roles = "Administrators")] attribute in Action Method. It will allow those users who have “Administrators” role. Other roles are not allowed to access.

You can apply all the above on Controller Level or Action Method Level

Example:
namespace MyMvcApplication
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
 
        [Authorize]
        public ActionResult CompanySecrets()
        {
            return View();
        }
 
        [Authorize(Users="AG Kumar")]
        public ActionResult StephenSecrets()
        {
            return View();
        }
 
        [Authorize(Roles = "Administrators")]
        public ActionResult AdministratorSecrets()
        {
            return View();
        }
 
    }

}

ASP.NET MVC Execution Process / ASP.NET MVC Page Life Cycle

Requests to an ASP.NET MVC-based Web application first pass through the UrlRoutingModule object, which is an HTTP module. This module parses the request and performs route selection. The UrlRoutingModule object selects the first route object that matches the current request. If no routes match, the UrlRoutingModule object does nothing and lets the request fall back to the regular ASP.NET or IIS request processing.

First Request à UrlRoutingModule (HTTP Module ) à Check for the route à If found Route à Obtain the Route Handler (IRouteHandler) à Creates an IHttpHandler object and pass it to the IHttpContext object à MvcHandler will select the appropriate View to handle the request

Detail Explanation:
·       Receive the first request for the application
o   In the Global.asax file, Route objects are added to the RouteTable object.
·       Perform routing
o   The UrlRoutingModule module uses the first matching Route object in the RouteTable collection to create the RouteData object, which it then uses to create a RequestContext (IHttpContext) object.
·       Create MVC request handler
o   The MvcRouteHandler object creates an instance of the MvcHandler class and passes it the RequestContext instance.
·       Create a controller
o   The MvcHandler object uses the RequestContext instance to identify the IControllerFactory object (typically an instance of the DefaultControllerFactory class) to create the controller instance.
·       Execute controller - The MvcHandler instance calls the controller’s Execute method.
·       Invoke action
o   ControllerActionInvoker object that is associated with the controller determines which action method of the controller class to call, and then calls that method.
·       Execute result

  • Loads the appropriate View to the complete the request 

Tuesday, 8 May 2018

How do I delete a Windows Service using registry editor ?

  1. Start the registry editor (regedit.exe)
  2. Move to the HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services key
  3. Select the key of the service you want to delete
  4. From the Edit menu select Delete
  5. You will be prompted "Are you sure you want to delete this Key" click Yes
  6. Exit the registry editor

Wednesday, 2 May 2018

Overview of the .NET Framework

Overview of the .NET Framework
The .NET Framework is a technology that supports building and running the next generation of apps and XML Web services. The .NET Framework is designed to fulfill the following objectives:
·        To provide a consistent object-oriented programming environment whether object code is stored and executed locally, executed locally but Internet-distributed, or executed remotely.
·        To provide a code-execution environment that minimizes software deployment and versioning conflicts.
·        To provide a code-execution environment that promotes safe execution of code, including code created by an unknown or semi-trusted third party.
·        To provide a code-execution environment that eliminates the performance problems of scripted or interpreted environments.
·        To make the developer experience consistent across widely varying types of apps, such as Windows-based apps and Web-based apps.
·        To build all communication on industry standards to ensure that code based on the .NET Framework integrates with any other code.
The .NET Framework consists of the common language runtime (CLR) and the .NET Framework class library. The common language runtime is the foundation of the .NET Framework. Think of the runtime as an agent that manages code at execution time, providing core services such as memory management, thread management, and remoting, while also enforcing strict type safety and other forms of code accuracy that promote security and robustness. In fact, the concept of code management is a fundamental principle of the runtime. Code that targets the runtime is known as managed code, while code that doesn't target the runtime is known as unmanaged code. The class library is a comprehensive, object-oriented collection of reusable types that you use to develop apps ranging from traditional command-line or graphical user interface (GUI) apps to apps based on the latest innovations provided by ASP.NET, such as Web Forms and XML Web services.
The .NET Framework can be hosted by unmanaged components that load the common language runtime into their processes and initiate the execution of managed code, thereby creating a software environment that exploits both managed and unmanaged features. The .NET Framework not only provides several runtime hosts but also supports the development of third-party runtime hosts.
For example, ASP.NET hosts the runtime to provide a scalable, server-side environment for managed code. ASP.NET works directly with the runtime to enable ASP.NET apps and XML Web services, both of which are discussed later in this topic.
Internet Explorer is an example of an unmanaged app that hosts the runtime (in the form of a MIME type extension). Using Internet Explorer to host the runtime enables you to embed managed components or Windows Forms controls in HTML documents. Hosting the runtime in this way makes managed mobile code possible, but with significant improvements that only managed code offers, such as semi-trusted execution and isolated file storage.
The following illustration shows the relationship of the common language runtime and the class library to your apps and to the overall system. The illustration also shows how managed code operates within a larger architecture.
Managed code within a larger architecture .NET Framework in context
The following sections describe the main features of the .NET Framework in greater detail.
Features of the common language runtime
The common language runtime manages memory, thread execution, code execution, code safety verification, compilation, and other system services. These features are intrinsic to the managed code that runs on the common language runtime.
Regarding security, managed components are awarded varying degrees of trust, depending on a number of factors that include their origin (such as the Internet, enterprise network, or local computer). This means that a managed component might or might not be able to perform file-access operations, registry-access operations, or other sensitive functions, even if it's used in the same active app.
The runtime also enforces code robustness by implementing a strict type-and-code-verification infrastructure called the common type system (CTS). The CTS ensures that all managed code is self-describing. The various Microsoft and third-party language compilers generate managed code that conforms to the CTS. This means that managed code can consume other managed types and instances, while strictly enforcing type fidelity and type safety.
In addition, the managed environment of the runtime eliminates many common software issues. For example, the runtime automatically handles object layout and manages references to objects, releasing them when they are no longer being used. This automatic memory management resolves the two most common app errors, memory leaks and invalid memory references.
The runtime also accelerates developer productivity. For example, programmers write apps in their development language of choice yet take full advantage of the runtime, the class library, and components written in other languages by other developers. Any compiler vendor who chooses to target the runtime can do so. Language compilers that target the .NET Framework make the features of the .NET Framework available to existing code written in that language, greatly easing the migration process for existing apps.
While the runtime is designed for the software of the future, it also supports software of today and yesterday. Interoperability between managed and unmanaged code enables developers to continue to use necessary COM components and DLLs.
The runtime is designed to enhance performance. Although the common language runtime provides many standard runtime services, managed code is never interpreted. A feature called just-in-time (JIT) compiling enables all managed code to run in the native machine language of the system on which it's executing. Meanwhile, the memory manager removes the possibilities of fragmented memory and increases memory locality-of-reference to further increase performance.
Finally, the runtime can be hosted by high-performance, server-side apps, such as Microsoft SQL Server and Internet Information Services (IIS). This infrastructure enables you to use managed code to write your business logic, while still enjoying the superior performance of the industry's best enterprise servers that support runtime hosting.

.NET Framework class library
The .NET Framework class library is a collection of reusable types that tightly integrate with the common language runtime. The class library is object oriented, providing types from which your own managed code derives functionality. This not only makes the .NET Framework types easy to use but also reduces the time associated with learning new features of the .NET Framework. In addition, third-party components integrate seamlessly with classes in the .NET Framework.
For example, the .NET Framework collection classes implement a set of interfaces for developing your own collection classes. Your collection classes blend seamlessly with the classes in the .NET Framework.
As you would expect from an object-oriented class library, the .NET Framework types enable you to accomplish a range of common programming tasks, including tasks such as string management, data collection, database connectivity, and file access. In addition to these common tasks, the class library includes types that support a variety of specialized development scenarios. Use the .NET Framework to develop the following types of apps and services:
·        Console apps.
·        Windows GUI apps (Windows Forms).
·        Windows Presentation Foundation (WPF) apps
·        ASP.NET apps.
·        Windows services.
·        Service-oriented apps using Windows Communication Foundation (WCF).
·        Workflow-enabled apps using Windows Workflow Foundation (WF).

The Windows Forms classes are a comprehensive set of reusable types that vastly simplify Windows GUI development. If you write an ASP.NET Web Form app, you can use the Web Forms classes.


Wednesday, 25 April 2018

How to search stored procedures containing a particular text?


select *
      from information_schema.routines
      where routine_definition like '%employee_id%'
      and routine_type='procedure'

How I find a particular column name within all tables of SQL server database?

Find a particular column name within all tables of SQL server database.

select * from information_schema.columns
where column_name like '%employee_id%'



Find a particular column name and datatype details within all tables of SQL server database.

SELECT
OBJECT_NAME(c.OBJECT_ID) TableName
,c.name AS ColumnName
,SCHEMA_NAME(t.schema_id) AS SchemaName
,t.name AS TypeName
,t.is_user_defined
,t.is_assembly_type
,c.max_length
,c.PRECISION
,c.scale
FROM sys.columns AS c
JOIN sys.types AS t ON c.user_type_id=t.user_type_id where c.name like '%family_id%'

ORDER BY c.OBJECT_ID;