Jun 24 2010

Call a .NET Web Service in a BlackBerry Widget

Mohammed Al-Atari

URL: http://www.geekreflex.com/blog/blogarticle.aspx?ArticleID=13

One of my responsibilities where I work is to provide custom software for our BlackBerry smart phones. As of June 30, 2010, BlackBerry MDS Runtime will no longer be supported by RIM (Research in Motion). This posed a problem since we upgraded our users to new BlackBerry Bold 9700s this year. The new BlackBerry application platform focuses on two approaches; BlackBerry Widgets and Java. BlackBerry Widgets utilize web development languages such as HTML, CSS, Javascript and AJAX. Since I am not very familiar with Java development, I chose to migrate our existing MDS applications to BlackBerry Widgets.

RIM offers a plug-in for Microsoft Visual Studio that allows .NET developers to use a .NET programming environment to develop BlackBerry applications. The MDS plug-in worked great and provided the ability to reference a .NET Web Service with ease. The good news is, this plug-in has been updated to support new BlackBerry Widgets, however it’s still in Beta form. If you need to reference a web service in a BlackBerry Widget app you’ll notice immediately that it’s not as easy in the new web plug-in as was in the MDS plug-in. Not to worry though. With a little bit of AJAX, you can consume a web service without any problem and I’m going to explain and demonstrate how to do this from start to finish.

For this example, we’ll do the following:

  • Create a BlackBerry Widget project in Microsoft Visual Studio 2008.
  • Create a .NET Web Service with a simple “Hello World” method.
  • Invoke the web service method in the BlackBerry Widget app using XMLHttpRequest.

First, you’ll need a couple of things before you can create a BlackBerry Widget; the BlackBerry Web Plug-in for Visual Studio and the Sun Java Development Kit 1.6 or Higher. Follow this link to get the Plug-in and JDK. The Web Plug-in for Eclipse is also provided, but for this example we’ll be using the Visual Studio Plug-in.

Once you have the Plug-in and JDK installed, open Visual Studio 2008 and Create a new Project. Here you should simply be able to select the BlackBerry Project type, then BlackBerry Widget and hit OK. However, since the Plug-in is still in Beta it’s a bit buggy. Before you can actually save a BlackBerry Widget project you have to create a separate project type first, and then add a BlackBerry Widget project as a new Project. If not, you’ll be presented with the following error when trying to save the project.

I didn’t research this issue so there could be other work-a-rounds and it’s possible you may not experience this error at all. I did encounter this error and I’m using Visual Studio Team System 2008 Development Edition and the MDS plug-in had also previously been installed.

So…instead of selecting the BlackBerry project type, expand Other Project Types and select Visual Studio Solutions. Select the Blank Solution Template, name it “HelloWorldWidget” or whatever you desire and click OK. Now, right-click on the Solution in the Solution Explorer and Add a New Project. This time, select the BlackBerry Project type, then the BlackBerry Widget Template. Again, name it “HelloWorldWidget” and click OK.

Two files will be created and added to your Widget project; config.xml and index.htm.

Before we go any further, let’s go ahead and create the Web Service. Add another New Project to your Solution. Under Visual Basic (used in this example) or Visual C# Project type, select Web and create an ASP.NET Web Service Application. Call it “HelloWorldService”. By default, a HelloWorld Web Method is already added to Service1.asmx.vb. If for whatever reason it’s not, add it.

Right click the Web Service in Solution Explorer, select Debug and Start new instance This will create a test ASP.NET Development Server we can use to call our service later.

Now let’s get back to the Widget. View the code of index.htm and add a simple input button to the body.

Eventually, clicking this button will display an alert box with the return string, “Hello World” from our web service. To do this, we just need a little AJAX script.

To keep our project neat and organized, create a New Folder in the Widget app and call it “scripts”. Right click the folder and select Add > New Item…. Select JScript from the BlackBerry category and name it “actions.js”.

Here we’re going to use XMLHttpRequest make a request to our web service and invoke the HelloWorld method. We’ll retrieve the response in XML, then parse the XML to retrieve our return string.

First, create the XMLHttpRequest object.

Now, you’ll need an event handler which will be called from the button click on the htm page. This will send the request for data to the web service. We’ll make the request by sending a GET method to the web service.

Make sure and change the url above to your test ASP.NET Development Server url.
The sayHello() function listens to the onreadystatechange property of the XMLHttpRequest object and calls another function that we’ll call callbackFunction(). This function determines when the server has completed our request and will handle the data returned.

The call back function checks for a readyState value of 4. This value indicates that the request has completed and we can use the data returned. There are other values that may be returned from this request but for this purpose we are interested in this value.
We’ll receive the data as text through the responseText property of the XMLHttpRequest object and then display it in an alert box.

Just a few more steps and we’re done! Open your config.xml file in your BlackBerry Widget application. Here you have several different configuration options you can change, however there is only one we are required to change before our widget will work correctly. We’ll need to give our widget access to the domain where our web service resides. Click Add Domain, then enter the domain into the textbox provided. Our web service is on our local machine so we’ll use http://localhost:2064. For this example, the ASP.NET Development Server is using port 2064, but this may be different on your machine.

Now let’s test it out! Make sure the widget application is set as the StartUp Project, then hit F5 (or start the debug instance from the GUI). The BlackBerry simulator should start loading and you will eventually be presented with your application. The BlackBerry Simulator is a pretty cool tool, as it does very well in simulating a BlackBerry device. You can also download other BlackBerry models to simulate from BlackBerry’s website.

Test the widget out by clicking the button that you created. Nothing happen? Good. We still have one more step before we can get a response, sorry. I wasted a lot of time trying to figure this one out, so I intentionally left it out above so it would stand out. We have to enable our web service to be invoked using SOAP and GET, as ASP.NET does not allow this by default. To do this, simply add the following code under system.web in your web service’s Web.config file.

Alright, now let’s run our widget application again! This time you should receive an alert box similar to the following after pressing the button:

Don’t worry, we’re still not finished. Our code at this point is just returning the XML from our web service method as plain text. You have a few options here. You can parse this text to retrieve the actual value, or you can return the data as XML using the responseXML property of the XMLHTTPRequest object. Then we can parse the XML with ease to get our “Hello World” string. Change your javascript callbackFunction() to look like the following:

If you want to learn more about XML Parsing, check on this link

Now the Widget application should display an alert box with a simple “Hello World” string.

Share This: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Facebook
  • Live-MSN
  • TwitThis
  • LinkedIn
  • MySpace
  • email

Jun 17 2010

How to call Server Side function from Client Side Code using PageMethods in ASP.NET AJAX

Mohammed Al-Atari

 URL: http://www.dotnetcurry.com/ShowArticle.aspx?ID=109

You cannot call server-side code ‘directly’ from client-side code. That is because by design, the server side code executes at server side and client side code at the client. However there are some workarounds. To call serverside code from javascript, you will need to use AJAX, and the easiest way out, is to use the ASP.NET AJAX Extensions.

One option while using Microsoft ASP.NET AJAX is to call ASP.NET Web services (.asmx files) from the browser by using client script. The script can call a webservice containing server-based methods (Web methods) and invoke these methods without a postback and without refreshing the whole page. However this approach could be overkill sometimes, to perform the simplest of tasks. Moreover the logic needs to be kept in a separate .asmx file. We need something that is more ‘integrated’ with our solution.

The option we are going to use in this article involves PageMethods. A PageMethod is basically a public static method that is exposed in the code-behind of an aspx page and is callable from the client script. PageMethods are annotated with the [WebMethod] attribute. The page methods are rendered as inline JavaScript.

Let us explore PageMethods with an example. The example we will be discussing here may not be the best example to explain PageMethods, but it will give you an idea of how to call server side code from client side. In this example, we will be connecting to the Customers table in the Northwind database. We will have some textboxes which will accept the CustomerID and in turn return the Contact Name of that Customer. The method returning ContactName will be called whenever the textbox loses focus. We will be using the onblur event where a javascript code will take in the value(CustomerID) from the textbox. This javascript function will then call a PageMethod (server side code) which returns the ContactName without any page refresh.

I assume that you have downloaded and installed ASP.NET AJAX extensions for ASP.NET 2.0. If not, I would advise you to download the extensions from here and install it before moving ahead. At any point of time, if you find a difficulty in understanding the code, download the sample project attached with this article at the end.

Step 1: Create an ASP.NET AJAX enabled website. Go to File > New > Website > ASP.NET AJAX-Enabled Web Site. Give the solution a name and location and click Ok.

Step 2: Drag and drop 2 labels and 4 textbox controls. We will be accepting the CustomerID from the user in the 2 textboxes and displaying the ‘ContactName’ in the other two textboxes. The textboxes that will display ‘ContactName’ has some properties set that will make it appear as a label without a border. Just set the BorderStyle=None, BorderColor=Transparent and ReadOnly=True. The markup will look similar to the following:

<form id=”form1″ runat=”server”>    

        <asp:ScriptManager ID=”ScriptManager1″ runat=”server”/>

        <div>

        <asp:Label ID=”lblCustId1″ runat=”server” Text=”Customer ID 1″></asp:Label>

        <asp:TextBox ID=”txtId1″ runat=”server”></asp:TextBox><br />

            <asp:TextBox ID=”txtContact1″ runat=”server” BorderColor=”Transparent” BorderStyle=”None”

                ReadOnly=”True”></asp:TextBox><br />

        <br />

        <asp:Label ID=”lblCustId2″ runat=”server” Text=”Customer ID 2″></asp:Label>

        &nbsp;

        <asp:TextBox ID=”txtId2″ runat=”server”></asp:TextBox><br />

            <asp:TextBox ID=”txtContact2″ runat=”server” BorderColor=”Transparent” BorderStyle=”None”

                ReadOnly=”True”></asp:TextBox>&nbsp;<br />

            </div>

    </form>

Before moving ahead, we will store our connection string information in the Web.config. Add the following tag below your </configSections> tag. Remember we have created an ‘ASP.NET AJAX enabled website’. The tag </configSections> along with some other tags automatically get added to the web.config.

<connectionStrings>

            <removename=”all”/>

            <addname=”NorthwindConnectionString”connectionString=”Data Source=(local); Initial Catalog=Northwind; Integrated Security = SSPI;”/>

      </connectionStrings>

Step 3: Currently we will add a method, ‘GetContactName()’ which will accept a CustomerID and return the Contact Name information from the Northwind database, Customer table. We will then transform this method as a PageMethod.

C#

public static string GetContactName(string custid)

    {

        if (custid == null || custid.Length == 0)

            return String.Empty;

        SqlConnection conn = null;

        try

        {

            string connection = ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString;

            conn = new SqlConnection(connection);

            string sql = “Select ContactName from Customers where CustomerId = @CustID”;

            SqlCommand cmd = new SqlCommand(sql, conn);

            cmd.Parameters.AddWithValue(“CustID”, custid);

            conn.Open();

            string contNm = Convert.ToString(cmd.ExecuteScalar());

            return contNm;

        }

        catch (SqlException ex)

        {

            return “error”;

        }

        finally

        {

            conn.Close();

        }

    }

VB.NET

 Public Shared Function GetContactName(ByVal custid As String) As String

        If custid Is Nothing OrElse custid.Length = 0 Then

            Return String.Empty

        End If

        Dim conn As SqlConnection = Nothing

        Try

            Dim connection As String = ConfigurationManager.ConnectionStrings(“NorthwindConnectionString”).ConnectionString

            conn = New SqlConnection(connection)

            Dim sql As String = “Select ContactName from Customers where CustomerId = @CustID”

            Dim cmd As SqlCommand = New SqlCommand(sql, conn)

            cmd.Parameters.AddWithValue(“CustID”, custid)

            conn.Open()

            Dim contNm As String = Convert.ToString(cmd.ExecuteScalar())

            Return contNm

        Catch ex As SqlException

            Return “error”

        Finally

            conn.Close()

        End Try

    End Function

Step 4: We will now transform this method as a PageMethod and then call this method GetContactName() from client side code; i.e. using JavaScript. To enable the method as a PageMethod, add the attribute [WebMethod] on top of the method:

C#

[System.Web.Services.WebMethod]

public static string GetContactName(string custid)

{

}

VB.NET

<System.Web.Services.WebMethod()> _

    Public Shared Function GetContactName(ByVal custid As String) As String

   End Function

At the sametime, add the attribute EnablePageMethods=”true” to the ScriptManager as shown below:

<asp:ScriptManager ID=”ScriptManager1″ runat=”server” EnablePageMethods=”true”/>

Step 5: Let us now create the JavaScript that will call this server side code. Add a javascript file called script.js to your solution (Right Click Project > Add New Item > Jscript File > Rename file to script.js). Add the following code to the javascript file.

function CallMe(src,dest)

 {    

     var ctrl = document.getElementById(src);

     // call server side method

     PageMethods.GetContactName(ctrl.value, CallSuccess, CallFailed, dest);

 }

 // set the destination textbox value with the ContactName

 function CallSuccess(res, destCtrl)

 {    

     var dest = document.getElementById(destCtrl);

     dest.value = res;

 }

 // alert message on some failure

 function CallFailed(res, destCtrl)

 {

     alert(res.get_message());

 }

Step 6: We now need to reference this JavaScript file from our aspx page and invoke the ‘CallMe()’ method whenever the textbox loses focus. To do so:

Add a reference to the javascript file in the body tag as shown below:

<body>

<script type=”text/javascript” language=”javascript” src=”script.js”> </script>

    <form id=”form1″ runat=”server”>    

………

Step 7: To invoke the methods whenever the textbox looses focus, add these lines of code in the Page_Load() event

C#

if (!Page.IsPostBack)

        {

            txtId1.Attributes.Add(“onblur”, “javascript:CallMe(‘” + txtId1.ClientID + “‘, ‘” + txtContact1.ClientID + “‘)”);

            txtId2.Attributes.Add(“onblur”, “javascript:CallMe(‘” + txtId2.ClientID + “‘, ‘” + txtContact2.ClientID + “‘)”);

        }

VB.NET

If (Not Page.IsPostBack) Then

                  txtId1.Attributes.Add(“onblur”, “javascript:CallMe(‘” & txtId1.ClientID & “‘, ‘” & txtContact1.ClientID & “‘)”)

                  txtId2.Attributes.Add(“onblur”, “javascript:CallMe(‘” & txtId2.ClientID & “‘, ‘” & txtContact2.ClientID & “‘)”)

End If

As shown above, we are using the Attributes.Add that lets us add an attribute to the server control’s System.Web.UI.AttributeCollection object. The function ‘CallMe’ kept in the ‘script.js’ file will be invoked. We are passing the source and destination textboxes as parameters. The source textbox will contain the CustomerID. The CustomerID will be looked up in the Customers table and the corresponding ‘ContactName’ will be retrieved in the destination textbox.

Well that is all that is needed to invoke server side code from client side. Run the code. Type ‘ALFKI’ in the first textbox and hit the tab key. You will see that the javascript function goes ahead and calls the PageMethod GetContactName() using PageMethods.GetContactName. It passes the value of the source textbox which contains the CustomerID. The ‘ContactName’ returned is displayed in the second textbox below the first one, in our case the value displayed is ‘Maria Anders’.

Troubleshooting: ‘PageMethods Is ‘Undefined’’ error

1.    Try setting EnablePageMethods=”true” in the script manager tag

<asp:ScriptManager ID=”ScriptManager1″ runat=”server” EnablePageMethods=”true”/>

2.    Don’t add the javascript references or code in the <head /> section. Add it to the <body> tag.

<body>

<script type=”text/javascript” language=”javascript” src=”script.js”> </script>

    <form id=”form1″ runat=”server”> 

    </form>

</body>

3.    Page methods needs to be static in code behind.

I hope you have got an idea of how to call server side code using JavaScript. I have used this technique successfully in a few projects and just love and admire PageMethods. I hope you found this article useful and I thank you for viewing it. The source code for this article can be downloaded from here.

Share This: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Facebook
  • Live-MSN
  • TwitThis
  • LinkedIn
  • MySpace
  • email

Jun 16 2010

iPhone Webclip Icons (apple-touch-icon)

Mohammed Al-Atari

I remember, years ago, I was baffled by the little 16×16 icons that were showing up in my URL toolbar, and it took a surprising amount of searching to find out how to create one. I refuse to let this happen again.

So: if you want to make a custom icon for your website that will show up in the Springboard when a user makes a “webclip”, using their iPhone or iPod Touch, the dirt simple way is:

  • Create a 57×57 PNG.
  • Name it “apple-touch-icon.png”
  • Throw it in the root folder of your website. (Not the root of your server, the root of your web documents.)

Boom. If you add a webclip for vjarmy.com, you’ll see my smiling mug.

If you want more flexibility – perhaps you don’t have access to the site root, perhaps you want to use a different file name or format – you can use a link tag in the head of the document, such as:

<head>
    <title>iHelloWorld</title>
    <link rel="apple-touch-icon" href="/whatever.jpg"/>
    OR
    <link rel="apple-touch-icon-precomposed" href="/whatever.jpg"/ />
</head>

I’ve tested this with a slightly larger (75×75) JPEG, and it works without trouble – it just scales things down.

If you’re testing this on your iPhone, you may notice a pause of a few seconds before the icon appears when you press “Add To Home Menu”. I’d imagine the icon only downloads when you request to make a webclip, instead of the “request it every time” method used for fetching favicon.ico. (As for why it’s a few seconds – well, that’s EDGE for you. The lag goes away when you use WiFi.)

Apple has more info on their iPhone Dev Center; look at “Create a WebClip Bookmark Icon”.

And don’t worry if your icon design skills aren’t up to snuff, but do worry if you care about the sanctity of your image:

Safari will automatically composite the icon with the standard “glassy” overlay so it looks like a built-in iPhone or iPod application.

Share This: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Facebook
  • Live-MSN
  • TwitThis
  • LinkedIn
  • MySpace
  • email

Jun 16 2010

Custom JavaScript Alert

Mohammed Al-Atari

URL:http://slayeroffice.com/code/custom_alert/
This is a demonstration of how to over-ride the default window.alert method of a browser.

This was born from the design requirements of a recent project to have non-standard alerts to notify the user of a problem with data they had entered. The trick here was that all products use the same validation scripts, and not all of them fell under this requirement.

To modify the validation scripts to expect another argument that would have told it to use a DIV overlay or a standard alert would have proven difficult to implement and maintain. A co-worker (Dean) wondered out loud if it was possible to overload the alert method, and turns out – you can.

You can test the alert functionality with the following button. You can also type javascript:alert("Hello World"); from your browsers URL bar to see it work.

The markup for the above button is:
<input value = "Test the alert" />

Psuedo-modality is achieved by using a 100% wide and 100% tall absolutely positioned DIV element that acts as the parent element of the custom alert. This DIV overlays everything on the page and prevents user interaction with elements other than the custom alert. Note that a 1×1 transparent png image is set as the background-image — this prevents MSIE from allowing the parent DIV to be “hollow”, which would defeat its purpose.

Only one alert can exist at a time — the function will return if it detects the existence of a previous instance of the “modalContainer” parent element. Hitting the “Ok” button will remove the “modalContainer” element from the DOM along with its child elements and hand control of the page back to the user.

In browsers that support position:fixed, meaning all of them except MSIE6 and lower, the alert will stay with the user as they scroll. Thanks to Kevin for the education on that property value.

This has been tested and verified to work in MSIE6, Firefox 1.0, Safari and Opera 7.1+.

Note: This is a demonstration only. I am not saying that this is a production worthy alternative to the default behavior of the window.alert method as it does not allow for true modality. I am only showing what is possible – implement at your own risk. Feel free to contact me with any suggestions.

Source:

// constants to define the title of the alert and button text.
var ALERT_TITLE = “Oops!”;
var ALERT_BUTTON_TEXT = “Ok”;

// over-ride the alert method only if this a newer browser.
// Older browser will see standard alerts
if(document.getElementById) {
 window.alert = function(txt) {
  createCustomAlert(txt);
 }
}

function createCustomAlert(txt) {
 // shortcut reference to the document object
 d = document;

 // if the modalContainer object already exists in the DOM, bail out.
 if(d.getElementById(“modalContainer”)) return;

 // create the modalContainer div as a child of the BODY element
 mObj = d.getElementsByTagName(“body”)[0].appendChild(d.createElement(“div”));
 mObj.id = “modalContainer”;
  // make sure its as tall as it needs to be to overlay all the content on the page
 mObj.style.height = document.documentElement.scrollHeight + “px”;

 // create the DIV that will be the alert
 alertObj = mObj.appendChild(d.createElement(“div”));
 alertObj.id = “alertBox”;
 // MSIE doesnt treat position:fixed correctly, so this compensates for positioning the alert
 if(d.all && !window.opera) alertObj.style.top = document.documentElement.scrollTop + “px”;
 // center the alert box
 alertObj.style.left = (d.documentElement.scrollWidth – alertObj.offsetWidth)/2 + “px”;

 // create an H1 element as the title bar
 h1 = alertObj.appendChild(d.createElement(“h1″));
 h1.appendChild(d.createTextNode(ALERT_TITLE));

 // create a paragraph element to contain the txt argument
 msg = alertObj.appendChild(d.createElement(“p”));
 msg.innerHTML = txt;

 // create an anchor element to use as the confirmation button.
 btn = alertObj.appendChild(d.createElement(“a”));
 btn.id = “closeBtn”;
 btn.appendChild(d.createTextNode(ALERT_BUTTON_TEXT));
 btn.href = “#”;
 // set up the onclick event to remove the alert when the anchor is clicked
 btn.onclick = function() { removeCustomAlert();return false; }


}

// removes the custom alert from the DOM
function removeCustomAlert() {
 document.getElementsByTagName(“body”)[0].removeChild(document.getElementById(“modalContainer”));
}

Share This: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Facebook
  • Live-MSN
  • TwitThis
  • LinkedIn
  • MySpace
  • email

Jun 12 2010

Google Maps into an ASP.NET page

Mohammed Al-Atari
URL:http://blog.evonet.com.au/post/Integrating-Google-Maps-into-an-ASPNET-page.aspx
While Microsoft have released their new Virtual Earth ASP.NET Control, I still haven’t found a decent wrapper that converts addresses to langitude and longitude co-ordinates.  There is a Geo coder web service available here (this shows the co-ordinates for the White House) but it seems to only work for US addresses, which doesn’t help me at all.
So for the moment, I’m still using Google Maps, and have prepared the following to show you how to integrate Google Maps into your ASP.NET pages
Step 1. Get a Google Maps API key
In order to use Google Maps on your site, you need to register for a free Google Maps API key from here: http://www.google.com/apis/maps/
Step 2. Download the SubGurim Google Maps wrapper dll
This one is the best Google Maps wrapper I have found so far http://en.googlemaps.subgurim.net/descargar.aspx.  It is a commercial product (from $10), or you can put up with the overlayed text in the free versions.Download the gmaps.dll file and add it to your \bin directory. Step 3. Set up your aspx page
In your aspx page, add a few text boxes to gather the address details.  You can simply use one textbox, or split the address to enable validation for suburbs, countries, etc.  I haven’t included any form validation in my example.
<p style=”text-align:right; margin-right:300px”> Street Address: <asp:textbox ID=”txtStreetAddress” runat=”server” Width=”150px” /><br /> Suburb: <asp:textbox ID=”txtSuburb” runat=”server” Width=”150px” /><br /> Country: <asp:textbox ID=”txtCountry” runat=”server” Width=”150px” /><br /><br /> <asp:Button Text=”Show Map” ID=”lnkShowMap” runat=”server” /> </p>
You need to add your Google API key to your web.config file like so:
<appSettings> <add key=”googlemaps.subgurim.net” value=”YourGoogleMapsAPIKeyHere” /> </appSettings>
And finally, you need to register the SubGurim wrapper at the top of your page (or in your web.config if you have a number of pages that display maps):
<%@ Register Assembly=”GMaps” Namespace=”Subgurim.Controles” TagPrefix=”cc1″ %>
Step 4: Add code to display the mapFinally, add code that collates your address fields and calls the Google Maps wrapper.
Protected Sub lnkShowMap_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles lnkShowMap.Click Dim strFullAddress As String Dim sMapKey As String = ConfigurationManager.AppSettings(“googlemaps.subgurim.net”) Dim GeoCode As Subgurim.Controles.GeoCode ‘ Combine our address fields to create the full address. The street, ‘ suburb and country should be seperated by periods (.) strFullAddress = txtStreetAddress.Text & “. ” & txtSuburb.Text & “. ” & txtCountry.Text ‘ Work out the longitude and latitude GeoCode = GMap1.geoCodeRequest(strFullAddress, sMapKey) Dim gLatLng As New Subgurim.Controles.GLatLng(GeoCode.Placemark.coordinates.lat, GeoCode.Placemark.coordinates.lng) ‘ Display the map GMap1.setCenter(gLatLng, 16, Subgurim.Controles.GMapType.GTypes.Normal) Dim oMarker As New Subgurim.Controles.GMarker(gLatLng) GMap1.addGMarker(oMarker) End Sub
That’s it! Check out the demo or download the source code, and let me know if you find a good wrapper for the Virtual Earth ASP.NET control!
Share This: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Facebook
  • Live-MSN
  • TwitThis
  • LinkedIn
  • MySpace
  • email

Jun 7 2010

FAQ in Web Forms

Mohammed Al-Atari
1         JavaScript
1.1        How to get client date and time
1.2        How to access a control by using JavaScript
1.3        How to invoke a server-side function with JavaScript
1.4        How to retrieve server side variables using JavaScript code
1.5        How to assign a value to a hidden field using JavaScript in ASP.NET
1.6        How to register the JavaScript function at Code-Behind
1.7        How to display images with a delay of five seconds
1.8        How to get browser screen settings and apply it to page controls
1.9        How to clear the session when the user closes a window
2         Ways to pass data between pages
2.1        How to use cookies
2.2        How to use QueryString
2.3        How to use Session
2.4        How to use Context
2.5        How to use PreviousPage
2.6        How to use Submit Form
2.7        How to use Server.Transfer
3         File Upload
3.1        How to upload a file
3.2        How to upload multiple files at once
3.3        Why upload fails when using an ASP.NET FileUpload control to upload large files
3.4        How to upload an image files only
3.5        How to get a File Upload control work with an UpdatePanel
4         Calendar
4.1        How to change the culture settings for a Calendar
4.2        How to select multiple non-sequential dates at Code-Behind
4.3        How to disable some dates in Calendar control
4.4        How to extend Calendar control for Server-Side validation
4.5        How to set ToolTips and links in Calendar control’s DayRender event
4.6        How to give some dates different appearances
5         List controls
5.1        How to enable ASP.NET DropDownList with OptionGroup support
5.2        How to disable an item in DropDownList
5.3        How to hold the selected value for a DropDownList
6         User control
6.1        How to add a new property to UserControl
6.2        How to access a dynamically created UserControl
6.3        How to access a control inside a UserControl
7         Dynamic controls
7.1        How to create a dynamic control
7.2        How to access a user entered value in a dynamic created TextBox control
7.3        Dynamic controls accessed by JavaScript
7.4        How to retain all added server controls dynamically after post back
7.5        Why dynamically created controls disappear after a post back
8         Style
8.1        How to use with Code-Behind
8.2        How to use with JavaScript
8.3        How to remove a space
8.4        How to use with html
8.5        How to set an image as Button’s background
8.6        How to color items in ListBox
9         Print
9.1        How to print a part of a web page with CSS
9.2        How to print a part of a web page with JavaScript (1)
9.3        How to print a part of a web page with JavaScript (2)
10    Mail
10.1   What classes are needed to send e-mails in ASP.NET
10.2   How to send emails by using System.Net.Mail
10.3   How to configure a SMTP Server
10.4   How to send an email with Gmail server
1.      JavaScript
1.1        How to get client date and time [top]
You can use java script function to show the date and time.
<script type=”text/javascript”>
    function displayTime()
    {
        var localTime = new Date();
        var year= localTime.getYear();
        var month= localTime.getMonth() +1;
        var date = localTime.getDate();
        var hours = localTime .getHours();
        var minutes = localTime .getMinutes();
        var seconds = localTime .getSeconds();   
        var div=document.getElementById(“div1″);
        div.innerText=year+”-”+month+”-”+date+” “+hours+”:”+minutes+”:”+seconds;
    }
</script>
Then you can call it at web page.
<body onload=”displayTime();”>
    <form id=”form2″ runat=”server”>
    <div id=”div1″></div>
    </form>
</body>
 
Related posts:
http://forums.asp.net/p/1247758/2303034.aspx
 
1.2        How to access a control by using JavaScript [top]
Reference the ClientID property (or UniqueID) of the control in the JavaScript.
protected void Page_Load(object sender, EventArgs e)
{
    Button btn= new Button();
    btn.ID = “btn5″;
    btn.Attributes.Add(“runat”, “server”);
    btn.Attributes.Add(“onclick”, “pop(‘” + btn.ClientID + “‘)”);
    btn.Text = “Test”;
    this.form1.Controls.Add(btn);
}
 
function pop(InputBoxID)
{
    var InputControl = document.getElementById(InputBoxID);
    alert(InputControl.value);
}
Or you can use the following method:
btn.Attributes.Add(“onclick”, “pop(this)”);
function pop(InputBox)
{
    alert(InputBox.value);
}
 
Related posts:
http://forums.asp.net/p/1239593/2260331.aspx#2260331
1.3        How to invoke a server-side function with JavaScript [top]
Firstly, you can drag a server button and put the server function into the button Click even, 
protected void Button1_Click(object sender, EventArgs e)
{
   FunctionName();
}
Secondly, you can call the server function at JavaScript by using the following code,
document.getElementById(“Button1″).click();
 
Related posts:
http://forums.asp.net/p/1242420/2274228.aspx
1.4       How to retrieve server side variables using JavaScript code [top]
 
<asp:HiddenField ID=”HiddenField1″ runat=”server” />   
public partial class LoginDemo : System.Web.UI.Page
{  
    private string str=”hello”;
    protected void Page_Load(object sender, EventArgs e)
    {
        HiddenField1.Value=str;
    }
}
Then you can access the control HiddenField1 using javascipt:
<script type=”text/JavaScript”>
Var tt=document.getElementByID(“HiddenField1”);
alert(tt.value);
</script>
  
Related posts:
http://forums.asp.net/p/1000655/1319119.aspx
1.5        How to assign a value to a hidden field using JavaScript in ASP.NET [top]
We can use JavaScript to set the value of a hidden control and get its value at the server after a post back.
<input id=”Hidden1″ type=”hidden” />
<script type=”text/JavaScript”>
var str=”hello”
document.getElementByID(“Hidden1”).value=str
</script>
protected void Page_Load(object sender, EventArgs e)
{
    string str=request["Hidden1"].ToString();
}
Related posts:
http://forums.asp.net/p/1262153/2362090.aspx
1.6        How to register the JavaScript function at Code-Behind [top]
Use ResterStartupScript
this.Page.ClientScript.RegisterStartupScript(this.GetType(),”alert”,”<script>alert(‘hello’);</script>”);
Use Literal control,
private void Button2_Click(object sender, System.EventArgs e)
{
    string str;
    str=”<script language=’JavaScript’>”; 
    str+=”selectRange()”;
     str+=”<script>”;
    Literal1.Text=str;
}
Related posts:
http://forums.asp.net/p/981603/1257057.aspx#1257057 
 
1.7        How to display images with a delay of five seconds [top]
With this script you can see clickable images rotating in real-time without requiring banner rotation software or page reloads/refreshes .You should see a new banner rotating every 5 seconds:
<%@ Page %>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<script runat=”server”>
</script>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head id=”Head1″ runat=”server”>
    <title>JavaScript</title>
    <script language=”javascript” type=”text/javascript”>
    var image=”";
    var banners=0;
    function loadbanners() {
   if (banners==1)
      {
         image=”images/AJAX.gif”;
      }
   if (banners==2)
      {
         image=”images/ASPDotNet.gif”;
      }
   if (banners==3)
      {
         image=” images/MSDN.gif”;
      }
      }
      function cycle()
      {
        if (++banners > 3)
        banners=1;
        loadbanners();
        document.getElementById(“banner1″).src =image;
        window.setTimeout(‘cycle();’,5000);
      }
    </script>
</head>
<body onload=”cycle();”>
    <form id=”form2″ runat=”server”>
    <div>
        <img alt=”" id=”banner1″ src=”images/start.png” />
   </div>
    </form>
</body>
</html>
Related posts:
http://forums.asp.net/p/1213103/2147140.aspx
1.8        How to get browser screen settings and apply it to page controls [top]
You can use the JavaScript, suppose the control type is <image>, see the code below:
<html>
<body>
<input onclick=”resizeImage()”/>
<img src=”http://www.microsoft.com/library/toolbar/3.0/images/banners/ms_masthead_ltr.gif”  id=”Img1″  />
<script language=”JavaScript”>
    var winWidth = 0;
    var winHeight = 0;
    function resizeImage(){
    var img=document.getElementById(“testImage”)
    if (window.innerWidth)
           winWidth = window.innerWidth;
     else if ((document.body) && (document.body.clientWidth))
           winWidth = document.body.clientWidth;
     if (window.innerHeight)
           winHeight = window.innerHeight;
     else if ((document.body) && (document.body.clientHeight))
           winHeight = document.body.clientHeight; 
     if (document.documentElement  && document.documentElement.clientHeight &&
                                          document.documentElement.clientWidth)
     {
         winHeight = document.documentElement.clientHeight;
         winWidth = document.documentElement.clientWidth;
     }
     img.width= winHeight;
     img.width= winWidth;
    }
</script>
</body>
</html>
Please remove the control style if it is present. 
Related posts:
http://forums.asp.net/p/1228180/2212987.aspx
1.9        How to clear the session when the user closes a window [top]
Use the code,
<script type=”text/javascript”>
function window.onbeforeunload()
{
    var xmlHttp;
    try
    {
        // Firefox, Opera 8.0+, Safari
        xmlHttp=new XMLHttpRequest();
    }
    catch (e)
    {
        // Internet Explorer
    try
    {
        xmlHttp=new ActiveXObject(“Msxml2.XMLHTTP”);
    }
    catch (e)
    {
        try
        {
            xmlHttp=new ActiveXObject(“Microsoft.XMLHTTP”);
        }
        catch (e)
        {
            alert(“Your browser does not support AJAX!”);
            return false;
        }
    }
    if(event.clientX>document.body.clientWidth&&event.clientY<0||event.altKey)
    {
        xmlhttp.open(“GET”,”exit.aspx”,false);
        xmlhttp.send();
    }
}
</script>
 
Related posts:
http://forums.asp.net/p/1237752/2255401.aspx
2.      Ways to pass data between pages
2.1        How to use cookies [top]
Create a page named page1.aspx, and then drag a button and a TextBox onto the page. Double click the button and then add the following code:
protected void Button1_Click(object sender, EventArgs e)
{
    HttpCookie cookie = new HttpCookie(“UserName”);
    cookie.Value = TextBox1.Text;
    cookie.Expires = DateTime.Now.AddDays(1);
    Response.Cookies.Add(cookie);
    Response.Redirect(“Page2.aspx”);
}
page1.aspx, 
<div>
     <asp:Button ID=”Button1″ runat=”server” onclick=”Button1_Click” Text=”Button” />
     <asp:TextBox ID=”TextBox1″ runat=”server”></asp:TextBox>
</div>
On page2.aspx, double click the form and put the following code in it:
protected void Page_Load(object sender, EventArgs e)
{
    if (Request.Cookies["UserName"] != null)
        Response.Write(Request.Cookies["UserName"].Value);
}
 
Related posts:
http://forums.asp.net/t/1223291.aspx
Asp.Net Cookies Overview
How to: Read a Cookie
How to: Delete a Cookie
ASP.NET State Management Overview
ASP.NET State Management Recommendations
2.2        How to use QueryString [top]
private void Button1_Click (object sender, System.EventArgs e)
{
    string url;
      url=”anotherwebform.aspx?name=” +
      TextBox1.Text + “&email=” + TextBox2.Text;
      Response.Redirect(url);
}
Destination web form
private void Page_Load (object sender, System.EventArgs e)
{
    Label1.Text=Request.QueryString["name"];
      Label2.Text=Request.QueryString["email"];
}
 
Related posts:
http://forums.asp.net/p/1223291/2191155.aspx
ASP.NET State Management Overview
ASP.NET State Management Recommendations
2.3        How to use Session [top]
private void Button1_Click(object sender, System.EventArgs e)
{
    //Drag TextBox1 and TextBox2 onto a web form
    Session["name"]=TextBox1.Text;
    Session["email"]=TextBox2.Text;
    Server.Transfer(“anotherwebform.aspx”);
}
Destination web form
private void Page_Load(object sender, System.EventArgs e)
{
    Label1.Text=Session["name"].ToString();
    Label2.Text=Session["email"].ToString();
    Session.Remove(“name”);
    Session.Remove(“email”);
}
Related posts:
http://forums.asp.net/p/1255625/2333723.aspx
How to: Read Values from Session State
How to: Save Values in Session State
HttpSessionState Class
ASP.NET State Management Overview
ASP.NET State Management Recommendations
2.4        How to use Context [top]
 
//Page1.aspx stores value in context before transferring
Context.Items(“UserName”) = txtName.Text;
Server.Transfer(“Page2.aspx”);
 
//Page2.aspx retrieves the value from Page1’s context
string sName;
sName = Context.Items(“UserName”).ToString;
Response.Write(“Your name is ” + sName);
Related posts:
http://forums.asp.net/t/1238286.aspx
HttpContext Class
ASP.NET State Management Overview
ASP.NET State Management Recommendations
2.5        How to use PreviousPage [top]
FirstForm.aspx
<asp:Button id=”buttonPassValue” runat=”server” Text=”Button” PostBackUrl=”~/SecondForm.aspx”>
</asp:Button>
SecondForm.aspx.cs
TextBox1.Text = Request.Form["TextBox1"].ToString();
Or SecondForm.aspx.cs
TextBox textBoxTemp = (TextBox) PreviousPage.FindControl(“TextBox1″);
TextBox1.Text = textBoxTemp.Text;
As you’ve noticed, this is a simple and clean implementation of passing values between pages.
Related posts:
http://forums.asp.net/p/1048041/1474374.aspx
Page.PreviousPage Property
How to: Pass Values Between ASP.NET Web Pages
2.6        How to use Submit Form [top]
page1.aspx,   
<%@ Page %>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<script runat=”server”>
</script>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head>
<script language=”javascript”>
    function CopyTextToHiddenField()
    {
        var textbox1Value = document.getElementById(“<%=TextBox1.ClientID%>”).value;
        document.forms[1].document.getElementById(“Hidden1″).value = textbox1Value;
    }
</script>
</head>
<body>
    <form id=”form1″ runat=”server”>
    <asp:TextBox ID=”TextBox1″ runat=”server”></asp:TextBox>
    </form>
    <form name=”SubmittedForm” action=”page2.aspx” method=”post”>
    <input id=”Submit1″ type=”submit” value=”submit” onclick=”CopyTextToHiddenField()” />
    <input name=”Hidden1″ type=”hidden” />
    </form>
</body>
</html>
page2.aspx,
<%@ Page %>
 
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
 
<script runat=”server”>
 
    protected void Page_Load(object sender, EventArgs e)
    {
        Response.Write(Request.Form["Hidden1"]);
    }
</script>
 
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head id=”Head1″ runat=”server”>
</head>
<body>
    <form id=”form1″ runat=”server”>
    <div>
    </div>
    </form>
</body>
</html>
 
Related posts:
http://forums.asp.net/p/1257184/2339923.aspx
2.7        How to use Server.Transfer [top]
page1.aspx,
<%@ Page %>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<script runat=”server”>
    protected void Button_Click(object sender, EventArgs e)
    {
        Server.Transfer(“page2.aspx”, true);
 
    }
</script>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head id=”Head1″ runat=”server”>
</head>
<body>
    <form id=”form1″ runat=”server”>
    <div>
        <asp:Button ID=”Button1″ runat=”server” Text=”Button” OnClick=”Button_Click” />
        <asp:TextBox ID=”TextBox1″ runat=”server”></asp:TextBox>
    </div>
    </form>
</body>
</html>
 
page2.aspx,
<%@ Page %>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<script runat=”server”>
    protected void Page_Load(object sender, EventArgs e)
    {
        Response.Write(Request.Form["TextBox1"]);
    }
</script>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head id=”Head1″ runat=”server”>
</head>
<body>
    <form id=”form1″ runat=”server”>
    <div>
       
    </div>
    </form>
</body>
</html>
 
Related posts:
http://forums.asp.net/p/1262144/2362078.aspx
http://msdn.microsoft.com/en-us/library/6c3yckfw.aspx
http://dotnetslackers.com/community/blogs/haissam/archive/2007/11/26/ways-to-pass-data-between-webforms.aspx
Cross-Page Posting in ASP.NET Web Pages
How to: Determine How ASP.NET Web Pages Were Invoked
3.      File Upload
3.1        How to upload a file [top]
if (FileUpLoad1.HasFile)
   FileUpLoad1.SaveAs(Server.MapPath(“upload”)+ “\\” + FileUpLoad1.FileName);
}
 
Related posts:
FileUpload Web Server Control OverviewFileUpload Class
3.2        How to upload multiple files at once [top]
Please check the following article, in the article, Haissam Abdul Malak will explain how to upload multiple files in an organized way using HtmlInputFile control.
Related posts:
http://forums.asp.net/t/1263738.aspx
http://aspalliance.com/1221_CodeSnip_Uploading_Multiple_Files_At_Once.all
3.3        Why upload fails when using an ASP.NET FileUpload control to upload large files [top]
For security reasons, ASP.NET is limited in terms of an uploaded file size. The default maximum file size is 4 MB but this can be changed by modifying the MaxRequestLength attribute of Machine.config’s <httpRuntime> element.
<httpRuntime executionTimeout=”240″ maxRequestLength=”20480″ />
 
Related posts:
http://forums.asp.net/t/1074332.aspx
http://forums.asp.net/p/1106754/1696069.aspx#1696069
3.4        How to upload an image files only [top]
See the code,
Fileupload.aspx:
<%@ Page AutoEventWireup=”true” CodeFile=”Fileupload.aspx.cs” Inherits=”FileuploadDemo” %>
<!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 runat=”server”>
    <title>Upload Image Demo</title>
</head>
<body>
    <form id=”form1″ runat=”server”>
    <div>
        <asp:Image ID=”Image1″ runat=”server” />
        <asp:FileUpload ID=”FileUpload1″ runat=”server” />
        <asp:Button ID=”btnSubmit” runat=”server” Text=”Submit” OnClick=”btnSubmit_Click” />
    </div>
    </form>
</body>
</html>
Fileupload.aspx.cs:
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
 
public partial class FileuploadDemo : System.Web.UI.Page
{
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        string fileFullname = this.FileUpload1.PostedFile.FileName;
        string dataName = DateTime.Now.ToString(“yyyy-MM-dd hh-mm-ss”);
        string fileName = fileFullname.Substring(fileFullname.LastIndexOf(“\\”) + 1);
        string type = fileFullname.Substring(fileFullname.LastIndexOf(“.”) + 1);
        if (FileUpload1.PostedFile.ContentType.ToUpper().IndexOf(“IMAGE”) > -1)
        {
            System.Drawing.Image img = System.Drawing.Image.FromStream(FileUpload1.PostedFile.InputStream);
            int Width = img.Width;
            int Height = img.Height;
 
            if (Width > 1000 || Height > 1000 || FileUpload1.PostedFile.ContentLength > 1024 * 1024 * 200)
            {
                this.ClientScript.RegisterStartupScript(this.GetType(), “Startup”,                       “<script language=’javascript’>alert(‘The image size is too large!’);</script>”);
            }
            else
            {
                if (type == “jpg” || type == “gif” || type == “bmp” || type == “JPG” || type == “GIF”)
                {
                    string ImagePath = “images/”;
                    string sPath = Server.MapPath(ImagePath) + dataName + fileName;
                    string imgPath = ImagePath + dataName + fileName;
                    this.FileUpload1.PostedFile.SaveAs(sPath);
                    this.ClientScript.RegisterStartupScript(this.GetType(),                           “Startup”, “<script language=’javascript’>alert(‘Success!’);</script>”);
                    this.Image1.ImageUrl = imgPath;
                    this.btnSubmit.Enabled = false;
                    this.btnSubmit.Text = “Success!”;
                    this.btnSubmit.Enabled = true;
 
                }
                else
                {
                    this.ClientScript.RegisterStartupScript(this.GetType(), “Startup”,                           “<script language=’javascript’>alert(‘File type is not right!’);</script>”);
                }
            }
        }
        else
        {
            this.ClientScript.RegisterStartupScript(this.GetType(), “Startup”,                    “<script language=’javascript’>alert(‘The uploaded file is not a image file!’);</script>”);
        }
    }
}
 
Related posts:
http://forums.asp.net/p/1051895/2171502.aspx
3.5        How to get a File Upload control work with an UpdatePanel [top]
The FileUpload control does not work with asynchronous post backs and therefore does not work from within an AJAX UpdatePanel.
The trick to make the FileUpload to work within an Ajax UpdatePanel is to setup a PostBackTrigger in the UpdatePanel control.
Demo code:
<asp:UpdatePanel ID=”UpdatePanel1″ runat=”server”>
<Triggers >
<asp:PostBackTrigger ControlID =”Button1″ />
</Triggers>
<ContentTemplate >
<asp:FileUpload ID =”fileupload1″ runat =”server” /><br />    
<asp:Button ID =”Button1″ runat =”server” Text =”Upload” OnClick=”Button1_Click” /><br />
<asp:Label ID =”Lable1″ runat =”server”  Text =”"></asp:Label>
<asp:LinkButton ID =”LinkButton1″ runat=”server” Text =”Click Here” OnClick=”LinkButton1_Click”></asp:LinkButton>
</ContentTemplate>
</asp:UpdatePanel>
 
Related posts:
http://forums.asp.net/p/1105208/1689084.aspx
4.      Calendar
4.1        How to change the culture settings for a Calendar [top]
In calendar.aspx.cs:
private void Page_Load(object sender, System.EventArgs e)
{
    System.Globalization.CultureInfo culture = System.Globalization.CultureInfo.CreateSpecificCulture(“ens”);
    System.Threading.Thread.CurrentThread.CurrentCulture = culture;     System.Threading.Thread.CurrentThread.CurrentUICulture = culture;
}
 
Related posts:
http://forums.asp.net/t/1133896.aspx
4.2        How to select multiple non-sequential dates at Code-Behind [top]
Invoke the member function ‘Add’ of the control’s SelectedDates collection. You can add dates in any sequence, because the collection will automatically arrange them in order for you.
protected void Calendar1_SelectionChanged(object sender, EventArgs e)
{
    Calendar1.SelectedDates.Clear();
    Calendar1.SelectedDates.Add(new DateTime(2008, 8, 1));
    Calendar1.SelectedDates.Add(new DateTime(2008, 8, 7));
    Calendar1.SelectedDates.Add(new DateTime(2008, 8, 15));   
}
 
Related posts:
http://forums.asp.net/t/1260917.aspx
4.3        How to disable some dates in Calendar control [top]
protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)
{
    string date=”02/01/2008″;
    DateTime dt = DateTime.Parse(date);
    if (e.Day.Date == dt)
        e.Day.IsSelectable = false;
}
 
Related posts:
http://forums.asp.net/t/1230073.aspx
How to: Customize Individual Days in a Calendar Web Server Control
4.4        How to extend Calendar control for Server-Side validation [top]
Refer to:
http://support.microsoft.com/default.aspx?scid=kb;en-us;310145 
4.5        How to set ToolTips and links in Calendar control’s DayRender event [top]
 
protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)
{
    e.Cell.Controls.Clear();
    HyperLink link = new HyperLink();
    link.Text = e.Day.Date.Day;
    link.ToolTip = “anything you want here!”;
    link.NavigateUrl = url;
    e.Cell.Controls.Add(link);
}
 
Related posts:
http://forums.asp.net/p/1036174/1800067.aspx
4.6        How to give some dates different appearances [top]
We can do this with the following code:
protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)
{
    if (e.Day.Date.Month == 2 && e.Day.Date.Day == 25)
    {
        e.Cell.BackColor = System.Drawing.Color.Yellow;
    }
    if (e.Day.Date.DayOfWeek == DayOfWeek.Friday || e.Day.Date.DayOfWeek == DayOfWeek.Saturday)
    {
 
        e.Cell.Controls.Clear();
        e.Cell.Text = “today isweekend”;
    }
}
 
Related posts:
http://forums.asp.net/p/1036174/1800067.aspx
How to: Customize Individual Days in a Calendar Web Server Control
How to: Format Calendar Web Server Control Elements Using Styles
5.      List controls
5.1        How to enable ASP.NET DropDownList with OptionGroup support [top]
We can override the function of DropDownList, and add the additional property for it.
Here are some good articles about it.
Refer to:
http://www.codeproject.com/KB/custom-controls/xlist.aspx 
http://www.codeproject.com/KB/custom-controls/DropDownListOptionGroup.aspx
5.2        How to disable an item in DropDownList [top]
<asp:DropDownList ID=”DropDownList1″ runat =”server” Width=”235px” AutoPostBack=”False”>
    <asp:ListItem>1</asp:ListItem>
    <asp:ListItem>2</asp:ListItem>
    <asp:ListItem>3</asp:ListItem>
    <asp:ListItem>4</asp:ListItem>
</asp:DropDownList>
protected void Page_Load(object sender, EventArgs e)
{
    DropDownList1.Attributes.Add(“onchange”, “change();”);
}
<script type =”text/javascript” >
      function change()
      {
         var dd=document.getElementById (‘<%=DropDownList1.ClientID %>’);
         var value=dd.options[dd.selectedIndex].value;
         if(value!=”2″) //supose you want to disable the item numbered 2
         {
            setTimeout(“__doPostBack(‘DropDownList1′,”)”, 0);
         }
       }
</script>
 
Related posts:
http://forums.asp.net/p/1041568/1451492.aspx 
5.3        How to hold the selected value for a DropDownList [top]
You should place your data binding code for the dropdownlist in the !page.Ispostback block.
the !postback block will ensure it will only be filled once during post backs.
if(!Page.IsPostBack)
{
    //bind template drop down here
}
 
Related posts:
http://forums.asp.net/p/1251081/2312321.aspx
6.      User control
6.1        How to add a new property to UserControl [top]
You can setup new properties inside the class definition of the user control at its .ascx.cs file.Example:
ascx file,
<%@ Control AutoEventWireup=”true” CodeFile=”WebUserControl.ascx.cs” Inherits=”WebUserControl” %>
<asp:Label ID=”Label1″ runat=”server” Text=”Label”></asp:Label>
<asp:Calendar ID=”Calendar1″ runat=”server”></asp:Calendar>
<asp:TextBox ID=”TextBox1″ runat=”server”></asp:TextBox>
ascx.cs file,
public partial class WebUserControl : System.Web.UI.UserControl
{
    String text2 = String.Empty;
    public String Text
    {
        get
        {
 
            return Label1 .Text ;
        }
        set
        {
            Label1 .Text  = value;
        }
    }
    public String Text2
    {
        get
        {
            return text2;
        }
        set
        {
            text2 = value;
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        TextBox1.Text = text2;
    }
}
aspx file
<%@ Register src=”WebUserControl.ascx” mce_src=”WebUserControl.ascx” TagName=”WebUserControl” TagPrefix=”uc1″ %>
<uc1:WebUserControl id=”WebUserControl1″ runat=”server” Text=”Hello world” Text2=”Hello world.”>
</uc1:WebUserControl>
 
Related posts:
http://forums.asp.net/t/349580.aspx
6.2        How to access a dynamically created UserControl [top]
You can use FindControl method to get a reference to the target child control of your user control and then use it just like any other controls.
Example:
UC.ascx,
<%@ Control ClassName=”UC” %>
<script runat=”server”>
</script>
<asp:TextBox ID=”txtName” runat=”server”></asp:TextBox>
Page.aspx:
<%@ Page %>
 
<%@ Register src=”UC.ascx” tagname=”UC” tagprefix=”uc1″ %>
 
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<script runat=”server”>
    protected void btnLoad_Click(object sender, EventArgs e)
    {
        UC uc = new UC();
        uc.LoadControl(“~/uc/UC.ascx”);
        uc.ID = “MyUC”;
        form1.Controls.Add(uc);
        (form1.FindControl(“MyUC”).FindControl(“txtName”) as TextBox).Text = “ASP.NET”;
    }
</script>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head runat=”server”>
    <title>User Control Demo</title>
</head>
<body>
    <form id=”form1″ runat=”server”>
    <div>
        <asp:Button ID=”btnLoad” runat=”server” Text=”Loading user control …”
            onclick=”btnLoad_Click” />
    </div>
    </form>
</body>
</html>
 
6.3        How to access a control inside a UserControl [top]
Assume there is a user control called UC and there is only a TextBox control inside it. Now drag this user control into a web page, you can use the following code to visit the TextBox control.
((TextBox)UC1.FindControl(“TextBox1″)).Text = “demo”;
To known the basic principle, please refer to INamingContainer:
http://msdn.microsoft.com/en-us/library/system.web.ui.inamingcontainer.aspx
7.      Dynamic controls
7.1        How to create a dynamic control [top]
We can create the dynamic control in the Page_Init() event or Page_Load() event,
protected void Page_Load(object sender, EventArgs e)
{
    TextBox dynamicTextBox = new TextBox();
    dynamicTextBox.ID = “DynamicTextBox”;
    dynamicTextBox.AutoPostBack = true;
    dynamicTextBox.Text = “InitData”;
    dynamicTextBox.TextChanged += new EventHandler(dynamicTextBox_TextChanged);
    this.Form.Controls.Add(dynamicTextBox);
}
void dynamicTextBox_TextChanged(object sender, EventArgs e)
{
    Response.Write(“hello”);
}
 
Related posts:
http://forums.asp.net/t/1152363.aspx
7.2        How to access a user entered value in a dynamic created TextBox control [top]
a.      Get the value from the form’s POST data. Here is the code:
if(Request.Form["dynamicTextBox"] != null)
    selectedValue = Request.Form["dynamicTextBox"].ToString();
b.      Get the value by finding the control at the webpage.
TextBox txt=this.form1.FindControl(“dynamicTextBox”) as TextBox;
See the whole demo code,
<%@ Page %>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<script runat=”server”>
    public string Res = string.Empty;
    protected void Page_Load(object sender, EventArgs e)
    {
        TextBox dynamicTextBox = new TextBox();
        dynamicTextBox.ID = “dynamicTextBox”;
        form1.Controls.Add(dynamicTextBox);
    }
    protected void btnForm_Click(object sender, EventArgs e)
    {
        lblMsg.Text += “<br /> Form way:”;
        if (Request.Form["dynamicTextBox"] != null)
            Res = Request.Form["dynamicTextBox"].ToString();
        lblMsg.Text += Res;
    }
    protected void btnFindControl_Click(object sender, EventArgs e)
    {
        lblMsg.Text += “<br /> FindControl way: “;
        TextBox dynamicTextBox = this.form1.FindControl(“dynamicTextBox”) as TextBox;
        Res = dynamicTextBox.Text;
        lblMsg.Text += Res;
    }
</script>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head runat=”server”>
    <title>Demo</title>
</head>
<body>
    <form id=”form1″ runat=”server”>
    <div>
        <asp:Label ID=”lblMsg” runat=”server” Text=”"></asp:Label>
        <asp:Button ID=”btnForm” runat=”server” Text=”Form Way” OnClick=”btnForm_Click” />
        <asp:Button ID=”btnFindControl” runat=”server” Text=”FindControl Way” OnClick=”btnFindControl_Click” />
    </div>
    </form>
</body>
</html>
 
Related posts:
http://forums.asp.net/p/1119972/1745762.aspx 
7.3        Dynamic controls accessed by JavaScript [top]
Reference the ClientID property (or UniqueID) of the control in the Javascript.
protected void Page_Load(object sender, EventArgs e)
{
    Button btn= new Button();
    btn.ID = “btn5″;
    btn.Attributes.Add(“runat”, “server”);
    btn.Attributes.Add(“onclick”, “pop(‘” + btn.ClientID + “‘)”);
    btn.Text = “Test”;
    this.form1.Controls.Add(btn);
}
function pop(InputBoxID)
{
   var InputControl = document.getElementById(InputBoxID);
   alert(InputControl.value);
}
Or,
Use the following method.
btn.Attributes.Add(“onclick”, “pop(this)”);
function pop(InputBox)
{
   alert(InputBox.value);
}
 
Related posts:
http://forums.asp.net/p/1239593/2260331.aspx#2260331
7.4        How to retain all added server controls dynamically after post back [top]
You should recreate these dynamic control at Page_load or Page_init() function everytime.
protected void Page_Load(object sender, EventArgs e)
{
    //recreate these dynamic control.
}
 
Related posts:
http://forums.asp.net/p/1242809/2280514.aspx 
7.5        Why dynamically created controls disappear after a post back [top]
The dynamic button must be re-created on each post back, so remove the if(!Page.IsPostBack). It’s probably better if you create the controls at the Page_Init event.
Related posts:
http://forums.asp.net/p/1080863/1598618.aspx
8.      Style
8.1        How to use with Code-Behind [top]
Label1.Attributes.Add(“style”, “background-color:Red”);
 
8.2        How to use with JavaScript [top]
document.getElementById(“Label1″).style.backgroundColor = “Red”;
 
8.3        How to remove a space [top]
Add the following code inside of the “head” tag,
<style type=”text/css”>
body
{
    padding: 0px;
    margin: 0px;
}
</style>
 
8.4        How to use with html [top]
<link href=”<%= CSS %>” rel=”stylesheet” type=”text/css” />
Note: CSS is valuable
Linked style sheet usually lives in <head> tag, but there is no need to worry if it is put inside <body> tag.  As well, <head> tag must have a runat=”server” attribute.
Related posts:
http://forums.asp.net/p/1197909/2076464.aspx 
8.5        How to set an image as Button’s background [top]
<input name=”Submit” type=”button” value=”" style=”border-style: none; background-color: Transparent; background-image: url(‘bg.png’); width: 68px; height: 20px; vertical-align: middle;” />
 
Related posts:
http://forums.asp.net/t/299555.aspx
8.6        How to color items in ListBox [top]
Demo code:
<style type=”text/css”>
.optred{background-color:red;}
.optblue{background-color:blue;}
</style>
protected void Page_PreRender(object sender, EventArgs e)
{
    bool flag=false;
    foreach (ListItem li in ListBox1.Items)
    {
        if (flag)
        {
            li.Attributes.Add(“class”, “optred”);
            flag = false;
        }
        else
        {
            li.Attributes.Add(“class”, “optblue”);
            flag = true;
        }
    }
}
 
Please refer to:
http://www.codeproject.com/KB/webforms/ColorListBox.aspx 
9.      Print
9.1        How to print a part of a web page with CSS [top]
CSS CODE:
<style media=”print”>
        .Noprint
        {
            display: none;
        }
        .Print
        {
            page-break-after: always;
        }
</style>
HTML CODE:
<div>
     I am not print;
</div>
<div>
     I will print;
</div>
Related posts:
http://forums.asp.net/t/981539.aspx
9.2        How to print a part of a web page with JavaScript (1) [top]
JavaScript CODE:
<script language=”JavaScript” type=”text/JavaScript”>
        function doPrint() {
        bdhtml=window.document.body.innerHTML;
        sprnstr=”<!–startprint–>”;
        eprnstr=”<!–endprint–>”;
        prnhtml=bdhtml.substr(bdhtml.indexOf(sprnstr)+17);
        prnhtml=prnhtml.substring(0,prnhtml.indexOf(eprnstr));
        window.document.body.innerHTML=prnhtml;
        window.print();
        }
</script>
HTML CODE:
<!–startprint–>
This area will print!
<!–endprint–>
<br />
I will not print?
<input id=”btnPrint” type=”button” value=”Print” onclick=”doPrint()” />
 
Related posts:
http://forums.asp.net/p/1234564/2256428.aspx
9.3        How to print a part of a web page with JavaScript (2) [top]
JavaScript CODE:
<script language=”javascript” type=”text/javascript”>
    function printdiv(divID)
    {
      var headstr = “<html><head><title></title></head><body>”;
      var footstr = “</body>”;
      var newstr = document.all.item(divID).innerHTML;
      var oldstr = document.body.innerHTML;
      document.body.innerHTML = headstr+newstr+footstr;
      window.print();
      document.body.innerHTML = oldstr;
      return false;
    }
</script>
HTML CODE:
<input name=”b_print” type=”button” onclick=”printdiv(‘divID’);” value=” Print ” />
<div id=”divID”>
<h1 style=”color:green”>
The Div content which you want to print</h1>
</div>
Related posts:
http://forums.asp.net/t/1263912.aspx
10.      Mail
10.1        What classes are needed to send e-mails in ASP.NET [top]
Class MailMessage and SmtpMail are used to send emails from an ASP.NET application. MailMessage and SmtpMail are from System.Web.Mail namespace of .NET Framework 1.1 Class Library. Also, you can use System.Net.Mail instead of System.Web.Mail if you have .NET Framework version 2.0 installed.
10.2        How to send emails by using System.Net.Mail [top]
CODE-BEHIND:
MailMessage message = new MailMessage();
message.From = new MailAddress(“fromusername@DomainName”);
message.To.Add(new MailAddress(“tousername@DomainName”));
message.CC.Add(new MailAddress(“ccusername@DomainName”));
message.Subject = “Subject”;
message.Body = “Content”;
SmtpClient client = new SmtpClient();
client.Send(message);
web.config:
<system.net>
    <mailSettings>
        <smtp from=”username@DomainName”>
            <network host=”SMTPServerName” port=”25″ userName=”username” password=”secret” defaultCredentials=”true” />
        </smtp>
    </mailSettings>
</system.net>
Related posts:
http://forums.asp.net/t/971802.aspx
10.3        How to configure a SMTP Server [top]
Taking the IIS as an example, please review the following links:
http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/56c94d38-b10f-4a1b-a1cd-3714387a042a.mspx?mfr=true
http://www.codeproject.com/KB/winsdk/ConfigServerSmtp.aspx
10.4        How to send an email with Gmail server [top]
Please read FAQ “How to send email by using System.Net.Mail?” first. Please note that you need to be aware of the following points while configuring the following settings:
  • SMTP server name
  • Port number
  • SSL authentication
Gmail SMTP server name is “smpt.gmail.com”;
Gmail port is 465, not the default port 25;
The SSL authentication should be set to true;
So the secret of sending mails successfully with Gmail is: port 465, server name “smtp.gmail.com” and SSL = true.
Related posts:
http://forums.asp.net/p/1167140/1944223.aspx
http://forums.asp.net/p/1234241/2235990.aspx
Share This: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Facebook
  • Live-MSN
  • TwitThis
  • LinkedIn
  • MySpace
  • email