Tuesday, January 7, 2014

Known Issue GetOwinContext() return System.NullReferenceException

HttpContext.Current.GetOwinContext().Authenticate returns System.NullReferenceException when used in web api ie. Apicontroller.

The reason is the original context is not restored after leaving the await block. This is when used with task parallelism await async block.

So switching to .NET 4.5 solved the problem. But why? It seems that in ASP.NET 4.5, a task friendly synchronization context got introduced. This synchronization context ensures that the originel context is restored after leaving the await block.
So make sure that you either:
  • Set httpRuntime.targetFramework to 4.5, or
  • In your appSettings, set aspnet:UseTaskFriendlySynchronizationContext to true.
http://bartwullems.blogspot.se/2013/09/aspnet-web-api-httpcontextcurrent-is.html

http://vegetarianprogrammer.blogspot.se/2012/12/understanding-synchronizationcontext-in.html

Monday, January 6, 2014

Variable Scoping in Javascript

It is always important to make use of VAR to declare variable identifiers. If you miss doing this , there are two implications.

1. It is then by default act as GLOBAL variable.

2. Chances are these variables will be overwritten everytime developers uses same variable name across the modules. This is worst defect and sometimes difficult to figure it out.

/* Declared globally. */

function FindTruth(id) {

…

}

…

// Later in your page, another programmer adds…

var FindTruth= $(‘Overwritten-False-Fact’); // The FindTruth function just got

// overwritten.

Namespacing- Best Practice



/* Using a namespace. */

var MyNamespace = {

FindTruth: function(id) {

…

},

// Other methods can go here as well.

}

…
// Later in your page, another programmer adds…
var Findtruth= $(‘Overwritten-False-Fact’);// Nothing was overwritten.

In JavaScript Object Oriented programming this is Singleton pattern.

Now one can access method using MyNamespace.Findtruth(Id);

We can even structure it separately and then later add group of methods to decorate as library.

/* Super namespace. */

var SuperLib = {};

SuperLib.Common = {

// A singleton with common methods used by all objects and modules.

};

SuperLib.DataAccess= {

//Hold and transfer data

};

SuperLib.Helper= {

//Html Helper

};

!! Negation in Javascript

Double negation casts a string or a number to a boolean:
var bool = !!num;
The following values are equivalent to false in conditional statements:
  • false
  • null
  • undefined
  • The empty string "" (\ '')
  • The number 0
  • The number NaN
All other values are equivalent to true.
var x = "somevalue" var isNotEmpty = !!x.length;
Let’s break it to pieces:
x.length   // 9
!x.length  // false
!!x.length // true
 

Some Useful Basic Different ways of Javascript Coding

Style 1 Procedural Way

/* Start and stop animations using functions. */

function startAnimation() {

…

}

function stopAnimation() {

…

}

Style 2: using Prototype to define Class function

/* Anim class. */

var Anim = function() {

…

};

Anim.prototype.start = function() {

…

};

Anim.prototype.stop = function() {

…

};

/* Usage. */

var myAnim = new Anim();

myAnim.start();

myAnim.stop();

Style 3: Encapsulated Prototyping

/* Anim class, with a slightly different syntax for declaring methods. */

var Anim = function() {

…

};

Anim.prototype = {

                start: function() {

               …

              },

               stop: function() {

              …

 }

};

Style 4: Function.prototype.method

/* Add a method to the Function object that can be used to declare methods. */

Function.prototype.method = function(name, fn) {

                this.prototype[name] = fn;

};

/* Anim class, with methods created using a convenience method. */

var Anim = function() {

…

};

Anim.method(‘start’, function() {

…

});

Anim.method(‘stop’, function() {

…

});



Style 5: Chain Function Approach

/* This version allows the calls to be chained. */

Function.prototype.method = function(name, fn) {

                     this.prototype[name] = fn;

                    return this;

};

/* Anim class, with methods created using a convenience method and chaining. */

var Anim = function() {

…

};

Anim.method(‘start’, function() {

…

})

.method(‘stop’, function() {

…

});

Tuesday, December 31, 2013

Owin Pipeline with respect to IIS Integrated Pipeline mode Issues

When working Owin authentication you must face following problems.

  • Check if your IIS application pool is in Integrated mode. Note: Running of an OWIN middleware is supported only on IIS Integrated pipeline. Classic pool is not supported. 
  • Check if you have Microsoft.Owin.Host.SystemWeb Nuget package installed. This package is required for the OWIN startup class detection.
  • If your Startup class is still not detected in IIS, try it again by clearing the ASP.net temporary files. 
  •  Sometimes Owin works well with VS IISexpress .
  • <

    appSettings>

    <


    add key="owin:AppStartup" value="[AssemblyNamespace].Startup,[AssemblyName]" />
    </

    appSettings>
     

    Tuesday, December 24, 2013

    Modified ASP.NET 4.5 CPU Throttling percentCpuLimit


    http://blogs.msdn.com/b/webdev/archive/2013/11/26/modified-asp-net-4-5-cpu-throttling.aspx

    <configuration>
        <system.web>
            <applicationPool percentCpuLimit=”90” percentCpuLimitMinActiveRequestPerCpu=”100”>
        </system.web>
    </configuration>

    The default throttling limit was also lowered from 99% to 90% in order to detect high pressure and avoid negative scaling earlier.

    Just Asp.net Identity Core


    Before You dive further please go through these blogpost for more clarity and brevity.






    1. No Entity Framework.
    2. No Asp.net database tables
    3. Use existing Database user table for authentication.
    Have extended and used following Interface and class
    1. IUser
    2. IUserStore
    3. UserManager

    In order to refer our own table we have extended the method FindSync of UserManager.


    public class CustomUserManager:UserManager<ApplicationUser>

    {


    public CustomUserManager() : base(new CustomUserSore<ApplicationUser>())

    {


    //We can retrieve Old System Hash Password and can encypt or decrypt old password using custom approach.


    this.PasswordHasher = new OldSystemPasswordHasher();

    }




    public override System.Threading.Tasks.Task<ApplicationUser> FindAsync(string userName, string password)

    {


    Task<ApplicationUser> taskInvoke = Task<ApplicationUser>.Factory.StartNew(() =>

    {


    //First Verify Password...


    PasswordVerificationResult result = this.PasswordHasher.VerifyHashedPassword(userName, password);


    if (result == PasswordVerificationResult.SuccessRehashNeeded)

    {


    //Return User Profile Object...


    //So this data object will come from DB via Nhiberanate


    ApplicationUser applicationUser = new ApplicationUser();

    applicationUser.UserName =
    "san";


    return applicationUser;

    }


    return null;

    });


    return taskInvoke;

    }

    }

    For Source code
    http://code.msdn.microsoft.com/Simple-Aspnet-Identiy-Core-7475a961


     

    Tuesday, December 3, 2013

    Javascript Identity Operator vs Equality Operator

     

    Equality and inequality tests

    ==, !=
    It checks and compare values of the variable.
     

    Example

    var firstVal = 5;//Number

    var secondVal = "5";//String

    if (firstVal == secondVal) {

    console.log("They are the equal");

    } else {

    console.log("They are NOT the equal");

    }

    Output:They are the equal
     ONlY Values are compared.

     

    Identity and nonidentity tests

    ===, !== It checks and compare values and types of the variable.

    Example

    var firstVal = 5; //Number

    var secondVal = "5"; //String

    if (firstVal === secondVal) {

    console.log("They are the same");

    } else {

    console.log("They are NOT the same");

    }

    Output : They are  NOT the same.

    Values and Types are compared.
     

    Wednesday, November 27, 2013

    .net 4.5 Data Parallelism vs Task Parallelism

    If you have come across TPL task parallel library of .net 4.5 its important that you also have focus on below new library.

  • Task parallelism is the simultaneous execution on multiple cores of many different functions across the same or different datasets.
  • Data parallelism (aka SIMD) is the simultaneous execution on multiple cores of the same function across the elements of a dataset.
  •  http://msdn.microsoft.com/en-us/library/dd460717(v=vs.110).aspx
  • http://msdn.microsoft.com/en-us/library/ff963548.aspx
  •  
  • http://www.zdnet.com/understanding-task-and-data-parallelism_p2-3039289129/

    Data parallelism is pretty simple. It is the concept that you have a lot of data that you want to process — perhaps a lot of pixels in an image, perhaps you have a whole lot of payroll cheques to update. Taking that data and dividing it up among multiple processors is a method of getting data parallelism. This is an area that supercomputers have excelled at for years. It is a type of problem that is pretty well understood and more emphasis has been put on data parallelism in the past than on task parallelism.
    Task parallelism, on the other hand, is where you have multiple tasks that need to be done. So perhaps you have a large data set and you want to know the minimum value and you want to know the maximum and you want to know the average. This is a rather trivial example but you could have different processors each look at the same data set and compute different answers. So task parallelism is a different way of looking at things. Instead of dividing up the data and doing the same work on different processors, in task parallelism what you're doing is dividing up the task to apply.
    The most common task parallelism is something called "pipelining

    Data Parallelism

    http://msdn.microsoft.com/en-us/library/dd460720(v=vs.110).aspx

    Parallel.ForEach{

    }

    Task Parallelism

     
    static

    void Main(string[] args)

    {


    Task[] tasks = new Task[2]

    {


    Task.Factory.StartNew(() => {


    TaskA objTaskA=new TaskA();


    // objTaskA.MessageSent += MessageSent;


    // objTaskA.TaskCompleted += TaskCompleted;

    objTaskA.Activate();

    }),


    Task.Factory.StartNew(() => {


    TaskB objTaskB=new TaskB();

    objTaskB.Activate();

    })

    };


    Task.WaitAll(tasks);



    }



     

    Tuesday, November 26, 2013

    VS2012 IDE Issue No exports were found that match the constraint contract name

    Today I tried to add new project in VS2012 IDE for development it didn't allow me to proceed as it popup an error stating this
    VS2012 IDE Issue No exports were found that match the constraint contract name

    I got the workaround in Stackoverflow-
    http://stackoverflow.com/questions/17596543/no-exports-were-found-that-match-the-constraint-contract-name

    Step 1: Close VS2012
    Step 2:
    Just delete or rename this folder:
    %AppData%\..\Local\Microsoft\VisualStudio\11.0\ComponentModelCache
    

    Step 3:
    Restart VS2012


    The probable reason would be VS2012 had not been closed for longer period of time therefore resulting in above error.

    Technical Design - Application Architecture These Terms does matters.

    At application architecture level, we come across layers and tiers terminology.I will not delve much into these terms now but would rather focus on the details of it.  Yes we know presentation , business, service , data access layer and many such stacks that defines application architecture at logical level. We then built solution taking these layers pointers into consideration. Then comes what the code files where we have domain entities, utilities , classes, interface and so on..

    Well, sometimes it becomes non trivial to appropiately name such source code files unders these layers.

    To complete these blogs actually I need an expert advice to make this meaningful and comprehensive. I'm sure there is no such reference atleast available online. Everyone has their own theisis of explanation and fundamentals behind.

    Most common suffix ending list of file name.

    1. Manager
    2. Provider
    3. Handler
    4. Helper
    5. Factory
    6. Services
    7. Extender
    8. Contract

    So On

    The point is as naive architecture I may put them wrongly and may latter refractor based on review. I'm sure there can be rule book across but fail to find one.

    Need help.

    Thursday, November 14, 2013

    Predefined type 'System.Object' is not defined or imported

    This is rarest of the rare error that comes when we build/debug solution in Visual Studio for .net . The problem is the missing MSCORLIB dll system.core which somehow not exists in .csproj file. The developer resort this by recreating new solution or clean the folder, get the latest code from TFS and then build it. But the problem sometimes lies as-is. One can take this to next level by locating this tag . if this is not present Add this. Forgot to mention, open this file in notepad rather VS IDE.

    Then you rebuild the solution once again to get your ANIMAL(I mean your solution-which may have large number of class library in it) run.
    Do post your comment if run into similar problem or please let me know the best way to get away with this one.

    Tuesday, November 12, 2013

    Design Pattern and Most general Software Terminology

    Its long time in my career and sometimes we flumble with the basics, concepts and fundamentals.
    Here is the list of few design patterns or terminology where we come across during day to day SDLC life cycle. I will try updating this particular post in future to include the most favourable one.

    Facade: It provides simplied interface to a larger body of code-class library. In simple terms a group of class library or dll referenced in single interface and this later expose to calling events or client.
    Purpose - It wraps poorly designed collections of API into or with single well designed API.

    Adapter : Is also called Wrapper pattern or Decorative pattern (GOF ). The actual usuage or orgin, when one should coin this- This is to be used when we have module which is to be used but incompatible with other module. At such places we create interface out of the class and create compatible bridge to use across.

    Boiler Plate  Code- Is a section of code that can be included in many place with no or minimal changes.

    • Shotgun Debugging- To apply too many solution at a time to solve issue.Troubleshoot.
    • Spaghetti Code- To many branching of code, difficult to read and understand
    • Smoke Testing- To do high level testing to ensure system do not break. This ignores finer level of testing. Imagine a smoke pass into pipe to check leak
    • Regression Testing-Testing to ensure new changes do not break existing functionality.
    • Write Only Code- Difficult to read
    • Runtime-
    • Break Fix-
    • Service Pack
    • Drivers
    • HotFix-
    • Refactoring- Change system internally without affecting functionality.
    • Pilot
    • Prototype
    • Proof of Concept
    • Psuedo Code- Code that is written in user readable format unlike programming language.
    • Peer Review
    • Patch
    • Plumbing work
    • Legacy System
    • Gold Code- Code that is live and burn in disc. Final release product.
    • Gap Analysis
    • Impact Analysis
    • Evaluation
    • Feasibility Check
    • AntiPattern- In appropiate solution for a problem but still used as temporary setup.

     

    Thursday, October 24, 2013

    Symmetric Encryption, Asymmetric Encryption and Hashing Cryptographic


    1. Symmetric encryption. Uses the same public key to encryption and Decryption
    Algorithm : DES, AES, 3DES,RC4

    2. Asymmetric Encryption: Use public key to encypt the data and private key to decrypt the data.
    Like email exchange.
    Algorithm : RSA

    Sender encypts data with public key and reciever decrypt using private key.

    3. Hashing is kind of cryptographic unlike encryption. It is also called one way encryption.
    Algorithm : MD5 and SHA-1
    It uses secret key or checksum or password salt-random generated value to encrypt the data. It is called one-way hashing as we cannot reverse the original data or decrypt the value back to clear text.

    http://packetlife.net/blog/2010/nov/23/symmetric-asymmetric-encryption-hashing/

    Monday, October 21, 2013

    VS2013 Performance Test Approach and Strategy

    Summary-
    1. KPI /metrics to identify performance index.
    Refer this http://msdn.microsoft.com/en-us/magazine/cc188783.aspx
    The next step is to clearly define your metrics. Examples of metrics include the number of orders processed per minute or the number of milliseconds required to execute a request on an ASP page. Metrics allow you to quantify the results of the changes made between each of your test runs. They provide a comparison to the standard defined for your Web application.

    2. Saved your load test results in Database for reports comparison against baseline. Identify baseline date
    Say SUT test. One can baseline single user test for given scenario consisting of test cases.
    SQL Express: SQLCMD /S localhost\sqlexpress /i loadtestresultsrepository.sql
  • SQL: You can install the database to any existing SQL server. For example, if you had a SQL server named ContosoServer1 you would use the following command:
    SQLCMD /S ContosoServer1 -i loadtestresultsrepository.sql

  • http://msdn.microsoft.com/en-us/library/dd997707.aspx
    http://msdn.microsoft.com/en-us/library/vstudio/ms182600.aspx

    3. Identify the acceptable response time per request call
    4. Permissible transaction failure or error count.
    5. Combo load test and load test with data driven.
    Say
    Scenario S1
    S1_01 Login
    S1_02 Perform Step 1
    S1_03 Perform Step 2

    Scearnio  S2
    S1_01 Add Details
    S1_02 Perform Step 1
    S1_03 Perform Step 2

    Sceanrio S3
    S1_01 Update Details
    S1_02 Perform Step 1
    S1_03 Perform Step 2

    Broadly I identify 3 high level test scenario. Login, Add and Update

    Ideal Test Condition: Load test With 5 users
    User 1: S1
    User 2: S1
    User 3: S1
    User 4: S1
    User 5: S1
    Same Scenario Different data points different User.
    Run: Concurrent
    Duration of load run: say 30 mins
    Capture Response time


    Real Time Condition: Combo load test with 5 users
    User 1: S1
    User 2: S2
    User 3: S3
    User 4: S2
    User 5: S3
    Different Scenario Different data points different User.
    Run: Concurrent
    Duration of load run: say 30 mins
    Capture Response time




     

    Friday, October 18, 2013

    SEO: Hash bang vs Push state/Replace State Html5

    SEO in simple terms ensure the web page ranking and indexin for search engine. In order to do so we built our web pages to align to that standard and rules to be SEO non agnostic. Tags, Keywords, meta data and page state helps to get into top of the search list and there we called is is SEO compliant.

    Hash # in website URL helps enables interactive within page. It helps locate quick element and navigation across page scroling without having to make a request back to the server. With this we can manipulate browser history when moving forward and backward due to which overall segment of SEO is defeated. To resolve this Google came up with workaround of Hash # Bang ! in url
    sample link http://well.com/#!/User1

    Now it is not a standard but solution to work with SEO on hash issue. We do heavy duty at backend code in server to check “_escape_fragment_” This is again one of the problem in terms of processing and latency.

    Looking into all this HTML5 Push state is good solution to above problem

    For such URL http://example1.com/#images1/1 to tell a JavaScript application to load image #1 on to the screen, can be given as URL: http://example1.com/images1/1 – with no Hash at all

    pushState(data, title, url)
    replaceState(data, title, url)

    window.history.pushState(state, state.title, "detail.aspx?article=" + article);



     

    Thursday, October 17, 2013

    VS2013 Load Test RIG Installation

    VS2013 and its power packed Test Manager for application performance test suite is going to be big leap when moving from QTP load runner. It offers you everything under the sun.
    Before you try VS2013 Ultimate RC its important for us to understand the technical know and how of the subject.


    1. Configuring controller and Agents -Load Test RIG
    2. Combo load test vs Load Test.
    3. Data Driven load test for each user load. Real time scenario
    4. Create Test cases , identify scenarios -Most critical ones
    5. Number of concurrent users.
    6. Sequential or overlapped loading of user session
    7. Think time
    8. Sampling Rate
    9. Base Response time
    10. Thoughoutput/Latency of page
    11. Allowed error count for given passed transactionsvs failed transactions


    Load test RIG Installation and configurations:
    http://blogs.msdn.com/b/edglas/archive/2007/02/17/load-agent-and-load-controller-installation-and-configuration-guide.aspx

    http://visualstudiomagazine.com/articles/2010/07/08/load-testing-with-visual-studio-2010.aspx

    Sunday, October 13, 2013

    The Change Up Android App with Html5 using VS2012

    I always wanting to write my first Android App but ends up in despair as I don't want to move from my comfort zone of Visual studio for that matter .net. Finally I got my small Hello world App installed in Android device. Before this all I would like to share the links/references to starter kit that makes you get going and hopefully you can break or zeal to develop your first app in Android. ITs Html5 so one can port this in Windows phone aswell all you need is windows 8 environment to do it in a right way. Once this is done you can port your app in Windows Store or Google Play full fledgedly.

    http://geekswithblogs.net/omtalsania7/archive/2013/10/08/android-app-development-in-html5-using-visual-studio-2012-express.aspx

    Prerequisites
    Android SDK: http://developer.android.com/sdk/index.html
    Java SDK: http://www.oracle.com/technetwork/java/javase/overview/index.html
    Ant SDK: http://ant.apache.org/bindownload.cgi

    Mandate: VS2012

    Xamarin and Phonegap are the awesome tool to start with your Android app development however if you are .net geek then above enablement is for you.

    Troubleshooting Tips:
    1. If you unable to debug or built app in VS2012 then all you can do it using following command.
    Go to your solution folder then type locate ant.bat
    something like this.
    D:\androidApp1> d:\ant\ant.bat debug

    2. If you unable to configure android SDK , try installing Xamarin as it sets all the environment for you. Still you can through with VS2012.

    3. Update repository .
    d:\Android\android-sdk\tools>android.bat update sdk --no-ui

    4.d:\Android\android-sdk\tools\ant\build.xml:397: SDK Pla
    tform Tools component is missing. Please install it with the SDK Manager (tools\
    android.bat)
    Total time: 0 seconds

    Install Android SDK platform.if you install Xamarin, it will take care of this one aswell.


    If your built is successfull you can check for .apk file in release folder and can mail /distribute to Android users for quick test.

    Hope this is helpful.
     

    Wednesday, September 18, 2013

    Paging with OFFSET and FETCH in SQL 2012


    Paging with OFFSET and FETCH

     

    Created a sample table with few records. @PAGESIZE variable gives the no of records needed in each page, @STARTINGROW variable gives the starting record count, @SORTCONDITION gives the sorting attribute and order (functional requirement).

     

    DECLARE @PAGESIZE INT

    DECLARE @STARTINGROW INT

    DECLARE @SORTCONDITION VARCHAR(250)

     

    SET @PAGESIZE = 20

    SET @STARTINGROW = 10 -1

    SET @SORTCONDITION = 'EMPNO ACS'

     

    SELECT        R1.ID 

    ,             R1.EMPNO 

    ,             R1.EMPNAME

    ,             R1.EMPADD1

    FROM   SAMPLEFETCH R1       (NOLOCK)

    ORDER BY

                  CASE   @SORTCONDITION

                  WHEN   'EMPNO ACS' THEN EMPNO

                  WHEN   'EMPNAME ASC' THEN EMPNAME

                  WHEN   'EMPADD1 ASC' THEN EMPADD1

                  END ASC,

                  CASE   @SORTCONDITION

                  WHEN   'EMPNO DESC' THEN EMPNO

                  WHEN   'EMPNAME DESC' THEN EMPNAME

                  WHEN   'EMPADD1 DESC' THEN EMPADD1

                  END DESC

    OFFSET @STARTINGROW ROWS

    FETCH NEXT @PAGESIZE ROWS ONLY

    Query Execution Steps


    Parse time is the time spent during checking SQL statement for syntax errors, breaking the command up into component parts, and producing an internal execution tree

    Compile time is time spent during compiling an execution plan in cache memory from the execution tree that has just been produced.

    Execution time is total time spent during execution of compiled plan.

    It is really a good idea to split this kind of stored procedure to sub procedures that would help to reduce the parse and compile time.

    --Clear the cache and buffer

    DBCC FREEPROCCACHE

    DBCC DROPCLEANBUFFERS

     

    --How much time a query is taking can be best measured by setting STATISTICS TIME ON

     

    SET STATISTICS TIME ON

     

    --Execute the Stored procedure

     

    EXEC ExecutionTimeTest 'Supervisor', 123037

     

    SET STATISTICS TIME  OFF

    SQL Server parse and compile time:

       CPU time = 281 ms, elapsed time = 365 ms.

     

    SQL Server Execution Times:

       CPU time = 140 ms,  elapsed time = 209 ms.

     

    SQL Server Execution Times:

      CPU time = 421 ms,  elapsed time = 574 ms.