Algorithms for DNA related analysis – Introduction

Before discussing about algorithms, I will discuss some frequent terms used in DNA analysis. I’m not a biological student but one who uses algorithms  for DNA mappings, sequencing related analysis need to understand frequently used terms around DNA

  • Amino acids
  • Proteins
  • Nucleic acids
  • Genome
  • Transcription
  • Translation
  • DNA replication

Amino acids

Amino acids are chemical compounds which are building blocks of proteins and act as intermediates in metabolism. Protein characteristics always dependent on the amino acids precise content and their sequence. It means each protein has different amino acid contents and sequence. Also the chemical properties determine protein biological activity. To understand a protein structure and its stability (protein folding), it is essential to understand amino acid structure and chemistry first.

There are 20 types of amino acids within a protein 10 of which can be produced by human and other 10 are supplied through food. Human body doesn’t store excess amino acids (those available from food) like fat and starch so they should be available through food daily.

Recent study findings on insulin resistance for diabetes type 2 patients revealed that lipids and Branched-Chain amino acids (BCAA) work together to promote metabolic diseases. The presence of BCAA related signature is predictive of incidence, progression and remission of diabetes and insulin resistance.

Proteins

Proteins are complex molecules that are made up of smaller unit’s amino acids as a long chain. Proteins can be categorized into types based on their function, few of the types are

  1. Antibodies – attaches to virus to protect the body
  2. Enzymes – Assist in the formation of new molecules from the DNA information
  3. Messenger – to transmit signals between cells, tissues and organs
  4. Structural component – Used for cell structure and support.
  5. Transport/storage – Carry atoms and molecules around the body
  6. Proteins can synthesised using two ways
  7. Biosynthesis – These are synthesised in cytoplasm from encoded gene instructions
  8. Chemical synthesis – These are synthesised chemically with peptide synthesis

A simple good example is identifying antibodies in the blood for determining HIV existence in the patient’s body

Nucleic acids

Nucleic acids are essential molecules of life. They include DNA (deoxyribonucleic acid) and RNA (ribonucleic acid) which are made from nucleotides. Each nucleotide consists of 5-carbon sugar, a nitrogenous base and one or more phosphate groups and categorised as DNA or RNA depending upon the sugar component. If the sugar component is deoxyribose, then it’s a DNA or if sugar component is ribose, then it’s a RNA.

DNA consists of two long strands of nucleotides which are anti-parallel in nature (opposite direction)

RNA plays an important role in protein synthesis and is divided into three types

  1. Transfer RNA (tRNA)
  2. Messenger RNA (mRNA)
  3. Ribosomal RNA (rRNA)

DNA and RNA contains sequence of genetic instructions that are essential for encoding cells, organs etc.

Genome

A Genome is encoded DNA genetic material of an organism which contains all the information needed for building and maintaining the organism. It is estimated humans contains more than 3 billion DNA base pairs in all the cells that have a nucleus. A genome contains set of instructions needed to build cells. Each one will have two types of

Genome sequencing and matching helps the analysts in predicting and matching like DNA. It is nothing but decoding genetic sequence in the form four letters A C G T. With newer technologies, sequencing became very cheaper when compared a decade ago.

Scientists uses genome compositions to study evolution history of genomes by comparing the proportion sizes of repetitive DNA and non-repetitive DNA.

Transcription is a process of creating a copy of mRNA (messenger RNA) from a DNA gene sequence. This mRNA enters cytoplasm after leaving cell nucleus. Cytoplasm direct protein synthesis according to encoded instructions stored in mRNA.

DNA contains two strands sense and antisense. mRNA is actually a single stranded unlike DNA and a compliment of antisense strand of DNA (template strand).

Transcription is done with the following steps

  1. Pre-initiation –
  2. Initiation
  3. Promoter clearance
  4. Elongation
  5. Termination

There is a process called reverse transcription in which RNA is transcribed into DNA (opposite of DNA to RNA). This behaviour usually found in viruses such as HIV etc.

Translation

Translation is a process of decoding and translating instructions from messenger RNA (mRNA) to direct protein synthesis. It converts gene sequence to amino acids sequence with the help of ribosomes and transfer RNA which in turn forms proteins.

Translation is done three steps

  1. Initiation
  2. Elongation
  3. Termination

Detailed steps involved in translation

  1. DNA transcribes genetic information by creating mRNA
  2. mRNA leaves cell nucleus and enters into cytoplasm
  3. mRNA carries genetic instructions from chromosomes to ribosomes
  4. Ribosomes assembles and translates genetic information to sequence of amino acids provided by tRNA
  5. A protein is formed based on amino acid sequences

DNA replication

DNA replication is process of replicating two identical DNA helices from the original DNA helix. This process is required in every living organism to carry out the following functions

  1. To build and regulate the cell from the encoded genetic information
  2. Genetic information transmission from one generation to other

The replicated helices are called as daughters and original DNA helix is called as parent. Parent strand is divided into two strands and a complimentary strand is created for each separated strand thus forming a daughter. This process is called as semi-conservative because each daughter contains one parent strand and one complimentary strand of parent strand.

By studying DNA replications, researchers were able to find the relations between certain disease behaviours. A recent example of this type of study is presence of DNA replication stress in human cancers. Human cancer is characterized by genomic instability. From the study, it was proved oncogene-induced DNA replication stress rises genomic instability in human cancers (increases deletions in common fragile sites). As a result genome copy number changes.

In the next part, I’ll discuss various algorithms and tools used for DNA analysis.

EMR and PHR for use in hospitals

An EMR is an electronic health record system that keeps track of patient’s medical history specific to particular provider. It’s a digital version of paper charts maintained by providers. People who are in patient care(doctor, clinician, radiologist, pharmacist etc.) will access EMR to view and update medical records frequently.

An EHR is an electronic health record system that keeps track of patient’s medical history from more than one providers.

A Personal health record (PHR) is a tool used to collect, track and share past and current about your health or the health of someone in your care.

EHR and PHR are similar in nature (conforms to interoperable standards) but with some differences. EHR fully managed by providers whereas PHR is fully managed, shared and controlled by patient and can aggregate data from multiple sources. EHR’s are available to multiple providers without patient consent whereas PHR is available only on patient’s consent.

PHR are of two types based on who owns and controls the data, tethered PHR and interoperable. Tethered PHR is linked with EHR of multiple providers whereas interoperable PHR is independent of health providers and are more specific to the patient.

Microsoft Health Vault PHR for use in hospital

Hospitals maintains patient’s health records with EMR software which are fully controlled and managed by them and are specific in nature. This type of record management unless implemented part of EMR software have the following limitations when addressing patient’s needs. Most EMR’s available in the market doesn’t provide these features and are expensive to develop.

1) Lack of co-ordinated care of patient

The people engaged in patient care often have to access latest updated patient’s information for quick diagnosis and preventive medication. This information may come from various sources such as health devices, external health providers, and care team (doctors, clinicians, and radiologist).

2) Lack of sharing patient’s health records with other health providers

When patient attends another health provider, sometimes patient’s medical history from various hospitals attended is required to diagnose medical conditions.

3) Lack of patient’s ability to access medical history at any time

Patient have to access last hospital visit information and view medical history from time to time.

4) Lack of access to patient’s medical histories from different hospitals at one place

Patients may visit more than one hospital in their life time. With each visit, patient medical information is recorded. These records are not easily accessible from each provider to aggregate and store them at one place.

5) Lack of real time health monitoring updates from patient and care team

Often patient have to be monitored for chronic conditions with health devices such as blood glucose monitor, blood pressure monitor, heart rate monitor, pedometer etc. for diagnostic purposes.

Why PHR is preferred than EHR for addressing patient information needs inside and outside hospitals

Hospitals when addressing patient information needs to overcome the EMR limitations, usually can adopt EHR or PHR. EHR is specific to one or more providers and doesn’t provide interoperability with other hospitals. Still a patient can view and schedule appointments with EHR but restricted from doing any updates to their health information records.

I studied some research papers of some EHR implementations in hospitals, the results are as follows

· Hospitals were more likely to have implemented EHR if they were Larger Institutions, major teaching hospitals, Part of a larger hospital system, located in urban areas, or had dedicated coronary care units.

· No meaningful relationship was found between adoption levels of EHR and Ownership Status of the hospital in terms Public vs Private hospitals.

· Most commonly reported barriers were: inadequate capital for purchases (74%), concerns about maintenance costs (44%), resistance from physicians (36%), unclear return on investment (32%), and lack of staff with IT skills (30%).

· Among hospital that implemented EHRs, these factors were mentioned as having positive effects: additional reimbursement for EHR use (82%), financial incentives for adoption (75%), availability of IT implementation technical support (47%), objective third-party evaluation of EHR products (35%).

· Although adoption levels were low, a significant proportion of hospitals reported to have already used electronic format of laboratory and radiologic reports, radiologic images, medication lists, and some decision-support functions.

· Interoperability issues can also be noticed as barrier. Lack of health information exchange between hospitals has reduced the potential value of these systems.

· From a policy perspective, creating incentives for use of EHRs and creating disincentives for not using these systems can be a potential facilitator.

· Finally, it is important to notice that this study was focused on adoption levels of EHRs in US hospitals, and did not study the actual effectiveness of these systems.

PHR addresses patient needs more than EHR. It helps the patient to keep latest up-to-date information collected from various sources at one place.

Based on my study on PHR case studies, some of the PHR findings are

· Laboratory test results were the most commonly used feature. Scheduled visits, medical conditions, and current medications were among other frequently accessed features.

· Test results were populated to PHR with a delay of ten days to allow clinician review prior to patient access. However, it is concluded that patients want results to be simultaneously populated in their PHR.

· In terms of clinical information, Provider Profiles were the most accessed pages.

· More than 80% agreed that the PHR helped them manage their medical problems, get better prepared for their scheduled visits, and take charge of their healthcare.

· Although more than two-thirds of patients agreed the information was accurate and complete, a significant number of patients believed inaccuracies in current medications (25%) and medical conditions (32%).

· It is observed that patients desired PHR as a convenient tool of information exchange, and found it useful, particularly for laboratory test results, medication list, medical conditions lists, and links to information resources.

Why Health Vault PHR

There are several PHR solutions available in the market. Currently Health Vault PHR is the best PHR solution among the other PHR solutions. My selection of Health Vault solution is based on the following reasons for the evaluation

· Free with no licence fee but with affordable integration costs

· Bi directional (two way) updates with EMR

· interoperable with standards

· Cloud based scalable web solution

· Accessed through various mediums and devices such as tablet, mobile, health device, web services.

· Integrated with 20+ health devices

· Secure communication between parties

· Patient centred with controlled access

· Extensible with custom applications and services

· Customizable local storage

· Pluggable authentication providers such as Open ID providers specific to hospital

I decided to use triangular model evaluation framework for the evaluation of Health Vault application for use in hospitals.

S.No

Criteria

Description

1

Organisation

Refers to hospital

2

Provider user

Refers to individual service providers in the hospital such as doctor, clinician and radiologist

3

Technology

Refers to Health Vault PHR

4

Patient needs

Refers to patient needs inside and outside hospital

I used some ratings based on functionality and accessing information in each criteria

1) Fully implemented 2) Partially implemented 3) Not implemented

Feature

Rating

Provide functionality to import or export Continuity of care document (CCD) and Continuity of care (CCR) documents

1

Secure authentication

1

Accessible via various mediums and devices (tablet, mobile, web)

1

Adheres to privacy principles

2

Ability to view and store medication history

1

Ability to view and store DICOM images

1

Ability to view and store family details

1

Ability to view and store miscellaneous files

1

Ability to view and store Allergies data

1

Ability to view and store immunization records

1

Ability to add and maintain health devices used for monitoring

1

Ability to maintain health profiles

1

Ability to share and print profiles

1

Ability to view and store procedures

1

Ability to view and store various health measurements

1

Ability to view access and update history

1

Ability to view and store family details and contacts

1

Ability to share and import information through email

1

Health Vault case studies

I have studied case studies of some hospitals using EMR software and integrated with PHR applications. The underlying principles and architecture is same for every PHR. Thus, I collected and studied some research papers on PHR general use in hospitals not specific to Health Vault.

Few hospitals who integrated Health Vault PHR with their EMR software as listed below

1) Maudsley NHS Foundation trust , UK

Maudsley foundation trust is the largest mental health service with over 35000 patients in Europe. Maudsley implemented a project called MyHealthBox which includes Health Vault integration to provide Summary Care Record to all patients

2) Mason General Hospital, WA, US

MyMasonHealth is a patient online solution implemented at Mason general hospital which integrates Health Vault with existing EMR using Microsoft Health Vault community connect to engage patients with improved experience in emergency rooms and clinics.

3) Brooks rehabilitation, Jacksonville, Florida, US

Brooks rehabilitation implemented a project Brooks Health Connect which integrated Health Vault with existing EMR. At Brooks, 90% of patients comes from referring acute care hospitals and are placed in various care settings within first 60 days. To improve patient experience and reduce the times between the team, Continuity of care solution is required to facilitate.

4) Steward Health Care System , Boston, US

5) Lucile Packard Children’s Hospital , Stanford, US

Lucile Packard Children’s hospital is a major referral center for severely ill children. The patients who visit the hospital are referred by Primary care provider outside LPCH are at 90% of overall visits. The remaining 10% patients visit directly to the hospital and its clinics. Hospital receives patient referrals from over 30 states. LPCH implemented an interoperable PHR like Health Vault to overcome the issues related to sharing and co-ordinated care.

6) PeaceHealth – St. Joseph Medical Center, Bellingham, Washington

Comprehensive preregistration and discharge process using HealthVault community connect.

Concerns

Some concerns below related to usage of Health Vault PHR (or any general PHR) in hospitals, most of them addressed by industry expects

PHR records may not be accurate with current health status

I agree patient can modify health records which may not be true with current or past health history. Hospitals should not fully depend on PHR information. The main use of PHR is to provide up to date information of patient’s last visit and scheduling appointments. In my study, all the hospitals who integrated Health Vault PHR already implemented bi-directional updates with EMR and health vault. This means anything that is recorded in EMR will be synced to Health Vault and vice versa. On patient’s next visit, doctor access patient information from hospital EMR not Health Vault directly.

But if the patient visits another hospital (not linked to previous hospital) by modifying health vault information which is rare and if there is no record that is pointing to previous hospital, new hospital may fail in collecting previous medical history and may depends on Health Vault information.

Patient’s privacy

Health Vault or any other interoperable PHR is a patient controlled health record (PCHR). Patients can allow or deny access to their health records to any provider user at any time. Every hospital access is different and acted as a separate client for accessing the data.

Information Security

How safely and securely information communicated between various stake holders through Health Vault.

The communication between Health Vault and other parties is always secured and encrypted using industry standard protocols. Health Vault communication mainly done by patient, EMR system and provider users through https protocol and email.

Health Vault is a cloud deployed solution accessed by anyone using secure hypertext transfer protocol (https) through a web browser. Https is a standard secured protocol used by everyone and is done through digital certificates. Encryption and decryption done through private and public keys. At one end, the information is encrypted by a private key and other end the information is decrypted by public key. Client apps and services also have to do communication using https protocol to connect to Health Vault cloud.

Email is the other form of communication used by provider users. This communication is done using direct messaging protocol. Direct messaging protocol is a standards protocol which encrypts and secure a message. Each health vault user is allocated with a direct project email address when registering a health vault account. Currently Microsoft is offering this feature only for users registered in US instance.

References

Rebecca Todd, Maudsley launches Health Vault based PHR, 2012, E-Health insider (UK),

Arash Anoshiravani, Gregory Gaskin, Ed Kopetsky, Christy Sandborg, and Christopher A. Longhurst, Implementing an Interoperable Personal Health Record in Pediatrics: LessonsLearned at an Academic Children’s Hospital, 2011, J Particip Med

Health Systems Choose Microsoft HealthVault Community Connect to Improve Care Coordination, Engage Patients and Families, 2011, Microsoft

Lingxia Liao, Min Chen, Son Vuong, Xiaorong Lai, Novel Web-enabled Healthcare Solution on HealthVault System, 2012, Dept. of Computer Science, Univ. of British Columbia, V6T 1Z4, Canada

Bruno Alvesa, Henning Müllerab, David Godela, Omar Abu Khaleda, Michael Schumachera, Interoperability prototype between hospitals and general practitioners in Switzerland, 2010, University of Applied Sciences Western Switzerland (HES-SO), Sierre & Fribourg, Switzerland and Medical Informatics Service, University & Hospitals of Geneva, Switzerland

Nhan V Do, Rick Barnhill, Kimberly A Heermann-Do, Keith L Salzman,Ronald W Gimbel4, The military health system’s personal health record pilot with Microsoft HealthVault and Google Health, 2011,J Am Med Inform Assoc

Care Coordination Approaches with Microsoft Technologies, 2011, Microsoft

New Microsoft Health Solution Connects Hospitals with Patients and Referring Physicians to Improve Coordination of Care, 2010, Microsoft

Microsoft Health Vault https://www.healthvault.com/au

http://blogs.msdn.com/b/wwhealthit/archive/2011/02/28/microsoft-healthvault-community-connect.aspx

http://www.med.umich.edu/him/myphr.pdf

http://www.healthit.gov/policy-researchers-implementers/direct-project

TETHERED PHR AND INTEROPERABLE PHR

A Personal health record (PHR) is a tool used to collect, track and share past and current about your health or the health of someone in your care.

PHR’s are categorized into two types based on its data ownership and control

1) Tethered PHR

  • Linked to EHR of multiple providers
  • Provider owns and manages patient information
  • Extension of the provider’s health system EMR
  • Allows the patient to view information stored in EMR
  • Allows the patient to communicate via email or online appointment systems
  • Patients cannot share information electronically with outside providers
  • Patients cannot import and integrate their data from external sources

2) Interoperable PHR

  • Patient owns and manages his own health information
  • Stored in a central repository, accessible to all on consent
  • Electronic linkages with multiple providers, health systems and pharmacies
  • Integrated with provider’s health system EMR
  • Easily accessible and controllable
  • Patients can share information electronically with outside providers
  • Patients can import and integrate their data from external sources

ASP.Net Web API 2 controller custom content negotiation

By default, ASP.net web api 2 automatically  delivers xml and json content types without any explicit serialization in controller with the help of content negotiation (conneg).

For example if your controller defines a default Get method that returns some object, on client request this object may be returned as xml or json string without adding explicit serialization code inside the method.

public class MyController : ApiController
{
//   Request uri /api/My/1
public Resource get(int id) 
{ 
  return new Resource{ Name="Raj" }; 
}
} 
//where Resource is defined as below 
public class Resource {
 public string Name {get; set;} 
}

When the client requests uri /api/My/1 with header Accept (or Content-Type) set to ‘application/json’, web api returns json representation of Resouce object. If the request header Accept (or Content-Type) set to ‘application/xml’, then controller returns xml representation of Resource object. 

Here No explicit serialization is required for json and xml. If any media type other than json or xml, then custom MediaTypeFormatters can be used. These custom formatters extend either BufferedMediaTypeFormatter or MediaTypeFormatter with some overridden methods and are configured inside WebApiConfig Register method.

  public class CustomTextFormatter : BufferedMediaTypeFormatter
    {
        public CustomTextFormatter()
        {

	    SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/mytype"));
            SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/mytype"));

	    // Important to add the below code otherwise if the client request doesn't contain
	    // any encoding header, a 500 server error will be thrown
            SupportedEncodings.Add(new UTF8Encoding(false, true));
            SupportedEncodings.Add(new UnicodeEncoding(false, true, true));
        }

        public override bool CanReadType(Type type)
        {

            return type == typeof(Resource);
        }

        public override bool CanWriteType(Type type)
        {
	    //Ensure we are serializing only for Resource object
	    // if more types to be allowed, add the conditions
            return type == typeof(Resource);
        }

        public override void WriteToStream(Type type, object value, Stream writeStream, HttpContent content)
        {
            Encoding effectiveEncoding = SelectCharacterEncoding(content.Headers);

            using (StreamWriter sWriter = new StreamWriter(writeStream, effectiveEncoding))
            {
                var str = MyCustomSerializer.SerializeResourceToMyType((Resource) value);
                sWriter.Write(str);
            }
        }
    }

By default , all the configured  formatters will be applied to all the controllers defined in the project.

  public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

	    //adds a custom formatter to api formatters list
            config.Formatters.Add(new CustomTextFormatter());

        }
    }

What if you want to restrict custom formatter to only one controller. A work around for this scenario is to  use a controller attribute with the implementation of Initialize method of IControllerConfiguration interface.

 public class CustomTextTypeAttribute : Attribute, IControllerConfiguration
    {
        public void Initialize(HttpControllerSettings controllerSettings, HttpControllerDescriptor controllerDescriptor)
        {
          
	    //Add the custom formatter at first (or simply add to the list)    
            controllerSettings.Formatters.Insert(0,new CustomTextFormatter());

        }
    }

Now add this attribute to your controller

[CustomTextType]
public class MyController : ApiController
{

if the client requests uri /api/My/1 with header Accept (or Content-Type) set to ‘application/mytype’ (or ‘text/mytype’), our custom formatter will be invoked.

image

if a different controller url requested with the new content type ‘application/mytype’, then you may get default configured formatter (the first formatter in the formatters) or a 406 error if no formatters configured.

Windows phone 8 App vehicle stamp duty calculator

Today I have published my first app on Windows phone store, a comprehensive vehicle stamp duty calculator for calculating vehicle stamp duty rates for all the states in Australia. I think presently there’s no windows mobile app to do the same. 

Access store app at

http://www.windowsphone.com/en-au/store/app/au-vehicle-stampduty-calculator/35d0b2fd-2eed-4d42-bb14-029c0b0a3b57

Few screen shots below

imageimageimageimageimageimageimageimage

* Buttons colors are based on phone theme accent color.

Currently I’m working on other versions,  Web (using ASP.Net MVC), Windows store, Android and IPhone ( using Xamarin Studio in C#).

Extending MVC Ajax Form

In this post, I’ll explain and demonstrate how to extend MVC Ajax form helpers with the following functionality:

  1. Automatically create an ajax target element when no UpdateTargetId is provided.
  2. Auto-refresh a form after a period of time, say 1 minute.

Here, I’ll assume that you have a basic understanding of how to work with MVC Ajax forms.

If not then read the “Introduction to MVC Ajax forms” section below, otherwise skip it and go to the section “Extending Ajax form helper”.

1. Introduction to MVC Ajax forms

In MVC, to place elements in a form, the Html.BeginForm helper method is used.

@using(Html.BeginForm(“Method”,”Controller”)

{

}
To enable Ajax capabilities for your form (post to and refresh from the server without refreshing an entire page), do the following:

  1. Create a partial view for the form
  2. Create an action method that returns the partial method above.
  3. Ensure “jquery.unobtrusive-ajax.js” is included in your main view or layout
  4. Use Ajax.BeginForm with Ajax options instead of using the Html.BeginForm helper method
  5. Render the partial view in your main view

 

The common Ajax.BeginForm method syntax is as shown below:

@using(Ajax.BeginForm(“Action”,”Controller”, RouteAjaxOptions, HtmlAttributes)

{

}
The required Ajax option is UpdateTargetId. It denotes the target element id in which the response is either updated to or inserted before or after, depending on another Ajax option InsertionMode.  InsertionMode is optional and set to replace by default. If no UpdateTargetId is provided then the Ajax response is never updated.

@using (Ajax.BeginForm(“ActionMethod”, “Controller”, new AjaxOptions { UpdateTargetId =”targetelementid”})

{

}
Generally the partial view is rendered inside the update target element in the main view. It really depends on the situation.

When the Ajax form is submitted, the action method returns HTML from a partial view and the response is updated in or inserted before or after the UpdateTargetId element.

2. Extending Ajax form helper

In the example project, I’ll demonstrate how to handle a MVC form without the UpdateTargetId option and Auto Refresh the form with randomly generated background colors from the server after some time period. All this using custom form helper methods.
clip_image001

  1. Create a basic MVC4 project. A project will be created without any controllers and views other than layout and view_ start views. In VS2010, no control and views are created.
    clip_image002
  2. Copy the Helpers directory from the source code to your project’s main directory.
    clip_image003
    I have added:
    a) A new AjaxOptions object that inherits System.Web.Mvc.Ajax.AjaxOptions and extended with properties RefreshTime
    b) A new Ajax extension helper method BeginFormEx that takes a new extended AjaxOptions object instead of System.Web.Mvc.Ajax.AjaxOptions
    Ajax.BeginFormEx(string action, string controller, RouteValueDictionary routeValues, AjaxOptions options, RouteValueDictionary htmlAttributes);
    Also added various overload methods for the method above.
  3. Copy “jquery.unobtrusive-ajax.js” to your scripts folder. This updated file contains extra script to handle required functionality.
  4. Copy “FooModel.cs” from the source code to your project’s Models directory. This model holds CurrentColor, PreviousColor and RefreshTime values. 
  5. Add a new partial view “MyForm” in your project shared views folder and add the following code.
    clip_image004
  6. Add a new (update if it exists) view Index.cshtml in the Views/Home directory. This will be the main view that displays the preceding partial view MyForm. Add the following code.
    clip_image005
  7. Add a new controller (or update if it exists) HomeController.cs in Controllers/Home directory. This controller will handle a main view and partial views. Create two methods, one for the main view Index and another to handle the MyForm post.
    clip_image006
  8. All done, compile and start the project.

You’ll see the form background color will be changed every 3 seconds. Try with various timings in the Refresh Time text box(1s= 1000).

In this article I have demonstrated how to extend MVC ajax helpers and how to auto-refresh an ajax form after a period of time.
clip_image007

Web based Vehicle Stamp duty Calculator (MVC5+BootStrap)

I have developed a new responsive website(http://www.calc.net.au)  using asp.net mvc5 and bootstrap for hosting web based tax tools such as vehicle stamp duty calculator.

This website serves as a common place for all the types of AU tax calculators and their web API’s. It will host other calculators ASAP like mortgage calculator, property stamp duty etc.  and still under development.

I have deployed web based vehicle stamp duty calculator on this website and can be accessed directly with url http://www.calc.net.au/vehicle/stampduty

Here few screen shots

imageimage
image

 

image image

Reading WinRT component embedded resource file in windows 8 store javascript app

A WinRT component can used to include some common code along with embedded resources that can be reused in store app irrespective of language in which it is developed like C#, JavaScript etc.
In this article, I’ll explain how to read a WinRT component embedded resource file from JavaScript app. App reads content from embedded resource and replace your page content with new content.

1. Create a WinRT component

1. Create a new windows store apps class library or WinRT component say with name ‘ExampleLib’.
WinRT component

2. If it is a class library, open its properties and change output to WinRT component.

Class library settings

3. Add a text file say ‘Data.txt’ in the project root folder with some text and change to embedded resource from its properties.

Embedded resource

4. Add a new C# code file ResHelper.cs in the project root folder and add the following code in that

using System;
using System;
using System.IO;
using System.Reflection;
using System.Threading.Tasks;
using Windows.Foundation;

namespace ExampleLib
{
    public  sealed class ResHelper
    {
       static async Task<string> ReadResourceAsync(Assembly assembly, string resource)
        {
            string xml;
            using (var stream = assembly.GetManifestResourceStream(resource))
            {
                    using (var reader = new StreamReader(stream))
                    {
                        xml = await reader.ReadToEndAsync();
                    }
            }
            return xml;
        }
        public static IAsyncOperation GetConfiguration(string fileName)
        {
            return (ReadResourceAsync(typeof(ResHelper).GetTypeInfo().Assembly, fileName)).AsAsyncOperation();
        }

    }
}

}

2. Create a windows store app in javascript

1. Create a new windows store app under language javascript (blank app is fine)
2. Add reference to ExampleLib
3. Open default.js and add the following code in activated.

args.setPromise(WinJS.UI.processAll().then(function () {

//call getConfiguration method with fully qualified
//file name (including dll name, folder path if any and file name)
ExampleLib.ResHelper.getConfiguration("ExampleLib.Data.txt")
.done(function (result) {
document.body.innerText = result;
}, function (err) {
document.body.innerText = err;
});

}));

Complete solution looks like as below

Projects

All done, deploy and run the app, now you’ll see embedded resource content as your main page content. Try with invalid file name; you’ll see an error message

you can download solution from here ExampleApp

Using SkipIf with Aspose words for .Net

Aspose words for .Net doesn’t support word field skipif to skip some merge fields between tablestart and tableend i,e skipping rows based on some condition.

Here, I’ll explain how to include skipif common functionality  with custom merge field in the word document.
The custom skipif merge field syntax should be as below

skipif:tablename:condition  

where condition must be a valid t-sql where clause and use ~ for spaces if any. Skipif can be used at any position and for any table. If you use multiple skipif’s for the same table, the last skipif will be considered ignoring all the previous skipif’s.

Ex:

if the table name is productstable (provided with tablestart: and tableend:)

skipif:productstable:price>0   (or in alt f9 view, { MERGEFIELD skipif:productstable:price>0 } )

skipif:productstable:price~in~(100,200,300,400)

1) Define a method ApplyFilters that takes two parameters, data set and aspose document.


DataSet ApplyFilters(DataSet ds, Document doc)
        {
            var fieldNames = doc.MailMerge.GetFieldNames().ToList();
            var newDs = ds.Clone();
            var skipIfs = fieldNames.Where(x => x.ToLower().StartsWith("skipif"));
            if (skipIfs.Any())
            {
                foreach (DataTable table in ds.Tables)
                {
                    foreach (var s in skipIfs)
                    {
                        var sp = s.Split(":".ToCharArray());
                        if (sp.Length > 2)
                        {
                            var where = sp[2];
                            if (!String.IsNullOrWhiteSpace(where))
                            {
                                DataTable newTable;
                                where = where.Replace("~", " ");
                                var skipRows = table.Select(where);
                                var rows = table.AsEnumerable().Except(skipRows);
                                var dataRows = rows as List ?? rows.ToList();
                                if (dataRows.Any())
                                {
                                    newTable = dataRows.CopyToDataTable();
                                }
                                else
                                {
                                    table.Clear();
                                    newTable = table;
                                }
                                newTable.TableName = table.TableName;
                                newDs.Tables.Remove(newTable.TableName);
                                newDs.Tables.Add(newTable);
                            }
                        }
                    }
                }
            }
            return newDs;
        }

2) Define a class that inherits IFieldMergingCallback and implement FieldMerging method


public class HandleSkipIfField : IFieldMergingCallback
    {
        void IFieldMergingCallback.FieldMerging(FieldMergingArgs args)
        {
            if (!String.IsNullOrWhiteSpace(args.TableName))
            {
                var fieldName = args.FieldName;
                if(fieldName.ToLower().StartsWith("skipif"))
                {
                    args.Text = "";
                }
            }
        }

        void IFieldMergingCallback.ImageFieldMerging(ImageFieldMergingArgs args)
        {
            // Do Nothing
        }
    }

3) Add below code before firing executewithregions


//Add below 2 lines before executewithregions
doc.MailMerge.FieldMergingCallback = new HandleSkipIfField();
var dataSource = ApplyFilters(ds, doc);


doc.MailMerge.ExecuteWithRegions(dataSource);