Beyond Hidden fields with ASP.Net

ASP .Net

ASP .Net

As we all know hidden fields are used to store a temporary value that will be needed on the page at a later stage which is available only on the code behind. Even asp.net uses hidden field to store View State. It is a common practice among programmers to include one or more hidden fields on the page as and pass values to and fro on the page.

Problem with Hidden Field

While rendering hidden filed, asp.net changes the ID attribute of the control and it comes up with something similar to “ctl00_ContentPlaceholder1_ListView1_ctrl0_Label1″.

Since the server control HiddenField does not support a CssClass attribute, we can not assign a class to the control. While developing asp.net they might have though why wold someone want set and style to a control that is not visible on the page. Valid question; but we will end up with a problem while accessing the value from such a hidden field using jQuery. Here is a nice solution for that problem, which generates a friendly ID for the hidden control.

Problem with multiple Hidden Fields

We add a new hidden field as and when needed on the page. But what if there is a situation where in you will need to store mare than 5-6 temporary values on the page? Poor man’s solution would be to use a delimiter based string, split and use the string as and when needed. But the solution that I am proposing is much better and simpler and extensible.

Beyond Hidden Fields and welcome JSON

The solution uses a JSON object to store the temporary values.  All you do is define an anonymous class with appropriate properties and values, pass it on to an extension method of Page class. The page extension method returns a script block with the json object; call a register script method on the page and you are done. Here is the code:

public static void RegisterPageScript(this Page currentPage, object data, string variableName)
        {
            var configString = JsonConvert.SerializeObject(data);
            if (!string.IsNullOrEmpty(configString))
            {
                var pageScriptTag = string.Format("< script type=\"text/javascript\"> var {0} =  {1} ", variableName, configString);
                currentPage.ClientScript.RegisterClientScriptBlock(Type.GetType("System.String"), "pageSettings", pageScriptTag.ToString());
            }
        }

How to use this method? Here is the code:

var pageSettingsObject = new { Prop1 = "some text", Prop2 = 1 };
this.Page.RegisterPageScript(pageSettingsObject, "PageSettings");

Run the page and take a look at the rendered page source. You will notice that PageSettings is a javascript variable which can be directly accessed using javascript and more over it is a javascript object and hence a set of such values are stored in an object. You can easily access the values needed. For example, open up FireBug, go to console, and try something like this

alert(PageSettings.Prop1);

The value is available for javascript/jQuery… :)

What if you would like to send some more temporary values to server side code and want to change couple of values in the PageSettings object? Very much possible, as JSON object is a dynamic object, you can add a new property as and when needed. Just say

PageSettings.Prop3 = "blah blah...!"

Now the JSON object stores that too. You can again verify the same on firebug console. If you would like to send the whole JSON object to server side, convert the JSON object in to string, set it to a hidden field (a server control) . Here is the code:

 

$('#SomeHiddenField').val(JSON.stringify(PageSettings));

This new approach allows you to structure your code better and is easy to maintain rather than adding a bunch of silly looking hidden fields and accessing them.

 


Facebook introduces HTML 5 Resource Center for Developers

HTML5_Logo

Some time back Facebook announced a new HTML5 Resource Center for developers. The main reason behind this is it give ample of resources to developers for building great experiences across multiple platforms. It features information about developing web apps, games, testing web apps on mobile and PC and so on. In a way it acts as a great source of information for developers who are diving in to HTML 5. The company has also created a group HTML5 where you can join to share and get more information about facebook and HTML5.

Build the Future With HTML5

Build the Future With HTML5

Why was it created?

Most of the applications today are becoming available on the internet and the devices which access such applications vary from smart-phone, tablets, computers, TVs and more. Each such devices come with their own resolution, browser capabilities and limitations. It becomes very hard for developer to maintain different versions code for different browsers and different devices. HTML5 enables developers to work with a single code base which runs on all devices.

Facebook has more than 350 millions users on mobile. Applications can reach all such users by supporting mobile devices. Utilizing HTML5 and related technologies becomes crucial for surging in to such a market. Facebook’s endeavor helps developers across the world to accelerate innovation and build better user experience of cross-platform web apps.

 What is in it for me..?

Facebook follows Build, Test, Distribute method for HTML5 web apps.

Build section has ample of tutorials and guidance for creating the applications, Games and more. You can check the Showcase to see what other developers are building with HTML5.

Testing the application on different environments is a crucial part of the development activity. Many a times testing takes more time than the real development. Testing section covers all such aspects in detail including different automated frameworks such as Selenium.

Distribution is the last part which is quite easy if the first two levels are completed properly. Information on distributing apps on different channels such as Chrome Web Store, Facebook on mobile, native app stores and more can be found in this section.

If you are planning to make applications in HTML5 or migrating existing web apps to support HTML5 then visit the HTML5 Resource Center to get a good starting point.

How To manage your emails with Outlook Web Access Rules

Outlook Web App

Most of use MS Outlook at work for exchanging emails. MS Outlook as we know is only a tool which connects to the mail server such as MS Exchange Server and helps us send and receive mails. All the Rules we define on Outlook are only client specific; if you close Outlook or if you shut down your computer, those rules stop working immediately.

Microsoft also provides a web interface for Exchange server which is used by most of the companies to give mail access to employees outside the company network. You can manage your inbox by creating filtering rules on the outlook web app.

Creating Rules with Outlook Web App

Creating a Rule on Outlook Web App will filter the mails as soon as it reaches the Exchange Server, before Outlook on your desktop gets the mail.

To set-up a Rule login to Outlook Web App, Choose Options on the right top and select “Create an Inbox Rule”.

Outlook Web App Options

Outlook Web App Options

You will land in a new page which allows to manage all Outlook Rules.

Outlook Web App Manage Rules

Outlook Web App Manage Rules

You can choose from many available options to create a new Rule.  Let us click on “Create a new rule for arriving messages…” which will give a new window to decide what to do with the arriving mail.

Outlook Web App Inbox Rule Creation

Outlook Web App Inbox Rule Creation

The list is quite exhaustive as you see above. You can choose any item in the “when message arrives” drop-down based on your need  and for each such item outlook asks for supporting input. For example if you choose “It was received from”, then outlook allows you to select an email address from your address book; if the email address  in not available on the address book, there is a text box to manually enter the same.

After deciding what to choose from the first drop-down, we have multiple options for “Do the following:” starting from moving it to a different folder to deleting the message before it reaches inbox. Once done, save the new Rule; from now on the new rule will be in action checking all the emails that flow to your inbox. Any existing Rule can be modified by choosing the “Details” button.

For advanced users, there is a “More Options…” link while creating or modifying a rule. It allows adding multiple actions for a Rule and to add exceptions for the rule. There is a check box at the bottom which says “Stop processing more rules”. Choosing the check-box will disable processing the email with any other matching rules.

Outlook Web App Inbox Rule Advanced Options

Outlook Web App Inbox Rule Advanced Options

 Shortcut way to Create a Rule

Creating a rule by choosing Options is one way; but there is  a faster way to create a rule. Just right click on the mail for which you would like to create a rule.

Create Outlook Inbox Rule Faster

Create Outlook Inbox Rule Faster

This will automatically choose the email address for the new Rule. Just select the action part and and save the Rule.

How to stop Google Analytics from tracking my own visits to my site?

Google Analytics Logo

One of the problem with Google Analytics is it tracks all visits to your website, which includes your visits to the website also. You would visit your website many times to check whether it is working as expected. But each such visit are tracked in GA which causes inaccurate tracking.

How do I stop tracking My visits?

There are a couple of ways in which you can disable GA from tracking your visits. But unfortunately none of them are strait-forward. We will see possible ways to disable GA tracking and you can choose the one which is most suitable for you.

Disabling GA tracking by making a Host Entry

Hosts file has IP address to Domain mappings.  The IP address “127.0.0.1″ points to localhost or the local machine. The idea her is to map  www.google-analytics.com to localhost. By doing this, all requests to GA server will end up pointing to the same system. That means you have disabled GA tracking on that machine permanently. Digital Inspiration has a good post on making host entry to disable GA tracking.

This approach has some down sides such as you are disabling the tracking for all websites visited on the machine. If you use multiple computers then host entry change has to be done on all the computers.

Those who are curious to know more about hosts file go through this article “What is the hosts file?

Excluding My visits in the tracking report

Another approach is to exclude my visits to the site from tracking report. This is done by including a filter for your IP address or a range of IP addresses.  Google has published a document “How do I exclude my internal traffic from reports?” which guides you through the process.

Using “Google Analytics Opt-out Browser Add-on”

After hearing all developer woes about disabling GA tracking for their own visits, google has finally come up with an add-on which does the job. You can download and install Google Analytics Opt-out Browser Add-on which tells the ga.js not to collect tracking data for the visits made from that browser.

Analytics Opt-out Browser Add-on

Analytics Opt-out Browser Add-on

The add-on supports Internet Explorer, Google Chrome, Mozilla Firefox, Apple Safari and Opera, so you can install the plugin on any of the browser and visit your website using the specific browser. If you wish to have it for all browsers, then there is an option to enable/disable to same.

DIY Reading Lamp

DIY Reading Light

Many of you should be having the habit of reading something before you go to bed. You might have already browsed around for a good reading lamp also. But there are only a handful of varieties available when it comes to reading lamps. When you look around for a reading lamp, any one of the following pops up:

Reading Lamps

Reading Lamps

I was also looking for a simple but useful reading light and came across a nice reading lamp and the best part is,  there is a video on how to make one for yourself.


 

Who made this nice reading lamp?

After watching the video you would definitely want to know who came up with this cool idea. All credit goes to Steve Hoefer, a globally recognized inventor and creative problem solver, who also runs Grathio Labs. He has posted couple of such cool projects on his blog.

Introduction to Google Dart – new Javascript alternative language

Dart Logo

Google announced its new programming language “Dart” at GoTo Conference in October 2011. Google highlights it as a language for “Structured Language for Web Programming”. Dart is a class based, optionally typed programming language. The language as such is not a replacement for Javascript, but offers a modern alternative for scripting in web browsers.

Why one more new language?

There are umpteen number of programming languages out in the wild each of which say problems faced by other languages have been addressed. Dart is a new addition to the stack which is intended to solve Javascript’s problems which can’t be solved just by evolving the language. Dart mainly concentrates on better performance and scale-ability.  We all know that developing feature rich heavy applications with Javascript is not so easy even though we have a couple of nice framework’s such as jQuery, Backbone.js, Knockout.js, Ext.js etc. and Dart addresses such limitations.

Dart’s design goals included: to be a structured yet flexible language, to be familiar and natural for programmers, and to meet high performance. We have many options for server-side language, but when it comes to browser we are limited to Javascript. Falsh was used earlier to do the same but now it is fading away due to many factors.

How will Dart help overcome problems of Javascript?

Dart has supports optional types; so you can  start coding without types initially and add types as and when needed.  If you declare types, Dart generates possible warnings – not errors. With existing languages, developer has to choose between static or dynamic languages which need heavyweight tool-chains and a coding style. Javascript doesn’t care whether you assign an integer or a string to a variable as it is weakly typed. Many a times this causes some hard to catch errors. Dart addresses this by providing enabling just enough type safety.

Dart is a structured language and allows to organize code in a modular style splitting it up in to different functions. This enables developer to write maintainable code and is easy to change that searching across a bunch of “if else” conditions in a single block of code. Dart is developed considering huge applications and large teams to build highly complex and scale-able applications. For example in javascript, code from all the

One big bummer with javascript is it tries to execute whatever code it can and as soon it can before even the DOM loads completely leading to undesirable effects. With jQuery developers always make sure that the functions calls go in to document.ready() function. Dart solves this problem by waiting till the DOM completely loads.

Compatibility

With enough of issues and unsupported features of javascript which is there in the field since they bygone age, we are moving on to a new language. Browser compatibility is always a concern as some times developers have to code for specific browsers. Dart can easily be compiled to javascript on the fly so it supports all the browsers that are around. Google Chrome comes with a native Virtual Machine which runs dart on the fly. Competing browsers can also implement the VM over a time. That depends on the popularity and utility of the language; now the language is very new and there is a long time for it to gain popularity.

Google is developing a cloud based IDE for Dart which possibly be the first Dart application would attract the crowd to jump in to the language.

Is it time for me to learn Dart?

Dart is in its early stage and it is quite difficult to say whether it is the next big thing that will happen on the client side programming. The language is pretty neat and very easy and provides many improvements over the limitations of Javascript. Right now the documentation provided by Google is very limited. There are not many tutorials available online  no books are available on Dart. If you want to explore the features, then the basic examples provided on Dart’s Home page would be enough. If you wish to use it in your next project, may be it is not the right time to start using it.

[Update]

Dart is already getting some traction..! Someone made a Dart to JVM bytecode converter called jdart which takes a Dart file as input and creates a .jar file. It is limited in features but who knows what comes up next..! So gear up now and start with Dart.

Searching Specific Site in Google Chrome

Chrome Logo

Google chrome address bar changed the way we search on the web.  We no longer have to visit a search engine to search; Chrome  searches on the default search engine directly and gives us the result. After Chrome even Firefox made the same change to its address bar (which no longer works on Firefox anyway).  I really like the address bar search as we never have to visit a search engine to get search results.

Specific Site Searching

Chrome also allows you to search in specific site. When you type in the name of the site, it will ask you to press tab to search in the site.

Chrome Specific Site Search

Chrome Specific Site Search

Here chrome is asking us to press tab just after typing “git” to search on github.com saving valuable keystrokes and saving us from searching the search box on the site.. :)

How to add a new site to “Specific Search”?

Chrome also allows to manage the sites  which support specific search. Just Click on the Tools button on the top right and choose Options. Or Click Here to land in to Options page. Under the Search section, click on “Manage Search Engines” and go to “Other Search Engines” section. You will see a  list of sites which are added already.

Add New Site to Specific Search

Add New Site to Specific Search

To add a new site, scroll to end, Type in a Site Title, keyword which you will type in the address bar to start the search and the search URL. Search URL will be the URL which the site uses to search with the search term as a query string. Enter “%s” as placeholder for the search parameter and you are done.

For example, let us add codeplex to our specific search list.

  • Enter Any Convenient title such as CodePlex in the first text box
  • Enter a keyword such as codeplex.com in the second text box.
  • To get the search URL, go to codeplex site, search for any random term, and copy the URL. Replace the search term on the URL with a “%s” (http://www.codeplex.com/site/search?query=%s&ac=8)
Now open up another tab by pressing Ctrl+T and type in codeplex.com on the address bar and see the result… :)

What is new with asp.Net MVC 4?

Model View Controller

Asp.Net MVC is around for quite some time and it has created some real waves among developers. Its first version was released in December 2007 and the recent stable release MVC 3 came in January 2011. MVC 3 comes up with lot many features which make development faster such as support for Dependency Injection, new templating engine called Razor Templates etc. MVC 4 moves further to provide better development environment.

What is asp.net MVC?

For those who are new to asp.net MVC, here is a small introduction: MVC is an architectural pattern which is popular for its most striking feature – separation of concerns. With MVC, business logic, user interface and the mapping between logic and interface fall in to distinct layers. One can build highly maintainable applications faster compared to asp.net Web Forms. To get a good understanding of asp.net MVC, watch this tutorial video “Building Applications with asp.net MVC“.

Features of MVC 4

Major improvements on MVC 4 fall in to supporting mobile devices or devices such as tablets in general which come with all possible screen size and resolutions.

  • The default template used to create the MVC site got a makeover and it looks more modern now. The  new template comes with adaptive rendering ability which makes the page look good on both desktop browsers and mobile browsers without any customization. The template uses Javascript to give richer UI.  Here is a sample of new MVC 4 template on desktop and mobile.
MVC 4 Desktop Template

MVC 4 Desktop Template

 

MVC 4 Mobile Template

MVC 4 Mobile Template

  • To check the mobile version of the page, either you can use a mobile emulator such as Opera Mobile Emulator or reduce the browser size.
  •  A new template for mobile/tablet specific sites “Mobile Application project ” is added to the template gallery. It is based on jQuery Mobile, building touch-optimized UI.
  • If an existing site is to be modified to support mobile devices, then “Display Modes” features helps to do that. Depending the on the browser from which the request is made, corresponding display mode will be activated to provide optimal browsing experience. It also provides a View Switcher feature to easily switch between different views.
  • Recipes and Code Generation in Visual Studio: Recipes framework  helps to write code-generation plugins, which you can be used to replace the built-in code generators for Add Area, Add Controller, and Add View. Recipes are deployed as NuGet packages to enable easy sharing with other developers in the team.
  • Task Support for Asynchronous Controllers: Now you can write asynchronous action methods as single methods to return an object of type Task orTask<ActionResult>.
  • MVC 4 also supports Azure SDK
Download and Install
Currently MVC 4 Developer preview is available for download.
It is also available via Web Platform Installer for both VS 2010 and VS 2011 Developer preview

How-To Synchronize bookmarks and Browser settings with Chrome

Google Chrome Logo

Google Chrome has become a popular browser faster than any other browser in the browser market. It’s success is because it’s faster than any other browser; be it loading pages or the time it takes to open. The best part is it has a lesser memory footprint while running compared to any other browser. In fact, Firefox is losing its market share to Chrome because of this one reason and Firefox considering this aspect seriously.

Apart from all its nifty features, Chrome has a very handy feature which allows you to synchronize all your browser settings and bookmarks. This enables you to download your settings on any computer irrespective of whether it runs on Windows, Mac or Linux.

Managing bookmarks and organizing them has always been troublesome. People have used simple browser favourites to on-line services such as xmarks. Advantages of xmarks is it provides an on-line interface to your bookmarks and it has add-ons for different browsers to enable sync across multiple browsers.

What can be synchronized?

Once you enable the sync feature, chrome instantaneously syncs all your bookmarks, bookmarklets, add ons, chrome themes, Apps, Saved passwords, preferences and auto-fills. You can actually configure what to sync and what not to sync, which will give you the ability to disable syncing  information such as saved passwords and auto-fill data.

How to enable Synchronization?

To enable synchronization, click on Settings button on the right top corner; choose Options. Select “Personal Stuff” on the right pan or you can visit this link to land in to the options.  Click on the “Set up Sync…” button.

Chrome Set up Sync

Set up Sync

Chrome will ask you to give your google account credentials. Once you give valid credentials and login, you will get a window which allows choosing between syncing all data and selective syncing.

Customize Sync Preferences

Customize Sync Preferences

You can either choose to synchronize everything or select the one’s which you want. If you enable synchronization for passwords, they will be encrypted by default; however you have an option to encrypt all your synced data also. Once done, click OK and that’s all. Chrome keeps all the data safely saved on google servers tagged with your google account.

To download your settings on any other computer such as your home PC, again go to settings and enable synchronization. Within few seconds, chrome will download all synced data stored on the server including your bookmarks, theme and add ons. If you make any changes to settings, those changes will be synced and when you open Chrome on the other PC which you had configured, such changes will be downloaded instantly.

How do I stop synchronization and clear my data?

You have already enabled sync but what if you want to get rid of all the data from google servers? Yes there is a way to do that through Google Dashboard. Visit Google Dashboard and scroll to “Chrome Sync” section, which displays details on the data synced and time at which last sync was done. Click on “Stop sync and delete data from Google” and you are done.

How do I restore default settings and clear synced data on google chrome?

You had synced your data on a PC but now you want to clear all synced data from Chrome but not from the server. There is no straight forward way to do it but there is a workaround for that.

Chrome creates a file called “First Run” under the application root or under the user’s AppData folder.

For Windows XP :

C:\\Documents and Settings\\UserName\\Local Settings\\Application Data\\Google\\Chrome\\Application

For Windows Vista or Later:

C:\\Users\\UserName\\AppData\\Local\\Google\\Chrome\\Application

When Chrome loads each time, it checks for the file “First Run”. If the file is not present, it launches the initial setup wizard; just delete the file. Next time when Chrome starts the setup wizard will beinitiated.

Real-Time Web Traffic analysis with Google-Analytics

Google Analytics Logo

Google Analytics has played a pivotal role in web traffic analysis for couple of years.  Since this service is available free of cost and  information is presented in an intuitive user interface, Google Analytics Tracking has become popular among web developers.

What is Google Analytics?

For those who are new to Google Analytics, here is a brief introduction to Google Analytics :  It is a web analytics solution which gives rich insights into website traffic and marketing effectiveness. With powerful, flexible and easy-to-use features you  analyze your traffic data in an entirely new way. By using Google Analytics, one can write better content with specific target market. You can have a look at the List of Google Analytics Features to get more specific idea on the capabilities of GA. Here is a nice video which gives you a guided tour of GA and how you can use it for effective marketing of your website.

 

Can I see what is happening to my website now?

Recently google improved GA to provide real-time traffic analysis. Last time when we are developing a custom GA tracking solution, it used to update the data once in 4 hours. Testing team had to wait 4 hours to see the tracking results. This was a head ache as they could not accurately verify the results in real-time.

Gogle Analytics Real-Time

Gogle Analytics-Real-Time

But guess what, google has provided real-time tracking facility now with the launch of “Google Analytics Real-Time” and it’s free. Real-Time site analytics is available through a set of new reports and this new feature is in Beta stage now. This feature will be available only the new version of GA. To switch to new version of GA, choose the New Version link at the top right corner.

If you do not see GA Real-Time enabled for you, you can sign up here for an early access since the service is enabled for only a select number of users.

With this new feature you can instantly analyze the impact of social media campaigns. You can tag links that you share on social media such as twitter or Facebook, you can instantly see how it is impacting the traffic. If you would like to tag your links and see the impact of social media, you can use the URL Builder Tool to do it.