11+ Year IT Industry Experience, Working as Technical Lead with Capgemini | Consultant | Leadership and Corporate Trainer | Motivational and Technical Speaker | Career Coach | Author | MVP | Founder Of RVS Group | Trained more than 4000+ IT professionals | Azure | DevOps | ASP.NET | C# | MVC | WEB API | ANGULAR | TYPESCRIPT | MEAN | SQL | SSRS | WEB SERVICE | WCF... https://bikeshsrivastava.blogspot.in/ http://bikeshsrivastava.com/
Tuesday, July 26, 2016

WebApi Load performance testing tool.

Today i am going to explain about Web api or web application Load testing tool "APACHE JMETER".You can create concurrent user at a time APACHE JMETER create thread group according concurrent user.

Apache JMeter is used to test performance  static and dynamic resources both  (Webservices (SOAP/REST), Web dynamic languages  in  PHP, Java, ASP.NET, Files, etc...  Java Objects, Data Bases  Queries, FTP Servers and more other..).


 It can be used to simulate a heavy load on any server, group of any servers, any network or any object to test its strength or to analyze overall Load  performance under different load types. You can use it to make a graphical analysis chart,Excel report,csv report, of performance or to test your server/script/object behavior under heavy concurrent load.

Features of APACHE JMETER:-
  • You can test performance on many different server/protocol types using jmeter:
    • Web - HTTP, HTTPS protocol 
    • SOAP / REST services.
    • FTP
    • Database via JDBC 
    • LDAP  authentication.
    • Message-oriented middleware (MOM) via JMS in java.
    • Mail - SMTP(S), POP3(S) and IMAP(S)
    • Native commands or shell scripts
    • TCP protocol 
  • Complete portability and 100% Java purity.
  • its support fully multi-threading framework allows concurrent sampling user  by many threads and simultaneous sampling of different functions by separate thread groups.
  • Careful GUI design allows faster Test Plan building and debugging.
  • Caching and offline analysis/replaying data  of test results very fast.
  • you can make report in form of graph,csv,excel..etc....
        How to use APACHE JMETER to test WebApi?
Step 1:-Download and  install on your machine.but you need to install java environment because its pure java application.  

Step 2:- Create a test plan.see image ................



Step 3:- Create thread group(concurrent user) following these step.............
Add=>Threads(Users)=>Thread group...thereafter open new panel, according your requirment you can set any number of concurrent user(thread). .see image ................


Step 4:-You can add httpheader parameter see image...

after adding httpheader panel you add header parameters like this see image.

Step 5:-You can add httprequest  parameter see image...



Thereafter you'll set your request parameter,proxy,baseurl,relativeurl.etc...

Step 6:-If you are using any type of authentication in your application you'll set authentication part ..see image.

Step 7:-Add listener panel to show performance report ,there are many type of report format  you can select any .see image.........

Step 8:-Check your all setting again and click on start button which is in top of screen(green button)
After click on START you can check you request and response data on view result panel.
see image............

click on summery report you report is generated in the form of table ,you save it in own form. 

Note:-This is best tool to test load performance of any web application or web api.
Bikesh Srivastava Interview Question, MVC, WEB API
Monday, July 25, 2016

What is difference between constant,readonly,dynamic,var and static in C# ?

Today i am going to explain about constant(const),readonly,dynamic.var and static in c#.Also i going to differentiate about these c# keyword because most of developer confused about these keyword in c#. 




                        constant (const)
In c#  the constants refer to fixed values of variable  that the program may not change during its execution time . These fixed values of variable  are also called literals.you can assign constants can be of any of the basic data types like an integer, a floating, a character,or a string literal. See image ..........




                             readonly
In the c# readonly keyword is use as  a modifier for field. Whenever you a field declaration includes a readonly modifier in c#, assignments to the fields value  introduced by the declaration can only occur as part of the declaration or in a constructor in the same class.A field that can  marked as "readonly", can only be set once during the construction of an object (in the constructor). See image..........



"Readonly" is the keyword whose assigned  value we can change during runtime process or we can assign value  it at run time but only through the non-static constructor. Not even a method or function.

                                    static
In c# each object has its own set of member,properties ,variables and all the member variables have a scope part.
If you want a variable to have the same value throughout all instances of the object then we can declare it as a static variable in our program. To manipulate and use the values of static variables we can also define a function as static.

In c# the keyword "static" means that only one instance  of a given variable exists for a class. Static variables are used to define constants because their values can be retrieved by invoking the class without creating an instance of it.


In c# static variables can be initialized outside the member function or class definition. The following code is an example of a static variable, which shows the declaration and initialization of a static variable.See image.......


                                                               Dynamic
In c# 4.0 the dynamic keyword is new, and is used to tell the compiler that a variable's type can change or that it is not known until run-time.It means, their type is inferred at run-time and not at  the compile time execution  in contrast to var type.See image............




                                           var
From c# 3.0 “Var” Keyword = Var keyword is an implicit way to defining Datatypes. Implicit means indirect way to defining variable types.

In  c# it means data at the right hands side the left hands side data types is defined by the compiler during the generation of the “IL” code. See image..........




              
       Difference between "object" "var" and "dynamic"


Object keyword
Var keyword
Dynamic keyword
Added in C# 1.0.
Added in C# 3.0.
Added in  C# 4.0.
object in c# can store any kind of value,data, it is base class in c#.
It can also store any type of value but It must to initialize var types value at the time of declaration .
It can also  store any type of the variable, 
its Compiler has little information about the type.store in heap.
It is type safe i.e. Compiler has all information about the stored value, so that it doesn't cause any issue at run-time.
It is not type safe i.e. Compiler doesn't have any information about the type of variable.
it  can be passed as method argument and method also can return object type data .
Var type cannot be passed as method argument and method cannot return object data. Var type work in the scope where it defined.
Dynamic type can be passed as method argument and method also can return dynamic type.
Need to cast object variable to original type to use it and performing desired operations.
No need to typecast because compiler has all information to perform operations.
Casting is not required but you need to know the properties and methods related to stored type name .
Cause the problem at run time if the stored value is not getting typecast to underlying data type.
Doesn't cause problem because compiler has all information about stored value.
Cause problem if the wrong properties or methods are accessed because all the information about stored value is get resolve only at run time.
Useful when we don’t have more information about the data type.

=>Intelligence available  
Useful when we don’t know actual type i.e. type is anonymous.


=>Intelligence available 
Useful when we need to code using reflection or dynamic languages or with the COM objects, because you need to write less code.
=>Intelligence not  available 

   
Difference between "readonly" "const" and "static"




Bikesh Srivastava C#, Interview Question
Monday, July 18, 2016

How to use Area in MVC ?

Today i am going to explain about "area" in MVC.In very short, we can say "an area is sub part of MVC application, can be defined as Smaller functional units in an ASP.NET MVC project with its own set of whole features(model,view,controller,web.config).Inside a single MVC application we can create multiple "area".we can understand area after showing this image given below.


Area image

Blog,Help Desk,Shopping is Area which is inside a Main application MVC project.

How To use area inside MVC application:-

Step 1:-Create a MVC Project.

MVC page

Step 2:-You can see your application without area.Run application without area it'll working fine.
Solution page

Step 3:-Add area in your application.see image.

add area

Now you can add multiple area in any type of MVC application.Now i am adding a area name is "Mens".see image

Show solution

Now i am going to add next area name is "Womans".see image.

show area

Now you can see in image I've added two area in Main application.
Now you are able to create model,view,controller inside any area according your requirment as well as Main application.
Note:-If you are using any area in Mvc Application then you'll have to change your Route.config file because default routing have ambiguity problem .otherwise after run application throw error like this.see image.

Step 4:-Create controller , action for each area and view.

Error page

But you can hit directly using area path .see image.
Output

Step 5:-Change route.config file.see  image.

routing

If you want default route is any area then you'll have to add 
.DataTokens["area"]= "Test"; line inside route.config file.otherwise  by default page working fine from Main application. Be aware about route configuration (Controller name,Action name);

Now you are ready to work with area in MVC.

Step 6:- How to redirect one area to other area in mvc?
Hyperlink from one area view to other area view use this code.

 @Html.ActionLink("Redirect to other View", "Index", "Home", new { Area = "womans" },null)


Step 7:- Run application.








Bikesh Srivastava Interview Question, MVC
Monday, July 11, 2016

What is Filter in MVC ?

Today i am going to explain how to use Filter in MVC application .In this part of blog we will try to describe how we can use custom filters and attributes in an ASP.NET MVC application.

Why we can use Filter in MVC:-
Sometime we need to add logic either before or after an action method runs.To support this type of feature in MVC useing Filter.

Types of Filter in MVC:-

1. Action Filter
2. Authorization Filter
3. Result Filter
4. Exception Filter

1.Authorization Filter:-
This Filter will be execute before action start executing .this  filter is  use to authorize a request for action . We will add the filter object in Global.asax or any other class inside application. These interfaces and event use in this filter.
Interface:- IAuthorizationFilter
event:- OnAuthorization

Example with code:-

public class AuthorizationFilterAttribute : FilterAttribute, IAuthorizationFilter
{
    void IAuthorizationFilter.OnAuthorization(AuthorizationContext filterContext)
    {
        filterContext.Controller.ViewBag.AuthorizedMessage = "AuthorizationFilter filter is called before action.";
    }
}


2.Action Filter:-
This Filter will be execute before and after action start executing .In this  filter we can use pre-processing and post-processing logic.. We will add the filter object in Global.asax or any other class inside application. These interfaces and event use in this filter.
Interface:- IActionFilter
event:-  1.OnActionExecuting
               2.OnActionExecuted

Example with code:-

public class ActionFilterAttribute : FilterAttribute, IActionFilter
{
    void IActionFilter.OnActionExecuted(ActionExecutedContext filterContext)
    {
        filterContext.Controller.ViewBag.ActionMessage1 = "IActionFilter.OnActionExecuted event fire and filter is called";
    }

    void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext)
    {
        filterContext.Controller.ViewBag.ActionMessage2 = "IActionFilter.OnActionExecuting event fire and filter called";
    }
}


3.Result Filter:-
This Filter will be execute before and after action start executing .We can use this Filter  in the event that we need some adjustment to be done in the Action outcome.  We will add the filter object in Global.asax or any other class inside application. These interfaces and event use in this filter.
Interface:- IResultFilter
event:- 1.OnResultExecuted
             2.OnResultExecuting

Example with code:-

public class ResultFilterAttribute : FilterAttribute, IResultFilter
{
    void IResultFilter.OnResultExecuted(ResultExecutedContext filterContext)
    {
        filterContext.Controller.ViewBag.ResultMessage1 = "IResultFilter.OnResultExecuted event fire and filter called";
    }

    void IResultFilter.OnResultExecuting(ResultExecutingContext filterContext)
    {
        filterContext.Controller.ViewBag.ResultMessage2= "IResultFilter.OnResultExecuting event fire and filter called";
    }
}

4.Exception Filter:-
This Filter will be execute whenever any action of the controller throw exception.this  filter is  mainly use to custom error  logging module.We will add the filter object in Global.asax or any other class inside application. These interfaces and event use in this filter.
Interface:- IExceptionFilter
event:-  OnException

Example with code:-

public class ExceptionFilterAttribute : FilterAttribute, IExceptionFilter
{
    void IExceptionFilter.OnException(ExceptionContext filterContext)
    {
        filterContext.Controller.ViewBag.ExceptionMessage = "IExceptionFilter.OnException event fire and filter called";
    }
}

Execution Flow (Order) of Filter:-


IAuthorizationFilter.OnAuthorization
||
IActionFilter.OnActionExecuting
||
IActionFilter.OnActionExecuted
||
IResultFilter.OnResultExecuting IResultFilter.OnResultExecuted
||
//If throwing any exception from action where you are using Exception filter then hit this method
||
IExceptionFilter.OnException



Simple example with MVC application:-

Step 1:-Create Mvc Application and type All filter code inside Global.asax like this.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;

namespace MVC_Filter
{
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {//register all configuration with Filter
            AreaRegistration.RegisterAllAreas();
            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            AuthConfig.RegisterAuth();
        }
    }
//Autherization Filter
    public class AuthorizationFilterAttribute : FilterAttribute, IAuthorizationFilter
    {
        void IAuthorizationFilter.OnAuthorization(AuthorizationContext filterContext)
        {
            filterContext.Controller.ViewBag.AuthorizedMessage = "AuthorizationFilter filter is called before action.";
        }
    }
//Action Filter
    public class ActionFilterAttribute : FilterAttribute, IActionFilter
    {
        void IActionFilter.OnActionExecuted(ActionExecutedContext filterContext)
        {
            filterContext.Controller.ViewBag.ActionMessage1 = "IActionFilter.OnActionExecuted event fire and filter is called";
        }

        void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext)
        {
            filterContext.Controller.ViewBag.ActionMessage2= "IActionFilter.OnActionExecuting event fire and filter called";

        }
    }
//Result Filter
    public class CustomResultAttribute : FilterAttribute, IResultFilter
    {
        void IResultFilter.OnResultExecuted(ResultExecutedContext filterContext)
        {
            filterContext.Controller.ViewBag.ResultMessage1 = "IResultFilter.OnResultExecuted event fire and filter called";
        }

        void IResultFilter.OnResultExecuting(ResultExecutingContext filterContext)
        {
            filterContext.Controller.ViewBag.ResultMessage2 = "IResultFilter.OnResultExecuting event fire and filter called";
        }
    }
//Execption Filter
    public class ExceptionFilterAttribute : FilterAttribute, IExceptionFilter
    {
        void IExceptionFilter.OnException(ExceptionContext filterContext)
        {
            Exception ex = filterContext.Exception;
            filterContext.ExceptionHandled = true;

            var ControllerName = (string)filterContext.RouteData.Values["controller"];
            var ActionName= (string)filterContext.RouteData.Values["action"];
            var model = new HandleErrorInfo(filterContext.Exception, ControllerName , ActionName);
            filterContext.Result = new ViewResult()
            {
                ViewName = "ErrorPage",
                ViewData = new ViewDataDictionary(model),
            };
        }
    }
}

Step 2:-Create a controller and action.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Mvc_testFilter.Models;

namespace Mvc_testFilter.Controllers
{
    public class HomeFilterController : Controller
    {//using Filter as attribute
        [AuthorizationFilter]
        [ActionFilter]
        [ResultFilter]
        [ExceptionFilter]
        public ActionResult Index()
        {
            //  To Exception Filter testing purpose
            //int i = 0;
            //int j = 10;
            //int result = j / i;

            return View();
        }
    }
}
Step 3:-Right Click on =>Index=>AddView=>Create a new view name is"Index".


@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Testing page for Filter::</title>
</head>
<body>
    <div>
        <h1>Excuting Filter Attribute</h1>
        <ul>
            <li>@ViewBag.Message</li>
//View bag data is coming from Filter class according error in order(Flow).
            <li>@ViewBag.ActionMessage1</li>
            <li>@ViewBag.ActionMessage2</li>
            
            <li>@ViewBag.ResultMessage1</li>
            <li>@ViewBag.ResultMessage2</li>
        </ul>
    </div>
</body>
</html>

Step 4:-Right Click on =>View Folder=>AddView=>Create a new view name is"ErrorPage".

@model System.Web.Mvc.HandleErrorInfo //use this class on view.

@{
    ViewBag.Title = "ErrorPage";
}

<hgroup class="title">
    <h1 class="error">Error.</h1>
    <h2 class="error">An error occurred while exception throw when processing your request.</h2>
</hgroup>

Step 5:-Check your FilterConfig.cs file inside App_Start folder.

using System.Web;
using System.Web.Mvc;
namespace Tcl_IzoGlass
{
    public class FilterConfig
    {
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
        }
    }
}

Step 6:-Register FilterConfig class inside Global.asax which is already define above.

FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);

Step 7:-Set Routing in RouteConfig.cs which is inside App_Start folder like this.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace Tcl_IzoGlass
{
    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
//set routing for filter controller.
                routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "HomeFilter", action = "Index", id = UrlParameter.Optional }
            );          
        }
    }
}

Step 8:-Run application output is:--

Excuting Filter Attributre::

AuthorizationFilter filter is called before action.
IActionFilter.OnActionExecuted event fire and filter is called.
IActionFilter.OnActionExecuting event fire and filter called.
IResultFilter.OnResultExecuted event fire and filter called.
Bikesh Srivastava MVC, WEB API

Life Is Complicated, But Now programmer Can Keep It Simple.