Pages

Tuesday, October 28, 2008

.NET Reflector: Soup to Nuts by Andrew Clarke

I found this great post last week on simple-talk and I decided to repost it here on my blog. Happy Learning!

Andrew Clarke

.NET Reflector: Soup to Nuts

22 October 2008

by Andrew Clarke

Nobody could  accuse .NET Reflector of being over-documented. The information is around, but has never, up until now, been pulled together into one place.  We decided to try to make a start! This article supplements the demonstration video by Jason Crease, which comprehensively covers the basics of how to use .NET Reflector, and which should be seen first if you are new to NET Reflector.

NET Reflector has a special place in the pantheon of NET Development tools. It was first written by Lutz Roeder when the .NET Framework was still in beta, and since then has developed alongside it. So ubiquitous has it become that .NET Developers use its' name as a verb, as in 'let's reflector it'. What they mean is to browse and investigate the assemblies that comprise the code with a tool that is capable of showing what's there, and how classes, methods, or entire assemblies relate to each other, within the context of the application.

Why use .NET Reflector?

NET Reflector gives you the means to inspect, analyze, and browse the contents of a .NET component, such as an assembly. It will show you the metadata, IL instructions, resources and XML documentation. This tool can disassemble the instructions into source code in a variety of .NET languages, and translates the other binary information into an intelligible form. It does this through a process called 'reflection', which retrieves information about the various classes, methods, and properties included in a particular assembly (hence the name of the tool).

Most likely, you'll need .NET Reflector to track down performance problems and bugs. It is great for browsing classes, and maintaining, or becoming familiar with, code bases. Some of its features include:

  • An Analyzer option, which can be used to find assembly dependencies, and even windows DLL dependencies.
  • A call tree and inheritance-browser, which will pick up documentation or comments, stored in the xml files that are used to drive Intellisense inside Visual Studio. It will then display this information alongside the associated assemblies.
  • Ability to cross-navigate related documentation (xmldoc), searching for specific types, members and references.
  • Ability to convert your source between languages, such as C# and VB!

All sorts of questions crop up during development that can be answered with .NET Reflector:

  • What line of code is producing that error message?
  • What uses a particular piece of code, and what code does it, in turn, use?
  • How does a class, method, or entire assembly fit into your application?
  • What are the differences between two versions of the same assembly?
  • What features of the API of some legacy code can you use?
  • How do the various parts of your system interact with each other?

When you're working on a large team-based project, .NET Reflector is often the quickest way of getting a clear insight into how the application is working and where the bugs and weaknesses are. There is a great difference between knowing the public interface of a module and actually seeing what the code does.

Once .NET Reflector is combined with add-ins, it can become a tool to facilitate testing and make team-working more effective. There have been many occasions when .NET Reflector has assisted in the recovery of source code after it has been lost.

What is in a .NET Assembly?

Essentially, .NET Reflector allows you to 'see' what is in a .NET assembly.

A .NET language compiler will produce binary CIL (MSIL) code, and any resources that are required, in a file called an 'assembly'. The binary CIL code is written for a theoretical stack-based processor, to make it easy to run assemblies securely on different processors, in any environment supporting the .NET framework.

Then, a just-in-time (JIT) compiler will compile this abstracted, language-independent binary code, and optimise it into actual machine 'native' code for the target processor, and compile all the resources used. The .NET Common Language Runtime (CLR) supplies at least one JIT compiler for every NET-supported computer architecture, so the same set of CIL can be JIT-compiled and run on different architectures.

The CIL includes instructions for loading, storing, initializing, and calling methods on objects, as well as instructions for arithmetic and logical operations, control flow, direct memory access, exception handling, and other operations. It is designed to support polymorphism, inheritance, abstract types, and so on. When a high level language, such as C#, compiles code, it converts it to CIL. The process is reversible but because it is possible for two different high-level syntaxes to produce the same CIL, it may not be exactly the same as the original code.

As well as producing CIL, a .NET compiler will also produce metadata. This will contain everything needed for runtime, sufficient for the code to describe itself during execution without needing type libraries or the Interface Definition Language (IDL), and allowing JIT compilation, linking and introspection to work.

All the classes and class members that are defined in the assembly, as well as the external classes and class members called from the assembly, are described in the metadata, as are all the class methods. This includes details of its parameters, the return type, and the assembly in which it belongs. When the CLR executes CIL, it checks that the metadata of the called method matches that of the calling method. This metadata is used by the process of reflection, and is read by ..NET Reflector.

As well as the metadata, the assembly will also contain any required resources such as attributes, custom attributes, images and strings, and will also contain security information. You can browse this information from within reflector, as shown in Figure 1:

Figure 1: .NET Reflector displaying string resources

The whole assembly is put in an extended version of the portable executable (PE) file, used for executables, object code, and DLLs, and which enables the operating system to recognize common language runtime images. The PE file has only one import – mscoree.dll – which then loads the CLR Header and Data sections, and runs the assembly's just-in-time (JIT) compiler. The PE header's data directory contains a .NET directory entry, which points to a new header in the file containing everything the operating system needs to run it.

.NET Reflector, ILASM and ILDASM

Microsoft supplies two tools for investigating assemblies:

  1. ILASM, the Microsoft IL Assembler. It will take an ASCIII assembly language source-code file, and produce binary IL (MSIL) code. It adds in all the specified resources to create the assembly.
  2. ILDASM, the .NET disassembler. This is part of the .NET framework, and works the other way round. It will produce an 'assembly' file from an IL file. This assembly file is very much like a traditional Assembly source code file.

They are designed to be complementary, so that the output of one can go into the other to produce an identical file to the original.

The ILASM and ILDASM tools are useful, but not sufficient by themselves. Unfortunately, ILDASM is best only with CLI assembly sections, whereas EXE files are in PE format, which ILDASM may not extract correctly. The tool will show method signatures and member variables, but the code will be in .NET byte code.

To be able to extract everything you want from a NET assembly, in the language that was used originally to create the assembly, you will need .NET Reflector. This will also allow you to browse and inspect the other resources in the assembly, and even the XML documentation used by the IDE that created the assembly.

.NET Reflector, as we've said, uses 'Reflection' to do its work. Reflection is used to retrieve information about the various classes, methods, and properties included in a particular assembly. Reflection has to determine the interface, structure, enumeration, or delegate of a type at runtime. This process can be used to examine any .NET code, whether a single class or an entire assembly, and .NET Reflector uses this process to make sense of the contents of an assembly.

Reflector cannot view itself.  It needs to use reflection but, because .NET Reflector needs to work with all versions of the .NET Framework, it uses its own assembly loading infrastructure, which does not rely on the Reflection API. This allows .NET Reflector to load .NET Framework 2.0 assemblies without having the .NET Framework 2.0 installed. However, it also makes it difficult for anyone trying to explore how .NET Reflector works!

Installing, Registering and Launching .NET Reflector

.NET Reflector was written by Lutz Roeder, and has evolved over the entire life of the .NET Framework. It was first released in October 2000 running on .NET Framework 1.0 Beta. It has been updated continuously to work with each new release of the framework and is now on Version 5. This current version supports query expressions and other concepts introduced in C# 3.5 but only if you select ".NET 3.5" as the optimisation within the menu (under View |Options | Disassembler | Optimization). Along the way, a number of additions have been made, on request, sometimes for very general requirements, but occasionally for supporting special uses.

Lutz provided licenses only to users who register their names and email addresses. Registration was, and remains, free, but the software was never open-source or in the public domain. The new owners, Red Gate, will continue with this policy.

The application comes as a zipped package without an installer. It consists of .NET Reflector, the configuration file, license file and readme file.

Reflector can be launched, unregistered, just by clicking on the file in Explorer. However, there are many advantages to registering it with the Windows Shell.

You can register Reflector simply by issuing the following from the command line:

Reflector.exe /register

Once Reflector is integrated into the Windows shell, you can simply right-click on any DLL to open and browse it using Reflector, as shown in figure 2:

Figure 2: Immediately you've registered the program, life becomes easier (Note the context menu)

You can unregister Reflector by issuing:

Reflector.exe /unregister

As discussed, once registered, you'll generally launch Reflector just by clicking on the file in Explorer. However, if you are using reflector as a tool for several projects you may want to invoke it from the command line, using a particular configuration file (more on this later) for each project:

Reflector.exe  /configuration:<filename>

Or, to specify the assembly you wish to examine:

Reflector  <assembly>

This syntax is used by the operating system to display assemblies on startup of .NET Reflector once .NET Reflector is registered.

A Quick Spin through .NET Reflector

The following sections provide a simple example of the "disassembling" power of Reflector, followed by a brief tour of some of the useful features that are enabled once you register the tool with the operating system.

Disassembling Hello World

We can create the simplest possible program, and assemble it:

Figure 3: Assembler source code for  Hello World

And, at the command-line, execute:

C:\WINNT\Microsoft.NET\Framework\v2.0.50727\ilasm.exe helloWorld.il

Run the program:

HelloWorld.exe

You can then do one of the following…

  • Drag and drop it into Reflector
  • Use 'File-> Open' in Reflector (or Ctrl O)
  • Use the following URI (from Notepad, for example):
    code ://HelloWorld:1.0.0.1/<Module>/main()
  • Pop the above URI in your browser (if you ran Reflector.exe /register)
  • Run reflector from the command line

And this is what you'd see…

Figure 4: Hello World in Reflector, with disassembler window set to IL

Notice that the disassembly is not perfect, because some symbolic information is always lost in the original compilation.

Ever wondered how what the PowerShell 'Hello world' looks like?

Figure 5: PowerShell Hello world!

You can right-click any type or Assembly, or press Ctrl-R, to see what the class depends on, and what is exposed by, instantiated by, and assigned by the class.

Figure 6: The analyser looking at class dependencies

Maintaining Assembly lists

When you launch Reflector for the first time, you can choose a default set of assemblies. With .NET Reflector, you can create the groups of assemblies that you are interested in, and open/browse them as a set. The list of assemblies is stored in the Reflector configuration file, Reflector.cfg, and will be loaded next time you open the program. Reflector allows you to create as many assembly lists as you want.

As discussed earlier, not only can you define and store an assembly set into a file, but you can also launch reflector.exe with a particular assembly list file, via the command line.

Creating, selecting and deleting assembly lists in Reflector can be slightly confusing at first because it's not immediately obvious that the place to go to do it is the File | Open List dialog box. You can create new lists from the box by clicking 'Add' to clone the current list.You can also remove assembly lists from the same dialog box.

Figure 7: Managing your assembly lists!

You can switch between assembly lists with the same dialog box, or from the command line. To choose a different set of default assemblies for the current assembly list you should:

  1. Remove all assemblies from the list, by selecting them and using the Delete key
  2. Invoke the Refresh command.
  3. Add the assemblies to make up the set

This feature makes it easy to browse a variety of projects and frameworks, even if they have conflicting names

Sharing URIs

One of the great advantages of registering Reflector is that you can then, from within reflector, 'bookmark' any item within an assembly just by recording a custom URI for it (i.e. putting the URI on the clipboard by pressing Ctrl-Alt-C). Once a URI is clicked on, .NET Reflector displays the item. The URI includes the version and hash value for the assembly.

The URI can be shared with fellow developers to provide a link to the item, since it only requires the other person to have Reflector and the same .dll/.exe to which you created a shortcut. There is also a CodeShortcut add-in that allows you to save URIs on the desktop.

So, if you click on the following URI:

code://System.Xml:2.0.0.0:b77a5c561934e089/System.Xml.XmlConvert

You will see something similar to figure 7:

Figure 7: Opening a file in Reflector from a URI

Reflector Add-ins

A number of add-ins have been written for Reflector most, but not all, of which are open-source. There are many different add-ins and it is best to get an up-to-date listing and description than to rely on an article like this that will soon get out-of-date. An up-to-date listing is always kept at CodeProject:

http://www.codeplex.com/reflectoraddins

Some of the add-ins extend the language that Reflector disassembled to, such as PowerShell, Delphi, and MC++. Other add-ins will analyse assemblies in different ways, such as providing quality metrics, sequence diagrams, class diagrams, dependency structure matrices or dependency graphs. It is possible to use add-ins to search text, save disassembled code to disk, export an assembly to XMI/UML, to do side-by-side comparisons of different versions of code, or to search code.

Add-ins are being added the whole time and include those that: allow the debugging of processes, Facilitate testing by creating stubs and wrappers and allow browsing assemblies in other .NET foundations, such as Silverlight, WWF, Biztalk, SQL Server,  or windows Forms

There are also a range of utility add-ins, one of which allows .NET Reflector to be used within Visual Studio, and another that allows you to save the URI shortcuts of an item onto the desktop

Conclusions

.NET Reflector has always been an essential tool for understanding NET assemblies. There are many reasons for wanting to look at what is going on in an assembly. Any developer will need to do so, even if it is just a tool to help with understanding performance issues. With all the features that have been added over the years in response to requests by developers, and the add-in contributions, it has become a tool that it is impossible to be without when doing .NET software development.

Andrew has, for a while, been helping to flesh out the Wikipedia entry for .NET Reflector, and has modified parts of this article to do so. We're very conscious that .NET Reflector is generally very easy to use, and in that sense doesn't need documentation, but some features, such as the use of URIs, aren't intuitive! If you would like to add to this article, or you spot errors, then send an edited version to editor@Simple-Talk.com and we'll update the article and add you to an acknowledgements section.

Acknowledgements

  • Lutz Roeder, Jason Haley, and countless bloggers about .NET Reflector for supplying material
  • Bart Read for checking the first draft
  • Tony Davis for proofing the Article
  • Colin Patel-Murray for spotting a typo

Andrew Clarke

Author profile: Andrew Clarke

Andrew Clarke has been developing software applications for over 25 years. He is a database expert, but has a particular interest in website-publishing and ECommerce. He recently worked with the first two winners of the 'Apprentice' program at Amstrad, creating various business applications, and since worked with Tim Campbell setting up the 'Bright Ideas Trust'. He also subedits and reviews articles for Simple-Talk.

Search for other articles by Andrew Clarke

Monday, October 27, 2008

Ongoing Phishing Attack Exposes Yahoo Accounts

The Netcraft toolbar community has detected a vulnerability on a Yahoo website, which is currently being used to steal authentication cookies from Yahoo users — transmitting them to a website under the control of a remote attacker. With these stolen details, the attacker can gain access to his victims' Yahoo accounts, such as Yahoo Mail.

The attack exploits a cross-site scripting vulnerability on Yahoo's HotJobs site at hotjobs.yahoo.com, which currently allows the attacker to inject obfuscated JavaScript into the affected page. The script steals the authentication cookies that are sent for the yahoo.com domain and passes them to a different website in the United States, where the attacker is harvesting stolen authentication details.

When websites use cookies to handle authenticated sessions, it is extremely important to protect the cookie values and ensure they are not seen by other parties. Cross-site scripting vulnerabilities often allow these values to be accessed by an attacker and transmitted to a website under their control, which then allows the attacker to use the same cookie values to hijack their victim's session without needing to log in. This type of attack can be mitigated to some extent by using HttpOnly cookies to prevent scripts gaining access to the cookies — a feature that is now supported by most modern browsers.

Earlier this year, Netcraft blocked a similar flaw on another Yahoo website. The previous attack targeted a cross-site scripting vulnerability on Yahoo's ychat.help.yahoo.com site, which was served securely using a valid SSL certificate, adding further credibility to the attack. The attacker used the vulnerability to inject malign JavaScript into one of the site's webpages. Unlike the current attack, the injected code was sourced from a server in Spain, but also resulted in the victim's cookies being stolen and transmitted to a PHP script on the same server.

pula.js-resized.png
The small cookie-stealing script injected by the attacker.

hotjobs-yahoo-xss.png
A similar technique employed by the current attack.

In both cases, Netcraft found that the Yahoo cookies stolen by the attacker would have allowed him to hijack his victims' browser sessions, letting him gain access to all of their Yahoo Mail emails and any other account which uses cookies for the yahoo.com domain.

Simply visiting the malign URLs on yahoo.com can be enough for a victim to fall prey to the attacker, letting him steal the necessary session cookies to gain access to the victim's email — the victim does not even have to type in their username and password for the attacker to do this. Both attacks send the victim to a blank webpage, leaving them unlikely to realise that their own account has just been compromised.

ychat-resized.png
Both attacks send victims to a innocuous-looking, blank webpage.

The Netcraft Toolbar protects users against both of these attacks, warning that the malformed Yahoo URLs contain cross-site scripting elements, and that the URLs have been classified as known phishing sites.

Netcraft has informed Yahoo of the latest attack, although at the time of writing, the HotJobs vulnerability and the attacker's cookie harvesting script are both still present.

Reference URL: Netcraft

Sunday, October 26, 2008

Terrorist 'tweets'? US Army warns of Twitter dangers

WASHINGTON (AFP) - - A draft US Army intelligence report has identified the popular micro-blogging service Twitter, Global Positioning System maps and voice-changing software as potential terrorist tools.

The report by the 304th Military Intelligence Battalion, posted on the website of the Federation of American Scientists (FAS), examines a number of mobile and web technologies and their potential uses by militants.

The posting of the report on the FAS site was reported Friday by Wired magazine contributing editor Noah Shachtman on his national security blog "Danger Room" at wired.com.

The report is not based on clandestine reporting but drawn from open source intelligence known as OSINT.

A chapter on "Potential for Terrorist Use of Twitter" notes that Twitter members sent out messages, known as "Tweets," reporting the July Los Angeles earthquake faster than news outlets and activists at the Republican National Convention in Minneapolis used it to provide information on police movements.

"Twitter has also become a social activism tool for socialists, human rights groups, communists, vegetarians, anarchists, religious communities, atheists, political enthusiasts, hacktivists and others to communicate with each other and to send messages to broader audiences," the report said.

Hacktivists refers to politically motivated computer hackers.

"Twitter is already used by some members to post and/or support extremist ideologies and perspectives," the report said.

"Extremist and terrorist use of Twitter could evolve over time to reflect tactics that are already evolving in use by hacktivists and activists for surveillance," it said. "This could theoretically be combined with targeting."

The report outlined scenarios in which militants could make use of Twitter, combined with such programs as Google Maps or cell phone pictures or video, to carry out an ambush or detonate explosives.

"Terrorists could theoretically use Twitter social networking in the US as an operation tool," it said. "However, it is unclear whether that same theoretical tool would be available to terrorists in other countries and to what extent."

Besides Twitter, the report examined the potential use by militants of Global Positioning Systems and other technologies.

"GPS cell phone service could be used by our adversaries for travel plans, surveillance and targeting," it said, noting that just such uses have been discussed in pro-Al-Qaeda forums along with the use of voice-changing software.

"Terrorists may or may not be using voice-changing software but it should be of open source interest that online terrorist and/or terrorist enthusiasts are discussing it," the report said.

Reference URL: Yahoo News

Tuesday, October 21, 2008

Microsoft Web Application Installer

The IIS team of Microsoft have new Web Application Installer, follow the blog of Rob Conery of SubSonic to learn more.

Overview

The Web Application Installer Beta is designed to help get you up and running with the most widely used Web Applications freely available for your Windows Server. Web AI provides support for popular ASP.Net and PHP Web applications including Graffiti, DotNetNuke, WordPress, Drupal, OSCommerce and more. With just a few simple clicks, Web AI will check your machine for the necessary pre-requisites, download these applications from their source location in the community, walk you through basic configuration items and then install them on your computer.

System requirements

  • Supported Operating Systems are: Windows Vista RTM, Windows Vista SP1, Windows Server 2008
  • You must have administrator privileges on your computer to run Web Platform Installer Beta
  • .NET 2.0 Framework
  • Supported Architectures: x86 and 64-bit

Friday, October 17, 2008

What is Visual WebGui?

I have a little conversation with our Architech who lives in Florida and I've learned from him this Visual WebGui. I believe this is something interesting. We are going to use this in our next Enterprise Application.

What is Visual WebGui?

Visual WebGui introduces a different approach to AJAX front-ends. While the trend is towards empowering the client (browser) with more capabilities, enabling direct consumption of services by client side objects and distributing processing between the client and the server, WebGui adopts the server based computing approach whereby service consumption and processing is handled on the server and human interaction is handled on the client. This model provides intrinsic benefits for enterprise applications since it provides additional measures of security and control which are not available on browser based solutions. This approach, called "Empty Client", employs de-coupled GUI components which decouple GUI logic from GUI presentation (rendering) and enable remoting of the display/input capture between the client (browser) and the server. It is this approach that provides an even greater benefit by enabling application logic (usually entailing both business and presentation logic) to be handled within one, stateful, object-oriented environment developed in a high level, OOP language such as C#, VB.Net or Java rather than a mix between Javascript and a server based language.

Using a homogenous platform provides developers with immeasurable productivity benefits and enables developers to make better use of existing assets, knowledge and experience rather than requiring the steep learning curve of AJAX. Visual WebGui provides server side controls which behave like existing desktop application controls both in design time and in run-time. These controls manifest themselves as AJAX controls on the browser in run-time and look like their desktop counterparts. The architecture of the system is in no way limited to representing these base controls in their current "desktop" look and feel since it makes use of de-coupled components. Our initial offering contains the popular Microsoft controls that are a basic part of any Windows based application. These controls provide a huge productivity benefit to web developers who lag behind their desktop bretheren, while supporting the most common needs of desktop application developers without letting them down.

In addition the system is extremely extensible. Visual WebGui's SDK enables extending the framework by adding additional controls, changing themes/flavors (skins), creating composite controls based on base controls and creating gateway components. Since ultimately Visual WebGui is an extension to the app servers context (in the case of .Net an extention to IIS/ASP.net) it can interoperate with client side and server side legacy code. This means that Visual WebGui UIs can host and interoperate with existing HTML/Javascript client only controls or with embedded DOM objects such as Applets and ActiveX controls. Similarly existing web applications can interoperate with WebGui components/forms/windows since they are in essence URLs like any other sharing the same application and session context.

ASP .NET Dynamic Data Video tutorial by Bill Burrows

This tutorial covers an overview to ASP.NET Dynamic Data features. Dynamic Data is new to the .NET Framework 3.5 (SP1) and provides a way to easily creature, modify, and maintain a data driven website. Microsoft describes Dynamic Data as: "ASP.NET Dynamic Data provides a framework that enables you to quickly build a functional data-driven application, based on a LINQ to SQL or Entity Framework data model. It also adds great flexibility and functionality to the DetailsView, FormView, GridView, and ListView controls in the form of smart validation and the ability to easily change the display of these controls using templates." This tutorial covers the creation of a Dynamic Data site using Visual Web Developer Express 3.5 (SP1). It then talks about the conceptual ideas underlying the technology. Dynamic Data sites are highly customizable so the tutorial covers several ways to perform customization. Finally, the tutorial introduces the Dynamic Data Wizard, a project under development, that make customization easy via a "wizard" approach.

Reference URL: ASP .NET Dynamic Data by Bill Burrows

kick it on DotNetKicks.com

Wednesday, October 15, 2008

Upload T-SQL and execute at your hosting provider using an ASP.NET page

With this approach, you can use the Database Publishing Wizard to generate a T-SQL file from your local database. Then, you can upload the script to your hosting provider, and use the sample ASP.NET page provided to execute the code below.

This approach is useful in the following circumstances:

    * Your hosting provider has not deployed the Database Publishing Services, enabling simple publishing of your SQL Server database
    * Your hosting provider does not have a T-SQL script execution window or the T-SQL script generated by the Database Publishing Wizard is too large to paste into the T-SQL script execution window

Here is the code, just copy it then paste to your RunSQL.aspx

<%
// Sample code for executing a T-SQL file using an ASP.NET page
// Copyright (C) Microsoft Corporation, 2007. All rights reserved.

// Written as a sample with use in conjuction with the SQL Server Database Publishing Wizard
// For more information visit http://www.codeplex.com/sqlhost/

// **************************************************************************
// Note: Please ensure that you delete this page once your database has been published to the remote server
// **************************************************************************

%>

<%@ Page Language="C#" AutoEventWireup="true" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Net" %>


<%
// **************************************************************************
// Update these variables here
// **************************************************************************

// Url of the T-SQL file you want to run
string fileUrl = @"http://<<YourDomainName>>/<<YourFileName>>.sql";

// Connection string to the server you want to execute against
string connectionString = @"<<Your Connection String>>";

// Timeout of batches (in seconds)
int timeout = 600;


%>

<!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>Executing T-SQL</title>
</head>
<body>
<form id="form1" runat="server">
<div>

</div>
</form>
<%
SqlConnection conn = null;
try
{
this.Response.Write(String.Format("Opening url {0}<BR>", fileUrl));

// read file
WebRequest request = WebRequest.Create(fileUrl);
using (StreamReader sr = new StreamReader(request.GetResponse().GetResponseStream()))
{
this.Response.Write("Connecting to SQL Server database...<BR>");

// Create new connection to database
conn = new SqlConnection(connectionString);

conn.Open();

while (!sr.EndOfStream)
{
StringBuilder sb = new StringBuilder();
SqlCommand cmd = conn.CreateCommand();

while (!sr.EndOfStream)
{
string s = sr.ReadLine();
if (s != null && s.ToUpper().Trim().Equals("GO"))
{
break;
}

sb.AppendLine(s);
}

// Execute T-SQL against the target database
cmd.CommandText = sb.ToString();
cmd.CommandTimeout = timeout;

cmd.ExecuteNonQuery();
}

}
this.Response.Write("T-SQL file executed successfully");
}
catch (Exception ex)
{
this.Response.Write(String.Format("An error occured: {0}", ex.ToString()));
}
finally
{
// Close out the connection
//
if (conn != null)
{
try
{
conn.Close();
conn.Dispose();
}
catch (Exception e)
{
this.Response.Write(String.Format(@"Could not close the connection. Error was {0}", e.ToString()));
}
}
}


%>
</body>
</html>






Below are the instructions to use this approach:

   1. Run the Database Publishing Wizard to generate a T-SQL script file for your local database
   2. Using FTP (or another approach if applicable), upload this T-SQL file to your hosting account
   3. Download the sample ASP.NET page by clicking on this link: RunSQL.aspx
   4. Edit the ASPX page and change the values of the variables fileUrl and connectionString as follows:
         1. fileUrl should be the url of the T-SQL file you uploaded. For example if your domain name is www.mydomain.Com, then the url would be http://www.mydomain.com/File.Sql
         2. connectionString should be the connection string of your hosted SQL Server database
   5. Upload the ASPX page to your hosting account
   6. Point your web browser to the ASPX page you uploaded. When this page has completed loading, your database should now be populated in the remote SQL Server database
   7. Important: Delete the T-SQL file and ASPX page in your hosting account. This will prevent others from reading your data or tampering with your database.

 

Reference URL: Upload T-SQL and execute at your hosting provider using an ASP.NET page


kick it on DotNetKicks.com

Don’t run production ASP.NET Applications with debug=”true” enabled by ScottGu

I didn't know this before until I saw this article from ScottGu. So here it goes, read his article about web.config's <compilation debug=”true”/>.

One of the things you want to avoid when deploying an ASP.NET application into production is to accidentally (or deliberately) leave the <compilation debug=”true”/> switch on within the application’s web.config file.

Doing so causes a number of non-optimal things to happen including:

1) The compilation of ASP.NET pages takes longer (since some batch optimizations are disabled)

2) Code can execute slower (since some additional debug paths are enabled)

3) Much more memory is used within the application at runtime

4) Scripts and images downloaded from the WebResources.axd handler are not cached

This last point is particularly important, since it means that all client-javascript libraries and static images that are deployed via WebResources.axd will be continually downloaded by clients on each page view request and not cached locally within the browser.  This can slow down the user experience quite a bit for things like Atlas, controls like TreeView/Menu/Validators, and any other third-party control or custom code that deploys client resources.  Note that the reason why these resources are not cached when debug is set to true is so that developers don’t have to continually flush their browser cache and restart it every-time they make a change to a resource handler (our assumption is that when you have debug=true set you are in active development on your site).

When <compilation debug=”false”/> is set, the WebResource.axd handler will automatically set a long cache policy on resources retrieved via it – so that the resource is only downloaded once to the client and cached there forever (it will also be cached on any intermediate proxy servers).  If you have Atlas installed for your application, it will also automatically compress the content from the WebResources.axd handler for you when <compilation debug=”false”/> is set – reducing the size of any client-script javascript library or static resource for you (and not requiring you to write any custom code or configure anything within IIS to get it).

What about binaries compiled with debug symbols?

One scenario that several people find very useful is to compile/pre-compile an application or associated class libraries with debug symbols so that more detailed stack trace and line error messages can be retrieved from it when errors occur.

The good news is that you can do this without having the have the <compilation debug=”true”/> switch enabled in production.  Specifically, you can use either a web deployment project or a web application project to pre-compile the code for your site with debug symbols, and then change the <compilation debug=”true”/> switch to false right before you deploy the application on the server.

The debug symbols and metadata in the compiled assemblies will increase the memory footprint of the application, but this can sometimes be an ok trade-off for more detailed error messages.

The <deployment retail=”true”/> Switch in Maching.config

If you are a server administrator and want to ensure that no one accidentally deploys an ASP.NET application in production with the <compilation debug=”true”/> switch enabled within the application’s web.config file, one trick you can use with ASP.NET V2.0 is to take advantage of the <deployment> section within your machine.config file.

Specifically, by setting this within your machine.config file:

<configuration>

    <system.web>

          <deployment retail=”true”/>

    </system.web>

</configuration>

You will disable the <compilation debug=”true”/> switch, disable the ability to output trace output in a page, and turn off the ability to show detailed error messages remotely.  Note that these last two items are security best practices you really want to follow (otherwise hackers can learn a lot more about the internals of your application than you should show them).

Setting this switch to true is probably a best practice that any company with formal production servers should follow to ensure that an application always runs with the best possible performance and no security information leakages.  There isn’t a ton of documentation on this switch – but you can learn a little more about it here.

Hope this helps,

Scott

kick it on DotNetKicks.com

Tuesday, October 14, 2008

What Is a Sidejacking Attack?


Corey Nachreiner, CISSP, demonstrates a relatively simple way for someone sitting near you at a wireless hotspot to steal your credentials for any Web account you log into... then later, log on as you and see your private info. Based on a Black Hat presentation by Robert Graham of Errata Security.



Sunday, October 12, 2008

Common Tips/Tricks for Optimizing any VS 2005 Build Time by Scottgu

If you are using the VS 2005 Web Application project option, here are a few optimizations you might want to consider:

1) If you have a very large project, or are working on an application with many other developers, you might want to consider splitting it up into multiple "sub-web" projects. I wouldn't necessarily recommend this for performance reasons (unless you have thousands and thousands of pages it probably doesn't make a huge difference), but it can sometimes make it easier to help manage a large project. Please read this past blog-post of mine on creating sub-web projects to learn how to use this.

2) Consider adding a VS 2005 Web Deployment project to your solution for deep verification. I mentioned above that one downside of using the VS 2005 Web Application Project option was that it only compiled the code-behind source code of your pages, and didn't do a deeper verification of the actual .aspx markup (so it will miss cases where you have a mis-typed tag in your .aspx markup). This provides the same level of verification support that VS 2003 provided (so you aren't loosing anything from that), but not as deep as the Web Site Project option. One way you can still get this level of verification with VS 2005 Web Application Projects is to optionally add a VS 2005 Web Deployment Project into your solution (web deployment projects work with both web-site and web-application solutions). You can configure this to run only when building "release" or "staging" builds of your solution (to avoid taking a build hit at development time), and use it to provide a deep verification of both your content and source code prior to shipping your app.

Common Tips/Tricks for Optimizing any VS 2005 Build Time

Here are a few things I recommend checking anytime you have poor performance when building projects/solutions (note: this list will continue to grow as I hear new ones - so check back in the future):

1) Watch out for Virus Checkers, Spy-Bots, and Search/Indexing Tools

VS hits the file-system a lot, and obviously needs to reparse any file within a project that has changed the next time it compiles. One issue I've seen reported several times are cases where virus scanners, spy-bot detecters, and/or desktop search indexing tools end up monitoring a directory containing a project a little too closely, and continually change the timestamps of these files (they don't alter the contents of the file - but they do change a last touched timestamp that VS also uses). This then causes a pattern of: you make a change, rebuild, and then in the background the virus/search tool goes in and re-searches/re-checks the file and marks it as altered - which then causes VS to have to re-build it again. Check for this if you are seeing build performance issues, and consider disabling the directories you are working on from being scanned by other programs. I've also seen reports of certain Spybot utilities causing extreme slowness with VS debugging - so you might want to verify that you aren't having issues with those either.

2) Turn off AutoToolboxPopulate in the Windows Forms Designer Options

There is an option in VS 2005 that will cause VS to automatically populate the toolbox with any controls you compile as part of your solution. This is a useful feature when developing controls since it updates them when you build, but I've seen a few reports from people who find that it can cause VS to end up taking a long time (almost like a hang) in some circumstances. Note that this applies both to Windows Forms and Web Projects. To disable this option, select the Tools->Options menu item, and then unselect the Windows Forms Designer/General/AutoToolboxPopulate checkbox option (for a thread on this see: http://forums.asp.net/1108115/ShowPost.aspx).

3) Examine which 3rd party packages are running in Visual Studio

There are a lot of great 3rd party VS packages that you can plug into Visual Studio. These deliver big productivity wins, and offer tons of features. Occasionally I've seen issues where performance or stability is being affected by them though. This is often true in cases where an older version (or beta) of one of these packages is being used (always keep an eye out for when a manufacturer updates them with bug-fixes). If you are seeing issues with performance or stability, you might want to look at trying a VS configuration where you uninstall any additional packages to see if this makes a difference. If so, you can work with the 3rd party manufacturer to identify the issue.

Visual Basic Build Performance HotFix

The Visual Basic team has released several hotfixes for compilation performance issues with large VB projects. You can learn how to obtain these hotfixes immediately from this blog post. The VB team also has a direct email address -- vbperf@microsoft.com -- that you can use to contact them directly if you are running into performance issues.

Hope this helps,

Scott

Thursday, October 9, 2008

CodeSmith's New Video Tutorial

CodeSmith's video tutorial was now live in their website.


CodeSmith Projects

One of CodeSmith's most powerful features is CodeSmith Projects. Jump start your knowledge of CodeSmith Projects and get familiar with some tips and tricks to make the most use of CodeSmith Projects. Whether you are working with Visual Studio, MSBuild, Windows Explorer, a command line / batch file, or CodeSmith itself, CodeSmith Projects makes automating your code generation process easy and consistent.

http://www.codesmithtools.com/video/codesmith-projects.html


SchemaExplorer

SchemaExplorer is CodeSmith's built-in interface for working with metadata from databases. Join us for a quick tour of the features of SchemaExplorer and how they can be used with CodeSmith.

http://www.codesmithtools.com/video/schemaexplorer.html


CodeSmith Overview by Rob Howard

Rob Howard presents a 15 minute overview of the benefits of using CodeSmith.

http://www.codesmithtools.com/videotutorials/codesmith-4.0-overview.html