Friday, September 25, 2009
Handling Master Page Click Events in the Content Page
Wednesday, August 19, 2009
Silverlight 2.0: usage of the converters from external assembly in app.xaml
it is my first post and I'd like to strat it from a small trick for defining value converters in app.xaml file in silverlight project.
Problem:
If you define Converters in app.xaml (see below) then you find that Visual Studio designer fails to render User Controls (Visual Studio designer become blank).
Upd: not the converter defenition in app.xaml file cause the visual studio designer to go blank but xmlns defenition.
Solution:
To avoid this designer problem move namespace declaration closer to usage:
Voila!!! now designer work perfect and able to render our content.
Tuesday, August 18, 2009
What’s new in .NET Framework 4.0
· Performance and Scalability of WCF and WF are expected to increase by minimum 10X.
· New workflow models.
· Seamless integration between WCF and WF including a new Visual Designer.
· Parallel Programming framework using PLINQ, Task Parallel Library and Coordination Data Structures to better utilize power of multi-processor and multi-core machines.
· Build declarative applications with WF, WCF and WPF using XAML. So, XAML is no more only for WPF and WF.
· WCF enhancements :
o RESTful enhancements
§ Simplifying the building of REST Singleton & Collection Services, ATOM Feed and Publishing Protocol Services, and HTTP Plain XML Services using WCF
§ WCF REST Starter Kit to be released on Codeplex to get early feedback
o Messaging enhancements
§ Transports - UDP, MQ, Local in-process
§ Protocols - SOAP over UDP, WS-Discovery, WS-BusinessActivity, WS-I BP 1.2
§ Duplex durable messaging
o Correlation enhancements
§ Content and context driven, One-way support
o Declarative Workflow Services
§ Seamless integration between WF and WCF and unified XAML model
§ Build entire application in XAML, from presentation to data to services to workflow
· WF enhancements :
o Significant improvements in performance and scalability
§ Ten-fold improvement in performance
o New workflow flow-control models and pre-built activities
§ Flowcharts, rules
§ Expanded built-in activities – PowerShell, database, messaging, etc.
o Enhancements in workflow modeling
§ Persistence control, transaction flow, compensation support, data binding and scoping
§ Rules composable and seamlessly integrated with workflow engine
o Updated visual designer
§ Easier to use by end-users
§ Easier to rehost by ISVs
§ Ability to debug XAML
· First CTP to be released during PDC in Oct 2008.
· Information on this page will be updated as and when it is available.
.stylebak1 {
background-color:silver;
}
.style2 {
text-align: left;
font-family: Verdana;
}
.style3 {
text-align: left;
font-family: Arial, Helvetica, sans-serif;
}
.style4 {
color: #FFFFFF;
background-color: #000000;
}
Related Articles
Parallel Computing using .NET framework - Overview
Master Managed Threading and Synchronization Techniques
Creating Virtual directory in IIS with c#
Important URLs
http://www.brainbell.com/tutorials/ASP/Using_Personalization.html
http://www.webreference.com/programming/asp/site_appearance3/2.html
JavaScript:
http://it.toolbox.com/blogs/coding-dotnet/validation-of-date-using-javascript-18023
http://www.aspdotnetcodes.com/ViewQuestion_161.aspx
weschools.com
jQuery Tutorials for Designers
http://www.webdesignerwall.com/tutorials/jquery-tutorials-for-designers/
LINQ URL
http://csainty.blogspot.com/2008/01/linq-to-sql-insertupdatedelete.html
http://www.codeproject.com/KB/linq/LINQSQLCS.aspx
http://www.aspnettutorials.com/tutorials/database/linq-adding-database-ajax-cs.aspx
http://69.10.233.10/KB/WPF/binding_in_linq-sql.aspx?display=Print
http://www.c-sharpcorner.com/UploadFile/scottlysle/GenericL2SinCS07212008041344AM/GenericL2SinCS.aspx
SharePoint Interview Question URL
http://www.megasolutions.net/qs/Sharepoint_Portal_Interview_Questions.aspx
SQL Server URL
http://sqltips.wordpress.com/category/row_number/
http://www.blogtoplist.com/software/blogdetails-11403-3.html
http://database.ittoolbox.com/documents/popular-q-and-a/how-to-find-the-nth-maxmin-records-in-sql-server-2803
http://www.sqlteam.com/article/find-nth-maximum-value-in-sql-server
http://www.planet-source-code.com/URLSEO/entrancegeneric/ShowWorldSeOnly!asp/blnResetAllVariables!False/intFirstRecordOnPage!1/intLastRecordOnPage!20/intLastRecordInRecordset!5806/cmdGoToPage!2/lngWId!10/anyname.htm
http://www.geekpedia.com/tutorial181_Capturing-screenshots-using-Csharp.html
http://www.codeproject.com/KB/aspnet/NTierApp_UsingLINQ.aspx
http://www.hookedonlinq.com/StandardQueryOperators.ashx
One More for AJAX
http://www.worldofasp.net/News/AJAX/re-2747_How-to----move-from-AjaxPro-to-ASP-NET-AJAX-PageMethods.aspx
http://www.asp.net/ajax/documentation/live/tutorials/ExposingWebServicesToAJAXTutorial.aspx
Microsoft's founder and head Bill Gates steps down
http://www.microsoft.com/presspass/exec/billg/videos/default.aspx?videoID=0
Tired of querying in antiquated SQL?
http://linqpad.net/
Create Data-Centric Web Applications With Silverlight 2
http://msdn.microsoft.com/hi-in/magazine/cc895493(en-us).aspx?pr=blog
Winwodws Workflow Foundation - Good Links
http://joeon.net/post/Windows-Communication-Foundation---65-Links-to-make-you-an-expert!.aspx
http://weblogs.asp.net/scottgu/archive/2006/08/31/windows-workflow-foundation.aspx
http://msdn.microsoft.com/en-us/library/ms734584(VS.85).aspx
http://joeon.net/post/2008/02/Windows-Workflow-Foundation-Tutorial-Series.aspx
SharePoint - Search Link for WSS 3.0 & MOSS 2007
http://msdnrss.thecoderblogs.com/2008/09/16/spsearchasmx-web-service-will-not-return-any-results-in-the-search-server-2008-integrated-wss-30-environment/
http://sharepointmagazine.net/news/analysis/leveraging-the-sharepoint-platform-part-1
http://sharepointmagazine.net/news/analysis/leveraging-the-sharepoint-platform-part-1
Data Access Tutorials http://www.asp.net/learn/data-access/
SharePoint Reference Site URL
http://laflour.spaces.live.com/
http://msdn.microsoft.com/en-us/library/bb386295.aspx
http://www.google.com/chrome/index.html?hl=en&brand=CHMG&utm_source=en-hpp&utm_medium=hpp&utm_campaign=en
to fetch mails from our pop3 account and store it in db using .net 2.0?
http://www.codeproject.com/KB/IP/Pop3MailClient.aspx
http://microsoft.apress.com/asptodayarchive/72309/listing-all-windows-user-group-accounts-from-asp
SharePoint And Silverlight Integration Presentation Link
http://www.slideshare.net/andynogueira/share-point-summit-2008-andy-nogueira-share-point-and-silverlight
http://www.slideshare.net/andynogueira/share-point-summit-2008-andy-nogueira-share-point-and-silverlight
Silverlight Toolkit URL
http://www.codeplex.com/Silverlight
While in the journey of a fast life, amidst so much competition, anxiety, corporate race, I had a chance to read this. It touched me. So I thought of sharing with you…
CrossTab SQL
http://sqlblogcasts.com/blogs/madhivanan/archive/2007/08/27/dynamic-crosstab-with-multiple-pivot-columns.aspx
Test your web design in different browsers
If you want to test your web application in different browser on different OS, you can use this link (if you do not have systems having different OS and different browser)
http://browsershots.org/
Developing PHP On Your Visual Studio 2008/2005
http://www.dev102.com/2008/09/16/developing-php-on-your-visual-studio-20082005/
SQL URL
http://blogs.msdn.com/lcris/archive/category/12750.aspx
http://www.asp.net/learn/security/view.aspx?__id=05&__language=cs&supportsjs=true
http://quickstarts.asp.net/QuickStartv20/aspnet/doc/security/login.aspx#createuser
Security Basics and ASP.NET Support
http://www.asp.net/Learn/Security/tutorial-01-cs.aspx
Introduction to Web Programming
http://www.microsoft.com/mspress/books/sampchap/6714.aspx
http://support.microsoft.com/kb/178222/en-us
http://support.microsoft.com/kb/162059
Hope you have see this link for Silverlight demo site. Can we plan something like this for a demo site
http://www.mscui.net/PatientJourneyDemonstrator/
http://www.slideshare.net/spushpak/dot-net-training-wcf-dot-net35
Reflection on C# http://basgun.wordpress.com/2008/08/15/virtual-earth-map-control-aspnet/
Remote Desktop Manager using C# - URL
http://www.codeproject.com/KB/cs/Palantir.aspx
Sample Web Application for .NET Clients - URL
http://coherence.oracle.com/display/COH34UG/Sample+Web+Application+for+.NET+Clients
he assembly created from our compiled classes is placed within a subdirectory of
C:\WINDOWS\Microsoft.NET\Framework\VersionNumber\Temporary ASP.NET Files\WebTime
where VersionNumber is the version number of the .NET Framework (e.g., v2.0.50215) installed on your computer.
The below link is for REST
http://weblogs.asp.net/shijuvarghese/archive/2008/04/04/rest-and-wcf-3-5.aspx
URL : FTP, Email, And Threading using C#
FTP C# Examples
http://www.example-code.com/csharp/ftp.asp
Threading in C#
http://www.albahari.com/threading/
Email Object C# Examples
http://www.example-code.com/csharp/emailObject.asp
Workflow Links
http://live.sharepointcommunity.de/wiki/Wiki-Seiten/Workflow.aspx
Threading in C#
http://www.albahari.com/threading/
MOSS Multilingual Site Configuration
http://www.codeproject.com/KB/sharepoint/MOSS_multilingual.aspx
Visual Studio 2008 and .NET Framework 3.5 Training Kit
http://www.microsoft.com/downloads/details.aspx?familyid=8BDAA836-0BBA-4393-94DB-6C3C4A0C98A1&displaylang=en
RSS URL
http://www.mnot.net/rss/tutorial/#What
http://www.rssdotnet.com/documents/code_examples.html
http://cyber.law.harvard.edu/rss/rss.html
http://rss-net.sourceforge.net/documents/class_library_reference/
http://www.dotnetcurry.com/BrowseArticles.aspx?CatID=54&AspxAutoDetectCookieSupport=1
Good Links
http://www.carlosag.net/Tools/CodeTranslator/
http://www.bigresource.com/VB-Get-Internet-Connection-Speed-amp-Bytes-Sent-Received-oilD7D4A9C.html
http://www.bigresource.com/VB-Internet-Connection-Speed-rcZw8KbK70.html
ASP.NET Developer Center
http://msdn.microsoft.com/hi-in/asp.net/default.aspx
Silverlight
http://msdn.microsoft.com/hi-in/silverlight/default(en-us).aspx
Visual Studio 2008 Samples URL
http://msdn.microsoft.com/hi-in/vs2008/bb330936%28en-us%29.aspx
how to Update Multiple rows in sql server table
Hello,
I want to Update Multiple rows in sql server table.
Like Tablename is tblA and I have 2 columns in it id and name
now I want to update more than 1 rows at a time like name=a(id=1),name=b(id=2),name=c(id=3).. and more
let me know the optimized query with example if u can.
Use bulkinsert functionality of sql server 2005
http://develtop.tistory.com/entry/Bulk-Insert-into-SQL-from-C-App
URL : 6 basic steps of how to create a WebPart in SharePoint
http://www.c-sharpcorner.com/UploadFile/shivprasadk/12222301222009065151AM/122223.aspx
http://www.c-sharpcorner.com/UploadFile/sharepointholic/SharePointCustomizationTricks101192009140559PM/SharePointCustomizationTricks1.aspx
http://www.c-sharpcorner.com/UploadFile/mahesh/CustomControls10082008232606PM/CustomControls.aspx
Hope you have see this link for Silverlight demo site. Can we plan something like this for a demo site
http://www.mscui.net/PatientJourneyDemonstrator/
Hotfix for Visual Studio hang when opening Web project from a remote site
http://blogs.msdn.com/xmlteam/archive/2009/03/06/hotfix-for-visual-studio-hang-when-opening-web-project-from-a-remote-site.aspx
Creating JSON-enabled WCF services in .NET 3.5
http://www.pluralsight.com/community/blogs/fritz/archive/2008/01/31/50121.aspx
http://dotnetslackers.com/articles/ajax/JSON-EnabledWCFServicesInASPNET35.aspx
http://jeffbarnes.net/portal/blogs/jeff_barnes/archive/2007/11/19/how-to-ajax-enable-a-wcf-service.aspx
http://geekswithblogs.net/technetbytes/archive/2008/05/29/122496.aspx
http://msdn.microsoft.com/en-us/library/bb412167.aspx
http://www.codeproject.com/kb/ajax/aspnetchat.aspx
Unable to add data connection
http://usedotnet.blogspot.com/2008/10/visual-studio-2008-error.html
Stored procedures to implement paging for large tables or queries in SQL Server 2005 and SQL Server 2008
http://www.mssqltips.com/tip.asp?tip=1699
Using CSS and Styles with the Menu Control
http://msdn.microsoft.com/en-us/library/ms366731.aspx
Using Linq To SQL with ObjectDataSource Control
http://weblogs.asp.net/zeeshanhirani/archive/2008/05/05/using-linq-to-sql-with-objectdatasource-control.aspx
http://www.c-sharpcorner.com/UploadFile/scottlysle/GenericL2SinCS07212008041344AM/GenericL2SinCS.aspx
http://cgeers.wordpress.com/2008/12/06/aspnet-menu-sliding-doors-of-css/#download
http://cgeers.wordpress.com/download/
Output Caching Master Page in ASP.NET
http://dotnetperls.com/Content/Output-Caching-Master-Page.aspx
How To Call WebService
http://silverlight.net/forums/p/24005/86700.aspx#86700
http://weblogs.asp.net/nilotpal/archive/2008/09/19/hosting-a-service-on-iis.aspx
SharePoint URL:
http://pramodtech.blogspot.com/2007/05/moss-2007-faqs.html
Mobile URL:
http://cid-0779b8ef58de4561.skydrive.live.com/browse.aspx/Public
===========
http://aspnetinfo.googlepages.com/home
http://moredotnet.googlepages.com
1) C:\WINDOWS\Microsoft.NET\Framework\v3.0\Windows Communication Foundation\ServiceModelReg.exe –i
2) iisreset
OR
1) aspnet_regiis –ua
2) aspnet_regiis –i
3) C:\WINDOWS\Microsoft.NET\Framework\v3.0\Windows Communication Foundation\ServiceModelReg.exe –i
4) iisreset
Using Page.ClientScript.RegisterClientScriptBlock
The RegisterClientScriptBlock method allows you to place a JavaScript function at the top of the
page. This means that the script is in place for the startup of the page in the browser.
C#
Using Page.ClientScript.RegisterStartupScript
The RegisterStartupScript method is not too much different from the RegisterClientScriptBlock
method. The big difference is that the RegisterStartupScript places the script at the bottom of the
ASP.NET page instead of at the top.
protected void Page_Load(object sender, EventArgs e)
{
string myScript = @"alert(document.forms[0][’TextBox1’].value);";
Page.ClientScript.RegisterStartupScript(this.GetType(),
"MyScript", myScript, true);
}
Using Page.ClientScript.RegisterClientScriptInclude
The final method is RegisterClientScriptInclude. Many developers place their JavaScript inside a
.js file, which is considered a best practice because it makes it very easy to make global JavaScript
changes to the application. You can register the script files on your ASP.NET pages using the Register-
ClientScriptInclude method
C#
string myScript = "myJavaScriptCode.js";
Page.ClientScript.RegisterClientScriptInclude("myKey", myScript);
This creates the following construction on the ASP.NET page:
Monday, August 17, 2009
Alert/Prevent Users From closing the browser
Open a PopUp Window on the ASP.NET Button Click event and pass Parameters
C#
protected void Button1_Click(object sender, EventArgs e)
{
string queryString =
"http://localhost:39208/TreeView.aspx?param1="
+ TextBox1.Text.Trim();
string newWin =
"window.open('" + queryString + "');";
ClientScript.RegisterStartupScript
(this.GetType(), "pop", newWin, true);
}
VB.NET
Protected Sub Button1_Click(ByVal sender As Object, _
ByVal e As EventArgs)
Dim queryString As String = _
"http://localhost:39208/TreeView.aspx?param1=" & _
TextBox1.Text.Trim()
Dim newWin As String = _
"window.open('" & queryString & "');"
ClientScript.RegisterStartupScript(Me.GetType(), _
"pop", newWin, True)
End Sub
Export GridView to Excel
C#
protected void Button1_Click(object sender, EventArgs e)
{
Response.AddHeader("content-disposition",
"attachment;filename=FileName.xls");
Response.Charset = String.Empty;
Response.ContentType = "application/vnd.xls";
System.IO.StringWriter sw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter hw = new HtmlTextWriter(sw);
GridView1.RenderControl(hw);
Response.Write(sw.ToString());
Response.End();
}
VB.NET
Protected Sub Button1_Click(ByVal sender As Object, _
ByVal e As EventArgs)
Response.AddHeader("content-disposition", _
"attachment;filename=FileName.xls")
Response.Charset = String.Empty
Response.ContentType = "application/vnd.xls"
Dim sw As System.IO.StringWriter = _
New System.IO.StringWriter()
Dim hw As System.Web.UI.HtmlTextWriter = _
New HtmlTextWriter(sw)
GridView1.RenderControl(hw)
Response.Write(sw.ToString())
Response.End()
End Sub
To read about some more tips and tricks about the GridView, check GridView Tips and Tricks using ASP.NET 2.0
Supress Postback on an ASP.NET ImageButton
ASP.NET Image Button
Using MarkUp - Observe the onClientClick event
runat="server" OnClientClick="return false;" />
Using Code Behind:
C#
protected void Page_Load(object sender, EventArgs e)
{
btnShow.Attributes.Add("onclick", "return false;");
}
VB.NET
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
btnShow.Attributes.Add("onclick", "return false;")
End Sub
HTML Image Button
To prevent postback on an HTML Image button, use the following tag:
onclick="return false;" src="Images/Show.gif" />
Convert Domain Name to I.P Address
C#
using System.Net;
protected void Page_Load(object sender, EventArgs e)
{
foreach (IPAddress address in
Dns.GetHostAddresses("www.devcurry.com"))
{
Response.Write(address.ToString());
}
}
VB.NET
Imports System.Net
Protected Sub Page_Load(ByVal sender As Object, _
ByVal e As EventArgs)
For Each address As IPAddress In
Dns.GetHostAddresses("www.devcurry.com")
Response.Write(address.ToString())
Next address
End Sub
How to Create an ASP.NET AJAX ModalPopUp Extender Dynamically
Add the following markup in your page:
Then in the code behind, add the following code. On clicking the Button, we have added code to create another button dynamically which contains functionality to show and hide a ModalPopUp
C#
protected void Button1_Click(object sender, EventArgs e)
{
Button btnNew = new Button();
btnNew.ID = "Button2";
btnNew.Text = "Click Me to Show PopUp";
AjaxControlToolkit.ModalPopupExtender modalPop =
new AjaxControlToolkit.ModalPopupExtender();
modalPop.ID = "popUp";
modalPop.PopupControlID = "ModalPanel";
modalPop.TargetControlID = "Button2";
modalPop.DropShadow = true;
modalPop.CancelControlID = "btnCancel";
this.Panel1.Controls.Add(modalPop);
this.Panel1.Controls.Add(btnNew);
}
VB.NET
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim btnNew As New Button()
btnNew.ID = "Button2"
btnNew.Text = "Click Me to Show PopUp"
Dim modalPop As New AjaxControlToolkit.ModalPopupExtender()
modalPop.ID = "popUp"
modalPop.PopupControlID = "ModalPanel"
modalPop.TargetControlID = "Button2"
modalPop.DropShadow = True
modalPop.CancelControlID = "btnCancel"
Me.Panel1.Controls.Add(modalPop)
Me.Panel1.Controls.Add(btnNew)
End Sub
Ask For Confirmation Before Submitting Data in ASP.NET
C#
protected void Page_Load(object sender, EventArgs e)
{
string myScript = @"";
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "MakeSure", myScript);
form1.Attributes.Add("onsubmit", "return askBeforeSubmit();");
}
VB.NET
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim myScript As String = ""
Page.ClientScript.RegisterClientScriptBlock(Me.GetType(), "MakeSure", myScript)
form1.Attributes.Add("onsubmit", "return askBeforeSubmit();")
End Sub
You can also ask for confirmation without writing any code. Just use the OnClientClick event on the button as shown below:
OnClientClick="return confirm('Are you sure?');"/>
How to execute javascript onLoad only once in an ASP.NET page
However if you would like to execute it only once during the first postback, then here's how to do so:
Copy this code in the of your MasterPage
The code determines if there is a postback in Javascript and then executes code based on the result. Hence the alert popup is shown only once.
You can several other tips related to calling JavaScript in Master/Content Pages over here:
Calling JavaScript from ASP.NET Master Page and Content Pages - Part I
Calling JavaScript from ASP.NET Master Page and Content Pages - Part II
Ask user before closing the browser - IE and Mozilla
Add OnKeyUp to an ASP.NET TextBox
C#
protected void Page_Load(object sender, EventArgs e)
{
TextBox1.Attributes.Add("onKeyUp", "CallScript(this)");
}
VB.NET
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
TextBox1.Attributes.Add("onKeyUp", "CallScript(this)")
End Sub
How to do a Page PostBack With a Delay
Add the following code in the Page_Load event:
C#
protected void Page_Load(object sender, EventArgs e)
{
TimeSpan ts = new TimeSpan(0, 0, 0, 5);
System.Threading.Thread.Sleep(ts);
}
VB.NET
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
Dim ts As New TimeSpan(0, 0, 0, 5)
System.Threading.Thread.Sleep(ts)
End Sub
Note: Avoid using this approach too much in a Production environment.
How to apply CSS to a GridView Row based on a condition
C#
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DataRowView drv = e.Row.DataItem as DataRowView;
if (drv["Discontinued"].ToString() == "true")
e.Row.CssClass = "selected";
}
}
VB.NET
Protected Sub GridView1_RowDataBound(ByVal sender As Object, _
ByVal e As GridViewRowEventArgs)
If e.Row.RowType = DataControlRowType.DataRow Then
Dim drv As DataRowView = TryCast(e.Row.DataItem, DataRowView)
If drv("Discontinued").ToString() = "true" Then
e.Row.CssClass = "selected"
End If
End If
End Sub
How to refresh an ASP.NET GridView automatically at regular intervals
Add the GridView and the Timer control inside an ASP.NET AJAX UpdatePanel as shown below :
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Timer ID="Timer1" runat="server" Interval="3600" ontick="Timer1_Tick">asp:Timer>
<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False" DataKeyNames="CustomerID"
DataSourceID="SqlDataSource1" AllowPaging="True" AllowSorting="True">
<Columns>
<asp:BoundField DataField="CustomerID" HeaderText="CustomerID" ReadOnly="True" SortExpression="CustomerID" />
<asp:BoundField DataField="CompanyName" HeaderText="CompanyName" SortExpression="CompanyName" />
<asp:BoundField DataField="ContactName" HeaderText="ContactName" SortExpression="ContactName" />
<asp:BoundField DataField="Address" HeaderText="Address" SortExpression="Address" />
<asp:BoundField DataField="City" HeaderText="City" SortExpression="City" />
Columns>
asp:GridView>
ContentTemplate>
asp:UpdatePanel>
Then in the code behind, add the following code which refreshes the GridView after every minute
C#
protected void Timer1_Tick(object sender, EventArgs e)
{
GridView2.DataBind();
}
VB.NET
Protected Sub Timer1_Tick(ByVal sender As Object, ByVal e As EventArgs)
GridView2.DataBind()
End Sub
Opening a new window from code behind on Button Click in ASP.NET
Add the following script to the section of your page
<script language="javascript" type="text/javascript">
function openNewWin(url) {
var x = window.open(url, 'mynewwin', 'width=600,height=600,toolbar=1');
x.focus();
}
script>
Then add a Button Control in the following manner
<asp:Button ID="btnOpenPop" runat="server" Text="Open Pop"
onclick="btnOpenPop_Click" />
Finally add some code in the code behind file
C#
protected void btnOpenPop_Click(object sender, EventArgs e)
{
string url = "http://www.dotnetcurry.com";
ClientScript.RegisterStartupScript(this.GetType(), "OpenWin", "");
}
VB.NET
Protected Sub btnOpenPop_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim url As String = "http://www.dotnetcurry.com"
ClientScript.RegisterStartupScript(Me.GetType(), "OpenWin", "")
End Sub
I have created my own Role Provider
==========
I have created my own Role Provider because I found the one that ASP.Net provides to be way too bulky in
terms of tables in the database. I found implementing a custom RoleProvider to be quite easy.
My only problem is that right now I cannot have multiple roles for a page. I saw somewhere that at the top of
your class you need to "anotate it" with some security code. This is what I have
[PrincipalPermission(SecurityAction.Demand, Role="Admin")]If I try to include multiple roles by using a comma
separated list I get errors. If i try to specify multiple role keys then I also get errors. Do i Need to
specify multiple PrinicipalPermissions by any chance?
I have very little experience with ASP.Net's role management. Can someone point me in the right direction or
at some good literature.
Answer:
=======
Hi, you can add the PrinicpalPermission attribute multiple times.
[PrincipalPermission(SecurityAction.Demand, Role="Admin")]
[PrincipalPermission(SecurityAction.Demand, Role="AnotherRole")]
Hiding a File using C# and VB.NET
and opening of files. Here’s how to hide a file using C# and VB.NET
C#
class Program
{
static void Main(string[] args)
{
try
{
string filePath = @"D:\Network.txt";
FileInfo f = new FileInfo(filePath);
f.Attributes = FileAttributes.Hidden;
Console.WriteLine("File Hidden");
}
catch (Exception ex)
{
// handle ex
}
}
}
Accessing the ASP.NET Authentication, Profile and Role Service in Silverlight
Accept dd/mm/yyyy date format in ASP.NET AJAX MaskedEditExtender
CultureName="en-GB" TargetControlID="txtDate"
Mask="99/99/9999" MaskType="Date" AcceptNegative="None"/>
ControlExtender="MaskedEditExtender1"
EmptyValueMessage="Please enter Date" InvalidValueMessage="Invalid Date"
ControlToValidate="txtDate" ValidationGroup="DtVal" />
Adding OnClick event to an ASP.NET Label control
Now in the Code Behind, use the Control.Attributes.Add() to add the OnClick event to the Label Control
C#
protected void Page_Load(object sender, EventArgs e)
{
Label1.Attributes.Add("onClick", "CallMe();");
}
VB.NET
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
Label1.Attributes.Add("onClick", "CallMe();")
End Sub
Display an Image for EmptyData in an ASP.NET GridView
However if you want to display an image instead of text when no results are returned, then here's how to do so:
ImageUrl="~/images/NoDataFound.jpg"
AlternateText="No data found"
runat="server"/>
Shown above is an EmptyDataTemplate that can be used within the GridView. Inside the , we are using the image control to display an image when no records are returned
How do you programmatically determine if an ASP.NET application is running locally
How to do this the reliable way, a very simple solution is to use the 'isLocal' property of the Request class as shown below:
C#
protected void Page_Load(object sender, EventArgs e)
{
if (HttpContext.Current.Request.IsLocal)
{
Response.Write("App is local");
}
}
VB.NET
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
If HttpContext.Current.Request.IsLocal Then
Response.Write("App is local")
End If
End Sub
Change DateFormat In an ASP.NET GridView
Note: HTMLEncode=True helps prevent cross-site scripting attacks.
In order to display the date in a user friendly date format, use the following method to turn off the HTMLEncode and use :
DataSourceID="SqlDataSource1" AllowPaging="True" AllowSorting="True">
HtmlEncode="false" HeaderText="SomeDate" />
...
If you do not want to do it this way, the other way is to use a Template Field as shown below
DataSourceID="SqlDataSource1" AllowPaging="True" AllowSorting="True">
...
Creating a Dynamic Hyperlink in ASP.NET using the Web.Config
Now read this entry from the web.config using AppSettings
NavigateUrl="<%$ Appsettings:someurl %>" Text="Click Here">
Display the First and Last Day of Week In ASP.NET
C#
DateTime dt = DateTime.Now;
DateTime wkStDt = DateTime.MinValue;
DateTime wkEndDt = DateTime.MinValue;
wkStDt = dt.AddDays(1 - Convert.ToDouble(dt.DayOfWeek));
wkEndDt = dt.AddDays(7 - Convert.ToDouble(dt.DayOfWeek));
Response.Write(wkStDt.ToString("MMMM-dd") + "
");
Response.Write(wkEndDt.ToString("MMMM-dd"));
VB.NET
Dim dt As DateTime = DateTime.Now
Dim wkStDt As DateTime = DateTime.MinValue
Dim wkEndDt As DateTime = DateTime.MinValue
wkStDt = dt.AddDays(1 - Convert.ToDouble(dt.DayOfWeek))
wkEndDt = dt.AddDays(7 - Convert.ToDouble(dt.DayOfWeek))
Response.Write(wkStDt.ToString("MMMM-dd") & "
")
Response.Write(wkEndDt.ToString("MMMM-dd"))
How to add Control dynamically in an ASP.NET AJAX application
C#
protected void Button1_Click(object sender, EventArgs e)
{
int cnt = 0;
if (ViewState["txtBoxes"] != null)
cnt = (int)ViewState["txtBoxes"];
cnt = cnt + 1;
ViewState["txtBoxes"] = cnt;
for (int i = 0; i < cnt; i++)
{
TextBox tb = new TextBox();
tb.Text = "";
tb.ID = "TextBox" + cnt;
UpdatePanel1.ContentTemplateContainer.Controls.Add(tb);
}
}
VB.NET
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim cnt As Integer = 0
If ViewState("txtBoxes") IsNot Nothing Then
cnt = CInt(Fix(ViewState("txtBoxes")))
End If
cnt = cnt + 1
ViewState("txtBoxes") = cnt
For i As Integer = 0 To cnt - 1
Dim tb As New TextBox()
tb.Text = ""
tb.ID = "TextBox" & cnt
UpdatePanel1.ContentTemplateContainer.Controls.Add(tb)
Next i
End Sub
Display Message On MouseOver In an ASP.NET GridView
The RowDataBound event is raised when a data row (represented by a GridViewRow object) is bound to data in the GridView control. This enables you to provide an event-handling method that performs a custom routine, such as modifying the values of the data bound to the row, whenever this event occurs.
SelectCommand="SELECT [CustomerID], [CompanyName], [ContactName], [Address], [City] FROM [Customers]">
DataSourceID="SqlDataSource1" AllowPaging="True" AllowSorting="True"
OnRowDataBound="GridView1_RowDataBound">
C#
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if ( e.Row.RowType == DataControlRowType.DataRow )
{
e.Row.Attributes.Add("onmouseover", "alert('Display some message');");
}
}
VB.NET
Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
If e.Row.RowType = DataControlRowType.DataRow Then
e.Row.Attributes.Add("onmouseover", "alert('Display some message');")
End If
End Sub
Hiding a Column in an ASP.NET GridView
1. Set the GridView column’s 'Visibility' property to 'False'. However in this case, GridView will not bind the data to the GridView. So if you want to use that hidden column (like a Master-Detail scenario), you won't be able to do it.
You can also hide the column programmatically in the RowDataBound event
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
e.Row.Cells[0].Visible = false;
}
VB.NET
Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
e.Row.Cells(0).Visible = False
End Sub
2. Use the OnRowCreated event which gets called after the data is bound
C#
protected void GridView1_OnRowCreated(object sender, GridViewRowEventArgs e)
{
e.Row.Cells[0].Visible = false;
}
VB.NET
protected void GridView1_OnRowCreated(object sender, GridViewRowEventArgs e)
{
e.Row.Cells[0].Visible = false;
}
Using this way, you can use a hidden column's data even if it is hidden.
Fetching all controls on a page ordered by their ID
C#
protected void Button1_Click(object sender, EventArgs e)
{
var ctrl = from ctr in this.Controls.Cast
select ctr;
}
VB.NET
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim ctrl = _
From ctr In Me.Controls.Cast(Of Control)().OrderBy(Function(c) c.ID) _
Select ctr
End Sub
How to Prevent Word Wrap in an ASP.NET GridView
The trick is to use
Check this sample:
Wrap="True" />
Text='<%# Bind("SomeLongText") %>'>
I am sure there are many developers who had this problem in the past without a decent solution. Let me know if it worked for you!
How to find all the checked checkboxes in an asp.net gridview
I have seen this question a gazillion times on the forums – Finding checked checkboxes in an ASP.NET GridView. Here’s how to do so. The CheckBox in our example is in a TemplateField as shown below:
<asp:TemplateField>
<ItemTemplate >
<asp:CheckBox id="CheckBox1" runat="server" />
ItemTemplate>
asp:TemplateField>
In order to find the checked checkboxes on a button click, use this simple code
C#
protected void Button1_Click(object sender, EventArgs e)
{
foreach (GridViewRow gvr in GridView1.Rows)
{
CheckBox chkBox = (CheckBox)gvr.FindControl("CheckBox1");
if (chkBox != null && chkBox.Checked)
{
}
}
}
VB.NET
Protected Sub Button1_Click(ByVal sender As Object, _
ByVal e As EventArgs)
For Each gvr As GridViewRow In GridView1.Rows
Dim chkBox As CheckBox = _
CType(gvr.FindControl("CheckBox1"), CheckBox)
If chkBox IsNot Nothing AndAlso chkBox.Checked Then
' Do Something
End If
Next gvr
End Sub
3 quick things to check if your ASP.NET session ends before timeout
Session ending before timeout is an issue faced by many developers who use IIS 6. I have found that in most cases, this is caused when you set the recycling of worker processes using IIS manager.
Check this cool post to understand this better.
Here are 3 quick suggestions to troubleshoot this issue (assuming that you are using In-process mode - ASP.NET session state):
1. Check and see if you have configured recycling of worker processes
2. If you are maintaining cookie enabled sessions, check if the cookie is not getting deleted/modified at the client end.
3. Check to see if IIS/Application Pool is not getting restarted at regular intervals. Your application pool will restart if your global.asax or the web.config/ machine.config changes
Cause a PostBack on KeyPress from the asp.net dropdownlist
Here’s how to cause a postback from DropDownList on keypress
C#
protected void Page_Load(object sender, EventArgs e)
{
if (Request.Params["__EVENTTARGET"] != null)
{
string evnt = Request.Params["__EVENTTARGET"].ToString();
string args = Request.Params["__EVENTARGUMENT"].ToString();
if (evnt == "DropDownList1" && args == "onkeypress")
{
// write some code to execute on postback
}
}
DropDownList1.Attributes.Add("onkeypress",
Page.GetPostBackEventReference(DropDownList1,"onkeypress"));
}
VB.NET
Protected Sub Page_Load(ByVal sender As Object, _
ByVal e As EventArgs)
If Request.Params("__EVENTTARGET") IsNot Nothing Then
Dim evnt As String = _
Request.Params("__EVENTTARGET").ToString()
Dim args As String = _
Request.Params("__EVENTARGUMENT").ToString()
If evnt = "DropDownList1" _
AndAlso args = "onkeypress" Then
' write some code to execute on postback
End If
End If
DropDownList1.Attributes.Add("onkeypress",_
Page.GetPostBackEventReference(DropDownList1, "onkeypress"))
End Sub
Adding a ToolTip to an ASP.NET Hyperlink Control in a GridView
I recently came across a cool solution proposed by Jose to add a tooltip to an ASP.NET Hyperlink control kept inside a GridView. The solution is to create a template field and add a Hyperlink control to it as shown below:
<asp:TemplateField HeaderText="SomeLink">
<ItemTemplate>
<asp:HyperLink ID="HyperLink1" runat="server"
NavigateUrl='<%# Eval("SomeLink") %>' Text='<%# Eval("SomeLink") %>'
ToolTip='<%# Eval("SomeText") %>'>
asp:HyperLink>
ItemTemplate>
asp:TemplateField>
How to Reduce the Margin/Padding around a CheckBox
One
Two
Three
Four
Output
image
Check out the first two checkboxes which have the default width, margin and padding. Now check out the last two checkboxes which have a reduced width, margin and padding.
This tip should save time for those who have been trying to do the same using the margin and padding properties. The trick is to also set the width property.
How to Debug Client-Side Script In Internet Explorer
Open IE > Tools > Internet Options
Click Advanced Tab > Under the ‘Browsing’ section, clear the checkbox against ‘ Disable script debugging (Internet Explorer)’.
image
That’s it. Now put a breakpoint in your JavaScript code and run the application in Visual Studio.
There are other tools like Microsoft Script Editor too which can be used.
Other browsers like Firefox has tools like FireBug, which is a great tool to debug Client-Side Script.
How To: Use Forms Authentication with Active Directory in ASP.NET 2.0
ASP.NET Session Expiration Redirect
Unfortunately ASP.NET doesn't provide a nice out of the box solution for handling the session timeout gracefully. Everything expires behind the scenes and your user is left unaware of what has happened. Additional problems can arise if the user abandoned their browser in a state that you didn't code for, which can result in errors or exceptions taking place.
With this in mind I like to put a Session Expired page in place in my applications and pro-actively send the user there when their session ends. This accomplishes a few different things:
1) Provides a nice user experience for your users
2) Prevents your application from being left in an unknown state when the session / auth ticket expires
3) Prevents application errors and exceptions from occurring when a user tries to perform an action on a page after their session / auth ticket has expired
Nested MasterPage(s) For All Authenticated Pages
You need to implement a MasterPage (or a Page base class) for all of your authenticated pages so you can inject a bit of javascript to handle the redirect on session timeout.
Get Your Web.config Settings Straight
Make sure that your auth ticket timeout and session timeout match.
protection="All"
path="/"
requireSSL="false"
timeout="45"
name=".ASPXAUTH"
slidingExpiration="true"
defaultUrl="Login.aspx"
cookieless="UseDeviceProfile"
enableCrossAppRedirects="false" />
Create Your Session Expiration Page
Create a page for your users to be taken to when their session expires. I created SessionExpired.aspx with the following message:
Session Expired
Your session has expired due to inactivity.
Click here to login again
Ensure the Authentication ticket is signed out in your code behind:
FormsAuthentication.SignOut();
Add The Session Expiration Javascript To Your Page_Load
In the Page_Load method of your MasterPage (or base page class) add the following code:
// Handle the session timeout
string sessionExpiredUrl = Request.Url.GetLeftPart(UriPartial.Authority) + "/SessionExpired.aspx";
StringBuilder script = new StringBuilder();
script.Append("function expireSession(){ \n");
script.Append(string.Format(" window.location = '{0}';\n", sessionExpiredUrl));
script.Append("} \n");
script.Append(string.Format("setTimeout('expireSession()', {0}); \n", this.Session.Timeout * 60000)); // Convert minutes to milliseconds
this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "expirescript", script.ToString(), true);
That's It
The session timeout script should be injected into each of your authenticated pages now. The client's browser will begin the countdown after each page has loaded or each PostBack has occurred. Once the countdown is reached the browser will redirect to your SessionExpired page.
Reference:
http://msmvps.com/blogs/shahed/archive/2007/09/05/redirect-to-login-page-on-session-expiration-asp-net.aspx
Aaron Schnieder
http://www.churchofficeonline.com
[PATCH] Fix for Membership.{Encrypt, Decrypt}Password
WCSF Application Architecture 1: Introduction
Caching LinqToSql results with SqlCacheDependency
In early 2008 I needed to cache the results from LinqToSql-queries. I like the SqlCacheDependency (especially in SQL 2K5 Server).
I also like the new extension methods posibillity... So this is what I came up with.
SqlCacheDependency
With SqlServer 2005 SqlCacheDependency became very useful. In Sql 2000 the dependency could only be created on full tables (not rows). The Cache was destroyed as a table being cached changed even if your query did not affect the row changed, but Sql 2005 can handle SqlCacheDependency on row-level... Hence SqlCacheDependency is destroyed only if a row that my query affects is being changed.
The thing you do to use SqlCacheDependency is to create a SqlCommand that contains the Sql-query you want to cache the result of.
Then you create a SqlCacheDependency with the SqlCommand as a parameter.
LinqToSql
It´s hard not to love LinqToSql... Sure, I know some DBA´s that do not love the thought of foreign code executing queries in there databases (if we ignore the option to use stored procedures with LinqToSql). I personally think that it´s ok to only use permissions in BLL on method level like:
PrincipalPermission(System.Security.Permissions.SecurityAction.Demand,Role"ADMIN",Authenticatedtrue)
The simplicity of development and the oppurtunity to quick changes in DAL and database makes it hard to resist LinqToSql :)
SqlCacheDependency with LinqToSql
Why cache LinqQueries?
Everytime you iterate over a LinqToSql-query it will execute...
Like -> foreach(MyObj o in MyLinqQuery) will execute the query against the SqlServer. One solution I´ve seen people using is: List = MyLiqToSqlQuery.ToList(); and then use cache on the result. This will ofcourse work, but you´ll not know if anything changes in the database unless you use SqlCacheDependency.
The challenge of LinqToSql & SqlCacheDependency is to extract the SqlQuery to be able to store it in a SqlCommand and then use the SqlCommand in the SqlCacheDependency. You will also have to provide functionality for parameters that the LinqQuery may hold... I created a generic ExtensionMethod for IQueryable to solve my problem.... one method to cache all LinqQueries
The code should be explained enough by the comments I think.
public static class Cache
{
///
/// Caches Linq query´s that is created for LinqToSql.
/// Limitations are the same as SqlCacheDependency
///
///
/// The linq query
/// Your LinqToSql DataContext
/// The unique Id for the cache
///
public static List
{
try
{
List
if (objCache == null)
{
/////////No cache... implement new SqlCacheDependeny//////////
//1. Get connstring from DataContext
string connStr = dc.Connection.ConnectionString;
//2. Get SqlCommand from DataContext and the LinqQuery
string sqlCmd = dc.GetCommand(q).CommandText;
//3. Create Conn to use in SqlCacheDependency
using (System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(connStr))
{
conn.Open();
//4. Create Command to use in SqlCacheDependency
using (System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(sqlCmd, conn))
{
//5.0 Add all parameters provided by the Linq Query
foreach (System.Data.Common.DbParameter dbp in dc.GetCommand(q).Parameters)
{
cmd.Parameters.Add(new System.Data.SqlClient.SqlParameter(dbp.ParameterName, dbp.Value));
}
//5.1 Enable DB for Notifications... Only needed once per DB...
System.Web.Caching.SqlCacheDependencyAdmin.EnableNotifications(connStr);
//5.2 Get ElementType for the query
string NotificationTable = q.ElementType.Name;
//5.3 Enable the elementtype for notification (if not done!)
if (!System.Web.Caching.SqlCacheDependencyAdmin.GetTablesEnabledForNotifications(connStr).Contains(NotificationTable))
System.Web.Caching.SqlCacheDependencyAdmin.EnableTableForNotifications(connStr, NotificationTable);
//6. Create SqlCacheDependency
System.Web.Caching.SqlCacheDependency sqldep = new System.Web.Caching.SqlCacheDependency(cmd);
// - removed 090506 - 7. Refresh the LinqQuery from DB so that we will not use the current Linq cache
// - removed 090506 - dc.Refresh(System.Data.Linq.RefreshMode.OverwriteCurrentValues, q);
//8. Execute SqlCacheDepency query...
cmd.ExecuteNonQuery();
//9. Execute LINQ-query to have something to cache...
objCache = q.ToList();
//10. Cache the result but use the already created objectCache. Or else the Linq-query will be executed once more...
System.Web.HttpRuntime.Cache.Insert(CacheId, objCache, sqldep);
}
}
}
//Return the created (or cached) List
return objCache;
}
catch (Exception ex)
{
throw ex;
}
}
}
IMPORTANT
You need to call SqlDependency.Start for example in global.asax
//In Application Start Event
System.Data.SqlClient.SqlDependency.Start("DataContextConnectionString");
//In Application End Event
System.Data.SqlClient.SqlDependency.Stop("DataContextConnectionString");
HowTo: Call the Extension Method
So now yo can get call LinqCache
How to Open a Page In Full Screen Mode using JavaScript
One of my team members had a requirement of opening up a page in Full Screen mode. He wanted that when a link on the page is clicked, the same page should be opened in Full Screen Mode. If you too have a similar requirement, then here’s how to do so:
DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Open Page FullScreentitle>
<script type="text/javascript">
function FullScreenMode(){
var win = window.open("", "full", "dependent=yes, fullscreen=yes");
win.location = window.location.href;
window.opener = null;
}
script>
head>
<body>
<input id="Button1" type="button" value="Full Screen"
onclick="FullScreenMode()"/>
body>
html>If you want the parent window to close when the new window opens in full screen mode, just add window.close(); as the last line in the JavaScript code.
Import Excel Data Into An ASP.NET GridView using OLEDB
I have seen a lot of users asking how to import data from an excel sheet into an ASP.NET GridView.
I will show two ways to do so - Using OLEDB and Using Microsoft.Office.Interop.Excel
In this post, we will see how to import data using OLEDB
C#
using System.Data.OleDb;
using System.Data;
public partial class UploadD : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string cnstr = "Provider=Microsoft.Jet.Oledb.4.0;Data Source=C:\a.xls;"
+ "Extended Properties=Excel 8.0";
OleDbConnection oledbConn = new OleDbConnection(cnstr);
string strSQL = "SELECT * FROM [Sheet$]";
OleDbCommand cmd = new OleDbCommand(strSQL, oledbConn);
DataSet ds = new DataSet();
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
}
VB.NET
Imports System.Data.OleDbIn the next article, we will see how to import Excel Data Into an ASP.NET GridView using Microsoft.Office.Interop.Excel
Imports System.Data
Partial Public Class UploadD
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
Dim cnstr As String = "Provider=Microsoft.Jet.Oledb.4.0;" &_
"Data Source=C:\a.xls; Extended Properties=Excel 8.0"
Dim oledbConn As New OleDbConnection(cnstr)
Dim strSQL As String = "SELECT * FROM [Sheet$]"
Dim cmd As New OleDbCommand(strSQL, oledbConn)
Dim ds As New DataSet()
Dim da As New OleDbDataAdapter(cmd)
da.Fill(ds)
GridView1.DataSource = ds
GridView1.DataBind()
End Sub
End Class
Import Excel Data Into an ASP.NET GridView using Microsoft.Office.Interop.Excel
In my previous article, we saw how to import Excel Data into an ASP.NET GridView using OLEDB. In this next article, we will see how to import Excel Data Into an ASP.NET GridView using Microsoft.Office.Interop.Excel. This untested code was written by Vince Xu -MSFT and I thought of sharing it with you.
C#
using Microsoft.Office.Interop.Excel;
using System.Text;
using System.Reflection;
public partial class ImportDD : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
DataSet ds = GetExcel("c:\\aa.xls");
GridView1.DataSource = ds;
GridView1.DataBind();
}
public DataSet GetExcel(string fileName)
{
Application oXL;
Workbook oWB;
Worksheet oSheet;
Range oRng;
try
{
// creat a Application object
oXL = new ApplicationClass();
// get WorkBook object
oWB = oXL.Workbooks.Open(fileName, Missing.Value, Missing.Value,
Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Missing.Value);
// get WorkSheet object
oSheet = (Microsoft.Office.Interop.Excel.Worksheet)oWB.Sheets[1];
System.Data.DataTable dt = new System.Data.DataTable("dtExcel");
DataSet ds = new DataSet();
ds.Tables.Add(dt);
DataRow dr;
StringBuilder sb = new StringBuilder();
int jValue = oSheet.UsedRange.Cells.Columns.Count;
int iValue = oSheet.UsedRange.Cells.Rows.Count;
// get data columns
for (int j = 1; j <= jValue; j++)
{
dt.Columns.Add("column" + j, System.Type.GetType("System.String"));
}
// get data in cell
for (int i = 1; i <= iValue; i++)
{
dr = ds.Tables["dtExcel"].NewRow();
for (int j = 1; j <= jValue; j++)
{
oRng = (Microsoft.Office.Interop.Excel.Range)oSheet.Cells[i, j];
string strValue = oRng.Text.ToString();
dr["column" + j] = strValue;
}
ds.Tables["dtExcel"].Rows.Add(dr);
}
return ds;
}
catch (Exception ex)
{
return null;
}
finally
{
Dispose();
}
}
}
VB.NET
Imports Microsoft.Office.Interop.Excel
Imports System.Text
Imports System.Reflection
Partial Public Class ImportDD
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
Dim ds As DataSet = GetExcel("c:\aa.xls")
GridView1.DataSource = ds
GridView1.DataBind()
End Sub
Public Function GetExcel(ByVal fileName As String) As DataSet
Dim oXL As Application
Dim oWB As Workbook
Dim oSheet As Worksheet
Dim oRng As Range
Try
' creat a Application object
oXL = New ApplicationClass()
' get WorkBook object
oWB = oXL.Workbooks.Open(fileName, Missing.Value, Missing.Value,_
Missing.Value, Missing.Value,Missing.Value, Missing.Value, Missing.Value, _
Missing.Value, Missing.Value,Missing.Value, Missing.Value, Missing.Value, _
Missing.Value, Missing.Value)
' get WorkSheet object
oSheet = CType(oWB.Sheets(1), _
Microsoft.Office.Interop.Excel.Worksheet)
Dim dt As New System.Data.DataTable("dtExcel")
Dim ds As New DataSet()
ds.Tables.Add(dt)
Dim dr As DataRow
Dim sb As New StringBuilder()
Dim jValue As Integer = oSheet.UsedRange.Cells.Columns.Count
Dim iValue As Integer = oSheet.UsedRange.Cells.Rows.Count
' get data columns
For j As Integer = 1 To jValue
dt.Columns.Add("column" & j, _
System.Type.GetType("System.String"))
Next j
' get data in cell
For i As Integer = 1 To iValue
dr = ds.Tables("dtExcel").NewRow()
For j As Integer = 1 To jValue
oRng = CType(oSheet.Cells(i, j), _
Microsoft.Office.Interop.Excel.Range)
Dim strValue As String = oRng.Text.ToString()
dr("column" & j) = strValue
Next j
ds.Tables("dtExcel").Rows.Add(dr)
Next i
Return ds
Catch ex As Exception
Return Nothing
Finally
Dispose()
End Try
End Function
End Class
Followers
My Blog List
Blog Archive
-
▼
2009
(66)
-
►
August
(64)
- Silverlight 2.0: usage of the converters from exte...
- What’s new in .NET Framework 4.0
- Creating Virtual directory in IIS with c#
- Important URLs
- Alert/Prevent Users From closing the browser
- Open a PopUp Window on the ASP.NET Button Click ev...
- Export GridView to Excel
- Supress Postback on an ASP.NET ImageButton
- Convert Domain Name to I.P Address
- How to Create an ASP.NET AJAX ModalPopUp Extender ...
- Ask For Confirmation Before Submitting Data in ASP...
- How to execute javascript onLoad only once in an A...
- Ask user before closing the browser - IE and Mozilla
- Add OnKeyUp to an ASP.NET TextBox
- How to do a Page PostBack With a Delay
- How to apply CSS to a GridView Row based on a cond...
- How to refresh an ASP.NET GridView automatically a...
- Opening a new window from code behind on Button Cl...
- I have created my own Role Provider
- Hiding a File using C# and VB.NET
- Accessing the ASP.NET Authentication, Profile and ...
- Accept dd/mm/yyyy date format in ASP.NET AJAX Mask...
- Adding OnClick event to an ASP.NET Label control
- Display an Image for EmptyData in an ASP.NET GridView
- How do you programmatically determine if an ASP.NE...
- Change DateFormat In an ASP.NET GridView
- Creating a Dynamic Hyperlink in ASP.NET using the ...
- Display the First and Last Day of Week In ASP.NET
- How to add Control dynamically in an ASP.NET AJAX ...
- Display Message On MouseOver In an ASP.NET GridView
- Hiding a Column in an ASP.NET GridView
- Fetching all controls on a page ordered by their ID
- How to Prevent Word Wrap in an ASP.NET GridView
- How to find all the checked checkboxes in an asp.n...
- 3 quick things to check if your ASP.NET session en...
- Cause a PostBack on KeyPress from the asp.net drop...
- Adding a ToolTip to an ASP.NET Hyperlink Control i...
- How to Reduce the Margin/Padding around a CheckBox
- How to Debug Client-Side Script In Internet Explorer
- How To: Use Forms Authentication with Active Direc...
- ASP.NET Session Expiration Redirect
- [PATCH] Fix for Membership.{Encrypt, Decrypt}Password
- WCSF Application Architecture 1: Introduction
- Caching LinqToSql results with SqlCacheDependency
- How to Open a Page In Full Screen Mode using JavaS...
- Import Excel Data Into An ASP.NET GridView using O...
- Import Excel Data Into an ASP.NET GridView using M...
-
►
August
(64)