Tuesday, December 28, 2010

Open new window with Response.Redirect() in Asp.net

Today I want share with you a very interesting tips using Response.Redirect(). In asp.net there are various ways to move from one page to another. Mostly used.
  1. Response.Redirect()
  2. Server.Transfer()
 But unfortunately you cant open a new window with those two methods. Which is possible with anchor link like <a href="#" target="_blank" >. When goggling I find that most of the answer is it is not possible or to make it possible you would add JavaScript method to using it. But I don't want this, at last I found two approaches. Now I want to share with these two approaches with asp.net  Response.Redirect() and  Server.Transfer().

First approach(easiest way):

Just use the OnClientClick event of the button. 
<asp:Button ID="btnHome" runat="Server" CssClass="button" Text="Go home"
OnClick="btnHome_Click" OnClientClick="aspnetForm.target ='_blank';"/>
protected void btnHome_Click(object sender, EventArgs e)
{
    Response.Redirect("Home.aspx");
}

If you want to access the form inside the Master page to Child page level

Button1.OnClientClick=string.Format("{0}.target='_blank';",((HtmlForm)Page.Master.FindControl("form1")).ClientID);

This code will find the controls collection and find your form and allow you to get access to the client id so you can be sure you have proper naming of it for the JavaScript to function correctly. Make sure you replace "form1" with whatever you have your parent form id="name" set to inside your Master’s page markup.

For multiple buttons on a single page and only want a specific button to launch into a new window.

<asp:Button ID="btnHomePage" runat="Server" CssClass="button" Text="Your home"
OnClick="btnHomePage_Click" OnClientClick="aspnetForm.target ='_self';"/>

protected void btnHomePage_Click(object sender, EventArgs e)
{
   //Do normal code for postback
}

For more details.visits

In next post I will share with you another approach to open new window using response.redirect() insha Allah.

Presentation @ Microsoft Talkz in AIUB

Yesterday I had joined a nice seminar at AIUB(American International University Bangladesh) arranged by Microsoft which is titled by "Microsoft Talkz". I amazed to see the interest of students at that seminar. Huge crowd in  the auditorium some students were waiting outside the hall for entrance but no single space is available for accommodate them.Really a new experience for me. I feel lucky to get the opportunity to participate that event.

Microsoft student partner(MSP) did a very good job to organize the whole event very nicely. There were also some expert technical guys discuss with new Microsoft technologies.

Razor new view engine in asp.net was my presentation topic. One can download it from here: Razor view engine in asp.net .

Monday, December 6, 2010

Presentation@Kuet S-PAC Programm

Very recently IEEE KUET branch organized a awesome program Students Professional Awareness Conference(S-PAC ).  IEEE Student Branch KUET link( www.kuet.ac.bd/ieee ) introducing First S-PAC on Bangladesh Dated 3,4,5 December,2010 on KUET campus.

Students Professional Awareness Conference(S-PAC ) covers Workshop, Seminar, and Panel Discussions & Various Contests on the above stated topics comprising national & international guests.


It's really great initiative by KUET IEEE branch specially a big thanks to Shihab(who is chair for this event) and his team and also the KUET authority. I am also feeling lucky got an opportunity to attend this event as a speaker. My topic is "How to improve security and performance in ASP.net".
One can download it from here: How to improve security and performance in ASP.net

Its really new experience for me. Huge no of audience(almost 3000) were attends this event. I'm  amazed to got huge response from audience after presentation.

Sunday, November 7, 2010

How to add Google Map in asp.net

Today I have added Google Map my asp.net application successfully !! Don't worry it's not a big deal. Very easy and you will find a lots of article, tutorial about it. For using google map you just need a google account for google map api and basic JavaScript knowledge. For non commercial use google map is free.

In aspx page add Google Map API KEY in header part of html....like this
<head >
<script src="http://maps.google.com/maps?file=api&v=2& key=ABQIAAAAclK0B2lXQwV5lPy1rLiTFBSN1aiKepvDswXjKa4j2DDWdYvOjhQMO1tywqS8ObgP5dtO70AyyArhzA"
type="text/javascript"> </script >
</head>
You can get your own google map api key from this link. You can place your url

Monday, September 27, 2010

“Razor” – a new view engine for ASP.NET

Razor” – a new view engine for ASP.NET developed by Microsoft.

The new view-engine option have been working on is optimized around HTML generation using a code-focused templating approach. The codename for this new view engine is “Razor”,

Microsoft had a number of design goals when building and testing Razor, attempting to create a compact, expressive, and fluid ASP.NET view engine.

In addition, the Redmond company worked to ensure that customers would be able to leverage Razor immediately, by using their existing language and HTML skills.

Design Goals for "Razor"

Sunday, September 26, 2010

Access Properties of a UserControl from other UserControl in ASP.Net Page

Few days ago I have posted an article "How To Access One UserControl from Another UserControl Using ASP.NET". When I try to find out solution for this I have got some nice articles about this issue. Rami vermula shows how to access properties of UserControl from another UserControl In asp.net.

This is really very helpful to solved my problem and immedidately me implement it in my solution.Now share for you .....

WebUserControl1.ascx
===================
This is the first UserControl on the page, from which we access the other UserControl (WebUserControl2.ascx) Properties.

Code
======

Automatic URL re-basing in the HtmlHead control

If you're using Master Pages in ASP.NET and trying to resolve <script> or <style> references in the page head, you may have run into this this show-stopper. If so, here's why it's happening, and here's an easy way to fix it.

If you've worked with ASP.NET Master Pages, you've no doubt taken advantage of automatic URL re-basing within the HtmlHead control. This bit of ASP.NET magic helps assure that a content page has access to the correct resources:

<head id="head1" runat="server">
<title>My Page</title>
<link href="css/common.css" rel="stylesheet" type="text/css" />
</head >

When you add the runat="server" attribute to the tag,

Thursday, September 23, 2010

The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).

Server Error in 'ASP.Net' Application.

The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Web.HttpException: The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
____________________________________________________________________________

Recently I have faced this type of error on browse my application after add JavaScript method. This is the first time I have faced this issue. Newly written method is double checked by me but nothing found. Then try to find in asp.net forum now this time got the solution :).

Very silly mistake......now I have share with you.

Wednesday, September 22, 2010

DateTime Custom Picture Formatting

Using Picture Formats for Custom Formatting

The standard format specifiers are useful in most cases whilst still maintaining the correct style of date and time for the user's location. On some occasions however, it is necessary to have complete control over the positioning and styling of each element of date and time information.

For this, picture formats must be used. These allow an exact format to be created using any combination of elements from a DateTime.

DateTime theDate = DateTime.Parse("3 Jan 2007 21:25:30");
string result;

result = theDate.ToString("d-MM-yy");//result ="3-01-07"
result = theDate.ToString("HH:mm");//result ="21:25"
result = theDate.ToString("h:mm tt");//result ="9:25 PM"

Available Picture Formatting Codes

The above example shows several formats and the results. The full list of available formatting codes is as follows:
SpecifierDescriptionExamples
yOne-digit year. If the year cannot be specified in one digit then two digits are used automatically."7"
"95"
yyTwo-digit year with leading zeroes if required."07"
yyyyFull four-digit year."2007"
g or ggIndicator of Anno Domini (AD)."A.D."
MOne-digit month number. If the month cannot be specified in one digit then two digits are used automatically."1"
"12"
MMTwo-digit month number with leading zeroes if required."01"
MMMThree letter month abbreviation."Jan"
MMMMMonth name."January"
dOne-digit day number. If the day cannot be specified in one digit then two digits are used automatically."3"
"31"
ddTwo-digit day number with leading zeroes if required."03"
dddThree letter day name abbreviation."Wed"
ddddDay name."Wednesday"
hOne-digit hour using the twelve hour clock. If the hour cannot be specified in one digit then two digits are used automatically."9"
"12"
hhTwo-digit hour using the twelve hour clock with leading zeroes if required."09"
HOne-digit hour using the twenty four hour clock. If the hour cannot be specified in one digit then two digits are used automatically."1"
"21"
HHTwo-digit hour using the twenty four hour clock with leading zeroes if required."09"
tSingle letter indicator of AM or PM, generally for use with twelve hour clock values."A"
"P"
ttTwo letter indicator of AM or PM, generally for use with twelve hour clock values."AM"
"PM"
mOne-digit minute. If the minute cannot be specified in one digit then two digits are used automatically."1"
"15"
mmTwo-digit minute with leading zeroes if required."01"
sOne-digit second. If the second cannot be specified in one digit then two digits are used automatically."1"
"59"
ssTwo-digit second with leading zeroes if required."01"
fFraction of a second. Up to seven f's can be included to determine the number of decimal places to display."0"
"0000000"
zOne-digit time zone offset indicating the difference in hours between local time and UTC time. If the offset cannot be specified in one digit then two digits are used automatically."+6"
"-1"
zzTwo-digit time zone offset indicating the difference in hours between local time and UTC time with leading zeroes if required."+06"
zzzFull time zone offset indicating the difference in hours and minutes between local time and UTC time with leading zeroes if required."+06:00"

Some of the formatting codes use the same letter as a format specifier. When used within a format string that is greater than one character in length this does not present a problem.

If you need to use a single character picture format string, the letter must be preceded by a percentage sign (%) to indicate that the standard format specifier is not to be used.

DateTime theDate = DateTime.Parse("3 Jan 2007 21:25:30");
string result;

result = theDate.ToString("d");// result = "03/01/2007"
result = theDate.ToString("%d");// result = "3"

How To Access One UserControl from Another UserControl Using ASP.NET

Few days ago, I need to access one UserControlfrom to another UserControl.The scenario is like,When I press a button it will assign a value from UserControl-1's TextBox to UserControl-2's TextBox. I have developed it but I made a silly mistake so that it was not working.

Now this is the time turn to google......:). Fortunately I have got almost similar solution from KaushaL PariK(MVP). Very simple.....from his solution I found out my problem....now place this here for you guys....hope that you enjoy it.

Some known tips

Missing debug menu on Visual Studio 2008

Before using Visual Studio 2010 I had usually developed application in Visual studio 2008. I don't remember, for some reason I can't find debug menu on my VS 2008. After goggling I have found the solution. I would like to share with you. It may help other guys.

Its very simple just use it:

Run "devenv /resetskippkgs" from command prompt, it will solve your problem.

"It is an error to use a section registered as allowDefinition='MachineToApplication' beyond application level" in asp.net

Very recently, I have got this error message when try to browsing my developed application in asp.net. So I try to solve in many ways but failed then move to google...:). I got some nice solutions...now share with you:

This error occurs primarily out of 2 scenarios.

First scenario:

When you create an new web application using visual studio.net, it automatically creates the virtual directory and configures it as an application.

However, if you manually create the virtual directory and it is not configured as an application, then you will not be able to browse the application and may get the above error. The debug information you get as mentioned above, is applicable to this scenario.

Tuesday, August 24, 2010

Introducing WebMatrix

WebMatrix is a free, lightweight Web development stack that makes it easy to build web sites that can grow with you, from installation to product deployment & maintenance. Developers can take advantage of mastering fundamental concepts of building apps for the web by using WebMatrix.

ASP.Net Web Matrix is a free tool released by Microsoft for the rapid development of web applications running on servers which support ASP.NET. It is a managed application written in the programming language C#.

Thursday, August 12, 2010

Presentation slide @aloashbei community

Now my presented slid "Mobile Application development using .NET framework" at Aloashbei community get together is available at here...
Aloashbei get-together contents

Sunday, August 1, 2010

Disable Browser Back Button

It is a common question for developer how to to prevent user’s from going to previous page using Browser Back button.
You can do it in various way:


Javascript Codesnippet1:

<script type = "text/javascript" >
function disableBackButton()
{window.history.forward();
}
setTimeout("disableBackButton()", 0);
</script>


For internet explorer: <body onload="disableBackButton()">
If you are using firefox then use <body onunload="disableBackButton()"> instead of onload.

Saturday, July 31, 2010

How to disable CheckBoxList using Javascript

I have faced this problem very recently,how to disable CheckBoxList using Javascript. It is not possible to disable like other object(textbox,combobox..) . After goggling I have found the solution now its sharing with you.....

Javascript code:
               // Get the checkboxlist object.
                var objCtrl = document.getElementById('<%=chkNeighborhoodFeatures.ClientID %>');                // Does the checkboxlist not exist?
                if(objCtrl == null)
                {        return;
                }

                var i = 0;
                var chkNeighborhoodFeaturesArray = objCtrl.getElementsByTagName('input');
                // iterate through listitems that need to be enabled or disabled
                for(i = 0; i
                {
                    objItem = document.getElementById('<%=chkNeighborhoodFeatures.ClientID %>' + '_' + i);
                    if(objItem == null)
                    {
                     continue;
                    }
                    // Disable/Enable the checkbox.
                    objItem.disabled = true;
                    // Should the checkbox be disabled?
                    objItem.checked = false;

                } 
           

Tuesday, July 20, 2010

Presentation@aloashbei community

Last 17th July I had presented  "Mobile Application development using .NET framework" at Aloashbei community get together. The aloashbei community was meeting together for the first time in Emmanuel’s Banquet Hall (House#4, Road# 134-135, Gulshan – 1, Dhaka) on 17th July at 10:30 AM.

Monday, June 21, 2010

Microsoft Expression Studio 4 released !!

Microsoft Expression Blend is a user interface design tool developed and sold by Microsoft for creating graphical interfaces for web and desktop applications that blend the features of these two types of applications. It is an interactive, WYSIWYG front-end for designing XAML-based interfaces for Windows Presentation Foundation and Silverlight applications. It is one of the applications in the Microsoft Expression Studio suite.

Expression Blend supports the WPF text engine with advanced OpenType typography and ClearType, vector-based 2D widgets, and 3D widgets with hardware acceleration via DirectX.
  • create rich web experiences, games, desktop apps, and more
  • design apps that use the full power of Silverlight
  • take your ideas from concept to finished project work effectively with design tools, Expression Blend and Visual Studio
You will find the new version from here: http://www.microsoft.com/expression/

Sunday, June 13, 2010

How to compile C# Application for both 32 bit and 64 bit system?

I have faced this problem when one of my client try to run SMS Suit software in Windows 7 64 bit. Previously it is working perfectly in vista and windows xp 32 bit . After searching online I have found lots of solutions on it now I want to share these with you...

Solution :1

You can edit your visual studio c# project file (.csproj) and put this snippet:
1.<PlatformTarget> x86 </PlatformTarget>

inside

2.<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">


Solution :2(Command-line form)
Using CorFlags to set the 32BIT flag on the executable. E.g:
corflags.exe myapp.exe /32BIT+

This will modify your exe, so you might wanna keep a backup just in case. You can also revert the flag using /32BIT- instead of /32BIT+.


Solution :3(Simplest way)
1.Right click your Project, and select Properties.
2.In properties, select the Build tab. Under Platform target, select x86.
3.Hit Ctrl+Shift+S to save all files, right click the Solution and select "Clean" to get rid of old binaries. Any builds after that should be 32 bit .
Now it is ready for both 32 bit and 64 bit OS.



This should solve the problem ! Please inform me if there is another better way.

Wednesday, June 9, 2010

Looping Through Controls in ASP.NET

In my recent development I have badly needed to read all the controls from asp.net page. After searching I have found lots of solution. Now I want share with you one of these solution. In this solution we read all the control from asp.net page with out using master page.

**Remember to add namespace  System.Collections.Generic
 
Code: C#

private static Control FindControlIterative 
(Control root, string id)
        {
            Control ctl = root;
            LinkedList ctls = new LinkedList();

            while (ctl != null)
            {
                if (ctl.ID == id)
                    return ctl;
                foreach (Control child in ctl.Controls)
                {
                    if (child.ID == id)
                        return child;
                    if (child.HasControls())
                        ctls.AddLast(child);
                }
                ctl = ctls.First.Value;
                ctls.Remove(ctl);
            }
            return null;
        }


 Code: VB.net
  
Private Shared Function FindControlIterative
(ByVal root As Control, _
ByVal id As String) As Control

  Dim ctl As Control = root
  Dim ctls As LinkedList(Of Control) = 
                  New LinkedList(Of Control)

  Do While (ctl IsNot Nothing)
   If ctl.ID = id Then
    Return ctl
   End If
   For Each child As Control In ctl.Controls
    If child.ID = id Then
     Return child
    End If
    If child.HasControls() Then
     ctls.AddLast(child)
    End If
   Next
   ctl = ctls.First.Value
   ctls.Remove(ctl)
  Loop

  Return Nothing

 End Function

 Read Control when use Master Page:

And this is where things get a bit tricky with MasterPages. The problem is that when you use MasterPages the page hierarchy drastically changes. Where a simple this.FindControl() used to give you a control instance you now have to drill into the container hierarchy pretty deeply just to get to the content container.

Code:C#

public static Control FindControlRecursive(Control Root, string Id)
{
if (Root.ID == Id)
return Root;

foreach (Control Ctl in Root.Controls)
{
Control FoundCtl = FindControlRecursive(Ctl, Id);
if (FoundCtl != null)
return FoundCtl;
}
return null;
}

You can use this method this way..

this.lblError = FindControlRecursive(this.Master,"lblError") as Label;

MS Sql server: How to do multiple rows insert ?

Recently I have faced a problem when insert multiple row insert at single call. After first row insert then problem arise from  second row insert. After goggling I have found a solution : it need to clear parameter after each row insert. I want to share that example with you:

Code :C#
// Arranging Data in an Array.
const int no_of_values = 2;
int[] val1 = new int[no_of_values];
int[] val2 = new int[no_of_values];
val1[0] = val1;
val2[0] = val2;
val1[1] = val11;
val2[1] = val22;
// Do the inserts using Parameterized queries.
Connection.Open();
SqlCeCommand command = Connection.CreateCommand();
command.CommandText = "Insert INTO [Table] (col1, col2) Values (...val1, ...val2)";
for (int i = 0; i < no_of_values; i++)
{
command.Parameters.Clear(); //it needs to clear parameter after each row inserted.
command.Parameters.Add("...val1", val1[ i ]);
command.Parameters.Add("...val2", val2[ i ]);
command.ExecuteNonQuery();
}
Connection.Close();

I have fixed this problem for MS SQL Server, it is also same for oracle too.
Hope that it may helpful for developers.

Monday, June 7, 2010

String Formatting in C#

Numbers

Basic number formatting specifiers:
Specifier Type Format Output (Passed Double 1.42) Output (Passed Int -12400)
c Currency {0:c} $1.42 -$12,400
d Decimal (Whole number) {0:d} System.FormatException -12400
e Scientific {0:e} 1.420000e+000 -1.240000e+004
f Fixed point {0:f} 1.42 -12400.00
g General {0:g} 1.42 -12400
n Number with commas for thousands {0:n} 1.42 -12,400
r Round trippable {0:r} 1.42 System.FormatException
x Hexadecimal {0:x4} System.FormatException cf90

Custom number formatting:
Specifier Type Example Output (Passed Double 1500.42) Note
0 Zero placeholder {0:00.0000} 1500.4200 Pads with zeroes.
# Digit placeholder {0:(#).##} (1500).42
. Decimal point {0:0.0} 1500.4
, Thousand separator {0:0,0} 1,500 Must be between two zeroes.
,. Number scaling {0:0,.} 2 Comma adjacent to Period scales by 1000.
% Percent {0:0%} 150042% Multiplies by 100, adds % sign.
e Exponent placeholder {0:00e+0} 15e+2 Many exponent formats available.
; Group separator see below

The group separator is especially useful for formatting currency values which require that negative values be enclosed in parentheses.

This table will help you to format the string value to double value:

Value           Format String              Result
1234.567     {0:0.00}                      1234.57
1234.567     {0:00000.0000}          01234.5670
1234.567     {0:#####.##}             1234.57
1234.567     {0:#.###}                   1234.567
1234.567     {0:#.#}                       1234.6
1234.567     {0:#,#.##}                  1,234.57
1234.567     {0:$#,#.##}                $1,234.57
1234.567     {0:$ #,#.##}               $ 1,234.57
1234.567     {0:($ #,#.##)}             ($ 1,234.57)
-1234.567    {0:#,#.##}                 -1,234.57
.1234           {0:#%}                       12%
.1234           {0:Percent = #.0%}     Percent = 12.3%

Example:
double dValue=1234.567;
string sCurrency =  dValue.ToString(" {0:0.00}",dValue);
Output: 1234.57

Or,
double dValue=23.00;
String.Format("{0:$#,##0.00;($#,##0.00);Zero}",dValue );
This will output “$1,240.00″ if passed 1243.50. It will output the same format but in parentheses if the number is negative, and will output the string “Zero” if the number is zero.

For more info: http://blog.stevex.net/string-formatting-in-csharp/

Deprecated HTML elements /Bad Tag

There are several HTML elements and attributes that have now been declared deprecated by the World Wide Web Consortium (the organization that sets HTML standards).

'Deprecated' means that the elements no longer serve a purpose and have been replaced by other methods, mostly involving cascading stylesheets (CSS). Although it is recommended that web browsers continue to support them, eventually they will become obsolete.

Here lists all the deprecated elements and attributes of HTML 4..
  1.  The FONT and BASEFONT tags
  2.  The CENTER tag and ALIGN attribute
  3. The U, S and STRIKE elements
  4. The BACKGROUND and BGCOLOR attribute
  5. The BORDER attribute
  6. The TEXT, LINK, ALINK and VLINK attributes
  7. The HPSACE and VSPACE attributes
  8. The LANGUAGE attribute
  9. The CLEAR attribute
  10. The WIDTH and HEIGHT attributes
  11. The TYPE attribute for lists
  12. The START and VALUE attributes for lists
  13. The COMPACT attribute for lists
  14. The APPLET element
  15. The DIR and MENU elements
  16. The ISINDEX element
  17. The NOSHADE and SIZE attributes for HR
  18. The NOWRAP attribute
  19. The VERSION attribute
For more details....Deprecated HTML element/ Bad Tag

How to get File size in ASP.NET/C#

In asp.net forum I have got this question many times like this, "How to get File size" or "How to get File Length". For this today I want to share with you how to get the file size in asp.net. Its very simple but helpful...

Code:C#

Add namespace:
Using System.IO;


string sMyFileName = "~/photos/test.jpg";

FileInfo finfo = new FileInfo(Server.MapPath(sMyFileName ));
long FileInBytes = finfo.Length;
long FileInKB = finfo.Length / 1024;
long FileInMB = FileInKB /1024;

Response.Write("File Size: " + FileInBytes.ToString() +
" bytes (" + FileInMB.ToString() + " MB)");

Windows 7 : C# Error:'Microsoft.Jet.OLEDB.4.0' provider is not registered on the local machine

Problem

Today I have faced this error when try to use MS Access database from SMS software. After goggling I have found the solution in ...
MSDN forum


Solution

The behavior you described is expected. If your application runs in 64-bit mode, all of the components it uses must also be 64-bit. There is no 64-bit Jet OLE DB Provider, so you get the message described. You would receive a similar error when trying to connect to a database using OLE DB or ODBC if there is no 64-bit version of the specified OLE DB provider or ODBC driver.
This problem only occurs in applications that run in 64-bit mode. Compiling the application so it runs only in 32-bit mode is the best current solution.

How to compile application to run in both 32 bit or 64 bit?
You can do it several ways...

Solution :1

You can edit your visual studio c# project file (.csproj) and put this snippet:
1.<PlatformTarget>x86</PlatformTarget>
inside
2.<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">


Solution :2
Using CorFlags to set the 32BIT flag on the executable. E.g:
corflags.exe myapp.exe /32BIT+

This will modify your exe, so you might wanna keep a backup just in case. You can also revert the flag using /32BIT- instead of /32BIT+.

Solution :3(Simplest way)
1.Right click your Project, and select Properties.
2.In properties, select the Build tab. Under Platform target, select x86.
3.Hit Ctrl+Shift+S to save all files, right click the Solution and select "Clean" to get rid of old binaries. Any builds after that should be 32 bit .
Now it is ready for both 32 bit and 64 bit OS.

This should solve the problem ! Please inform me if there is another better way.

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

Thursday, April 29, 2010

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.

Wednesday, April 28, 2010

Validation control not work in FireFox or other browser

When I use validation control on asp.net it works for IE fine but failed to work in Firefox. After goggling I will find the solution. I share this code here, hope it may help others.

The ASP.Net validations controls only work client side in IE.
You can make them work in other browsers, coding as below:

C#

Page.Validate();

if ( !Page.IsValid )
{
return;
}
//Continue Your code

VB.NET

Page.Validate()

If Not Page.IsValid Then
Return
End If
'Continue Your code


Have a nice day.

Tuesday, April 27, 2010

how to get MAC address using C#

How to get the MAC address of  system using Asp.net/C#

Now I want to share with you some simple but important for our rapid development.
Here I want to discuss how to get system MAC address using c# ,

First way:
You need to import the System.Net namespace for this to work.
This will support IPv4 and IPv6.


NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface adapter in nics)
    {
        IPInterfaceProperties properties = adapter.GetIPProperties();
        adapter.GetPhysicalAddress().ToString();
    }

Second way:
public string GetMACAddress()
{
  ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
  ManagementObjectCollection moc = mc.GetInstances();
  string MACAddress = String.Empty;
 foreach (ManagementObject mo in moc)
 {
     if (MACAddress == String.Empty) // only return MAC Address from first card   
           {
              if ((bool)mo["IPEnabled"] == true) MACAddress = mo["MacAddress"].ToString();
           }
      mo.Dispose();
 }

  MACAddress = MACAddress.Replace(":", "");
 return MACAddress;
}


You might want to also add  "mo["Caption"].ToString()" to test before the mac address so that you know which devices you are looking at.
Also, don't forget to use try/catch blocks on these as a NullPointerReference will kill the app.



How to get Client MAC address(Web):

To get the client MAC address only way we can rely on JavaScript and Active X control of Microsoft.It is only work in IE if Active X enable for IE. As the ActiveXObject is not available with the Firefox, its not working with the firefox and is working fine in IE.


This script is for IE only:

<script language="javascript">
     function showMacAddress(){

    var obj = new ActiveXObject("WbemScripting.SWbemLocator");
    var s = obj.ConnectServer(".");
    var properties = s.ExecQuery("SELECT * FROM Win32_NetworkAdapterConfiguration");
    var e = new Enumerator (properties);


    var output;
    output='<table border="0" cellPadding="5px" cellSpacing="1px" bgColor="#CCCCCC">';
    output=output + '<tr bgColor="#EAEAEA"><td>Caption</td><td>MACAddress</td></tr>';
    while(!e.atEnd())

    {
        e.moveNext();
        var p = e.item ();
        if(!p) continue;
        output=output + '<tr bgColor="#FFFFFF">';
        output=output + '<td>' + p.Caption; + '</td>';
        output=output + '<td>' + p.MACAddress + '</td>';
        output=output + '</tr>';
    }

    output=output + '</table>';
    document.getElementById("box").innerHTML=output;
}
</script>

Hope that it may help you.Please inform me if any one get any wrong with me.
Thanks

Monday, April 26, 2010

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

How to bind Data in Customized Gridview

In asp.net gridview control is widely used control. It has lots of properties and attributes which help the developers for rapid development. Generally we can use Gridvew to show data in tabular format.
But It has a lots of events and features which is make this control a most powerful control for asp.net.
There are various types of field in Gridview such as:
1.BoundField
2.ImageField
3.HyperLinkField
4.ButtonField
5.TemplateField
6.CommandField
7.CheckBoxField

These fields gives developer more flexibility to customize the gridview. Paging is efficiently handling by Gridview it is one of cool feature of it. There are various way to bind data into gridview.

Today I want to focus how to bind data to a customized gridview. I have used this following way to bind customized gridview very frequently. Obviously,there may be more easier way to bind in customize gridview.
Here I have used BoundField,Templatefield to customize the grid.


Here is the aspx code for Gridview:

<asp:GridView ID="gvUser" runat="server" AutoGenerateColumns="False" OnRowCommand="gvUser_RowCommand"  ShowHeader="true">

<Columns>
                        <asp:boundfield datafield="User_ID" headertext="User ID" visible="false">
                        <asp:boundfield datafield="User_NAME" headertext="User Name"></asp:boundfield>
                        <asp:boundfield datafield="User_ADDRESS" headertext="User Address"></asp:boundfield>                       
                        <asp:templatefield headertext="Edit Info">
                            <itemtemplate>
                                <asp:linkbutton commandname="EditRowData" d="lbtnEdit" runat="server"></asp:linkbutton>
                            </itemtemplate>
                        </asp:templatefield>
                        <asp:templatefield headertext="Delete Info">
                            <itemtemplate>
                                <asp:linkbutton commandname="DeleteRowData" id="lbtnDelete" runat="server"></asp:linkbutton>
                            </itemtemplate>
                        </asp:templatefield>
                        <asp:templatefield headertext="User Status">
                            <itemtemplate>
                                <asp:linkbutton commandname="ActiveRowData" id="lbtnActiveRow" runat="server"></asp:linkbutton>
                            </itemtemplate>
                        </asp:templatefield>
                        
                    </asp:boundfield>
               
Here is the aspx.cs code:
I have placed this code under Search button click event:
 
protected void btnSearch_Click(object sender, EventArgs e)
    {  
      
        oUserDeatilList = GetList();//Get List Of data from database.
        //You can retrieve data as you like it may be in dataset or datatable no matter.
        //I have discussed after that scenario.


        DataTable oDataTable = new DataTable("Sample");
        oDataTable.Columns.Add(new DataColumn("User_ID", typeof(string))); ;
        oDataTable.Columns.Add(new DataColumn("User_NAME", typeof(string)));
        oDataTable.Columns.Add(new DataColumn("User_ADDRESS", typeof(string)));
   

        // list of User Info are loaded into dataTable
        if (oUserDeatilList != null)
        {
            if (oUserDeatilList.UserDetailList.Count > 0)
            {
                foreach (CUserDetail oUserDetail in oUserDeatilList.UserDetailList)
                {
                    DataRow row = oDataTable.NewRow();
                    row["User_ID"] = oUserDetail.UserID;
                    row["User_NAME"] = oUserDetail.PersonName;
                    row["User_ADDRESS"] = oUserDetail.UserAddress;
               
                    oDataTable.Rows.Add(row);
                }
            }
        }
        gvUser.Columns[0].Visible = true;
        gvUser.Columns[1].Visible = true;
        gvUser.Columns[2].Visible = true;
        gvUser.Columns[3].Visible = true;
        gvUser.Columns[4].Visible = true;
        //bind data to gridview
        gvUser.DataSource = oDataTable;
        gvUser.DataBind();
        gvUser.Columns[0].Visible = false;

        // to generat linkButton text
        for (int i = 0; i < gvUser.Rows.Count; i++)
        {
            LinkButton lblEdit = ((LinkButton)gvUser .Rows[i].FindControl("lbtnEdit"));
            lblEdit.Text = "Edit";//you can do whatever you like with this control's property

            LinkButton lblDelete = ((LinkButton)gvUser.Rows[i].FindControl("lbtnDelete"));
            lblDelete.Text ="Delete";//you can do whatever you like with this control's property

            LinkButton lblActive = ((LinkButton)gvUser.Rows[i].FindControl("lbtnActiveRow"));
            lblActive.Text = "Active";//you can do whatever you like with this control's property
        }
    }

  
   protected void gvUser_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        GridViewRow gvRow = (GridViewRow)((LinkButton)e.CommandSource).NamingContainer;
        string sButtonText = ((LinkButton)e.CommandSource).CommandName;
        string sUserID = gvRow.Cells[0].Text;
     

        if (sButtonText.Equals("EditRowData"))
        {
            if (sUserID.Length > 0)
            {
                LinkButton oLinkButton = (LinkButton)gvRow.Cells[5].FindControl("lbtnEdit");
                string sUrl = "AddEditUser.aspx?" + USERID + "=" + sUserID;
                Response.Redirect(sUrl, false);
                //do whatever you like
            }
        }
        else if (sButtonText.Equals("DeleteRowData"))
        {
            if (sUserID.Length > 0)
            {
                LinkButton oLinkButton = (LinkButton)gvRow.Cells[5].FindControl("lbtnDelete");
                //or do whatever you like
            }
        }
        else if (sButtonText.Equals("ActiveRowData"))
        {
            if (sUserID.Length > 0)
            {
                LinkButton oLinkButton = (LinkButton)gvRow.Cells[5].FindControl("lbtnActiveRow");
                if (oLinkButton.Text.Equals("ACTIVE")
                {
                    oLinkButton.Text = "INACTIVE";
                }
                else
                {
                     oLinkButton.Text = "ACTIVE";
                }
                //do whatever you like
             
            }
        }      
    }

Hope that it may help you.

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

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