Sunday 26 July 2020

Angular Building Blocks

Angular  Basics

Angular is a platform and framework for building single-page client applications using HTML and TypeScript. Angular is written in TypeScript. It implements core and optional functionality as a set of TypeScript libraries that you import into your apps.

Module
The angular app has its own modularity system called the Angular Module of NgModule . Every Angular app has at least one module known as root module.

Component
The component is a controller class that encapsulates the view and the logic. The component class interacts with the view using the built-in API’s.

Template
The component’s view can be defined by templates. Templates are HTML’s that controls how things should be structured on the screen.

Metadata
Metadata is data about data. In Angular, metadata informs the Angular run time on how to process a class. The class case is the @Component decorator which identifies the class immediately below it as the component class.

Directives
A Directive is a class with @Directive decorator. So, technically a component is a directive with a template. There are two types of directives. Structural and Attribute directive.

Data Binding
Data binding binds the template and its component with the required data. So, we have interpolation, property binding, event binding and two-way binding (ngModel directive)

Services
Services are JavaScript functions designed to do specific tasks. It is a class that can perform certain activities like logging, data service, caching, configuration, etc. There is no service base class but it is one of the fundamental aspects of Angular Apps.

Dependency Injection
DI is a way to supply the instance of a class with fully form dependencies to other class/components. It’s one of the core features which keeps your angular apps loosely coupled.




Single Page Application

What is SPA (Single Page Application) 

A single-page application (SPA) is a web application or website that interacts with the web browser by dynamically rewriting the needed part of page  with new data from the web server, instead of the default method of the browser loading entire new pages

Advantages of SPAs and the Key Concept About How They Work
  • We will be able to bring a much-improved experience to the user
  • The application will feel faster because less bandwidth is being used, and no full page refreshes are occurring as the user navigates through the application
  • The application will be much easier to deploy in production, at least certainly the client part: all we need is a static server to serve a minimum of 3 files: our single page index.html, a CSS bundle, and a Javascript bundle.
  • We can also split the bundles into multiple parts if needed using code splitting.
  • The frontend part of the application is very simple to version in production, allowing for simplified deployment and rollbacks to previous version of the frontend if needed
Some of SPA Examples

SPA Frameworks and Details


Drawbacks of Single Page Application Architecture



Friday 11 May 2018

MVC Questions

MVC is a

  • a useful way to organize code , markup and control flow
  • easy to learn
  • designed to help you build and maintain software better


MVC solves Separation of Concerns problem with introduction of below things

  • Models - Data and Business Logic
  • Views - Presentation and UI 
  • Controllers - User actions and Control Flow 
ActionResults: 
ActionResult is an abstract parent class from which ViewResult class has been derived. Following are different response types whcih can be send to end user.


  • ViewResult - Renders a specified view to the response stream
  • PartialViewResult - Renders a specified partial view to the response stream
  • EmptyResult - An empty response is returned
  • RedirectResult - Performs an HTTP redirection to a specified URL
  • RedirectToRouteResult - Performs an HTTP redirection to a URL that is determined by the routing engine, based on given route data
  • JsonResult - Serializes a given object to JSON format
  • JavaScriptResult - Returns a piece of JavaScript code that can be executed on the client
  • ContentResult - Writes content to the response stream without requiring a view
  • FileContentResult - Returns a file to the client
  • FileStreamResult - Returns a file to the client, which is provided by a Stream
  • FilePathResult - Returns a file to the client


Questions
I have created a controller method foo() but i want to call view bar when this method is called. How to achieve it 
Ans: In the foo method , while you are returning view pass parameter name of view  
Example : View('Bar');



Difference between ActionResult and ViewResult

public ActionResult Index()
{
      return View(); // this is a view result class
}

The above code means that you are returning a “ViewResult” object and due to polymorphism, this object is automatically type casted to the parent class type, i.e., “ActionResult”.

In polymorphism, the parent class object can point towards any one of its child class objects at runtime. For example, in the below code snippet, we have parent “Customer” class which is inherited by “GoldCustomer” and “SilverCustomer” class


public class Customer
{}

public class GoldCustomer : Customer
{}

public class SilverCustomer : Customer
{}

So down the line, later during runtime, your parent “Customer” object can point to any one of the child objects, i.e., “GoldCustomer” or “SilverCustomer”.

Customer obj = new Customer(); obj = new GoldCustomer(); obj = new SilverCustomer();

In MVC when request is sent the response can be anything like HTTP Response, Json Response etc..

MVC Team has created a general class called ActionResult which can be further inherited from different type of result 

Tuesday 17 January 2017

API; what and why?

API; what and why?

Let’s start right at the start and figure out what an API is and why you should consider using one.
The term API stands for ‘Application Programming Interface’. In the world of web development the term ‘API’ is synonymous with online web services which client apps can use to retrieve and update data. These online services have had several names/formats over the years such as SOAP, however the current popular choice is to create a REST (or RESTful) API.
We’ll come onto REST and why REST is now preferred later, but first let’s examine why you would even bother with an API.
Let’s consider a modern application which may include several mobile apps on various platforms and usually some kind of web application too. Without an API, a basic architecture may look like this where each client app has its own embedded business logic.

Notice that each client app has its own embedded business logic (probably written in several different languages) which connects directly to the database to get, update and manipulate data. This local business logic means that the client apps can easily become complex and all need to be maintained in sync with each other. When a new feature is required, you’ll have to update each app accordingly. This can be a very expensive process which often leads to feature fragmentation, bugs and can really hold back innovation.
Now let’s consider the same architecture with a central API which hold all the business logic.

Each app uses the same API to get, update and manipulate data. All apps have feature parity and when you need to make a change you just make it in one place in line with the ‘Don’t Repeat Yourself’ (DRY) principle of software development. The apps themselves then become relatively lightweight UI layers.

Friday 6 January 2017

Where to use HttpHandler in ASP.Net Application

In this article we will understand a few more scenarios where we can implement HttpHandler in an ASP.NET application.

Count number of request to certain page
Yes, there might be some other solution for this problem but we can use HttpHandler to count the number of hits to a certain page. Here is the implementation of trying to count the hits of a Home.aspx page. At first we are checking the request URL. If the URL contains “Home.aspx” then we will increment the count value by one.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
 
namespace WebApp
{
    public class countHandler : IHttpHandler
    {
        static int CountRequest = 0;
        public void ProcessRequest(HttpContext context)
        {
            if (context.Request.RawUrl.Contains("Home.aspx"))
            {
                CountRequest++;
            }
         }
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}
The handler is realy simple and now we need to register the handler. Add the following code to your web.config file.
</system.webServer>
  <handlers>
    <add name="myImageHandler" verb="*" path="*.aspx" type="WebApp. countHandler"/>
  </handlers>
</system.webServer>
Ok, we have finished our implementation part. Now let’s try to call the Home.aspx page in a browser. After calling the Home.aspx page, our handler will execute and it will increase the “CountRequest” value by one.

We are seeing that now the CountRequest value is 2, because the output screen has taken in the second trial.

Count number of request

Redirect one page from other page
This is another possible scenario where we can implement HttpHandler as a solution. Let’s think about a situation where one web page exists but then it no longer exists but your client thinks that the page is still in the application.

Now to solve this problem we need to redirect the HTTP request of that page to some other page. For the redirect operation we can use HttpHandler. Have a look at the following code.

In this implementation if someone tries to reach the Home.aspx page then she will redirect to the abc.html page. In this way we can implement redirection.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
 
namespace WebApp
{
    public class loginHandler : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            if (context.Request.RawUrl.Contains("Home.aspx"))
            {
                context.Response.Redirect("abc.html"); 
            }
        }
 
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}
The registration of a HttpHandler is very similar to the previous example. Now if we try to reach the Home.aspx page then it will automatically be redirected to the abc.html page.
Redirect one page from other page

Check whether or not a cookie is present in the current HTTP request
This is another possible scenario. Again , there might be another solution for that but we can implement HttpHandler to detect cookies in HTTP requests.

The count property of the HttpContext class will tell the number of cookies in the current HTTP request. In this example we are detecting the cookie count, if the count is more than 0 then we will consider that the cookie is present in the current HTTP request and we will drop that request immediately.

Here is the implementation:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
 
namespace WebApp
{
    public class loginHandler : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            if (context.Request.Cookies.Count > 0)
            {
                context.Response.ContentType = "text/plain";
                context.Response.Write("Please don't send cookie in HTTP Request");
            }
        }
 
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}
The registration process of HttpHandler is similar to the previous example, there is no change in that. So that we are skipping that part.

When we will now try to browse the “home.aspx” page (or any .aspx page, because our handler will detect the .aspx page request). We will see the default message rather than the page contents. The reason is, we are sending the SessionId from cookies.

current HTTP request

Monday 25 July 2016

Fixing Orphaned Users

  
This is a problem that plagues DBAs everywhere. When you restore a database, you run the risk of orphaning the users in the database. All users are linked via a SID to a login and if you have SQL Server logins, who’s SIDs are managed by SQL Server, you are at risk. Typically a restore to the same server from which the backup was taken won’t cause an issue unless you dropped and recreated the login. Generally the problem rears its ugly head when you restore a backup to a server that was not the original location. You planned ahead and created the same logins on the new server as existed on the old server, so why do the users end up orphaned? As I mentioned earlier, SQL Server manages the SIDs for SQL Server logins so there is no guarantee that the new login has the same SID as the original login did. Then when you restore your database, the users in that database are expecting SIDs that are not there and the next thing you know you have orphaned users. Just a note, this does not occur with Windows Logins because the SID is controlled by Windows or Active Directory. Unless you drop and re-create the user in Windows, the SID of an Active Directory user will be the same on all SQL Servers and hence your user accounts see the SID they are looking for. So, the million dollar question is, how do you fix the problem without dropping and re-creating the user and messing up the permissions in the process? Microsoft provides us with a handy little stored procedure called sp_change_users_login that you can use to fix orphaned users. This procedure can do several things; it can tell you which users are orphaned, it lets you fix an orphaned user manually, and it can attempt to automatically fix your issues. So let’s look at an example. I have deliberately orphaned a user called Annie in the AdventureWorks2008 database. When I run sp_change_users_login with the REPORT option, I can see that I indeed have an orphaned user.
EXEC sp_change_users_login 'REPORT'

UserName UserSID
-------- -----------------------------------
Annie 0xA5B5548F3DC81D4693E769631629CE1D

To fix this orphaned user all I have to do is run sp_change_users_login with the UPDATE_ONE action and tell SQL Server the name of my orphaned user and the name of the appropriate login.
EXEC sp_change_users_login 'UPDATE_ONE','Annie','Annie'
There you have it, a simple quick fix to orphaned users that you can use next time you have an issue. I just want to add one more thing regarding the AUTO_FIX action of sp_change_users_login. If you use this option, the procedure tries to automatically fix your orphaned users by matching user name to login name. If no match is found, it will create the appropriate login for you. The only reason I don’t like it is that is has the potential to create logins you don’t want, especially if your login names happen to deliberately differ from your user names

Saturday 9 July 2016

Web Service , WCF , WCF Rest , Web API

Web Service

  1. It is based on SOAP and return data in XML form.
  2. It support only HTTP protocol.
  3. It is not open source but can be consumed by any client that understands xml.
  4. It can be hosted only on IIS.

WCF

  1. It is also based on SOAP and return data in XML form.
  2. It is the evolution of the web service(ASMX) and support various protocols like TCP, HTTP, HTTPS, Named Pipes, MSMQ.
  3. The main issue with WCF is, its tedious and extensive configuration.
  4. It is not open source but can be consumed by any client that understands xml.
  5. It can be hosted with in the applicaion or on IIS or using window service.

WCF Rest

  1. To use WCF as WCF Rest service you have to enable webHttpBindings.
  2. It support HTTP GET and POST verbs by [WebGet] and [WebInvoke] attributes respectively.
  3. To enable other HTTP verbs you have to do some configuration in IIS to accept request of that particular verb on .svc files
  4. Passing data through parameters using a WebGet needs configuration. The UriTemplate must be specified
  5. It support XML, JSON and ATOM data format.

Web API

  1. This is the new framework for building HTTP services with easy and simple way.
  2. Web API is open source an ideal platform for building REST-ful services over the .NET Framework.
  3. Unlike WCF Rest service, it use the full featues of HTTP (like URIs, request/response headers, caching, versioning, various content formats)
  4. It also supports the MVC features such as routing, controllers, action results, filter, model binders, IOC container or dependency injection, unit testing that makes it more simple and robust.
  5. It can be hosted with in the application or on IIS.
  6. It is light weight architecture and good for devices which have limited bandwidth like smart phones.
  7. Responses are formatted by Web API’s MediaTypeFormatter into JSON, XML or whatever format you want to add as a MediaTypeFormatter.