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

Five Methods To Deal with Errors In ASP .Net

Any real-world web application needs a program to handle errors. In ASP.NET Web Forms there are certain events and custom error pages to deal with them. In ASP.NET MVC there is [HandleError] feature, exception filters and custom error pages to deal. In ASP.NET Core there are a set of methods and, exception filters for you. In this blog topic; I will discuss 5 methods for error handling.

These methods are from the Configure() method of the startup class. They are available as extension methods of the IApplicationBuilder object received by the Configure() method. These extension method generally call the Microsoft.AspNetCore.Diagnostics middleware to get the job done.

To view these methods in action, create a new ASP.NET Core application based on Web Application project template. Then open the HomeController and deliberately put an exception from the Index() action as shown below:

public IActionResult Index()

{

throw new Exception(“This is some exception!!!”);

return View();

}

The code above is quite simple and needs no explanation.

Let’s discuss the 5 methods one by one:

1. UseDeveloperExceptionPage() – Looks after exception details during development

The  UseDeveloperExceptionPage() method is very easy during development stage. To use this method open the Startup.cs file, locate the Configure() method and change it to appear like this:

public void Configure(IApplicationBuilder app,

IHostingEnvironment env,

ILoggerFactory loggerFactory)

{

app.UseDeveloperExceptionPage();

….

….

}

As mentioned earlier this method should be used only during development stage as you don’t want to show the details to the end user. That’s why it is a good idea to call UseDeveloperExceptionPage() method like this:

if (env.IsDevelopment())

{

app.UseDeveloperExceptionPage();

}

else

{

//something else here

}

Now the UseDeveloperExceptionPage() is housed inside an if block. If the hosting environment is development IsDevelopment() method returns true and only then UseDeveloperExceptionPage() gets called. Otherwise some other error handling code take place.

2. UseExceptionHandler() – Gives the control to custom error handler

This method uses a specified error handler to deal with the exception. The error handler logs the exceptions and show a friendly message to the end user. To use this method first of all open the HomeController and locate the Error() action. This action is added as a part of the Web Application project template and also has the corresponding view – Error.cshtml – inside the Views folder.

Change the Error() action as shown below:

public IActionResult Error()

{

var exception = HttpContext.Features

.Get<IExceptionHandlerFeature>();

ViewData["statusCode"] = HttpContext.

Response.StatusCode;

ViewData["message"] = exception.Error.Message;

ViewData["stackTrace"] = exception.

Error.StackTrace;

return View();

}

The Error() action extracts exception details and sends them to the Error view through ViewData. To grab the exception that was thrown the code uses Features.Get() method on HttpContext. The HTTP status code is obtained using the Response.StatusCode property. The status code, exception message and exception stack trace are stored in ViewData dictionary for the use on the Error view.

Now open Error view and change it as shown below:

<h1>@ViewData["message"]</h1>

<h2>Status Code : @ViewData["statusCode"]</h2>

<div>@ViewData["stackTrace"]</div>

The above code is simple enough for any explanation.

Finally, visit the Configure() method and change it to call UseExceptionHandler().

public void Configure(IApplicationBuilder app,

IHostingEnvironment env,

ILoggerFactory loggerFactory)

{

app.UseExceptionHandler(“/Home/Error”);

….

….

}

As you can see, this time we call UseExceptionHandler() method and specify /Home/Error action as a string parameter. So whenever there is any unhandled exception control will be taken to Error() action.

3. UseStatusCodePages() – This shows error pages for HTTP status codes

The two methods discussed above deal with the unhandled exceptions that arise from your code. But, that’s not the only source of errors. At times errors are generated due to internal server errors, non existent pages, web server authorization issues and so on. These errors are reflected by the HTTP status codes such as 500, 404 and 401.

To deal with these errors you can use UseStatusCodePages() method. This method can be used as follows:

public void Configure(IApplicationBuilder app,

IHostingEnvironment env,

ILoggerFactory loggerFactory)

{

….

….

app.UseStatusCodePages();

….

….

}

Although the default version permits us to see the HTTP status code, but it is a plain text. So you can format it as an HTML fragment. You can do that as shown below:

app.UseStatusCodePages(“text/html”,

“<h1>Status code page</h1> <h2>Status Code: {0}</h2>”);

The UseStatusCodePages() method now uses HTML markup to render the status code. Notice the use of {0} to output the status code at a specific place within the markup.

4. UseStatusCodePagesWithRedirects() – Perform URL redirection upon error

Many times you might want to handover the control to some action whenever there is some HTTP error (such as 404). It is then, UseStatusCodePagesWithRedirects() comes handy. It sends HTTP status code 302 (Found) to the browser and performs the redirection using the action specified. Take the following code:

public void Configure(IApplicationBuilder app,

IHostingEnvironment env,

ILoggerFactory loggerFactory)

{

….

….

app.UseStatusCodePagesWithRedirects(“/CustomErrorPages/{0}”);

….

….

}

The code takes UseStatusCodePagesWithRedirects() method and passes /CustomErrorPages/{0} as a string parameter. The {0} placeholder is used only if you wish to pass the status code (such as 404) to the handler. Then sum up another action to the HomeController as shown below:

[Route("/CustomErrorPages/{code}")]

public IActionResult StatusCodeErrors(string code)

{

ViewData["statusCode"] = code;

return View();

}

The [Route] attribute maps /CustomErrorPages to StatusCodeErrors(). The StatusCodeErrors() action accepts code parameter that is the HTTP status code. Make sure to add the StatusCodeErrors view and output the ViewData statusCode value on it.

Note that this response is given by Error view. The {0} placeholder passed 404 to the Error() action. You can conditionally give some different view based on the status code if you so wish. You can also device a mechanism like this:

app.UseStatusCodePagesWithRedirects(“/CustomErrorPages/{0}.html”);

You can now see the code redirects to a separate HTML pages stored as 404.html, 500.html and so on. This way you can display different custom error pages for different status codes.

5. UseStatusCodePagesWithReExecute() – Re-execute the request pipeline with alternate action

The UseStatusCodePagesWithReExecute() is similar to UseStatusCodePagesWithRedirects() in that both executes some alternate action if there is any HTTP error. But, UseStatusCodePagesWithRedirects() does redirection to the alternate action whereas UseStatusCodePagesWithReExecute() re-executes the entire request pipeline and executes the alternate action. The UseStatusCodePagesWithRedirects() sends status code of 302 to the browser and browser address bar reflects the new URL upon redirection. In case of UseStatusCodePagesWithReExecute() the original status code is sent to the browser and the address bar will continue to show the original URL.

You can use the UseStatusCodePagesWithReExecute() method as follows :

public void Configure(IApplicationBuilder app,

IHostingEnvironment env,

ILoggerFactory loggerFactory)

{

….

….

app.UseStatusCodePagesWithReExecute(“/CustomErrorPages/{0}”);

….

….

}

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 Use Your GPU in .NET

Introduction

This blog topic is going to tell you that a modern Core I7 is most probably the slowest piece of programmable hardware that your PC has. Modern Quad Core CPUs have almost 6 Gflops whereas modern GPUs have about 6Tflops of computational power.

This can dynamically execute simple programs written in a C dialect on your GPU, CPU or both. They are compiled and executed at the run time.

This also shows that GPU programming is not that hard. You will need a little bit of basic programming skills.

Why I need this?

Your PC is a powerful machine. By using only a CPU to execute tasks, you might waste about 90% of its potential.

Basically all data fits into some other numeric arrays.

Instances for a powerful speed up are:

  • Work on images or movies

  • When parallel works are done

  • Save time and energy by using GPU and CPU parallely

  • Use your GPU for a task while have your CPU free for something else

Keep in mind that this topic speaks about OpenCL. Unlike Cuda, it runs on any GPU (Amd, Nvidia, Intel) and also on the CPU. So any program you code can be used on any device. (Even phones)

Tested on NVIDA, AMD, and Intel.

These are the results for some prime calculations:

You can really speed up your program. Native C# is 5 times slower than the best speed you can get on your PC. The speedup factor can approach 500 times in pure multiply and add workloads. It is easy to write a program for your GPU and CPU with this class.

OpenCL code always runs faster than C# on arrays.

How To Use It?

OpenCL programming is very time consuming. This helper project will lessen your programming such that you can focus on the core problem. It is written in C# but could be adapted to any .NET language and also C++.

Suppose you want to know all the prime numbers from 2 to 10^8. Here is a simple implementation in C#

tatic void IsPrimeNet(int[] message)

{

Parallel.ForEach(message, (number, state, index) =>

{

int upperlimit = (int)Math.Sqrt(number);

for(int i=2;i<=upperlimit;i++)

{

if (message[index]%i == 0) //no lock required. every index is independent

{

message[index] = 0;

break;

}

}

});

}

Now take this code and translate to OpenCL-C.
The following
Kernel is declared as a string in a file, inline or in a resource file.

kernel void GetIfPrime(global int* message)

{

int index = get_global_id(0);

int upperl=(int)sqrt((float)message[index]);

for(int i=2;i<=upperl;i++)

{

if(message[index]%i==0)

{

//printf(“” %d / %d\n””,index,i );

message[index]=0;

return;

}

}

//printf(“” % d””,index);

}

OpenCL does cover your kernel in a loop. For simple 1D Arrays, you can get the index by calling get_global_id(0); The upper index is passed when you call the the kernel.

Instead of int[], you can write int* and so on.

You have to pass logics in the same order in which you declared them. You can also call printf inside your kernel to debug later. You can define many methods as you want inside the kernel. You can pick the entry point afterwards by stating Invoke(“Name Here”).

OpenCL C is the same as C but you can’t use pointers and you also have some special data types.

Here is how you can use this project:

Add the Nuget Package Cloo

Add reference to OpenCLlib.dll.
Download OpenCLLib.zip.

Add using OpenCL

static void Main(string[] args)

{

int[] Primes = Enumerable.Range(2, 1000000).ToArray();

EasyCL cl = new EasyCL();

set the accelerator after loading the kernel

cl.Accelerator = Accelerator.Gpu; //You can also

cl.LoadKernel(IsPrime); //Load kernel string here, (Compiles in the background)

cl.Invoke(“GetIfPrime”, Primes.Length, Primes); //Call Function By Name With Parameters

//Primes now contains all Prime Numbers

}

static string IsPrime

{

get

{

return @”

kernel void GetIfPrime(global int* message)

{

int index = get_global_id(0);

int upperl=(int)sqrt((float)message[index]);

for(int i=2;i<=upperl;i++)

{

if(message[index]%i==0)

{

//printf(“” %d / %d\n””,index,i );

message[index]=0;

return;

}

}

//printf(“” % d””,index);

}”;

}

}

With this, you can compile and call upon OpenCL kernels.

If you want to use every bit of computational power of your PC, you can use the class MultiCL. This class splits your work into N parts. Every part is pushed onto the GPU or CPU whenever required. This way, you attain the maximum performance from your PC.

static void Main(string[] args)

{

int[] Primes = Enumerable.Range(2, 1000000).ToArray();

int N = 200;

MultiCL cl = new MultiCL();

cl.ProgressChangedEvent += Cl_ProgressChangedEvent1;

cl.SetKernel(IsPrime, “GetIfPrime”);

cl.SetParameter(Primes);

cl.Invoke(0, Primes.Length, N);

}

private static void Cl_ProgressChangedEvent1(object sender, double e)

{

Console.WriteLine(e.ToString(“0.00%”));

}

Working

This work refers to the Nuget package Cloo. With Cloo, orders to OpenCL are possible from .NET.

It hides the installation details you need to know to use OpenCL and Cloo. To get more information about your kernel or device, use the class OpenCL.

There are 3 classes in this project:

  • EasyCL
  • MultiCL
  • OpenCL

Every call to Invoke calls the corresponding methods in the OpenCL API:

void Setargument(ComputeKernel kernel, int index, object arg)

{

if (arg == null) throw new ArgumentException(“Argument “ + index + ” is null”);

Type argtype = arg.GetType();

if (argtype.IsArray)

{

Type elementtype = argtype.GetElementType();

//ComputeBuffer<int> messageBuffer = new ComputeBuffer<int>(context,

//ComputeMemoryFlags.ReadOnly | ComputeMemoryFlags.UseHostPointer, (int[])arg);

ComputeMemory messageBuffer = (ComputeMemory)Activator.CreateInstance

(typeof(ComputeBuffer<int>), new object[]

{

context,

ComputeMemoryFlags.ReadWrite | ComputeMemoryFlags.UseHostPointer,

arg

});

kernel.SetMemoryArgument(index, messageBuffer); // set the array

}

else

{

//kernel.SetValueArgument(index, (int)arg); // set the array size

typeof(ComputeKernel).GetMethod(“SetValueArgument”).MakeGenericMethod(argtype).Invoke

(kernel, new object[] { index, arg });

}

}

Every time you change the kernel, the program gets recompiled:
For a faster prototype phase, this class tells you why you cannot compile your kernel.

public void LoadKernel(string Kernel)

{

this.kernel = Kernel;

program = new ComputeProgram(context, Kernel);

try

{

program.Build(null, null, null, IntPtr.Zero); //compile

}

catch (BuildProgramFailureComputeException)

{

string message = program.GetBuildLog(platform.Devices[0]);

throw new ArgumentException(message);

}

}

It is very important to know that if your GPU driver crashes or kernels use 100% of your GPU for more than 3 seconds (on pre Win10 machines), the kernel will get aborted. You should dispose the EasyCL object after that.

//If windows Vista,7,8,8.1 you better be ready to catch:

EasyCL cl = new EasyCL();

cl.InvokeAborted += (sender,e)=> Cl_InvokeAborted(cl,e);

private void Cl_InvokeAborted(EasyCL sender, string e)

{

//your logic here

}

What is missed?

You cannot choose if you want to use the host pointer or read write access to int[] passed to the kernel. This seems to be a legacy function.

This class is written for PCs. With VS/Xamarin, it could be easy adapted for phones.

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 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

What is model binding in ASP.NET ?

Part I

Introduction

Model binding maps data from HTTP requests to enact method parameters. The parameters might be simple types like strings, integers or floats or some complex types. This is a great attribute of MVC because to map incoming data to a counterpart is a repeated task. MVC solves this problem by abstracting binding away so programmers don’t have to rewrite a slightly different version of the same code in every app.

How does model binding work

When MVC receives an HTTP request, it assigns it to a specific action method of a controller. It desides which action method to run based on what is in the routed data, then it binds values from the HTTP request to that action method’s parameters. For instance, let’s consider the following URL:

http://contoso.com/movies/edit/2

Since the route template looks like this, {controller=Home}/{action=Index}/{id?}, movies/edit/2 routes to the Movies controller, and its Edit method. It also accepts an optional parameter called id. The code for the action method should look something like this:

Copy

C#

public IActionResult Edit(int? id)

Note: The strings in the URL route are not case sensitive.

MVC will bind request data to the action parameters by name. MVC will search for values for every parameter using the parameter name and the names of its public settable properties. In the above instance, the only action parameter is named id, which MVC binds to the value with the same name in the route values. In addition to route values MVC will bind data from various parts of the request and it does not follow any set of orders. We enlist the data sources in a order that model binding looks through them:

  1. Form values: These are form values that go in the HTTP request using the POST method.
  2. Route values: The set of route values provided by Routing
  1. Query strings: The query string part of the URI.

To mention form values, route data, and query strings are all stored as name-value pairs.

Since model binding asked for a key named id and there is nothing named id in the form values, it proceeded to the route values looking for that key. In our example, it’s a match. Binding happens, and the value is converted to the integer 2. The same request if you do by using Edit(string id), this would convert to the string “2”.

So far the example uses simple types. In MVC simple types are any .NET primitive type or type with a string type converter. If the action method’s parameter were a class such as the Movie type, which contains both simple and complex types as properties, MVC’s model binding will still handle it nicely. It uses reflection and recursion to traverse the properties of complex types looking for matches.

In order for binding to occur the class should have a public default constructor and member to be bound must be public writable properties. When model binding happens the class will only be instantiated using the public default constructor, then the properties can be set.

When a parameter is bind, model binding doesn’t go looking for values with that name and it moves forward to bind the next parameter. If binding fails, MVC does not show an error. You can find out model state errors by checking the ModelState.IsValid property.

Note: Each entry in the controller’s ModelState property is a ModelStateEntry containing an Errors property. It’s very rare to query this collection. Use ModelState.IsValid instead.

Additionally, there are some special data types that MVC must consider when performing model binding:

  • IFormFile, IEnumerable<IFormFile>: One or more uploaded files that are part of the HTTP request.
  • CancelationToken: Used to cancel activity in asynchronous controllers.

These types can be bound to action parameters or to properties on a class type.

On the completion of model binding, Validation occurs. The default mode of model binding works good for the most of the development scenarios.

We conclude the discussion here. We shall continue the rest of the discussion in our next article.

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

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