RSS

Tag Archives: ASP.NET

microsoft asp.net

Internationalization Aspects for Web Applications

Making web applications that supports multiple languages might be a challenging to maintain. So before building you should consider several aspects that are concerned with internationalization.

In summary very often it is not only translating the texts to other “languages” but also supporting “specific culture/locale”s as well!!!.

First of all there are certain terms that are often described when it comes to supporting multiple languages.

Internationalization (I18n)

In software applications, internationalization (often shortened to “I18N , meaning “I – eighteen letters and then a -N”) is the process of planning and implementing applications and services so that they can easily be adapted to specific local languages translations and cultures, a process called localization(which described below) which also means making your applications and services “localizable”.

In Other words the process of changing your software so that it isn’t hardwired to one language/locale/culture.

 

Localization (l10n)

The process of adding the appropriate resources to your software so that a particular language/locale is supported. This often includes adding language translation files without re-implementing/rebuilding your application.

 

Approaches to Localizing Web Applications

For web applications you can either do the translations in server side or do it in the client side. This almost always depends on the way your web application has been developed. ie. if it is a SPA application written with AngularJS then doing the translations in client side is preferable.

 

Server Side Translations for ASP.NET Applications

Obvious choice is to use the .NET framework support to create resource files(.resx) in the application and get the framework support to set CurrentCulture and CurrentUICulture for the current request thread. You need to suffix resource files with standard culture acronym and appropriate resource values will be selected by framework. Visual studio has builtin support for managing resource files.

resources

In summary “CurrentCulture” will be used for date formatting, number formatting etc. and the CurrentUICulture will be used for resource translations. You can configure the settings as following in Web.config file.

<configuration>
<system.web>
<globalization culture="auto:en-US" uiCulture="auto:fr" />
</system.web>
</configuration>

 

Use of “auto” in globalization setting.

We can set the current culture and “ui culture” as shown above with “auto” prefixed setting. when we use “auto” client user browser’s settings will be used to detect cultures and if not present will be defaulted to “en-US” and “de” in above example. This is through accept-language” request header as shown below. These settings are typically found in OS level or changeable in browser settings.

accept-language

 

Set Current Culture and Current UI Culture Programatically

For ASP.NET applications culture settings can be set at application_beginrequest or application_aquirerequeststate. This will affect all web pages unless they have been written at page level as describe below

void Application_BeginRequest(object sender, EventArgs e)
{
  Thread.CurrentThread.CurrentCulture = new System.Globalization.CreateSpecificCulture("en-US");

  Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("en-US");
}

Overriding Culture at Individual Page Level(ASP.NET Web Forms)

ASP.NET web forms has a virtual method called  “InitializeCulture” which can be overridden to change culture settings at page level as shown below.

protected override void InitializeCulture()
{
        Thread.CurrentThread.CurrentCulture = 
            CultureInfo.CreateSpecificCulture("en-US");
        Thread.CurrentThread.CurrentUICulture = new 
            CultureInfo("en-US");

        base.InitializeCulture();
}

Client Side Translations

For web applications client side translations are often done with the help of JSon files which acts as resource files.

Localization for Angular JS

Angular Js has built in support for datetime, currency simbol and number format culture support via https://docs.angularjs.org/guide/i18n. Language translations to be done easier in AngularJS, we can use https://github.com/angular-translate/angular-translate library.

In brie your angular application’s config phase you need to configure the translate provider service that provided with the library with some basic settings ie. path to language translation resources folder etc.  as shown below

function configure($logProvider, routerHelperProvider, exceptionHandlerProvider, $translateProvider) {
$translateProvider
 .addInterpolation('$translateMessageFormatInterpolation')
 .preferredLanguage('en')
 .fallbackLanguage('en')
 .useStaticFilesLoader({
 prefix: '/app/i18n/',
 suffix: '.json'
 });
}

You can maintain the translation files JSON in your project as indicated below

translation folder

translation json content

Translation JSON Example (Spanish-es)

Within the UI language translation key can be used with the directive given by the translation library as indicated below.

translation in UI

Above the “translate” is a directive given by angular translate library. “Splash_Msg” is a key in translation file which will be included in run time.

Internationalization Concerns

  • Date Time – Week month name translations should be done to support localization. It is often easier to find and use controls that supports these concerns or build your own that supports these features. When date time period calculations done it is often easier to do it with base neutral culture.
  • calendar

    French and English Language Supported Date Picker

    Bootstrap UI DateTime Picker (http://plnkr.co/edit/nLw9DMgOLDK1dTIOJq4Q?p=preview)

    Date time related concerns are probably be the most complex and challenging concern in localization. Time Zone related conversions are extremely hard to deal accurately in web applications with different locales.

  • Unit of Measure – This might be probably not very important but some parts of the world it is often specific units are being used when displaying data. e.g., in Russia, it is normal to use Russian abbreviations (in Cyrillic letters) instead of standard symbols, e.g. кг and not kg.
  • Monetary conversions – It is often useful to display monetary values with locale specific currency units or using money symbols specific to the culture. Frameworks like .NET framework and Angular l18n supports currency formatting and currency symbols but biggest concern is exchange rates.
  • Numeric Formats – In some cultures symbols have been used for different purposes. e.g. Comma and period being used  alternatively for decimals  33.3 (English) > 33,3 (German). Client side validations and server side validations should be used with care for these concerns and additional coding has to be done.
  • String translations – String translations for static string labels are relatively easier to do when it compared to culture specific formatting. Resource files with different languages are often used.

Language/Culture Selections

Culture and language selections can be done in variety of ways in web applications. It can be detected automatically based on request information or can be set by user as briefly described below.

  • Browser settings
    • accept-language http header present in request headers
    • Location of the client – Based on client request remote IP location can be detected and hence the culture can be set automatically.
  • User Selections
    • User selects language – Within the UI we can let user to select preferred language and change the language in user interface.
    • Store it in profile – Based on user registration or in user profile page we can set the language and culture.

What to Translate

  • Static Texts – Static text labels are relatively easily factored out to resource files
  • Application Data – Application data is probably one of the most difficult to be translated unless you use a dynamic translation service to translate data(e.g. Google Translate). It is difficult and inefficient to “store” these translation data and will be difficult to maintain highly changing data to be maintained with different languages unlike static text labels etc. present in a web site.
  • Error Messages – Error messages should also be translated to specific languages. Specially the client side validation script should be written to support multiple langues.
 
Leave a comment

Posted by on April 22, 2016 in .NET, AngularJs, ASP.NET, Javascript

 

Tags: , , , , ,

Configuring Redis Session State Provider With Azure

Redis is an open source (BSD licensed), in-memory data structure store, used as database, cache and message broker. Even though it has been originally developed for POSIX systems it can be easily configured to store session data in .NET with the aid of couple of nugget packages and using windows port that can be downloaded from https://github.com/MSOpenTech/redis.

One particular need you might need to store session external to webserver itself is when you have a web farm/multiple webservers with an authenticated user where subsequent requests would be redirected to different servers for example via a load balancer. Traditionally this can be solved easily with session store providers but using Redis for this can be fast and easier if you have your host system in Azure which was in my case.

To test the implementation locally for development you could do following,

  1. Download Redis port for windows from https://github.com/MSOpenTech/redis. Note: it is not available in http://redis.io site.redis windows port extract
  2. 2. Starting local Redis server is very easier as indicated below.

redis server

It will start the Redis server and note the connection details. You can change these by changing redis.conf file which is documented in the site.

e.g. https://github.com/MSOpenTech/redis/blob/2.8/redis.conf

redis server start

3. You can use various commands specified in the project site’s documentation e.g. to view session keys use command below. (not to worry on hacking my servers these are my DEV ENV values )

redis keys

4. Then you have to do install redis session state provider nugget package from https://www.nuget.org/packages/Microsoft.Web.RedisSessionStateProvider/ to your project.

5. One caveat here is to support “sliding expiration” for session state you need to make sure you install package version >=1.5.0. Sliding expiration is typically a must in session state management. Current version at the time of writing is 1.6.5 so make sure you install the latest.

6. To install RedisSessionStateProvider, run the following command in theNuget Package Manager Console of Visual Studio.

PM> Install-Package Microsoft.Web.RedisSessionStateProvider -Version {latest version number here}

7. Then all you have to do is add following configuration section in your web.config and change values accordingly.

session state config

8. After you have successfully tested it in your development environment you might need to configure Redis in windows Azure. Creating Redis Cache in Azure is super easy as shown below. At the time of writing it will be only supported in new Azure portal found in http://portal.azure.com/. Old portals does not support Azure Redis Cache.

azure redis create

azure redis create 2

9. Choose appropriate pricing tear depending your data load.

azure redis pricing

10. It will take a while to create the Redis cache. It sometimes takes more than 10 minutes to up and gets running.

redis cache creating

11. After you create Redis cache you need to configure cryptographic key and connection details for the nuget package. Selecting created Redis cache will show the access keys as below.

redis session config cryptographic keys

12. Then all you need to do is enter Access key and host name of azure redis server to the web.config. Notice how the connection details being entered, its quite different than we used earlier for local Redis server. Also note that host name given by Microsoft is always ends suffixed with cache.windows.net. So your full host name should look like someuniquename.redis.cache.windows.net. This will essentially point your session store to Azure Redis cache.

redis session config values

Note: Redis desktop manager can be used to manage Redis DB if you prefer GUI interface which can be download at http://redisdesktop.com/

redis desktop manager

 
Leave a comment

Posted by on October 20, 2015 in .NET, ASP.NET, ASP.NET MVC, Azure, C#

 

Tags: , , , , ,

Cross site request forgery (CSRF) Protection Considerations in ASP.NET Webforms and ASP.NET MVC

Cross site request forgery (CSRF) attacks or one click attacks(term being used interchangeably) are one of the most common vulnerabilities present in websites, dashboards etc. In ASP.NET MVC and ASP.NET webforms have some built in security switches you can turn on to defend against CSRF risks but still there are less known facts and caveats in this area that those built in mechanisms will not rescue. ASP.NET MVC developers think they can mitigate the risk by using [ValidateAntiForgeryToken] action filter with MVC actions. To generate the anti-XSRF tokens, call the @Html.AntiForgeryToken() method from an MVC view or @AntiForgery.GetHtml() from a Razor page. This is mostly true but there are still some risks regarding CSRF for Http “GET” requests which is really important to understand which I will be discussing below. If needed you can jump into that.

What about ASP.NET webforms? Many developers think that built in view state would mitigate CSRF risk which is absolutely not. Even though View state will make CSRF attack very little harder, it will not make it impossible. MAC encoding present in ASP.NET webforms is also to prevent viewstate tampering not to defend against CSRF. If an attacker can log in to the page by his own account but still needs to hack into some other user’s account, he can easily grab the view state for the particular page and can be used to attack target user account page action via CSRF. In theory this clearly indicate that there must be some random token not guessable in advance to defend against CSRF risk.  So general recommendation is synchroniser token pattern which used to mitigate this risk.

Does ViewStateUserKey used in ASP.NET web forms really mitigate CSRF risk?

What you can do is set ViewStateUserKey property of the web page instance to set a unique key in Page_Init event handler to associate the page’s view state with a specific authenticated user.

void Page_Init(object sender, EventArgs e)
{
  if (User.Identity.IsAuthenticated)        
  {
    ViewStateUserKey = Session.SessionID;
  }
}

When you do this malicious user cannot guess this to include in payload of “one click attack” since this value is unique to specific user. Since requests are validated against this key and exception will be thrown hence CSRF attack will be mitigated. However there are very important security breaches that can possibly arise that must remembered with this approach.

  1. ViewStateUserKey property is an extra addition to the data used in ViewState MAC calculation. If that value changes between post-backs, the ViewState Machine Authentication Code (MAC) calculation will fail hence exception will be thrown. However important bit is view state MAC validation will only be checked against for post backs. What this means is get requests are still vulnerable to “one click attacks” consider this “https://www.foo.com/deleteproducts.aspx?productid=23” this will be happily bypass View State Mac validation.
  2. Sometimes developers disable viewstate

 

Mitigating HTTP Get CSRF vulnerability?

As stated above even if you apply CSRF protection measure there still you are vulnerable to Get request associated CSRF attacks. Surprisingly this is not mentioned in many CSRF related material. Better approach is to employ combination of below or at least one of the approaches mentioned below to mitigate GET CSRF risk.

  1. One easy approach what I do believe is actions like “https://www.foo.com/deleteproducts.aspx?productid=23” will only be allowed through POST requests. But do remember to include preventive measures as stated above. Allowing only POST requests will NOT mitigate CSRF risk.
  2. Including another random secret key regenerated based on session key can also be employed so in the legitimate website links will be generated in the UI for this. Key can also be included in the cookie and hence can be verified in combination with request url verification token(This approach is known as Double submission cookies). Malicious users can’t lure legitimate users to click on links since random key is generated based on session id and should match against the cookie values. https://www.foo.com/deleteproducts.aspx?productid=23&randomkey={xxx}
  3. Only allowing requests with a referrer header from the same site is another approach. This has issues since referrer header can be legitimately altered in request propagation to the server from the user browser by firewalls, browsers proxy which can be leads to throwing off legitimate requests from server.
  4. Challenge-Response – When there is an important business transaction such as deleting products above to a get request as stated above, server can respond with another authentication response such as CAPTCHA, re-authentication with password. However using this is really impractical in most scenarios but really strong mechanism.

 

 
Leave a comment

Posted by on September 14, 2015 in ASP.NET, Security

 

Tags: ,

Pre-Bundling and Pre-Minification in ASP.NET

There are number of bundling and minification libraries available for asp.net/asp.net MVC applications. Following are few I have come across with.

• Microsoft ASP.NET Web Optimization Framework – Available as a nuget package
• WebGrease – Available as a nuget package.
• Request Reduce – Available as a nuget package, supports external resources, Also supports Less, SASS and Coffee Script.
• Packer
• Closure compiler
• JSMin
• SquishIt
• Combres
• Cassette – Also compile CoffeeScript & LESS

What is the one common limitation with these libraries?
However almost all above libraries require you to do initial bundling configuration in application before requests are being made. Then write directives in your views to render the configured bundles.
Following is what you would typically do in this instance it is ASP.NET MVC bundling… Similar kind of code needs to be put with other libraries.

public static void RegisterBundles(BundleCollection bundles)
{
     bundles.Add(new ScriptBundle(&quot;~/bundles/jquery&quot;).Include(
                 &quot;~/Scripts/jquery-{version}.js&quot;));
         // Code removed for clarity.
}

Then in your views you refer to these bundles.

 @Scripts.Render(&quot;~/bundles/jquery&quot;);

This is almost always ok but there are situations where this is not what the problem to be solved e.g. think about dynamically driven multi-site CMS handlers. These CMS handlers do host probably thousands of microsites inside their own one single abstract parent site handler. If we try to configure bundling with these it becomes impossible to use this approach or will become huge burden and will make things much slower.

I recently helped to one of my colleague to solve similar situation. Requirement was really simple in the admin panel you just select set of files for one of your micro-site and then it will generate bundled and minified output file.

Library I used for this was YUICompressor.NET which available as a nuget package. This is a .NET port of the Yahoo! UI Library’s YUI Compressor Java project. It can be installed as below to your project.

yui-compressor

You can write code similar to following to get compressed and minified output.

var cssFiles = Directory.GetFiles(Server.MapPath(&quot;~/CMSSitePath/1260/css-uploads&quot;));

StringBuilder sb = new StringBuilder();			
foreach (var cssFile in cssFiles)
{
     sb.AppendLine(System.IO.File.ReadAllText(cssFile)); //make sure using AppendLine instead of Append of string builder
}
			
var compressedCss = new CssCompressor().Compress(sb.ToString());
System.IO.File.WriteAllText(Server.MapPath(&quot;~/WebSites/1260/css/main-css.min.css&quot;), compressedCss);

As you can see above code is a very simple and naïve approach for solving the problem. Make sure to use AppnedLine of string builder instesad of Append this will be specially helpful for JavaScript otherwise you might end up with minification errors for some javsacript files. For demo purpose many additional error checks, configuration and streams has not been used. But you get the idea. Anyhow practically since the output is a bundled file that must be loadable in web browser without spending much time even the above code will be sufficient to handle production requirements no need for streams to read files (since input file contents are relatively less than 1mb most of the time).

 
Leave a comment

Posted by on June 26, 2015 in ASP.NET, ASP.NET MVC, C#

 

Tags: , , , ,

Remove unnecessary view engines if you don’t use them in ASP.NET MVC

Visual Studio 2012 MVC 4 internet project template by default supports Razor View engine out of the box where the views suffixed with cshtml extension created by default. If you further go through this route and use Razor view engine still ASP.NET MVC 4 default template uses web forms view engine by default before using Razor view engine when it comes to view resolution which has probably a little performance pay.
If you use Glimpse debugging plugin for ASP.NET MVC4 you can easily view this as shown below.
ASP.NET MVC View resolution in Glimpse

As you can see above web forms view engine by default used prior to Razor view engine. This might be a micro optimization but you should remove the web forms view engine if you are not using this as shown below or at least you should change the order if you are mostly using Razor views than web forms views.

protected void Application_Start()
		{
			AreaRegistration.RegisterAllAreas();

			WebApiConfig.Register(GlobalConfiguration.Configuration);
			FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
			RouteConfig.RegisterRoutes(RouteTable.Routes);
			BundleConfig.RegisterBundles(BundleTable.Bundles);
			AuthConfig.RegisterAuth();

			//Remove default view engines
			ViewEngines.Engines.Clear();
			// add the Razor view engine
			ViewEngines.Engines.Add(new RazorViewEngine());

		}

If you do this modification in Global.asax file you should see more efficient view resolution as shown below.
view engines in ASP.NET MVC

 
Leave a comment

Posted by on July 22, 2013 in ASP.NET, ASP.NET MVC

 

Tags: ,

Process cannot access the file error in IIS 7

One common for reason this kind of error in IIS 7 is the port used by the web site might be used by some other application in advance. One nice tool you could use to figure out what is happening here is sysinternals tcp view tool which is found here http://technet.microsoft.com/en-us/sysinternals/bb897437.

Here is how I found the culprit for the issue my laptop.

It is actually Skype which uses port 80 for its own communication so does the error comes like that in IIS. You can use the edit bindings to change the port of the website in IIS as following.

 
Leave a comment

Posted by on June 18, 2012 in ASP.NET, IIS 7

 

Tags: ,

Upgrading issue in ASP.NET 3.5 to 4 for HTML post

If you have asp.net 3.5 projects which have text boxes that allow user to enter HTML in to the text box which is very common theme in CMS systems but if you want to upgrade your project to ASP.NET 3.5 to 4.0 you might get into trouble in those pages. you might get this kind of error
“A potentially dangerous Request.Form value was detected from the client”

In .NET 3.5 you can fix similar “potentially dangerous request ” issue as following. you need to do following change


 //add ValidateRequest="false" to the web page you use html post
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication9.WebForm1" ValidateRequest="false" %>

in your web pages.

Actually if you think why this request validation is enabled by default its a good thing for applications because it is specialty use full against XSS attacks. you can find more about XSS attacks in http://ha.ckers.org/xss.html  which indicates
large amount of possible permutations and approaches for XSS attacks. So when you disalble this security feature make sure you are doing following in your code behind files etc.


// do safe checks everywhere possible when you use HTML text box values
if (this.IsPostBack)
{

this.OutputLabel.Text =
HttpUtility.HtmlEncode(
Request["InputHTMLBox"]);
}

However when after you have already done above and if you try to upgrade your application to ASP.NET 4 without additional configuration changes your application pages which do HTML post would still throw errors similar to above with “potentially dangerous request….etc etc”. Actually fix for this can be easily  seen in your dev machine by looking at Yellow screen of death(YSOD) as shown in above screenshot. You need to do following web.config change


<httpRuntime requestValidationMode="2.0" />

But like me you might think why you need to do this change in addition to the changes you had to do in ASP.NET 3.5 the reason is in ASP.NET 4.0, this protection is applied to all requests (not just .aspx pages)
and it’s fired in the BeginRequest event of HttpApplication. If you need to
revert to the old behavior, you can change it via web.config and so that your pages have a chance to disable request validation.

You can use Microsoft’s Anti-XSS Library if you need more fine grain control or you can write custom HTML post validator without reverting to old mode with a class that inherit from


System.Web.Util.RequestValidator

and specifying its name in
web.config.


<httpRuntime requestValidationType="webapp1.custHTMLPostValidator, webapp1" />

 
Leave a comment

Posted by on March 7, 2012 in ASP.NET

 

Tags: