Dec 25, 2016

Using Doxygen command line to Generate HTML documentation for C# Application

We have covered document generate using Doxygen GUI in the previous post. As I have mentioned in the previous post to cover Doxygen command in next post.

So As we are going to cover Doxygen command using generate documentation. 

I assumed you have already downloaded and installed Doxygen in your system.

And your C# application very well commented on method, classes, and other objects.

So, after all, set we are going to generate a document using the command line.

Step 1: Press CTL+R and write cmd and hit the enter to open the command prompt.

Step 2: First a fall need to create Doxygen configuration file using command line with the following command
C:\Work>doxygen -g doxygenfile
Run above command and generate the configuration file.

Step 3: Once the configuration file is generated require few configuration as per your project and path requirements. So edit generated configuration file and update following options.
INCLUDE = Doxygen config_file_name
OUTPUT_DIRECTORY = Doxyment_directory
PROJECT_NAME = "My Project"
RECURSIVE = YES
OPTIMIZE_OUTPUT_JAVA = YES
Above configurations are good to generate the document. For more configurations visit on Doxygen website.

Step 4: Once you done with configuration file changes then run command for the document generate.
doxygen <config_file>
Above is the syntax for doxygen command.
Run the below command to generate the document.
doxygen doxygen
Once you run above command. Doxygen will process the generate document.

Step 5: Once above command successfully run then you will check your output directory and the document will be there.
That's it!! 

Hope you like it. Happy coding!.

Generate HTML documentation using doxygen for C#

This post is dedicated to developers because after reading this post developers life will easy to create the document directly from the code.

For creating the document, we are going to cover the Doxygen utility.

Using Doxygen, a developer can create the document using Doxygen GUI or Doxygen command. We are going to cover both ways generate the document. The first post we are cover GUI only and next post will cover Doxygen command.

Before we going further one thing is very important to generate document is the comment of the code without comment document will not generate properly.

I assume you know, how to write XML comment on the code of every method, classes, and other objects.

Once you have written comments on code and ready to generate the document.

For generate the document follow the below steps.

Step 1: Download Doxygen from the Doxygen website.

Step 2: Once download, install into your system.

Step 3: After installation, open the Doxywizard

Step 4: Once open Doxywizard GUI then follow below image with steps.
In Doxygen GUI, check the yellow highlighted text with the following explanation. 
Above image step 1: Specify the working directory from which doxygen will run. For that, you need to create a blank folder and select that path. In our demo, we have created DOXY folder under the D drive.

Above image step 2: Select the Wizard tab and select Project from Topics. Right-hand side fills form details as per your project related to Project Name, Source code Directory Path, Destination Directory and Scan recursively.

For Scan recursively checkbox use for the subfolder scanning.
Now click on Mode Topics and select your project language, We have selected "Optimise for Java or C# output"


Step 5: Once done with Wizard tab click on Expert tab

Under Expert tab select Build Topics and select as per your requirement configuration options from the right-hand side. For the understanding of the configuration options, visit on Doxygen site.

Here we have select few options which are good to generate the document.

Step 6: Last step for the generate document. Click on Run tab
Once you click on Run tab, you will see the Run doxygen button underneath the tab. Now we are ready to generate the document.

Click on Run doxygen button and you will see the progress on the output produced by doxygen box.

After successful completion, you will check your output directory folder and your document will be ready. 

Open the index.html page on the browser and check document.

Hope you like it. Happy Codding!!

Dec 3, 2016

Create HTML document from the swagger generated JSON file using Asp.Net Core

Today, We will create HTML document from the Swagger generated JSON file using Asp.net.

Let's create document step by steps.

Step 1 : Create Asp.Net Core Web API project using visual studio.

Step 2 : Once the solution is ready then follow below link to configure Swagger in Asp.Net Core.

https://docs.microsoft.com/en-us/aspnet/core/tutorials/web-api-help-pages-using-swagger

First Install Swashbuckle NuGet Package.
Install-Package Swashbuckle -Pre

Once NuGet Package successfully installed then add the following code on startup.cs for Swagger integration with the solution.
// This method gets called by the runtime. Use this method to add services to the container
        public void ConfigureServices(IServiceCollection services)
        {
            // Add framework services.
            services.AddApplicationInsightsTelemetry(Configuration);

            services.AddMvc();

            // Inject an implementation of ISwaggerProvider with defaulted settings applied
            services.AddSwaggerGen();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            app.UseApplicationInsightsRequestTelemetry();

            app.UseApplicationInsightsExceptionTelemetry();

            app.UseMvc();

            // Enable middleware to serve generated Swagger as a JSON endpoint
            app.UseSwagger();

            // Enable middleware to serve swagger-ui assets (HTML, JS, CSS etc.)
            app.UseSwaggerUi();
        }
Hope you get the better idea after visited link and above steps.

Step 3 : After completed above step your solution is ready and run and browse the swagger ui.

For the same configuration on application example, you can fine on my GitHub repository

Step 4 : Now time to run the application and browse the Swagger UI page.

It will be URL like http://localhost:XXXX/swagger/ui/index.html (XXXX is your port number).
Once navigate to this URL. It will look like below image.

Step 5 : You can see on the swagger screen there is a one JSON file link. It looks like http://localhost:XXXX/swagger/v1/swagger.json.

Step 6 : We have JSON file ready with all contain so time to browse http://editor.swagger.io/.

Step 7 : On Swagger editor click on file menu and choose "Import URL" and a popup will open and asking for URL.

Step 8 : Copy JSON URL and paste on above popup dialog. Make sure "Use CORS proxy" uncheck when your URL is from localhost.

Else you can paste JSON string directly to the "Paste JSON" (Select file menu and choose Paste JSON). Click on Import button to load the JSON file on Swagger editor.

Step 9: After clicking on Import button it will show two part of the screen. One side YAML and once side HTML document.


Step 10 : Last and important step once you see above the screen. Now we are ready to perform download document. 
For HTML document click on "Generate Client" from the menu and select "HTML" 

Once you download the file you will able to view beautiful HTML document generated.

Hope you are like it so please keep reading .

Oct 16, 2016

How to call stored procedure from Entity framework core and apply AsNoTracking

The latest version of Microsoft Asp.Net Core and Entity Framework Core is a hot topic in the market. Today, I am talking about how to call stored procedure from Entity Framework Core.

Here I am not teaching you. How to create stored procedure. Hope you already know it.

The support for stored procedure in Entity Framework Core is similar to the earlier versions of Entity Framework.
Let's see example
_context.Set<Products>().FromSql("GetAllProducts @CategoryId = {0}", categoryId).AsNoTracking().ToList()
We are calling "GetAllProducts" stored procedure passing categoryId.

Before calling stored procedure using Entity Framework Core. You require to include package "Microsoft.EntityFrameworkCore.SqlServer" to support calling stored procedure on the project.json file.

AsNoTracking
Disabling change tracking is useful for read-only scenarios because it avoids the overhead of setting up change tracking for each entity instance.

You should not disable change tracking if you want to manipulate entity instances and persist those changes to the database using Microsoft.EntityFrameworkCore.DbContext.SaveChanges.

Hope you like this post and keep reading!!

Oct 9, 2016

Microsoft MVP 2016 - Kalpesh Satasiya

Friends, 1st October 2016. It's memorable day for me and my family. I got below email from Microsoft  for "Congratulations 2016 Microsoft MVP!"



I have been awarded for Microsoft Most Valuable Professional 2016 for Visual Studio and Development Technologies.

I would like to thanks,  Mr. Gadharv Rawat and Microsoft MVP community for their support and guidance.  I would also like to thanks, MvpAward team for considering me to become a Microsoft MVP. As always there has been great support from friends and family.

Last but not the list, thanks to my beautiful wife, Mr. Jalpesh Vadagama and my blog reader for your constant support, encourage and guidance to me.

Thank you very much!!

Sep 19, 2016

Types of data binding in Angular 2


Today, I am going to cover hot topic of the market Angular 2. Just a few days ago Angular 2 was released and everyone very excited to know about Angular - 2 then compare to AngularJs.

One thing I tell you there is no connection between AngularJs and Angular - 2. So Angular 2 has own concept and support ECMA - 6 (which is the latest version of JavaScript).

AngularJs is supporting ECMA - 5 so there is the main difference between AngularJs and Angular 2.

As we know in AngularJs by default support two-way binding so we can say AngularJs added $watch on each control which is use ng-model.

So there are the performance issues of AngularJs, Angular 2 has overcome those issues so that provides more binding types so you can choose based on your requirement where you want which type of binding.

Angular 2 support four types of binding

  1. Interpolation
  2. One Way Binding
  3. Two Way Binding
  4. Event Binding

1. Interpolation

Interpolation is the easiest and best-known way of data binding. In AngularJs, it looked likes this:
<h1>{{vm.student.name}}</h1>
In Angular 2, we can still use the curly braces, but we can omit controller name or vm, because we already have the context. so here we can use directly object or variable name.
<h1>{{student.name}}</h1>

2. One Way Binding

The way we used to apply one-way binding is ng-bind just like this:

In Angular 2 we can use square brackets around the property we want to bind to.
<span [innertext]="student.name"></span>
This may look a bit strange at first, but it definitely is valid HTML. We actually can take any HTML property, like innerText, wrap it in square braces and you can then bind it to a model.

This could for example also work on style properties:
<span [student.bgcolor]="style.backgroundcolor"></span>

3. Two Way Binding

The most used use case of two-way binding in AngularJs is using it on any field or any other form elements. When we type something in the textbox on one side, the value goes to the controller and then back and forth.

In AngularJs we are using the ng-model directive on the element and bind it to the value:
 

In Angular 2 we also have a special directive called ngModel. But here some syntax is changed from AngularJs.
<input [(ngmodel)]="student.name" /> 
We use the square brackets because it's a property, but we also use the parenthesis.
This syntax is called Banana in a Box ([()]). What this means is when you see this syntax, it's two-way binding at work.

4. Event Binding

You can do event binding with any valid HTML event available, like click, focus or blur. In AngularJs you should need built-in directives to use event binding.

For example, for binding to a click, one would use:
    

In Angular 2, we can just take the same property that is on the HTML element (click in the previous example) and wrap it in parenthesis.
So, with properties we use square braces [], but with events we use parenthesis ():
<button (click)="AddStudent()">Save</button> 

Note: Angular 2 has dropped tons of directives (like ng-click, ng-blur, ng-focus, etc) and also dropped the convention of splitting words with dashes and use camel case instead (ng-repeat vs ngFor, ng-if vs ngIf etc).

Hope you like this article and Happy coding!!.

Sep 4, 2016

How to get remote IP address in Asp.Net Core Web API


In Asp.Net Core Web API to get Remote Client, IP Address is changed to the previous version of Asp.Net
.

In Core introduced new library for Http request and response.

Require the following namespace to add.
using Microsoft.AspNetCore.Http.Features;
Once, you added namespace then just need to add following a line of code for capture the Remote Client IP Address.
HttpContext.Features.Get()?.RemoteIpAddress?.ToString();
Once more thing I want to explain about null handle in Core using "?".

So you can see in the above line how to handle the null object.

Note: When you try to run the application from the local system so above line of code return the result "::1" but it will work once you deploy your application somewhere.

Hope you getting the desired result and save your time.

Aug 6, 2016

Taken session on Microsoft Azure cloud technology

I have taken session on Azure cloud technology at SK Patel Institutes of Computer Studies.

It was a good experience to share knowledge with student at college level. BCA Students also very existed to learn Microsoft Azure cloud technology.

Share knowledge about Azure Services like
1. SAAS
2. PAAS
3. IAAS

Also solved student queries about Azure and other technologies related.

College has published Microsoft Azure related session information on news paper.



Some random pictures during the session.







Special thanks to Mr. Jalpesh Vadgama and I inspired from him.




Thanks to Dr. Nidhi Divecha and Dr. Sanjay M. Shah. Who has given such opportunity to share our knowledge with students.


Jul 11, 2016

How to create AngularJs Application in Visual Studio 2015

Nowadays one of the most popular client-side framework is Angularjs and when we talk about .net developers they love to use Visual Studio IDE for developing any application because they used to with visual studio.

Once, you have installed visual studio 2015. Now time to add some extension to support AngularJs.

Open visual studio IDE and go to tools section from the main menu and select Extension and Updates.

The popup is open once the selection was done. Now click on Online from the left side menu and search “SideWaffle" which is one of the extension provide client side templates for visual studio.

Once result populates for SideWaffle, Click on install button so It will take some time to install templates on visual studio.

SideWaffle

Once installation was done for SideWaffle then we are done with all require setup for AngularJs application for visual studio.

For creating new AngularJs Application in Visual Studio

Select File, New Project. Under the Visual C# templates, select SideWaffle under the Web, select AngularJs And Web API - Empty template and name the new project “FirstAngularJSApp” and click the OK button to create the new project.

SideWaffle-2

Now we are ready to do magic with AngularJs Application and Web API.
SideWaffle also installs many other templates which are useful for other applications.

Hope you like it. Keep a reading blog.

Jul 10, 2016

How to get application base directory and WWWroot path in asp.net core 1.0

Short and simple post for accessing Application base directory and wwwroot path in asp.net core 1.0.

This post is useful for newbie of asp.net core framework because many things changed from previous version of .Net framework.

IHostingEnvironment service to get both Application base directory and wwwroot. 
Let's see code example for IHostingEnvironment service.
private IHostingEnvironment _hostingEnvironment;
public ValuesController(IHostingEnvironment hostingEnvironment)
{
    _hostingEnvironment = hostingEnvironment;
}
// GET: api/values
[HttpGet]
public IEnumerable<string> Get()
{
    // _hostingEnvironment.WebRootPath -- wwroot folder path 
    // _hostingEnvironment.ContentRootPath -- Application Base Path

    return new string[] { _hostingEnvironment.WebRootPath, _hostingEnvironment.ContentRootPath };
}
It's a simple and informative post regarding asp.net core 1.0.

Hope you like it and keep reading for more!!

Jul 8, 2016

Microsoft has released Asp.Net Core 1.0



Recently Microsoft has released Asp.Net Core 1.0 with significant updates. New release with many updates like more modular, cross-platform, and cloud optimized.  ASP.NET Core is now available, and you can start using it today by downloading it here.

ASP.NET Core 1.0 is an open source web framework for building modern web applications that can be developed and run on Windows, Linux and the Mac. 

One good news for developer who are confuse for MVC and Web API because of now that it combine into single web programming framework.

For more detail please read of Microsoft Website.

Jul 7, 2016

Go to Implementation feature in Visual Studio 2015



Latest Microsoft IDE is Visual Studio 2015 and there are many features introduced with this IDE. So I always existed to explore those features whenever new feature comes.

We are going to talk more about one of the more productive feature is Go to Implementation. That is very easy to navigate actual implementation.

Developer's life is easy to pick/navigate on actual implementation because previously this option is not  available to need to depend on some third party tools like Resharper, etc.

Older version on Visual Studio has only Go to Definition option so it will bring to interface where function is declare and not able to reach on actual implementation.

So for more productive and reach at actual implementation. Go to Implementation feature is useful and I love to explore this feature and make development life easier.

Hope you like this new feature from Visual Studio 2015.





Jul 6, 2016

How to use constant in AngularJs



As we know like some short of configuration require in project level. How we do such configuration in Angularjs using Constant.

Let’s more talk about how to declare and use Constant configuration.

We are going to cover classic example of constant . Whenever you want to use config that could be ineluctable at any part of application and it works.

Lets see code here.
(function () {
    'use strict';

    angular
        .module('app', [
        // Angular modules
        'ngAnimate',
        'ngRoute'

        // Custom modules

        // 3rd Party Modules

        ])
        .constant('userRole', {
            owner: 'Owner',
            administrator: 'Administrator',
            user: 'User'
        });
})();

As define userRole as a constant in code same like JSON format so there are better way to config in your application. Classic way might be it is not best way to use constant instead of create a service and load with $http a JSON file.

Once you declare constant than how to use in your application.
(function () {
    'use strict';

    angular
        .module('app', [
        // Angular modules
        'ngAnimate',
        'ngRoute'

        // Custom modules

        // 3rd Party Modules

        ])
        .constant('userRole', {
            owner: 'Owner',
            administrator: 'Administrator',
            user: 'User'
        }) 
 .controller('MainCtrl', function (userRole) {
            // Do something with myConfig...   
            var vm = this;
            vm.Role = userRole.administrator;                        
        });
})();
In the above code we have inject userRole on MainCtrl so we can use userRole inside the controller.

Define controller as vm (var vm = this) and userRole assign to Role property of controller like vm.Role = userRole.administrator;

You can find source code from GitHub.

That’s it. Hope you like it. Stay tuned for more!!

Jul 4, 2016

HtmlEncode and HtmlDecode in Asp.Net Core or Asp.Net 5

Latest version of Microsoft Asp.Net Core 1.0 provide Html encode and decode feature using following Namespace and class.

As we know now Microsoft Asp.Net Core is open source so we can see the actual code of system level classes which was not possible earlier.

All source code avalaible in GitHub on aspnet repository.

HtmEncode and HtmlDecode is now part of System.Runtime.Extensions.
namespace System.Net
{
    public static partial class WebUtility
    {
        public static string HtmlDecode(string value) { return default(string); }
        public static string HtmlEncode(string value) { return default(string); }
        public static string UrlDecode(string encodedValue) { return default(string); }
        public static byte[] UrlDecodeToBytes(byte[] encodedValue, int offset, int count) { return default(byte[]); }
        public static string UrlEncode(string value) { return default(string); }
        public static byte[] UrlEncodeToBytes(byte[] value, int offset, int count) { return default(byte[]); }
    }
}
How to use HtmlEncode and HtmlDecode static property.
var dummyString = "Dummy%20String";
var decodeString = System.Net.WebUtility.HtmlDecode(dummyString );
That’s it. Hope you like it. Stay tuned for more!!

Jul 2, 2016

isNaN funtion and NaN error in Javascript

This blog post is dedicated to JavaScript newbie and JavaScript lover.

NaN is a "Not a Number" in JavaScript.

1. NaN error
- NaN error is very common for JavaScript developer. When you are looking some calculation that time generally come.

- One thing remember when you are working with JavaScript  and declare any variable (var i;) and that variable value default as 'undefined'. so its a good practice to assign default value to the variable.
//var first = undefined;
var first;

//So when you do console.log(first); its print in console 'undefined'
console.log(first);

So take care it and don't forget to assign default value to variable else it will create a problem on some statement.
var first = 0;

consol.log(first)
//Console output is 0

When getting NaN error?
- When variable value is undefined and use that variable and calculate with some other variable that time getting NaN.

Let's see example.
var first;
var second = 4;

console.log(first + second);
//Output is NaN

//As we prevent NaN, declare variable with default value
//in our case first variable value is undefined so let assign value to variable.

first = 0;
console.log(first + second);
//Output is 4


2. isNaN function
  - It's a global function in JavaScript to check if a value is a NaN value.

When you writing JavaScript code for calculation of numeric values and its a safe way to handle numeric value and check value is not a NaN value using IsNaN function.

Let's see example how to handle NaN value in JavaScript.
var first;
var second = 4;
var sum = first + second
if (isNaN(sum)){
  console.log("value is a NaN");
}else{
  console.log('Value is not a NaN');
}

Hope this is useful for newbie of JavaScript.


Jun 26, 2016

How to change Asp.net Identity token expiration in Asp.Net Core or MVC 6

Asp.Net Identity default expiration time is 1 day. Some time its require to change based on our requirement.

Default property initialization on DataProtectionTokenProviderOptions class is
 public TimeSpan TokenLifespan { get; set; } = TimeSpan.FromDays(1);

Require customization for change to default token expiration time.

Following step require to change default expiration token time.

Step 1 : Create new class with name DefaultDataProtectorTokenProviderOptions and Inherit from DataProtectionTokenProviderOptions class.
public class DefaultDataProtectorTokenProviderOptions : DataProtectionTokenProviderOptions { }

Step 2 : Create new class with name DefaultDataProtectorTokenProvider and Inherit from DataProtectorTokenProvider class.
public class DefaultDataProtectorTokenProvider : DataProtectorTokenProvider where TUser : class
    {
        public DefaultDataProtectorTokenProvider(IDataProtectionProvider dataProtectionProvider, IOptions options) : base(dataProtectionProvider, options)
        {
        }
    }
Step 3 : Time to use above classes on Startup class and AddTokenProvider.
Step 4: Declare private variable for provider name
 private const string _defaultTokenProviderName = "Default";

Step 5 : Under ConfigureServices method add following code for token expiration time change.


Here you can see set time span for token expiration.
// Set time span for token expiration time
           
                options.TokenLifespan = TimeSpan.FromMinutes(15);
           

You can get the source code from GitHub.

Hope you like this so please keep reading.

Jun 20, 2016

Web Essential extension for Visual Studio

Visual Studio supports extensions and There are so many useful extension available in market for Visual Studio. You can be lots more productive using this extension. “Web Essentials” is one of the best extension available for visual studio. It has been developed by Mads Kristensen. You can download this extensions from the following link.

http://vswebessentials.com/

There are different versions available for different versions of visual studio. There is lot of features available in web essentials for the HTML, CSS and JavaScript editors.

Web essentials features:
There are so many features available in visual studio 2015 web essentials. We are going to cover only few.

CSS Vendor specific properties:
There are lots of CSS vendor specific properties available specially for Mozilla family. So now you can add those very easily via web essentials.



Color preview in CSS:
Now we see that color previews are available with web essentials:



JSHint:
JS hint is really good for following JavaScript coding standards. There settings with from where you can define the coding standards for the same. 

Syntax Highlighting:
There are lots of more syntax highlighting provided i.e. Robot.txt, HTML5 App Cache and few more.

Markdown:
It’s provides great features like syntax highlighting, intellisense for embedded language features, preview features, custom stylesheet etc.



There are many more features available. You can visit following link know more about Web Essentials features.

http://vswebessentials.com/features/

That’s it. Hope you like it. Stay tuned for more!!

May 15, 2016

Laravel-5 or 5.2 remove public folder name from the URL


Laravel-5 or 5.2 Remove public folder name from the project URL.

I have configured and installed laravel but now I am facing the issue of URL it will work with the public folder instead of simply end with the project name.
I have written URL as localhost/projectname and my project name is Laraveldemo.

so I can access the URL for the project as localhost/laraveldemo but it's not rendering the view.So I did the R&D how the URL will be in laravel.

I was read the document where written as you can access URL using public directory.so it will be a
localhost/laraveldemo/public.


Now I want to deploy the project to a live server and want to remove the public from the URL.
I did a number of R&D and find the solution as below in just two steps.


1) Rename the server.php in your Laraveldemo root folder to index.php


2) Copy the .htaccess file from /public directory to your project e.x Laraveldemo root folder.



May 8, 2016

How to use bootstrap selectpicker for dropdown


Today we will be looking for some bootstrap magics with the dropdown.

We aware of like bootstrap has changed the idea of presentation of design and layout.

Here we are picking off the great stuff for dropdown.  So for that bootstrap has selectpicker js.

Let's check how to use selectpicker for dropdown and related css and js file reference.
        


    
 

 
  

    
 
 

 

 

In example, we have seen like on dropdown assign class="selectpicker" and that class is used for jquery operation and calling selectpicker() method.

There are many bootstrap select picker avaiable so enjoy and play with select picker.

Apr 30, 2016

How to get JSON POST body on Asp.Net MVC

How to get JSON POST body on Asp.Net MVC controller action. There is two way to get POST data on controller method.

Following is a JSON POST data and assume we are passing this data on the body part.

{
        "Name": "Team Name",
        "Lat": 29.723169,
        "Lng": -95.514999,
        "ShiftEndTime": 1000,
        "ShiftStartTime": 0
    }

And the following class is your Model.

public class TeamViewModel
    {
 public long TeamId { get; set; }
        public string Name { get; set; }
        public double Lat { get; set; }
        public double Lng { get; set; }
        public TimeSpan ShiftStartTime { get; set; }
        public TimeSpan ShiftEndTime { get; set; }
    }

Let's see one by one method to get JSON body POST data.

Refer image and see highlighted yellow mark
1. Select POST method
2. Highlighted body section and selected raw data
3. selected raw data with "Application/JSON" as type
4. Underbody selection writes your JSON object

1. As a Parameter
  • Generally, this method is used in most in normal cases so we can see in MVC this is the default case to get JSON POST data from the body as a parameter.

public ActionResult Index(TeamViewModel model)
    {
       //TODO
    //Write your code here
    
 }

You can see here TeamViewModel pass as a parameter and then utilize for further logic.

2. From Request Object

  • Generally, this kind of cases used when directly post request from other pages or same kind of requirement.
public ActionResult Index()
{
            
            Stream req = Request.InputStream;
            req.Seek(0, System.IO.SeekOrigin.Begin);
            string json = new StreamReader(req).ReadToEnd();

            PlanViewModel plan = null;
            try
            {
                // assuming JSON.net/Newtonsoft library from http://json.codeplex.com/
                plan = JsonConvert.DeserializeObject<TeamViewModel>(json);
            }
            catch (Exception ex)
            {
                // Try and handle malformed POST body
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
   
     //TODO:: you can write your logic here
   

}

You can see the code, get JSON POST data from the Request object. Once you read StreadReader object and converted into the string.

Then string will convert into TeamViewModel object help of JsonConvert.DeserializeObject method and finally get the TeamViewModel object.

Hope you enjoy this post and learn something.

Please post your suggestion in comment section.

Apr 24, 2016

How to consume RESTful service from the client

We have discussed, How to create RESTful service in my previous blogs.

Today, We are talking about how to consume RESTful service from the client.

API call using HTTP Methods for RESTful Services

We will cover most uses methods like GET, POST, PUT and DELETE only.

For example purpose, I have created one API solution and will use for following examples.

Postman is using as a REST Client and consumes REST API service.

1. POST
 - Using POST request we are going to add new products.
 - Open Postman client from chrome browser addon (Note: You can use any REST client for RESTful service)





Check yellow highlighted section from top to bottom.
1. First, select POST from select box
2. Add headers as we know we are talking about RESTful services so JSON format came into pictures.
3. Add Content-Type as "application/json" and Accept as "applicaiton/json".
4. Now time to add your request data on body section. (ref. Images)

2. GET
 - Using GET request we are getting existing product data.


1. First, select GET from select box
2. Add URL on URL box ref. image.
3. Add Content-Type as "application/json" and Accept as "applicaiton/json".
3. Click on send button and you will get the result on box section

3. PUT
- Using PUT request we are going to update existing record.


1. First, select PUT from select box
2. Add URL on URL box with product id( ref. image).
3. Add Content-Type as "application/json" and Accept as "applicaiton/json".
4. Product existing data as a JSON format add on body section
3. Click on the send button and you will see record will be updated.

4. DELETE
- Using DELETE request we are going to delete existing record.


1. First, select DELETE from select box
2. Add URL on URL box with product id (ref. image).
3. Add Content-Type as "application/json" and Accept as "applicaiton/json".
3. Click on the send button and delete existing record from the database.

These simple baby steps post help to a newbie on RESTful service.

Give your suggestion for better improvements on the comment section.

Apr 22, 2016

How to save keystroke during the development using Visual Studio

Today, I am going to share my experience with Visual Studio and how to save keystroke during the development.

Why I am writing this post because of recently I had attended Global Azure BootCamp and that I had enjoyed and learned lot of thing but one of the things was inspired me. It's a Mahesh Dhola session and he had one thought about save keystroke.

So that I had decided to write a post on this and share this good thought to others.

I know experienced developer know the shortcuts and some tricky magic with Visual Studio but this is help for beginner or newbie to Visual Studio.

Let's start one magic and save keystroke during development on visual studio.
  1. When you are creating class also need to write a constructor. So for constructor you just need to write "ctor" and press tab key so constructor will ready for you.
    Before "ctor"
    
    After
    
    Public Student(){
    
    }
    
  2. When you want to create a new property you just need to write "prop" and press twice tab key and property ready for you.
    Before "prop"
    
    After
    
    public TYPE NAME { get; set; }
    
  3. When you want to write try .. catch block then just write try and press tab key twice.
    Before "try"
    
    After
    
      try 
     {         
      
     }
     catch (Exception)
     {
      
      throw;
     }
    
  4. If you want to write any block statement like if, switch, for etc. so visual studio have one interesting feature "Surround with" just press CTL + K + S and open a dialog to choose your block statement and it will prepare skeleton for you.
  5. If you want to write any HTML tag then just you need to right <input and press tab key twice and it will prepare skeleton for you.
    <input
    
  6. When you want to open and collapse any code of block  just press CTL + M twice.
    CTL + M twice
    
  7. When you want to a proper structure in a format, just press CTL + K + D.
    CTL + K + D
    
  8. When you want to find closing brackets just press CTL + } (end bracket).
    CTL + }
    
  9. When you want to move your cursor back just press CTL + - (minus).
    CTL + - (minus)
    
  10. When you want to move your cursor forwards just press CTL + Shift + - (minus).
    CTL + Shift + - (minus)
    
  11. When you want to comment a code block just press CTL + K + C
    CTL + K + C
    
  12. When you want to uncomment a code block just press CTL + K + U
    CTL + K + U
    

There are many magic shortcuts on Visual Studio. Please visit for more shortcuts http://visualstudioshortcuts.com/2015/

Hope this post will help to someone and also share your thoughts in a comment so I will incorporate into this post and that will help to others.

Apr 19, 2016

How to create RESTful API with MVC 6 and Asp.Net Core 1.0

Going to create RESTful API using ASP.NET Core 1.0 or MVC 6. I assume, you know the RESTful API so I am not going to explain what is the RESTful Service / API in this article.

We are talking about MVC 6 and Asp.Net core 1.0. just for your information if you don’t know that like MVC 6 is a part of Asp.Net core 1.0 and it is a completely new unified framework for writing server side web applications and APIs.

One of the changes in MVC 6 is a separation of Asp.Net MVC  and Web API is now past and merge into one. I thought it is good to having a look what changed has made to creating a RESTful API in MVC 6.

Let's start with simple CRUD (Create, Read, Update, Delete) operation in MVC 6 API.

Following  below steps to create RESTful API in MVC 6 with Visual Studio 2015.

Step 1: Create a new project using visual Studio 2015.
  - Open Visual Studio 2015 and go to file section and select New Project.

Step 2: Here you can choose ASP.NET 5 templates.


  - As I already mention MVC 6 has removed the separation of web controller and API controller and combine into one. So it's no matter which application you choose.
  - Yes, If you have a specific requirement like just want to create RESTful API then also ASP.NET 5 templates fulfill your requirement.

Step 3: Once solution created, you will notice few new things come up with default solution and few things have been removed.

  • App_Data, App_Start and Global.asax have been removed.
  • New *.Json file have been added.
  • Added new folders wwwroot and Dependencies
 Step 4: Build the solution and restore the packages during the build process.
  -  Please check output window for build process and check solution has built successfully.

Step 5: You need to add Model for this exercise which is a Student.
  - Student Model have following property
        a. StudentId
        b. Name
        c. SurName


using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace RESTfulAPI.Models
{
    public class Student
    {
        public int StudentId { get; set; }
        public string Name { get; set; }
        public string SurName { get; set; }
    }
}


Step 6: Now create a new controller for Student API, Select API Controller.


Write controller name as per your requirement.

 

Step 7: Once added API controller. You will get ready API controller.
  - MVC 6 and Visual Studio 2015 provide the scaffolding of RESTful API.
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNet.Http;
using Microsoft.AspNet.Mvc;
using Microsoft.Data.Entity;
using RESTfulAPI.Models;

namespace RESTfulAPI.Controllers
{
    [Produces("application/json")]
    [Route("api/Students")]
    public class StudentsController : Controller
    {
        private ApplicationDbContext _context;

        public StudentsController(ApplicationDbContext context)
        {
            _context = context;
        }

        // GET: api/Students
        [HttpGet]
        public IEnumerable GetStudent()
        {
            return _context.Student;
        }

        // GET: api/Students/5
        [HttpGet("{id}", Name = "GetStudent")]
        public async Task GetStudent([FromRoute] int id)
        {
            if (!ModelState.IsValid)
            {
                return HttpBadRequest(ModelState);
            }

            Student student = await _context.Student.SingleAsync(m => m.StudentId == id);

            if (student == null)
            {
                return HttpNotFound();
            }

            return Ok(student);
        }

        // PUT: api/Students/5
        [HttpPut("{id}")]
        public async Task PutStudent([FromRoute] int id, [FromBody] Student student)
        {
            if (!ModelState.IsValid)
            {
                return HttpBadRequest(ModelState);
            }

            if (id != student.StudentId)
            {
                return HttpBadRequest();
            }

            _context.Entry(student).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!StudentExists(id))
                {
                    return HttpNotFound();
                }
                else
                {
                    throw;
                }
            }

            return new HttpStatusCodeResult(StatusCodes.Status204NoContent);
        }

        // POST: api/Students
        [HttpPost]
        public async Task PostStudent([FromBody] Student student)
        {
            if (!ModelState.IsValid)
            {
                return HttpBadRequest(ModelState);
            }

            _context.Student.Add(student);
            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateException)
            {
                if (StudentExists(student.StudentId))
                {
                    return new HttpStatusCodeResult(StatusCodes.Status409Conflict);
                }
                else
                {
                    throw;
                }
            }

            return CreatedAtRoute("GetStudent", new { id = student.StudentId }, student);
        }

        // DELETE: api/Students/5
        [HttpDelete("{id}")]
        public async Task DeleteStudent([FromRoute] int id)
        {
            if (!ModelState.IsValid)
            {
                return HttpBadRequest(ModelState);
            }

            Student student = await _context.Student.SingleAsync(m => m.StudentId == id);
            if (student == null)
            {
                return HttpNotFound();
            }

            _context.Student.Remove(student);
            await _context.SaveChangesAsync();

            return Ok(student);
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                _context.Dispose();
            }
            base.Dispose(disposing);
        }

        private bool StudentExists(int id)
        {
            return _context.Student.Count(e => e.StudentId == id) > 0;
        }
    }
}




Step 8: Now time to access RESTful API from POSTMAN.
- You can consume RESTful API from any source and get the result.

Hope this will help you to create your first RESTful API using MVC 6 and ASP.NET Core 1.0.

Apr 17, 2016

Global Azure Bootcamp 2016 Ahmeadbad - Organized by Ahmedabad User Group

It was my pleasure to attended Global Azure Bootcamp 2016 organized by Ahmedabad User Group.

It was fun and knowledge sharing session was taken by all speakers.


Full day enjoyed with different session and was truly amazed.

I was reached at 10 am in the morning at a venue and organized very well by Ahmedabad User Group.



Mahesh has started with welcome speech to all participate.


First session was taken by my friend Jalpesh about Azure DocumentDB


Then Jagdish has take over the stage for next session and he has taken session about Azure mobile services.


After Jagdish session, it was a lunch time.






After lunch, post lunch session was taken by Sanket Shah about Architecting Modern solution on Azure. He had some fun with coding and tool.



After that, we had Kaushal Bhavsar session and he had taken about secure two-factor authentication with Azure technologies. He had presented the live demo on Azure.


It was time to last session and it was taken by Mahesh Dhola about DevOps and Microsoft Azure. He had some fun with the white board and provided old and new technologies term.



After the end of the almost everyone getting some sort of virtual gift from Global Azure Bootcamp 2016 sponsor by lucky draw.

I am also a lucky guy to get some reward as a form of www.azuredockit.com 1 year licence.


Really it was very fun event and enjoyed a lot. !!