Monday, May 31, 2010

Which path you have to use in your application?

What is Absolute path?

Absolute paths are called that because they refer to the very specific location, including the domain name. The absolute path to a Web element is also often referred to as the URL. For example, the absolute path to this Web page is: http://aspboss.blogspot.com/2010/04/how-to-get-client-ip-address-using.html

What is Relative path?
Relative paths change depending upon what page the links are located on. Another word,A relative path is a path relative to the working directory of the user or application, so the full absolute path may not need to be given. There are several rules to creating a link using the relative path:
  •      links in the same directory as the page have no path information listed   filename
  •      sub-directories are listed without any preceding slashes weekly/file-name
  •     links up one directory are listed as   ../filename
Linking to a resource from a reusable control in different levels in your web app folder tree can be a tedious and not so obvious task.

Now have a look where to use absolute paths or relative paths

    1.Absolute paths - http://www.yoururl.com/a/b/c/page.aspx - It is not acceptable for reusable components.
    2. Relative paths
          o current level based - a/b/c/page.aspx - Doesn't work for reusable components.
          o root based - /a/b/c/page.aspx - That works good in some cases but not in every.
          o app based - ~/a/b/c/page.aspx - Perfect when you can use it

What's wrong with root based paths?

When you work on a project you often use built-in WebServer of the Visual Studio and your app runs on http://localhost:XXXX/. Everything seems to be working fine with the root based paths. Now it's time to deploy your app on a test machine. You deploy it on http://test/myBestApp/. Now all your root based paths are pointing to http://test/Page.aspx instead of http://test/myBestApp/Page.aspx. That's a good reason not to use root based paths.

Is ~ (tilde) can solve it?

That's a good solution that comes out of the box and takes care finding the root of your app. Ok, but what if need to build the URL on the fly like in this example:

~/Item.aspx?id=<% Request.QueryString[ "id" ] %>

This won't work if you put it in a Hyperlink like this:

<asp:hyperlink id="hlnkItemDetails" navigateurl="~/Item.aspx?id=<% Request.QueryString[ "id" ] %>" runat="server">

Don't think about changing the quotation marks. It won't work however you try.

The universal solution - Page.ResolveUrl

Now that's what can help you in every situation (or at least all cases I can think of).
Think about this case: you have a custom control in ~/items/controls/ItemViewControl.ascx. This control is used in ~/Default.aspx and ~/items/Default.aspx. You need to link to ~/items/Item.aspx?id=<query param="" string="">from ItemViewControl.ascx.

You can't use ~ (tilde), root based, current folder relative or absolute path for some of the reasons written above.

This is where Page.ResoulveUrl comes into help. You can build your link in this way:

<a href='<% String.Format( "{0}?id={1}", Page.ResolveUrl( "~/items/Item.aspx" ), Request.QueryString[ "id" ] %>'></a>

Yes, it is a bit complicated, but at least you won't be worried about broken links and they will work as expected wherever you put them.

Thursday, May 27, 2010

Accessing Master page functions from a content page

Accessing Master page functions from content page we must include a MasterType directive at the top of the Content page ASPX file:

<%@ MasterType virtualpath="~/DetailsMaster.master" %>

In DetailsMaster.master.cs page
public void SavePageData()
{
// function definition
}

After place the MasterType directive is in place in the Content page, then public functions in the Master page are available to the Content page code.

C# Code:
//Call the SavePageData function from the Master page
Master.SavePageData();

I hope it will helpfull for other developer.

Accessing Master page controls from a content page

Today I want to share with you how to use master page control from content page.
Suppose there is a Label on the Master page that we want to write to from the Content page.

1. We must include a MasterType directive at the top of the Content page ASPX file:

<%@ MasterType virtualpath="~/DetailsMaster.master" %>


2. We must include a public function in the Master page that returns a typed reference to the Label:

VB.net

Public Function LabelReference() As Label
' Create a reference to an actual label on the page
LabelReference = lblDetailsItemName
End Function
C#
public Label LabelReference()
{
// Create a reference to an actual label on the page
return lblDetailsItemName;
}

3. We can access the Label from the Content page using the Master syntax:

Master.LabelReference.Text = "Demo text";

Hope that it will help for developer.

Tuesday, May 25, 2010

Creating Object to a Class dynamically using Reflection

What is Reflection?

Reflection is the feature in .Net, which enables us to get some information about object in run time. That information contains data of the class. Also it can get the names of the methods that are inside the class and constructors of that object.

To write a C# .Net program which uses reflection, the program should use the namespace System.Reflection. To get type of the object, the typeof operator can be used. There is one more method GetType(). This also can be used for retrieving the type information of a class. The Operator typeof allow us to get class name of our object and GetType() method uses to get data about object's type.

One can use the Activator class for creating objects and then you can use reflection to call methods on the new instance, e.g.:

Example-1: C#
In this example simply show that how to create instance of a object dynamically,

using System;
using System.Runtime.Remoting;
using System.Reflection;
namespace ConsoleApplication3
{
interface IBase
{
void fu();
}
class Emp: IBase
{
public void fu()
{
Console.Write("Hello");
}
}
class Class1
{
[STAThread]
static void Main(string[] args)
{
Type type = Type.GetType("ConsoleApplication3.Emp");
IBase obj = (IBase)Activator.CreateInstance(type);
obj.fu();
}
}


Example-2: C#
In this example just show that how to create instance of a object dynamically and GET and SET the property value at runtime.

using System;
using System.Runtime.Remoting;
using System.Reflection;

namespace SampleApp
{
public class Person
{
private string name = string.Empty;

public Person()
{
}
public string Name
{
get { return name; }
set { name = value; }
}
}
class Program
{
static void Main(string[] args)
{
object obj = ((ObjectHandle)Activator.CreateInstance(null, "SampleApp.Person")).Unwrap();
Type type = obj.GetType();
type.GetProperty("Name").SetValue(obj,"Hello World", null);
string personName = type.GetProperty("Name").GetValue(obj, null).ToString();

Console.WriteLine(personName);
Console.ReadLine();
}
}
}

How to get the CheckBoxlist Value using Javascript

A CheckBoxList renders as an HTML Table tag and does not have checked property. The child controls are CheckBoxes and do have the checked property.

There is no client-side "value" property in a CheckBoxList.

That is a server-side only property. You can only get the Text property of the ListItem (Item 1, Item 2, etc in this example).

Example:

<form id="form1" runat="server">
 <asp:CheckBoxList id="CheckBoxList1" runat="server">
  <asp:listitem Value="1">Item 1</asp:listitem>
  <asp:listitem Value="2">Item 2</asp:listitem>
  <asp:listitem Value="3">Item 3</asp:listitem>
 </asp:CheckBoxList>
 <input type="button" onclick="readCheckBoxList();" value="Read CheckBoxList" />
</form>


<script type="text/javascript">
<!--
function getCheckBoxListItemsChecked(elementId)
{
 var elementRef = document.getElementById(elementId);
 var checkBoxArray = elementRef.getElementsByTagName('input');
 var checkedValues = '';

 for (var i=0; i<checkBoxArray.length; i++)
 {
  var checkBoxRef = checkBoxArray[i];

  if ( checkBoxRef.checked == true )
  {
////////////
// AFAIK, you cannot get the value property of a ListItem in a CheckBoxList.
// You can only get the Text property, which will be in an HTML label element.
////////////


   var labelArray = checkBoxRef.parentNode.getElementsByTagName('label');

   if ( labelArray.length > 0 )
   {
    if ( checkedValues.length > 0 )
     checkedValues += ', ';

    checkedValues += labelArray[0].innerHTML;
   }
  }
 }

 return checkedValues;
}
function readCheckBoxList()
{
 var checkedItems = getCheckBoxListItemsChecked('<%= CheckBoxList1.ClientID %>');
 alert('Items checked: ' + checkedItems);
}
// -->
</script>

Url rewritng in ASP.net 4.0

What is URL Routing?

URL routing was a capability we first introduced with ASP.NET 3.5 SP1, and which is already used within ASP.NET MVC applications to expose clean, SEO-friendly “web 2.0” URLs. URL routing lets you configure an application to accept request URLs that do not map to physical files. Instead, you can use routing to define URLs that are semantically meaningful to users and that can help with search-engine optimization (SEO).

For example, the URL for a traditional page that displays product categories might look like below:

http://www.mysite.com/products.aspx?category=software

Using the URL routing engine in ASP.NET 4 you can now configure the application to accept the following URL instead to render the same information:

http://www.mysite.com/products/software

With ASP.NET 4.0, URLs like above can now be mapped to both ASP.NET MVC Controller classes, as well as ASP.NET Web Forms based pages.
For more info please visits scottgu's article..
http://weblogs.asp.net/scottgu/archive/2009/10/13/url-routing-with-asp-net-4-web-forms-vs-2010-and-net-4-0-series.aspx

Sunday, May 16, 2010

How to export Excel uisng HtmlForm(GridView) object in asp.net

Today I want to show you another way how to export Excel file from HtmlForm object. This is a serial post for How to export Excel file. Using HtmlForm object we should  use a Control which is rendering by HtmlTextWriter.

In this article, I use the GridView control. Here I provide a method where you pass a GridView control as parameter after that this method render this gridview control as a excel file from html object.

Code:C#

Namespace:
using System.Web.UI.HtmlControls 


public void ExportFromHtmlForm(GridView gvEmployee)
    {
        HtmlForm form = new HtmlForm();
        string attachment = "attachment; filename=Employee.xls";
        Response.ClearContent();
        Response.AddHeader("content-disposition", attachment);
        Response.ContentType = "application/ms-excel";
        StringWriter stw = new StringWriter();
        HtmlTextWriter htextw = new HtmlTextWriter(stw);
        form.Controls.Add(gvEmployee);
        this.Controls.Add(form);
        form.RenderControl(htextw);
        Response.Write(stw.ToString());
        Response.End();
    }

Write As XML with .XLS extensions

Today I want to share with you how to write XML file as an excel file from DataTable. Here I  provide you a function where you just send a DataTable as a parameter and this function is responsible for generate the Excel file.

Code:
     public void ExportAsXMLtoXLS(DataTable dt)
    {
        System.Data.DataTable dt = GetData();
        dt.TableName = "Employees";
        dt.WriteXml(Server.MapPath(".")+ @"\GenerateData.xls", XmlWriteMode.IgnoreSchema);
        Response.Redirect("GenerateData.xls");
    }

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'...