Thursday, 15 November 2018

Exception Handling in Web API

Exception Handling in ASP.NET Web API
There are many ways to handle the exception.
  1. HttpResponseException
  2. Exception Filters
  3. HttpError
HttpResponseException: This exception class allows us to return HttpResponseMessage to the client. It returns HTTP status code that is specified in the exception Constructor.

public Product GetProduct(int id{
    Product item = repository.Get(id);
if (item == null)
throw new HttpResponseException(HttpStatusCode.NotFound);
return item;

Exception Filters: You can customize how Web API handles exceptions by writing an exception filter. An exception filter is executed when a controller method throws any unhandled exception that is not an HttpResponseException exception. The HttpResponseException type is a special case, because it is designed specifically for returning an HTTP response. Exception filters implement the System.Web.Http.Filters.IExceptionFilter interface.
The simplest way to write an exception filter is to derive from the System.Web.Http.Filters.ExceptionFilterAttribute class and override the OnException method.

public class NotImplExceptionFilterAttribute : ExceptionFilterAttribute
public override void OnException(HttpActionExecutedContext context)
if (context.Exception is NotImplementedException)
context.Response = new HttpResponseMessage(HttpStatusCode.NotImplemented);

Register Exception Filters
There are many ways to register exception filter but the developers generally follow three approaches to register filter.
  1. Decorate Action with exception filter.
  2. Decorate Controller with exception filter.
  3. Filter Register globally.
To apply the filter to a specific action, add the filter as an attribute to the action:

public class ProductsController : ApiController { [NotImplExceptionFilter] public Contact GetContact(int id) { throw new NotImplementedException("This method is not implemented"); } }

To apply the filter to all of the actions on a controller, add the filter as an attribute to the controller class:

[NotImplExceptionFilter] public class ProductsController : ApiController { // ... }

To apply the filter globally to all Web API controllers, add an instance of the filter to the GlobalConfiguration.Configuration.Filters collection. Exeption filters in this collection apply to any Web API controller action.

public static class WebApiConfig { public static void Register(HttpConfiguration config) { config.Filters.Add(new ProductStore.NotImplExceptionFilterAttribute()); // Other configuration code... } }

HttpError: CreateErrorResponse method of Request object helps us to return meaningful error code and message to the client.

public HttpResponseMessage GetProduct(int id{
    Product item = repository.Get(id);
if (item == null)
var message = string.Format("Product with id = {0} not found", id);
return Request.CreateErrorResponse(HttpStatusCode.NotFound, message);
return Request.CreateResponse(HttpStatusCode.OK, item);
Continue Reading →

Wednesday, 31 October 2018

RXJS Operators

Operators By Category

1- Creating Observables

Operators that originate new Observables.
  • Create — create an Observable from scratch by calling observer methods programmatically
  • Defer — do not create the Observable until the observer subscribes, and create a fresh Observable for each observer
  • Empty/Never/Throw — create Observables that have very precise and limited behavior
  • From — convert some other object or data structure into an Observable
  • Interval — create an Observable that emits a sequence of integers spaced by a particular time interval
  • Just — convert an object or a set of objects into an Observable that emits that or those objects
  • Range — create an Observable that emits a range of sequential integers
  • Repeat — create an Observable that emits a particular item or sequence of items repeatedly
  • Start — create an Observable that emits the return value of a function
  • Timer — create an Observable that emits a single item after a given delay

2- Transforming Observables

Operators that transform items that are emitted by an Observable.
  • Buffer — periodically gather items from an Observable into bundles and emit these bundles rather than emitting the items one at a time
  • FlatMap — transform the items emitted by an Observable into Observables, then flatten the emissions from those into a single Observable
  • GroupBy — divide an Observable into a set of Observables that each emit a different group of items from the original Observable, organized by key
  • Map — transform the items emitted by an Observable by applying a function to each item
  • Scan — apply a function to each item emitted by an Observable, sequentially, and emit each successive value
  • Window — periodically subdivide items from an Observable into Observable windows and emit these windows rather than emitting the items one at a time

3- Filtering Observables

Operators that selectively emit items from a source Observable.
  • Debounce — only emit an item from an Observable if a particular timespan has passed without it emitting another item
  • Distinct — suppress duplicate items emitted by an Observable
  • ElementAt — emit only item n emitted by an Observable
  • Filter — emit only those items from an Observable that pass a predicate test
  • First — emit only the first item, or the first item that meets a condition, from an Observable
  • IgnoreElements — do not emit any items from an Observable but mirror its termination notification
  • Last — emit only the last item emitted by an Observable
  • Sample — emit the most recent item emitted by an Observable within periodic time intervals
  • Skip — suppress the first n items emitted by an Observable
  • SkipLast — suppress the last n items emitted by an Observable
  • Take — emit only the first n items emitted by an Observable
  • TakeLast — emit only the last n items emitted by an Observable

4- Combining Observables

Operators that work with multiple source Observables to create a single Observable
  • And/Then/When — combine sets of items emitted by two or more Observables by means of Patternand Plan intermediaries
  • CombineLatest — when an item is emitted by either of two Observables, combine the latest item emitted by each Observable via a specified function and emit items based on the results of this function
  • Join — combine items emitted by two Observables whenever an item from one Observable is emitted during a time window defined according to an item emitted by the other Observable
  • Merge — combine multiple Observables into one by merging their emissions
  • StartWith — emit a specified sequence of items before beginning to emit the items from the source Observable
  • Switch — convert an Observable that emits Observables into a single Observable that emits the items emitted by the most-recently-emitted of those Observables
  • Zip — combine the emissions of multiple Observables together via a specified function and emit single items for each combination based on the results of this function

5- Error Handling Operators

Operators that help to recover from error notifications from an Observable
  • Catch — recover from an onError notification by continuing the sequence without error
  • Retry — if a source Observable sends an onError notification, resubscribe to it in the hopes that it will complete without error

6- Observable Utility Operators

A toolbox of useful Operators for working with Observables
  • Delay — shift the emissions from an Observable forward in time by a particular amount
  • Do — register an action to take upon a variety of Observable lifecycle events
  • Materialize/Dematerialize — represent both the items emitted and the notifications sent as emitted items, or reverse this process
  • ObserveOn — specify the scheduler on which an observer will observe this Observable
  • Serialize — force an Observable to make serialized calls and to be well-behaved
  • Subscribe — operate upon the emissions and notifications from an Observable
  • SubscribeOn — specify the scheduler an Observable should use when it is subscribed to
  • TimeInterval — convert an Observable that emits items into one that emits indications of the amount of time elapsed between those emissions
  • Timeout — mirror the source Observable, but issue an error notification if a particular period of time elapses without any emitted items
  • Timestamp — attach a timestamp to each item emitted by an Observable
  • Using — create a disposable resource that has the same lifespan as the Observable

7- Conditional and Boolean Operators

Operators that evaluate one or more Observables or items emitted by Observables
  • All — determine whether all items emitted by an Observable meet some criteria
  • Amb — given two or more source Observables, emit all of the items from only the first of these Observables to emit an item
  • Contains — determine whether an Observable emits a particular item or not
  • DefaultIfEmpty — emit items from the source Observable, or a default item if the source Observable emits nothing
  • SequenceEqual — determine whether two Observables emit the same sequence of items
  • SkipUntil — discard items emitted by an Observable until a second Observable emits an item
  • SkipWhile — discard items emitted by an Observable until a specified condition becomes false
  • TakeUntil — discard items emitted by an Observable after a second Observable emits an item or terminates
  • TakeWhile — discard items emitted by an Observable after a specified condition becomes false

8- Mathematical and Aggregate Operators

Operators that operate on the entire sequence of items emitted by an Observable
  • Average — calculates the average of numbers emitted by an Observable and emits this average
  • Concat — emit the emissions from two or more Observables without interleaving them
  • Count — count the number of items emitted by the source Observable and emit only this value
  • Max — determine, and emit, the maximum-valued item emitted by an Observable
  • Min — determine, and emit, the minimum-valued item emitted by an Observable
  • Reduce — apply a function to each item emitted by an Observable, sequentially, and emit the final value
  • Sum — calculate the sum of numbers emitted by an Observable and emit this sum

9- Backpressure Operators

  • backpressure operators — strategies for coping with Observables that produce items more rapidly than their observers consume them

10- Connectable Observable Operators

Specialty Observables that have more precisely-controlled subscription dynamics
  • Connect — instruct a connectable Observable to begin emitting items to its subscribers
  • Publish — convert an ordinary Observable into a connectable Observable
  • RefCount — make a Connectable Observable behave like an ordinary Observable
  • Replay — ensure that all observers see the same sequence of emitted items, even if they subscribe after the Observable has begun emitting items

11- Operators to Convert Observables

  • To — convert an Observable into another object or data structure

To read more about

Continue Reading →

Tuesday, 23 October 2018

UI Framework Questions

What is React JS?
ReactJS basically is an open-source JavaScript library which is used for building user interfaces specifically for single page applications. It’s used for handling view layer for web and mobile apps. React also allows us to create reusable UI components.

React allows developers to create large web applications which can change data, without reloading the page. The main purpose of React is to be fast, scalable, and simple. It works only on user interfaces in application. This corresponds to view in the MVC template. It can be used with a combination of other JavaScript libraries or frameworks, such as Angular JS in MVC.

What is Redux
Redux is a predictable state container for JavaScript apps.
Redux makes it easy to manage the state of your application. Another way of looking at this – it helps you manage the data you display and how you respond to user actions.

What is Webpack
Webpack is an open-source JavaScript module bundler. Its main purpose is to bundle JavaScript files for usage in a browser, yet it is also capable of transforming, bundling, or packaging just about any resource or asset. Webpack takes modules with dependencies and generates static assets representing those modules.

What is Babel
Babel is a JavaScript compiler.

Babel is a toolchain that is mainly used to convert ECMAScript 2015+ code into a backwards compatible version of JavaScript in current and older browsers or environments. Here are the main things Babel can do for you:

What is the difference between CSS and SASS?
Sass is a preprocessor for CSS, which makes it essentially the same thing as CSS. Being a preprocessor, you code in Sass and later the code is compiled into CSS. It functions as a (amazing) power-up for CSS, enabling features that are yet to exist in CSS. Sass’ main goal is to improve maintainability as your stylesheets getting larger and more complex. Some handy features Sass provided are:
  1. Variables, you can store reusable values with variables, this can be handy to store values like color hex code or a font stack.
  2. Nesting, you can write hierarchical CSS selectors simpler with Sass, just write it in nests just like what we do with HTML elements.
  3. Partials, you can write your stylesheet in a modular way using partials and import statements, improving your code maintainability and readability.
  4.  Mixins, they are like functions which you can define and reuse throughout your stylesheets. For example, sometimes we have to write one declaration for each rendering engine, like border-radius that should be accompanied by -webkit-border-radius, -moz-border-radius and so on. You can group all those border-radius statements into one mixin and just use the mixin whenever you need to define the border-radius for your element. Neat, isn’t it?
  5. Extension and Inheritance, which lets you share a set of CSS properties across your stylesheets.
  6. Mathematical Operators, like +, -, *, /, and % to aid you in determining various numbers throughout your stylesheets.

Continue Reading →

Select and where in Lamda

Where: Filters a sequence of values based on a predicate.

Select: Projects each element of a sequence into a new form.

     //Output: 1,2,3,4,5,6,7,8,9,10
            var numbers = Enumerable.Range(1, 10);
            //Output:  2,4,6,8,10
            var even = numbers.Where(n => (n % 2) == 0).ToList();

            //Output: false,true,false,true,false,....true
            var evens = numbers.Select(n => (n % 2) == 0).ToList();

            //Output: 1,2,3,4,5,6,...10
            var lineNumbers = numbers.Select(i => i).ToList();

Continue Reading →


ADO .Net (2) Ajax (1) Angular Js (17) Angular2 (24) ASP .Net (14) Azure (1) Breeze.js (1) C# (49) CloudComputing (1) CMS (1) CSS (2) Design_Pattern (3) DI (3) Dotnet (21) Entity Framework (3) ExpressJS (4) Html (3) IIS (1) Javascript (6) Jquery (9) Lamda (3) Linq (11) Mongodb (1) MVC (48) NodeJS (7) RDLC (1) Report (1) Sql Server (29) SSIS (3) SSRS (2) UI (1) WCF (12) Web Api (10) Web Service (1) XMl (1)