Sunday, October 19, 2014

Cookieless Session Vs Cookie Session

Reconstructed MSDN Understanding:-

Simple E.g. You go in pub and you handover your jacket in a counter .To get your jacket back you get some token as a reference. Similarly we have session id which is generated on request made to server and it is placed cookies.

Quick Take:-

Cookie Session

1. Cookie store session id and it identify session data from server for each request and response. User agent browser to server.

2. If Session object is not created or used apart from session_start , for each new requests it creates new session IDs. Hence it is require to create session object either in session_start or any part of application.

Cookie Less Session

1. In this case session id is static and remain same for entire session period
2. Session id is stored in URL for each request and response.

There can be possibilty when there is device where cookies are disabled and in such scenario we can make use of Cookie less session. There is feature itself in by using Autodetect for UseDeviceProfile.

Saturday, October 18, 2014

FactFile SessionID in and SqlServer SessionState

Facts to be remember. While dealing with session always keep below factfile into consideration.

I created a variable in the Session_Start in the global.asax file:
var sessionID = Session.SessionID;
I found the following data while debugging the application:

ASP.NET generated : lehxv4so4ioi2gqqaxtjzhyo
SQL Server saved  : lehxv4so4ioi2gqqaxtjzhyo84497b6f
in bold is your sessionid and in italics is the application id
the extra 8 bytes are the applicationid

SQL Server Session Tables


SQL Server Session Database

tempdb database in SQL Server by default
  1. Very Very Imp never use Tempdb for outproc session.
  2. In out proc mode session_end never calls, no use if you apply any debug or diagnostics pointers.
If we using webfarm and out proc session, ensure machine key across server instance is unique.

Cookie Container





IIS Debugging -WET Tracing For IIS

IIS Debugging
Whenever you have to check the request serving and find out how http pipeline processed at kernel aswell as user mode level using this options
Ofcourse HTTPERR log , httpsys and iislogs and Perfmon will be of great use. But this comes very handy.
c:\> logman stop httptrace -ets
The command completed successfully.
c:\> tracerpt.exe trace-output.etl -of XML -o trace-output.xml
c:\> logman start httptrace -p Microsoft-Windows-HttpService 0xFFFF -o trace-output.etl -ets
The command completed successfully.

Session Variables vs Session Timeout vs Session Mode

Recent time i had tough time dealing with sessions in , especially when it is product related to sitecore where we have complex setup with mulitple instance within same app domain and website.
The reason why I m pondering on session variables vs Session timeout vs session mode is something we need to be extra careful when identifying the problem at the same time understanding it. This is where you start your right investigations.

What I know, as this session things are such we rarely come across with issues and it becomes history by the time we forget the concepts inline with same applies to cookies and caching. We tend to forget them as we don't apply them very frequently. Telling long story shorts!

We got into trouble with session and we assumed and presummed it was session timeout -expiry issue as it is getting timeout after every 2 minutes. This is what we have been thinking and taking are investigation ahead.

Then later stage we realized we haven't gave much thoughts session mode.

Remember there is settings for session IIS aswell as in web.config , sometimes it do not sync. Check that aswell.

Coming back session mode, we have two session mode one In-Proc and Out-Proc
Now Out-Proc can be two ways to setup one is SessionState= StateServer that is done through state Service in Run-> Services.msc and it is kind of window service run outside of IIS.Hence there is no question of app pool recycle or app domain restart or bin changes as it is out proc your session still alive for given time period.

Same applies for out proc mode with SessionState= SQLServer where we store session in sql server. In Master aspnetTempsession.There is two tables where it has applicationsession table and its corresponding mapping in aspnetTempsession. May be one can look into this in details..SQL Server Agent plays crucial role as there is job which manages session managment at large.
The above is some overview as I learnt it in hard way after such a long experience in .net

After understanding the above concepts we got to know we were following wrong directions as we didn't got our problem statement right.
My application was using Out Proc and problem still persisted , timeout was again 2 minutes and still we haven't got into the bottom of it.

Soon we came up with different strategy we added trace response.write in staging env we just capture session ID and aswell as did lookup what happing in background using sql profiler trace.

Here is the catch!
We found that Session.ID still available as is for timeout period=20 minutes whereas session variables are setting it to null every time after 2 minutes..My investigation and probing --debugging the root cause is still on-- Need to reveal yet!


Hence I kept emphasing on verdict of be Sure, doubly sure what is it , is it related to session expiry or Session variables or session mode(Incorrectly set)

We you are using In- Proc,
Check Tezz Fernandez blogs. for sure we will get some idea how to resolve your issues.

Some Scott Gutrie Way

On Some Tracing Event window Tracing
c:\> logman stop httptrace -ets
The command completed successfully.
c:\> tracerpt.exe trace-output.etl -of XML -o trace-output.xml
c:\> logman start httptrace -p Microsoft-Windows-HttpService 0xFFFF -o trace-output.etl -ets
The command completed successfully.
Signing Off
Santosh Poojari


Windows Azure Storage Issue with Micirosoft.DataServices.Client loading assembly

This problem is most common with windows Azure SDK version where it get conflicts with versions of dll related to Micirosoft.DataServices.Client . As a temporary get away to this problem is to just exclude it from runtime tags in your app.config or web.config. Beware you need again need to fix if you have to deploy this to production environment.

Sometime update to Nuget package doesn't work the way we want.

Friday, September 5, 2014

Wow ! Background Task in Separate thread in web form

Its unfortunate that I never used threading to that extent as most of my work involved in web platform with very little to do with threading and task parallelism. Still there are cases where this Background Task can come handy. Now it depends.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.IO;

using System.Threading;

public partial class _Default : System.Web.UI.Page

protected void Page_Load(object sender, EventArgs e)

//We started this task in separate thread which will not interfere in web page usual activity.

//We can still perform all operations and this below task will run in background.

BackgroundTest longTest = new BackgroundTest(50);

Thread backgroundThread = new Thread(new ThreadStart(longTest.RunLoop));

backgroundThread.Name = "BackgroundThread";

backgroundThread.IsBackground = true;

Label1.Text = "end";


/// Non Stoppable Button click..I mean we can still perform this operation

/// independent of below background thread.




protected void Button1_Click(object sender, System.EventArgs e)

Response.Write("Som Button Click");


/// Background Thread


class BackgroundTest

int maxIterations;

public BackgroundTest(int maxIterations)

this.maxIterations = maxIterations;
public void RunLoop()

String threadName = Thread.CurrentThread.Name;

for (int i = 0; i < maxIterations; i++)


System.IO.File.AppendAllText("E:/test", DateTime.Now.ToString());




Unity Dependency Injection Resolve

Unity Dependency Injection has given us lot of flexibility in terms of customizations and suits to our requirement. There has been good reference and api for Unity MVC , Web API and WCF service. Here is the good free online e-book to start from scratch. It covers everything from DI, AOP, exception handling, caching and customization.

If you looking for creating instance with Unity DI for any class this is what we must do.

Injection constructor
Injection Methods

Few things to keep in mind.
1. We register interface/Class for object reference.
2. We set resolver for each class object
3. We get the resolver.

Option 1
public class MyObject

  public MyObject(SomeClassA objA, SomeClassB objB)

  public MyObject(DependentClassA depA, DependentClassB depB)

IUnityContainer uContainer = new UnityContainer();
MyObject myInstance = uContainer.Resolve();
Option 2

IUnityContainer container= new UnityContainer();
               new InjectionConstructor(
               new ResolvedParameter<DependentClassA>(), new ResolvedParameter<DependentClassB>()));
               var instance= container.Resolve<MyObject>();
We can even have global configuration to resolve all our object instance for any class library.

Wednesday, August 13, 2014

Scheduled Load Test

Automating the execution of load tests is actually quite easy. Typically, a load test would be scheduled to run overnight, over a weekend, or even over the course of a few weeks.

The easiest way to accomplish this is to simply have a batch file that executes the load test, and to use the NT Scheduler that comes with all current versions of Windows to schedule when this batch file is executed.

 An example load test start script may look something like this:

  "C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\mstest.
  exe" /TestContainer:ProdLoadTest.loadtest /RunConfig:"C:\Source

In this example, the arguments below are passed to MSTest.

Represents the load test that should be executed. This contains all the details, such as Network Mix, run details, and so on, required to execute the test.


Represents the current test configuration which lists the controller to use, deployment options, test naming standards, etc., discussed earlier.

VS 2013 Web Load Test Most Common Mistake Using Property StringBody with Content Type Json


Every time you deal with data driven web load test in Visual studio remember to follow the correct format for content type. Otherwise one ends up looking into different areas while troubleshooting the issue related to data bind data source . Sequential, Unique and random
Load Runner Vs Visual Studio Load test :-
It can be my ignorance....please spare me if you see any discrepancies in my thought or understanding process.
It reminds how load runner used to work- I used to work with performance test team who shared their screen with me to show the progress of the load run and the failed transactions. There is a threshold limit for number for transactions that is permissible to fail above which test was used to marked as RED or failed. Now coming back to what I understand, this something not about stress test but the test related to number of users that must be loaded to run the test. We used to provide the test data for each scenario and users in excel. Once recording is done during load test this data is picked by each users and constant user load or ramp up of users( step up) applied to generate real time scenario.
UNLIKE load runner, webtest in VS records the scenario and runs for all data users at once which is kind of non realistic procedure. What I mean here is, the user data is not bind during load test but it is available as complete run in web test which makes it in complacent or absurd for real time scenario.
Its like say login functionality.. I have userid and password for say 10 users in excel. I did recording of webtest with datasource bind to this excel which picks up 10 users at one go. When I apply say load test on this webtest for say 2 users it don't picks up 2 user input data but rather runs one webtest with all 10 users in one set and then subsequent round 2 with set of 10 users input.
Visual Studio Load test
[1 webtest -10 user input data]- load test -2 users = 1 Users [1webtest 10 user input data run] +1 users[1webtest 10 user input data run] 
Load Runner
[1 webtest]- load test -10 users input data feed = 10 user runs with 10 data inputs =10 run
this is perfect and concur to real time scenario
Please correct me, if you think this is not the behavior because I spend almost a month understanding this aspect , I research lot but none of the available information talk about this nitty gritties.


Do remember to apply right format structure, even missing quotes in semantics will lead you to spend lot of time solving the datasource issue..
Sometimes webtest runs fine with hardcoded login userid and password but when we bind the data source to bodystring( it is when login is in popup JS) you need to be extra careful with format.
  1. In main content panel of WebTest1.webtest
  2. Right click WebTest1 > Add Web Service Request
    1. Right click http://localhost/ > Properties
    2. Set the url to the web service end point
      1. Set Url: http://localhost:64093/api/user
    3. Expand the url http://localhost:64093/api/user
      1. Right ClickString Body > Properties
      2. Set Content Type : application/json
      3. String Body > Click Ellipsis ...
        "UserId": "{{DataSource1.UserId#csv.UserId}}"
        (NOTE: Using {{DataSource1.UserId#csv.UserId}} will set the value from the CSV.)
  3. Click Save 

Tuesday, August 12, 2014

Parse IIS Log Logparser to filter request to prevent SQL injection.

Problem Scenario

We can reduce traffic by using URL rewrite at the same time making use of Request filtering will ensure unnecessary requests are stopped at IIS web server level itself thus not hitting any database server for further processing. To a greater extent increasingly different combination of useless querystring for given url also a cause of sql server performance degradation.

Parse IIS log using Logparser tool

Using the query below I could see the most frequently used querystring values and it was obvious the site experiencing a SQL Injection attack.

logparser.exe -i:iisw3c “select top 20 count(*),cs-uri-query from ex140702.log
group by cs-uri-query order by count(*) desc” -rtp:-1 >file.txt
By viewing the output we can add rules for request that is coming in for webserver in IIS request filtering.
We can keyword for querystring which are identified in the logs by doing this in a way we can restrict unnecessary request and provide access denied to such request. Status code 404.
SELECT STRCAT(TO_STRING(sc-status), STRCAT(‘.’, TO_STRING(sc-substatus))) AS Status, COUNT(*)
AS Total FROM w3svc.log to TopStatusCodes.txt GROUP BY Status ORDER BY Total DESC
Some important areas to be looked for performance stats
  1. SQL Profiler
  2. Database Tuning Advisor
For more details

SQL Server Performance Tips: Top Queries by total CPU Time

SQL Server: Inbuilt Reports



My Repository and source of information

Server Configuration

Contains most of the .NET Framework sections and settings.
web.config (root)
Contains more of the ASP. NET-specific sections and settings.
%windir%\System32\inetsrv\config (by default)
Contains the IIS global web server, configuration sections, and site settings using location tags.
%windir%\System32\inetsrv\config (by default)
Contains the configuration for IIS Manager and the IIS Manager users.
This is used for shared configuration, which allows applicationHost.config and administration.config to be relocated.

Debugging and Troubleshooting Sources

  1. Windows Event log.
  2. Task Manager process Check
  3. Perfmon performance monitor
  4. Perfview
  5. Http.sys error log
  6. IIS log - Log parser, google analytic tool
  7. Network Connectivity :Ping, tracert and pathping
  8. Port Connectivity telnet
  9. SQL Profiler - tuning option to be selected.
  10. .net CLR profiler
  11. Visual studio Tier Interaction

Monday, August 11, 2014

System Level Jargons

  1. Thick Client
  2. Thin Client
  3. Smart Client
  4. Rich Client
  5. Agent
  6. Upstream application
  7. Downstream application
  8. Back door entries
  9. Backend
  10. Frontend
  11. OLTP- Online transaction Processing
  12. Master- Transaction tables
  13. OLAP
  14. MOLAP
  15. Datawarehourse
  16. Datamart
  17. Reporting
  18. Staging Database
  19. ETL- Extract Transform Load
  20. Load balanced.
  21. Custom Development vs Packaged Application
  22. Reverse Engineering/forward engineering


Wednesday, August 6, 2014

AngularJs -Directive with Template and TemplateUrl

Directive example here is kind of Widget that is reused . Example of book widget


<html data-ng-app="app" id="ng-app" lang="sv">

<div data-ng-controller="ControllerWithScope">

<my-books book="maths"></my-books>

<my-books book="science"></my-books>

Controller and directive:

Here if we use template: "put html element"
if we use templateUrl: provide url

Very Very important:
app.directive('myBooks', function () {
Here 'myBooks' is case sensitive will fail if used mybooks.


Sunday, August 3, 2014

Web Capacity Analysis Tool (WCAT)

This tool comes very handy if you want to check some specific page level performance w.r.t requests processed in IIS.

Say for e.g, you want to check response time of any page as compared to baseline response time this tools comes as a quick rescue.

Download Tool

Steps to run this tool.

I find this very useful when you don't have to configure heavy duty software , server to just test simple or troubled page.


Monday, July 28, 2014

Url Rewrite: Check Request URL Best Practice

Append or Remove the Trailing Slash Symbol

Enforce Lowercase URLs

Checking If a Request Is for a File or a Directory

Using String Functions with Rule Actions and Conditions

Add a note hereURL Rewrite offers three string functions that can be used with the rule actions and conditions:

·         Add a note hereToLower — Returns the string as lowercase.

·         Add a note hereUrlEncode — Returns the string as a URL-encoded format.

·         Add a note hereUrlDecode — Returns the string as a decoded string.