Ahsan's Experience

sharing experiences in .net ………

How to get client’s languages using Asp.net

Recently I have fall in a situation that I need the clients language for fulfill the business requirement. I have found lots of resources about it. Today I want to share with you how to get client’s language using asp.net.

You can get the language from Browser using

HttpRequest.Request.ServerVariables(“HTTP_ACCEPT_LANGUAGE”).

or, You can also use this

HttpRequest.UserLanguages();

Here HttpRequest.UserLanguages return a array of languages,so to retrieve the language you can use index of array like,

HttpRequest.UserLanguages(0);

But there are some differents between them.HttpRequest.UserLanguages() returns a sorted array of language preferences, whereas the Request.ServerVariables(“HTTP_ACCEPT_LANGUAGE”) returns a (comma-separated) string. In other words, HttpRequest.UserLanguages appears to take the value of Request.ServerVariables(“HTTP_ACCEPT_LANGUAGE”).

There are another way you can get it from CulturalInfo class.

CultureInfo ci = System.Threading.Thread.CurrentThread.CurrentUICulture;

This will give you what is set in the browser as the current language.But you need to set UICulture=”Auto” on page or global level before using System.Threading.Thread.CurrentThread.CurrentUICulture. Otherwise it will not give you the expected result. It is really a more direct way to get the client’s culture.

May 16, 2010 Posted by | asp.net, Javascript | , , , , , | Leave a comment

Visual Studio 2010 Community Launch Successfully!!

Visual Studio 2010 community launch program successfully held at 8 May 2010. Really its a great events those who are attends at that program. Trust me, those who are failed to attend this ceremony they missed a great event.

C# 4.0 Demystified presented by Tanzim bhai and Silverlight for Windows Mobile 7 using VS 2010 presented by Asif bhai make this events more fruitful specially for developers. And Omi bhai organized the whole ceremony very nicely.
For more info: please visits

May 11, 2010 Posted by | Microsoft, MSDN Community | | Leave a comment

How to get client “IP Address” using Asp.net /C#

I have found that in various forum newbie are very frequently asked this type of question how to get client IP or get mac address or country. So that I would like to share this for that user. Though its very simple but helpful.

Tip:1
To get the client IP you can use the following function
string sClientIp=Request.UserHostAddress();
or
string strHostName = System.Net.Dns.GetHostName();
string clientIPAddress = System.Net.Dns.GetHostAddresses(strHostName).GetValue(0).ToString();

Tip:2:To avoid Proxy IP:

To get the IP address of the machine and not the proxy use the following code

HttpContext.Current.Request.ServerVariables[“HTTP_X_FORWARDED_FOR”];

This will returns the client IP in string format.

Code:
C#

string ip;

ip=Request.ServerVariables(“HTTP_X_FORWARDED_FOR”);
if(ip==string.Empty)
{
ip=Request.ServerVariables(“REMOTE_ADDR”);
}

REMOTE_ADDR does not always provide the users IP but rather the ISPs’ IP address so first test HTTP_X_FORWARDED_FOR as this one is the real user IP.

Another important note to this the HTTP_X_FORWARDED_FOR may contain an array of IP, this can happen if you connect through a proxy.What also happens when this happens is that the REMOTE_ADDR may contain the proxy IP. To avoid this problem you can parse the HTTP_X_FORWARDED_FOR for first entery IP.

Code:
C#

string ip;
ip=Request.ServerVariables(“HTTP_X_FORWARDED_FOR”) ;
if (!string.IsNullOrEmpty(ip))
{
string[] ipRange = ip.Split(‘,’);
string trueIP = ipRange[0].Trim();
}
else
{
ip=Request.ServerVariables(“REMOTE_ADDR”);
}

Hope that it may helpful for the newbie.Please inform me if anything wrong in this article.
More more info pls visit: http://aspboss.blogspot.com/

May 6, 2010 Posted by | asp.net, C#, Web | , , , | 2 Comments

How to detect browser Information in Asp.net

Sometimes some fresher asked me how they get browser information when using asp.net. In online you can find lots of resources about. I have placed this code snippet form msdn which may help newbie.

Place this code under any button event or Page_Load event:

System.Web.HttpBrowserCapabilities browser = Request.Browser;
string s = “Browser Capabilities\n”
+ “Type = ” + browser.Type + “\n”
+ “Name = ” + browser.Browser + “\n”
+ “Version = ” + browser.Version + “\n”
+ “Major Version = ” + browser.MajorVersion + “\n”
+ “Minor Version = ” + browser.MinorVersion + “\n”
+ “Platform = ” + browser.Platform + “\n”
+ “Is Beta = ” + browser.Beta + “\n”
+ “Is Crawler = ” + browser.Crawler + “\n”
+ “Is AOL = ” + browser.AOL + “\n”
+ “Is Win16 = ” + browser.Win16 + “\n”
+ “Is Win32 = ” + browser.Win32 + “\n”
+ “Supports Frames = ” + browser.Frames + “\n”
+ “Supports Tables = ” + browser.Tables + “\n”
+ “Supports Cookies = ” + browser.Cookies + “\n”
+ “Supports VBScript = ” + browser.VBScript + “\n”
+ “Supports JavaScript = ” +
browser.EcmaScriptVersion.ToString() + “\n”
+ “Supports Java Applets = ” + browser.JavaApplets + “\n”
+ “Supports ActiveX Controls = ” + browser.ActiveXControls
+ “\n”
+ “Supports JavaScript Version = ” +
browser[“JavaScriptVersion”] + “\n”;

For more info please visits:
http://msdn.microsoft.com/en-us/library/3yekbd5b%28v=VS.100%29.aspx
http://aspboss.blogspot.com/2010_04_01_archive.html

May 3, 2010 Posted by | asp.net, C#, Firefox, IE, Web Browser | , | Leave a comment

Visual Studio 2010 Community Launch @Bangladesh

MSDN Bangladesh Community cordially invites you to attend Visual Studio 2010 Community Launch.

Date: Saturday, 08 May 2010
Time: 10:30 – 14:00
Location: uditorium, IDB Bhaban
Street: Sher-E-Bangla Nagar
Town/City: Dhaka, Bangladesh

Program Flow:

– Opening Speech – Omi Azad, Developer Evangelist, Microsoft Bangladesh Ltd.

– A Quick Look at Visual Studio 2010 – Irtiza A. Akhter, CTO, Micro Web Planet

– C# 4.0 Demystified – Tanzim Saqib, Software Designer, British Telecom

– ASP.Net page life cycle – Ahsan Murshed, Software Engineer, Cyber Jahan Ltd.

– Silverlight for Windows Mobile 7 using VS 2010 – Asif Huque, SaaS Developer, British Telecom

– T Shirt & CD Distribution – Lunch and Closing

May 3, 2010 Posted by | Microsoft | , , | Leave a comment

How to show Page loading progress with modal background

Problem:

In my recent application development I have faced a strange problem to show modal background with page loading progress. I had tried in different way but not working perfectly. Then I have solved it. I think that there is another efficient way to solved it but now this time it is working for me.

Solution:

In css class:
.divModalBackground
{
filter: alpha(opacity=50); -moz-opacity:0.5; opacity: 0.5;
width:100%;
background-color: #999988;
position: absolute;
top: 0px;
left: 0px;
z-index: 800;
}

In aspx page:
<asp:Panel ID=”Panel1″ runat=”server” Height=”900px” Width=”100%” CssClass=”divModalBackground” Visible=”true” >
<asp:Image runat=”Server” ID=”ImageLoader” CssClass=”LoadingProgress” ImageUrl=”../../App_Themes/Black/images/ajax-loader.gif” />
</asp:Panel>

In aspx.cs page I put the code like this:
//to show modal popup at page startup
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
Panel1.Visible = true;
}

In aspx page place this
// to clear the modal background when page load complete, place this code at the end of your page just before the end of the form tag
<script type=”text/javascript” >
function init()
{
var objdiv=document.getElementById(‘<%=Panel1.ClientID%>’)
if(objdiv)
{
objdiv.style.visibility = ‘hidden’;
}
}

init();
</script>

April 28, 2010 Posted by | Ajax, asp.net, Html, Javascript, Web | , , , | Leave a comment

Problem using AJAX call in IE6 and IE7

IE6 & IE7 makes problem when use xmlhttprequest for ajax

At first time when I used core ajax using xmlhttprequest. Using this technique we sent parameter as querystring through the url,like this,

function GetEmailId()
{
var url=”http://server.com/test.aspx&#8221;;
url=url+”&sid=test”;
xmlhttp.onreadystatechange=statechangedLogin;
xmlhttp.open(“GET”, url, true);
xmlhttp.send(null);
}
function statechangedLogin()
{
if(xmlhttp.readyState==4)
{
if(xmlhttp.responseText==”Login”)
{
//write your code
}
}
}

For the first time it is working fine,but when you try to second time in the same browser(IE6) its not work.

This is becuse Internet Explorer will also cache dynamic pages and this is a problem because the URL of the page may not change but the content will.A workaround for this situation can be achieved by adding a unique time stamp or random number, or possibly both, typically using the Date object and/or Math.random() such as url=url+”&sid=test”+Math.random();.

As for example:

function GetEmailId()
{
var url=”http://server.com/test.aspx&#8221;;
url=url+”&sid=test”+Math.random();
xmlhttp.onreadystatechange=statechangedLogin;
xmlhttp.open(“GET”, url, true);
xmlhttp.send(null);
}

For simple document request the query string delimiter ‘?’ can be used, or for existing queries a final sub-query can be added after a final ‘&’ – to append the unique query term to the existing query. The downside is that each such request will fill up the cache with useless (never reused) content that could otherwise be used for other cached content (more useful data will be purged from cache to make room for these one-time responses).

A better workaround can be achieved by adding meta tags to dynamic pages in order to make them no-cachable:

<meta http-equiv=”Pragma” content=”no-cache” />
<meta http-equiv=”Expires” content=”-1″ />

For more info please visit:
http://en.wikibooks.org/wiki/JavaScript/XMLHttpRequest
http://blogs.msdn.com/ie/archive/2006/01/23/516393.aspx
http://stackoverflow.com/questions/1229821/problem-using-ajax-call-in-ie6-and-ie7-i-am-asking-the-same-question-again-ca

April 26, 2010 Posted by | Ajax, IE, Javascript, Web, Web Browser | , , , | 1 Comment

scrollTop not work in IE6

scrollTop problem in IE6

I face a lots of problem ie6.Now I want to share one with you and how to solve it.
Hope that it may helps you.
divObj.scrollTop=0 moves to top of the div but it is not working in IE6.

To solve this you can use:

divObj.scrollTop = divBody.offsetTop; //for scroll to top of the div
divObj.scrollHeight = divBody.offsetHeight; //for scroll to bottom of the div

for more info please visit:
http://radio.javaranch.com/pascarello/2005/12/14/1134573598403.html

April 25, 2010 Posted by | Html, IE, Javascript, Web Browser | , , , | Leave a comment

Basic Idea on JSON

What is JSON?

JSON is a very lightweight data format based on a subset of the JavaScript syntax, namely array and object literals. JSON allows communicating with server in a standard way. JSON is used as communication notation instead of XML.

JSON objects are typed while XML data is typeless
1.JSON types: string, number, array, boolean,
2.XML data are all string

JSON stands for Javascript Object Notation which is a data structuring format that is extremely clean and lightweight. Even though JSON is native to javascript (as in, it can be turned into an object directly by javascript), it is quite easy to handle with other languages, making it an ideal replacement of XML when javascript is involved with the exchange of data (i.e. ajax).

var fruitColors =
{
“apple”:”green”,
“banana”:”yellow”,
“orange”:”orange”
};

alert(fruitColors .apple); //outputs “green”
alert(fruitColors .orange); //outputs “orange”

The above code creates an javascript object bike with two properties apple and orange

JSON Structures
• A collection of name/value pairs
In various languages, this is realized as an object, record,struct, dictionary, hash table, keyed list, or associative array
• An ordered list of values
In most languages, this is realized as an array, vector, list, or sequence

JSON Object Notation
• A JSON object is an unordered set of name/value pairs
• A JSON object begins with { (left brace) and ends with } (right brace)
• Each name is followed by : (colon) and the name/value pairs are separated by , (comma)

For more info please visit:
http://msdn.microsoft.com/en-us/library/bb299886.aspx
http://www.json.org/
http://en.wikipedia.org/wiki/JSON

April 22, 2010 Posted by | json, Web | | Leave a comment

Dynamically add control in asp.net

Recently I have faced a problem when try to dynamically add controls in asp.net, like this,
In test.aspx page

<body>
<form id=”form1″ runat=”server”>
<div>
<asp:PlaceHolder ID=”PlaceHolder1″ runat=”server” >    </asp:PlaceHolder>

</div>
</form>
</body>

In test.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
Button btn = new Button();
btn.ID = “btnSave”;
this.PlaceHolder1.Controls.Add(btn);
}

Problem:

It is working fine but when I press any button I mean any post back occur It disappears.
After search for a long time I got the proper solution, now I would like to share this with you.

Solution:
To avoid this problem one should dynamically load the controls during Page_Init because we may want to hook up our events with proper handler at an early stage.

protected void Page_Init(object sender, EventArgs e)
{
Button btn = new Button();
btn.ID = “btnSave”;
btn.Click+=new EventHandler(btn_Click);
this.PlaceHolder1.Controls.Add(btn);
}

Some Tips:
In addition I have got more tips on it,

Control’s Lify cycle:

1.Initialization
2.Load view state
3.Process postback data
4.Load
5.Send postback change notifications
6.Handle postback events
7.Prerender
8.Save state
9.Render
10.Dispose
11.Unload

You will get details from here:http://msdn.microsoft.com/en-us/library/aa719775%28VS.71%29.aspx

1.During Page_Init you cannot assign dynamic control property,because in Page_Init event Initialization happens before loadViewState in control’s life cycle.The value assigned to the properties during Initialization will simply get overwritten by the ViewState values.

2.If you are expecting your ViewState to retain after the postback, always assign same ID to the dynamic control,if you use like this,

protected void Page_Init(object sender, EventArgs e)
{
TextBox t = new TextBox();
t.ID = Guid.NewGuid().ToString();
this.form1.Controls.Add(t);
}

It will not work. You should use same id or fixed id ,
like this, t.ID=”txtName”;

April 21, 2010 Posted by | asp.net, C# | , , | 1 Comment

Problem with Session StateServer mode

StateServer mode stores session state in a process, referred to as the ASP.NET state service, that is separate from the ASP.NET worker process or IIS application pool. Using this mode ensures that session state is preserved if the Web application is restarted and also makes session state available to multiple Web servers in a Web farm.

But new user are facing problem with this Session state mode.

First ensure to use StateServer mode, you must first be sure the ASP.NET state service is running on the server used for the session store. The ASP.NET state service is installed as a service when ASP.NET and the .NET Framework are installed.

The ASP.Net state service is installed at the following location:
systemroot\Microsoft.NET\Framework\versionNumber\aspnet_state.exe
To configure an ASP.NET application to use StateServer mode, in the application’s Web.config file do the following:
1.Set the mode attribute of the sessionState element to StateServer.
2.Set the stateConnectionString attribute to tcpip=serverName:42424.

Example:
<configuration>
<system.web>
<sessionState mode=”StateServer”
stateConnectionString=”tcpip=SampleStateServer:42424″
cookieless=”false”
timeout=”20″/>
</system.web>
</configuration>

Problem:
“Unable to make the session state request to the session state server. Please ensure that the ASP.NET State service is started and that the client and server ports are the same. If the server is on a remote machine, please ensure that it accepts remote requests by checking the value of HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\aspnet_state\Parameters\AllowRemoteConnection. If the server is on the local machine, and if the before mentioned registry value does not exist or is set to 0, then the state server connection string must use either ‘localhost’ or ‘127.0.0.1’ as the server name.

Solution:
Main solution is allow remote connection from registry.
To allow remote connection:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\aspnet_state\Parameters\AllowRemoteConnection set value to 1
Restart ASP.NetStateService from systemroot\Microsoft.NET\Framework\versionNumber\aspnet_state.exe.

For more information visit: http://msdn.microsoft.com/en-us/library/ms178586.aspx

April 20, 2010 Posted by | asp.net, Session | , , | 2 Comments

Use Master page tag in Content page of asp.net

How to use the <body> onclick from content page in asp.net?

Master page is introducing from asp.net 2.0, this is the main layout page for whole application content page just inherit it.

So that,we get the <body> tag only in Master page,in content page there is no body tag. But I need to use this body tag from content page.

After search it I found a solution in asp.net forum. Original link: http://forums.asp.net/t/1062445.aspx

Sample:

<%@ Page Language=”C#” MasterPageFile=”~/MasterPage.master” AutoEventWireup=”true” CodeFile=”Default.aspx.cs” Inherits=”Default” Title=”Test Page” %>

<asp:Content ID=”Content1″ ContentPlaceHolderID=”ContentPlaceHolder1″ Runat=”Server”>
<script type=”text/javascript”>

function ClearBox()
{
var divBoxID=document.getElementById(‘BoxDiv’);
divBoxID.style.display=’none’;
}

document.body.onclick= ClearBox;

</script>

<input id=”Button1″ type=”button” value=”button” />

</asp:Content>

For more info pls visit:
http://msdn.microsoft.com/en-us/library/7a9d6h4f.aspx
http://forums.asp.net/t/1225951.aspx

April 20, 2010 Posted by | asp.net, C#, Html, Master Page | , | Leave a comment

Request format is unrecognized for URL unexpectedly ending

Today I want to share with you a new problem which I had faced yesterday.
Problem:
It was about web service related error. I have used Web Method() in my application to fill up a country dropdown. Everything was going well but when I had used this web method it showed me an error like this:

System.InvalidOperationException: Request format is unrecognized for URL unexpectedly ending in ‘/GetCountyList’.

Information:
After googling, I have found the solution.

This error was occured because GET and POST are disabled by default in ASP.NET 2.0 and greater.

Now I would like to share this with you. From msdn I have got some relative information which may help you to get understand clearly.

The .NET-connected Web services support HTTP GET, HTTP POST and SOAP protocols. By default, in .NET Framework 1.0, all three protocols are enabled. By default, in .NET Framework 1.1 or greater, HTTP GET and HTTP POST are both disabled. This is for security reasons.

Applications that use HTTP GET or HTTP POST to invoke a Web service fail when the Web service is upgraded to .NET Framework 1.1 or greater. These applications receive a exception: System.InvalidOperationException: Request format is unrecognized.

Solution:
HTTP GET and HTTP POST may be enabled by editing the Web.config file for the vroot where the Web service resides. The following configuration enables both HTTP GET and HTTP POST:

<configuration>
<system.web>
<webServices>
<protocols>
<add name=”HttpGet”/>
<add name=”HttpPost”/>
</protocols>
</webServices>
</system.web>
</configuration>

For more info pls visits these links:
http://support.microsoft.com/default.aspx?scid=kb;en-us;819267
http://forums.asp.net/t/1459560.aspx
http://aspadvice.com/blogs/ssmith/archive/2007/09/04/FIX-Request-format-is-unrecognized-for-URL-unexpectedly-ending-in.aspx
http://forums.asp.net/t/988377.aspx

April 20, 2010 Posted by | web service | , , , , | 1 Comment