Windows 2012 Hosting - MVC 6 and SQL 2014 BLOG

Tutorial and Articles about Windows Hosting, SQL Hosting, MVC Hosting, and Silverlight Hosting

WebMatrix Hosting - ASPHostPortal :: Using Razor, CSHTML, ASP.NET Web Pages, WebMatrix as a Web Service

clock May 23, 2011 06:12 by author Jervis

I've been trying to learn about Razor, CSHTML, ASP.NET Web Pages, and WebMatrix.  I've been writing some examples specifically targetting HTML5 mobile apps.  After all, the best way to learn a technology is to dive into it.  I wanted to call some web services in a web page, so of course, I was going to use CSHTML.  I wrote some code that didn't need any parameters, that was pretty easy.  However, what do you do when you want to pass some parameters in.  There are two solutions I can think of:

- Pass the params in the QueryString, perform a GET operation, and request the items in the CSHTML file.  This is easy, simple, and makes sense.  You code would need to protect the entries that are passed in on the url, but hey, you already know how easy it is to change them.  So, this is what I am doing here.
- Pass the params in the Body, perform a POST operation, and request the items in the CSHTML file.  This takes a little more work, but I think its a better way to do things.

I decided to pass in a GET because I just needed to do something simple and get data.  I like REST principles, but I'm no zealot that things have to be done X way.  Here's my javascript client side code using jQuery and jQuery Mobile:

function
WhereIsUserNow() {
var UserToView = "@UserToView";
$.ajax({
type: "GET",
url: "@Href("~")Services/MostRecent.cshtml?UserToView=" + UserToView,
dataType: "json",
contentType: "application/json",
success: function (outPut) {
WhereUserHasBeenMostRecent(outPut);
},
error: function (xml, err) {
alert("err:" + xml.responseText);
}
});
}
else {
alert("Please select a user before trying this tab.");
}
}


And now here's my server side cshtml code:

@{
   
    string UserName = Membership.GetUser().UserName; 
    string UserToView = Request.Params["UserToView"];
    //do a bunch of things.
    Response.Write(Json.Encode(UserNow));
}

Finally, my code will send json data out the client web browser.  Thankfully, it all seems to be working.  Probably need some added security somewhere, but who doesn't. 

Hope this brief tutorial can help. If you’re looking for CSHTML and webmatrix hosting, please visit our site for further information. If you have any question about webmatrix hosting, please don’t hesitate to contact us at [email protected].

Reasons why you must trust ASPHostPortal.com

Every provider will tell you how they treat their support, uptime, expertise, guarantees, etc., are. Take a close look. What they’re really offering you is nothing close to what ASPHostPortal does. You will be treated with respect and provided the courtesy and service you would expect from a world-class web hosting business.


You’ll have highly trained, skilled professional technical support people ready, willing, and wanting to help you 24 hours a day. Your web hosting account servers are monitored from three monitoring points, with two alert points, every minute, 24 hours a day, 7 days a week, 365 days a year. The followings are the list of other added- benefits you can find when hosting with us:

- DELL Hardware
Dell hardware is engineered to keep critical enterprise applications running around the clock with clustered solutions fully tested and certified by Dell and other leading operating system and application providers.
- Recovery Systems
Recovery becomes easy and seamless with our fully managed backup services. We monitor your server to ensure your data is properly backed up and recoverable so when the time comes, you can easily repair or recover your data.
- Control Panel
We provide one of the most comprehensive customer control panels available. Providing maximum control and ease of use, our Control Panel serves as the central management point for your ASPHostPortal account. You’ll use a flexible, powerful hosting control panel that will give you direct control over your web hosting account. Our control panel and systems configuration is fully automated and this means your settings are configured automatically and instantly.
- Excellent Expertise in Technology
The reason we can provide you with a great amount of power, flexibility, and simplicity at such a discounted price is due to incredible efficiencies within our business. We have not just been providing hosting for many clients for years, we have also been researching, developing, and innovating every aspect of our operations, systems, procedures, strategy, management, and teams. Our operations are based on a continual improvement program where we review thousands of systems, operational and management metrics in real-time, to fine-tune every aspect of our operation and activities. We continually train and retrain all people in our teams. We provide all people in our teams with the time, space, and inspiration to research, understand, and explore the Internet in search of greater knowledge. We do this while providing you with the best hosting services for the lowest possible price.
- Data Center
ASPHostPortal modular Tier-3 data center was specifically designed to be a world-class web hosting facility totally dedicated to uncompromised performance and security
- Monitoring Services
From the moment your server is connected to our network it is monitored for connectivity, disk, memory and CPU utilization – as well as hardware failures. Our engineers are alerted to potential issues before they become critical.
- Network
ASPHostPortal has architected its network like no other hosting company. Every facet of our network infrastructure scales to gigabit speeds with no single point of failure.
- Security
Network security and the security of your server are ASPHostPortal’s top priorities. Our security team is constantly monitoring the entire network for unusual or suspicious behavior so that when it is detected we can address the issue before our network or your server is affected.
- Support Services
Engineers staff our data center 24 hours a day, 7 days a week, 365 days a year to manage the network infrastructure and oversee top-of-the-line servers that host our clients’ critical sites and services.



WebMatrix Hosting - ASPHostPortal :: Surfacing the Visual Basic Templates in WebMatrix

clock May 19, 2011 06:14 by author Jervis

When you first launch WebMatrix 1.0 after installing it, you see a screen as shown in Figure 1.



Choosing the "Site From Template" option, you see the screen shown in Figure 2. Each of these templates are C# site templates.



WebMatrix supports Web site development in both C# and Visual Basic, so where are the Visual Basic templates? I expected to see a screen with templates for both languages. In this article, I demonstrate the steps needed to create the screen shown in Figure 3. This allows the creation of Visual Basic sites from templates as easily as C# sites, based on the site templates available from Microsoft at the time of this writing (March 2011).

If the C# templates are still Version 1.0 and you are just interested in installing the additional VB 1.0 templates, then download the code from this article's Web page and follow the directions in the ReadMe.txt file in the download. If the templates have been updated or new templates have been added, you may need to follow the steps in this article to create a new "Site From Template" page in order to include those new elements, especially to update the SHA1 checksums in the TemplateFeed.xml file in the Micrososft WebMatrix templates folder.



The Visual Basic templates were released later, on Monday February 7, 2011 as a
NuGet package. NuGet is a Visual Studio extension that makes it easy to install and update open source libraries and tools.

Since NuGet is an extension, it must be run within WebMatrix or Visual Studio and does not appear in the computer's Start menu. In WebMatrix, it must run from the Administration page of a site as shown in Figure 4. I used the Starter Site template.



Selecting that option for the first time will lead to prompts to create a site administration password. Follow the prompts to create the site administration password. Log onto the site administration page with the newly created password and then search for "VB". You will see a page similar to Figure 5 that will allow you to download each of the VB site templates



After installing each one, by default they will appear in the {My Documents}\My Web Sites\{Site Name}\Microsoft Templates\ folder. To use any of these templates to create Visual Basic sites, as provided by Microsoft, you have to create an "Empty Site" as shown in Figure 2. Then you must copy the contents of one of these Microsoft Templates folders to the root of the Empty Web site.

I know that WebMatrix is a v1.0 product, and I'm grateful that Visual Basic templates are available, but I can't help but think, "Give me a break. Are you serious Microsoft?" C# developers can simply pick a template from a main menu, but Visual Basic developers have to go through this much convoluted effort? No wonder Visual Basic developers sometimes feel like second-class citizens in the Microsoft ecology.

To create the screen shown in Figure 3, we have to accomplish the following tasks. They are more steps than I would like, but hopefully they are easy to follow. Note that Administrator access is required since it involves changes to the C:\Program Files\Microsoft WebMatrix\templates\ folder. If you are on a 64-bit version of Windows, that path would be C:\Program Files (x86)\Microsoft WebMatrix\templates\.

1. Download the Visual Basic templates into a WebMatrix site.
2. Create the same folder structure and metadata files as the C# templates.
3. Create zip files from Step 2, with a VB suffix so they can later co-exist in the templates folder.
4. Compute the SHA1 checksum for each of the VB template files.
5. Modify the TemplateFeed.xml file in the Microsoft WebMatrix\templates folder to include the VB templates.
6. Copy the updated VB template zip files and updated TemplateFeed.xml file into the WebMatrix\templates folder.

For Step 1, assuming you have been following along so far, it has been completed.

For Step 2, create a "temp" working folder where you have update rights. See
Listing 1 for a complete directory listing of the results of Step 2 for reference.

Copy the Microsoft WebMatrix\templates folder into this temp folder. Copy the Microsoft Templates folder with the downloaded VB 1.0 templates into your temp folder. In the temp\Microsoft Templates folder, remove the spaces from the folder names and delete the License.rtf and README.txt files. You will have only four folders: BakeryVB, CalendarB, PhotoGalleryVB, StarterSiteVB.

Within each of those folders, create a folder named the same without the VB suffix and copy all the files into that folder. Example: you will have a temp\Microsoft Templates\BakeryVB\Bakery folder that contains all the files that were in temp\Microsoft Templates\BakeryVB folder.

Next extract the parameters.xml and manifest.xml files from the root of the corresponding C# template zip files and place them in the corresponding temp\Microsoft Templates\{site}VB\{site} folder. Example: temp\Microsoft Templates\BakeryVB\ folder will now have the parameters.xml and manifest.xml files from the \temp\templates\Bakery.zip file. You may find the open source 7-Zip utility available from 7-zip.org helpful in this and subsequent processes. See 
Listing 1 for a sample of the final folder/file structure.

For Step 3, create separate zip files of the contents of each of the temp\Microsoft Templates\{site}VB\ folders. Be sure to create the zip files such that the manifest.xml and parameters.xml and {site} folder are at the root of the zip file. Name these zip files the same as their parent folder with the zip extension. Example: temp\Microsoft Templates\BakeryVB\ will contain a BakeryVB.zip file that contains exactly the contents of the temp\Microsoft Templates\BakeryVB folder. See 
Listing 2 for a sample final result.

For Step 4, use the File Checksum Integrity Verifier (FCIV.exe) utility available from Microsoft
here. Download and extract the fciv.exe utility and place in the C:\Windows folder so it can be available for use from any folder. Open a DOS Command window, navigate to the {My Documents}\temp folder and issue the following command:

fciv -add "Microsoft Templates" -r -type *.zip

Note the SHA1 values that are generated for each of the zip files you created.

For step 5, make a backup copy of the file TemplateFeed.xml file located in the temp\templates folder. Use notepad or your favorite editor to update the TemplateFeed.xml file with four new application sections, one for each of the VB template zip files. Simply copy the C# application section and modify the underlined locations as shown in the code below. The Code Download has the fully updated TemplateFeed.xml file for your reference.

<entry type="application">
    <productId>BakeryVB</productId>
    <title resourceName="Entry_BakeryVB_Title">Bakery VB</title>
    <version>1.0</version>
    <summary resourceName="Entry_BakeryVB_Summary">
Sample web site in VB showing a list of products that can be ordered.</summary>
    <id>http://www.microsoft.com/web/webstack/bakery</id>
    <updated>2010-3-24T18:30:02Z</updated>
    <published>2010-03-24T18:30:02Z</published>
    <longSummary resourceName="Entry_BakeryVB_LongSummary">
Sample web site in VB showing a list of products that can be ordered.</longSummary>
    <link href="http://microsoft.com/web/webstack/bakery" />
    <images>
      <icon>http://go.microsoft.com/fwlink/?LinkId=195175</icon>
    </images>
    <keywords>
      <keywordId>Templates</keywordId>
    </keywords>
    <author>
      <name>Microsoft</name>
      <uri>http://www.microsoft.com/</uri>
    </author>
    <installers>
      <installer>
        <id>1</id>
        <languageId>en</languageId>
        <installerFile>
          <fileSize>50</fileSize>
          <installerURL>file://%ProgramFiles%\Microsoft WebMatrix\templates\BakeryVB.zip</installerURL>
          <sha1>d40bbb4eb23bda648a95c0841e7d762d57d6c372</sha1>
        </installerFile>
        <msDeploy />
      </installer>
    </installers>
  </entry>

For Step 6, backup the existing TemplateFeed.xml file at {Program Files}\Microsoft WebMatrix\templates and overwrite it with your modified TemplateFeed.xml file. Also copy in the VB template zip files created in step 3. If all the steps were performed correctly, WebMatrix will show a screen similar to Figure 3 when "Site From Template" is selected.


Conclusion
Microsoft WebMatrix is an exciting product that makes the creation of custom ASP.NET Web sites possible without all the complexity of the full Visual Studio environment. Another advantage is the ability to easily leverage proven applications from the Web Gallery. WebMatrix also demonstrates Microsoft's commitment to open source by including PHP and MySQL applications in the Web Gallery.

Microsoft WebMatrix has great potential, but it is a version 1.0 release and it shows when it comes to Visual Basic template support. The steps needed to surface the Visual Basic templates in the Site From Template screen are overly complex. Microsoft should provide an independent installer package that integrates the Visual Basic site templates with a single command, so that both C# and Visual Basic templates are presented equally.


And now, you can get this potensial product on our site. We have supported Microsoft WebMatrix hosting with only $5.00/month. Shoud you have further question about this product, please always feel free to email us at [email protected] or here.



WebMatrix Hosting - ASPHostPortal :: What is WebMatrix?

clock May 16, 2011 08:44 by author Jervis

What is WebMatrix?

Last week, ASPHostPortal has just launched their new product called WebMatrix. And the question is what is WebMatrix? WebMatrix is a free, lightweight Web development stack that makes it easy to build web sites that can grow with you, from installation to product deployment & maintenance.  Developers can take advantage of mastering fundamental concepts of building apps for the web by using WebMatrix. Microsoft’s WebMatrix is very powerful and easiest tools that include everything need to develop a website and all are free. It is windows application which can run in both windows and Linux environment.



It is a new lightweight web development tool that also integrates the above technologies, and makes it even easier for people to get started with web development using ASP.NET. If you are developing small applications to your office by using scripts or VBA then WebMatrix can be a good option, but if you are developing a enterprise applications then it’s better to stick with your current technology. By using this you can start web development easily it is task focused tool, which is just 15 in Size.

It supports HTML5

WebMatrix includes built-in publishing support that makes it easy to deploy Web sites and Web applications to remote hosters. WebMatrix supports using FTP and FTP/SSL as well as the Microsoft Web Deploy (aka MSDeploy) infrastructure. FTP and FTP/SSL enable you to easily publish the local files of your site over to a remote server.

Who’s it for?

If you’re writing classic ASP or PHP sites, WebMatrix makes it more than easy to transition seamlessly over to the ASP.NET development stack.  If you’re new to web development in general, WebMatrix will be a big win for you too, as it makes it easy to build simple brochure and data-driven modular sites.  Web Pages built with the Razor view engine/syntax can also be edited in notepad, and don’t need to be compiled like you would with ASP.NET Web Forms or MVC.


For those of you already working in Visual Studio, you’ll be able to jump right in without a learning curve.  That’s great for those times when you need to work with the Office/scripting developers who would use WebMatrix as their primary tool or when building lightweight sites.

What’s in the WebMatrix download?

The WebMatrix download size is small at about 15Mb, and takes about 5 minutes to install.  In the download, you’ll get IIS Developer Express, SQL Compact Edition & the ASP.NET Razor View Engine, along with access to an OSS web application gallery and integration with web hosting providers.  By downloading the Web Platform Installer you have everything in one package that you need to create & publish rich web sites simply and quickly.  It’s really nice to finally have a complete package with all the tools in it rather than spending time finding multiple products to have to download, install and configure.

Conclusion

Now, if you want to get all this news features with very low cost, you can visit our site. We can guarantee  you that we have supported WebMatrix hosting.

Reasons why you must trust ASPHostPortal.com

Every provider will tell you how they treat their support, uptime, expertise, guarantees, etc., are. Take a close look. What they’re really offering you is nothing close to what ASPHostPortal does. You will be treated with respect and provided the courtesy and service you would expect from a world-class web hosting business.

You’ll have highly trained, skilled professional technical support people ready, willing, and wanting to help you 24 hours a day. Your web hosting account servers are monitored from three monitoring points, with two alert points, every minute, 24 hours a day, 7 days a week, 365 days a year. The followings are the list of other added- benefits you can find when hosting with us:

- DELL Hardware
Dell hardware is engineered to keep critical enterprise applications running around the clock with clustered solutions fully tested and certified by Dell and other leading operating system and application providers.
- Recovery Systems
Recovery becomes easy and seamless with our fully managed backup services. We monitor your server to ensure your data is properly backed up and recoverable so when the time comes, you can easily repair or recover your data.
- Control Panel
We provide one of the most comprehensive customer control panels available. Providing maximum control and ease of use, our Control Panel serves as the central management point for your ASPHostPortal account. You’ll use a flexible, powerful hosting control panel that will give you direct control over your web hosting account. Our control panel and systems configuration is fully automated and this means your settings are configured automatically and instantly.
- Excellent Expertise in Technology
The reason we can provide you with a great amount of power, flexibility, and simplicity at such a discounted price is due to incredible efficiencies within our business. We have not just been providing hosting for many clients for years, we have also been researching, developing, and innovating every aspect of our operations, systems, procedures, strategy, management, and teams. Our operations are based on a continual improvement program where we review thousands of systems, operational and management metrics in real-time, to fine-tune every aspect of our operation and activities. We continually train and retrain all people in our teams. We provide all people in our teams with the time, space, and inspiration to research, understand, and explore the Internet in search of greater knowledge. We do this while providing you with the best hosting services for the lowest possible price.
- Data Center
ASPHostPortal modular Tier-3 data center was specifically designed to be a world-class web hosting facility totally dedicated to uncompromised performance and security
- Monitoring Services
From the moment your server is connected to our network it is monitored for connectivity, disk, memory and CPU utilization – as well as hardware failures. Our engineers are alerted to potential issues before they become critical.
- Network
ASPHostPortal has architected its network like no other hosting company. Every facet of our network infrastructure scales to gigabit speeds with no single point of failure.
- Security
Network security and the security of your server are ASPHostPortal’s top priorities. Our security team is constantly monitoring the entire network for unusual or suspicious behavior so that when it is detected we can address the issue before our network or your server is affected.
- Support Services
Engineers staff our data center 24 hours a day, 7 days a week, 365 days a year to manage the network infrastructure and oversee top-of-the-line servers that host our clients’ critical sites and services.



Press Release - ASPHostPortal Offers Microsoft Web Matrix Hosting

clock May 13, 2011 06:36 by author Jervis

ASPHostPortal is a premiere web hosting company that specialized in Windows and ASP.NET-based hosting. ASPHostPortal has proved its existence in hosting company by supports the new Microsoft Web Matrix Hosting. This application is pre-installed on the server and it allows you to install several world-class favorites application, such as DotNetNuke, nopCommerce, etc. For more information about this new product, please visit http://www.asphostportal.com.

It mentions that WebMatrix installs in minutes and incorporates a web server, database, and programming framework in an all-in-one integrated experience. WebMatrix will streamline the coding, testing, and deployment of any ASP.net website, and also pre-configures and installs the most popular open source applications, including WordPress, DotNetNuke, Umbraco and Joomla! WebMatrix also integrates the Web Application Gallery and Web Application Installer from Microsoft, enabling developers who use PHP, MySQL or other web development components to download, install and configure these components directly from WebMatrix.

"The launch of Web Matrix hosting illustrates the power and existence of the ASPHostPortal," said CEO of ASPHostPortal.com, Robert Kruger. "We are very pleased with this launch of new product for all our new and existing customer. The launch of this product signifies that we always follow the development of existing technology and we always strive to provide the best for our customers as our motto 'do good things and good things will come to you'."

"With Web Matrix technology, you will feel how easy it is to develop your website. Just start from open source web applications, built-in web templates or just start writing code yourself, very simple." said Dean Thomas, General Manager of ASPHostPortal.com.

About ASPHostPortal.com:

ASPHostPortal.com is a hosting company that best support in Windows and ASP.NET-based hosting. ASPHostPortal.com have many great plans that can meet your business requirement. For more details about ASPHostPortal.com, please visit the official site at
http://www.asphostportal.com



ASP.NET MVC Hosting - ASPHostPortal :: Create ASP.NET MVC Localization with Language Detection

clock January 6, 2011 05:09 by author Jervis

In this tutorial I will show a simple way to create localization (globalization) for web application using APS.NET MVC framework. It should work fine with MVC 1 and 2 and I’m currently using .NET 3.5 SP1, but .NET 4.0 will work as well. All code is in C# and for language translations I use XML files.

Language files with XML


For translations of different languages I use simple xml files. I store them in App_Data/messages/<locale>.xml, for example en-US.xml or de-DE.xml. Here is the xml structure:

<items>
  <item key="home">Home</item>
  <item key="products">Products</item>
  <item key="services">Services</item>
</items>

You should have identical language files for all desired languages. All translation items should be the same (with equal “key” attributes).

Create Translator class

Main translation work will be done by Translator singleton class. Create “Infrastructure” folder in your MVC project and put class Translator there.
First, let’s make class singleton:


private static Translator instance = null;
public static Translator Instance
{
    get
    {
        if (instance == null)
        {
            instance = new Translator();
        }
        return instance;
    }
}
private Translator() { }

Add the following fields and properties to the class:

private static string[] cultures = { "en-US", "bg-BG" };
private string locale = string.Empty;

public string Locale
{
    get
    {
        if (string.IsNullOrEmpty(locale))
        {
            throw new Exception("Locale not set");
        }
        else
        {
            return locale;
        }
    }
    set
    {
        if (Cultures.Contains(value))
        {
            locale = value;
            load();
        }
        else
        {
            throw new Exception("Invalid locale");
        }
    }
}

public static string[] Cultures
{
    get
    {
        return cultures;
    }
}

Field "cultures" lists available cultures. "Locale" keeps current culture. And in "set" part of Locale property you can see invocation of load() method. I will talk about it later.
To keep localization data I will create simple dictionary and then use keys from XML for dictionary keys and XML item values as dictionary values. Simple Translate method will do translation job. I have indexer method for easy access.


private Dictionary data = null;

public string Translate(string key)
{
    if (data != null && data.ContainsKey(key))
    {
        return data[key];
    }
    else
    {
        return ":" + key + ":";
    }
}

public string this[string key]
{
    get
    {
        return Translate(key);
    }
}

If some key cannot be found and translated, I return the key with ":" around it, so you can easy find untranslated items.
Finally, for loading XML I use LINQ to XML. I have static caching dictionary, so I don't need reading XML on every request.


private static Dictionary<string, Dictionary<string, string>> cache =
  new Dictionary<string, Dictionary<string, string>>();

private void load()
{
    if (cache.ContainsKey(locale) == false) // CACHE MISS !
    {
        var doc = XDocument.Load(
            HttpContext.Current.Server.MapPath(
               "~/App_Data/messages/" + locale + ".xml"))

        cache[locale] = (from item in doc.Descendants("item")
                         where item.Attribute("key") != null
                         select new
                         {
                             Key = item.Attribute("key").Value,
                             Data = item.Value,
                         }).ToDictionary(i => i.Key, i => i.Data);
    }

    data = cache[locale];
}

public static void ClearCache()
{
    cache = new Dictionary<string, Dictionary<string, string>>();
}

You can use translator in your controller like this:
Translator.Instance[key];
After load() methid I have ClearCache method for easy developing (you know, once read, data is cached and you have to restart IIS Application Pool to refresh localization data).
Translator class is ready, I will show you how to use it later.


Create localization helpers

Create static class LocalizationHelpers and put it in "Helpers" folder in your project.

public static string CurrentCulture(this HtmlHelper html)
{
    return Translator.Instance.Locale;
}

public static string T(this HtmlHelper html, string key)
{
    return html.Encode(Translator.Instance[key]);
}

public static string T(this HtmlHelper html, string key,
    params object[] args)
{
    return html.Encode(string.Format(
        Translator.Instance[key], args));
}

I will use this in html views for translation like this

<%= Html.T("products") %>

If you want params in translated values you can use second T implementation like string.Format. First helper CurrentCulture is used in language select user control to determine current culture.

Create BaseController class

Create BaseController class that extends Controller and put it in "Infrastructure" folder of your MVC project. You should extend all your controller classes from this class. Create simple property for current selected culture (locale)

public string CurrentCulture
{
    get
    {
        return Translator.Instance.Locale;
    }
}

You will use this in your controller when you initialize your model, for example.
In the following code I will explain language detection and saving with cookie.


private void initCulture(RequestContext requestContext)
{
    string cultureCode = getCulture(requestContext.HttpContext);

    requestContext.HttpContext.Response.Cookies.Add(
        new HttpCookie("Culture", cultureCode)
        {
            Expires = DateTime.Now.AddYears(1),
            HttpOnly = true,
        }
    );

    Translator.Instance.Locale = cultureCode;

    CultureInfo culture = new CultureInfo(cultureCode);
    System.Threading.Thread.CurrentThread.CurrentCulture = culture;
    System.Threading.Thread.CurrentThread.CurrentUICulture = culture;
}

private string getCulture(HttpContextBase context)
{
    string code = getCookieCulture(context);

    if (string.IsNullOrEmpty(code))
    {
        code = getCountryCulture(context);
    }

    return code;
}

private string getCookieCulture(HttpContextBase context)
{
    HttpCookie cookie = context.Request.Cookies["Culture"];

    if (cookie == null || string.IsNullOrEmpty(cookie.Value) ||
         !Translator.Cultures.Contains(cookie.Value))
    {
        return string.Empty;
    }

    return cookie.Value;
}

private string getCountryCulture(HttpContextBase context)
{
    // some GeoIp magic here
    return "en-US";
}

First I try to get language cookie if there is any (if this is not first time visit). If there is no cookie you can detect browser language, make GeoIP IP address lookup and so on. After finding some valid locale/culture I set response cookie for next page visits. After this I change current thread culture. This is useful if you want to format some date or currency values.
You should call initCulture in overridden Initialize method.


Changes in HomeController

Don't forget to change parent class of all your controller to BaseController. Add following code to your HomeController, so you can change current culture. When you open specified URL, a cookie is set and user is redirected to index page. This URL is like example.com/home/culture/en-US. Clear cache method is for deleting current cache without restarting application pool. Access it with example.com/home/ClearLanguageCache.

public ActionResult Culture(string id)

{
    HttpCookie cookie = Request.Cookies["Culture"];
    cookie.Value = id;
    cookie.Expires = DateTime.Now.AddYears(1);
    Response.SetCookie(cookie);

    return Redirect("/");
}

public ActionResult ClearLanguageCache(string id)
{
    Translator.ClearCache();

    return Redirect("/");
}

To change current language I will create special user control which will be included in may Master.Site layout. Create CultureUserControl.ascx and put it in Views/Shared/ folder of your MVC project. Here is the code:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>

<% if (Html.CurrentCulture() == "bg-BG") { %>
    <a id="lang" href="/home/culture/en-US">en</a>
<% } else { %>
    <a id="lang" href="/home/culture/bg-BG">bg</a>
<% } %>

In my layout I use <% Html.RenderPartial("CultureUserControl"); %> to include it.

Conclusion

In this simple tutorial I've created localization infrastructure for ASP.NET MVC web application. Translations of different languages are stored in XML files. Then I use Translator class to load them. Current user culture is kept in cookie. You can access Translator class in html views using some helpers. Also all the translation data i cached so it will not be loaded form XML every request.
Hope this tutorial helps.


Reasons why you must trust ASPHostPortal.com

Every provider will tell you how they treat their support, uptime, expertise, guarantees, etc., are. Take a close look. What they’re really offering you is nothing close to what ASPHostPortal does. You will be treated with respect and provided the courtesy and service you would expect from a world-class web hosting business.

You’ll have highly trained, skilled professional technical support people ready, willing, and wanting to help you 24 hours a day. Your web hosting account servers are monitored from three monitoring points, with two alert points, every minute, 24 hours a day, 7 days a week, 365 days a year. The followings are the list of other added- benefits you can find when hosting with us:

- DELL Hardware
Dell hardware is engineered to keep critical enterprise applications running around the clock with clustered solutions fully tested and certified by Dell and other leading operating system and application providers.
- Recovery Systems
Recovery becomes easy and seamless with our fully managed backup services. We monitor your server to ensure your data is properly backed up and recoverable so when the time comes, you can easily repair or recover your data.
- Control Panel
We provide one of the most comprehensive customer control panels available. Providing maximum control and ease of use, our Control Panel serves as the central management point for your ASPHostPortal account. You’ll use a flexible, powerful hosting control panel that will give you direct control over your web hosting account. Our control panel and systems configuration is fully automated and this means your settings are configured automatically and instantly.
- Excellent Expertise in Technology
The reason we can provide you with a great amount of power, flexibility, and simplicity at such a discounted price is due to incredible efficiencies within our business. We have not just been providing hosting for many clients for years, we have also been researching, developing, and innovating every aspect of our operations, systems, procedures, strategy, management, and teams. Our operations are based on a continual improvement program where we review thousands of systems, operational and management metrics in real-time, to fine-tune every aspect of our operation and activities. We continually train and retrain all people in our teams. We provide all people in our teams with the time, space, and inspiration to research, understand, and explore the Internet in search of greater knowledge. We do this while providing you with the best hosting services for the lowest possible price.
- Data Center
ASPHostPortal modular Tier-3 data center was specifically designed to be a world-class web hosting facility totally dedicated to uncompromised performance and security
- Monitoring Services
From the moment your server is connected to our network it is monitored for connectivity, disk, memory and CPU utilization – as well as hardware failures. Our engineers are alerted to potential issues before they become critical.
- Network
ASPHostPortal has architected its network like no other hosting company. Every facet of our network infrastructure scales to gigabit speeds with no single point of failure.
- Security
Network security and the security of your server are ASPHostPortal’s top priorities. Our security team is constantly monitoring the entire network for unusual or suspicious behavior so that when it is detected we can address the issue before our network or your server is affected.
- Support Services
Engineers staff our data center 24 hours a day, 7 days a week, 365 days a year to manage the network infrastructure and oversee top-of-the-line servers that host our clients’ critical sites and services.



About ASPHostPortal.com

We’re a company that works differently to most. Value is what we output and help our customers achieve, not how much money we put in the bank. It’s not because we are altruistic. It’s based on an even simpler principle. "Do good things, and good things will come to you".

Success for us is something that is continually experienced, not something that is reached. For us it is all about the experience – more than the journey. Life is a continual experience. We see the Internet as being an incredible amplifier to the experience of life for all of us. It can help humanity come together to explode in knowledge exploration and discussion. It is continual enlightenment of new ideas, experiences, and passions

 photo ahp banner aspnet-01_zps87l92lcl.png

Author Link

Corporate Address (Location)

ASPHostPortal
170 W 56th Street, Suite 121
New York, NY 10019
United States

Sign in