Wednesday, June 13, 2012

A Graphical Language with a Difference

Visual programming(Google Blockly) kept me excited for a while and drove me to solve the 'Maze' puzzle. At the first attempt I tried something in a regular fashion and re-factored it to be much simpler.  With more complex puzzles, this is going to be fun and interesting. 

Here is what I came with.

Maze Solution


Happy Mazing!!!

Tuesday, June 12, 2012

Web Config Transformation - TransformXml

In certain circumstances, we would need all the configs to be transformed when we publish or build it in release/build mode while default behavior of  visual studio is to transform  the build specific web.config. I needed the same for one of my projects and here is how it was accomplished.

The actual transform logic is all in the TransformXml MSBuild task from Microsoft.Web.Publishing.Tasks.dll. So we can utilise the same functionality for generating any config file with a simple MSBuild script. Microsoft.Web.Publishing.Tasks.dll is part of VS 2010 and the default install location is C:\Program Files\MSBuild\Microsoft\VisualStudio \v10.0\Web

Here are the steps to get all the config transformed at one-shot irrespective of the build configuration that is selected in visual studio.
  1. Unload the project or open up the *.csproj (C#) in any text editor. 

  2. Edit the project in visual studio/ any text editor

  3. Add the below Target inside the "Project" node. This would transform the web.Debug.config to WebDebugTransformed.config irrespective of the build configuration.
    <Target Name="BeforeBuild">
    <TransformXml Source="$(SolutionDir)Widget\Web.config"
         Transform="$(SolutionDir)Widget\Web.Debug.config"
         Destination="$(SolutionDir)Widget\WebDebugTransformed.config"
         StackTrace="true" />  
    </Target>
    
    The "BeforeBuild" and "AfterBuild" targets will be already defined in comments at the end of most project files. Multiple TransformXml tags can be added to get all the required config files. 

    Here are the targets in Microsoft.Common.targets that you can safely override.
    BeforeCompile, AfterCompile, BeforeBuild, AfterBuild, BeforeRebuild, AfterRebuild, BeforeClean, AfterClean, BeforePublish, AfterPublish, BeforeResolveReference,AfterResolveReferences, BeforeResGen, AfterResGen

  4. Now, Reload and build the project. The transformed config file would be in the specified destination directory.

Happy Coding!!!

Thursday, May 3, 2012

File Protection - ASP.NET

It's always a good practice to restrict files that is not intend for normal users. The easiest way is to not place the file in the web directory.The recommended way is to forbidden file access is to use the System.Web.HttpForbiddenHandler.

By default, ASP.NET is configured to intercept and to stop requests for several different file types that are used in ASP.NET applications and these are configured in the root Web.config.

Here are the file types that are configured by default to be forbidden from user access.
*.asax, *.ascx, *.master, *.skin, *.browser, *.sitemap, *.config, *.cs, *.csproj, *.vb, *.vbproj, *.webinfo, *.licx, *.resx, *.resources, *.mdb, *.vjsproj, *.java, *.jsl, *.ldb, *.dsdgm, *.ssdgm, *.lsad, *.ssmap, *.cd, *.dsprototype, *.lsaprototype, *.sdm, *.sdmDocument, *.mdf, *.ldf

ASP.NET ensures the privacy of these files by associating both file types with System.Web.HttpForbiddenHandler. If the forbidden file is requested, System.Web.HttpForbiddenHandler returns an error to the user as a response to the request. 

Here is the high level overview of how the page is served
When a request hits the IIS Web server, the file extension is examined and based on its extension the request is handled by IIS itself or it is directed to the ISAPI extension. When it comes to static file like .htm, IIS handles it and returns back the contents of it but in case of dynamic files like .aspx IIS routes the request to the aspnet_isapi.dll ISAPI extension, the ISAPI extension routes the request onto the ASP.NET engine which maps the file extension to HTTP Handlers. For example, ASP.NET Web pages are rendered by the PageHandlerFactory; the SOAP responses of Web services are generated by the WebServiceFactoryHandler. The PageHandlerFactory knows how to render the HTML markup of an ASP.NET Web page; the WebServiceFactoryHandler knows how to accept incoming SOAP requests, invoke the proper Web service method, and return the response in a properly formatted SOAP response.


Protecting the files
In order for ASP.NET to block the desired file type IIS needs to be configured to forward the requests to ASP.NET and also the web.config of the application needs to be configured to block the desired file type.

Configuring IIS to block the desired file type
  1. Open IIS and right-click on the web site/virtual directory and choose "Properties" 
  2. Web Site Properties
  3. Navigate to the Home Directory tab and click "Configuration"
  4. Application Configuration
  5. To add application mappings for each extension that you want ASP.NET to block, click Add. Then, in the Executable field, fill in the path of your aspnet_isapi.dll. 
    • To identify the location of the Aspnet_isapi.dll file that handles the ASP.NET requests, select the .aspx application mapping and then click Edit.Mostly the ISAPI extension will be at $WINDOWS_DIR$\Microsoft.Net\Framework\$VERSION$
  6. In the "Extension" Field, Enter the file type. for example, .ini
  7. In the Verbs section, select the All Verbs option. Verify that the Script Engine check box is selected and that the Check If File Exists check box is not selected.
  8. Click OK.
  9. If required, Repeat this procedure for every file name extension that you want to have processed by ASP.NET.
Web Config Configuration
In the Web.config file add the <httpHandlers> configuration element under the <system.web> element.

    
        
        
    
The above is for IIS version prior to 7.0. IIS 7.0 supports 2 modes, Integrated and Classic. Integrated is the default mode for ASP.NET apps on IIS 7.0 which require handlers to be placed in <system.webServer>/<handlers> instead of <system.web>/<httpHandlers>. Here is the config for IIS 7.0

    
        
        
    
Apart from System.Web.HttpForbiddenHandler which issues the HTTP 403 error "Forbidden: Access is denied" when an attempt is made to access a forbidden resource "System.Web.StaticFileHandler" can be used which generates one of the following errors: HTTP 401 error "Unauthorized"; HTTP 403 error "Forbidden: Access is denied"; or HTTP 404 error "File or directory not found".

Happy Coding!!!

Monday, March 19, 2012

ELMAH - Error Logging Modules and Handlers - (Security)


Securing the logs should be one of the important aspects to be considered when using ELMAH. If the logs are not secured, it can open up the inner working of the application to unauthorized personal. 

By default, ELMAH is configured to deny access to the error log it produces unless we are accessing it from the server the site is hosted on.  To secure the logs, we would need to configure the below

  • Enabling or disabling remote access to the logs 
  • Granting or denying permissions via ASP.Net authorization

Here is what can happen if the logs are not secured -  ASP.NET session hijacking with Google and ELMAH

Enabling or disabling remote access to the logs
ELMAH provides a configuration section and a setting to enable or disable remote access to the error log display and feeds. Here is the snippet that needs to be added to the configuration file.

    
Remote access is enabled when the value of the allowRemoteAccess attribute is either 1, yes, true or on. Otherwise it is disabled. Local access is always available.

Granting or denying permissions via ASP.Net authorization  
Using ASP.NET’s Membership Provider and in-built authorization system we can deny anonymous access by adding the following definition to our web.config file. It can go anywhere inside the root configuration element.

    
      
        
      
    

This will allow any authenticated user to view the error log. If you only want a select group of people to be able to view the log, you could put those users into a ‘Support’ role and use something like:

    
    

Happy Coding!!!

Tuesday, March 6, 2012

ELMAH - Error Logging Modules and Handlers - (Basic)


Creating custom classes or using an existing class for exception handling and logging should be considered/included as part of the design.  Sometimes I've noticed that the exception handling takes the lower priority and this shouldn't be the case. Anything that is coded is error prone and it happens unexpectedly due to the environment, data, etc., all these aspects can play around which can cause YSOD and to debug it we would need as much of info that can lead us to root cause.

After working with multiple logging framework, I found ELMAH to be one of the best in many aspects. Here are few..

  • Easy to configure and use
  • Can be configured dynamically without re-building or re-deploying the app
  • Logs almost all the exceptions
  • affable UI to view the entire logs

Here is the basic steps to get it started.


1. Add reference - elmah.dll



2. Add the below configuration to web.config
<configuration>
 <configsections>
  <sectiongroup name="elmah">
   <section name="security" requirePermission="false" type="Elmah.SecuritySectionHandler, Elmah"></section>
   <section name="errorLog" requirePermission="false" type="Elmah.ErrorLogSectionHandler, Elmah"></section>
   <section name="errorMail" requirePermission="false" type="Elmah.ErrorMailSectionHandler, Elmah"></section>
   <section name="errorFilter" requirePermission="false" type="Elmah.ErrorFilterSectionHandler, Elmah"></section>
  </sectiongroup>
 </configsections>
 <elmah>
  <errorLog logpath="c:\logs\elmah" type="Elmah.XmlFileErrorLog, Elmah"></errorLog>
 </elmah>
 <system.web>
  <httphandlers>
   <add path="elmah.axd" type="Elmah.ErrorLogPageFactory, Elmah" verb="POST,GET,HEAD"></add>
  </httphandlers>
  <httpmodules>
   <add name="ErrorLog" type="Elmah.ErrorLogModule, Elmah"></add>
  </httpmodules>
</system.web>
</configuration>
Just these two steps would configure elmah. Note that we have specified the location to store the logfiles in the config file. The logs would be stored in .xml format. 

To get to the UI, navigate to the handler that is configured on the web.config. In this case, it would be http://localhost:*****/elmah.axd

Here is how the log UI would look like.
Here is how the UI would look when there are exceptions that are logged.
To view more details on the exception, Click on the "details" link in the error section.

Even we can use Nuget to configure elmah.
Package Manager does all the config changes. Now the application is configured to use elmah.  Isn't neat and clean?

Here is the link to elmah. The above is just a basic config of elmah and it has way more features to be explored. Go-head explore and have fun.


Happy Coding!!!  

Tuesday, February 7, 2012

Unable to generate a temporary class(result=1) - .Net


Sometimes trying to customize the configurations to fit your needs by not following the default configuration could lead us to interesting unknown specifics. This time I was meddling with the root config to redirect the temp files to be stored on f:\ rather than the default c:\.  Here is the result of doing so.



Server Error in '/XYZ/XYZZ' Application.




Server was unable to process request. ---> Unable to generate a temporary class (result=1).
error CS2001: Source file 'C:\Windows\TEMP\uao6dgcc.0.cs' could not be found
error CS2008: No inputs specified
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Web.Services.Protocols.SoapException: Server was unable to process request. ---> Unable to generate a temporary class (result=1).
error CS2001: Source file 'C:\Windows\TEMP\uao6dgcc.0.cs' could not be found
error CS2008: No inputs specified

if you need to understand the config hierarchy  - configuration file hierarchy.

The above exception clearly tells us that changes done to the root config is not enough and there are places still to look at. In most of the cases you won’t see this issue since your default directory would have the appropriate write privileges.


After researching for a while here are few things that needs to be taken care

XmlSerializer createsC# (.cs) files and compiles them into .dll files in the directory named by the TEMP environment variable; serialization occurs with those DLLs. This seems strange to me and I think the root config should have overridden this. 

For detailed info on XML Serialization

Here is the configuration that would fix it. KB Article link - http://support.microsoft.com/kb/934529


<system.xml.serialization>
<xmlSerializer tempFilesLocation="Full path of the tempfolder" />
 </system.xml.serialization>

Provide read/writeprivileges for the Temp folder to the ASPNET account. When ASP.NET Web Services process WebMethods, the identity that is used most frequently to gain access to the system Temp folder is the local ASPNET account, which is the default account under which ASP.NET applications run.


However, if you have configured your application to use impersonation in itsWeb.config file, the thread can also use the identity of any caller. If this isthe case, all potential calling identities must have read/write privileges tothe Temp folder. A likely calling identity is the Internet Information Services(IIS) application's anonymous account (typically the ISUR_xxx account).The thread may also use the IWAM_xxx account.

I have also read that precompilation of xml serialized classes could help. I haven't tried it. If you try and it worked, Please post it in the comments. Good luck with it.

Happy Coding!!!!

Tuesday, January 31, 2012

Microsoft ACE Driver


Porting an application irrespective of the hardware or an framework upgrade can teach us a lot, sometimes it can get painful to arrive at the solution that meets the recommendations from Microsoft and the clients. There are many aspects that drives the solution and for me this time it’s the “Time” and “Cost”.

I was porting an MVC app to the new server – Windows Server 2008 64bit. The application had an existing feature that reads and writes excel data to/from the database and to accomplish this JET driver were used.  An interesting fact is that the JET driver that can be used on the 32 bit server is not compatible with 64bit servers.
Here is the KB article for it - http://support.microsoft.com/kb/957570

Here are two options that can used to achieve the required functionality

  • Use Open XML to read and write to the data from the new Excel files (.xlsx format).  In this scenario, you would then need to ensure your old Excel files (.xls files) are converted to the new .xlsx file format or you would need to continue to use Jet to read and write from the .xls files, since these files are not xml based.
  • Another option would be to continue to use Jet on the Windows 2008 server.  Since Jet is a Windows component, it is still found on Windows 2008 machines.  Jet itself is being deprecated but it can still be used.  In order to use it, your client would just need to ensure their run their web application as a 32 bit application.  The only caveat to this is that Jet won’t be able to read and write from the new Excel format (.xlsx files).
          Here is the “How To” link for it. I tried this #2 and it didn't work.

None of the above options suites my needs i.e., “Time” and “Cost”. The only solution is to use the ACE driver (Microsoft.ACE.OLEDB.12.0) which is compatible with 32 and 64bit servers.

The caveat for using the ACE driver is that it could hang the IIS worker process by throwing up a message box during exceptions. IIS is not well equipped to handle those scenarios (stateless behavior) which may result in memory or performance issues.  

Here is the Data Access Road Map which talks about the JET database engine - http://msdn.microsoft.com/en-us/library/ms810810.aspx

Here is the actual driver download link – http://www.microsoft.com/download/en/details.aspx?id=13255

The download link explains the scenarios where the ACE driver is not the super best fit. The #4 was the one that explains the stateless behavior that can cause the IIS worker process to be in hung state.
  •  As a general replacement for Jet (If you need a general replacement for Jet you should use SQL Server Express Edition).
  • As a replacement for the Jet OLEDB Provider in server-side applications.
  • As a general word processing, spreadsheet or database management system -To be used as a way to create files. (You can use Microsoft Office or Office automation to create the files that Microsoft Office supports.)
  • To be used by a system service or server-side program where the code will run under a system account, or will deal with multiple users identities concurrently, or is highly reentrant and expects stateless behavior. Examples would include a program that is run from task scheduler when no user is logged in, or a program called from server-side web application such as ASP.NET, or a distributed component running under COM+ services.

All said, it’s up to the us to decide and move on. Take the path/decision that well suites your project goals.

Happy Coding!!!!