Author Archives: hanskishore

Regular expression reference

Regular expression reference table list

Regular ExpressionExplanation
a-zmatches small letters starting from 'a' - 'z'
A-Zmatches capital letters starting from 'A' - 'Z'
.dot(.) represents single wildcard character (joker in a card game)
\escape character. To escape the actual representation and represent actual character
^is used to negate a batch of character like [^a-z] -- matches the characters other than 'a' - 'z'
{m, n}m, n are integers here. represents any preceding character appears atleast 'm' times and atmost 'n' times. ex: a[1, 3] 'a' can appear 1-3 times
*represents the preceding expression can occur from 0 to any number of times. ex: \d* any digit can appear from 0 to any number of times
+represents the preceding expression will occur atleast once. ex: \d+ - digit will appear atleast once.
?represents the preceding character is optional(it may occur). ex: a? -- the match may have 'a' & ab?c -- 'b' is optional.
\wrepresents alphanumeric [a-zA-Z0-9_]
\rcarriage return
\sspace (represents space, tab, newline or carriage return)
^....$^ starting an expressiong and $ represents ending of the expression
()capturing part
|OR (cats|dogs|birds) - cats or dogs or birds
\bboundary between a word and a non-word character.
Any expression written in CAPITAL LETTER represents opposite of actual definition
ex: \D - non digits
\W - non alphanumeric
\S - non whitespace
Referencing any captured groups using parenthesis('()')
--- there can be many groups clubbed together and to refer each group use
ex: (\d*\.([,\d*]?))*$
\0 - full matched text
\1 - group 1
\2 - group 2

Running application from registry key path

This post for my reference:
I had a different version of MSAccess application and I had to run the application using Powershell script. The path of the application differs from computer to computer, since mine x64 bit the application resides in Program Files(x86) folder and in some other x32 bit machines the application is in Program Files. Moreover with different versions of Access the folder structure changes.

With the registry key it will target the latest version installed on your machine

for /f "tokens=3*" %%x in ('reg query "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\MSACCESS.exe" /v PATH') do set ACCESSM="%%x %%y"
"%ACCESSM%\MSACCESS.EXE \"Database Path\" /X macro-name"

Nuget package listing fails on the machine behind corporate firewall

I was unable to browse packages from visual studio, Package Manager Console or GUI. The message would be no packages found in the current source. Using Fiddler, I am opted to watch the traffic being sent, and all HTTP requests are successfully made and completed. When searching for “Log” I get a single request for the count of items (45), and then the follow up filter request with all 45 package items in detail. To verify if something within our corporate network was blocking the request, I also made each of the requests from Internet Explorer, and both were successful.

I realised that the response type is different and seems our corporate firewall policy is blocking them. I browsed for the solution and I found the it in Nuget Issue tracker which is helpful:
You can get around it with Fiddler2 and FiddlerScript. Edit the FiddlerScript, find the method “OnPeekAtResponseHeaders” and add the following code fragment before the method closing brace.

  if (oSession.HostnameIs("") && oSession.oResponse["Content-type"].Contains("text/xml")) {
        oSession.oResponse["Content-type"] = oSession.oResponse["Content-type"].Replace("text/xml", "application/atom+xml");

This will modify the response type. Thank you Nuget guys…

Creating a fixedwidth text file in excel using macro

To the data if you know the width that need to be specified set the columnwidths for each column, if you want all the columns to a fixed width you can select all the data columns and set theri their widths.

  Select the Developer>Visual Basic in the excel file

select insert module and write the method


Sub ExportText()
    ' Modify as needed
    Const strFile = "C:\Export\Test.txt"

    Dim r As Long
    Dim m As Long
    Dim c As Long
    Dim n As Long
    Dim f As Long
    Dim lngMaxWidth As Long
    Dim strLine As String
    Dim lngColWidth As Long

    m = Cells.Find(What:="*", SearchOrder:=xlByRows, _
    n = Cells.Find(What:="*", SearchOrder:=xlByColumns, _
    ReDim lngWidths(1 To n) As Long
    For c = 1 To n
       ' lngMaxWidth = 0
      '  For r = 1 To 100
       '     lngColWidth = Cells(r, c).ColumnWidth
        '    If Len(Cells(r, c).Text) > lngMaxWidth Then
         '       lngMaxWidth = Len(Cells(r, c).Text)
          '  End If
        'Next r
        lngWidths(c) = Cells(1, c).ColumnWidth
        'lngMaxWidth + 1
    Next c
    f = FreeFile
    Open strFile For Output As #f
    For r = 1 To m
        strLine = ""
        For c = 1 To n
            strLine = strLine & Cells(r, c).Text & _
                Space(lngWidths(c) - Len(Cells(r, c).Text))
        Next c
        Print #f, strLine
    Next r
    Close #f
End Sub

Alternate row colors for WPF ListView

To set the alternate background colors for the listview in WPF, set the style and then refer that style object in the listview

  <Style x:Key="ListViewAlternateColors" TargetType="ListViewItem">
                <Trigger Property="ItemsControl.AlternationIndex" Value="0">
                    <Setter Property="Background" Value="Gray" />
                <Trigger Property="ItemsControl.AlternationIndex" Value="1">
                    <Setter Property="Background" Value="LightGoldenrodYellow" />
                <Trigger Property="IsSelected" Value="True">
                    <Setter Property="Background" Value="White" />

and then set the style to the listview

 <ListView Height="170" ItemContainerStyle="{StaticResource ListViewAlternateColors}" Name="listView1" Width="719" AlternationCount="2" SelectionChanged="listView1_SelectionChanged" >
                        <TextBlock Text="{Binding Title}" />    

Hope this helps someone.

Service and Operation behaviors in WCF

Behaviors in WCF are used to say how it’s going to behave at the service level, endpoint level or operation level. ServiceBehaviorAttribute  is used to apply behaviors at the service level. To apply behaviors at operation level use OperationBehaviorAttribute.

ServiceBehaviorAttribute: This attribute can be applied only to service implementations. It has properties that are useful in enabling a specified feature for the service.

  •  AddressFilterMode: specifies the type of filter that the dispatcher system uses to locate the endpoint that handles requests.

  1. Any:  matches on any address of an incoming message
  2. Exact: exact match on the address of an incoming message
  3. Prefix: prefix match on the address of an incoming message
  • AutomaticSessionShutdown: allows to automatically close the session when the channel is closed and the service has finished processing any remaining messages.(true/false)
  • ConcurrencyMode: controls the internal threading model, enabling support for reentrant or multithreaded services.

  1. Single: Service instance is single-threaded and does not accept reentrant calls (other messages must wait)
  2. Reentrant:Service instance is single-threaded accepts reentrant calls. the reentrant service accepts calls when you call another service (make the object state consistent before callouts and make operation-local data is valid after callouts.)
  3. Multiple: service is a multi-threaded. (Synchronization need to be maintained).
  • ConfigurationName: used to declare a name for use in the name attribute of the <service> element in the config file.
  • IgnoreExtensionDataObject: enables the run time to ignore extra serialization informatin that is not required to process the message.(true/false).
  • IncludeExceptionDetailInFaults: enables the unhandled exceptions in a service to return in SOAP faults. Used for debugging purposes.(true/false)
  • InstanceContextMode: specifies whether and when services and their service objects are to be recycled during an exchange with a client.

  1. persession: new instance object is created for each session.
  2. percall: new instance object is created prior to and recycled subsequent to each call.(defaults for no session)
  3. Single: only one instance object is used for all incoming calls.
  • MaxItemsInObjectGraph: used to limit on the number of items in an object graph that are serialized.(number)
  • Name and Namespace: controls the name and namespace for WSDL.
  • ReleaseServiceInstanceOnTransactionComplete: specifies whether the service object is recycled when a transaction completes.(true/false)
  • TransactionAutoCompleteSessionClose: specifies whether outstanding transactions are completed when the session closes.(true/false)
  • TransactionIsolationLevel: specifies the transaction isolation level that the contract supports.(isolationlevel of)

  1. Serializable: volatile data can be read but not modified, and no new dat can be added during the transaction.
  2. RepeatableRead:volatile data can be read but not modified during the transaction. New data can be added during the transaction.
  3. ReadCommitted: volatile data cannot be read during the transaction, but can be modified.
  4. ReadUncommitted: volatile data can be read and modified during the transaction.
  5. snapshot:volatile data can be read. Before a transaction modified data, it verified if another transaction has changed the data after it was intitially read. If the data has been updated, an error is raised. This allows a transaction to get to the previously committed value of the data.
  6. chaos: pending changes from more highly isolated transactions cannot be overwritten.
  7. upspecified:a different isolation level than the one specified is being used, but the level cannot be determined. An exception is thrown if this value is set.
  • TransactionTimeout: specifies the time period within which a transaction must complete or it aborts.
  • UseSynchronizationContext: indicates whether to synchronize inbound method calls with the user interface thread automatically.
  • ValidateMustUnderstand: informs the system whether it should confirm that SOAP headers marked as MustUnderstand have, in fact, been understood.


Windows Communication Foundation

Since WCF has been introduced in .Net 3.0, it’s keep growing and the features available are also improving. Lets see how WCF works.

Actually there are many reasons to communicate one application to another or utilize resources available in the market. There are different connection scenarios for this. Webservices is one such where one application exposes a service which can consumed by clients which are able access that. There can be one-way, request-reply or duplex types of communications.
Earlier Microsoft shipped different tools for each type of communications. So it’s really a correct solution. So they introduced WCF which is able to perform all the major communication types available in the market.
The process of WCF is simple:
Typically, for any client to consume the service what it needs is
1. Where to find the service?
2. How to connect the service?
3. And What are the operations available from the service?
With the WCF, they have provided different bindings(System Provided) to define the connectivity part

BindingConfiguration ElementDescription
BasicHTTPBinding<basicHttpBinding>This binding is more suitable for communication with basic WS-Basic profile webservices. Similar to ASP.Net Webservices (ASMX). This uses HTTP as transport protocol and MTOM(xml) as default message encoding. Supports Transport, Message and Mixed security modes. Will not support Sessions and Transactions. Supports buffered streaming.
WSHTTPBinding<wsHttpBinding>Provides secure and interoperable communication (WS*), suitable for non duplex connections. Uses SOAP protocol, and text as default encoding. Supports security (Transport, Mixed, Message modes), by default at message mode. Supports Sessions (Reliable, Security) by default none.
WSDualHttpBinding<wsDualHttpBinding>Provides secure, interoperable, reliable and duplex communication contract with text encoding by default. Supports Security at message level by default and only security mode available. Supports sessions(Reliable, Security) with reliablesession as default.
WSFederationHttpBinding<wsFederationHttpBinding>This binding is basically used federation communication. supports security(Message, Mixed, none) at Message level by default. Supports sessions (Reliable, Security). Transactions are allowed.
NetHttpBinding<netHttpBinding>This binding is basically designed for consuming HTTP or websocket services and uses binary encoding by default. Websockets are only supported on Windows 8. NetHttpBinding will check for request-reply or duplex contract and change its behavior accordingly. It will use HTTP for request-reply and websockets for duplex.
NetHttpsBinding<netHttpsBinding>A secure netHttpBinding.
NetTcpBinding<netTcpBinding>This binding replaces the earlier .net remoting. This secure way of communicating between two WCF capable services.
NetNamedPipeBinding<netNamedPipeBinding>This binding generates a run-time communication stack by default, which uses transport security, named pipes for message delivery and a binary message encoding. This is appropriate for on machine WCF communications. It also supports transactions.
NetMsmqBinding<netMsmqBinding>This binding provides support for queuing by using Message Queuing (MSMQ) as a transport and enables support for loosely-coupled applications, failure isolation, load leveling and disconnected operations.
NetPeerTcpBinding<netPeerTcpBinding>This binding provides a secure connection for multiple machine communication. provides support for the creation of peer networking applications that use a TCP-level peer-to-peer mesh infrastructure. Each PeerNode instance can host multiple peer channels defined with this binding type.
MsmqIntegrationBinding<msmqIntegrationBinding>This binding is suitable for cross-machine communication between a WCF application and existing MSMQ applications.
WebHttpBinding<webHttpBinding>WCF allows to expose WCF web services through HTTP requests that use "plan old XML" (POX) style messaging instead of SOAP-based messaging. For clients to communicate with a service using HTTP requests, an endpoint of the service must be configured with the WebHttpBinding that has the WebHttpBehavior attached to it. The WCF also requires that the individual service operations are annotated with WebGet or WebInvoke attributes.

Implementing an MVC action filter to throttle requests

The following is from StackOverflow , for my future reference

    /// <summary>
/// Decorates any MVC route that needs to have client requests limited by time.
/// </summary>
/// <remarks>
/// Uses the current System.Web.Caching.Cache to store each client request to the decorated route.
/// </remarks>
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
public class ThrottleAttribute : ActionFilterAttribute
    /// <summary>
    /// A unique name for this Throttle.
    /// </summary>
    /// <remarks>
    /// We'll be inserting a Cache record based on this name and client IP, e.g. "Name-"
    /// </remarks>
    public string Name { get; set; }

    /// <summary>
    /// The number of seconds clients must wait before executing this decorated route again.
    /// </summary>
    public int Seconds { get; set; }

    /// <summary>
    /// A text message that will be sent to the client upon throttling.  You can include the token {n} to
    /// show this.Seconds in the message, e.g. "Wait {n} seconds before trying again".
    /// </summary>
    public string Message { get; set; }

    public override void OnActionExecuting(ActionExecutingContext c)
        var key = string.Concat(Name, "-", c.HttpContext.Request.UserHostAddress);
        var allowExecute = false;

        if (HttpRuntime.Cache[key] == null)
                true, // is this the smallest data we can have?
                null, // no dependencies
                DateTime.Now.AddSeconds(Seconds), // absolute expiration
                null); // no callback

            allowExecute = true;

        if (!allowExecute)
            if (String.IsNullOrEmpty(Message))
                Message = "You may only perform this action every {n} seconds.";

            c.Result = new ContentResult { Content = Message.Replace("{n}", Seconds.ToString()) };
            // see 409 -
            c.HttpContext.Response.StatusCode = (int)HttpStatusCode.Conflict;

Sample Usage

    [Throttle(Name="TestThrottle", Message = "You must wait {n} seconds before accessing this url again.", Seconds = 5)]
public ActionResult TestThrottle()
    return Content("TestThrottle executed");

You can also implement input throttling at the web server. With IIS 7.0 or 7.5, consider
using Dynamic IP restrictions, which are available for download at

Binding Client Controls using Ajax

Binding client controls after getting data from Ajax enabled WCF web service. Ajax provides many useful objects to bind data to client controls like DataView, DataContext, ADONetServiceProxy and ADONetDataContext. If you are using ASPX page:
If you are creating an ASP.NET web page, add a ScriptManager with a ScriptReference
to MicrosoftAjaxTemplates.js.

<asp:ScriptManager ID="ScriptManager1" runat="server">
              <asp:ScriptReference Name="MicrosoftAjaxTemplates.js" />

If you are creating an HTML page or an MVC view, reference the static JavaScript files

  <script type="text/javascript" src="MicrosoftAjax.js"></script>
   <script type="text/javascript" src="MicrosoftAjaxTemplates.js"></script> 

Bind data from the data fetched from the ajax datacontext like:

   <li>{{FieldName}}: {{FieldName2}} </li>

You need to add the javascript code to the of the ASPX page at the load time, you can use pageLoad function like:

  function pageLoad(){
                              autoFetch: true,
                              dataProvider: 'Service Name.svc',
                              fetchOperation:'MethodName within the service'
                          $get('data object id')             

You can do the Live Binding
for live binding you just need to replace

{{ <Property>}} with <span>{binding <Property>}</span>
<ul id="ulidName" style="display:none">
     <li><span>{binding fieldName}</span>: <span>{binding fieldName2}</span></li>

Live Binding won’t actually update the controls automatically when there is a change on the server but it’ll update the changes on the client datasource. To update data, you can use DataView.fetchData method.

Two way Data Binding is also available to update the client controls. Two-way data binding provides live binding’s ability to automatically update client controls when the client data source is updated, and it also updates the client data source when the contents of a bound client control are changed.
to use it

      <span>{binding <Property>, mode=twoWay}</span>

You can use live binding with formatted data by specifying JavaScript functions for the convert and convertback properties.
Eg: {binding , convert=toJavascriptFunction, convertBack=fromJavascriptFunction}

Updating Server data from client controls
If you need to allow users to update the data using client controls, use one of the following
three classes with an instance of DataView:
— DataContext
— AdoNetServiceProxy
— AdoNetDataContext

Data Context
The ASP.Net AJAX Sys.Data.DataContext class connects to the WCF data service or Ajax enabled WCF web service and reads, updates, and inserts data from a javascript client. With DataContext, you can develop a CRUD application using nothing but client-side JavaScript code, providing responsiveness similar to a Microsoft Windows application within the browser environment.

Typically, you use a DataView client control to present the DataContext to the user. Set the DataView:DataProvider to the instance of DataContext, and use live-binding markup in the template to allow users to edit the data. When the user has indicated that she is done making changes (such as by clicking a Submit button), call the DataContext.saveChanges JavaScript function.

This example demonstrates using DataContext and DataView together to connect to an ASP.NET web service:

<script type="text/javascript">
var dataContext = new Sys.Data.DataContext();
<button onclick="dataContext.saveChanges()">Submit Changes</button>
<ul sys:attach="dataview" class="sys-template" dataview:autofetch="true"
dataview:dataprovider="{{ dataContext }}"
dataview:fetchparameters="{{ {orderBy: 'Name'} }}"
<input type="text" value="{binding Name}"/><br/>
<input type="text" value="{binding Address}"/>

You can use the ASP.NET AJAX Sys.Data.AdoNetServiceProxy class to read, update, add, and delete records exposed by a WCF data service using REST. After you create an instance of AdoNetServiceProxy by specifying the location of the WCF data service, you can call the query and update, insert, remove, and invoke JavaScript functions to perform individual operations, or you can call the createActionSequence JavaScript function to run several operations together.

This example demonstrates using AdoNetServiceProxy and DataView together to connect to a WCF web service:

<script type="text/javascript" src="../MicrosoftAjax/MicrosoftAjax.js"></script>
<script type="text/javascript" src="../MicrosoftAjax/MicrosoftAjaxTemplates.js">
<script type="text/javascript" src="../MicrosoftAjax/MicrosoftAjaxAdoNet.js"></script>
<script type="text/javascript">
var peopleService = new Sys.Data.AdoNetServiceProxy('../Services/peopleDataService.svc');
<body xmlns:sys="javascript:Sys"
<ul class="list sys-template" sys:attach="dataview"
dataview:dataprovider="{{ peopleService }}"
dataview:fetchparameters="{{ {$orderby: 'Name'} }}"
<span class="name">{{ Name }}</span>
<span class="value">{{ Address }}</span>

Ado Net DataContext
Although you should be familiar with AdoNetServiceProxy, ASP.NET AJAX provides a second class for accessing WCF data services: AdoNetDataContext. AdoNetDataContext is derived from DataContext, and it uses the AdoNetServiceProxy class for communicating with WCF data services. However, it adds support for identity management, associating entity sets from different fetch operations, hierarchical data, and optimistic concurrency. You can use AdoNetDataContext exactly like you use AdoNetServiceProxy.

Planning Role Management in ASP.Net

When planning role management, follow these best practices:
1> Use Windows authentication for intranet applications when users have Active Directory domain accounts. This provides single sign-on for users and centralizes account management. If you use Windows authentication, ASP.Net uses roles to represent group memberships.
2> If you must create accounts for users separate from their Active Directory domain accounts, work with systems administrators to include the application’s role management in their account management process. For example, when a user leaves the organization, systems administrators will need to remove both the user’s Active Directory domain account and the application account.
3> Never assign privileges to an individual user. Instead, add users to roles, and assign privileges to those roles. If an employee leaves the organization, you only need to remove the user from the role rather than modifying how privileges are assigned.
4> Create separate roles for different management tasks. For example, instead of creating roles for just users and administrators of a blog application, create separate roles for readers, writers, editors, content approvers, and website managers. Even though it might require you to add users to multiple roles, having more granular roles simplifies delegating tasks if more flexibility is required in the future.
5> Always derive new security classes from existing .NET classes. Microsoft has carefully reviewed and tested the security components of the .NET framework. This does not mean the .NET framework does not contain security weaknesses; all code does. However, the .NET framework’s extensive review and testing helps to make them more secure than classes written by individual developers.