Archive for the ‘Asp.Net’ Category
Handling multiple configuration settings (Development, Staging, Production) gracefully.
In Asp.net 2.0 multiple connectionStrings & appSettings can be handled very easily using the attribute “configSource”
create a new xml file devAppSettings.config under a new folder myConfigsettings
AJAX – Export to Excel / Word
If you are using Update Panel and try to Export gridview contents to EXCEL or Word, your asp.net page will throw nasty error. “Sys.WebForms.PageRequestManagerParserErrorException”
Its because AJAX & Response.write don’t go together. By calling Response.Write() directly you are bypassing the normal rendering mechanism of ASP.NET controls. The bits you write are going straight out to the client without further processing (well, mostly…). This means that UpdatePanel can’t encode the data in its special format.
There are couple of ways to solve this problem.
1. Place the Export Button outside of Update Panel.
2. By Pass the Export Button using <Triggers>
</ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID=”cmdExport” />
</Triggers>
</asp:UpdatePanel>
if your Export button is part of UserControl then specify usercontrolid:buttonid
</ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID=”uscSelCtl:cmdExport” />
</Triggers>
</asp:UpdatePanel>
Asp.net Web Service Timing Out (0x80004005)
Recently if your webservices started failing / timing out it its worth your time to take a look at this support article.
“HttpException (0x80004005): Request timed out.”
“System.InvalidOperationException: There were not enough free threads in the ThreadPool object to complete the operation”
Contention, poor performance, and deadlocks when you make Web service requests from ASP.NET applications
http://support.microsoft.com/kb/821268
Related Reading :
Item 5 talks about Asp.Net WS
Asp.Net Filter Datatable by Column
Filter Datatable by Rows
If you need to get subset of a big dataset into datatable Rowwise …
Dim dtEmp as DataTable Dim dsEmployee as New DataSet dsEmployee = someobject.getdata() 'dataset can be populated in many ways which is not explained here. Dim sExpr as String Dim drRows() as DataRow, drSingleRow as DataRow sExpr = "EmpID > 100" 'Condition drRows = dsEmployee.Tables(0).Select(sExpr) 'If you need to add Sort Order it can be added to sExpr Dim sSortOrder as String sSortOrder = "EmpName DESC" drRows = dsEmployee.Tables(0).Select(sExpr,sSortOrder) For Each drSingleRow in drRows dtEmp.ImportRow(drRows) Next ' Datatable dtEmp has filtered records
Filter Datatable by Column
If you need to get subset of big dataset into datatable columnwise…
Dim dtEmp as DataTable Dim dsEmployee as New DataSet dsEmployoee = someobject.getdata() 'dataset can be populated in many ways which is not explained here. 'This copies the structure and data dtEmp = dsEmployee.Tables(0).Copy dtEmp.Columns.Remove("Unwanted Column 1") dtEmp.Columns.Remove("Unwanted Column 2") dtEmp.Columns.Remove("Unwanted Column 3")
Prevent Session Timeout in Asp.net
Prevent Session Timeout in Asp.net [VB]
ASP.Net 2.0 [VB]
Inspired by this article from Code Project. [Thanks Ach1lles ]
I slightly modified few things to work for VB and VS2005 environment. The code works perfect and I’m very happy with it.First I created a Module file and created this function.
Public Function KeepAlive() As String Dim int_MilliSecondsTimeOut As Integer = (HttpContext.Current.Session.Timeout * 60000) - 30000 Dim sScript As New StringBuilder sScript.Append("<script type='text/javascript'>" & vbNewLine) 'Number Of Reconnects sScript.Append("var count=0;" & vbNewLine) 'Maximum reconnects Setting sScript.Append("var max = 6;" & vbNewLine) sScript.Append("function Reconnect(){" & vbNewLine) sScript.Append("count++;" & vbNewLine) sScript.Append("var d = new Date();" & vbNewLine) sScript.Append("var curr_hour = d.getHours();" & vbNewLine) sScript.Append("var curr_min = d.getMinutes();" & vbNewLine) sScript.Append("if (count < max){" & vbNewLine) sScript.Append("window.status = 'Refreshed ' + count.toString() + ' time(s) [' + curr_hour + ':' + curr_min + ']';" & vbNewLine) sScript.Append("var img = new Image(1,1);" & vbNewLine) sScript.Append("img.src = 'http://localhost/myapp/reconnect.aspx';" & vbNewLine) sScript.Append("}" & vbNewLine) sScript.Append("}" & vbNewLine) sScript.Append("window.setInterval('Reconnect()',") sScript.Append(int_MilliSecondsTimeOut.ToString() & "); //Set to length required" & vbNewLine) sScript.Append("</script>") KeepAlive = sScript.ToString End Function
All this code does is, build a simple javascript function and its called from server side.The works like this,- Gets the current session timeout duration.
– Subtract 30 seconds from it and assign it to MilliSecondsTimeOut variable
– Create a Reconnect() javascript function
– Create a global variable with max value 6
– Get current hour and Min [just for displaying the last refresh time]
– Verify whether count is less than max value (ie 6)
– If so, change the window status with Text
– Create a dummy image and set reconnect.aspx url as its source [this way a call is made to server and it wont session timeout]Create a timer using window.setInterval and assign the MilliSecondsTimeOut value.
[this way this function is called 30 seconds before session timeout]Tha max value (6) can be set to any number. If its 6 then this session timeout is avoided 5 times.
Default session timeout is 20min. 20 * 5 = 100 mins. Which is good for non-secure page.
Then
On the pages where I want to prevent Session Timeout I entered this line.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load Try 'dont forget to add this line Page.ClientScript.RegisterClientScriptBlock(Me.GetType, "reconn key", KeepAlive()) If Not Page.IsPostBack Then --- --- --- End If Catch eX as Exception '---- End Try End Sub
Created reconnect.aspx in Visual Studio and deleted the .vb and .designer.vb files.This is the final version of reconnect.aspx
<%@ Page Language="vb" AutoEventWireup="false"%> <%@ OutputCache Location="None" VaryByParam="None" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "<a href="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" mce_href="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd</a>"> <html xmlns="<a href="http://www.w3.org/1999/xhtml" mce_href="http://www.w3.org/1999/xhtml">http://www.w3.org/1999/xhtml</a>" > </html>
Note : When you compile the project sometimes, VS2005 complains reconnect.aspx is not in right format.
So I EXCLUDED this file from my project. Now VS 2005 will compile without complaining and the logic will also work.- Happy Programming
Copy Datatable from one Dataset to another Dataset
Copying a datatable from one dataset to another was not that straightforward as I thought.
Dim dsSource As New DataSet Dim dsDestination As New DataSet 'Your way to get data from XML or DB. dsSource = object.getdata() dsDestination = object.getmoredata() 'This is important, without this it will result in error 'when you try to copy the datatable from one dataset to another dsSource.Tables(0).TableName = "NewTableName" dsDestination.Tables.Add(dsSource.Tables(0).Copy) dsDestination.Tables(0).Tablename = "SomeTable" dsDestination.Tables(1).Tablename = "NewTableName" 'The one we copied from other Dataset
Note 1 : When you are using more than one datatable in a dataset it is advisable you name the datatables.
Note 2 : These kinds of scenarios arise, when you are trying to establish Relation between datatables in a dataset.
(Cascading master – detail relation)
Creating dynamic, fancy EmptyDataText for GridView
Gridview has capability to display “default” messages when “No data” exists during binding.
Standard Way in .aspx
<asp:GridView ID=”gvControl” runat=”server” AutoGenerateColumns=”False” GridLines=”None” CellPadding=”0″ CellSpacing=”0″ OnRowDataBound=”gvCategories_RowDataBound” BackColor=”#dddddd” ShowHeader=”false” EmptyDataText=”<BR> No data exists <BR><BR>“>
….
…..
</asp:GridView>
Fancy Way (.vb or .cs)
You can make it fancy & dynamic by doing it in code behind.
Create fancy texts using WordArt (MS Word) and copy it to Image Editor (Paint.net, gimp, Paint) and save it as JPG.
gvControl.EmptyDataText = "<img src='~/images/NoData.jpg' border='0'>" gvControl.EmptyDataRowStyle.HorizontalAlign = HorizontalAlign.Center gvControl.databind
Note: When you use emptydatatext in codebehind donot forget to use databind.
‘The invoked member is not supported in a dynamic module.’
Error ‘The invoked member is not supported in a dynamic module.’ while generating exception string
While Using ASPUnhandledException.dll for exception handling, I received this error via email.
This error message was not at all helpful in production environment.
On careful debugging I found out that my Stored Proc failed.
Instead of giving the reason for Stored Proc failure it gave this obscure message. If someone knows why it gives this message it will be helpful.
(reason my sp failed was because I was calling a non-existing user defined function)
How to add Company & Version details to your Assembly file or .dll ?
If you want to add details like (Your [company] name, Product name, Copyright info, Version Number) to your custom library ?
ex :
Its very simple.
Open Assembly.vb or Assembly.cs and modify the following items.
You can add more attributes that are not given here. Use Visual Studio intelli-sense to find more attributes.
[VB]
<Assembly: AssemblyTitle(“Your Library Name”)>
<Assembly: AssemblyDescription(“Description about the library”)>
<Assembly: AssemblyCompany(“Your Company name”)>
<Assembly: AssemblyProduct(“Product Name”)>
<Assembly: AssemblyCopyright(“Copyright © 2007”)>
<Assembly: AssemblyTrademark(“Product Trademark”)>
<Assembly: ComVisible(False)>
<Assembly: AssemblyVersion(“1.0.0.0”)>
<Assembly: AssemblyFileVersion(“1.0.0.0”)>
Locking Cell and Changing Cell Style UltraWebGrid
Refer this article for Column Locking / Freezing in Infragistics Ultra WebGrid
If you need to change background color for a frozen columns then ..
backcolor property must be changed first then cells have to be locked.
e.Layout.Bands(0).Columns(0).CellStyle.BackColor = Drawing.Color.Beige e.Layout.Bands(0).Columns(0).Header.Fixed = True
and in InitializeLayout of ultraWebgrid
Private Sub ultrawebgrid_InitializeLayout(ByVal sender As Object, ByVal e As Infragistics.WebUI.UltraWebGrid.LayoutEventArgs) Handles uwgCategory.InitializeLayout e.Layout.UseFixedHeaders = True End Sub
Call Javascript Function inside asp:Hyperlink Control
If you ever want to call a javascript function (with or without parameter) from a server side hyperlink control here it is..
Step 1 :
declare your javascript function between
Step 2:
<asp:HyperLink ID=”hypCate” runat=”server”
NavigateUrl='<%# “javascript:showPopUp(” & DataBinder.Eval(Container.DataItem, “ID”) & “);” %>’
Text='<%#DataBinder.Eval(Container.DataItem, “Name”)%>’ />
Carefully follow the single and double quotes for NavigateUrl attribute.
Needless to say showPopUp is the name of Javascript Function.
It displays the NAME as hyperlink. Clicking that calls javascript showPopUp.
Column Locking / Freezing in Infragistics Ultra WebGrid
(NetAdvantage for ASP.NET)
If you want to freeze first few columns like EXCEL and horizontally scroll rest of the columns in Ultra WebGrid here you go…
Event :
UltraWebGrid1_InitializeLayout(object sender, Infragistics.WebUI.UltraWebGrid.LayoutEventArgs e)
VB Code :
e.Layout.UseFixedHeaders = true e.Layout.Bands(0).Columns(1).Header.Fixed = true e.Layout.Bands(0).Columns(2).Header.Fixed = true
Above code freezes the two columns (second,third) in Grid.
C# Code
protected void UltraWebGrid1_InitializeLayout(object sender, Infragistics.WebUI.UltraWebGrid.LayoutEventArgs e) { e.Layout.UseFixedHeaders = true; e.Layout.Bands[0].Columns[1].Header.Fixed = true; e.Layout.Bands[0].Columns[2].Header.Fixed = true; }
Gridview : Empty First Row / Asp.net 2.0
If you using Gridview control and your Grid doesnt have HEADER information then make sure you turn off the “ShowHeader” property for that Gridview or else you will notice a blank line on top of the grid. If you are
If you do viewsource you will notice this mystery line <tr><th></th</tr> as first line of grid table.
Create/Manage Multiple Websites in IIS on Windows 2000 / XP
On Windows 2000/XP Professional only one website can be created in IIS. (i.e) default website.
If you have some requirement for testing multiple websites on same development box its not possible with IIS alone.
FREE IIS Management tool
JetStat has a tool to accomplish the above mentioned task. “IISAdmin”
It has some cool features like
– Create and Manage as many local IIS web sites.
– Install and configure asp scripts on local web sites
– Gives quick access to home folder of the website
– Enabling advanced features on creation of new web site
– Quick access to IIS Management Console
– Automatically configures database folder permissions
– Full support Windows 2000/XP (IIS 5.0, 5.1, 6.0)
– Easy of use and flexible
The application is FREE and it doesn’t occupy much space.
Download from here.
Asp.net Get/Set Date and Time as String
In many occasions all we may need is simple date and time.
Now property gives more information which needs to be trimmed down using Format function. Here we have two handy string type properties from Microsoft.
TimeString Property
Returns or sets a String value representing the current time of day according to your system.
TimeString always returns the system time as “HH:mm:ss“, which is a 24-hour format. This format is culture-invariant, which means it does not change even if you change the Regional Options in Control Panel.
ex :
Dim MyTime As String = TimeString If CInt(TimeString.Substring(0, 2))Â < 12 Then MyGreeting = Reverse("Good Morning") Else MyGreeting = Reverse("Good Afternoon") End If
Timeofday : returns / sets the same but as date datatype.
ooOoo
DateString Property
DateString always returns the system date as “MM-dd-yyyy“, which uses the abbreviated month name.
These formats are culture-invariant, which means they do not change even if you change the Regional Options in Control Panel.
Today : returns / sets the same but as date datatype.
Interface vs Base Class (.Net)
Interface is similar to a base class, it is also very different.
They are similar..
– Both provide structure to another class that uses them
– Both can be used for polymorphism
Interfaces are different than base classes ..
– A class can inherit only one base class, but it can implement many interfaces. (Very important)
– A base class can contain implementation, an interface cannot contain implementation
– Interfaces can only contain Methods, Properties, Indexers, and Events. They cannot contain fields or constants (which are used for implementation)
Steps to Change from Visual Studio Development Server to Use IIS Web Server
Using Visual Studio 2005
1. Goto Project Properties > Select Web Tab
2. Click “Use IIS Web Server” radio button
3. Click on “Create Virtual Directory” button
4. Open Web.config and change debug to true <compilation debug=”true”>
5. Open IIS (Start > Run > Inetmgr)
6. Goto that your project Virtual Directory
7. Right click > Select Properties
8. Under Virutal Directory Tab, make sure it has Application Name. If its blank, click on Remove button next to it and click Create.
9. Under ASP.Net tab make sure Asp.net Version is 2.0 or whatever you need
10. Under Directory Security tab click EDIT
11. Make sure Anonymous and Integrated Windows authentication is enabled.
If these steps are not followed
you may not be able to debug you application using Visual Studio,
you may not be able to use IIS web server or its features.
Asp.net Detecting Session timeout and redirection
If you are using Basepage logic its better to use this code there.
Redirection logic is written for pages with Frames or without Frames
Protected Overrides Sub OnPreRender(ByVal e As System.EventArgs) MyBase.OnPreRender(e) If context.Session.IsNewSession = True Then Dim strCookieHeader As String = Page.Request.Headers("Cookie") If Not strCookieHeader Is Nothing Then strCookieHeader = strCookieHeader.ToLower End If 'Checking for duplicate Session. If Not strCookieHeader Is Nothing AndAlso strCookieHeader.IndexOf("asp.net_sessionid") >= 0 Then If Page.Request.IsAuthenticated = True Then System.Web.Security.FormsAuthentication.SignOut() End If 'If you want to redirect to defaultpage you can use this 'Page.Response.Redirect("default.aspx?Timeout") 'If you are using Frames then this will work. Response.Write("window.open('default.aspx?Timeout','_parent');") End If End If End Sub
Recordset to Datatable (Asp.Net)
If you are migrating your application from Asp to Asp.Net, Recordsets to Datatable will be key issue.
If you want to utilize the power of Datagrid or any Asp.net controls then DataTable and DataSets is the way to go.
Fortunately converting Recordset to DataTable or DataSet is very easy.
Steps
1 . Create an OleDb DataAdapter
2. Create a DataTable Object
3. Fill the Adapter with Recordset values.
4. Add DataTable to DataSet (if needed)
Now the coding part
Dim MyAdapter As OleDbDataAdapter = New OleDbDataAdapter() Dim <strong>dtRSTable</strong> As System.Data.DataTable = New DataTable() MyAdapter.Fill(<strong>dtRSTable</strong>, Rs) Now <strong>dtRSTable</strong> is ready. This dtRSTable can be directly referenced in a datagrid or added to DataSet dgSampleGrid.datasource = dtRSTable.Defaultview dgSampleGrid.databind 'or 'Adding DataTable to DataSet dim dsTable as New DataSet dsTable.Tables.Add(dtRSTable)
Comment on Server Side Asp.Net
with 2 comments
Inspired by ASP.NET 2.0 Server Side Comments
If you want to comment a particular column in GridView, HTML commenting approach wont work.
You have to use
example:
Written by gchandra
October 2, 2007 at 9:53 am
Posted in Asp.Net, Tips and Tricks
Tagged with Asp.Net, Commenting, ServerSideControl