Sunday, May 16, 2010

XML Parsing Error: no element found

Recently when I am working with web service which returns data as XML format. But unfortunately I always found that the page always show error : XML Parsing Error: no element found. Error does not contain specific information about the source of error.

Problem:
The common reason for XML Parsing Error: no element found is missing closing tag for one or two html element, so I checked whole xml docs several times to make sure not miss any start and closing( or ) tags.

Solution:

After searching for while I found that somehow ASP.NET treat the response of page as XML document and that’s why we receive XML Parsing Error: no element found error.
To solve this error I added a line
Response.ContentType = "text/HTML" 
to .cs page. This line tells ASP.NET runtime that response is HTML text and not XML.

Thursday, May 13, 2010

How to DataTable export to Excel in asp.net

It is a very common question is asp.net forum and other forum that how to export DataTable to excel in asp.net.
There are various ways to export data to excel, such as:

    1.    Write As XML with .XLS extensions
    2.    Render DataTable as Excel
    3.    Uisng HtmlForm object
    4.    Using VerifyRenderingInServerForm

Insha Allah, I will discuss all these export types gradually. Today I want to discuss here how to export DataTable to Excel. Its very simple ,I write down a method here just call it ana pass your DataTable as a parameter then this method generate a Excel file for you.

Code:
 public void ExportDataTable(DataTable dt)
        {
            string attachment = "attachment; filename=" + FileName.xls + "";
            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.AddHeader("content-disposition", attachment);
            HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
            string sTab = "";
            foreach (DataColumn dc in dt.Columns)
            {
                HttpContext.Current.Response.Write(sTab + dc.ColumnName);
                sTab = "\t";
            }
            HttpContext.Current.Response.Write("\n");

            int i;
            foreach (DataRow dr in dt.Rows)
            {
                sTab = "";
                for (i = 0; i < dt.Columns.Count; i++)
                {
                    HttpContext.Current.Response.Write(sTab + dr[i].ToString());
                    sTab = "\t";
                }
                HttpContext.Current.Response.Write("\n");
            }
            HttpContext.Current.Response.End();
        }

Tuesday, May 11, 2010

Presentation @ Visual Studio 2010 community launch program

I have presented  "ASP.net page life cycle" at Visual Studio 2010 community launch program.

You can download the presentations from this link. this rapidshare link collected from Omi Azad blog.

Monday, May 10, 2010

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.

Tuesday, May 4, 2010

How to get visitor's Country,longitude,latitude from IP address is asp.net

It is very common questions for new web developer how to get the client's country location to track the user.In various forum I

have faced this questions. So that today I want to share how to get client's country location,longitude,latitude,country code etc.
To get this you need to use a
free database which has IP to Location mapping
or
call a web service that does the same for you.

Using free web services is the easy way to get the location of the user based on its IP address. After goggling I have found the

following web service which provide this service absolutely free and that too without any complex interface to do the same.

http://freegeoip.appspot.com/

The above website provides free IP Geolocation Web Service that returns data in three formats .

1. XML [Extended Markup Language]
2. CSV [Comma Separated Values]
3. JSON [JavaScript Object Notation]

Here I am explaining how to get the data in XML format.
It is very easy to use this web service,just send your ip address through the URL
like:
http://freegeoip.appspot.com/xml/116.68.204.254

The returned XML with result are as below:

<Response>
<Status>true</Status>
<Ip>116.68.204.254</Ip>
<CountryCode>BD</CountryCode>
<CountryName>Bangladesh</CountryName>
<RegionCode>81</RegionCode>
<RegionName>Dhaka</RegionName>
<City>Dhaka</City>
<ZipCode/>
<Latitude>23.723</Latitude>
<Longitude>90.4086</Longitude>
</Response>

How to consume this web service and get the result:
Here WebRequest and WebProxy is responsible for make call this url and xml response is received by WebResponse and store it to dataset using XMLTextReader.

Code:
private DataTable GetGeoLocation(string ipaddress)
{
//Create a WebRequest
WebRequest rssReq = WebRequest.Create("http://freegeoip.appspot.com/xml/"
+ ipaddress);
//Create a Proxy
WebProxy px =new WebProxy("http://freegeoip.appspot.com/xml/" + ipaddress, true);

//Assign the proxy to the WebRequest
rssReq.Proxy = px;

//Set the timeout in Seconds for the WebRequest
rssReq.Timeout = 2000;
try
{ //Get the WebResponse
WebResponse rep = rssReq.GetResponse();

//Read the Response in a XMLTextReader
XmlTextReader xtr = new XmlTextReader(rep.GetResponseStream());

//Create a new DataSet
DataSet ds = new DataSet();

//Read the Response into the DataSet
ds.ReadXml(xtr);
return ds.Tables[0];
}
catch
{
return null;
}
}

How to show result in aspx page:
You can place this code on Page_Load event or under any button event whenever you like:
Protected void ShowGeoLocatio()
{
string sIpaddress;
sIpaddress= Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if(sIpaddress== "" || sIpaddress== null)
{
sIpaddress= Request.ServerVariables["REMOTE_ADDR"];
}

//call the function to consume web service and store result into datatable
DataTable odtGeoLocation = GetGeoLocation(sIpaddress);
if (odtGeoLocation != null)
{
if (odtGeoLocation .Rows.Count > 0)
{
lblCity.Text = odtGeoLocation .Rows[0]["City"].ToString();
lblRegion.Text = odtGeoLocation .Rows[0]["RegionName"].ToString();
lblCountry.Text = odtGeoLocation .Rows[0]["CountryName"].ToString();
lblCountryCode.Text = odtGeoLocation .Rows[0]["CountryCode"].ToString();
}
else
{
lblError="Sorry,no data found!!";
}
}
}

Hope that it may helps the developer.Thanks.

Monday, May 3, 2010

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.

Visual Studio 2010 Community Launch @Bangladesh

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

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

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

Method 'StartWorkflowOnListItem' in type 'Microsoft.SharePoint.WorkflowServices.FabricWorkflowInstanceProvider'

Exception: Method 'StartWorkflowOnListItem' in type 'Microsoft.SharePoint.WorkflowServices.FabricWorkflowInstanceProvider'...