ASP.NET Developer Notes

Ryan Garaygay's ASP.NET notes online

April 2008 - Posts

Control Visibility, ViewState and Security and Performance

It is not unheard of to come across a solution where use of asp:Placeholder and asp:Panel (or some other container) Visibility is employed to show/hide certain details from the user especially when when implementing "simple" Authorization/Permission features ("simple" since there are likely more complicated and/or better ways to handle it) Of course you could always implement declarative authorization features in ASP.NET but I believe it would cause the user to be redirected to the page identified as the login url and might not be applicable if you want to stay on the same page.

So if you simply perform checks in code you might have the following approach: Does User.Indentity.Name have permission to view this page? Yes/No? If yes, display contents of panel/placeholder, if no set their visibility to false.

Simple and might do the trick.

BUT never forget that although they are invisible, some values might be present in the viewstate (eg. values bound to gridview inside the panel/placeholder). Although viewstate might look cryptic, remember that it is just base 64 encoded string. And although you could have employ encrypted ViewState, it would still be not a good idea and you will have unnecessary overhead.

So just a quick note to self (and possibly others) that settings PlaceHolder/Panel visibility to false doesn't stop it from saving information in viewstate. Obvious to some but not to all so if you're guilty, better fix that code before someone gets to see something they shouldn't.

I'm also interested how best to implement this in code (not using ASP.NET built-in declarative authorization rules - ie. in web.config). HttpModule maybe? But note that I would want the resulting page to have the same look and feel (still use master page) rather than simply a text in the page (and nothing more) or worst an exception throw because user doesn't have view permission for example, nor redirected to a generic page. I'll try to explore this but someone who might have a good idea out there comes across this and shares his/her notes.

UPDATE: I just realized that aside from the security consideration in this case disabling viewstate when not need would improve performance significantly (depending on how items you have in your page makes use of viewstate - eg. disabling view state when hiding a gridview is significant) so adding Performance to the title as well.

Also, be cautious about disabling view state. It is used by control to persist information across postbacks so if you do disable them make sure you test your page well.

* Cross post from .NET Developer Notes on Control Visibility, ViewState and Security and Performance

Posted: Apr 29 2008, 08:25 PM by ryangaraygay | with no comments
Filed under:
Hand Editing Web.Config or not

I've come across a number of issues in the past where the cause of the issue is that someone hand edited the web.config and resulted to a not well formed XML (missing tags, unclosed quotes et al).

The recommended way of doing it is to minimize these issues is to use the ASP.NET Configuration Settings Dialog which is available to IIS (not sure if there is a stand alone executable for this). Here are simple steps to do it.

1. Open IIS

2. Right Click on target site/virtual directory and select Properties

 

3. The Properties dialog should show up. Select ASP.NET tab.

 

4. At the ASP.NET tab, you should see and click Edit Configuration. (if you're opening Properties of a website, you should also see an "Edit Global Configuration" button which corresponds to the machine wide web.config). Doing so should display the Configuration Settings Dialog

 

5. Make your modifications without fear of unclosed quotes whatsoever. You could likely still mess up some settings but I can assure you that it would be easier to do when you're manually hand editing the file.

 

Also note that when adding a web.config in Visual Studio (using Add New Item) you will get a comment somewhere at the top stating: 

<!--

    Note: As an alternative to hand editing this file you can use the

    web admin tool to configure settings for your application. Use

    the Website->Asp.Net Configuration option in Visual Studio.

    A full list of settings and comments can be found in

    machine.config.comments usually located in

    \Windows\Microsoft.Net\Framework\v2.x\Config

-->


The "Website->Asp.Net Configuration option in Visual Studio" mentioned are items in the toolbar and appears if you have the website project (or its files) open/selected (see image below)

This is also a recommended way of doing it for web site projects (not available in Web Application Projects).

Editing web.config is likely inevitable for development but as much as possible I would recommend not hand-edit them unless you (or others in the team) really have to (especially for those with not much experience with XML/HTML - it is trivial but could minimize some headaches)

UPDATE: I have updated the post title from "Hand Editing web.config, not" to "Hand Editing web.config or not" since it seems to make a big difference. I personally hand edit most if not all web.config I work with but this is merely an alternative based on experience where there are actually people out there guilty of messing the xml for a lot of reasons. Being an alternative it may or may not be best for all situations. Also, as a starting/budding developer it is sometimes (if not all the times) best to learn from mistakes so I am in no way against hand editing of files. However like gurus out there, be careful in doing as it would probably hurt more than missing something in HTML. Furthermore for those not yet confident enough to mess up with config manually this might be for you. Although again it's best to learn from mistakes if you can afford to do so since you will surely remember it more. :)

Posted: Apr 22 2008, 09:49 AM by ryangaraygay | with 7 comment(s)
Filed under:
ASP.NET Development Server cannot be accessed using non-localhost URL

An interesting point about the ASP.NET Development Server (previously named "Cassini") was raised hours ago by Alvin, a coworker of mine.

Forgive my ignorance but it seems that the said builtin server was constrained to be accessed only with localhost or 127.0.0.1 and would not work when using your IP (non loopback) nor machine name.

For IE you get : Internet Explorer cannot display the webpage

For Firefox : Unable to connect. Firefox can't establish a connection to the server at 192.168.1.xxx:PPPP (port number). The page title appears as Problem loading page 

Not much there but if you use Fiddler you would see that it is returning an HTTP Error 500 which refers to "Bad Gateway".

Somehow that tells me, it's not your code but something with the server or the machine.

Looking around, here's what I found:

Troubleshooting the ASP.NET Development Server

"Page Cannot Be Displayed" Error (502 Error)"

One possible cause of a 502 error or an error indicating that the page cannot be displayed is that the browser cannot resolve a URL containing "localhost" and a port number, such as http://localhost:8080/ExampleWebSite/Default.aspx. The ASP.NET Development Server works exclusively with localhost, and by default, uses a randomly selected port number for each request.

Furthermore, from Web Servers in Visual Web Developer link you will find:

If you cannot or do not want to use IIS as your Web server, you can still test your ASP.NET pages by using the ASP.NET Development Server. The ASP.NET Development Server, which is included with Visual Web Developer, is a Web server that runs locally on Windows operating systems, including Windows XP Home Edition. It is specifically built to serve, or run, ASP.NET Web pages under the local host scenario (browsing from the same computer as the Web server). In other words, the ASP.NET Development Server will serve pages to browser requests on the local computer. It will not serve pages to another computer. Additionally, it will not serve files that are outside of the application scope. The ASP.NET Development Server provides an efficient way to test pages locally before you publish the pages to a production server running IIS.

Although it may seem that accessing the site from the same machine but using your IP would seem like accessing it locally, it doesn't seem to be the case. Could be that technically it would go out of your local machine first then, find which machine the IP points to so effectively it's being accessed externally already (sorry can't explain better than that). What's interesting though is that accessing the machine results in the same behavior for some reason. Maybe someone can clear it up for us. Or maybe Cassini is really accessible this way and I'm just missing something.

One last thing, for those who wish to specify a specific port to use with ASP.NET Development Server here's a link : How to: Specify a Port for the ASP.NET Development Server

Might seem pretty obvious for some but for those of us who haven't cared about this before then hopefully something to add to our knowledge base (or if I'm missing something, at least something to spark your curiosity)

Issue with System.Transactions, SqlConnection and Timeout

Just recently, a post was made in Microsoft Forums regarding a bug/behavior of Committable Transactions and SqlConnection timeout. The same issue is evident for TransactionScope which was posted in 2006. Good thing there is a fix.

I have used TransactionScope a number of times including in one of my previous posts on Unit Testing (integration testing if you're particular about it) DataAccess so will focus on it for now (but as said, same issue with Committable Transaction class).

When you use TransactionScope and set the timeout to a certain value (not sure what is the default is not specified) and the timeout elapsed before the TX is completed, what happens is that actions made before the timeout is rolled back but after that, the connection unbinds itself from the transaction and if any action, places itself in autocommit mode (just like a regular connection) and if actions are made after the timeout (BUT still inside the TransactionScope, since these were performed in autocommit mode, they will not be rolled back).

Trying out the code below (or the downloadable sample project at the bottom) you will notice that in the "BASIC" example (which demonstrates the issue), you try to insert 5 rows, TransactionScope timeout more or less happens after the 2nd row, then after the TransactionScope, you check the database and there are 3 rows committed (instead of NONE). 

The good news is that MSFT found this issue too and had a fix for it a little after the release (probably after the System.Transaction or release of .NET 2.0) which involves a new keyword in the connection string : transaction binding defined in MSDN as :

Controls connection association with an enlisted System.Transactions transaction.

Possible values are:

Transaction Binding=Implicit Unbind;

Transaction Binding=Explicit Unbind;

Implicit Unbind causes the connection to detach from the transaction when it ends. After detaching, additional requests on the connection are performed in autocommit mode. The System.Transactions.Transaction.Current property is not checked when executing requests while the transaction is active. After the transaction has ended, additional requests are performed in autocommit mode.

Explicit Unbind causes the connection to remain attached to the transaction until the connection is closed or an explicit SqlConnection.TransactionEnlist(null) is called. An InvalidOperationException is thrown if Transaction.Current is not the enlisted transaction or if the enlisted transaction is not active.

So as you can see, the Implicit Unbind was the default behavior (which exibits the issue when the TX times out) and using explicit unbind will have the connection remain "bound" to the transaction instead of detaching itself and live it's life on it's own (and in on autocommit mode). Effectively, those actions performed after the Transaction Scope times out will also be uncommitted and we have a consistent behavior.

Here's my code while trying to verify the issue on my own (code taken from the forums with a few additions to help illustrate better). NOTE: Don't forget to modify the connection accordingly (as you see fit on your environment). Had this on VS2005, .NET 2.0 and the sample project is a console application.

    1 using System;

    2 using System.Data.SqlClient;

    3 using System.Transactions;

    4 using System.Threading;

    5 

    6 class Demo

    7 {

    8     static string connectionString;

    9 

   10     static void Main(string[] argv)

   11     {

   12         // ** Change connection strings accordingly

   13 

   14         Console.WriteLine("TransactionScope - BASIC");

   15         Console.WriteLine("============================");

   16         connectionString = @"server=.\sql2005;database=testDB;integrated security=SSPI";

   17         TransactionScopeTest();

   18 

   19         Console.WriteLine();

   20         Console.WriteLine("TransactionScope - IMPLICIT UNBIND");

   21         Console.WriteLine("============================");

   22         connectionString = @"server=.\sql2005;database=testDB;integrated security=SSPI;transaction binding=implicit Unbind;";

   23         TransactionScopeTest();

   24 

   25         Console.WriteLine();

   26         Console.WriteLine("TransactionScope - EXPLICIT UNBIND");

   27         Console.WriteLine("============================");

   28         connectionString = @"server=.\sql2005;database=testDB;integrated security=SSPI;transaction binding=explicit Unbind;";

   29         TransactionScopeTest();

   30 

   31         Console.ReadKey();

   32     }

   33 

   34     private static void TransactionScopeTest()

   35     {

   36         try

   37         {

   38             ReCreateTable();

   39             Console.WriteLine("Table recreated");

   40 

   41             try

   42             {

   43                 using (TransactionScope tx = new TransactionScope(TransactionScopeOption.RequiresNew, TimeSpan.FromSeconds(2)))

   44                 {

   45                     Console.WriteLine("Transaction started lasting 2 seconds");

   46                     using (SqlConnection con = new SqlConnection(connectionString)) // connection string is set in main method (see examples)

   47                     {

   48                         con.Open();

   49                         Console.WriteLine("Server is {0}", con.ServerVersion);

   50                         Console.WriteLine("Clr is {0}", Environment.Version);

   51 

   52                         for (int i = 0; i < 5; i++)

   53                         {

   54                             using (SqlCommand cmd = con.CreateCommand())

   55                             {

   56                                 cmd.CommandText = "insert into TXTEST values ( " + i + " )";

   57                                 cmd.ExecuteNonQuery();

   58                                 Console.WriteLine("Row inserted");

   59                             }

   60 

   61                             Thread.Sleep(TimeSpan.FromSeconds(1));

   62                         }

   63 

   64                         Console.WriteLine("Committing... now we get the timeout (sort of)");

   65 

   66                         tx.Complete();

   67                     }

   68                 }

   69             }

   70 

   71             catch (Exception e)

   72             {

   73                 Console.WriteLine(e.Message);

   74             }

   75 

   76             Console.WriteLine("Table contains {0} rows!!!", CountTable());

   77             DropTable();

   78         }

   79 

   80         catch (Exception e)

   81         {

   82             Console.WriteLine("Unexpected error:");

   83             Console.WriteLine(e.ToString());

   84         }

   85     }

   86 

   87     static void ReCreateTable()

   88     {

   89         try

   90         {

   91             DropTable();

   92         }

   93 

   94         catch (Exception) { }

   95 

   96         using (SqlConnection con = new SqlConnection(connectionString)) // connection string is set in main method (see examples)

   97         {

   98             con.Open();

   99             using (SqlCommand cmd = new SqlCommand("create table TXTEST ( F1 int )", con))

  100                 cmd.ExecuteNonQuery();

  101         }

  102     }

  103 

  104     static int CountTable()

  105     {

  106         using (SqlConnection con = new SqlConnection(connectionString)) // connection string is set in main method (see examples)

  107         {

  108             con.Open();

  109             using (SqlCommand cmd = new SqlCommand("select count(*) from TXTEST", con))

  110                 return (int)cmd.ExecuteScalar();

  111         }

  112     }

  113 

  114     static void DropTable()

  115     {

  116         using (SqlConnection con = new SqlConnection(connectionString)) // connection string is set in main method (see examples)

  117         {

  118             con.Open();

  119             using (SqlCommand cmd = new SqlCommand("drop table TXTEST", con))

  120                 cmd.ExecuteNonQuery();

  121         }

  122     }

  123 }

Download Demo - TransactionTimeoutIssue.zip (5.05 kb)

The sample project also contains another class for illustrating the issue with Committable Transaction. Just exclude the TransactionScope class and uncomment the Main method in CommittableTransactionDemo.cs. 

Please feel free to drop me message if I'm missing something or if there's any issues with the download. :D

More Information:

MSDN - Implementing an Implicit Transaction with TransactionScope 

MSDN - ConnectionString

Posted: Apr 14 2008, 08:02 AM by ryangaraygay | with 4 comment(s)
Filed under:
More Posts