Monday, December 31, 2018

Difference between Entity framework and ADO .Net

Entityframework is a wrapper to ADO.net thus a bit slow but safe in comparision of ADO .Net

If we use EF and LINQ then the maintainability and code redundancy reduces as we donot have to write the big queries anymore like SP and all.

Make Connection and Connection Dispose not required in EE with the help of using state it controlled automatically.

Difference between Entity framework and LINQ

LINQ only works with SQL Server Databas while Entityframework can works with various databases like Oracle, DB2, MYSQL, SQL Server etc.

LINQ generates a .dbml to maintain the relation while Entityframework generates an .edmx files initially. The relation is maintained using 3 different files .csdl, .msl and .ssdl

LINQ has not support for complex type. Entityframework has support for complex type.

LINQ cannot generate database from model.Entityframework can generate database from model.

LINQ allows only one to one mapping between the entity classes and the relational tables /views.Entityframework allows one-to-one, one-to-many & many-to-many mappings between the Entity classes and the relational tables /views.

LINQ allows you to query data using DataContext.Entityframework allows you to query data using EntitySQL, ObjectContext, DbContext.

LINQ provides a tightly coupled approach.Entityframework provides a loosely coupled approach. Since its code first approach allow you to use Dependency Injection pattern which make it loosely coupled .

Difference between providers and viewproviders

Service declared by providers are accesbile by content children also but service declared by viewproviders are not accesbile by content children, it accesbile by component and and its view children.


Lets peek at the declaration of the TodoAppComponent:

class TodoList {
  private todos: Todo[] = [];
  add(todo: Todo) {}
  remove(todo: Todo) {}
  set(todo: Todo, index: number) {}
  get(index: number) {}
  getAll() {}
}
@Component({
  // ...
  viewProviders: [TodoList]
  // ...
})
class TodoAppComponent {
  constructor(private todos: TodoList) {}
  // ...
}

Inside of the @Component decorator we set the viewProviders property to an array with a single element - the TodoList class. The TodoList class holds all the todo items, which are entered in the current session.

We inject the TodoList service in the TodoAppComponent’s constructor, but we can also inject it in any other directive’s (or component) constructor, which is used in the TodoAppComponent’s view. This means that TodoList is accessible from:

TodoList
TodoComponent
TodoInputComponent

However, if we try to inject this service in FooterComponent’s constructor we are going to get the following runtime error:

ORIGINAL EXCEPTION: No provider for TodoList!
This means that providers declared in given component with viewProviders are accessible by the component itself and all of its view children.

In case we want to make the service available to FooterComponent as well we need to change the declaration of the component’s providers from viewProviders to providers.

When to use viewProviders?
Why would I use viewProviders, if such providers are not accessible by the content children of the component? Suppose you’re developing a third-part library, which internally uses some services. These services are part of the private API of the library and you don’t want to expose them to the users. If such private dependencies are registered with providers and the user passes content children to any of the components exported by the public API of your library, she will get access to them. However, if you use viewProviders, the providers will not be accessible from the outside.

https://medium.com/@tkssharma/understanding-viewchildren-viewchild-contentchildren-and-contentchild-b16c9e0358e

Saturday, December 29, 2018

Interview

1. How to validate xml in c#?
Ans : Create an xml schema and use XmlValidator class.

2.Can we overload constructor in typescript?
Ans TypeScript allows you to declare overloads but you can only have one implementation and that implementation must have a signature that is compatible with all overloads. 

3. How to generate com component in .Net?
Ans: check the check box make com visible.

4. How to pass data from view to controller in MVC?
Ans

5. How to bind one view model with two view and update only one view base on condition.
Ans :

Monday, December 24, 2018

Difference between ActionResult and ViewResult

ActionResult" is an abstract class while "ViewResult" derives from "ActionResult" class. "ActionResult" has several derived classes like "ViewResult" ,"JsonResult" , "FileStreamResult" and so on.

"ActionResult" can be used to exploit polymorphism and dynamism. So if you are returning different types of view dynamically "ActionResult" is the best thing. 

Sunday, December 23, 2018

Advantage of Routed Event?

The single routed event is listening for three buttons. If you try to write the same code using ordinary events, you'll have to use three separated events, one event by button.

This means that, instead of defining multiple events on every control in a same child, you have to define a routed event at the parent level, which will be raised by every concerned child.

A click occurs in a button and rises up to its StackPanel and then to the containing window where one code handles all clicks.
Routed events give us the flexibility to write our event handler code in the most conveniant place. 

Interview

1. If two view connected with one viewmodel and you want to update only one view while changed view model, how will you do that?
2. What are different layer in wpf architechture?
3. What are different type of container?
4. What is differnece between Static Resource and dynamic resource?
5. What is data context?
6. How will you update data base while adding new properties in model?
7. Difference between WPF and windows form in respect of display?
8. Is WPF replace Direct X?
9. Difference between Visual Tree and Logical Tree?
10. What is RelayCommand?
11. Difference between IEunumerable and IQueryable.


1.Difference Between angular 1 and angular 2
2. What is service in angular 2? And how to create it?

Saturday, December 22, 2018

Convert Angular JS application to Angular 2 application


  1. Each AngularJS module to respective Angular module.
  2. Element type directive to a Component.
  3. Attribute type directive with a template to a Component.
  4. Attribute type directive without a template to a Directive.
  5. Find the set of controllers and templates in your routes and convert each of them to a component. If two different templates use the same controller, you must create two different components corresponding to each of the templates. 
  6. Make sure to move common business logic to an Injectable (aka service) to improve code reusability.
  7. Convert a factory or a service to an Injectable (aka services)
  8. Convert a provider too to an Injectable but using useFactory 
  9. Convert a filter to a Pipe.
  10. Write all your run block code in a callback by chaining on the bootstrap method call of main.ts file. Example:

Friday, December 21, 2018

Don't use function inside template

If we have used function in template, it will be called many times even Input parameters are same as previous, This is because of the Change detection mechanism in Angular. 
Angular cannot detect whether the result of function is changed until it runs the that function 

Solution
Can we cache the result for a certain input then, next time use the same input to simply return the cached result?

The pure pipe can help us in this case.

Angular executes a pure pipe only when it detects a pure change to the input value. A pure change is either a change to a primitive input value (String, Number, Boolean, Symbol) or a changed object reference (Date, Array, Function, Object)


https://dzone.com/articles/why-we-shound-not-use-function-inside-angular-temp

Wednesday, December 19, 2018

Disadvantage of Cookies

Cookies enable you to store the session information on the client side which has the following advantages,

• Persistence: One of the most powerful aspects of cookies is their persistence. When a cookie is set on the client's browser, it can persist for days, months or even years. This makes it easy to save user preferences and visit information and to keep this information available every time the user returns to your site. Moreover, as cookies are stored on the client's hard disk so if the server crashes they are still available.

• Transparent: Cookies work transparently without the user being aware that information needs to be stored.

• They lighten the load on the server's memory.

 Disadvantages of Cookies

The following are the disadvantages of cookies :

• Sometimes clients disable cookies on their browsers in response to security or privacy worries which will cause problem for web applications that require them.

• Individual cookie can contain a very limited amount of information (not more than 4 kb).

• Cookies are limited to simple string information. They cannot store complex information.

• Cookies are easily accessible and readable if the user finds and reopens.

• Most browsers restrict the number of cookies that can be set by a single domain to not more than20 cookies (except Internet Explorer). If you attempt to set more than 20 cookies, the oldest cookies are automatically deleted.

Resolver in angular

Resolver is that intermediate code, which can be executed when a link has been clicked and before a component is loaded.

How to Creating a Resolver.
Create a service.
Import “Resolve” interface from ‘@angular/router’.
Implement the Resolve interface with your class
Override resolve() method.
Resolve method should have two parameters. One is routesnapshot and other one is statesnapshot. Check this link for more.
Resolve method should return a value or observable, if you want to use it later in your loaded component class.


Path should be defined as follows 

{path:templateContainer,component:TemplateContainerComp,resolve:{cres:AppResolver}

How to receive data in component?

constructor(private route: ActivatedRoute){

let x = route.data.cres;
}

Source : https://codeburst.io/understanding-resolvers-in-angular-736e9db71267

Friday, December 14, 2018

HTTP Cookies in Web API

A cookie is controlled by some attribute set in the cookie header, these attributes are as follows:

Domain: It is the specified domain that is receives the cookie. If the domain is not specified then the domain is the origin server.

Path: It specifies the limit in the domain if the path is not specify then it uses the URI path.

Expires: It specifies the date/time when the cookie will be expire, the user can delete the cookie when it has expired.

Max-age: It is a numeric value that specifies the timespan of the cookie that includes the life of the cookie. It can be deleted if it reaches its maximum age like as "expires" does.

Web API and Cookies

We know that the Web API creates services over the HTTP. It can be a web page for making AJAX requests, it can be a native app for retrieving the data or it can be a headless bot for pooling the data. The Web API does the work over the HTTP and the cookie is the part of the HTTP.

Setting a Cookie with multiple values

public HttpResponseMessage Get() 

HttpResponseMessage respMessage = new HttpResponseMessage(); 
respMessage.Content = new ObjectContent(new string[] 

  "value1", 
  "value2" 
}, new JsonMediaTypeFormatter()); 
var nvc = new NameValueCollection(); 
nvc["sessid"] = "1234"; 
nvc["3dstyle"] = "flat"; 
nvc["theme"] = "red"; 
var cookie = new CookieHeaderValue("session", nv); 
cookie.Expires = DateTimeOffset.Now.AddDays(1); 
cookie.Domain = Request.RequestUri.Host; 
cookie.Path = "/"; 
respMessage.Headers.AddCookies(new CookieHeaderValue[] { cookie }); 
return respMessage; 



https://www.devcurry.com/2013/04/http-cookies-and-aspnet-web-api.html

Http message handlers in Web API

A message handler is a class that receives an HTTP request and returns an HTTP response. Message handlers derive from the abstract HttpMessageHandler class.

Typically, a series of message handlers are chained together. The first handler receives an HTTP request, does some processing, and gives the request to the next handler. At some point, the response is created and goes back up the chain. This pattern is called a delegating handler.


Server-Side Message Handlers
On the server side, the Web API pipeline uses some built-in message handlers:

HttpServer gets the request from the host.
HttpRoutingDispatcher dispatches the request based on the route.
HttpControllerDispatcher sends the request to a Web API controller.
You can add custom handlers to the pipeline. Message handlers are good for cross-cutting concerns that operate at the level of HTTP messages (rather than controller actions). For example, a message handler might:

Read or modify request headers.
Add a response header to responses.
Validate requests before they reach the controller.

https://docs.microsoft.com/en-us/aspnet/web-api/overview/advanced/http-message-handlers

Dependency Injection in Web API

UnityContainer can be used for dependency Injection in Web API.

https://docs.microsoft.com/en-us/aspnet/web-api/overview/advanced/dependency-injection

Exception in Web API

Summary
We can use HttpResponseException when the possibility of exception is known by us. In the above example, we have thrown exception using HttpResponseException class as we know there is a chance to employee not found in the database.

We can use exception filter to catch unhandled exceptions on action/controllers.

We can use Exception Handlers to catch any type of unhandled exception application-wide.

Detail

There are many ways to handle the exception. 

Using HttpResponseException

This exception class allows us to return HttpResponseMessage to the client. It returns HTTP status code that is specified in the exception Constructor. 

For example, the following method of EmployeeController returns Status code 404 (not found), if employee data is not found for ID.

public Employee Get([FromODataUri] int key)  
{  
    Employee data = context.Employees.Where(k => k.Id == key).FirstOrDefault();  
  
    if (data == null)  
    {  
        var response = new HttpResponseMessage(HttpStatusCode.NotFound)  
        {  
            Content = new StringContent(string.Format("No Employee found with ID = {0}", key)),  
                ReasonPhrase = "Employee Not Found"  
        };  
  
        throw new HttpResponseException(response);  
    }  
    return data;  


Using HttpError

CreateErrorResponse method of Request object helps us to return meaningful error code and message to the client. CreateErrorResponse creates an instance of HttpError object and returns it as HttpResponseMessage object.
public HttpResponseMessage Get([FromODataUri] int key)  
{  
    Employee data = context.Employees.Where(k => k.Id == key).FirstOrDefault();  
    if (data == null)  
    {  
        string message = string.Format("No Employee found with ID = {0}", key);  
        return Request.CreateErrorResponse(HttpStatusCode.NotFound, message);  
    }  
    return Request.CreateResponse(HttpStatusCode.OK, data);;  
}  

Using Exception Filters

Exception filters can be used to handle unhandled exceptions which are generated in Web API. The exception filter can be able to catch the unhandled exceptions in Web API. This filter is executed when an action method throws the unhandled exception. Note that exception filter does not catch HttpResponseException exception because HttpResponseException is specifically designed to return the HTTP response.

namespace WebAPITest  
{  
    using System.Net;  
    usingSystem.Net.Http;  
    usingSystem.Web.Http.Filters;  
  
    public class CustomExceptionFilter: ExceptionFilterAttribute  
    {  
        public override void OnException(HttpActionExecutedContextactionExecutedContext)  
        {  
            string exceptionMessage = string.Empty;  
            if (actionExecutedContext.Exception.InnerException == null)  
            {  
                exceptionMessage = actionExecutedContext.Exception.Message;  
            }  
            else  
            {  
                exceptionMessage = actionExecutedContext.Exception.InnerException.Message;  
            }  
            //We can log this exception message to the file or database.  
            var response = newHttpResponseMessage(HttpStatusCode.InternalServerError)  
            {  
                Content = newStringContent(“An unhandled exception was thrown by service.”),  
                    ReasonPhrase = "Internal Server Error.Please Contact your Administrator."  
            };  
            actionExecutedContext.Response = response;  
        }  
    }  
}  


Register Exception Filters

Decorate Action with exception filter.
Decorate Controller with exception filter.
Filter Register globally.

To apply the exception filter to all Web API controllers, the filter needs to register to GlobalConfiguration.Configuration.Filters collection.
public static class WebApiConfig  
{  
    public static void Register(HttpConfigurationconfig)  
    {  
        config.Filters.Add(newCustomExceptionFilter());  
    }  
}  

Using Exception Handlers

Normally, exception filter is used to catch the unhandled exception. This approach will work fine but it fails if any error is raised from outside action. For example, if any error is raised in the following area then exception filter will not work.
Error inside the exception filter.
Exception related to routing.
Error inside the Message Handlers class.
Error in Controller Constructor.


https://www.c-sharpcorner.com/article/exception-handling-in-asp-net-web-api/

Modify Header in Web API

You will need to create a custom filter and apply that to your controller .
public class CustomHeaderFilter : ActionFilterAttribute
{
    public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
    {
       var count = actionExecutedContext.Request.Properties["Count"];
       actionExecutedContext.Response.Content.Headers.Add("totalHeader", count);
    }
}

How to make Post Cacheable?

Being cacheable is one of architectural constraints of REST. GET requests should be cachable by default – until special condition arises. Usually, browsers treat all GET requests cacheable. POST requests are not cacheable by default but can be made cacheable if either an Expires header or a Cache-Control header with a directive, to explicitly allows caching, is added to the response. Responses to PUT and DELETE requests are not cacheable at all.
There are two main HTTP response headers that we can use to control caching behavior:

Expires

The Expires HTTP header specifies an absolute expiry time for a cached representation. Beyond that time, a cached representation is considered stale and must be re-validated with the origin server. To indicate that a representation never expires, a service can include a time up to one year in the future.
Expires: Fri, 20 May 2016 19:20:49 IST

Cache-Control

The header value comprises one or more comma-separated directives. These directives determine whether a response is cacheable, and if so, by whom, and for how long e.g. max-age or s-maxage directives.
Cache-Control: max-age=3600
Cacheable responses (whether to a GET or to a POST request) should also include a validator — either an ETag or a Last-Modified header.

ETag

An ETag value is an opaque string token that a server associates with a resource to uniquely identify the state of the resource over its lifetime. When the resource changes, the ETag changes accordingly.
ETag: "abcd1234567n34jv"

Last-Modified

Whereas a response’s Date header indicates when the response was generated, the Last-Modified header indicates when the associated resource last changed. The Last-Modified value cannot be later than the Date value.

Source : https://restfulapi.net/caching/


So let’s say that the client sends a request for some metadata, and we want the client to cache it for 1 hour:
GET /customers/metadata HTTP/1.1
Host: api.example.com
Accept: application/json
Accept-Language: en
To do this, we just add the Cache-Control header to our response:
HTTP/1.1 200 OK
Content-Type: application/json
Cache-Control: max-age=3600
Content-Length: 88
Etag: "6d82cbb050ddc7fa9cbb659014546e59"

{
  "languageCodes": [
    {"da":"Danish"},
    {"no":"Norwegian"},
    {"en":"English"}
  ]
}
Source: https://www.kennethlange.com/boost-your-rest-api-with-http-caching/

Caching in Web API

Caching is a technique of storing frequently used data or information in a local memory, for a certain time period. So, next time, when the client requests the same information, instead of retrieving the information from the database, it will give the information from the local memory.

By default get is not cacheable, you need to make it using Action Filter

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Net.Http.Headers;  
using System.Web;  
using System.Web.Http.Filters;  
  
namespace Caching_In_API  
{  
    public class CacheFilter : ActionFilterAttribute  
    {  
        public int TimeDuration { get; set; }  
    public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)  
    {  
        actionExecutedContext.Response.Headers.CacheControl = new CacheControlHeaderValue  
        {  
            MaxAge = TimeSpan.FromSeconds(TimeDuration),  
            MustRevalidate = true,  
            Public = true  
        };  
    }  
    }  



https://www.c-sharpcorner.com/article/implementing-caching-in-web-api/

What are resource in Web API

Ques :
Is the following URL a resource? If it is, what is the name of that resource and what is its representation?
The GET response of the URL should look something like:
[
   {
      id: 6,
      name: "John"
   },
   {
      id: 7,
      name: "Jane"
   }
]

Ans:

REST architecture treats every content as a resource. These resources can be Text Files, Html Pages, Images, Videos or Dynamic Business Data. REST Server simply provides access to resources and REST client accesses and modifies the resources. Here each resource is identified by URIs/ Global IDs. REST uses various representations to represent a resource where Text, JSON, XML. The most popular representations of resources are XML and JSON.

Representation of Resources

A resource in REST is a similar Object in Object Oriented Programming or is like an Entity in a Database. Once a resource is identified then its representation is to be decided using a standard format so that the server can send the resource in the above said format and client can understand the same format.
For example, in RESTful Web Services - First Application chapter, a user is a resource which is represented using the following XML format −
 
   1
Mahesh Teacher
The same resource can be represented in JSON format as follows −
{ 
   "id":1, 
   "name":"Mahesh", 
   "profession":"Teacher" 
}

Source : https://www.tutorialspoint.com/restful/restful_resources.htm

The URL is never a resource or its name or its representation.
URL just tells where the resource is located and You can invoke GET,POST,PUT,DELETE etc on this URL to invoke the resource.
Data responded back are the resources while the form of the data is its representation.
Let's say Your URL with given GET parameters can output a JSON resource - this is the JSON representation of this resource. While with other flag in the GET it could respond with the same data in XML - that will be another representation of the very same resource.
Another definition
Also the resource name is considered to be the 'script name', e.g. in this case it is users.jsonwhile this resource name is self describing the resource representation itself - when calling this resource we expect the resource is in JSON, while when calling e.g. users.xml we would expect the data in XML.
  1. When I change the offset parameter in GET the response contains different data set - is it a new resource or its representation?
  2. When I define which columns are returned in response in GET, is it a different resource or different representation, or?
  1. Well, here the problem and answer are clear - we still call the same URL, the server responses with the data in the same form (still it is JSON), data still contains information about users - just the information itself has changed due to the new offset parameter. So it is obvious that it is still the same resource with the same representation and the same resource name as before.
  2. Second problem could be a little confusing. Though we are calling the same resource, though the resource contains the same data (just with only predefined column set) and though the data is in the same representation it could seem to us as a different resource. But due to the points in the paragraph above it is nor the different resource or different representation. Though the data set contains less information the requesting side (filtering this data set) should be considering this and behave accordingly. So again: it is the same resource with the same resource name and the same resource representation.

Content Negotiation in WebAPI

Content negotiation defined as "the process of selecting the best representation for a given response when there are multiple representations available."

The primary mechanism for content negotiation in HTTP are these request headers:

Accept: Which media types are acceptable for the response, such as "application/json," "application/xml," or a custom media type such as "application/vnd.example+xml"
Accept-Charset: Which character sets are acceptable, such as UTF-8 or ISO 8859-1.
Accept-Encoding: Which content encodings are acceptable, such as gzip.
Accept-Language: The preferred natural language, such as "en-us".

Serialization
If a Web API controller returns a resource as CLR type, the pipeline serializes the return value and writes it into the HTTP response body.

For example, consider the following controller action:

C#

Copy
public Product GetProduct(int id)
{
    var item = _products.FirstOrDefault(p => p.ID == id);
    if (item == null)
    {
        throw new HttpResponseException(HttpStatusCode.NotFound);
    }
    return item; 
}
A client might send this HTTP request:

console

Copy
GET http://localhost.:21069/api/products/1 HTTP/1.1
Host: localhost.:21069
Accept: application/json, text/javascript, */*; q=0.01
In response, the server might send:

console

Copy
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Content-Length: 57
Connection: Close

{"Id":1,"Name":"Gizmo","Category":"Widgets","Price":1.99}
In this example, the client requested either JSON, Javascript, or "anything" (*/*). The server responsed with a JSON representation of the Product object. Notice that the Content-Type header in the response is set to "application/json".

The object that serializes the resource is called a media formatter. Media formatters derive from the MediaTypeFormatter class. Web API provides media formatters for XML and JSON, and you can create custom formatters to support other media types.


https://docs.microsoft.com/en-us/aspnet/web-api/overview/formats-and-model-binding/content-negotiation

Area in MVC

ASP.NET MVC 2 introduced Area. Area allows us to partition large application into smaller units where each unit contains separate MVC folder structure, same as default MVC folder structure. For example, large enterprise application may have different modules like admin, finance, HR, marketing etc. So an Area can contain separate MVC folder structure for all these modules

The following is adminAreaRegistration class created with admin area.

Area Registration:
public class adminAreaRegistration : AreaRegistration 
{
    public override string AreaName 
    {
        get 
        {
            return "admin";
        }
    }

    public override void RegisterArea(AreaRegistrationContext context) 
    {
        context.MapRoute(
            "admin_default",
            "admin/{controller}/{action}/{id}",
            new { action = "Index", id = UrlParameter.Optional }
        );
    }
}
AreaRegistration class overrides RegisterArea method to map the routes for the area. In the above example, any URL that starts with admin will be handled by the controllers included in the admin folder structure under Area folder. For example, http://localhost/admin/profile will be handled by profile controller included in Areas/admin/controller/ProfileController folder.

Finally, all the area must be registered in Application_Start event in Global.asax.cs as AreaRegistration.RegisterAllAreas();

http://www.tutorialsteacher.com/mvc/area-in-asp.net-mvc

Followers

Link