April 2007 - Posts

I kindly invite you to check out my new article Extending the DataList Functionality at dotnetslackers.com. Your comments and ratings are appreciated.

Best Regards,

HC

Posted by haissam | with no comments

If you tried to close a window using javascript window.close() method in IE7, and as you may noticed a message will prompt "The Webpage you are viewing is trying to close the window. Do you want to close this window".

Because of the security enhancements in IE7, you can't close a window unless it is opened by a script. so the walkaround will be to let the browser thinks that this page is opened using a script then closing the window. below is the implementation.

1- Create a javascript function which will be called to close the window

<script language=javascript>

function CloseWindow()

{

window.open('','_self','');

window.close();

}

</script>

the code in bold is used to open a window in this case it's not defined into the current window. in this way, we let the browser thinks that the current window is opened using javascript, so when the window.close() is executed it will close it without the message being displayed.

Now you can try it by adding the below HTML code

<a href="" onclick="CloseWindow();">Testing Close Window</a>

Hope this post will help you.

Best Regards,

HC

 

Posted by haissam | 51 comment(s)

While working on forums, i have seen a lot of questions about converting C# code to VB.NET and vice versa. So i thought to share tools which will help you throughout your process

Convert To VB.NET

Convert To C#

Telerik Code Converter

Best Regards,

HC

 

Posted by haissam | 2 comment(s)

If you want a textbox to only allow its content to be a string matches any alphanumeric string with spaces. You could use the RegularExpressionValidator Control, set its ControlToValidate property to the TextBoxID, and set its ValidationExpression property to ^[A-Za-z0-9,\s]+$

HTML CODE

<asp:RegularExpressionValidator id="RegularExpressionValidator1" style='Z-INDEX: 109; LEFT: 192px; POSITION: absolute; TOP: 96px'
    runat="server" ErrorMessage="RegularExpressionValidator" ValidationExpression="^[A-Za-z0-9,\s]+$" ControlToValidate="TextBox1"></asp:RegularExpressionValidator>

if you don't want to allow a space, you should change the validationexpression property to ^[a-zA-Z0-9]+$

I have found a good reference for regular expressions, check out the below link

Regular Expressions

Best Regards, 

HC

 

Posted by haissam | with no comments

In this blog post, we will delete a node from an xml file based on its specified id attribute. The code below is written in C#

Xml File

<?xml version="1.0" encoding="utf-8"?>
<Document>
  <List id="1"></List>
  <List id="2"></List>
  <List id="3"></List>
  <List id="4"></List>
  <List id="5"></List>
  <List id="6"></List>
  <List id="7"></List>
</Document>

Code Behind:

  // Save the Xml File Path in a variable
   string xmlFilePath = Server.MapPath("~") + "/text.xml";

   // Create an instance of the XmlDocument
   XmlDocument mydoc = new XmlDocument();
   
   // Load the Xml File
   mydoc.Load(xmlFilePath);
   
   // Select Root Element
   XmlNode rootNode = mydoc.SelectSingleNode("Document");

   // Delete Single Node based on specific Attribute
   XmlNode mynode = mydoc.SelectSingleNode("Document/List[@id='1']");
   
   // Delete the Node
   rootNode.RemoveChild(mynode);

   // Save the Xml File Back
   mydoc.Save(xmlFilePath);

Best Regards,

HC

 

 

 

Posted by haissam | 1 comment(s)

In this blog post, I will show you how to navigate the XML file and get all a list of nodes in order to access their attributes.

Text.xml

Below is a XML file used in this example


 <?xml version="1.0" encoding="utf-8" ?>
<Document>
<List id="1"></List>
<List id="2"></List>
<List id="3"></List>
<List id="4"></List>
<List id="5"></List>
<List id="6"></List>
<List id="7"></List>
</Document>

C# Code

   // Create a instance of XmlDocument Object
   XmlDocument mydoc = new XmlDocument();

   // Get the XML file path
   string xmlFilePath = Server.MapPath("~") + "/text.xml";

   // Load the XML File
   mydoc.Load(xmlFilePath);
   
   // Use the SelectNodes method to get a nodelist of the specified XPATH
   XmlNodeList nodelist = mydoc.SelectNodes("Document/List");

   // Loop through the nodelist
   for(int i=0;i<nodelist.Count;i++)
   {

    // Set for each element in the nodelist to XmlNode
    XmlNode node = nodelist[i];

    // Get the node's attributes
    XmlAttributeCollection attCol = node.Attributes;

    // Print them for testing
    Response.Write(attCol[0].Value + "<br/>");
   }

Do not forget to import System.Xml namespace. The above code is commented to help you out understanding the steps taken

using System.Xml;

Best Regards,

HC

 

Posted by haissam | 1 comment(s)

In this blog post, i will show you a working example of how to open a popup window, do some processing and send the information back to the parent window.

First create a webform, in this example it's called WebForm1.aspx containing a textbox (txtPopResult). On it's page_load event, we will create an arraylist holding values from 0 to 9, save it in a session variable, and finally opening Popup.aspx in new window.

WebForm1.aspx

   private void Page_Load(object sender, System.EventArgs e)
  {
   // Create new instance of ArrayList object
   ArrayList al = new ArrayList();

   // loop to add values from 0 till 9 in the arraylist
   for(int i=0;i<10;i++)
   {
    al.Add(i);
   }

   // Save it in a Session variable
   Session["Array"] = al;

   // Open Popup window with a specified width and height.
LINE1:   Page.RegisterStartupScript("openpopup","<script language=javascript>window.open('Popup.aspx','test','height=200px;width=300px');</script>");
  }

Now the popup window will open, it contains a dropdownlist to hold the values of the Arraylist saved in the session variable. After the user selected an item from the dropdownlist, it will be saved inside the textbox (txtPopResult) in the parent window and it will be closed. To implement this functionality, we will add code to page_load event to fill the dropdownlist with the arraylist values. and we will handle the SelectionChanged of the dropdownlist.

Popup.aspx


    private void Page_Load(object sender, System.EventArgs e)
  {
   // Get the Array list from the session variable
   ArrayList al = (ArrayList)Session["Array"];
   
   // loop through arraylist items and add them to the dropdownlist.
   for(int i=0;i<al.Count;i++)
   {
    DropDownList1.Items.Add(i.ToString());
   }
}

 private void DropDownList1_SelectedIndexChanged(object sender, System.EventArgs e)
  {
   string selectedValue = DropDownList1.SelectedItem.Text;
LINE2:   Page.RegisterStartupScript("close","<script language=javascript>window.opener.document.getElementById('txtPopResult').value = '"+selectedValue+"';self.close();</script>");
  }

The code above in bold will set the textbox control in the parent window to the value selected by the user from the dropdownlist

N.B:  Line numbers are added for reference use only throughout this example.

 For ASP.NET 2.0 you should modify Line2 by the below code

 Page.ClientScript.RegisterStartupScript(this.GetType(),"close","<script language=javascript>window.opener.document.getElementById('txtPopResult').value = '"+selectedValue+"';self.close();</script>");

and Line1 by the below code

Page.ClientScript.RegisterStartupScript(this.GetType(),"openpopup","<script language=javascript>window.open('Popup.aspx','test','height=200px;width=300px');</script>");

Hope it helps you.

Best Regards,

HC

Posted by haissam | 44 comment(s)

A lot of questions are being asked about downloading a file from the web server to the client in ASP.NET. I have updated this blog post due to the high number of view & comments. You will realize i added a function called "ReturnExtension" which will return the proper content type and set it to the Response.ContentType property. Almost well known file types are supported.

C# Code

   // Get the physical Path of the file(test.doc)
   string filepath = Server.MapPath("test.doc");

   // Create New instance of FileInfo class to get the properties of the file being downloaded
   FileInfo file = new FileInfo(filepath);
 
   // Checking if file exists
   if (file.Exists)
   {
    // Clear the content of the response
    Response.ClearContent();
   
    // LINE1: Add the file name and attachment, which will force the open/cance/save dialog to show, to the header
    Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
   
    // Add the file size into the response header
    Response.AddHeader("Content-Length", file.Length.ToString());

    // Set the ContentType
    Response.ContentType = ReturnExtension(file.Extension.ToLower());

    // Write the file into the response (TransmitFile is for ASP.NET 2.0. In ASP.NET 1.1 you have to use WriteFile instead)
    Response.TransmitFile(file.FullName);

    // End the response
    Response.End();
   }

private string ReturnExtension(string fileExtension)
{
     switch (fileExtension)
            {
                case ".htm":
                case ".html":
                case ".log":
                    return "text/HTML";
                case ".txt":
                    return "text/plain";
                case ".doc":
                    return "application/ms-word";
                case ".tiff":
                case ".tif":
                    return "image/tiff";
                case ".asf":
                    return "video/x-ms-asf";
                case ".avi":
                    return "video/avi";
                case ".zip":
                    return "application/zip";
                case ".xls":
                case ".csv":
                    return "application/vnd.ms-excel";
                case ".gif":
                    return "image/gif";
                case ".jpg":
                case "jpeg":
                    return "image/jpeg";
                case ".bmp":
                    return "image/bmp";
                case ".wav":
                    return "audio/wav";
                case ".mp3":
                    return "audio/mpeg3";
                case ".mpg":
                case "mpeg":
                    return "video/mpeg";
                case ".rtf":
                    return "application/rtf";
                case ".asp":
                    return "text/asp";
                case ".pdf":
                    return "application/pdf";
                case ".fdf":
                    return "application/vnd.fdf";
                case ".ppt":
                    return "application/mspowerpoint";
                case ".dwg":
                    return "image/vnd.dwg";
                case ".msg":
                    return "application/msoutlook";
                case ".xml":
                case ".sdxl":
                    return "application/xml";
                case ".xdp":
                    return "application/vnd.adobe.xdp+xml";
                default:
                    return "application/octet-stream";
}

N.B:  If you want to bypass the Open/Save/Cancel dialog you just need to replace LINE1 by the below code

Response.AddHeader("Content-Disposition", "inline; filename=" + file.Name);

Response.TransmitFile VS Response.WriteFile:
 1- TransmitFile: This method sends the file to the client without loading it to the Application memory on the server. It is the ideal way to use it if the file size being download is large.
 2- WriteFile: This method loads the file being download to the server's memory before sending it to the client. If the file size is large, you might the ASPNET worker process might get restarted.

Hope this helps,

Posted by haissam | 54 comment(s)
The leading UI suite for ASP.NET - Telerik radControls
Outstanding performance. Full ASP.NET AJAX support. Nearly codeless development.