Monday, August 6, 2012

Unhandled Exception: "The file attached is invalid" with AsyncFileUploader and .NET Framework 4

 

I upgraded my ASP.NET framework from 3.5 to 4 recently, and encountered a host of problems.

I knew the problem was due to the upgrade because I had not changed my code, and yet, there were parts of the system that went haywire with seemingly esoteric errors.

Today, I got the error below when I tried to upload images on a web page that was working perfectly before.

2012-08-06_102203

 

Fortunately, the error is easy to solve.  I just followed the tip from ndkjava given on the ASP.NET forum.

Basically, what you need to do is to locate the control on the markup code and add this attribute to it.

ClientIDMode="AutoID"

For example, this is how my code looks like after adding it.

<asp:AsyncFileUpload ClientIDMode="AutoID" ID="AsyncFileUpload1" runat="server"  onuploadedcomplete="AsyncFileUpload1_UploadedComplete" />

Everything seems to work marvellously after that! :)


ps. If you want to download the latest version of the FileAsyncUpload which is in the ASP.NET AJAX Control Toolkit 4, you can get it at CodePlex here (updated 24 Jun 2012).


For tutorials on how to use the AJAX Control Toolkit FileAsyncUpload control,  you can find one here.

Thursday, August 2, 2012

Applying superscript and subscript to WordXML


I wrote an entry sometime back in Jan 2011 to show how you can easily generate a Word document using the OpenXML SDK with font size, font color and bold formatting.
Yesterday, I received a comment from Hema, who asked me how to add subscript and superscript formatting.
To tell the truth, I had not dabbled in those before.  But I decided since I have already come so far, I can just spend a little time to see if I can apply subscript and superscript effects to my previous code too.
I am glad I tried, because I realised its not too difficult.  The only problem is that there’s little documentation out there, so I managed to arrive at the solution purely through my own ‘experiment’ and I am not sure if my method is the most efficient!
I am assuming that you are familiar with the OpenXML SDK and procedures such as how to create Run and RunProperties based on my previous post.  What you need to add superscript or subscript is to use the “VerticalTextAlignment” class to specify if you wish to have a “Superscript” or “Subscript” or the default “Baseline” alignment.
Scroll below for the full code to generate a Word document with one single sentence with output like this:
2012-08-02_112934
 public void GenerateSentence(string filename)
        {
            WordprocessingDocument doc = WordprocessingDocument.Create(filename, 
               WordprocessingDocumentType.Document);
            MainDocumentPart mainPart = doc.AddMainDocumentPart();
            mainPart.Document = new Document();
            Body body = new Body();

            /**** Create the contents ****/
            DocumentFormat.OpenXml.Wordprocessing.Run run1;
            Paragraph para;

            string text1 = "The answer for ";
            string text2 = "10";            
            string text3 = "2";
            string text4 = " is 100";


            DocumentFormat.OpenXml.Wordprocessing.RunProperties runProperties1 = 
               new DocumentFormat.OpenXml.Wordprocessing.RunProperties
               (new RunFonts() { Ascii = "Script" });
            DocumentFormat.OpenXml.Wordprocessing.RunProperties runProperties2 = 
               new DocumentFormat.OpenXml.Wordprocessing.RunProperties
               (new RunFonts() { Ascii = "Courier New" });
            DocumentFormat.OpenXml.Wordprocessing.RunProperties runProperties3 = 
               new DocumentFormat.OpenXml.Wordprocessing.RunProperties
               (new RunFonts() { Ascii = "Arial" });
            DocumentFormat.OpenXml.Wordprocessing.RunProperties runProperties4 = 
               new DocumentFormat.OpenXml.Wordprocessing.RunProperties
               (new RunFonts() { Ascii = "Times New Roman" });            

            DocumentFormat.OpenXml.Wordprocessing.FontSize fs1 = 
               new DocumentFormat.OpenXml.Wordprocessing.FontSize();
            DocumentFormat.OpenXml.Wordprocessing.Color c1 = 
               new DocumentFormat.OpenXml.Wordprocessing.Color();
            DocumentFormat.OpenXml.Wordprocessing.Bold b1 = 
               new DocumentFormat.OpenXml.Wordprocessing.Bold();
            DocumentFormat.OpenXml.Wordprocessing.VerticalTextAlignment vta1 = 
               new DocumentFormat.OpenXml.Wordprocessing.VerticalTextAlignment();

            DocumentFormat.OpenXml.Wordprocessing.FontSize fs2 = 
               new DocumentFormat.OpenXml.Wordprocessing.FontSize();
            DocumentFormat.OpenXml.Wordprocessing.Color c2 = 
               new DocumentFormat.OpenXml.Wordprocessing.Color();
            DocumentFormat.OpenXml.Wordprocessing.Bold b2 = 
               new DocumentFormat.OpenXml.Wordprocessing.Bold();
            DocumentFormat.OpenXml.Wordprocessing.VerticalTextAlignment vta2 = 
               new DocumentFormat.OpenXml.Wordprocessing.VerticalTextAlignment();

            DocumentFormat.OpenXml.Wordprocessing.FontSize fs3 = 
               new DocumentFormat.OpenXml.Wordprocessing.FontSize();
            DocumentFormat.OpenXml.Wordprocessing.Color c3 = 
               new DocumentFormat.OpenXml.Wordprocessing.Color();
            DocumentFormat.OpenXml.Wordprocessing.Bold b3 = 
               new DocumentFormat.OpenXml.Wordprocessing.Bold();
            DocumentFormat.OpenXml.Wordprocessing.VerticalTextAlignment vta3 = 
               new DocumentFormat.OpenXml.Wordprocessing.VerticalTextAlignment();


            DocumentFormat.OpenXml.Wordprocessing.FontSize fs4 = 
               new DocumentFormat.OpenXml.Wordprocessing.FontSize();
            DocumentFormat.OpenXml.Wordprocessing.Color c4 = 
               new DocumentFormat.OpenXml.Wordprocessing.Color();
            DocumentFormat.OpenXml.Wordprocessing.Bold b4 = 
               new DocumentFormat.OpenXml.Wordprocessing.Bold();
            DocumentFormat.OpenXml.Wordprocessing.VerticalTextAlignment vta4 = 
               new DocumentFormat.OpenXml.Wordprocessing.VerticalTextAlignment();
            
        


            /*** Format text1, text2, text3 and text4  as one paragraph ***/
            run1 = new DocumentFormat.OpenXml.Wordprocessing.Run();

            fs1.Val = "40";
            c1.Val = "black";
            b1.Val = false;
            vta1.Val = VerticalPositionValues.Baseline;
            runProperties1.Append(fs1);
            runProperties1.Append(c1);
            runProperties1.Append(b1);
            runProperties1.Append(vta1);
            run1.Append(runProperties1);
            run1.Append(new DocumentFormat.OpenXml.Wordprocessing.Text(text1));

            fs2.Val = "40";
            c2.Val = "black";
            b2.Val = false;
            vta2.Val = VerticalPositionValues.Baseline;
            runProperties2.Append(fs2);
            runProperties2.Append(c2);
            runProperties2.Append(b2);
            runProperties2.Append(vta2);
            run1.Append(runProperties2);
            run1.Append(new DocumentFormat.OpenXml.Wordprocessing.Text(text2));

            fs3.Val = "40";
            c3.Val = "black";
            b3.Val = false;
            vta3.Val = VerticalPositionValues.Superscript;
            runProperties3.Append(fs3);
            runProperties3.Append(c3);
            runProperties3.Append(b3);
            runProperties3.Append(vta3);
            run1.Append(runProperties3);
            run1.Append(new DocumentFormat.OpenXml.Wordprocessing.Text(text3));


            fs4.Val = "40";
            c4.Val = "green";
            b4.Val = false;
            vta4.Val = VerticalPositionValues.Baseline;
            runProperties4.Append(fs4);
            runProperties4.Append(c4);
            runProperties4.Append(b4);
            runProperties4.Append(vta4);
            run1.Append(runProperties4);
            run1.Append(new DocumentFormat.OpenXml.Wordprocessing.Text(text4));

            para = new Paragraph(run1);
            body.AppendChild(para);

            /*** Append the entire body ****/
            mainPart.Document.Append(body);

            /* Save the results and close */
            mainPart.Document.Save();
            doc.Close();
        }//end GenerateSentence

NOTE: You might notice that when you open up the Word document, the spaces go missing.  I had this problem too, and upon Googling, found out that this is due to a  bug in Microsoft’s OpenXML Office 2010/2007 implementation.  Oh well….

Wednesday, August 1, 2012

How to solve “Error: Unrecognized element 'folderLevelBuildProviders'”


This morning, I created a ASP.NET using the default application and not touching any of the default code, I tested it successfully with the built-in web server Visual Studio 2010.  Next, I happily clicked on the “Publish Web Site” menu item and deployed it on the local IIS.
Since I did not even do anything to the default code, I thought there would be no problem when I try to call this web application from another computer.  To my dismay,  when I tried to view the site I see an "500 - Internal server error."
So I checked out the IIS manager and tried to click on the “.NET Compilation” icon.  And encountered this error  "Unrecognized element 'folderLevelBuildProviders' ".
Well, “fortunately”, it seems that this is a common problem when and tried to and solved this using the tip from stackoverflow.
So the solution is quite simple, you register the aspnet to recognise the Framework 4.0 like this:
2012-08-01_100301
What you need to make sure is that, depending on whether you are on a 32 bit or 64 bit machine, the command differs abit.
For 32 bit machine
C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319>aspnet_regiis –i
For 64 bit machine
C:\WINDOWS\Microsoft.NET\Framework64\v4.0.30319>aspnet_regiis –i

How to solve “There is a duplicate ‘system.web.extensions/scripting/scriptResourceHandler’” error

 

I got this error after I ran a “C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319>aspnet_regiis –i” command.

Apparently, it happens when you run an older version of ASP.NET application on an IIS server that has been upgraded to use the ASP.NET Framework 4.0.

I found the way to solve this problem via Brad Kingsley’s tip .

All you need to do is to edit your web.config and comment out the section “system.web.extensions” as follows.  It worked well for me, and I hope it does for you too! :)

2012-08-01_102555

Thursday, May 17, 2012

How to change NTFS permissions for files or folders using Microsoft’s Extended Change Access Control List tool (xcacls.exe) tool

 

If you need a command-line tool that you can include in your batch files to change the NTFS permissions of files or folders, you can use the following tool from Microsoft.

Download iCACLS : http://support.microsoft.com/kb/919240
Article from ss64: http://ss64.com/nt/icacls.html

For example, the command below gives

icacls c:\inetpub\wwwroot\files\ /grant mary:(M,WDAC)


NOTE: xcacls is DEPRECATED.  Please use iCACLS instead which comes bundled with Microsoft Windows 2003.


Article: http://support.microsoft.com/kb/318754
Download tool here: http://www.microsoft.com/downloads/details.aspx?FamilyID=0ad33a24-0616-473c-b103-c35bc2820bda&amp;DisplayLang=en


Other links:



  1. How to use Xcacls.vbs to modify NTFS permissions (dated 30 Oct 2006)

  2. Forum thread on Stackoverflow

Wednesday, May 16, 2012

Login failed for user 'IIS APPPOOL\DefaultAppPool'.

 

Following the instructions below solved my problem :)

http://learn.iis.net/page.aspx/624/application-pool-identities/

The type or namespace name 'Interop' does not exist in the namespace 'Microsoft.Office' error

 

I encountered the following error "The type or namespace name 'Interop' does not exist in the namespace 'Microsoft.Office' "

Found a working solution in one of the posts in this thread.

Here’s what I did:

  1. Download the Microsoft Office 2010: Primary Interop Assemblies Redistributable at this link.
  2. Installed the software; it would extract as a setup file named “o2010pia.msi”
  3. Navigated to the “.NET” tab and added the reference “Microsoft.Office.Interop.Word”.  You can also manually add the reference under the
    <assemblies>
    tag
    <add assembly="Microsoft.Office.Interop.Word, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71E9BCE111E9429C"/>

2012-05-16_163730


If all goes well, it should get rid of the error message just as it did for me :)

How to solve the "The type or namespace 'Packaging' does not exist in the namespace 'System.IO'" error

If you encounter this error "The type or namespace 'Packaging' does not exist in the namespace 'System.IO', here's an easy way to solve it.

Just locate the
<assemblies>
 tag in your web.config file and add this line.  It should resolve the compilation errors straightaway.
<add assembly="WindowsBase, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>

Wednesday, December 21, 2011

New version of WordXML document using OpenXML SDK 2.0 with bold, color and font size formatting


I first dabbled with the OpenXML SDK 2.0 in January 2011.

At that time, there was a problem which I could not solve: specifying different font sizes, font colors and bolding effects for different words on the same line.

I managed to achieve different formatting effects for sentences on different lines, but never managed to get it working if the words were on the same line.

Today, I finally figured out how to do it, and scroll down if you are interested to look at the code.

Oh, and do remember to add in the reference for OpenXML SDK and add the imports.

A screenshot of how the generated Word document looks like:

2011-12-21_214518
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Wordprocessing;
public void GenerateWord(){
            WordprocessingDocument doc = WordprocessingDocument.Create(filename, WordprocessingDocumentType.Document);
            MainDocumentPart mainPart = doc.AddMainDocumentPart();
            mainPart.Document = new Document();
            Body body = new Body();

            /**** Create the contents ****/
            DocumentFormat.OpenXml.Wordprocessing.Run run1, run2, run3, run4;
            Paragraph para;

            string text1 = "OpenXML Demo";
            string text2 = "By Dora Chua";
            string text3 = "Code modified from original at : ";
            string text4 = "http://msdn.microsoft.com/en-us/library/bb448854.aspx";
            string text5 = "Alex";


            DocumentFormat.OpenXml.Wordprocessing.RunProperties runProperties1 = new DocumentFormat.OpenXml.Wordprocessing.RunProperties(new RunFonts() { Ascii = "Times New Roman" });
            DocumentFormat.OpenXml.Wordprocessing.RunProperties runProperties2 = new DocumentFormat.OpenXml.Wordprocessing.RunProperties(new RunFonts() { Ascii = "Arial" });
            DocumentFormat.OpenXml.Wordprocessing.RunProperties runProperties3 = new DocumentFormat.OpenXml.Wordprocessing.RunProperties(new RunFonts() { Ascii = "Script" });
            DocumentFormat.OpenXml.Wordprocessing.RunProperties runProperties4 = new DocumentFormat.OpenXml.Wordprocessing.RunProperties(new RunFonts() { Ascii = "Courier New" });
            DocumentFormat.OpenXml.Wordprocessing.RunProperties runProperties5 = new DocumentFormat.OpenXml.Wordprocessing.RunProperties(new RunFonts() { Ascii = "Courier New" });
            
            DocumentFormat.OpenXml.Wordprocessing.FontSize fs1 = new DocumentFormat.OpenXml.Wordprocessing.FontSize();
            DocumentFormat.OpenXml.Wordprocessing.Color c1 = new DocumentFormat.OpenXml.Wordprocessing.Color();
            DocumentFormat.OpenXml.Wordprocessing.Bold b1 = new DocumentFormat.OpenXml.Wordprocessing.Bold();

            DocumentFormat.OpenXml.Wordprocessing.FontSize fs2 = new DocumentFormat.OpenXml.Wordprocessing.FontSize();
            DocumentFormat.OpenXml.Wordprocessing.Color c2 = new DocumentFormat.OpenXml.Wordprocessing.Color();
            DocumentFormat.OpenXml.Wordprocessing.Bold b2 = new DocumentFormat.OpenXml.Wordprocessing.Bold();

            DocumentFormat.OpenXml.Wordprocessing.FontSize fs3 = new DocumentFormat.OpenXml.Wordprocessing.FontSize();
            DocumentFormat.OpenXml.Wordprocessing.Color c3 = new DocumentFormat.OpenXml.Wordprocessing.Color();
            DocumentFormat.OpenXml.Wordprocessing.Bold b3 = new DocumentFormat.OpenXml.Wordprocessing.Bold();

            DocumentFormat.OpenXml.Wordprocessing.FontSize fs4 = new DocumentFormat.OpenXml.Wordprocessing.FontSize();
            DocumentFormat.OpenXml.Wordprocessing.Color c4 = new DocumentFormat.OpenXml.Wordprocessing.Color();
            DocumentFormat.OpenXml.Wordprocessing.Bold b4 = new DocumentFormat.OpenXml.Wordprocessing.Bold();


            DocumentFormat.OpenXml.Wordprocessing.FontSize fs5 = new DocumentFormat.OpenXml.Wordprocessing.FontSize();
            DocumentFormat.OpenXml.Wordprocessing.Color c5 = new DocumentFormat.OpenXml.Wordprocessing.Color();
            DocumentFormat.OpenXml.Wordprocessing.Bold b5 = new DocumentFormat.OpenXml.Wordprocessing.Bold();


            /*** Format text1   ***/
            run1 = new DocumentFormat.OpenXml.Wordprocessing.Run();
            fs1.Val = "20";
            c1.Val = "green";
            b1.Val = true;
           
            runProperties1.Append(fs1);
            runProperties1.Append(c1);
            runProperties1.Append(b1);

            run1.Append(runProperties1);
            run1.Append(new DocumentFormat.OpenXml.Wordprocessing.Text(text1));

            para = new Paragraph(run1);
            body.AppendChild(para);


            /*** Format text2 ***/
            run2 = new DocumentFormat.OpenXml.Wordprocessing.Run();

            fs2.Val = "20";
            c2.Val = "black";
            b2.Val = false;

            runProperties2.Append(fs2);
            runProperties2.Append(c2);
            runProperties2.Append(b2);

            run2.Append(runProperties2);
            run2.Append(new DocumentFormat.OpenXml.Wordprocessing.Text(text2));

            para = new Paragraph(run2);
            body.AppendChild(para);

            /*** Format text3 and text4 as one paragraph ***/
            run3 = new DocumentFormat.OpenXml.Wordprocessing.Run();

            fs3.Val = "15";
            c3.Val = "black";
            b3.Val = false;
            runProperties3.Append(fs3);
            runProperties3.Append(c3);
            runProperties3.Append(b3);

            run3.Append(runProperties3);
            run3.Append(new DocumentFormat.OpenXml.Wordprocessing.Text(text3));

            fs4.Val = "15";
            c4.Val = "red";
            b4.Val = true;
            runProperties4.Append(fs4);
            runProperties4.Append(c4);
            runProperties4.Append(b4);

            run3.Append(runProperties4);
            run3.Append(new DocumentFormat.OpenXml.Wordprocessing.Text(text4));

            para = new Paragraph(run3);
            body.AppendChild(para);


            /*** Format the user-typed text ***/
            fs5.Val = "30";
            c5.Val = "blue";
            b5.Val = false;
            runProperties5.Append(fs5);
            runProperties5.Append(c5);
            runProperties5.Append(b5);

            run4 = new DocumentFormat.OpenXml.Wordprocessing.Run();

            run4.Append(runProperties5);
            run4.Append(new DocumentFormat.OpenXml.Wordprocessing.Text(text5));

            para = new Paragraph(run4);
            body.AppendChild(para);


            /*** Append the entire body ****/
            mainPart.Document.Append(body);

            /* Save the results and close */
            mainPart.Document.Save();
            doc.Close();
}//end GenerateWord
        

Monday, October 24, 2011

Create a hyperlink using a QueryString or Form parameter in C# ASP.NET

 

This is a very short code snippet which shows you how you can create a hyperlink using a QueryString or Form parameter received from a referring page.

Note that you would need to do two things in order for this to work:

Step 1
First, paste the code below in the HTML markup.  The code below assumes that you are using a querystring parameter called “ID” that was passed over from a previous page.

<asp:HyperLink Target="_blank" ID="HyperLinkViewFeedback" runat="server"
NavigateURL='<%# String.Concat("~/Feedback/ViewFeedback.aspx?ID=",Request.QueryString["ID"]) %>'>View Feedback</asp:HyperLink>

Step 2
Add the “Page.DataBind()” method to the OnLoad of the code-behind file.

protected void Page_Load(object sender, EventArgs e)
{
Page.DataBind();
}

After that, you should see the hyperlink with the ID automatically appended as follows:


2011-10-24_132412

Wednesday, February 23, 2011

How to: Enable User Password Recovery Using the ASP.NET PasswordRecovery Control

How to: Enable User Password Recovery Using the ASP.NET PasswordRecovery Control
How to: Install and Configure SMTP Virtual Servers in IIS 6.0
Solving exceptions when doing password recovery

asp.net - Hashed passwords and PasswordRecovery control - Stack Overflow

asp.net - Hashed passwords and PasswordRecovery control - Stack Overflow: "UPDATE:

1) For some reason it works now. Namely, if we set requiresQuestionAndAnswer to false, then PR also sends email to firstUser


2) If passwords are stored in hashed form, then if:

a) enablePasswordRetrieval='true' and enablePasswordReset is set to either true or false --> PR generates exception
b) if enablePasswordRetrieval='false' and enablePasswordReset='false' --> PR generates exception
c) if enablePasswordRetrieval is set to false and enablePasswordReset is set to true, then PR automatically generates new pwd and emails it.


Similarly, if pwd is not hashed, but we have enablePasswordRetrieval='false', then enablePasswordReset must be set to true (so that PR generates a new pwd and emails it), else we get an exception"

Tuesday, February 22, 2011

How to: Read Connection Strings from the Web.config File

using System.Configuration;
using System.Data;

public static string GetUserName(string userid){
string fullname = "Unknown name";
string connString = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString; string sqlString = "SELECT * FROM Users WHERE UserID=@UserID";
SqlDataSource sqldatasource = new SqlDataSource(connString, sqlString);
sqldatasource.SelectParameters.Add(new Parameter("UserID", System.Data.DbType.String, userid));

DataView dv = (DataView)sqldatasource.Select(DataSourceSelectArguments.Empty);
if (dv != null && dv.Table != null & dv.Table.Rows.Count > 0)
{
fullname = dv.Table.Rows[0]["FullName"].ToString();
}

return fullname;
}

How to: Read Connection Strings from the Web.config File: "ConnectionStrings.ConnectionStrings['NorthwindConnectionString'];"

Monday, February 14, 2011

MembershipUser Class (System.Web.Security)

MembershipUser Class (System.Web.Security)

Using ConfigurationManager.AppSettings

Step 1
======
Add a reference to assembly


Step 2
======
Add this before the class header

using System.Configuration;

Step 3
======
Access the configuration setting using this code:

System.Configuration.ConfigurationManager.AppSettings["WebMasterEmail"]

Wednesday, February 2, 2011

The Search Form (Code Behind)

 

 protected void ButtonSearch_Click(object sender, EventArgs e)
{
string criterias = "";

criterias = TextBoxKeyword.Text.Length > 0 ? (criterias + "Keyword") : criterias;
criterias = TextBoxCourse.Text.Length > 0 ? (criterias + "Course") : criterias;
criterias = TextBoxStartDate.Text.Length > 0 ? (criterias + "EventDate") : criterias;
criterias = TextBoxDateOfEntryStart.Text.Length > 0 ? (criterias + "DateOfEntry") : criterias;


string keyword = TextBoxKeyword.Text.Length>0? TextBoxKeyword.Text : "NULL";
string course = TextBoxCourse.Text.Length > 0 ? TextBoxCourse.Text : "NULL";
string startdate = TextBoxStartDate.Text.Length > 0 ? TextBoxStartDate.Text : "NULL";
string enddate = TextBoxEndDate.Text.Length > 0 ? TextBoxEndDate.Text : "NULL";
string dateofentrystart = TextBoxDateOfEntryStart.Text.Length > 0 ? TextBoxDateOfEntryStart.Text : "NULL";
string dateofentryend = TextBoxDateOfEntryEnd.Text.Length > 0 ? TextBoxDateOfEntryEnd.Text : "NULL";

TextBox1.Text = "Criterias:" + criterias + "\nKeyword:" + keyword + "\nCourse:" + course
+ "\nStartDate:" + startdate + "\nEndDate:" + enddate
+ "\nDateOfEntryStart:" + dateofentrystart + "\nDateOfEntryEnd:" + dateofentryend;

SqlDataSourceEventsByCriteria.SelectParameters["Criteria"].DefaultValue = criterias;
SqlDataSourceEventsByCriteria.SelectParameters["Keyword"].DefaultValue = keyword;
SqlDataSourceEventsByCriteria.SelectParameters["Course"].DefaultValue = course;
SqlDataSourceEventsByCriteria.SelectParameters["EventStartDate"].DefaultValue = startdate;
SqlDataSourceEventsByCriteria.SelectParameters["EventEndDate"].DefaultValue = enddate;
SqlDataSourceEventsByCriteria.SelectParameters["DateOfEntryStart"].DefaultValue = dateofentrystart;
SqlDataSourceEventsByCriteria.SelectParameters["DateOfEntryEnd"].DefaultValue = dateofentryend;

try
{

DataView dvEvents = (DataView)SqlDataSourceEventsByCriteria.Select(DataSourceSelectArguments.Empty);
DataTable dtEvents = dvEvents.Table;
GridView1.DataSource = dtEvents;
GridView1.DataBind();
}
catch (Exception exSelect)
{
TextBox1.Text = exSelect.Message;
}
}

The Search Form

 

Remember to add the AjaxControlToolkit as reference first.

<%@ Page Title="" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeFile="TestSearch.aspx.cs" Inherits="Track_TestSearch" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" Runat="Server">
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
Keyword
<asp:TextBox ID="TextBoxKeyword" runat="server"></asp:TextBox>
<br />
Course
<asp:TextBox ID="TextBoxCourse" runat="server"></asp:TextBox>
<br />
Start Date
<asp:TextBox ID="TextBoxStartDate" runat="server"></asp:TextBox>
<asp:CalendarExtender
ID="CalendarExtender1" runat="server" TargetControlID="TextBoxStartDate"
Format="dd-MMM-yyyy">
</asp:CalendarExtender>
&nbsp;&nbsp;&nbsp;&nbsp;
End Date
<asp:TextBox ID="TextBoxEndDate" runat="server"></asp:TextBox>
<br />
<br />
<asp:CalendarExtender
ID="CalendarExtender2" runat="server" TargetControlID="TextBoxEndDate"
Format="dd-MMM-yyyy">
</asp:CalendarExtender>

<br />
Start Date
<asp:TextBox ID="TextBoxDateOfEntryStart" runat="server"></asp:TextBox>
<asp:CalendarExtender
ID="CalendarExtender3" runat="server" TargetControlID="TextBoxDateOfEntryStart"
Format="dd-MMM-yyyy">
</asp:CalendarExtender>
&nbsp;&nbsp;&nbsp;&nbsp;
End Date
<asp:TextBox ID="TextBoxDateOfEntryEnd" runat="server"></asp:TextBox>
<br />
<br />
<asp:CalendarExtender
ID="CalendarExtender4" runat="server" TargetControlID="TextBoxDateOfEntryEnd"
Format="dd-MMM-yyyy">
</asp:CalendarExtender>

<asp:TextBox ID="TextBox1" Rows="15" Cols="100" TextMode="MultiLine" runat="server"></asp:TextBox>

<asp:Button ID="ButtonSearch" runat="server" Text="Search"
onclick="ButtonSearch_Click" />

<br />

<asp:GridView ID="GridView1" runat="server">
</asp:GridView>

<asp:SqlDataSource ID="SqlDataSourceEventsByCriteria" runat="server"
ConnectionString="<%$ ConnectionStrings:ApplicationServices %>"
SelectCommand="GetEventsByCriteria6" SelectCommandType="StoredProcedure">
<SelectParameters>
<asp:Parameter Name="Criteria" Type="String" />
<asp:Parameter Name="Keyword" Type="String" />
<asp:Parameter Name="Course" Type="String" />
<asp:Parameter Name="EventStartDate" Type="String" />
<asp:Parameter Name="EventEndDate" Type="String" />
<asp:Parameter Name="DateOfEntryStart" Type="String" />
<asp:Parameter Name="DateOfEntryEnd" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
</asp:Content>

Generic Dynamically Constructed SQL string

 

USE [MyDB]
GO
/****** Object: StoredProcedure [dbo].[GetEventsByCriteria] Script Date: 02/02/2011 01:32:22 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET DATEFORMAT DMY
GO
create PROCEDURE [dbo].[GetEventsByCriteria6]
(
@Criteria nvarchar(255),
@Keyword nvarchar(255),
@Course nvarchar(255),
@EventStartDate nvarchar(25),
@EventEndDate nvarchar(25),
@DateOfEntryStart nvarchar(25),
@DateOfEntryEnd nvarchar(25)
)

As
DECLARE @SQLString NVARCHAR(500)
DECLARE @SQLStr1 NVARCHAR(200)
DECLARE @SQLStr2 NVARCHAR(200)
DECLARE @SQLStr3 NVARCHAR(200)
DECLARE @SQLStr4 NVARCHAR(200)

/* Set column list. CHAR(13) is a carriage return, line feed.*/
SET @SQLString = N'SELECT * FROM [EVENTS] ' + CHAR(13)

/* Set WHERE clause. */
SET @SQLStr1 = N' [EventStartDate]>=''' + @EventStartDate + ''''
+ N' AND [EventEndDate]<=''' + @EventEndDate + ''''


SET @SQLStr2 = N' [DateOfEntry]>=''' + @DateOfEntryStart + ''''
+ N' AND DateOfEntry<=''' + @DateOfEntryEnd+ ''''

SET @SQLStr3 = N' [EventTitle] LIKE ''%' + @Keyword + N'%'''

SET @SQLStr4 = N' [Course] LIKE ''%' + @Course + N'%'''


/* Set ORDER clause. */
if (charindex('WHERE',@SQLString)=0 and charindex('EventDate',@Criteria)<>0)
SET @SQLString = @SQLString + N' WHERE ' + @SQLStr1
else if (charindex('WHERE',@SQLString)<>0 and charindex('EventDate',@Criteria)<>0)
SET @SQLString = @SQLString + N' AND ' + @SQLStr1

if (charindex('WHERE',@SQLString)=0 and charindex('DateOfEntry',@Criteria)<>0)
SET @SQLString = @SQLString + N' WHERE ' + @SQLStr2
else if (charindex('WHERE',@SQLString)<>0 and charindex('DateOfEntry',@Criteria)<>0)
SET @SQLString = @SQLString + N' AND ' + @SQLStr2

if (charindex('WHERE',@SQLString)=0 and charindex('Keyword',@Criteria)<>0)
SET @SQLString = @SQLString + N' WHERE ' + @SQLStr3
else if (charindex('WHERE',@SQLString)<>0 and charindex('Keyword',@Criteria)<>0)
SET @SQLString = @SQLString + N' AND ' + @SQLStr3

if (charindex('WHERE',@SQLString)=0 and charindex('Course',@Criteria)<>0)
SET @SQLString = @SQLString + N' WHERE ' + @SQLStr4
else if (charindex('WHERE',@SQLString)<>0 and charindex('Course',@Criteria)<>0)
SET @SQLString = @SQLString + N' AND ' + @SQLStr4

SET @SQLString = @SQLString + N' ORDER BY [EventStartDate] DESC'
-- CONVERT(datetime, @eventstartdate, 103)

print @SQLString
EXEC sp_executesql @SQLString
--CONVERT(varchar(8), ctdate, 112)