Friday, July 11, 2014

Server.MapPath

Server.MapPath specifies the relative or virtual path to map to a physical directory.
  • Server.MapPath(".")1 returns the current physical directory of the file (e.g. aspx) being executed
  • Server.MapPath("..") returns the parent directory
  • Server.MapPath("~") returns the physical path to the root of the application
  • Server.MapPath("/") returns the physical path to the root of the domain name (is not necessarily the same as the root of the application)
An example:
Let's say you pointed a web site application (http://www.example.com/) to
C:\Inetpub\wwwroot
and installed your shop application (sub web as virtual directory in IIS, marked as application) in
D:\WebApps\shop
For example, if you call Server.MapPath in following request:
http://www.example.com/shop/products/GetProduct.aspx?id=2342
then:
  • Server.MapPath(".")1 returns D:\WebApps\shop\products
  • Server.MapPath("..") returns D:\WebApps\shop
  • Server.MapPath("~") returns D:\WebApps\shop
  • Server.MapPath("/") returns C:\Inetpub\wwwroot
  • Server.MapPath("/shop") returns D:\WebApps\shop
If Path starts with either a forward (/) or backward slash (\), the MapPath method returns a path as if Path were a full, virtual path.
If Path doesn't start with a slash, the MapPath method returns a path relative to the directory of the request being processed.
Note: in C#, @ is the verbatim literal string operator meaning that the string should be used "as is" and not be processed for escape sequences.
Footnotes
  1. Server.MapPath(null) and Server.MapPath("") will produce this effect too.

Friday, July 26, 2013

Find and Replace Text in Text / HTML Files

public void ReplaceInFile(string filePath,string replaceText,string findText)
{
    try
    {
         System.IO.StreamReader objReader;
         objReader= new System.IO.StreamReader(filePath);
         string content= objReader.ReadToEnd();
         objReader.Close();
         content= Regex.Replace(content,findText,replaceText);
         StreamWriter writer= new StreamWriter(filePath);
         writer.Write(content);
         writer.Close();
    }
     catch(IOException iexp)
{
   throw;
}

Tuesday, January 8, 2013

Execute JavaScript function from ASP.NET codebehind


Calling a JavaScript function from codebehind is quiet simple, yet it confuses a lot of developers. Here's how to do it. Declare a JavaScript function in your code as shown below:
JavaScript
<head runat="server">
    <title>Call JavaScript From CodeBehind</title>
    <script type="text/javascript">
        function alertMe() {
            alert('Hello');
        }
    </script>
</head>
In order to call it from code behind, use the following code in your Page_Load
C#
protected void Page_Load(object sender, EventArgs e)
{
    if (!ClientScript.IsStartupScriptRegistered("alert"))
    {
        Page.ClientScript.RegisterStartupScript(this.GetType(),
            "alert", "alertMe();", true);
    }
}

Tuesday, December 4, 2012

Select DropDownList programmatically


Set by Text:
 DDL.SelectedIndex = DDL.Items.IndexOf(DDL.Items.FindByText("PassedValue"));
Set by Value: 
DDL.SelectedIndex = DDL.Items.IndexOf(DDL.Items.FindByValue("PassedValue"));

Monday, July 9, 2012

Get the ConnectionString from the Web.Config file with only one line of code (C#)


Get the ConnectionString from the Web.Config file with only one line of code (C#):
var conString = ConfigurationManager.ConnectionStrings["LocalSqlServer"];
string strConnString = conString.ConnectionString;

Tuesday, May 8, 2012

Getting All Controls On The ASP.NET Page


While working with ASP.NET, from time to time, I need to change some parameter that is common to all controls of on a page. An example of such operation might be setting ReadOnly property for all TextBox controls etc.
Below is a sample method code I use to get a flattened hierarchy of controls on a page:
public static Control[] FlattenHierachy(Control root)
{
    List<Control> list = new List<Control>();
    list.Add(root);
    if (root.HasControls())
    {
        foreach (Control control in root.Controls)
        {
            list.AddRange(FlattenHierachy(control));
        }
    }
    return list.ToArray();
}
As you can see, it is pretty simple. The method recursively traverses control hierarchy and collects each control it finds on its way to a collection which is finally returned to the caller in a form of an array.
As mentioned above we can use this method to set the ReadOnly property of all TextBox-es on the page. To do this, a code similar to the one below can be used:
private void MakeTextBoxesReadOnly()
{
    Control[] allControls = FlattenHierachy(Page);
    foreach (Control control in allControls)
    {
        TextBox textBox = control as TextBox;
        if (textBox != null)
        {
            textBox.ReadOnly = true;
        }
    }
}
Using a combination of the above outlined methods it is easy to implement a kind of ReadOnlyMode page filter. Just identify what controls need to be ReadOnly and how to make them so (RadioButton for example doesn't have a ReadOnly property). When you know how and what you want to make ReadOnly, just override Page's OnPreRender method by adding a call a MakeTextBoxesReadOnly method (or whatever method you create).
Of course all of this is possible thanks to the great ASP.NET control model which is one of the things that I really like about ASP.NET.
Source: http://vaultofthoughts.net