Saturday, November 19, 2011

.NET XSLT Extending Functionalities

I needed to match strings using regular expression.  In XPath 2.0, there's a function called fn:matches.  XSLT in .NET does not support XPath 2.0.  To work around this limitation, I had to implement my own XSLT extension.

There are two ways to do this:

1.  Create the extension class XPathFunctionExtension to implement the logic.

    XsltArgumentList args = new XsltArgumentList();
    args.AddExtensionObject("urn:XPathFunctionExtension", new XPathFunctionExtension());

   In the XSL stylesheet,  add the namespace xmlns:ext="urn:XPathFunctionExtension"

   Use the function, ext:Matches(text, pattern)

2.  The second way is through scripting to implement the logic right on the the XSL stylesheet.

   <xsl:stylesheet version="1.0"
   xmlns:xsl="http://www.w3.org/1999/XSL/Transform"xmlns:msxsl="urn:schemas-microsoft-com:xslt"
   xmlns:ext="urn:XPathFunctionExtension"

  <msxsl:script language="C#" implements-prefix="ext">
    <![CDATA[
        public bool Matches(string input, string pattern)
        {
            return Regex.IsMatch(input, pattern);
        }
      ]]>
  </msxsl:script>

That's it!  Gotta love regular expressions!! :)

Oh yeah, remember to enable scripting:  new XsltSettings(true, true);
The second argument is the "enableScript" and it needs to be true;
Otherwise, you would get this error:  Execution of scripts was prohibited. Use the XsltSettings.EnableScript property to enable it.

Friday, November 18, 2011

Apache POI-XSSF

Set background color of a cell:

CellStyle result = workbook.createCellStyle();
result.setFillForegroundColor(IndexedColors.YELLOW.getIndex());
result.setFillPattern(CellStyle.SOLID_FOREGROUND);


Merge some cells together:


/**
 * Merge the cells into one
 *
 * @param sheet
 * @param rowNum
 * @param fromCellNum 0-based index
 * @param toCellNum 0-based index
 */
private static void mergeCells(Sheet sheet, int rowNum, 
                                     int fromCellNum, int toCellNum) {
    sheet.addMergedRegion(
              new CellRangeAddress(rowNum, rowNum, fromCellNum, toCellNum));
}


Set a comment:

/**
 * Set a comment on a cell.
 *
 * @param text
 * @param cell
 */
private static void setComment(String text, Cell cell) {
    // Numbers on Mac OS hands the comment much, much better than Excel.  
    // Ugh to Excel!
       
    Sheet sheet = cell.getSheet();
    Row row = cell.getRow();
    Workbook wb = sheet.getWorkbook();
       
    CreationHelper createHelper = wb.getCreationHelper();

    Drawing drawing = sheet.createDrawingPatriarch();
       
    // count the number of lines in the comment.  
    // use this to decide how many rows down to anchor the comment box.
    // Note: there may be a better way to do it.  just playing around for now.
    int lineCount = getLineCount(text);
       
    ClientAnchor anchor = createHelper.createClientAnchor();
       
    anchor.setCol1(cell.getColumnIndex());
    anchor.setCol2(cell.getColumnIndex()+10);
    anchor.setRow1(row.getRowNum());
    anchor.setRow2(row.getRowNum()+lineCount);
        
    Comment comment = drawing.createCellComment(anchor);
    RichTextString str = createHelper.createRichTextString(StringUtils.strip(text));

    // without the font set, the comment would not appear at all!
    Font font = wb.createFont();
    font.setFontName( "Arial" );
       
    str.applyFont(font);

    comment.setString(str);
       
    cell.setCellComment(comment);
}

Thursday, November 3, 2011

Gmail New Layout - Chat Box

As you may be aware, Gmail is piloting the new layout and going to push it out soon.  I tried it, and at first look, I didn't like it.  Everything got so big, taking too much real estate, especially if you had a small screen.

After a few tweaks, I got it to how I like it.  On the right-hand side, there's a gear icon; under it, there's a "Display Density" setting.  I chose "Compact" which made it small again.

I'm not sure how many people actually use the integrated chat box.  I know I don't.  I wanted to completely remove it before, but I know I can't.  With the new layout, on the lower left-hand side, there's a icon for "Chat" (would only appear if you had disabled the "Right-side chat" labs feature.) and next to it "Gadgets."  Clicking on the "Chat" would minimize the chat box.  Clicking on "Gadgets" would minimize the other gadgets.

Now, I have the simple and clean layout that I like.  If you don't like the default colors, you can go change the theme.  Sounds like a given, but sometimes, people forget about it.

Wednesday, September 21, 2011

XSLT Processing With Browser

 <SCRIPT LANGUAGE="JavaScript">

         function parseText2XML(text) {
             var result;

             if (window.DOMParser) {
                 parser = new DOMParser();
                result = parser.parseFromString(text,"text/xml");
             } else {
                  // IE
                xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
                xmlDoc.async = "false";
                result = xmlDoc.loadXML(text);
              }

             return result;
         }

         function transform(xmlText, xslText) {
             var result;

             var xml = parseText2XML(xmlText);
             var xsl = parseText2XML(xslText);

             if (window.ActiveXObject) {
                 // IE
                 result = xml.transformNode(xsl);
             } else if (document.implementation && document.implementation.createDocument) {
                // code for Mozilla, Firefox, Opera, etc.
                xsltProcessor=new XSLTProcessor();
                xsltProcessor.importStylesheet(xsl);
                resultDocument = xsltProcessor.transformToFragment(xml,document);

                var serializer = new XMLSerializer();

                result = serializer.serializeToString(resultDocument);
             }

             return result;
         }

     </SCRIPT>

Wednesday, August 17, 2011

VirtualBox Guest OS Window Automatic Resizing

Install guest additions if you don't have it already.  Make sure that "Auto-resize Guest Display (Host+G)" under the machine menu is checked.  My Guest Windows XP stopped resizing the window, and it turned out that I accidentally turned this off, so it's just something to verify.


Friday, August 12, 2011

Sharing Files Through Microsoft Remote Desktop Connection (RDC)

Context:

Mac OS X
Microsoft Remote Desktop Connection Client for Mac, Version 2.1.1
Windows Server

Problem:

I want to share and transfer files between my Mac and the remote Windows server.

Solution:

Under RDC menu, choose Preferences...
Once you're there, choose Drives.  There, you can choose which folder you want to share.  After that, you can remote desktop into the server.  On the server, you will see the folder available as a drive.  That's it.

Saturday, August 6, 2011

XSLT 1.0/XPath 1.0 Case-Insensitive String Match

With XPath 2.0, you can use fn:matches('My TeSt String','test', 'i') to do case-insensitive.

With XPath 1.0, here's how:

contains(translate('My TeSt String','ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), 'test')

This translate function maps letters and essentially turns uppercase letters into lowercase letters.

Friday, August 5, 2011

Java printf Percent (%) Sign

To put the percent sign '%' in as a literal,

System.out.printf("\nTested %d reports.  Found differences in %d reports.  %2.2f%% passed.  %2.2f%% failed.\n", 7, 1, ((float)(7-1)/7)*100, ((float)1/7)*100);
%[argument_index$][flags][width][.precision]conversion
 
The optional argument_index is a decimal integer indicating the position of the argument in the argument list. The first argument is referenced by "1$", the second by "2$", etc. 
The optional flags is a set of characters that modify the output format. The set of valid flags depends on the conversion. 
The optional width is a non-negative decimal integer indicating the minimum number of characters to be written to the output. 
The optional precision is a non-negative decimal integer usually used to restrict the number of characters. The specific behavior depends on the conversion. 
The required conversion is a character indicating how the argument should be formatted. The set of valid conversions for a given argument depends on the argument's data type.

Wednesday, August 3, 2011

Packet for query is too large...setting the 'max_allowed_packet' variable.

Context:

MySQL
Hibernate
Sequel Pro

Problem:

Tried to save a blob, but evidently, the size was larger than the allowed size by MySQL.  For me, the max_allowed_packet size was 1M.  One way that you can find this out is by running: 
SHOW VARIABLES LIKE 'MAX_ALLOWED_PACKET'; 

Solution:

To fix this, I simply increased the size to 5M by running 
SET GLOBAL MAX_ALLOWED_PACKET=5*1024*1024;

Footnote:

I was using Sequel Pro.  After I ran the set query to increase the size, I ran the show variable query.  I expected to see the new size; however, I did not see that.  When I ran the show variable query through mysl at the shell, I saw the new size.  Not sure why.  Anyway, it worked and I don't have time to investigate.  Need to move on to other stuff.

Tuesday, August 2, 2011

Parse HTML To Extract Certain Values Out With Java

Problem:

I needed to parse and extract some values from an html page.  I tried using JTidy, dom4j, JDOM, and the JDK built-in parser.  They gave me errors and refused to work.   They were overly complicated for what I wanted to do.  I wanted something simple and easy to parse some html to get some values from it by some queries on the elements.

Solution:

I found what I was looking for:  Jsoup!  http://jsoup.org/   It's exactly what I wanted.  I could even connect to a web site and get the Document back.

Document doc = Jsoup.connect("some url here").get();

I must say that I really like it!



Wednesday, July 27, 2011

Apple Magic Mouse

I've been using the Apple Magic Mouse for over a month now, and I must say that I really like it.  Make sure that you use it with BetterTouchTool.  With BetterTouchTool, you can program the mouse to do different things to your liking.  ButterTouchTool has a "windows snapping" feature like Windows 7 if you like that.

Tuesday, July 26, 2011

Acer Aspire 5732z Touchpad Not Working

Problem:  

A friend asked me for help.
Acer Touchpad suddenly stopped working.  Tried Fn+F7 as suggested, not working.  Tried uninstalling/reinstalling driver, not working.

Solution: 

On the left of the power button (where you turn your laptop on and off), there is a little button.  It's the on/off button for the touchpad.  Make sure that it's on.  Simple as that.  Took me a while to figure that out.  Since it wasn't my laptop, I didn't know all of its functions.  Hope this helps someone someday.

Wednesday, July 20, 2011

Removing Sweat Sheen With Photoshop

  1. Create a new layer and "darken" for blending mode
  2. Choose the brush and set "opacity=20%"
  3. Alt (keyboard) to pick the area without the sweat and apply to the sweat area
Reference:  http://www.youtube.com/watch?v=wEZgawNrt2E

Friday, July 15, 2011

HmacSHA1 in Java and C#

Java:

byte[] password = "password".getBytes();
SecretKeySpec keySpec = new SecretKeySpec(password,"HmacSHA1");
Mac hmacsha1 = Mac.getInstance("HmacSHA1");
hmacsha1.init(keySpec);
byte[] hash = hmacsha1.doFinal("test".getBytes());
String hashBase64 = new String(Base64.encodeBase64(hash));
System.out.println(hashBase64);

C#:

System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
byte[] password = encoding.GetBytes("password");

HMACSHA1 hmacsha1 = new HMACSHA1(password);
byte[] hash = hmacsha1.ComputeHash(encoding.GetBytes("test"));

String hashBase64 = Convert.ToBase64String(hash);
Console.WriteLine(hashBase64);

Base64 Encoding String in Java and C#

Java:

String base64 = new String(org.apache.commons.codec.binary.Base64.encodeBase64("test".getBytes()));
System.out.println(base64);

C#:

System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
string base64 = System.Convert.ToBase64String(encoding.GetBytes("test"));
Console.WriteLine(base64);

Convert String To Hex in Java and C#

Java:


String hex = new String(org.apache.commons.codec.binary.Hex.encodeHex("test".getBytes()));
System.out.println(hex);

C#:

System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
string hex = System.BitConverter.ToString(encoding.GetBytes("test")).Replace("-", string.Empty);
Console.WriteLine(hex);




Thursday, July 14, 2011

Parse XML String in Java

Here are a couple of easy ways to parse an xml string in java:

String xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?><string xmlns=\"http://playingtreee.blogspot.com/\">4654ebd75e9cbd8a4823e964f0dceef0</string>";

Example 1:
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new InputSource(new StringReader(xml)));
System.out.println(doc.getFirstChild().getTextContent());

Example 2:

DOMParser parser = new DOMParser();
parser.parse(new InputSource(new StringReader(xml))); 

Document doc = parser.getDocument();
System.out.println(doc.getFirstChild().getTextContent());

Wednesday, July 13, 2011

Key-Value Pairs in .NET

You can add these to App.config and Web.config.



  <appSettings>
    <add key="blog" value="playingtree"/>
  </appSettings>


To read it,


using System.configuration;


ConfigurationManager.AppSettings["ReportProcessingRoot"];

Monday, July 11, 2011

Farewell AJ

AJ passed away yesterday.  Gave him a burial today.  How sad :(  

Different Ways of Loading Properties Files in Java


MethodParameter formatLookup failure behaviorUsage example
ClassLoader.
getResourceAsStream()
"/"-separated names; no leading "/" (all names are absolute)Silent (returns null)this.getClass().
getClassLoader()
.getResourceAsStream
("some/pkg/resource.properties")
Class.
getResourceAsStream()
"/"-separated names; leading "/" indicates absolute names; all other names are relative to the class's packageSilent (returns null)this.getClass()
.getResourceAsStream
("resource.properties")
ResourceBundle.
getBundle()
"."-separated names; all names are absolute;.properties suffix is impliedThrows unchecked
MissingResourceException
ResourceBundle.
getBundle("some.pkg.resource")




http://www.javaworld.com/javaworld/javaqa/2003-08/01-qa-0808-property.html?page=2

Friday, July 8, 2011

Where to put mime.types in web app?

Put it under WEB-INF/classes/META-INF/mime.types so MimetypesFileTypeMap can find and load it.

vsvars32.bat is missing

C:\Program Files\Microsoft Visual Studio 10.0\Common7\Tools\vsvars32.bat


I installed Visual Studio 2010 Express and couldn't find the file vsvars32.bat anywhere; however, after I installed Visual Studio 2010 Professional, I was able to find it.

Install, Uninstall, Start, Stop Windows Service at Command Line

To install,
C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\installutil MyService.exe


In uninstall,
C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\installutil /u MyService.exe


To start,
net start MyService


To stop,
net stop MyService

Client/Server Communication Between Host OS and Guest OS in VirtualBox

Context:


Host OS:  Mac OS X
Guest OS:  Windows XP
VirtualBox


Problem:


I have IIS Express 7.5 running .NET web services in Windows XP.  I have Jetty running JEE web application in Mac OS X.  I need to make requests to IIS server, and in return, I also need to make requests to Jetty server.


Solution:


To enable the communication line to IIS Express in Windows XP, I need to set up a port forwarding with VirtualBox.  To do this, you go into the Network Adapters settings and choose "Port Forwarding,"  choose the plus sign (Insert new rule), you get a new row with six columns.  


Here's my settings:
  Name               Protocol         Host IP        Host Port       Guest IP     Guest Port
IIS Express         TCP           127.0.0.1         1071                                     1071


Guest IP is intentionally left blank.  When I do http://localhost:1071 in Mac OS X, the traffic gets forwarded to IIS Express in Windows XP running at port 1071.  One thing to note is that your Windows Firewall may block the traffic, so make sure that you allow that to happen.


To enable the communication line to Jetty from Windows XP, I don't need to set up anything.  I simply need to connect to it with its IP address.   In my case, my Mac has an IP address of 192.168.1.104, so I can connect to it with that IP address.

Missing Semicolon After &#xA0 With XmlWriter

Recently, I ran into this error:

Exception thrown in BuildReports: Invalid syntax for a hexadecimal numeric entity reference. Line 175, position 3159.

This exception was thrown when &#160; was converted into &#xA0 with the missing semicolon instead of &#xA0;

This was random.  Some &#160; got converted correctly with the semicolon; and some got converted with the missing semicolon.

I was able to fix it with changing the encoding from ASCII to UTF8

XmlWriterSettings settings = new XmlWriterSettings();
settings.Encoding = Encoding.UTF8;

Thursday, July 7, 2011

Struts 2 Gzip HTML Output

I want to send back gzip file of an html file.


struts.xml:



<action name="ReportView" class="ReportViewAction" method="execute">
    <result name="success" type="stream">
        <param name="contentType">text/html</param>
        <param name="inputName">fileStream</param>
        <param name="bufferSize">1024</param>
    </result>
</action>


Note:  you can set/override this static params in your action by providing getters.  For example, to return a dynamic value for the contentType


public String getContentType() {
   // contentType is set to whatever you want
   // depending on your content.
   // be it text/html, application/vnd.ms-excel, application/pdf
   return contentType;  
}


Action:



public class ReportViewAction extends ActionSupport implements ServletResponseAware {

    private String id;
    private InputStream fileStream;
    
    @Override
     public String execute() throws Exception {
         Session session = HibernateUtil.currentSession(false);
         Report report = (Report)session.load(Report.class, id);
         // content is a Blob
         fileStream = report.getContent().getBinaryStream();
         return super.execute();
    }
     
     public String getId() {
         return id;
     }

     public void setId(String id) {
         this.id = id;
     }

     // this matches the inputName specified struts.xml
     public InputStream getFileStream() {
         return fileStream;
     }

     public void setFileStream(InputStream fileStream) {
         this.fileStream = fileStream;
     }

     @Override
     public void setServletResponse(HttpServletResponse response) {
         response.setHeader("Content-Encoding", "gzip");
     }
}



Struts 2 File Upload

JSP:


<s:form action="FileUpload" enctype="multipart/form-data">
   <s:file name="upload" label="File"></s:file>
   <s:submit/>
</s:form>


Action:


public class FileUpload extends ActionSupport {
    private File file;
    private String contentType;
    private String filename;

    @Override
    public String execute() throws Exception {
       return super.execute();
    }

    public void setUpload(File file) {
       this.file = file;
    }

    public void setUploadContentType(String contentType) {
       this.contentType = contentType;
    }

    public void setUploadFileName(String filename) {
       this.filename = filename;
    }
}

Unzip and Gzip with Java

Download the zipped file.  Get the files within the zipped file and gzip each of the file.


ZipInputStream zipStream = null;

try {
    final int BUFFER = 2048;

    GZIPOutputStream dest = null
;
    zipStream = new ZipInputStream(new BufferedInputStream(
                                   new FileInputStream(file)));

    ZipEntry zipEntry;
    while ((zipEntry = zipStream.getNextEntry()) != null) {
       int count;
       byte data[] = new byte[BUFFER];

       String reportName = zipEntry.getName();
       File report = File.createTempFile("rpt", "gz");
       dest = new GZIPOutputStream(

              new FileOutputStream(report), BUFFER);

       while ((count = zipStream.read(data, 0, BUFFER)) != -1) {
         dest.write(data, 0, count);
       }
       dest.flush();
       dest.close();
    } finally {
       if(zipStream != null) {
          zipStream.close();
 
       }   
    }

Hibernate.createBlob with Apache HttpClient


I wanted to download a file with Apache HttpClient and save it as a blob with Hibernate.

HttpEntity httpEntity = response.getEntity();
Hibernate.createBlob(httpEntity.getContent(), (int) httpEntity.getContentLength());

The thing to note here is that the size of the file has to be specified by doing this(int) httpEntity.getContentLength()for it to work.

MySQL Data Modeler and UML Diagrams on Mac OS X

MySQL Workbench has a data modeling tool.  It's inconspicuous though.  To get to it, you have to open up the SQL Editor and do File -> New Model.  It can export to different output formats such as pdf, png, and even SQL that you can run on your database.  Additionally, you can "reverse engineer" your existing tables.


For UML Diagrams,  I like yEd Graphical Editor.  It does what I want it to do.


Both are free tools.

MySQL Database Browser on Mac OS X

I started using MySQL Workbench and Sequel Pro.  They work really well.

Upload files with other parameters in .NET

To simply send a file, .NET has this built-in.  Very easy to use.


System.Net.WebClient webClient = new System.Net.WebClient();
webClient.UploadFileAsync(new Uri(anURL),  aFile);


However, I needed to specify the file name and send other parameters, so here's what I did with the help of Krystalware.HttpUploadHelper:


// my files to upload
UploadFile[] files = new UploadFile[] { 
  new UploadFile(aFile, "aFileName", "application/zip")
};


// form data
NameValueCollection form = new NameValueCollection();
form["guid"] = guid;


HttpUploadHelper.Upload(anURL, files, form);

Wednesday, July 6, 2011

Running a Site using IIS Express from the Command Line

http://learn.iis.net/page.aspx/870/running-iis-express-from-the-command-line/
  1. Open a command prompt.

    You do not need Administrator user rights to run the commands in this walkthrough. However, you must have Administrator user rights if you want to run IIS Express on ports numbered 1024 or less.
  2. Run the following command to navigate to the IIS Express installation folder:

    cd \Program Files\IIS Express
    or if you are using a 64-bit OS, run the following command:

    cd \Program Files (x86)\IIS Express
  3. Run the following command to view the IIS Express usage string:

    iisexpress /?

    IIS Express Usage:
    ------------------
    iisexpress [/config:config-file] [/site:site-name] [/siteid:site-id] [/systray:boolean]
    iisexpress /path:app-path [/port:port-number] [/clr:clr-version] [/systray:boolean]

    /config:config-file
    The full path to the applicationhost.config file. The default value is the IISExpress8\config\applicationhost.config file that is located in the user's Documents folder.

    /site:site-name
    The name of the site to launch, as described in the applicationhost.config file.

    /siteid:site-id
    The ID of the site to launch, as described in the applicationhost.config file.

    /path:app-path
    The full physical path of the application to run. You cannot combine this option with the /config and related options.

    /port:port-number
    The port to which the application will bind. The default value is 8080. You must also specify the /path option.

    /clr:clr-version The .NET Framework version (e.g. v2.0) to use to run the application. The default value is v4.0. You must also specify the /path option.

    /systray:boolean
    Enables or disables the system tray application. The default value is true.

    /trace:debug-trace-level
    Valid values are info or i,warning or w,error or e.

    Examples:
    iisexpress /site:WebSite1
    This command runs WebSite1 site from the user profile configuration file.

    iisexpress /config:c:\myconfig\applicationhost.config
    This command runs the first site in the specified configuration file.

    iisexpress /path:c:\myapp\ /port:80
    This command runs the site from c:\myapp folder over port 80. 
  4. Run your site using one of the following:
    • Use /config to run a site from a configuration file.

      See "Running your site from a configuration file" for more information.
    • Use /path to run a site from the application folder.

      See "Running your site from the application folder" for more information.
    Note: The /path option and the /config option cannot be combined.
  5. Once your site is running, you can use the IIS Express system tray to manage it. For more information, see Use the Windows System Tray to Manage Websites and Applications. Alternatively, you can disable the system tray by running the following option:

    /systray:false

Running your site from a configuration file

IIS Express and IIS use the ApplicationHost.config file, which specifies global settings for sites, application pools, handlers, etc. IIS Express uses a default, user-specific ApplicationHost.config file to allow many users to share the same computer without interfering with other user's settings. This file is located in the %userprofile%\Documents\IISExpress\config folder or %userprofile%\My Documents\IISExpress\config folder, depending on your OS. When you run a site from a configuration file, you can specify which site to run.
You can use the following commands:
  • To run the website Website1 in the default configuration file, run:

    iisexpress /site:WebSite1
  • To run the first website in the default configuration file, run:

    iisexpress
  • To run the first website in a custom configuration file, run:

    iisexpress /config:c:\myconfig\applicationhost.config
  • To run a site called MyBlog from a custom configuration file, run:

    iisexpress /config:c:\myconfig\applicationhost.config /site:MyBlog
Note: The /config option specifies the full path of the configuration file. You can omit this option if you want to use the default configuration file. The /site option specifies a particular site in the configuration file. You can omit this option to run the first site in the configuration file.

Running your site from the application folder

You can also use the /path option to run a site directly from a folder. This option works for any type of application, including static HTML, ASP.NET, PHP, and WCF. By default, IIS Express will run the site on http://localhost:8080/. For a managed website, such as ASP.NET, IIS Express will use .NET 4.0. You can use the /port and /clr options to override these default values.
For example, the following command runs the specified application, "myapp," on http://localhost:9090/ by using .NET 2.0:
iisexpress /path:c:\myapp\ /port:9090 /clr:v2.0

Tuesday, July 5, 2011

ASP.NET: Visual Studio 2010 with IIS Express 7.5

Context:

Windows XP
Visual Studio 2010
ASP.NET
IIS 5.1
IIS Express 7.5

Problem:

I wanted to run my ASP web site from Visual Studio 2010 and access the web site from another computer.  In my case, it's a Windows XP running in VirtualBox.

Visual Studio 2010 came with a development server, you could run your ASP pages directly from it.  However, it is restricted.  You can only access it locally, meaning that you can only access it on the same machine that Visual Studio 2010 is running.

Since I wanted to access it from a different machine,  I tried publishing my web site to IIS 5.1.  After registering ASP.NET Framework 2 with it to work with aspx and asmx, I tried to access it from a different machine, and I got this in my event log:

Failed to execute request because the App-Domain could not be created. Error: 0x80131902 


Failed to initialize the AppDomain:/LM/W3SVC/1/ROOT


Exception: System.Configuration.ConfigurationErrorsException


Message: Exception of type 'System.Configuration.ConfigurationErrorsException' was thrown.


StackTrace:    at System.Web.Configuration.ErrorRuntimeConfig.ErrorConfigRecord.System.Configuration.Internal.IInternalConfigRecord.GetLkgSection(String configKey)
   at System.Web.Configuration.RuntimeConfigLKG.GetSectionObject(String sectionName)
   at System.Web.Configuration.RuntimeConfig.GetSection(String sectionName, Type type, ResultsIndex index)
   at System.Web.Configuration.RuntimeConfig.get_HostingEnvironment()
   at System.Web.Hosting.HostingEnvironment.StartMonitoringForIdleTimeout()
   at System.Web.Hosting.HostingEnvironment.Initialize(ApplicationManager appManager, IApplicationHost appHost, IConfigMapPathFactory configMapPathFactory, HostingEnvironmentParameters hostingParameters)
   at System.Web.Hosting.HostingEnvironment.Initialize(ApplicationManager appManager, IApplicationHost appHost, IConfigMapPathFactory configMapPathFactory, HostingEnvironmentParameters hostingParameters)
   at System.Web.Hosting.ApplicationManager.CreateAppDomainWithHostingEnvironment(String appId, IApplicationHost appHost, HostingEnvironmentParameters hostingParameters)
   at System.Web.Hosting.ApplicationManager.CreateAppDomainWithHostingEnvironmentAndReportErrors(String appId, IApplicationHost appHost, HostingEnvironmentParameters hostingParameters)

Solution:

For a while, I didn't know what the problem was.  I searched the Internet and found different solutions, such as trying to grant security access to the wwwroot and whatnot.  I tried it all, but it didn't work for me.  It was frustrating.


After some research, I found out that I could get what I wanted through getting Visual Studio 2010 SP1 and IIS Express 7.5.  After installing the SP1 and IIS Express, to tell Visual Studio to use IIS Express instead of the default Visual Studio Development Server, you right click on your web project and choose "Use IIS Express..."  That's it.  I did get it to work how I wanted it to.

P.S.  I've been a Java guy for a long time.  Recently, I started working on this project which has .NET stuff, so I just started digging into .NET for a couple of weeks now.