API – Suraj | Coding Passion Tue, 09 Oct 2018 07:03:49 +0000 en-US hourly 1 https://wordpress.org/?v=4.9.8 Tools which will make developers life easier /tools-which-will-make-developers-life-easier/ /tools-which-will-make-developers-life-easier/#respond Tue, 26 Apr 2016 18:19:22 +0000 /?p=623 Introduction

Today, the world has grown so much and has been so friendly for the developers, thousands of tools floating in the market for free, but we need to realize and have them in our bucket whenever required.
I will be discussing few important tools, which are handy and work out for every developer.

Tools!!

FIREBUG 2

The best tool for the developer which can be installed on FireFox (add-on). This helps monitor the structure of you HTML, CSS and also javascript. To add the Firebug and get it going add now!
Add FireBug
1
A web development tool which will help any developer track the issue with the client side and also track the response time for the requests in the network tab.

The tool tab looks like below:

3

POSTMAN

This is a very important tool, which is a restful api client, which helps developer not waste time debugging and every time running Visual Studio to check the result set and how the api behaves. We now just need to call the url of the API from Postman and it gives us the result, even the status code as well.
4
Get POSTMAN for Chrome
This will allow developers to request any API, may it be GET, PUT, POST or DELETE.

5

6
I made a get request to a exposed github API to show how the POSTMAN reacts and shows us the Json result also the response time and the Status(200 Ok, 404 Not found, 403 Forbidden).

Yslow 8

This is such a powerful tool for any developer developing any web application, which without any fondness to anyone, ruthlessly shows how good your web app is and how good it will behave? The below image says it all:

9

The above web site has been given a Grade ‘D’ by Yslow.  This also gives a description of why the grade is low, what can be modified or  implemented to improve your grade. Here, it also lets developers know for bundling and minification for the javascript and the style sheets. So use it and improve the performance of your web app.

Install the Yslow now:
Add Yslow
7

Css Sprite Generator

Sprites is a collection of images put together into a single image. So instead of adding multiple images and heavy-ing the web page, we can prefer sprites with images and using css to generate and display on web page.
Css sprite generator add on tool helps you create Sprites. Sprite Cow also helps you generate sprites and also the css to use on your web page.
10

Web developer

This is a very interesting add on for every developer. This has a lot of features added to it and each of them is useful while developing.
11
Web Developer Add on
Add the web developer add on and play around there are a lot of features out there for you.
12
There are features for Css, forms, javascript, images, cookies, etc.

Window Resizer

13
Another helpful tool for every developer, as now a days every web app is being designed to be responsive. Developers add css and html to make it responsive, but it is not possible for developers to test on every possible devices which end users would be using. This helps you resize your web app window and test if the pages are responsive as expected.
14
Add and play with it.
Window Resizer Add on

CSS Viewer

An interesting tool to be used, as it lets you view the css being used on the web page. This helps check the css hovering over the web page area.
15
CSS Viewer Add on
The add after added on web page looks like below:
16

Cache Clear 17

19
How many times we developer face the wrath from the testing team, that this is not working this is breaking and what not! And we ask them to do just one thing, “Please clear your cache”! and then everything works! Here is an add on which helps you clear cache for the application on click of a tool tip only.

Add and recommend testing to add as well. 😛
Clear Cache Add on

Angular Batrang 21

20
Angular being the king now, every developers starting to learn and use Angular. This is a very nice tool to be used on Angular application, if they wish to track the scopes and angular objects and how they behave!
After adding the extension, in the developer tool, it comes as an add on and you can navigate and play with it on your angular web app.
22
Angular Batrang Add on

Conclusion

These were few important developer tools, which I use in my day to day development and I hope this will help few developers as well as they are very useful once you start using and exploring them. Play around and you will be addicted to them. I hope readers will share their views and share which other important developer tools they recommend.
Come on! Recommend and share your views!

]]>
/tools-which-will-make-developers-life-easier/feed/ 0
Lets Chat Application using SignalR in MVC /lets-chat-application-using-signalr-in-mvc/ /lets-chat-application-using-signalr-in-mvc/#comments Sat, 16 Apr 2016 19:48:40 +0000 /?p=590 Download Source Code

Introduction

Here I would be demonstrating an application to chat and chat private as well, using SignalR.
Before that we need to know first what is SignalR! SignalR is an open and free library which can be used to have real-time functionality integrated to your web applications. There are a hell lot of areas where SignalR can come handy to make your application more handy and more integrated and more responsive to the end user as well. Real-time means having your server respond as quick as possible to the client as and when a request is made.
Now, take for an instance, we have a requirement to show the user uploading a file, the percentage of that file been uploaded on the server. Or I had come across a scenario where, we had to show the end user, who would be uploading a CSV file with ‘n’ number of rows and process each row for some validations. End user would be wondering what would be going on in the back-end. So, would it be great if we could show him how many rows have been processed and how many are left out! Similar to a progress window. Here, comes the SignalR magic!
Most of us think SignalR would be useful in making chat applications, but NO!,it has much more than just chat! I don’t think the makers of SignalR would have a thought in mind to make a chat application out of it! 😛
Much of a story now! Lets get into a bit of theory!

Theory

We will look into a simple image below and from that image we will try and gain some knowledge on the flow:
1
Now a days, every application requires a load of server response in the real time to sustain in the market, as the user expectations have raised high.
Remote Procedure Calls (RPC) is the concept that takes place in the SignalR internally. SignalR provides an API which helps in making the RPC between the server and the client. Actually, from the client side, server side functions are called using JavaScript, once the connection to server is set. The SignalR API also helps creating connections and manage them when required. In simple terms, SignalR provides connection between server and client, letting server to call the funcitons on the client side and from the client side, calling the server side. That somehow is called “Server-Push”.
SignalR starts with HTTP and then to a WebSocket if connection is available. From Wiki,
“WebSocket is a protocol providing full-duplex communication channels over a single TCP connection.”
An advantage of using WebSocket is it can be used by both client and server applications. WebSocket is considered to be the most efficient and consistent medium of communication as, it has the ability to manage server memory in a proper manner and being a full duplex communication, has low latency. These are the considerations made with SignalR which make it more efficient.
The SignalR decides the transport based on the browser, i.e. if the browsers support the kind of transport required by the SignalR. We will discuss the kinds of transports next:

HTML 5 Transports

  • WebSockets as we have already discussed. This transport is considered to be true-persistent, creating a two way connection between client and server if the browsers support.
  • Server Sent events also called Event Source, which is supported by all browsers except IE.

Comet Transports

Comet usually,is a web application model in which a long-held HTTP request allows server to post data to a client (browser).

  • Forever frame This is supported by Internet Explorer only. Creates a hidden frame making a request to endpoint on the server. Server keeps pinging client or sends script to the client, thus providing a one way connection, creating a new connection on every request.
  • Ajax Polling This is actually long polling, which is never persistent. This polls the request and waits until and unless the response is received from the server. This introduces latency and the connection resets.

Practical

We will be creating a chat application in order to explain the flow of SignalR. We install the SignalR, create a hub to which the client will interact, calling the server methods and in return the server responds and interact with the client.
You can directly add a new project in VS for the SignalR or create an MVC project and install the SignalR package/libraries from the Nuget.

PM > Install-Package Microsoft.AspNet.SignalR

This is download all the dependencies required for the SignalR.
2

After the successful installation, the above dll’s or packages are installed into your project.
There will be a class file which needs to be added to the root of your project, which would look like:

using Owin;
using Microsoft.Owin;
[assembly: OwinStartup(typeof(SignalRChat.Startup))]
namespace SignalRChat
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            // Any connection or hub wire up and configuration should go here
            app.MapSignalR();
        }
    }
}

This is OWIN based applicaiton. Every OWIN application will have a startup.cs class, where the component for the application pipeline are added. The OWIN attribute which specifies the type of property, specifying the project’s start up and the configuration method, sets up the SignalR mapping for the App.
There will be another two script files that would be added as we install the packages for SignalR.
3
These script files are mandatory to be loaded onto the .cshtml page in order to activate the SignalR.
Lets look into the code straight away:
We need to add a new hub class inside a Hub folder. Lets name that LetsChatHub.cs, which would look like:
hub

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.AspNet.SignalR;

namespace LetsChatApplication.Hubs
{
    public class LetsChatHub : Hub
    {
        public void Send(string name, string message,string connId)
        {
            Clients.Client(connId).appendNewMessage(name, message);
        }
    }
}

The above send method accepts the parameters, name (which you would be giving once you navigate onto the url), the message (which the user would be sending from the UI). The other parameter is connId, which would help us have chat private and not send to every user who navigates to the site. If you would like to have every user receive and send the messages who navigates to the URL. To allow every users the access, the code you change as below:

namespace LetsChatApplication.Hubs
{
    public class LetsChatHub : Hub
    {
        public void Send(string name, string message)
        {
            Clients.All.appendNewMessage(name, message);
        }
    }
}

The Send method, is requested from the client with the parameters after the connection is set on the client side and once the server receives the request, it processes and sends back the response to the client, using the appendNewMessage. This appendNewMessage method is added on the client side to receive the response and display on the UI to the client.
You need to add a controller, lets suppose: “LetsChat” with an action “LetsChat”, add a view to that with the below code to it.
The client side code would look like below:

@{
    ViewBag.Title = "LetsChat";

}


<h2>Lets Chat</h2>
<link href="~/Content/sweetalert.css" rel="stylesheet" />

<div class="form-group col-xl-12">
    <label class="control-label">Your connection Id</label><br />
    <input type="text" class="col-lg-12 text-primary" id="frndConnId" placeholder="Paste your friend's connection Id" /><br /><br />
    <label class="control-label">Your Message</label><br />
    <textarea type="text" class="col-lg-10 text-primary" id="message"></textarea>&nbsp;&nbsp;&nbsp;&nbsp;

    <input type="button" class="btn btn-primary" id="sendmessage" value="Send" /><br /><br />
    <img src="~/Content/smile.jpg" width="20" height="20" id="smile" style="cursor:pointer"/>
    <img src="~/Content/uff.jpg" width="20" height="20" id="ufff" style="cursor:pointer" />
    <div class="container chatArea">
        <input type="hidden" id="displayname" />
        <ul id="discussion"></ul>
    </div>
</div>
<br />
<input type="hidden" id="connId" />

<!--Reference the autogenerated SignalR hub script. -->
@section scripts {
    <script src="~/Scripts/jquery-1.10.2.min.js"></script>
    <script src="~/Content/sweetalert.min.js"></script>
    <script src="~/Scripts/jquery.signalR-2.2.0.min.js"></script>
    <script src="~/signalr/hubs"></script>
    <script>
        //var userName = "";
        //var sessionVal = '';
        $(function () {
            // Reference the auto-generated proxy for the hub.
            var chat = $.connection.letsChatHub;
            
            debugger;

            // Create a function that the hub can call back to display messages.
            chat.client.addNewMessageToPage = function (name, message) {
                // Add the message to the page.
                $('#discussion').append('<li><strong>' + htmlEncode(name)
                    + '</strong>: ' + htmlEncode(message) + '</li>');
            };
            // Get the user name and store it to prepend to messages.
            swal({
                title: "Lets Chat!",
                text: "<span style='color:#f8bb86;font-weight:700;'>Enter your name:</span>",
                type: "input",
                html: true,
                showCancelButton: true,
                closeOnConfirm: true,
                animation: "slide-from-top",
                inputPlaceholder: "Your Name"
            },
            function (inputValue) {
                userName = inputValue;
                if (inputValue === false) return false;
                if (inputValue === "") {
                    swal.showInputError("You need to type your name!");
                    return false;
                }
                $('#displayname').val(inputValue);
            });
            // Set initial focus to message input box.
            $('#message').focus();
            $('#message').keypress(function (e) {
                if (e.which == 13) {//Enter key pressed
                    $('#sendmessage').trigger('click');//Trigger search button click event
                }
            });
            $("#smile").click(function () {

            });
            // Start the connection.
            $.connection.hub.start().done(function () {

                $('#sendmessage').click(function () {
                    // Call the Send method on the hub.
                    var connId = $("#connId").val();
                    var frndConnId = $("#frndConnId").val();
                    var finalConnId = frndConnId == "" ? $.connection.hub.id : frndConnId;
                    chat.server.send($('#displayname').val(), $('#message').val(), finalConnId);
                    $("#connId").val($.connection.hub.id);
                    if (frndConnId == "") {
                        swal("You connection Id", $.connection.hub.id, "success");
                    }
                    // Clear text box and reset focus for next comment.
                    $('#discussion').append('<li><strong>' + htmlEncode($('#displayname').val())
                   + '</strong>: ' + htmlEncode($('#message').val()) + '</li>');
                    $('#message').val('').focus();
                });
            });
   
        });
    // This optional function html-encodes messages for display in the page.
    function htmlEncode(value) {
        var encodedValue = $('<div />').text(value).html();
        return encodedValue;
    }
    </script>
}

Lets Chat

We have a normal UI in place to add your message and send button to call the server methods.
Lets understand the code above part by part.

var chat = $.connection.letsChatHub;

Here, we set the connection to the Hub class. As you can notice here, letsChatHub, is the same hub class file name which we added to set up the server. The convention as follows, the intial of the methods or the class name starts with lowercase. From here, we use chat to access the Send method.

$.connection.hub.start().done(function () {
                $('#sendmessage').click(function () {
                    // Calls the Send method on the hub.
                    chat.server.send($('#displayname').val(), $('#message').val(), finalConnId);

chat.server.send,is self explanatory, it sets the chat connection to call the server Send method once the connection is set and started.

chat.client.appendNewMessage = function (name, message) {
//
}

This is called, when the Server receives the request and calls back the method on client side.

How the sample would work!

The sample provided for download, will be having few instructions to follow:

  • When you navigate to the LetsChat/LetsChat route, an alert would pop up asking you for the name with which you would like to chat. Sweet Alert !!
    5
  • Once you enter the name, you see a textbox which asks you for “Your friend’s connection Id”, but since you are starting the chat, you just send a message, and another pop up comes up, with your connection ID, which you need to share with your friends to share your message. Remember, only those who have your ID use it while chatting will be able to see and send through messages to you.
    6
  • When you friend navigates, he ought to generate his connection ID and share with you inorder to set up your connection completely. Thus, you need to have the connID to whom you will be sending and vice-versa with your friend as well. Then just chat!! 🙂
    7

If you would want to send message to all and make that common, then use the Clients.All code snippet to send all.
Another interesting thing, which was figured out is, the use of @section scripts{}, that lets the Signal R scripts render and active on your page and also using the @section scripts provides your code a good outlook.

Share and Send files using SignalR!!

Ooops!! Nice question right!
It is ideally not advised, rather I would not recommend to send or share files using Signal R. There always is better way to accomplish that. The idea would be using API, you can have an upload area, and use SignalR to show the progress and once upload completes, update the user regarding the completion and generate a download link on the UI for the users to download and view the file.
This is not always the best idea, but is just another idea. 🙂

Conclusion

This is just a simple Chat application, which you can use to chat with your friends, if you host on Azure or any other domain. But again,SignalR is not just this much. There is a lot of other effective use of SignalR. Will be sharing more utility of SignalR in few articles more.

References

Asp.Net
Asp.Net|SignalR

]]>
/lets-chat-application-using-signalr-in-mvc/feed/ 1
The Forms and Web Api Bridge /the-forms-and-web-api-bridge/ /the-forms-and-web-api-bridge/#respond Sun, 10 Apr 2016 14:44:27 +0000 /?p=584 Introduction

Recently, a scenario arose in which we had interact to a Web API from either a windows service or windows forms application. The logic and implementation seems easy once you are aware of the proceedings. I would be sharing this article for all those who wonder how! This is what my solution was to resolve this requirement. The implementation and the code is simple, but only a copy paste would not help unless we know what the keywords are and what they are meant for here. So let’s see:

Get Started

Before I start, the basic requirement would be a windows form and a web api project. So, the readers should know how to create a windows form and a web api application as a prerequisite. I will be sharing the Windows Forms application, which will ping the API we set via the url. As we know the medium of interaction or the bridge is HttpClient
According to MSDN:

Provides a base class for sending HTTP requests and receiving HTTP responses from a resource identified by a URI.

As the above definition suggests, the HttpClient class helps send HTTP requests and also get back the responses from the API resource we have provided. (Not only API, this article focuses on API). Thus, HttpClient is our bridge here.
I have created a windows forms application, which will post some values to the API on click of a button and also get back the response from the API. Lets have a look at the code:

private async void button1_Click(object sender, EventArgs e)
        {          
            string value = "After Test Post API (Result From API)"; //This value is sent to the API and again returned the same from it
            var text = await DataReceivedHandler(value);
            txtOutput.Text = text.Result;            
        }
     

        private static async Task DataReceivedHandler(string value)
        {
              using (var client = new HttpClient())
            {
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                var url = new Uri("https://localhost:54640/api/values?value="); //Change the Url to the Host (This is the default Values APi Controller)
                var result = await client.PostAsJsonAsync(url, value);
                if (result.StatusCode == System.Net.HttpStatusCode.NotFound)
                {
                    return await Task.Delay(200)
                                .ContinueWith(t => "Hello");
                }
                string testResult = await result.Content.ReadAsStringAsync();
                return testResult;
            }
        }

I am using async method here, to post the values to the API and also awaiting for the result/response from the API.
Snippet explanation
The default headers, the kind of media types we are sending may it be application/xml, application/xhtml+xml,or text/html. So for each request, we are clearing the headers and then annotating the media type we would be sending through the request.
Then, we are setting and formatting the url to the API, with the query string that needs to be passed.
Then we are posting to the API through the client object, using PostAsJsonAsyc. It is an async method which awaits internally for the response and gets back to the thread once the task is completed.
Then, we check for the response message status code, incase it is a failure (404/any other) or a success(200|OK).
If it is a success, through IsSuccessStatusCode (200|OK), then we are reading again asynchronously the string using ReadAsStringAsync() and finally returning the result from this method block.
This is actually the entire simple flow that flows through in the snippet and how we connect to the API using the bridge.

Conclusion

Here I have shown you how to post values to any API. This can be handy when you are using serial port values to be sent from any machine form client machine to your application hosted on other servers or even cloud. I hope this logic helps!
If any suggestion or better implementation logic, i would love to learn. 🙂

]]>
/the-forms-and-web-api-bridge/feed/ 0
Overview of MVC6 & Deploy application to Azure /overview-of-mvc6-deploy-application-to-azure/ /overview-of-mvc6-deploy-application-to-azure/#respond Sat, 02 Apr 2016 19:04:35 +0000 /?p=558 Introduction

With an anticipation and hope, this article would be an interesting and effective somehow. This article will be covering the Asp.Net 5’s MVC6 Welcome application. a brief about the all new concepts of MVC6 and the new structure it beholds. Then we create our first Welcome application and then have a walk through of the new Azure Portal and deploy our first web application.
Collage

The above image is all that we will be covering in our article.

Get Started

A perfect blend of cloud and web application is what Asp.Net 5 is intended for. Asp.Net 5 is now being called off as .NET core is what that stands out today. It is a framework with open source & cross platform for building cloud based web applications. Here Azure comes integrated to the Visual Studio applications. Web applications either can be deployed to cloud or be running on On-premise. .Net core is available on Visual Studio 2015 build. You can download the community edition of the Visual Studio which is actually free. 🙂
Community Edition Download. Give a try for sure!
.Net 5 core contains a small optimized run time environment called “CoreCLR” One more important point to note is, .Net Core is opensource and the progress can be updated on Github. They have the code exposed and the build can be tracked easily. .Net core is said to contain a set of libraries known as “CoreFx”. Below are the links to the Github. Just have a look:

Another important benefit is termed as “Portability”. What this means is, we can package and deploy the Core CLR which can in turn help you eliminate the dependency on the installed version of .Net framework. Multiple application running on different versions of CLR can be set ups well. This is the magic the team wanted to result out, which is great!
With .NET 5 and VS 2015 comes MVC6 into picture. Microsoft builds are moving faster than the world! 😀
When I first looked at the structure of the Solution when i added a new MVC project, I was like What!!
thinkzoo
Where is Global.asax.cs? Where is Web.config, App_Start?. Did I download the correct files and selected the correct template. These sort of questions were flickering in my mind. When ran the application it ran successfully as well. Strange!!

Let’s have a small trip into the MVC6

Unified MVC Controllers

MVC6, the merger, the blend of three frameworks, i.e. MVC, Web API2 & Web Pages. Previous versions of MVC, while adding a new template would prompt to check whether we want Web API along with MVC. Here we select the MVC project and we get the opportunity to work with API as well.
In previous versions there were two base controller classes, separate for normal controller and also for the Api controller, i.e. ApiController

public class TestController: Controller {

}

public class ApiTestController ; ApiController {

}

In earlier version as shown above, the controller base class were from System.Web.MVC.Controller and for API, System.Web.Http.ApiController. But in MVC6 it is only one, i.e. Microsoft.AspNet.Mvc.Controller.

Different style of HTML helpers

In MVC6 there comes a new title termed as Tag Helpers. They make life much more simpler. How! We will get to know once we see the code snippet.
For normal web pages, as we know the HTML helpers are defined within the System.Web.WebPages.Html under System.Web.WebPages
, whereas in MVC6, it is under the System.Web.MVC assembly..
The HTML helpers which we used to use in Razor or ASPX, were quite difficult for normal HTML developers to understand (suppose designers). Now i MVC6 that has been simplifies using the Tag Helpers.

@using (Html.BeginForm())
{
        @Html.LabelFor(m =&gt; p.EmpName, "Employee Name:")
        @Html.TextBoxFor(m =&gt; p.EmpName)
        
        <input type="submit" value="Create" />
}

But in MVC6 ,

@model AzureDemoProject.Models.Employee
@addtaghelper "Microsoft.AspNet.Mvc.TagHelpers" 
<form method="post">
<div><label>Employee Name:</label> <input type="text" /></div>
<input type="submit" value="Save" />

</form>

Now the second snippet looks more like HTML friendly and also a bit simple.
Mr. Damian Edwards, has posted the source code on Github which has examples of Tag Helpers. Please go through for better live understanding
Git Hub Tag Helpers Download and play around.

Support for Grunt, NPM & Bower

These are the latest trending front end development tools. These are quite new to me as well, 😛 but will be learning and posting articles on these as well in coming days. Stay tuned!!
Ok branding apart, 😉 lets have a brief idea on what these are.
gnpmbower
Bower:-This is a client side item added by default to MVC6 project. If not added, then Right click on the project-> Add->New Item
->Installed(Client Side)-> Bower.json
. You can find then the file is already installed. The file is inside the wwwroot->lib->bootsrap->bower.json. As you open up the file, you can find the client side tool packages added to the project and their versions. Thus, we got to know that the bower is a client side package manager which is used to add the front-end packages like bootstrap, jQuery, angular, etc.
Grunt:-In MVC6 project when we add, we can find the gulpfile.js, this is kind of an alternative to the Grunt as both perform the same kind of functions. The operations they perform is minification, cleaning, concatenation, etc. of both js & css files.
NPM:- Node Package Manager is present under the project with the name project.json. This holds the dependencies and their versions required by the web application we have set up.

"dependencies": {
    "EntityFramework.Commands": "7.0.0-rc1-final",
    "EntityFramework.MicrosoftSqlServer": "7.0.0-rc1-final",
    "Microsoft.ApplicationInsights.AspNet": "1.0.0-rc1",
    "Microsoft.AspNet.Authentication.Cookies": "1.0.0-rc1-final",
    "Microsoft.AspNet.Diagnostics.Entity": "7.0.0-rc1-final",
    "Microsoft.AspNet.Identity.EntityFramework": "3.0.0-rc1-final",
    "Microsoft.AspNet.IISPlatformHandler": "1.0.0-rc1-final",
    "Microsoft.AspNet.Mvc": "6.0.0-rc1-final",
    "Microsoft.AspNet.Mvc.TagHelpers": "6.0.0-rc1-final",
    "Microsoft.AspNet.Server.Kestrel": "1.0.0-rc1-final",
    "Microsoft.AspNet.StaticFiles": "1.0.0-rc1-final",
    "Microsoft.AspNet.Tooling.Razor": "1.0.0-rc1-final",
    "Microsoft.Extensions.CodeGenerators.Mvc": "1.0.0-rc1-final",
    "Microsoft.Extensions.Configuration.FileProviderExtensions" : "1.0.0-rc1-final",
    "Microsoft.Extensions.Configuration.Json": "1.0.0-rc1-final",
    "Microsoft.Extensions.Configuration.UserSecrets": "1.0.0-rc1-final",
    "Microsoft.Extensions.Logging": "1.0.0-rc1-final",
    "Microsoft.Extensions.Logging.Console": "1.0.0-rc1-final",
    "Microsoft.Extensions.Logging.Debug": "1.0.0-rc1-final",
    "Microsoft.VisualStudio.Web.BrowserLink.Loader": "14.0.0-rc1-final"
  },
 "scripts": {
    "prepublish": [ "npm install", "bower install", "gulp clean", "gulp min" ]
  }

As we can see in the above snippet, which is just a part of the project.json file. This is to show the default dependencies added to the project and the pre publish scripts mentioned. When we suppose add a new dependency, suppose I try and add System.Linq, it will list up the Nuget package as intellisense and then we add the version which also comes under the intellisense. Like below image:
projectjson
Then after hitting Ctrl+S, the restoring of the references packages starts.
restor
Then we see the references added. For more information on the project.json file and its contents, please visit the below link:
Project.json
Integration to Cloud & optimized: This is another major boost feature added to MVC6 application. Now it comes integrated to the cloud with Microsoft Azure and also the optimizing and monitoring tool provided by Azure, i.e. Application Insights.
We will have a walk through of adding the cloud Web application and then a brief on Application insights as well.
Boosted Dependency Injection: Now MVC6 application has in built and integrated dependency injection facility. There is no more need for the packages like, Ninject, Unity, Structure Map3 and all. The code for the configuration setting for the dependency injection is added inside the StartUp.cs class file as below:

// 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.AddEntityFramework()
                .AddSqlServer()
                .AddDbContext(options =&gt;
                    options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]));

            services.AddIdentity&lt;ApplicationUser, IdentityRole&gt;()
                .AddEntityFrameworkStores()
                .AddDefaultTokenProviders();

            services.AddMvc();

            // Add application services.
            //Dependency Injection as well
            services.AddTransient&lt;IEmailSender, AuthMessageSender&gt;();
            services.AddTransient&lt;ISmsSender, AuthMessageSender&gt;();
        }

The we normally inject the services into the constructor of the controllers. Is’nt that great!!
appsettings.json: As we know there is no Web.config file in our application, but we need to have a place where we have the settings required by the application at all stages. This is this place. In MVC6, they have had a upper hand over the JSON than the XML. 😛
The connection strings, the other app settings file we used to add inside the Web.config will now be contained here, that to in Json format. An example like below:

"Data": {
    "DefaultConnection": {
      "ConnectionString": "Server=(localdb)\\mssqllocaldb;Database=aspnet5-AzureWebAppDemo-XXXXXXXXXXXXXXXXXXX-XXX;Trusted_Connection=True;MultipleActiveResultSets=true"
    }
  }

global.json: This is a separate folder named Solution Items. here is the global.json file, which contains the solutions’s project references and their dependencies as well. Loos like below:

{
  "projects": [ "src", "test" ],
  "sdk": {
    "version": "1.0.0-rc1-update1"
  }
}

The appsettings is initialized into the project in the Startup.cs file as below:

var builder = new ConfigurationBuilder()
                .AddJsonFile("appsettings.json")
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);

The App_Start which had the RouteConfig.cs file also goes missing. In MVC is present inside the Startup.cs file as below:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
               app.UseMvc(routes =&gt;
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }

Thus, lets have a look at the entry point of the application:

// Entry point for the application.
        public static void Main(string[] args) =&gt; WebApplication.Run(args);

Another nice feature is the segregation of the Models & View Models. The Model now only will deal with the Db Entities and the context, where as the ViewModel will deal with the model classes which are required in the View binding.
This was just a brief about MVC6, more information and application building will be shown in the upcoming articles on MVC6. Now lets jump start the deployment to azure.

done

Head start Deployment

Now lets discuss creating a new MVC6 project from VS 2015 and then deploying to Azure, mostly I will pictorially explain you which will help understand better.

    • Step 1: Create a brand new project from the Visual Studio 2015 templates. Select the cloud directly and then the Web project as we will be deploying our application to azure.
      1
    • Step 2: Then after giving name for the project, another window will prompt which will ask for the Microsoft Azure configurations. Web App Name, which will actually be the URL for the application after hosted on cloud.
      Then asks for the Application Service under which the application will be registered and deployed.
      Region is another important factor which might come handy in the performance of the application. Thus, we select East Asia here.
      If asked for the Database server and the application required we add a new database server or use any existing database. We skip for now the database integration.
      2
    • Step 3: After setting up, we land in creating our first web application and the structure is like below:
      3
    • Step 4: Lets have a look at project structure which gets created.
    • 4
    • Step 5: Lets now publish and deploy our web application. Right click on the project and click ‘Publish’. We then see a window pop up like below:8
    • Step 6: This will now create an Application Service(Webservice) on Azure portal and also deploy our Web Application as a new Website. The status can be seen under Azure Activity :
      10 1112
      The above images are the over all status and the name of the publish package that got deployed.
    • Step 7: Then navigate to the Azure portal, already notifications would be highlighted to let you know that web site is now hosted and you can browse.
      15
      The status app type and the app status will update in a few minutes.

    Conclusion

    Thus, once the website is hosted on Azure, we can browse and run our application and share with anyone to navigate through our application. We came to know in this article how easy it is to deploy to cloud in the latest builds, making the lives of developers much easier. I will be sharing and covering the Application Insights in the next article which will follow this up. I hope this has helped in learning some facts about MVC6 and please post your feedback. Application Insights– upcoming. 🙂

    References

    MVC6
    MVC6 Features

    ]]> /overview-of-mvc6-deploy-application-to-azure/feed/ 0 Working with JSON in MVC /working-with-json-in-mvc/ /working-with-json-in-mvc/#respond Fri, 01 Apr 2016 19:05:10 +0000 /?p=547 Introduction

    JSON Java Script Object Notation , a very familiar and commonly used concept. It is a data interchange medium and is very lightweight. It is one kind of a syntax for storing and passing data. Since it is Java script object notation, it uses the java script style of syntax, but actually is text only. It also is language independent. The format would look like below:

    {"Books":[
        {"name":"Asp.Net Mvc", "code":"111"},
        {"name":"Angular Js", "code":"112"},
        {"name":"Javascript", "code":"113"},
        {"name":"CLR", "code":"114"}
    ]}

    Now this, JSON object can be created and used to POST or GET in MVC application. Usually, when we do an ajax call, we get the HTML fragments and send them to the browser or append to any DOM elements. That is acceptable, but sending HTML elements with data is not advisable, so would not that be great to send data in a specific format and the browser assigns the data into the HTML. Here, JSON comes in handy. Lets see how. I will explain in simple terms and snippets for better understanding as this topic is not complex at all.

    Peek into Snippets!!

    I will proceed with an anticipation that readers are aware of MVC (Model, View & Controller), as I will not be sharing the steps to create an MVC project. So, Lets start.
    When we create a controller in an MVC project, we know the default type added is ActionResult, which is generic to other types of method types pre-defined like: ViewResult, JsonResult, etc.. Thus, for returning a JSON data, we can use either ActionResult or JsonResult,but preferably use JsonResult as we already know the type, the method will return. JsonResult, is actually a special ActionResult, which suggests the ViewEngine that an object of JSON type will be returned rather than normal HTML.
    Lets see the snippet and then try and understand.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.MVC;
    using DemoJsonTest.Models;
    
    namespace DemoJsonTest.Controllers {
        public class EmployeeController : Controller {
            private Employee[] employeeData = {
                new Employee {Name:"Suraj Sahoo",EmpCode:"EMP042"},
                new Employee {Name:"Suraj Sharma",EmpCode:"EMP044"},
                new Employee {Name:"Suraj Ray",EmpCode:"EMP041"}
            };
    
        public ActionResult Index() {
            return View();
        }
       
        public JsonResult GetEmployeeDataJson(string empCode) {
            var employee = employeeData.Where(emp =&gt; emp.EmpCode == empCode).SingleOrDefault();
            return Json(employee, JsonRequestBehaviour.AllowGet);
        }

    Thus,in the above code, we have shown a normal controller, in whose constructor we have explicitly initialized a model named Employee with few dummy data. Then the main part is the JsonReult method using which, we are filtering the data based on the parameter passed, here EmpCode and then returning the Json object. Mark here, we have used JsonRequestBehaviour.AllowGet. Now whats this. This has an interesting concept behind it. Usually, the browsers to avoid malicious sites trying to intercept JSON data returned, in response to a GET request, it does not respond to GET requests by default.

    System.InvalidOperationException: This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet.

    The above is a part of the error thrown when we miss AllowGet. That is self explanatory actually. 😛
    We usually us ajax options, i.e. success method to process the JSON data received from the GET request and append or set to the HTML DOM elements.

    <script type="text/javascript">
    $.ajax({
        url: "GET REQUEST URL",
        type:"GET",
        success: function(empData) {
                var trgt = $("#tblEmployee");
                target.append("<tr><td>" + empData.Name + "</td><td>" + empData.EmpCode + "</td></tr>");
            },
        error: function() {
          //Do something..
            }
    
    });
    // ]]></script>

    Thus, in the above snippet, we are fetching the data in JSON format from the GET response and binding to the table html dom.
    A point to note here is that, when we assign/cast (actually) a model into JSON object and we explicitly specify few properties of the model and miss out on others, MVC framework is clever enough to first convert the model with each property into JSON and then assign default values to those properties which we have missed. Lets see an example of conversion:

    { "EmployeeId":0, "Name":"Suraj Sahoo", "EmpCode":"042",
         "IsActiveEmployee": false, "DepartmentId": null }

    Mark here,that we have only specified the values of Name and the EmpCode, all other values assigned after JSON conversion by the MVC smart framework.

    Conclusion

    We saw and discussed a very simple and interesting topic regarding the JSON in MVC and how smartly MVC handles the conversion. This helps when we use API and then return JSON,XML to interchange and expose our data. JSON is actually an alternative to XML form of data exchange. For angular JS now a dayswhich is in demand,we use the API controller, return JSON data and take the advantage of Angular two-way binding.
    I hope this helps the beginners out there learning MVC. This is a part of it. Enjoy coding. Open to suggestions. Don’t miss to add your feedback. 🙂

    ]]>
    /working-with-json-in-mvc/feed/ 0
    Send SMS using C# application /send-sms-using-c-application/ /send-sms-using-c-application/#comments Thu, 31 Mar 2016 12:22:25 +0000 /?p=540 Introduction

    In this article I will be sharing a quick and an interesting way to send SMS using a simple C# application. I will be using ViaNett API to send messages from my application. I will be creating a simple windows form which will trigger the API and send the SMS.
    Sending SMS has become a common objective for almost every site nowadays. Though they keep irritating you with continuous messages regarding their advertisements.
    1
    We use a simple REST API which provided by various providers in the market. You can try out some of them using the free trial version and send SMS. The reliable and faster one can be chosen. Also check for the Support the team provides.
    I have thrown my hands at ViaNett and Twilio APIs. Here I will be discussing using ViaNett. Let’s start without actually wasting time.

    Get Started

    To start with, visit the ViaNett website (ViaNett Free demo Account). Sign up and register you with your email address for the free account, which will provide you with 5 free SMS.
    After that, you land on a page having contents like below
    2
    Click on the Technical Api and that will navigate to different kinds of API it provides. We here would need the HTTP API in order to send the SMS, as we would be using the WebClient in order to use the API. We will be seeing the code below.
    After you click on the HTTP API, you will be navigated to another page which will have the API listed under an Example like below:

    Create a script to generate a URL like this: https://smsc.vianett.no/v3/send.ashx?src=xxxxx&dst=xxxxx&msg=Hello+world&username=xxxxx&password=xxxxx Retrieve this web page from your script/application, and the SMS will be sent.

    This is the API URL which our Web client will be using.
    Now to start with our demo application, we will be creating a windows form application. Now, I will not be writing up and lengthing my article with the step by step image for creating a Windows Form application. Those who are really new to windows form, please follow one of the best links below.
    Walkthrough To create Windows Form application
    After you create a simple windows form application, it would look something like below:
    3
    Create as simple as you can , as this is just for learning purpose. The UserName is the user name you had provided during the ViaNett registration i.e. the email address
    The password is the password you had given during the registration in the ViaNett.
    Then for the button click we have the following code:

    private void button1_Click(object sender, EventArgs e)
            {
                using (var web = new System.Net.WebClient())
                {
                    try
                    {
                        string userName = txtUserName.Text;
                        string userPassword = txtUserPassword.Text;
                        string msgRecepient = txtPhNumber.Text;
                        string msgText = txtMessage.Text;
                        string url = "https://smsc.vianett.no/v3/send.ashx?" +
                            "src="+msgRecepient +
                            "&dst="+msgRecepient +
                            "&msg="+System.Web.HttpUtility.UrlEncode(msgText,System.Text.Encoding.GetEncoding("ISO-8859-1")) +
                            "&username=" + System.Web.HttpUtility.UrlEncode(userName) +
                            "&password="+userPassword;
                        string result = web.DownloadString(url);
                        if(result.Contains("OK")){
                            MessageBox.Show("Sms sent successfully", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                        else{
                            MessageBox.Show("Some issue delivering","Message",MessageBoxButtons.OK,MessageBoxIcon.Error);
                        }
                    }
                    catch (Exception ex)
                    {
                        
                    }
                }
            }

    The above code would look simple rather it is. 😛

    When you select a Windows Form Application, by default System.Web  is not added to the reference list. Thus, you need to add that from the assembly list.

    System.Web is required as we add the WebClient to use the API and download the response.

    Here in the code, just giving a brief on what this snippet intends:

    We retrieve each text input from the user, i.e. the User name, User password, Text Message & the User Phone Number. We use these as the URL params to the Service API of the ViaNett.

    Then after that we will check for the response after sending the message and accordingly we update the User.

    **Point to note is: The country code needs to be prefixed to the phone number, in order to send the message else it will mail back regarding the failure to the registered email.

    Conclusion

    Thus, this is a small article on the integration and sending SMS using C# aaplication. I hope this helps beginners!! I will come up with more articles with other APIs and their other SMS features they support.

    References

    ViaNett

    ]]>
    /send-sms-using-c-application/feed/ 5
    WebSecurity in MVC /websecurity-in-mvc/ /websecurity-in-mvc/#respond Mon, 02 Mar 2015 19:26:10 +0000 /?p=279 Introduction

    In this article , I would be discussing a very interesting topic called WebSecurity in MVC applicationa and how easy and simple it is to implement and understand. Let me share a small incident for which I came across this concept. Usually we create an MVC application and select a template may it be Internet or Empty (these two are used frequently). Based on these templates, the web project gets scaffolded and we get the final project structure to work on. If we select an Internet application, then by default scaffolding we get controller “Home” and “Account” created. ASP.NET MVC bydefault provides the authentication through the Web Security. I tried to customize the way authentication was done and then realized this is so simple and easy, as it reduces so many lines of our codes. Lets discuss more on this with a small Demo.

    Lets Play..zoo

    Lets briefly get to know what Web Security is!! According to MSDN, it provides security and authentication to Asp.Net web applications with many more features like user account creation, Login User and Log off, Reset & Change Password, with the help of its in-built functions. It internally also does the Password hashing which is one of the main concern during creation of a user account. The different properties and methods are well explained in the MSDN link given above. This is usually called as Helper class that is present in the namespace- “System.WebMatrix.WebData”. When an Internet template is chosen we would find the “Dynamic Link Library” , WebMatrix.WebData.dll
    Lets create a new project in Visual studio:
    Here I create a new Asp.Net Web Project and name it as “WebSecurityDemo” and after clicking on ok the final creation of project in Visual Studio looks like below:
    Capture1
    As we can see in the above image, the project is scaffolded based on the Internet template in MVC. This by default creates the Home controller and Account controller with all kinds of authentication and security. This default web application without any coding, gives user options to Register, Login, Log off and OWIN authentication using Facebook, Twitter, G+(this requires some modification which I will be discussing later). But how does this happen!! This is done by the Authorize attribute provided by MVC, which is one of the best assets of MVC. Just specifying an attribute like “[Authorize]” which restrict user access to the methods/actions if specified at controller level or also can be specified at action level, just like the below snippet:

    [Authorize]
        [InitializeSimpleMembership]
        public class AccountController : Controller
        {
              [AllowAnonymous]
            public ActionResult Login(string returnUrl)
            {
                ViewBag.ReturnUrl = returnUrl;
                return View();
            }

    In the above snippet as you can see the Authorize attribute is given at the controller level, which will restrict users to access the action methods defined inside this controller,but as you can also see another attriute called [AllowAnonymous] this is provided on the action method, which means any user can access this action using the url directly. This attriute overrides the controller level attribute here. The best part to this authorize attributeis we can also override this and create our own custom Authorize attribute like below:-

    namespace WebSecurityDemoTest.Filters
    {
        public class WebSecurityAuthorize:AuthorizeAttribute
        {
            protected bool AuthorizeCore(HttpContextBase httpContext)
            {
                if (!httpContext.Request.IsAuthenticated)
                {
                    return false;
                }
                if (HttpContext.Current.Session["SessionHelper"] == null)
                {
                    return false;
                }
    
                return true;
            }
    
            protected void HandleUnauthorizedRequest(AuthorizationContext filterContext)
            {
                filterContext.Result = new RedirectResult("/");
                base.HandleUnauthorizedRequest(filterContext);
            }
    
        }
    }

    As you might see here, I have created a custom authorize attribute, which first checks if the current http Request is Authenticated or not, Since we will be using FormsAuthentication, this IsAuthenticated gets initialized after Login or inside the LoginPost method like:

    FormsAuthentication.SetAuthCookie(userName,true);

    The boolean value true does the trick. After successful login when the AuthCookie is set, the IsAuthenticated for the request is set to true. Now if that is not true, then it is handled by the other method i.e. HandleUnAuthorizedRequest. When there is an unauthorize request it checks and return the user back to the default page i.e. the login page. Here, as you can also see I have checked for the session also, after the user has a successful login, I create a session and store the values as is usually done, and based on that also I check if the session is not null, if the AuthorizeCore method returns true, then the user navigates to the desired landing page.  Thus, this is how a custom authorize attribute is created.

    Now lets discuss more about another class that is created inside the Filters folder, when the project gets created i.e. <em>”InitializeSimpleMembershipAttribute.cs”</em>. This class is responsible to initialize the tables required by the Web Security to run in the database. Lets see how the class looks like and discuss about that:-

    using System;
    using System.Data.Entity;
    using System.Data.Entity.Infrastructure;
    using System.Threading;
    using System.Web.Mvc;
    using WebMatrix.WebData;
    using WebSecurityDemoTest.Models;
    
    namespace WebSecurityDemoTest.Filters
    {
        [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
        public sealed class InitializeSimpleMembershipAttribute : ActionFilterAttribute
        {
            private static SimpleMembershipInitializer _initializer;
            private static object _initializerLock = new object();
            private static bool _isInitialized;
    
            public override void OnActionExecuting(ActionExecutingContext filterContext)
            {
                // Ensure ASP.NET Simple Membership is initialized only once per app start
                LazyInitializer.EnsureInitialized(ref _initializer, ref _isInitialized, ref _initializerLock);
            }
    
            private class SimpleMembershipInitializer
            {
                public SimpleMembershipInitializer()
                {
                    Database.SetInitializer<UsersContext>(null);
    
                    try
                    {
                        using (var context = new UsersContext())
                        {
                            if (!context.Database.Exists())
                            {
                                // Create the SimpleMembership database without Entity Framework migration schema
                                ((IObjectContextAdapter)context).ObjectContext.CreateDatabase();
                            }
                        }
    
                        WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true);
                    }
                    catch (Exception ex)
                    {
                        throw new InvalidOperationException("The ASP.NET Simple Membership database could not be initialized. For more information, please see https://go.microsoft.com/fwlink/?LinkId=256588", ex);
                    }
                }
            }
        }
    }

    As you can see, since this class extends itself from the ActionFilterAttribute, then it is used as an attribute only, usually at the controller level as you can check in the first code snippet. [InitializeSimpleMembershipAttribute]. This attribute, what it does in simple language is ensures before any action runs, that the membership has been created at the database level or not. So that when a userregisters it stores the data in the system defined tables. System Defined Tables!!thinkzoo. Yes the tables required for the Websecurity are created once we build and run the application and the controller action gets called which has the attribute defined. But how? The below peice of code snippet does the trick:-

    WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true);

    As you can see the method “InitializeDatabaseConnection” present in the WebSecurity class, explains itself what it does. This initializes the database connection based on the first parameter which is the database name here. Then the sql table with the name gets created, with columns UserId as the primary key and the UserName associated with the user who registers. Now we need to add a Database context to our project:

    1. Right click on the Model folder. Select Add new Item:capture2
    2. Then select Data and Add an Ado.Net Entity Data Model with a valid name.Capture3  I have named the data model as WebSecurity.edmx. This creates the conceptual model for the database after we give the connection.
    3. Then we need to specify the connection to the database. You can create a sample database or use an existing one. I will be using one existing one and will show how the tables for websecurity get generated. Select Generate from databaseCapture4
    4. Then the connection needs to be setup. Choose your local server, so in the database textbox enter “.(dot)” which means local DB and that would list the databases present in your local. Choose anyone you wish to.                                                Capture5                  Capture6
    5. Thus, when the connection is success and is established, we can find the connection string in theWeb.Config file.Capture7
    6. Then since you can scroll up and see in the InitializeSimpleMembership.cs we have the DefaultConnection specified, we need to change the configuration specified defaultin the web.config connection string, that is change the Data Source = . and remove the AttachedDbFileName entirely and then specify the Initial Catalog as the database name which you have added during the db connection. Finally the connection string with name “DefaultConnection” looks like:
      <add name="DefaultConnection" connectionString="Data Source=.;Initial Catalog=Customer;Integrated Security=SSPI;" providerName="System.Data.SqlClient" />

       
    7. Thus, we have reached the end to the set up. Now clean and build the solution once and then run. When we run the application, we land on the Home page as the Home controller has no authorization. And also remember one thing the membership/ websecurity tables will only get created once the InitializeSimpleMembership attribute is hit and in the above snippets it gets hit only when the Account controller is accessed. So when we go to any action method that is AllowAnonymous as we also need to land on the page, So we click on the Register.Capture9
    8. The below image shows the table created once the attribute is hit/executed. “dbo.webpages_Membership” stores all the information related to the User registered with the User password that is hashed and that to one way for more security. User Id which acts as the foriegn key here to the UserId primary key in the UserProfile table which also contains the UserName which is asked during the registration.Capture10
    9. After the registration, you will find yourself logged in as the UserName entered and the data in the tables would look like: Capture11Capture12Capture13
    10. Thus this is how the simple attribute, internally does everything.

    Now lets check for the codes , the method WebSecurity class implements. First is the “WebSecurity.UserLogin”

    WebSecurity.Login(model.UserName, model.Password, persistCookie: model.RememberMe)

    This method, takes the UserName, the password and the persistCookie which is the Remember Me check box. This maps the webpages_Membership table and the UserProfile table for the combination of the userName and password, if this satisfies or is perfectly mapped, it redirects user tothe authenticated page, else throws him back to the Login page. if wrong password is entered then it gives the ModelState error as incorrect username and password. If the Remember Me is checked, then the IsPersistent is true in the cookie which is created, then when next time even after closing the browser we come, the cookie persists based on the span it has and authenticates the user without the credentials.

    The next method used is “WebSecurity.ChangePassword”

    WebSecurity.ChangePassword(User.Identity.Name, model.OldPassword, model.NewPassword)

    This method takes the unique username, with the old Password and also the new Password as the parameters. It internally matches first the old password with the User name (Logged In) and then if satisfies stores or replaces the old password with the new one encrypting it or hashing it. This is that simple. 🙂

    Now the other method and an important one, when the user registered, how did the data get saved into the table!! Nice question .. 🙂 The answer is another inbuilt method that does the trick here i.e. “WebSecurity.CreateUserAndAccount”

    WebSecurity.CreateUserAndAccount(model.UserName, model.Password)

    what this does is, takes the parameter as the unique user name and the password, then adds the user name into the UserProfile table that returns the UserId and whichinturn is used as the foreign key with one to one relationship and hashes the password and stores in the webpages_Membership table. This is how a user gets registered so simply using WebSecurity.

    There is also a method called Logout, which simply logs out a user. “WebSecurity.Logout()”.

    Conclusion

    Thus, I discussed in this article the details of WebSecurity class and how to use that in the MVC application. The method and the membership authentication is the same, just we need to customize inorder to have our own hold over it. It is very easy ans simple to use, which makes the code less redundant and reusable and mainly maintainable. This follows usually the DRY concept which is Don’t Repeat Yourself. Thus this suggests to use evrything once, like have an Authorize attribute may it be Custom and reuse it wherever required. WebSecurity has everything defined, we just need to explore and use its methods and properties extensively to reduce the level of coding and LOC.
    Thus here I end my article I hope I could explain atleast something.
    Though I am not an expert and moreover a human, so mistakes are ovious. i would be glad if you find any or also suggestions and discussion are most welcome.
    Share and learn.
    CP

    ]]>
    /websecurity-in-mvc/feed/ 0
    Using API in MVC applications /using-api-in-mvc-applications/ /using-api-in-mvc-applications/#respond Tue, 20 Jan 2015 14:18:44 +0000 /?p=140 Introduction

    The Web Api (Application Programming Interface) feature is based on a special kind of controller to an MVC framework application, its normally as we do in MVC :). An api controller distinguishes itself from the normal controllers by the following :-

    • Action methods return model, rather than an ActionResult in MVC, objects.
    • Action methods are selected based on the HTTP method used in the request.(we will elaborate on this a bit ahead as we go ) 🙂

    The model objects that are returned from an API controller action method are encoded as JSON/XML based on the browsers used and sent to the client.

    Background

    We work using normal MVC4 framework, choosing an empty template. There is also a Web Api template but we cannot get to know the steps using that. Lets get into deeper following the steps in the Code section.

    Using the code

    A Web Api application is just a regular MVC framework app with the addition of a special kind of controller. Lets start with a small Demo for better understanding. Lets go step by step :-

    Creating the Model & Repository

    public interface IReservationRepository{
        IEnumerable&lt;Reservation&gt; GetAll();
        Reservation Get(int Id);
        Reservation Add(Reservation item);
        void Delete(int id);
        bool Update(Reservation item);
    }

    The GetAll() method is of Enumerable type of Reservation as it expects a list of items as output. The Get(Id) method is of type Reservation that expects an item that matches the Id passed/specified. The Add(item) method is also a Reservation type as it adds a new item with the properties of the Reservation entity. The Delete method simply deletes/remove the item with Id passed. The Update method is boolean type as if model state is valid and update is successful its returns true.

    public class ReservationRepository : IReservationRepository {
    private List&lt;Reservation&gt; data = new List&lt;reservation&gt; {
        new Reservation {ReservationId = 1, Name = "ABC", Location = "London"},
        new Reservation {ReservationId = 2, Name = "XYZ", Location = "US"},
        new Reservation {ReservationId = 3, Name = "MNC", Location = "Paris"}
    };
    
    private static ReservationRepository repo = new ReservationRepository();
    public static IReservationRepository getRepository(){
        return repo;
    }
    public IEnumerable GetAll(){
        return data;
    }
    public Reservation Get(int Id){
        var matchedItem = data.where(x =&gt; x.ReservationId == Id);
        return matchedItem.FirstOrDefault();
    }
    
    public Reservation Add(Reservation item){
        item.ReservationId = data.Count() + 1;
        data.Add(item);
        return item;
    }
    public void Delete(int is){
        Reservation item = Get(id);
        if(item != null){
            data.Delete(item);
            }
    }
    public bool Update (Reservation item){
        Reservation Item = Get(item.ReservationId);
        if(Item != null){
            Item.Name = item.Name;
            Item.Location = item.Location;
            return true;
            }
    else{
    return false;
    }
    }
    }

    public class ReservationController:ApiController{
    IReservationRepository repo = ReservationRepository.getRepository();
    public IEnumerable&lt;Reservation&gt; GetAllReservation()
    {
        return repo.GetAll();
    }
    public Reservation GetReservation(int id)
    {
        return repo.Get(id);
    }
    public Reservation PostReservation(Reservation item)
    {
        return repo.Add(item);
    }
    public bool PutReservation(Reservation item)
    {
        return repo.Update(item);
    }
    public void deleteReservation(int id)
    {
        repo.Delete(id);
    }
    }

    1. Lets start creating an Empty template MVC application and name it ReservationDemo. Since we have empty MVC project then we only get Models, Controllers & Views as empty folder. 🙂
    2. We add a model class as Reservation.cs into the Models folder. The Code snippet goes below :
      public class Reservation 
      {
      //Added the properties to the Reservation entity
      
      public int ReservationId {get; set;} // Uniquely identifies each model object.
      
      public string Name {get; set;}
      
      public string Location {get; set;}
      
      }
    3. Now we add an interface IReservationRepository.cs into the models folder again.The code snippet goes below:
    4. Now lets add a Repository class to the Models itself that implements the interface IReservationRepository. The code snippet goes below :- (Remember we are adding here into the models folder.)
    5. The Home Controller a normal controller is created to return the main view page to our app. We just add a view to its Index()ActionResult method.

      Creating API Controller

    6. Add a controller, right click on the contollers folder in the SolutionExplorer and select Add Controller from the popup menu. Change the controller name as ReservationController and select Empty Api Controller from the Template drop-down menu. The Code snippet goes as below:-

    The game after this is with the Jquery where the data results are bind on the ajax calls.

    Points of Interest

    This is an interesting concept, using Api that returns JSON results that can be used to bind data in the viewpage easily, using knockoutJs, BackboneJs.

    Referenced from Adam Freeman, Asp.Net MVC4 book.

    History

    Will post soon the data-bind using Knockout/Backbone Js. Hope this helps beginners like me.

    ]]>
    /using-api-in-mvc-applications/feed/ 0