Tag Archives: .net

How To Develop Web API in ASP.NET Core

To mention, developing Web API in ASP.NET Core is equivalent to decorating Web API in ASP.NET MVC with a few differences. The differences are mentioned below in brief:

  • Web API is not a separate framework. It got merged with ASP.NET Core MVC.
  • Previously a Web API class used to inherit from ApiController base class. Due to the merging mentioned above, the Web API doesn’t inherit from ApiController, in fact it inherits from the same Controller class that other controllers also inherit from.
  • As Web API is just another controller, you are free to have as many actions you want. Of course, to create a REST style service you still need to have those standard Get(), Post(), Put() and Delete() actions as before.
  • You can define the HTTP verb and action mapping at the action level using features like [HttpPost], [HttpPut] and [HttpDelete].

With the above overview, let’s build a simple REST style Web API that performs CRUD operations on the Customers table of the Northwind database.

Start by creating a new ASP.NET Core project using VS and pick the Web API project template.

The project contains ValuesController in the Controllers folder. Take note that the ValuesController inherits from Controller base class just like any other MVC controller.

Rename the default Web API class to CustomerServiceController. You will require database support for your service and hence you need to add NuGet packages for Entity Framework Core. You can do that through Project.json file:

….

“Microsoft.EntityFrameworkCore”: “1.0.1”,

“Microsoft.EntityFrameworkCore.SqlServer”: “1.0.1”

….

Take the Startup class and modify as shown below:

public class Startup

{

public void ConfigureServices

(IServiceCollection services)

{

services.AddMvc();

services.AddEntityFrameworkSqlServer();

}

public void Configure

(IApplicationBuilder app)

{

app.UseStaticFiles();

app.UseMvc(routes =>

{

routes.MapRoute(

name: “default”,

template: “{controller=Home}

/{action=Index}

/{id?}”);

});

}

}

The ConfigureServices() method sums up MVC and Entity Framework Core to the services collection. The Configure() method configures the MVC routing. This routing is not required by the Web API as such but is needed for local clients while consuming the Web API (as you will see in later parts).

Then add Models and Views folders to the project. Add Customer model class in the Models folder as given below:

[Table("Customers")]

public class Customer

{

[Key]

public string CustomerID { get; set; }

public string CompanyName { get; set; }

public string ContactName { get; set; }

public string Country { get; set; }

}

The Customer class is decorated with [Table] attribute that maps it to the Customers table. It contains four public properties namely CustomerID, CompanyName, ContactName and Country. The CustomerID is marked as the primary key using the [Key] attribute.

Then add NorthwindDbContext class to the Models folder and write the following code to it:

public class NorthwindDbContext:DbContext

{

public DbSet<Customer> Customers { get; set; }

protected override void OnConfiguring

(DbContextOptionsBuilder optionsBuilder)

{

optionsBuilder.UseSqlServer(“data source=.;

initial catalog=northwind;

integrated security=true”);

}

}

The NorthwindDbContext class acts as the DbContext for our data access and inherits from the DbContext class. The NorthwindDbContext defines Customers DbSet. The OnConfiguring() method configures the DbContext to use the SQL Server database with the specified connection string. Ensure to adjust the connection string to suit your need.

Now, open the CustomerServiceController and type the following code:

[Route(“api/[controller]“)]

public class CustomerServiceController : Controller

{

[HttpGet]

public List<Customer> Get()

{

using (NorthwindDbContext db =

new NorthwindDbContext())

{

return db.Customers.OrderBy(

i => i.CustomerID).ToList();

}

}

[HttpGet("{id}")]

public Customer Get(string id)

{

using (NorthwindDbContext db =

new NorthwindDbContext())

{

return db.Customers.Where(

i => i.CustomerID == id).SingleOrDefault();

}

}

[HttpPost]

public string Post([FromBody]Customer obj)

{

using (NorthwindDbContext db =

new NorthwindDbContext())

{

db.Customers.Add(obj);

db.SaveChanges();

return “Customer added successfully!”;

}

}

[HttpPut("{id}")]

public string Put(string id, [FromBody] Customer obj)

{

using (NorthwindDbContext db =

new NorthwindDbContext())

{

db.Entry(obj).State = EntityState.Modified;

db.SaveChanges();

return “Customer modified successfully!”;

}

}

[HttpDelete("{id}")]

public string Delete(string id)

{

using (NorthwindDbContext db =

new NorthwindDbContext())

{

var obj = db.Customers.Where(

i => i.CustomerID == id).SingleOrDefault();

db.Customers.Remove(obj);

db.SaveChanges();

return “Customer deleted successfully!”;

}

}

}

Take note of the following about the Web API you have created:

  • The CustomerServiceController is designed with [Route] feature that configures the routing for the Web API. The route adds /api is written after the name of the controller. So, our Web API will be located at /api/CustomerService.
  • The Web API comprise of five actions namely Get(), Get(id), Post(), Put(), Delete().
  • The HTTP verb to action mapping is done using the features – [HttpGet], [HttpPost], [HttpPut] and [HttpDelete] respectively.
  • The Customer parameter of the actions is model bound and makes use of the [FormBody] feature which indicates the parameter values that will be coming from the request’s body.
  • These features also specify the id route parameter when necessary.

Here in this article we shall not discuss the details of the Entity Framework Core code that is present in these actions. If you worked with EF before that code must be familiar to you. The above mentioned actions generally implement CRUD (create, read, update and delete) operations for the Customers table.

Ok. This completes the CustomerService Web API. Run the application and see the result. If all goes well you should see JSON customer objects removed in the browser.

Return of the IActionResult and HTTP status codes

In the above example the actions gave back the specific types like List<Customer>, Customer and string. However, that’s not required. You might return a generic IActionResult from all the Web API action methods. This technique gets easy when you want to indicate HTTP status codes along with the return values.

Consider the Put() method given below:

[HttpPut("{id}")]

public IActionResult Put(string id,

[FromBody] Customer obj)

{

using (NorthwindDbContext db =

new NorthwindDbContext())

{

db.Entry(obj).State = EntityState.Modified;

db.SaveChanges();

return new ObjectResult

(“Customer modified successfully!”);

}

}

The Put() now returns IActionResult in place of a string. Inside, the code develops a new ObjectResult object to return a string value back to the caller. The ObjectResult sets the HTTP status code to 200 (Ok) and then returns the specific value to the caller. All the actions of our CustomerService Web API can be modified to use this technique.

If you don’t want to return anything from an action (void) then you can use NoContentResult object instead of ObjectResult. The NoContentResult returns HTTP status 204 (no content).

You can also use certain inbuilt methods to indicate the HTTP status code. Some of them are mentioned below:

  • Ok() : Gives back HTTP status code of 200 (ok).
  • BadRequest() : Gives back HTTP status code of 400 (bad request).
  • NotFound() : Gives back HTTP status code of 404 (not found).

The following code shows Get(id) action modified to use NotFound() method.

[HttpGet("{id}")]

public IActionResult Get(string id)

{

using (NorthwindDbContext db =

new NorthwindDbContext())

{

var data= db.Customers.Where

(i => i.CustomerID == id).SingleOrDefault();

if(data==null)

{

return NotFound(“Invalid CustomerID!”);

}

return new ObjectResult(data);

}

}

As you can see, the code now checks whether data is null or not. If it is null it indicates that the CustomerID was not found in the database and hence NotFound() method is called with a custom error message.

We conclude the discussion here.

Keep coding!

Let us know your opinion in the comments sections below. And feel free to refer Microsoft’s site to gather more information.

If you want to improve your skill in ASP.Net and excel yourself in ASP.NET training program; our institute, CRB Tech Solutions would be of great help and for you. Come and join us with our well structured program for ASP .Net.

Stay connected to CRB Tech for more technical optimization and other updates and information.

Don't be shellfish...Buffer this pageEmail this to someoneDigg thisShare on FacebookShare on Google+Share on LinkedInPrint this pageShare on RedditPin on PinterestShare on StumbleUponTweet about this on TwitterShare on Tumblr

How To Highlight Keywords Using ASP.NET Core Middleware

Today in this article we shall discuss how to highlight keywords from response using .NET core middleware. Sometime you need to search for certain keywords from a response body and then highlight them with various colours. In ASP.NET Web Forms there is an HTTP module to achieve this. In ASP.NET MVC you must have written a custom filter to achieve this task. In ASP.NET Core you can code a custom middleware to do the same. This article tells you how.

If you are not aware with ASP.NET Core middleware, I suggest you read the basics first and then continue with this.

Let’s take a scenario that closely resembles what has been mentioned above and then create a simple example to explain what we learn.

Suppose you are building a website using ASP.NET Core. The website has a search box.

You can enter some keywords to search for and press the Search key. The server side then generates the response based on the business logic and also highlights the keyword. Let’s say the keyword “Nancy” gets highlighted.

Why do you need such functionality? The above scenario is quite straight and strictly speaking doesn’t need middleware as such, just consider the following possibilities:

  • You want to automatically insert advertisements into the response depending on one or more keywords.
  • You might wish to add headers or footers dynamically.
  • You want to tamper with the response HTML to suit your needs.
  • You want to do all the above without writing any specific program in the controllers or views.

In a nutshell, you want to manipulate the response from the server to suit your needs.

Now when you understood what we want to explain, let’s create a simple middleware that really does what we wish.

Start by creating a new ASP.NET Core project based on the Web Application template. Then sumup HomeController and Index view as usual. Place the following HTML markup inside the Index view.

@{

ViewData["Title"] = “Home Page”;

}

<div>

<form asp-action=”Index” asp-controller=”Home” method=”post”>

<input type=”text” name=”keyword” />

<input type=”submit” value=”Search” />

</form>

<p>Nancy Davolio : Her ducation comprise of a BA

in psychology from Colorado State University in 1970.

She also completed “The Art of the Cold Call.”

Nancy is a fellow of Toastmasters International.</p>

</div>

The Index view has a form tag helper that submits to the Index action of the HomeController. The method is set to POST. The form has of a textbox named keyword and a submit button. The paragraph just below the form simply holds a number of text data. The text will be generated from a database based on some server side processing. To make things simple, we won’t discuss about data access code here.

Next add a middleware class to the project and name it – MyMiddleware. The complete code of MyMiddleware is shown here:

public class MyMiddleware

{

private RequestDelegate nextMiddleware;

public MyMiddleware(RequestDelegate next)

{

this.nextMiddleware = next;

}

public async Task Invoke(HttpContext context)

{

if (context.Request.Method.ToUpper() == “POST”)

{

string highlightedText = “”;

Stream originalStream = context.Response.Body;

using (MemoryStream newStream = new MemoryStream())

{

context.Response.Body = newStream;

await this.nextMiddleware.Invoke(context);

context.Response.Body = originalStream;

newStream.Seek(0, SeekOrigin.Begin);

StreamReader reader = new StreamReader(newStream);

highlightedText = reader.ReadToEnd();

string keyword = context.Request.Form["keyword"];

highlightedText = highlightedText.Replace

(keyword, $”<span class=’Highlight’>{keyword}</span>”);

await context.Response.WriteAsync(highlightedText);

}

}

else

{

await this.nextMiddleware.Invoke(context);

}

}

}

The MyMiddleware class has a public constructor and asynchronous Invoke() method.

The constructor gets a RequestDelegate object that is a pointer to the next middleware in the chain. The Invoke() method is responsible for invoking your custom code and then call the next middleware.

The constructor first checks if the request is POST or not. We wish to highlight a keyword later after the operation, so this check is essential. The code then develops a new MemoryStream object and sets it to the Response’s Body property. It then invokes the next middleware such that we can begin our highlight operation.

The code then reads the whole response text using a StreamReader’s ReadToEnd() method. Once we have the text, we find out the keyword entered in the textbox.Then the code substitutes that keyword from the highlightedText string variable by wrapping it in a <span> tag. The <span> tag bears the Highlight CSS class that takes care of the highlight background color and text color. Finally, the modified text is written onto the response stream using the WriteAsync() method.

The Highlight CSS class is shown below:

.Highlight

{

background-color:brown;

color:white;

font-weight:bold;

padding:4px;

}

We are done with the middleware class. Let’s design an extension method such that we can add it more easily. Add MyMiddlewareExtensions class to the project and write the following program to it:

public static class MyMiddlewareExtensions

{

public static IApplicationBuilder UseMyMiddleware

(this IApplicationBuilder app)

{

return app.UseMiddleware<MyMiddleware>();

}

}

The above code has an extension method named UseMyMiddleware() and internally calls IApplicationBuilder’s UseMiddleware<T>() method.

Now, you can finish up your middleware by invoking this extension method from the Configure() method as shown below:

public void Configure(IApplicationBuilder app,

IHostingEnvironment env,

ILoggerFactory loggerFactory)

{

app.UseMyMiddleware();

….

….

app.UseStaticFiles();

app.UseMvc(routes =>

{

routes.MapRoute(

name: “default”,

template:

“{controller=Home}/{action=Index}/{id?}”);

});

}

We conclude the discussion here.

Let us know your opinion in the comments sections below. And feel free to refer Microsoft’s site to gather more information.

If you want to improve your skill in ASP.Net and excel yourself in ASP.NET training program; our institute, CRB Tech Solutions would be of great help and for you. Come join us with our well structured program for .Net.

Stay connected to CRB Tech for more technical optimization and other updates and information.

Don't be shellfish...Buffer this pageEmail this to someoneDigg thisShare on FacebookShare on Google+Share on LinkedInPrint this pageShare on RedditPin on PinterestShare on StumbleUponTweet about this on TwitterShare on Tumblr

Consume ASP.NET Core Web API using jQuery

In the article we shall discuss to create a Web API using jQuery. A Web API can be created by local clients or remote clients. Local clients are housed in the same web application as the Web API. Remote clients are the clients that are not part of the Web API application.

To tell about web applications, a typical local client takes a form of jQuery Ajax driven user interface that consumes the Web API. For instance, consider a simple page shown below:

The above client to the CustomerService Web API comprise of a dropdown list and 4 textboxes. The dropdown list has a list of present CustomerIDs. Selecting a CustomerID gives the other textboxes the respective values. You can change the values and click on Update button to save them. To insert a new Customer, do specify its CustomerID in the textbox besides the dropdown list, fill in other details and press the Insert button. Finally, to erase a Customer, select its CustomerID from the dropdown list and click on the Del button.

To design this page, add a new controller – HomeController – in the Controllers folder. Also add Index view and write the following HTML markup into it:

<h1>Customer Manager</h1>

<form>

<table border=”1″>

<tr>

<td>Customer ID :</td>

<td>

<select id=”customerid”></select>

OR

<input id=”newcustomerid” type=”text” />

</td>

</tr>

<tr>

<td>Company Name :</td>

<td><input id=”companyname” type=”text” /></td>

</tr>

<tr>

<td>Contact Name :</td>

<td><input id=”contactname” type=”text” /></td>

</tr>

<tr>

<td>Country :</td>

<td><input id=”country” type=”text” /></td>

</tr>

<tr>

<td colspan=”2″>

<input type=”button” id=”insert”

value=”Insert” />

<input type=”button” id=”update”

value=”Update” />

<input type=”button” id=”delete”

value=”Delete” />

</td>

</tr>

</table>

<br />

<div id=”msg”></div>

</form>

To initiate the Web API you created earlier, you will use jQuery Ajax. So, sum up Scripts folder under the wwwroot folder and place jQuery library into it

Also, add a <script> reference to the jQuery library in the <head> section of the Index view.

<script src=”~/Scripts/jquery-3.1.1.min.js”></script>

There are 5 jQuery Ajax calls needed by our client. They are as follows:

  • No sooner a page loads in the browser, the dropdown list must be filled with all the existing CustomerIDs. This is done by bringing the Get() Web API action through jQuery Ajax.
  • When you select a CustomerID from the dropdown list its details such as CompanyName, ContactName and Country are shown in the respective textboxes. This is done with the Get(id) Web API action from the change event handler of the dropdown list.
  • Clicking Insert, Update and Delete buttons call the Post(), Put() and Delete() Web API actions respectively, again through jQuery Ajax.

Next write the first Ajax call.

Filling the dropdown list with CustomerIDs

$(document).ready(function () {

var options = {};

options.url = “/api/customerservice”;

options.type = “GET”;

options.dataType = “json”;

options.success = function (data) {

data.forEach(function (element) {

$(“#customerid”).append(“<option>”

+ element.customerID + “</option>”);

});

};

options.error = function () {

$(“#msg”).html(“Error while

calling the Web API!”);

};

$.ajax(options);

});

The above written code makes an Ajax request using $.ajax() method of jQuery. Take notice how the url, type and dataType properties of the options object are specified. Since we wish to start Get() action, the url points to the Web API end point. The HTTP verb used is GET and the response data type is all set to json.

The success function simply fills the dropdown list with a series of <option> element each wrapping a CustoemrID. The error function portrays an error message when something goes wrong while starting the Web API.

Displaying details of a selected customer

The change event handler of the dropdown looks like this:

$(“#customerid”).change(function () {

var options = {};

options.url = “/api/customerservice/” +

$(“#customerid”).val();

options.type = “GET”;

options.dataType = “json”;

options.success = function (data) {

$(“#companyname”).val(data.companyName);

$(“#contactname”).val(data.contactName);

$(“#country”).val(data.country);

};

options.error = function (a, b, c) {

alert(a.responseText);

$(“#msg”).html(“Error while

calling the Web API!”);

};

$.ajax(options);

});

This code is very similar to the previous one. However, it adds the CustomerID whose details are to be fetched to the url. The success function fills the 3 textboxes with CompanyName, ContactName and Country. Do notice something significant- the property names are automatically converted to use camel casing. This way client side code gets to stick with the JavaScript ways of naming the things whereas server side code can continue to stick to the C# ways of naming the things.

To add a new customer

The click event handler of the Insert button is shown below:

$(“#insert”).click(function () {

var options = {};

options.url = “/api/customerservice”;

options.type = “POST”;

var obj = {};

obj.customerID = $(“#newcustomerid”).val();

obj.companyName = $(“#companyname”).val();

obj.contactName = $(“#contactname”).val();

obj.country = $(“#country”).val();

options.data = JSON.stringify(obj);

options.contentType = “application/json”;

options.dataType = “html”;

options.success = function (msg) {

$(“#msg”).html(msg);

};

options.error = function () {

$(“#msg”).html(“Error while

calling the Web API!”);

};

$.ajax(options);

});

The above written code uses POST verb to make the Web API call. Also, it sets data, dataType and contentType properties. The data property is set to the stringed version of the new customer object. Take note that this new object also uses camel casing while setting the properties. The dataType property is set to html because our Post() action returns a plain string. The contentType property indicates the request’s data type – JSON in this case.

The success function simply displays the message returned by the Post() action into the msg <div> element.

To modify an existing customer

The click event of the Update button is shown below:

$(“#update”).click(function () {

var options = {};

options.url = “/api/customerservice/”

+ $(“#customerid”).val();

options.type = “PUT”;

var obj = {};

obj.customerID = $(“#customerid”).val();

obj.companyName = $(“#companyname”).val();

obj.contactName = $(“#contactname”).val();

obj.country = $(“#country”).val();

options.data = JSON.stringify(obj);

options.contentType = “application/json”;

options.dataType = “html”;

options.success = function (msg) {

$(“#msg”).html(msg);

};

options.error = function (a, b, c) {

alert(c);

$(“#msg”).html(“Error while

calling the Web API!”);

};

$.ajax(options);

});

Most of the above program is similar to the code you wrote in the insert click event handler. The CustomerID being changed is added to the url. The HTTP verb is set to PUT.

To Delete a customer

Finally, the code that deletes a customer is mentioned below:

$(“#delete”).click(function () {

var options = {};

options.url = “/api/customerservice/”

+ $(“#customerid”).val();

options.type = “DELETE”;

options.dataType = “html”;

options.success = function (msg) {

$(“#msg”).html(msg);

};

options.error = function () {

$(“#msg”).html(“Error while

calling the Web API!”);

};

$.ajax(options);

});

The above program sets the HTTP verb to DELETE and makes an Ajax call like before.

This finishes the jQuery client to the Web API. Now you need to run the Index view and test all the operations.

We conclude the discussion here. Keep coding!!

Let us know your opinion in the comments sections below. And feel free to refer Microsoft’s site to gather more information.

If you want to improve your skill in ASP.Net and excel yourself in ASP.NET training program; our institute, CRB Tech Solutions would be of great help and for you. Come and join us with our well structured program for ASP .Net.

Stay connected to CRB Tech for more technical optimization and other updates and information.

Don't be shellfish...Buffer this pageEmail this to someoneDigg thisShare on FacebookShare on Google+Share on LinkedInPrint this pageShare on RedditPin on PinterestShare on StumbleUponTweet about this on TwitterShare on Tumblr

QuickStart TOR in .NET Core

Introduction

To mention there is no TOR library that supports .NET Core. Since a programmer needed, he put them together. It couldn’t do much magic, but it will perform the job 99% of the times, let us explain how:

  • You want to make anonymous requests.
  • You want to make requests to onion APIs.

They are the most common use cases those made someone to use TOR inside their application. This blogtopic aims to serve these basic needs and nothing more. In other words: if you simply want to “change your IP”, this article is for you.

Understand the problem

Some people tries to launch the Tor process in their local machine, giving the process a port number for the SOCKS port, and then configure their browser to point to the Tor process. This won’t work.

Tor is a SOCKS proxy that means it is able to connect to IP addresses and ports, but it fails to understand HTTP requests.

Configure TOR

  1. Download TOR Expert Bundle.
  2. You can find a sample TOR config file, let it be torrc.
  3. Put torrc in the proper default location (depending on your OS), or just run the tor process later by feeding it with the right configuration.
  4. Edit the sample config file:
    • Optionally change and edit the SocksPort, if you don’t change, it will go to 9050 port by default.
    • Change the default ControlPort 9051, optionally edit.
    • Change and modify the password hash:
      • To run a tes, for the ControlPortPassword = “ILoveBitcoin21″ the hash must be: HashedControlPassword 16:0978DBAF70EEB5C46063F3F6FD8CBC7A86DF70D2206916C1E2AE29EAF6

      • You must use different and more complicated one. Keep in mind that you can start tor like this: tor –hash-password password where password is the password you’ve chosen. It will give you the hashed password.
  5. Start tor, it will listen to the ports you set in the config file.

SocksPort vs ControlPort

The control port controls the Tor, mainly through other software like Arm. The Socks port is the port running as a SOCKS5 proxy. This is the one you wanted to use. Remember that Tor is not an HTTP proxy, so your script will need to be configured to use a SOCKS5 proxy.

Create & Test

You can skip this section and get the NuGet package and use it, but you might save time if you make sure everything runs fine, by running these tests. Now get .NET Core, if you haven’t already done so and fire up a terminal:

  1. git clone https://github.com/nopara73/DotNetTor
  2. cd DotNetTor/
  3. dotnet restore
  4. cd src/DotNetTor.Tests/
  5. dotnet test

How to use it

Consider the following simple console app, where

  1. You write out your real IP
  2. Your TOR IP
  3. Change your TOR circuit
  4. Finally write out the changed TOR IP.

var requestUri = “http://icanhazip.com/”; // Gives back your IP

// 1. Get your (real) IP, just like you normally do

using (var httpClient = new HttpClient())

{

var content = httpClient.GetAsync(requestUri).Result.Content.ReadAsStringAsync().Result;

Console.WriteLine($“Your IP: \t\t{content}”);

}

// 2. Get your IP through TOR

using (var socksPortClient = new SocksPort.Client())

{

var handler = socksPortClient.GetHandlerFromDomain(“icanhazip.com”);

using (var httpClient = new HttpClient(handler))

{

var content = httpClient.GetAsync(requestUri).Result.Content.ReadAsStringAsync().Result;

Console.WriteLine($“Your TOR IP: \t\t{ content}”);

}

// 3. Change TOR IP

var controlPortClient = new ControlPort.Client(password: “ILoveBitcoin21″);

controlPortClient.ChangeCircuit();

// 4. Get changed TOR IP

handler = socksPortClient.GetHandlerFromRequestUri(requestUri);

using (var httpClient = new HttpClient(handler))

{

var content = httpClient.GetAsync(requestUri).Result.Content.ReadAsStringAsync().Result;

Console.WriteLine($“Your other TOR IP: \t{content}”);

}

}

Summary

While this article did not cover a full-featured TOR library, but a minimal one, without any dependency, you must acknowledge that this article covered the most popular needs in a platform (.NET Core) where nothing else is available at the time of writing.

We conclude the discussion here. Let us know your opinion in the comments sections below. And feel free to refer Microsoft’s site to gather more information.

If you want to improve your skill in ASP.Net and excel yourself in ASP.NET training program; our institute, CRB Tech Solutions would be of great help and for you. Come and join us with our well planned and structured program for .Net.

Stay connected to CRB Tech for more technical optimization and other updates and information.

Don't be shellfish...Buffer this pageEmail this to someoneDigg thisShare on FacebookShare on Google+Share on LinkedInPrint this pageShare on RedditPin on PinterestShare on StumbleUponTweet about this on TwitterShare on Tumblr

Introduction to Exception Handling

This blog topic will give an overview on how to handle exceptions in your C# programs. The main objectives of this discussion are:

  • Know about an exception
  • Start a routine with a try/catch block
  • Release resources in a final block

Exceptions

Exceptions are unpredicted errors that happen in your programs. It is advisable to detect and handle program errors in your programming. For instance, assessing user input, checking null objects, and to verify the values returned from methods are all examples of good error handling that you must do all the time.

But, there are times when you don’t know if an error could occur. This is generally unlikely, but could still happen and you need to deal with them when they do occur. This is when exception handling comes in picture.

The System.Exception class gives you various methods and to obtain information on what went wrong. For instance, theMessage property gives summary information about what the error was, the Stacktrace property gives information from the stack for where the problem occurred, and the ToString() method is to reveal a verbose depiction of all the exceptions.

To identify the exceptions that you might need to handle depends on the routine you’re coding. E.g., if the routine opened a file with theSystem.IO.File.OpenRead() method, it could give any of the following exceptions:

  • SecurityException
  • ArgumentException
  • ArgumentNullException
  • PathTooLongException
  • DirectoryNotFoundException
  • UnauthorizedAccessException
  • FileNotFoundException
  • NotSupportedException

It’s easy to find out what exceptions a method can raise by looking in the .NET Frameworks SDK Documentation.

Try/catch Blocks

When exceptions are thrown, you must be able to handle them. This is done by using a try/catch block. Code that could throw an exception is put in the try block and exception handling code goes in the catch block. Listing 1 shows how to implement a try/catchblock. Since an OpenRead() method could throw one of several exceptions, it is placed in the try block. If an exception is thrown, it will be found in the catch block. The code in Listing 1 will print message and inform that if an exception is raised.

N.B. The programs in this lesson cause exceptions on purpose. The exceptions that are generated intentionally to exemplify the theoretical part.

Listing 1. Using try/catch Blocks: tryCatchDemo.cs

using System;

using System.IO;

class tryCatchDemo

{

    static void Main(string[] args)

    {

        try

        {

            File.OpenRead(“NonExistentFile”);

        }

        catch(Exception ex)

        {

            Console.WriteLine(ex.ToString());

        }

    }

}

Although the code in Listing 1 has a single catch block, all exceptions will be seen their owing to the type is of the base exception type “Exception”. In exception handling, more specific exceptions can be seen before their more general parent exceptions. E.g., the following code shows how to place multiple catch blocks:

catch(FileNotFoundException fnfex)

        {

            Console.WriteLine(fnfex.ToString());

        }

        catch(Exception ex)

        {

            Console.WriteLine(ex.ToString());

        }

If the file doesn’t exist, a FileNotFoundException exception will be shown and seen by the first catch block. However, if aPathTooLongException exception is raised, the second catch part would catch the exception.

Exceptions that can’t be handled will bubble up the stack until a calling routine in the call chain handles them. If you forget to include try/catch blocks in a part of your code and there aren’t any try/catch blocks earlier in the call chain, your program will stop with a message describing the exception. To mention that would be cryptic and uncomfortable for your users.

Finally Blocks

An exception leaves your program in an inconsistent state by not releasing the resources or by performing some other types of cleanup. A catch block is a nice place to figure out what may have gone wrong and try to recover, however it can’t cover all scenarios. So at times you need to perform clean up actions whether or not your program succeeds. At this situation it’s good for using a final block.

Listing 2 illustrates the usefulness of a finally block. Remember a file stream must be closed when you finished it. In this case, the file stream is the resource that should be cleaned up. In Listing 2, outStream is opened successfully, which means the program has a handle to an open file resource. When trying to open the inStream, a FileNotFoundException exception is raised, and the control goes immediately to the catch block.

It’s possible to close the outStream in the catch block, but if the algorithm is done successfully without an exception, how to deal with it? On success, the file will never be closed. We have included a finally block in Listing 2, which will always be carried out. Irrespective of whether the algorithm in the try block raises an exception or not, the code in the finally block will be executed before control leaves the method.

Listing 2. Implement a finally Block: FinallyDemo.cs

using System;

using System.IO;

class FinallyDemo

{

    static void Main(string[] args)

    {

        FileStream outStream = null;

        FileStream inStream = null;

        try

        {

            outStream = File.OpenWrite(“DestinationFile.txt”);

            inStream = File.OpenRead(“BogusInputFile.txt”);

        }

        catch(Exception ex)

        {

            Console.WriteLine(ex.ToString());

        }

        finally

        {

            if (outStream != null)

            {

                outStream.Close();

                Console.WriteLine(“outStream closed.”);

            }

            if (inStream != null)

            {

                inStream.Close();

                Console.WriteLine(“inStream closed.”);

            }

        }

    }

}

A finally block is not needed and you might ask what happens if you just put code after the catch block. Under normal circumstances, if the exception is found out, all code following the catch will be executed. However, try/catch/finally is for exceptional circumstances and it is always to be prepared for the worst.

Summary

The present blog topic was an introduction to handling exceptions. So now you must know what an exception is. You can implement algorithms within try/catch blocks that manage exceptions. Moreover you know how to clean up resources by using a finally block whose code is always effected before leaving a method.

We conclude the discussion here. Let us know your opinion in the comments sections below. And feel free to refer Microsoft’s site to gather more information.

If you want to improve your skill in ASP.Net and excel yourself in ASP.NET training program; our institute, CRB Tech Solutions would be of great help and for you. Come and join us with our scientifically structured program for .Net.

Stay connected to CRB Tech for more technical optimization and other updates and information.

Don't be shellfish...Buffer this pageEmail this to someoneDigg thisShare on FacebookShare on Google+Share on LinkedInPrint this pageShare on RedditPin on PinterestShare on StumbleUponTweet about this on TwitterShare on Tumblr

Microsoft Announces The Visual Studio For MAC

So Microsoft has finally made the announcement of VS 2017 and a release candidate. The organisation, Microsoft held the keynote for its Connect() developer conference where it announced the next version of its integrated development environment (IDE), VS 2017. The business is also providing a release candidate, which you can get from VisualStudio.com.

The IDE has been in way in the name of Visual Studio “15” since the early part of this year, and it gives a new installer. To mention that in fact, for the first time in history, the smallest installation comes at under 750MB. But obviously, packing it out with all of the attributes that it provides will make it much bigger; can be assumed to be over 60GB.

The company’s latest IDE has a heavy focus on mobile cross-platform development, coming with an iOS Simulator, an attribute which used to be an exclusive manner in designing on a Mac.

VS 2017 also involves improvements to IntelliSense, which is one of the most popular and helpful features of VS. New improvements include smart preselecting, filtering and XAML support.

Smart preselecting will make you determine the “target type” that is required at a position in code and will preselect items in the IntelliSense completion list matching that type. This will increase your typing flow and removes the burden of having to figure out the expected type at a given location. IntelliSense filtering will help you to filter the completion list by category; for instance, you can filter out the extension methods or see only events. This attribute boosts productivity when you’re working in a large code base where there are many items in the completion list or when dealing with unfamiliar code.

To be frank enough, this release will deliver a whole new experience for XAML IntelliSense to help the programmers bind quickly and correctly and view only relevant information. This smarter completion experience includes completion when binding events, paths and functions with x:Bind; camelCase matching support and namespace prefix auto completion.

There are also new Code Analysis attributes. Code Analysis originally launched with VS 2015, as a mode of knowing issues with your code while you’re typing it, rather than at the run-time. The new version of Visual Studio “takes live analysis and code fixes a step further by increasing the set of refactoring and code fixes available, and by introducing code style analyzers that identify style issues in code as soon as they’re typed.”

New refactoring options include:

  • Move Type To Matching File
  • Sync file and type the name
  • Translate property to method
  • Use object initialize
  • Convert null-check + throw to use?? + throw
  • Convert string.Format to interpolated string
  • Make method synchronous
  • Add the missing case
  • Add braces

This also has a new feature or attribute to debug named, called “Run To Click“. This attribute will enable developers to run a program until it reaches the line of code that breaks it. This does away with the need of creating break points.

But of course, this is a full new version of Visual Studio, and it would be impossible for us to outline its countless new attributes.

We conclude the discussion here.

Let us know your opinion in the comments sections below. And feel free to refer Microsoft’s site to gather more information.

If you want to improve your skill in ASP.Net and excel yourself in ASP.NET training program; our institute, CRB Tech Solutions would be of great help and for you. Come join us with our well structured program for .Net.

Stay connected to CRB Tech for more technical optimization and other updates and information.

Don't be shellfish...Buffer this pageEmail this to someoneDigg thisShare on FacebookShare on Google+Share on LinkedInPrint this pageShare on RedditPin on PinterestShare on StumbleUponTweet about this on TwitterShare on Tumblr

Most Popular Programming Languages In Trend

Today CRB Tech write about the most popular or trending programming languages worldwide. The easiest way to do is seek public opinion or using the Tiobe index listings.

Even if you search Google then you would get some pretty good idea. In this blog discussion we compared five programming languages to show how they fare against each other.

C++

The C++ language and also the C language continue to be popular worldwide. India ranks in the highest trending area followed by France and South Africa.

Though C++ is very around the world, yet it is not popular everywhere.

Java

This language rules the Tiobe charts; but same as C++ there are areas where Java does not flourish. Like C++, India is near the top and there is a new entry i.e. Bangladesh which actually has the highest trending for Java. The U.S. fails to appear in the top five.

C#

A very popular language again in India and is trending as one of the strongest language. To mention, China comes in at number two position for C#

It is also popular worldwide; but in areas of Africa they don’t. As with the previous two languages, the US is not in the top five.

Visual Basic

Visual Basic is a language that continues to try and hold its own. This happens to be the only language among the five we are discussing and does not have India listed in the top five.

Though Visual Basic is yet popular worldwide, including trends in areas of Africa where C# does not register, its most popular area is Central America.

Swift

Swift is now being used in place of Objective-C by a lot of iOS developers. Hence it has gained.

Swift is popular in many of the countries as the other languages. Again US is not among the top five. The Philippines, followed by Singapore and Indonesia, are the top three, with India coming in 4th.

Trending

Trending is the most interesting when you compare the five languages together. C/C++ continues to trend on a steady path, even at a higher level relative to most languages. Java fared the worst because it has gone from being higher than C/C++ to being well below. In recent months, Swift is trending higher than where Java is now. If both continue then Swift will likely overtake Java. Though C# has also trended relatively lower, but at lower numbers. The most dropped language is Visual Basic and it has fallen below C# and Swift to take the bottom position among the five languages.

To mention the data is based on Google Trends, which is relative to what people to how people are searching. Also you must note that like the Tiobe index, this is also a flawed way to look at language popularity. But we must admit that the data is interesting. If you have any say on the above, comment us below.

Most popular languages

Finally we mention what you can see is the most popular trending language in each country. C/C++ is predominant across the world, with Java spread in several countries as well. Finally, VB shows up only in few areas. That say Visual Basic is on the decline.

We conclude the discussion here.

Let us know your opinion in the comments sections below.

If you want to improve your skill in ASP.Net and excel yourself in ASP.NET training program; our institute, CRB Tech Solutions would be of great help and for you. Come join us with our well structured program for .Net.

Stay connected to CRB Tech for more technical optimization and other updates and information.

Don't be shellfish...Buffer this pageEmail this to someoneDigg thisShare on FacebookShare on Google+Share on LinkedInPrint this pageShare on RedditPin on PinterestShare on StumbleUponTweet about this on TwitterShare on Tumblr

Top Reasons to Look at .NET Core

Part II

Today we shall continue the same discussion and conclude what we started a few days back. If you haven’t taken a look at .NET Core yet, in this blog topic we have been discussing the top reasons that might allure you. In this blog post we included next 5 reasons that need to be mentioned:

6. Migrating to .NET Core

If you took a look at .NET Core in its beginning days, you must have found yourself noticing there were some obstacles to jump to migrate some .NET Framework code to .NET Core. But since then things have been changing and developers are in a constant process of taking to a direction which would bring the two frameworks closer together, and removes many of the challenges you might face. This effort has led to which you know as the .NET Standard Library, that supports a few key scenarios.

7. .NET Core Runtime (CoreCLR)

The CoreCLR represents the complete .NET Core runtime implementation and has several components. The .NET GC and Native Interop is one, but if you can also pick with the RyuJIT. It took years in it’s making, the RyuJIT was included in .NET 4.6 for x64 in 2015. It’s not only faster at generating codes, but also produce code that is either good or better than the x64 JIT.

8. Kestrel HTTP Server

Kestrel is a built-in HTTP server implementation which is shipped with ASP.NET Core. This comes as an additional option while deploying ASP.NET applications, hence allowing you to remove IIS from your stack. If you begin a new ASP.NET Core application from the templates given by Visual Studio, with latest .NET Core tools installed; you will notice the following code in your program.cs…

public static void Main(string[] args)

{

var host = new WebHostBuilder()

.UseKestrel()

.UseContentRoot(Directory.GetCurrentDirectory())

.UseIISIntegration()

.UseStartup<Startup>()

.Build();

host.Run();

}

If you miss the line UseKestrel(), add this as above and you are ready to go.

9. Microservices

If you want to build a system organised into Microservices, and equipped with that we’ve covered in this blog post, .NET Core could come up as a framework for you. Since the release of .NET Core, you’ll also find that there is an increase in the Azure support for the framework. Hence you can give this try.

10. Command Line Development

Do you have a special liking in development using command line interface tools, or working on a platform from which you can’t run the Visual Studio IDE? If yes, then .NET Core had CLI tools in mind during its development. Follow the given steps to get you started…

Install .NET Core.

Next open a command window, navigate to your choice of directory and type….

Dotnet new

Take a look in the directory, and you’ll find a very simple console application which is ready for development.

Version 1.0.1 of the .NET Core was released on September 13th 2016. The framework has been in close watch by many; some chose to ignore it and waited for it to become more mature, while others took a chance and included it in their current projects.

We conclude now, please refer our previous blogs to read the first part of it. Hope you liked the discussion. Please let us know your opinion in the comment section below.

If you want to enhance your skill in ASP.Net and make improvements in your coding skills, then the ASP.NET training program by our institute, CRB Tech Solutions would be of great help and for you. Come join us with our well structured program for .Net.

Stay connected to CRB Tech for more technical optimization and other updates and information.

Don't be shellfish...Buffer this pageEmail this to someoneDigg thisShare on FacebookShare on Google+Share on LinkedInPrint this pageShare on RedditPin on PinterestShare on StumbleUponTweet about this on TwitterShare on Tumblr

Top Reasons to Look at .NET Core

Part I

Today in this blog topic we discuss about the reasons for which we should look into .NET core in the present time. Version 1.0.1 of the .NET Core got released on September 13th 2016. After a close watch, the framework some chose to put it aside, but others actively included it in their projects. If you haven’t taken a look at .NET Core yet, here are the top reasons that might tempt you. In this blog topic we included 5 reasons and we shall continue with the rest in the second part of the article.

1. Modularity

.NET Core has a strong focus on modularity and that is a strong reason why you should give it a chance. To mention products built with .NET Core are comparatively more lean than their full framework counterparts. Another fact is that .NET Core’s code base is separated into smaller assemblies, and each each focus only on their intended usage. It is easy to include only the pieces of the framework that is required for your product. Hence you can customise your usage of .NET core.

To put in simple words, it is much easier to use pieces of the framework you might require to enhance the functionality of your current project, even if that product is running on the full .NET framework. E.g. ASP.NET Core, you migh find a small assembly in the Microsoft.AspNetCore namespace that can prove significant for your ASP.NET 4.6 application.

2. Cross Platform

Do you want to build an ASP.NET Core application, but would like to run it Linux? Well, .NET Core would come to your rescue even if you are developing on Windows using Visual Studio. .Net Core documentation includes versions of Ubuntu, CentOS, OS X, and more.

3. .NET Core Doesn’t Support WPF or WinForms. So What Next?

The sole answer to this is Universal Windows Platform (UWP) and it comes with a few bonuses. The first of all is that you can run UWP applications on any device in the Windows family. When UWP first initiated, it allowed you to develop applications for Windows 10 Desktop and Mobile; since then, Xbox, Windows 1, and Holographic have been added to that list. It is also worth mentioning that UWP apps, when set to release, are set by default to be optimised and compiled allowing increased performance.

4. ASP.NET Core

ASP.NET Core represents a very easy solution and is designed to run efficiently in cloud-based environments, while maintaining the flexibility. The configuration system for ASP.NET Core enables a variety of options, like taking in data from XML, JSON or INI files; in-memory sources; environment variables and more. Even you will find that unified Middleware Components have replaced the HTTP Handlers and Modules and making it easily configurable.

5. ASP.NET Core MVC

This is not to be understood as a replacement for full ASP.NET MVC but it is newly constructed from the group and is optimized for use with ASP.NET Core. You’ll find some familiar features like Razor; but there are new attributes too that will make your life easier as a developer. For instance, you no longer have to derive your controllers from different classes for Views and WebAPI. You can obtain both of the controllers from the abstract class Controller.

For E.g.

[Route(“api/[controller]“)]

public class DataController : Controller

{

public SomeData GetData()

{

return new SomeData() { Data = “Hello!” };

}

}

We conclude this part here to continue with the next in our upcoming blog.

If you want to improve your skill in ASP.Net and excel yourself in ASP.NET training program; our institute, CRB Tech Solutions would be of great help and for you. Come join us with our well structured program for .Net.

Stay connected to CRB Tech for more technical optimization and other updates and information.

Don't be shellfish...Buffer this pageEmail this to someoneDigg thisShare on FacebookShare on Google+Share on LinkedInPrint this pageShare on RedditPin on PinterestShare on StumbleUponTweet about this on TwitterShare on Tumblr

CRB Tech Solutions ASP. Net Training Program – Where Success Follows Excellence!

CRB Tech Solutions Pune offers real time and focused .Net training program. Our training program is well structured and follows a curriculum that would upskill you with corporate oriented requirements.

.Net course comprises of basic to innovative level and our dot net course is designed specially for you to overcome your shortfall and build your confidence. Our ASP.Net training will help you materialize your dreams and help you ahead for great careers wither in MNCs and MLCs in Pune. We have experienced mentors with years of industrial expertise and knowledge with hands-on real-time .Net tasks.

We have designed our .Net training program syllabus content and curriculum while focusing on learners’ need and corporate requirements. In our .Net program, you will learn MVC structure, asp .net, vb .net, ADO.net, Silverlight, .Net real-time venture and .Net positioning coaching.

Our training institute is built with lab features and excellent infrastructure. Our CRB Tech Solutions have guided and supported more than 500+ learners and offered 100% job placement. Our training program fee is well structured and worth it’s content and syllabus. You can avail our ASP.Net training program in Pune with daytime sessions, end of the week courses, night group sessions and speed up courses.

Why consider CRB Tech Solutions?

Well, that question comes when in the market there are many other training institutes. CRB Tech Solutions was started to motivate the students in not just building careers but nurturing each and every student of CRB with all the soft skills essential in the corporate sector. CRB Tech was build to equip students and make them technically skilled and excellence – enriched to make them significantly enter the era of competition and stand out unique in the crowd. So CRB Tech Solutions is the name that would add wings to your dreams.

How CRB Tech Solutions Is Unique ?

  • 100 % placement guarantee on paper
  • We offer LOI (conditional offer letter) from our clients
  • Unlimited placement calls for both freshers and alumni
  • One of the best in walk-in drives.
  • Lifetime supports in placement
  • Mentoring by extremely talented corporate expertise faculties.
  • Training in German language and hence enhance your abroad prospects.
  • Personality development training with which you will benefit by developing soft skills which would help you in cracking interviews which are very important in standing up among your contemporaries in the race of competitions.
  • Around 95% practically oriented training sessions.
  • Advanced Corporate Infrastructure

A Training Program designed for you:

  • Detailed and expertise training is additionally offered alongside customized technical training to guarantee the general development of the students.
  • Foremost curriculum: The modules of .NET training program are upgraded and redesigned on a periodical basis by our industry experts, to remain upgraded with the ongoing changes and recent improvements in the particular fields.
  • Guidance from professionals of the field
  • Campus drives on a regular basis: We direct customary grounds enlistment programs where a large number of our placement clients visit our organization, on a regular basis.
  • Aptitude training and Mock interviews: Aptitude preparing is a part of the syllabus and it enables you to successfully overcome the hardest of the aptitude tests, which you would face in the interviews. Mock interviews are taken to make the students acquaint with the real processes such that they can face real interviews with more confidence.

If you want to improve your skill set in ASP.Net and optimize yourself in .NET training, then our CRB Tech Solutions would be of great support for you. Join us with our scientifically designed program of ASP.Net course.

Stay connected to CRB Tech for more technical optimization and other resources.

Don't be shellfish...Buffer this pageEmail this to someoneDigg thisShare on FacebookShare on Google+Share on LinkedInPrint this pageShare on RedditPin on PinterestShare on StumbleUponTweet about this on TwitterShare on Tumblr