Thursday, 14 November 2019

Web API using ASP.NET and C#

Background
Connectivity between applications is a very important aspect from a business applications perspective. Nowadays there are a lot of mobile applications and single page applications are being created and such applications needs a strong service end that can provide these applications with the data and CRUD operations on the data.
SOAP and ASP.NET Web services
Traditionally, Web Services provided a great way of creating connected web applications. SOAP and XML created an excellent solution for creating connected web applications. SOAP is a standard XML based protocol that communicated over HTTP. We can think of SOAP as message format for sending messaged between applications using XML. It is independent of technology, platform and is extensible too. ASP.NET Web services provided an excellent way of creating SOAP based web services.
Problems with SOAP
The SOAP offered an excellent way of transferring the data between the applications. but the problem with SOAP was that along with data a lot of other meta data also needs to get transferred with each request and response. This extra information is needed to find out the capabilities of the service and other meta data related to the data that is being transferred coming from the server. This makes the payload heavy even for small data. Also, Web services needed the clients to create the proxy on their end. These proxies will do the marshaling and un-marshaling of SOAP WSDL and make the communication between the application and the web service possible. The problem with this proxy is that if the service is updated and the proxy on the client is not then the application might behave incorrectly.
Welcome to REST
REST stands for Representational State Transfer. This is a protocol for exchanging data over a distributed environment. The main idea behind REST is that we should treat our distributed services as a resource and we should be able to use simple HTTP protocols to perform various operations on that resource.
When we talk about the Database as a resource we usually talk in terms of CRUD operations. i.e. Create, Retrieve, Update and Delete. Now the philosophy of REST is that for a remote resource all these operations should be possible and they should be possible using simple HTTP protocols.
Now the basic CRUD operations are mapped to the HTTP protocols in the following manner:
§  GET: This maps to the R(Retrieve) part of the CRUD operation. This will be used to retrieve the required data (representation of data) from the remote resource.
§  PUT: This maps to the U(Update) part of the CRUD operation. This protocol will update the current representation of the data on the remote server.
§  POST: This maps to the C(Create) part of the CRUD operation. This will create a new entry for the current data that is being sent to the server.
§  DELETE: This maps to the D(Delete) part of the CRUD operation. This will delete the specified data from the remote server.
so if we take an hypothetical example of a remote resource that contain a database of list of books. The list of books can be retrieved using a URL like:
www.testwebsite.com/books
To retrieve any specific book, lets say we have some ID that we can used to retrieve the book, the possible URL might look like:
www.testwebsite.com/books/1 
Since these are GET requests, data can only be retrieved from the server. To perform other operations, if we use the similar URI structure with PUT, POST or DELETE operation, we should be able to create, update and delete the resource form the server. We will see how this can be done in implementation part.
Note: A lot more complicated queries can be performed using these URL structures. we will not be discussing the complete set of query operations that can be performed using various URL patterns.
Now the if we compare the REST API wit SOAP, we can see the benefits of REST. Firstly only the data will be traveling to and fro from the server because the capabilities of the service are mapped to the URIs and protocols. Secondly, there is no need to have a proxy at the client end because its only data that is coming and the application can directly receive and process the data.
WCF REST services
Windows Communication Foundation (WCF) came into existence much later than the web service. It provided a much secure and mature way of creating the services to achieve whatever we were not able to achieve using traditional web services, i.e., other protocols support and even duplex communication. With WCF, we can define our service once and then configure it in such a way that it can be used via HTTP, TCP, IPC, and even Message Queues. We can even configure WCF services to create REST services too i.e. WCF REST Services.
Note: Refer this article for details on WCF REST services: A Beginner’s Tutorial for Understanding Windows Communication Foundation (WCF)[^]
The problem with using WCF restful services is that we need to do a lot of configurations in a WCF service to make it a RESTful service. WCF is suited for he scenarios where we want to create a services that should support special scenarios such as one way messaging, message queues, duplex communication or the services that need to conform to WS* specifications.
But using WCF for creating restful services that will provide fully resource oriented services over HTTP is a little complex. Still WCF is the only option for creating the RESTful services if there is a limitation of using .NET 3.5 framework.
Introducing ASP.NET Web API

ASP.NET MVC - Web API. ASP.NET Web API is a framework that makes it easy to build HTTP services that reach a broad range of clients, including browsers and mobile devices. ASP.NET Web API is an ideal platform for building RESTful applications on the .NET Framework. it is used to develop HTTP based web services on the top of .NET Framework.

Microsoft came up with ASP.NET Web API quite recently to facilitate the creation of RESTful services that are capable of providing fully resource oriented services for a broad range of clients including browsers, mobiles and tablets. ASP.NET Web API is a framework for building REST services easily and in a rather simple way.

Today, a web-based application is not enough to reach all its customers or users. Now a day, Peoples become very smart that means they are using iPhone, mobile, tablets, etc. devices in their daily life. These devices are having a lot of useful apps for making their life easy. Actually, in the simple word we can say that we are moving from the web towards the apps world. So, if we like to expose our service data to the browsers as well as to all these modern devices apps in a fast, secure and simple way, we should have an API which is compatible with all browsers as well as all these modern days devices. ASP.Net Web API is a framework to build HTTP services which can be consumed by cross platform clients including desktops or mobile devices irrespective of the Browsers or Operating Systems being used. ASP.Net Web API supports RESTful applications and uses GET, PUT, POST, DELETE verbs for client communications.

  What is Web API? ASP.NET Web API is a powerful platform for building HTTP enabled service APIs that expose service and data. It can be consumed by a broad range of clients including browsers, mobiles, desktop and tablets. As it is HTTP service, so it can reach a broad range of client. ASP.NET Web API is very much similar to ASP.NET MVC because it contains the ASP.NET MVC feature like routing, controllers, action results, filter, model, etc. Note ASP.NET Web API is not a part of MVC framework. It is a part of the core ASP.NET. You can use Web API with ASP.NET MVC or any other type of web application. You can also create a stand-alone service using the Web API. Note: Using ASP.NET Web API we can only create HTTP services which are non-SOAP based.
  Why do we need Web API?
The ASP.NET Web API is a great framework provided by Microsoft for building HTTP services that can be consumed by a broad range of clients including browsers, mobiles, iPhone, and tablets, etc.  Moreover, ASP.NET Web API is open source and an ideal platform for building REST-full services over the .NET Framework.
These sets of articles are suitable for beginners as well as experienced ASP.NET Web API developers who want to learn ASP.NET Web API from scratch with real-time examples.
The articles start from the very basics of ASP.NET Web API and cover advanced concepts as we progress. If you are confident with the concepts that are going to discuss here, I am sure, you will be in a much better position to answer most of the interview questions as well as you can develop any real-time applications using ASP.NET Web API.

 As you know, today we all are connected with internet. Only web based application is not enough to reach to everyone. Now a days, we all are using apps through mobile devices, tablets which makes our life easy. So, if you want to expose your service to everyone which is accessible on browser as well as modern devices [Mobiles and Tablets Apps] and run fast then you need to expose your service as API which is compatible with every browser as well as these modern devices. ASP.NET Web API uses the full features of HTTP like request/response headers, caching, versioning, etc. It is also a great platform where you can create your REST-FUL services. You don’t need to define extra configuration setting for different devices unlike WCF REST Services.

WCF Rest service 
Note:
I want to clear one misconception that Web API does not replace to WCF. WCF is still a powerful programming model for creating SOAP based services which supports a variety of transport protocols like HTTP, TCP, Named Pipes or MSMQ etc.et's start


Step 1: Create a New Project

Open Microsoft Visual Studio and create a new project (File -> New -> Project). Select the "Installed" Templates, select Visual C#, then select Web. In the list of available templates, select ASP.NET Web Application (.NET Framework). Give your project a name (for my demo, I put "webapi"), then click OK.
In the next modal dialog, you may choose any suitable template. Let's select Web API, so it will prepare all the basic, initial files for the project. Click OK.
Done. Now you can browse the generated folders and files in the Solution Explorer. There are application configs, help page data, a few controllers, fonts, and CSS and JS files.

Routing Table

By default, the server uses the Routing Table located in App_Start/WebApiConfig.cs.
Image title
Pay attention to routeTemplate: "api/{controller}/{id}", it explains the API routing.
Now, let's make a basic example. In this tutorial, we will prepare an API for users, which is a pretty general entity/object of every system.

Adding a User Model

The model represents the user, thus we will include various fields like id, name, email, phone, and role.
In Solution Explorer, right-click in the Models folder, select Add, then select Class. Then provide a class name: User. The model class is ready.
Now we just add all the fields we decided to add:
public class User
{
    public int id { get; set; }
    public string name { get; set; }
    public string email { get; set; }
    public string phone { get; set; }
    public int role { get; set; }
}




Add a User Controller

In the Web API, the controller is an object that handles all HTTP requests. In Solution Explorer, right-click the Controllers. Select Add, then select Controller.
In the given dialog, select the Web API 2 Controller with read/write actions. Name the controller, UsersController. It will prepare the controller with all the proper CRUD actions.
I prepared a basic example with a dummy list of users:
public class UsersController : ApiController
{
    private User[] users = new User[]
    {
        new User { id = 1, name = "Haleemah Redfern", email = "email1@mail.com", phone = "01111111", role = 1},
        new User { id = 2, name = "Aya Bostock", email = "email2@mail.com", phone = "01111111", role = 1},
        new User { id = 3, name = "Sohail Perez", email = "email3@mail.com", phone = "01111111", role = 1},
        new User { id = 4, name = "Merryn Peck", email = "email4@mail.com", phone = "01111111", role = 2},
        new User { id = 5, name = "Cairon Reynolds", email = "email5@mail.com", phone = "01111111", role = 3}
    };
    // GET: api/Users
    [ResponseType(typeof(IEnumerable<User>))]
    public IEnumerable<User> Get()
    {
        return users;
    }
    // GET: api/Users/5
    public IHttpActionResult Get(int id)
    {
        var product = users.FirstOrDefault((p) => p.id == id);
        if (product == null)
        {
            return NotFound();
        }
        return Ok(product);
    }
    ...




Step 2: Deployment

Now you can build your solution (Ctrl+Shift+B in Visual Studio). Once the build has succeeded, you can run it. Click F5 and it will open in your browser automatically at your localhost in an available port (e.g. http://localhost:61024/). Most likely, you don't want to keep it constantly running in Visual Studio, so it'd be better to keep it as service.
In this case, we can deploy it to a local dedicated server using IIS (Internet Information Services).
First, open the IIS, on the left side under Sites - add a New Website (from the right panel or right-click on the Sites). Put in the following details: Site name, "webapi.localhost.net"; Physical path, "C:\projects\webapi" (where your solution is located); Binding - http or https; the host name will be the same, i.e. "webapi.localhost.net." Click OK.
IIS should run the Web API service on webapi.localhost.net.
If you try to open webapi.localhost.net in your browser, it won't open the result we created, because the browser tries to resolve this address (webapi.localhost.net) as a global domain. In order to map this domain name with the local server, we need to modify the local hosts file. On Windows (v10) the hosts file exists in the C:\Windows\system32\drivers\etc folder. The file doesn't have its own extension, it is the "host's" file.
Copy it to another location and open it in the editor.
You need to add the following to the end of this file:
# Web API host
127.0.0.1       webapi.localhost.net




Now you need to put the modified file back in the C:\Windows\system32\drivers\etc folder. As this folder is protected by Windows by default, you will get an access denied warning message, so you need to copy the file "As Administrator."
After the file is updated, webapi.localhost.net should load from your localhost (C:\projects\webapi).

Testing the API

It is time to test the API methods we created for our Web server: api/users and api/users/{id}. Open http://webapi.localhost.net/api/users in your browser. You should get the following output:
As we are creating the external API which should be accessible from outside our IDE, we need to test our API from another page. The easiest way is to do so is via the development toolbar (which exists in any modern browser). Usually it is activated when you press F12. Go to the 'Console' tab. Below I prepared two small examples you can use to test the APIs
In case jQuery is available, you can use:
$.ajax({
    type: "GET",
    url: 'http://webapi.localhost.net/api/users',
    success: (data) => {
        console.log(data);
    }
});




Otherwise, using native JavaScript, you can use the following code:
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://webapi.localhost.net/api/users');
xhr.onload = function() {
    console.log(xhr.response);
};
xhr.send();




Very likely you will receive the following error:
The response to the preflight request doesn't pass an access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource, because regular web pages can use the XMLHttpRequest object to send and receive data from remote servers, but they're limited by the same origin policy. Extensions aren't so limited. An extension can talk to remote servers outside of its origin, as long as it first requests cross-origin permissions.
Cross-Origin Resource Sharing (CORS) is a mechanism that uses additional HTTP headers to tell a browser to let a web application running at one origin (domain) have permission to access selected resources from a server at a different origin.

Adjust Cross-Origin Resource Sharing (CORS)

In order to solve this, we need to enable the CORS in our solution. In Visual Studio, open the Package Manage Console (available at the bottom of your screen, between Error List and Output). Run the following: Install-Package Microsoft.AspNet.WebApi.Cors
This will install the WebApi.Cors reference. Then open the "App_Start\WebApiConfig.cs" file. Add
config.EnableCors();
before
config.MapHttpAttributeRoutes();
Then go back to our UsersController.cs and add [EnableCors(origins: "*", headers: "*", methods: "*")] before the class definition.
Finally - rebuild the project again. Then try to test the APIs again; now it should work.

Tuesday, 12 November 2019

Design Pattern in Software Development (Examples using C#)

Design patterns are typical solutions which helps us solve to commonly-occurring problems in software design. Each pattern is like a blueprint that you can customize to solve a particular design problem in your code.

A pattern is not a specific piece of code, but a general concept for solving a particular problem. They are like pre-made blueprints that we can customize to solve a recurring design problem in our code.

(Design patterns are optimized, reusable solutions to the programming problems that we encounter every day. A design pattern is not a class or a library that we can simply plug into our system; it's much more than that. It is a template that has to be implemented in the correct situation. It's not language-specific either. A good design pattern should be implementable in most—if not all—languages, depending on the capabilities of the language. Most importantly, any design pattern can be a double-edged sword— if implemented in the wrong place, it can be disastrous and create many problems for you. However, implemented in the right place, at the right time, it can be your savior.)

  • Creational patterns provide object creation mechanisms that increase flexibility and reuse of existing code. (provide instantiation mechanisms, making it easier to create objects in a way that suits the situation.)
  • Structural patterns explain how to assemble objects and classes into larger structures, while keeping the structures flexible and efficient. (generally deal with relationships between entities, making it easier for these entities to work together)
  • Behavioral patterns take care of effective communication and the assignment of responsibilities between objects.(are used in communications between entities and make it easier and more flexible for these entities to communicate)

Thursday, 8 December 2016

JQuery for Beginners (Concept clear writing)

JQuery is open source lightweight Javascript Library which makes easy interaction between HTML and JavaScript. 

JQuery is not a language. JavaScript is a Language. JQuery is built over JavaScript and acts like a extendable javascript framework to simplifies HTML document manipulation, event handling, animating, and Ajax interactions for rapid web development.

Purpose of jQuery is to make it easy to use JavaScript on your website. JQuery also simplifies a lot of the complicated things from JavaScript, like AJAX calls and DOM manipulation.

If we know HTML CSS and JavaScript then jQuery learning will not be a big problem

jQuery takes a lot of common tasks that require many lines of JavaScript code to accomplish, and wraps them into methods that you can call with a single line of code.
The jQuery library contains the following options (means what JQuery can do):
  1. HTML and DOM operation or management
  2. CSS operation or management
  3. HTML event methods
  4. Animations and Effects
  5. AJAX

JQuery  a single JavaScript file and can be used by adding JQuery library in HTML file. (The <script> tag should be inside the <head> section):
<head>
<script
 src="jquery-3.1.1.min.js"></script>
</head>

No ned to add  type="text/javascript" inside the <script> tags  as JavaScript is the default scripting language in HTML5 and in all modern browsers.

 Common Syntax for JQuery is
$(<Where >).<When >(<What >);

Explanation : I want to show a message when ever document is ready or loaded completely.

Where(Selectors) : On Document.
When (Action): Document is in ready state or loaded completely.
What(Function) : Show an alert message.

JQuery selectors are used to "find" (or select) HTML elements based on their name, id, classes, types, attributes, values of attributes and much more.

JQuery syntax for above requirement is
$(document).ready(alert("Hi this is for for Dotnestspider lovers"));

Basic syntax is: $(selector).action()
  • A $ sign to define/access jQuery
  • A (selector) to "query (or find)" HTML elements
  • A jQuery action() to be performed on the element(s)

Examples:
$(this).hide() - hides the current element.
$("p").hide() - hides all <p> elements.
$(".test").hide() - hides all elements with class="test".

Complete Skeleton Example

<html>
<head>
<meta charset="utf-8" />
<title>Dotnetspider tutorial</title>
</head>
<body>

<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>

$(document).ready(alert("Hi"));

</script>
</body>
</html>

One special thing in JQuery
$(document).ready(function(){
  
 // jQuery methods are to be here
});

Why this is required?
This is to prevent any jQuery code from running before the document is finished loading (is ready).

It is nice to wait for the document to be completly loaded and ready before working with it. This also allows you to have your JavaScript code before the body of your document, in the head section.

When it fails fail if methods are run before the document is fully loaded
  • Trying to hide an element that is not generated yet
  • Trying to get the size of an image that is not loaded yet

The shorter method for above document.Ready is
$(function(){
  
 // jQuery methods are to be here
});



Saturday, 13 February 2016

Facts about Shree Jagganath. Still scientist are curious to know the science behind it. We are proud to be part of Shree Jagganath

1. The flag atop the temple always flaps in the opposite direction of air.
2. From any place in Puri you will always find the Sudarshan Chakra (Chakra at top of Temple) facing you.
3.Normally during day-time, air comes from sea to land & during evening, the vice-versa occurs. But in Puri it’s totally opposite.
4. No bird or planes fly above the temple.
5. The shadow of the main dome is invisible at any time of the day.
6. The quantity of cooked food inside the Temple remains same for the entire year. But that same quantity of prasadam can feed few thousand people & 20 lakh people, Still it won’t get wasted.

7. In the Temple kitchen, 7 pots are kept one on top of another and cooked on firewood. In this process the contents in the top pot get cooked first & then the bottom one.
8. After entering from Singhadwara’s first step (from inside of the Temple), you cannot hear any sound produced by the ocean. But, when you cross the same step (from outside of the Temple) you can hear it. This can be noticed clearly during evening.

Friday, 12 February 2016

Some Asp.net code snippets

TextChange event in ASP.NET (type in one textbox and get in other control instantly)
CodeBehind
txtPrice.Attributes.Add("onkeyup", "rewriteLabel()");
txtRtNon.Attributes.Add("onkeyup", "rewriteLabelNon()");

HTML side
function rewriteLabel()
{
       document.getElementById('txtCFPrice').value = document.getElementById('txtPrice').value;
}

function rewriteLabelNon()
 {
       document.getElementById('txtCFNon').value = document.getElementById('txtRtNon').value;
}
Clear the columns of GridView
grdview.Columns.Clear()

Attach Scrollbar in a GridView
<DIV style="height:400px; overflow:auto;Width:775px">
GridView here
</DIV>
String cookiename = TextBox1.Text;
        //grab cookie
        HttpCookie cookie = Request.Cookies[cookiename];
        //exists?
        if (null == cookie)
        {
            Label1.Text = "cookie not found";
        }
        else
        {
            password.Text=cookie.Value.ToString();
        }
Solution
TextBox2.Attributes.Add("value", cookie.Value.ToString());
Description
When the TextMode property of an ASP.NET TextBox is set to Password the value set in the Text property will not display at runtime. This can be a pain, however it is actually by design to prevent the unmasked password from being displayed in the HTML source of the page.
While the security reasons are good to not display the masked password value, leaving it unmasked in the source, it is also necessary at times to display the masked value in the TextBox. For example, a user profile page where the user has the ability to change their password. It makes sense to display it there. After all, the user has already authenticated to get to the page (although the value is sent with the data to the browser and could easily be sniffed).
Security reasons aside, you can work around this by adding the password value to the control as as Attribute. Since the TextBox renders as an HTML input control, you can set the value attribute easily, just as you would set the Text property.

Use this to set the value, instead of setting the Text property. You can still read the value from the control via the Text property.

If you get a error like multiple item can be selected for the dropdownlist.
How to assign text/value to a dropdownlist
The first method to select an item in an ASP.NET DropDownList control is using SelectedIndex property. To find the SelectedIndex of an item, you can use IndexOf method and pass use FindByValue method. Here is the code snippet to select item Mahesh" in the DropDownList.
DropDownList1.SelectedIndex = DropDownList1.Items.IndexOf(DropDownList1.Items.FindByValue("Mahesh"))
Alternatively, you can loop through all items of the DropDownList and compare the value of the item and use Selected property to select the matched item.
Private Function SelectCurrentQuarterAndYear(ByVal stringToSelect As String)
        DropDownList1.ClearSelection()
        For Each item As ListItem In DropDownList1.Items
            If item.Text = stringToSelect Then
                item.Selected = True
                Exit For
            End If

       
Next
End Function
To Disable Browser’s back button

Just put in html side of every page (from which page , you are coming ang to the page you came. Then only you can stop the back button for both the pages. If you are using common user control in all pages the in user contro’s html side put this code.)

<script language="javascript">
        window.history.forward(1);
</script>
MessageBox with alert in DOTNET
protected void ShowMessageBox(string messageDisplay)
        {
            string sJavaScript = "<script language=javascript>\n";
            sJavaScript += "alert('" + messageDisplay + "');\n";
            sJavaScript += "</script>";
            Page page = HttpContext.Current.Handler as Page;

            if (page != null)
            {
                messageDisplay = messageDisplay.Replace("'", "\'");
                ScriptManager.RegisterStartupScript(page, page.GetType(), "err_msg", "alert('" + messageDisplay + "');", true);

            }
        }
You can not add HTML i
nside JavaScript alert(). You can do some custom popup for this porpose like on as jQuery Dialog

Baisic Useful Git Commands

  Pushing a fresh repository Create a fresh repository(Any cloud repository). Open terminal (for mac ) and command (windows) and type the be...