Sunday, December 12, 2010

Pass and Use variables in ASP.net server to the client HTML or JavaScript code - Multiple ways

Any public variables available during the page load (page_load event) is usable as variables in the HTML code. Below are the multiple ways of using them.

Using ASP.net variables:
public partial class VariableTest : System.Web.UI.Page
{
    public string url = "http://www.google.com";
    protected void Page_Load(object sender, EventArgs e)
    {
       
    }
}
HTML Usage:
<a href="<%= url %>">click here</a>
Using Sessions:

These session variables might have loaded at any stage of your application. Even global.asax loading will do. Just make sure that they are available during page load.
protected void Page_Load(object sender, EventArgs e)
    {
        Session["newurl"] = "http://www.google.com";
    }
HTML Usage:
<a href="<%= Session["newURL"] %>">Click here</a>
Using Web.Config:
    Web.config file has the variable value as mentioned below.
<appSettings>
    <add key="newURL" value="http://www.google.com"/>
</appSettings>
HTML Usage:
<a href="<%= ConfigurationManager.AppSettings["newURL"] %>">Click Here</a>
Make sure that the namepsaces are referenced from your page. Otherwise you will have to change like System.Configuration.ConfigurationManager.AppSettings["newURL"]

Using the Variables in JavaScript
     Basically, all the above mentioned usages work like a string replace. So, you can even use it in javascript codes as shown below.
<a href="#" onclick="javascript:alert('<%= urls %>');return false;">Click here</a>
Using these variables in Server controls.
     Controls with server rendering enabled (runat="server") will not work using the methods mentioned above. Use Page.DataBind() to do the trick for you. Make sure that you are using <%# %> in this case

Server Code:
public partial class VariableTest : System.Web.UI.Page
{
    public string newurl = "http://www.google.com";
    protected void Page_Load(object sender, EventArgs e)
    {
        Page.DataBind();
    }
}

Designer Code:
<asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl="<%# newurl %>">HyperLink</asp:HyperLink>
OR
<asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl="<%# this.newurl %>">HyperLink</asp:HyperLink>


Wednesday, December 8, 2010

How to do a 301 redirect in ASP.net for permanently moved resources - Global.asax code changes

If you are here, you might already be knowing that 301 redirect is the standard way of telling your clients (browsers, usually) that a server resource or a page has been permanently moved to a new location. Since most search engines respect this code, they will make sure that your 301 redirects are duly noted in their indexes which results in accurate search results.

Here is one raw way of implementing this, using Global Application Class (Global.asax) file.

Pre-requisites
I'm assuming that you have a Global.asax file  in your specific ASP.net project. If don't, add it as a New Item. It will have already a place to handle Application level errors. The below code is the code, where you're going to implement the changes.

 void Application_Error(object sender, EventArgs e)
    {
        // Code that runs when an unhandled error occurs

    }
The Logic:
The idea is to trap the 404 error (this will occur since the requested page does not exists) and provide appropriate 301 redirect request as the output. The below code does just that. Refer inline comments for more information on what each line of code means.

The Sample Code:

void Application_Error(object sender, EventArgs e) 
    { 
        // Code that runs when an unhandled error occurs
        // retrieve the last server error
        HttpException he = (HttpException)Server.GetLastError();
        // check for 404 error
        if (he.GetHttpCode() == 404)
        {
            // implement the logic to decide whether redirect is needed
            if (Request.RawUrl.ToLower().Contains("oldpage.aspx"))
            {
                Server.ClearError(); // clear the existing server error, good to have for additional processing
                Response.Clear(); //clears the response cache, if some information already exists
                Response.Status = "301 Moved Permanently"; // set the 301 status header
                Response.AddHeader("Location", "newpage.aspx"); // set the redirect location
                Response.End();
            }
            
        }
    }

For simplicity sake, additional checks are avoided in the above code.

If more flexibility and control is needed, look for a good URL rewriter for ASP.net.

In case, if you're wondering what a Response.Redirect does, it's just a 302 redirect that says that the resource is found at another location, which is treated as a temporary redirect. For more information, refer the HTTP Status Codes at http://en.wikipedia.org/wiki/List_of_HTTP_status_codes

Saturday, December 4, 2010

Samsung Series-6 UA32C6900VR LED TV - My Experiences for far - Shock, Firmware, Remote Control Issue and Support Calls - Ups and Downs

Buying Process:
Well, the fight was tight between Sony's 32EX700/710 Series Model and Samsung UA32C6900VR for me to buy one. Even though the battle was won by Sony, due to a decent difference in the price in which it was offered, i ended up buying Samsung on Nov 01st 2010. Let's just say that buying part was satisfying enough.

The first event - The SHOCK
After two days, the Samsung technical guy came over, opened up the package and installed the TV. Immediately after, when i tried to plug in the USB drive at the back, i felt shock at the back panel. I took the tester out and checked to find out that each and every metal part, especially screws, at the back was giving a bright light in the tester. I called up the customer care and they told that someone will be send for. I tested my home for electrical problems and found everything (earthing and reversal of live and neutral issues) fine.

The technical guy came after a day was talking ----****. "There is always a signal coming at the end. It is not electricity. LED TV's will have that" etc etc. Since this was not technically convincing enough, i had to call the customer care again the next day and they connected me to the technical team. They told that it is by design and there will some voltage at the back which is below a safe threshold. I felt OK with the answer even though they didn't answer my question about the possibility of grounding these potentials at the back, so that these kinds of issues don't come up. They could have provided a 3-pin plug to accommodate this. Well, this issue was not big enough for me since i didn't know deep enough to decide on the technical feasibility. So, i started using the TV as they told and i have to tell you, it was performing well and i felt happy.

The second event - Firmware Upgrade
Before buying itself, there was this firmware already released. Since my TV was having an older version, i upgraded through USB and everything went fine.I saw minor enhancements in the UI.

The third event - Remote Control
Few times over the days, i noticed that the remote events are less responsive. After 3 weeks of usage, this issue became a major one. There were two remotes, one from the Set Top Box (Universal) and the other is the TV's original one. For both, the TV was not responding. Turning ON the TV was not a problem usually with the remote, it turned ON. Once the TV is turned on, the remote actions became pretty useless. I tried different things (making sure that the sensor is clean - removed the plastic wrapping, remote has good batteries, proper distance of 5-6ft is maintained, indoor lighting changes etc) that i know of, but nothing worked out. I have to again call customer care and report this issue. Now, within 2 hours technical guy is supposed to give me a call, But, 48 hours over and nobody called yet.

Conclusion:
Well, I guess we cannot conclude that the TV or the support is GOOD or BAD from any of these experiences, as you might have already figured out. But, it's just that i'm expecting a better quality from a technically superior (as it is said) commodity having a decent price, that too from a company well known in this arena. May be, it's just me!

Wednesday, December 1, 2010

Allow the user to enter new values in to the Dropdown controls like Combobox in web-HTML pages

Until this time, it was not easy enough to make a Dropdown accept new values too, from the user. It will always work based on the predefined list items only.

There is tiny add-on, built on JavaScript, that seems to solve this in a fairly easy way. With just few lines of JavaScript code, the plug-in was able to make the already existing Dropdown (input type set as Select) to look and work like a Combobox. There was no changes needed in the server code that processes the input from the user.

When compared to the jQuery AutoComplete control, this has minor disadvantages. I works only on dropdown controls, while jQuery control works based on multiple sources. But compared to AutoComplete control, this control makes the changes in the server control itself in such a way that there is absolute zero changes necessary in the server side and the changes will be up and running in few minutes.CSS attributes are also exposed so that the control UI can be changed as desired.

jQuery AutoComplete Control:
http://jqueryui.com/demos/autocomplete/

ComboDropdown Control:
http://combodropdown.info/samples.html

Friday, November 26, 2010

Port Forwarding in a separate modem and wireless router scenario using ASUS RT-N13U, Beetel and Airtel connection

The usual settings was not enough for my utorrent Web UI to get accessed publicly. There was additional settings to be done in the modem side. I was trying various settings until i find it all explained here at the below article.


All i had to do is to route the outside traffic to the internal router as mentioned, once the basic port forwarding was setup in the Wi-fi router.


Thursday, July 8, 2010

How to quickly switch between multiple Google accounts in Chrome?

Here is an extension for Google Chrome that can make logging into any of your Google Accounts pretty easy. The extension is named as Quick Google and is available here.
https://chrome.google.com/extensions/detail/cbgngpehipfmfmpjmhonhacgbkjpdidp

I have around 8 logins with Google and i had to enter them manually in all those login pages that i use daily. WIth Quick Google, i configured all those accounts and in just one single click, it logs me in and take me to a Google page where i can select the Google Services that i want use. Here is a screenshot from the website.



Essentialy, it works like a form filler, but specifically designed to work with Google's login pages. It works flawlessly and the Sign-in Assistant also seems to be useful for some services.

There are few cons too. The icons does not look that good and it looks like it will not work when Google changes their login pages as per the developer website. Hopefully, the google login pages will not get changed soon.

More information is available at http://sites.google.com/site/qgchrome/

Sunday, February 28, 2010

Replace all string values from a variable in a loop using JavaScript - Sample code

If you have looked at my other article, you already know how to replace all the matching string from a string variable. However, some times you will need to replace all the string values that are received from a variable.

This can be achieved by creating a Regular Expression object with the necessary variables and passing it to the regular replace method of the string. Below is the sample code.

var strToBeReplaced = "This 1 is a warning 2";
for (var k=1;k<3;k++)
{
    strToBeReplaced = strToBeReplaced.replace(new RegExp(k, 'g'), "message");
}
alert(strToBeReplaced);
//shows "This message is a warning message"


Wednesday, February 24, 2010

Convert or Replace carriage-return/New-Line/line-break/End-of-line characters in JavaScript

Even though this might seem simple, you might come across cross browser issues and other issues based on the pre-processing of the string from different programming languages. Let's forget all those and keep the below concepts in mind.

From JavaScript's perspective, the string can have "\r\n" as a whole OR "\r" only OR "\n" only. In most of the scenario, the string variable will be having \n at a minimum. Thus, considering all three possibilities, what we can do is this.

var newString = oldString.replace(/\n/g, "< br >").replace(/\r/g, "");

Note that the above sample code is using a Regular Expression match using "g", so that all the occurences will get replaced. Now, you can change the above logic as per your needs.

More Information:
For those who tend to confuse with all these characters, here is what it is in a nutshell. As an example, this is what gets stored in the variable when user press [ENTER] in the keyboard. The following are their representation as special characters.

\n New Line/Line feed
\r Carriage Return

Generally, UNIX systems will have "\n", "\r" will be used in MAC and a comibnation of "\r\n" will be used in Windows OS.

JavaScript replaceAll - replace all occurrences of a string with new string

During string replace, JavaScript replace() function replaces only the first occurence of the match. Use Regular Expression match to replace all the occurrences of the specified string. Regular Expression match can be specified by providing a "g" next to it, as shown below.

var stringVariable = "This message is a warning message";
alert(stringVariable.replace("message", "alert"));
//shows "This alert is a warning message"

alert(stringVariable.replace(/message/g, "alert"));
//shows "This alert is a warning alert"


Friday, February 19, 2010

LIC premium will not be payable using BillDesk through SBIcard.com

I had a BillDesk account which was accessible through sbicard.com. One of my LIC policy was added on that account. The payment notification through email and SMS were working fine.

When i went to add one more policy, i was unable to find LIC listed to select. Upon contacting BillDesk, they said that the option to pay for LIC has been removed and they will not processing the payments for the already existing LIC policies too. Unlucky me!

Not sure whether this is applicable all over India.

Thursday, February 18, 2010

ASP.net menu control does not render properly in Chrome and Safari

This was one major problem in the ASP.net website that I was working on. The control rendered properly in IE, Firefox and Opera EXCEPT Chrome and Safari. The initial guess was that there is something going wrong with my doctype settings and the CSS styles being applied.

A quick search over the net revealed that changing the Page.ClientTarget to "uplevel" will solve the issue; and it worked for few. But this didn't work for me.

Then there was a solution changing the web.config for adding browserCaps in the system.web section, which also failed for me.

Then, at last, there was solution adding .browser file to App_Browsers folder which worked for me.

Here are the steps.
1. Right click your project folder to add an ASP.net folder "App_Browsers".
2. Click "Add New" and create a browser file named Chrome.browser
3. Put the following code in that file after commenting the existing code.

<browsers>
<browser refID="safari1plus">
<controlAdapters>
<adapter controlType="System.Web.UI.WebControls.Menu" adapterType="" />
</controlAdapters>
</browser>
</browsers>

References:
http://www.google.com/support/forum/p/Chrome/thread?tid=7506cca26ec06af7&amp;hl=en
http://forums.asp.net/p/1369765/2860698.aspx#2860698
http://browsercompatibility.codeplex.com/



CSS background image URL setting not working for table cell in Safari and Chrome

I was scratching my head over this one. The inline style was specified as
style="background-image:url('image_link.jpg');
and it was working in all browsers like Internet Explorer, Firefox and Opera EXCEPT safari and chrome. After some trial and error, i found that this was due to the fact that my table cell (TD) was not having any contents. I inserted an non-breaking space and Voila! It works now.

Friday, January 15, 2010

Run (Execute) client script after an AJAX operation using Updatepanel

If there is a need to run a client script after an AJAX operation through UpdatePanel, use ScriptManager.RegisterStartupScript OR ScriptManager.RegisterClientScriptBlock. A typical usage is as follows.

ScriptManager.RegisterStartupScript(this, this.GetType(), "scriptname", "alert('update panel loading complete')", true);

Watch out, as some of these calls are getting deprecated

Additional Info:
http://fredrik.nsquared2.com/ViewPost.aspx?PostId=430