language setting for a website - c#

How can I make a website multilingual?
I want to create a website and in the home page i want the client to choose a language from English and Arabic. Then the whole website is converted to that language. What should I do to achieve this? I am creating this website in asp.net 2.0 with C#

What you're asking for is a tutorial, which you really should try googling for. Look at the links below, if there's something particular, more specific you don't understand - ask the question here.
http://www.beansoftware.com/ASP.NET-Tutorials/Globalisation-Multilingual-CultureInfo.aspx
http://www.asp.net/learn/Videos/video-40.aspx
http://www.about2findout.com/blog/2007/02/aspnet-multilingual-site_10.html
Good luck!

ASP.NET can use a number of mechanisms to change language settings - however you will need to perform the translations your self.
You could look at using Resource files for the common elements of your site - see this answer to Currency, Calendar changes to selected language, but not label in ASP.NET
However, for the main content you'd probably want to do something with the URL to ensure that your content is served correctly - the links that Honsa has supplied would be a good place to start.

Sample code i have done using resource file add global.asax
void Application_BeginRequest(Object sender, EventArgs e)
{
// Code that runs on application startup
HttpCookie cookie = HttpContext.Current.Request.Cookies["CultureInfo"];
if (cookie != null && cookie.Value != null)
{
System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(cookie.Value);
System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo(cookie.Value);
}
else
{
System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("en");
System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en");
}
}
http://satindersinght.blogspot.in/2012/06/create-website-for-multilanguage.html
http://satindersinght.wordpress.com/2012/06/14/create-website-for-multilanguage-support/
For Arabic you need to change the direction left to right

Related

How to manipulate a url to access a parent directory

I have an asp.net web application that is being hosted on an internal network. In my testing environment of course it gets hosted out on localhost:01010/Views/page.aspx. now whenever I take it live the Url changes to server_name/folder 1/folder 2/views/page.aspx. what I am trying to do is get a new page to open up as server_name/folder 1/folder 2/Uploaded_Images/randomimage.png. Now I Can get the url, but as soon as I do a single ".Remove(url.lastindexof("/")+1)" it returns "server_name/folder 1/folder 2/Views". The I perform my second ".Remove(url.lastindexof("/")+1)"
and the it only returns "server_name/". I am ripping my hair out at this one and am hoping somewhere in the world a .net developer already has this built in. Appreciate all the help.
Also just to specify this is webforms and not mvc. also there is no ajax or page manipulation going on except for a response.write to open the new page.
You don't need the +1, this works:
var url = "server_name/folder 1/folder 2/views/page.aspx";
url = url.Remove(url.LastIndexOf("/"));
url = url.Remove(url.LastIndexOf("/"));
Or you could do it like this:
var parts = url.Split('/');
var newPath = string.Join("/", parts.Take(3));
I assume you are talking about URL's used as links to parts of your site and not physical paths on the file system.
In most cases, you should be able to use methods that construct paths on the fly. For example, in any of your .aspx files (or .aspx.cs files), you can use the ResolveUrl method, like this:
Some link
If there are any places where you need the full URL including the domain (like for email notifications or something like that) then what I have done is keep a static variable accessible to my whole application that gets set the first time Application_BeginRequest runs:
void Application_BeginRequest(object sender, EventArgs e) {
if (SiteRoot == null) {
SiteRoot = HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority) +
(VirtualPathUtility.ToAbsolute("~") == "/" ? "" : VirtualPathUtility.ToAbsolute("~"));
}
}
That will pull the full URL from the Request details (the URL that the user used to access your site), without any trailing slash.

How to redirect percentage of users to a beta test web site?

First of all, we are using MVC 3, ASP.NET 4.0 and Visual Studio 2010.
Our goal is to open up our brand new web site to an open beta. We want to redirect a slowly increasing percentage of our traffic to our new site while the rest of our traffic goes to our existing site...
We were hoping to do this via a load balancer, but this is no longer an option due to resources, infrastructure and time. Right now it seems our only option is to do it via software.
Has anyone here done this? Do you have a good strategy or solution?
We will have two different URLS and we can use cookies to achieve this if needed.
It's fairly simple and would be done the same way user's are redirected to mobile site.
Implement Application_PreRequestHandlerExecute in global.asax.cs
If they fit whatever criteria you decide, Response.Redirect them. I'd store a cookie on whomever is going to stay on one site or the next so they dont erroneously get redirected while in the middle of viewing the non-beta site. This also doesn't handle the case of people not using cookies.
This is pseudo code, so it may not be 100% correct
protected void Application_PreRequestHandlerExecute(object sender, EventArgs
e)
{
if(Request.Cookies["BetaResult"] == null)
{
var cookie = new HttpCookie("BetaResult");
cookie.Expires = DateTime.Now.AddDays(1d);
if(whatever logic to redirect to beta)
{
cookie["BetaResult"] = "Beta";
Response.Cookies.Add(cookie);
Response.Redirect("your beta site");
}
else
{
cookie["BetaResult"] = "Main";
Response.Cookies.Add(cookie);
}
}
else
{
//if cookie value is beta, redirect to beta site, they 'are a chosen one'
}
}

URL Routing / rewriting in asp.net webform using c# for framework 4.0

I am working on a website which is almost complete. Website has been developed in ASP.Net, C# Framework 4.0.
I want to add a functionality for URL Routing / rewriting to make my URL more user friendly. I have found plenty of example on net but most of the examples are like http://www.example.com/phone or http://www.example.com/computer.
In my case my page is dependent on multiple query string like PageID, Language, ArticleID.
How can i convert below example URL to one as shown below
http://webd:8080/ArticleDetails.aspx?Language=en-US&PageID=19&ArticleID=18
Should be
http://webd:8080/Article/Article-title-should-appear-here.aspx
http://webd:8080/Archive.aspx?PageId=7&Language=en-US
Should be
http://webd:8080/Archive
http://webd:8080/Archive.aspx?PageId=7&Language=en-USx
Should be
http://webd:8080/الذاتية/وسوف-تذهب-المادة-الرابعة-العنوان-هنا.aspx
Yes, This is a multilingual website right now with English and Arabic version and later we need to add Spanish and the other languages also.
I have seen few examples on the net but i want some one to point me to a complete example and if it possible to have same for Arabic version of the website also.
I should be somehow able to pass Language=en-US PageID=19 ArticleID=18 and create the user friend url. I would appreciate a complete example for me to have a kick start.
In the past I've used an open-source URL rewriting component called UrlRewriter.NET, which should help you create the URL's you require.
But I have not tested this component to show Arabic.
These posts should help you in getting started if you plan on using UrlRewriter:
http://www.blogiversity.org/blogs/blogdayafternoon/archive/2008/12/18/url-rewriting-using-intelligencia-urlrewriter.aspx
http://weblogs.asp.net/scottgu/archive/2007/02/26/tip-trick-url-rewriting-with-asp-net.aspx
What actually happens is handling the Application_BeginRequest route for rewriting the url.
Add a Global.asax to your project (Global Application Class) - there are some predefined methods in that class. Use the Application_BeginRequest to rewrite your url with Context.RewritePath.
For instance based upon a datatable:
DataTable paths = BusinessLogic.Article.Path_List();
for (int i = 0; i < paths.Rows.Count; i++)
{
if (String.Compare(Request.Url.AbsolutePath.ToString(), paths.Rows[i]["ART_Path"].ToString(), true) == 0)
{
BusinessLogic.ArticleTypes aType = (BusinessLogic.ArticleTypes)Convert.ToInt32(paths.Rows[i]["ART_Type"]);
Context.RewritePath("/article.aspx?type=" + aType.ToString() + "&id=" + paths.Rows[i]["ART_ID"].ToString());
break;
}
}
Example for question:
protected void Application_BeginRequest(object sender, EventArgs e)
{
// Request.Url.AbsolutePath returns your path with preceding / -- example /default.aspx
// you do not want to hardcode this, but read it from a config file or database, but for the example it'll suffice
Dictionary<string,string> urls = new Dictionary<string,string>();
urls.Add("/Article/Article-title-should-appear-here", "/ArticleDetails.aspx?Language=en-US&PageID=19&ArticleID=18");
urls.Add("/Archive", "/Archive.aspx?PageId=7&Language=en-US");
urls.Add("/الذاتية/وسوف-تذهب-المادة-الرابعة-العنوان-هنا", "/Archive.aspx?PageId=7&Language=en-USx");
foreach (KeyValuePair<string, string> kvp in urls)
{
if (String.Compare(Request.Url.AbsolutePath, kvp.Key, true) == 0 || String.Compare(Request.Url.AbsolutePath, kvp.Key + ".aspx", true) == 0)
{
Context.RewritePath(kvp.Value);
break;
}
}
}

What would be considered the best way to architect sending email from a C# web application?

I am working on a web application that will be going live soon, and I am now trying to figure out the best way for handling sending email from the application. I understand completely HOW to send email from the application using the MailMessage and SmtpClient classes, however my question is from a different angle. My main purpose at my job before this project was support of old applications that had been developed before my time. In these applications, when they needed to send email, they hard coded any of the messages into the actual message with all of the HTML tags embeded directly into the C# code.
The application that I am working on will have a template for the emails to be sent in, as a sort of styling container, and the different messages will be embeded into the main content div's of the template. I would like to avoid hardcoding these templates in this application, so I have been trying to figure out the best way to layout my project. I have thought of using a t4 template, and reading the different t4's into the application and applying a String.Format with the specified parameters to add names/emails to the messages to be sent. However, I am not sure this is the best way to do it.
My other idea was to define a class for each type of message, however this would end up hardcoding messages again, which as I said I don't want to do.
My question is, how have you approached this in the past? What worked, and what didn't and for what reasons? I have looked all over online, but either the only content out there is on HOW to send the message, or I have not used the right Google power words.
I do it this way:
Code it the usual way with ViewModel and Razor Template
By creating the e-mail, use http://razorengine.codeplex.com/ to load and parse the template
Be aware to not use Html and Url helper if you want to send e-mails in a thread, because they rely on HttpContext which you don't have in that case. Build your own helpers if needed.
For example, if you have a ViewModel Car in your application which is displayed somewhere, you could also use this ViewModel as #model in a Razor Template for e-mail.
I've had to do this on a couple of occasions. I originally used the ASP.Net template engine based on I think a Rick Strahl blog post. It worked but there was always some issue I was banging my head against.
I switched to using the NVelocity template engine and found it a really simple way to create and maintain email templates. There are a number of other template engines and I suspect next time I might have a serious look at the Razor engine.
The code for merging values into the template:
private string Merge(ManualTypeEnum manualType, Object mergeValues)
{
var body = "";
var templateFile = string.Format("{0}MailTemplate.vm", manualType);
var velocity = new VelocityEngine();
var props = new ExtendedProperties();
props.AddProperty("file.resource.loader.path", Config.EmailTemplatePath);
velocity.Init(props);
var template = velocity.GetTemplate(templateFile);
var context = new VelocityContext();
context.Put("Change", mergeValues);
using (var writer = new StringWriter())
{
template.Merge(context, writer);
body = writer.ToString();
}
return body;
}
The values to merge are passed as an anonymous object, and can include various types including lists etc e.g.
var emailBody = Merge(newDocument.ManualType, new
{
ManualType = newDocument.ManualType.ToString(),
Message = change.Message,
NewTitle = newDocument.Title ?? "",
NewVersion = newDocument.Version ?? "",
Contact = From,
Changes = change.ToList(),
});

how to make multilingual site in asp.net

I am developing a site in asp.net in multiple languages but i didn't understand how this can be done because we can manage multilingual language by using resource files. we did this, but my major problem is that how we can change globalization at run time for a particular user. if A user choose English language then he/she can view this i English and if B user choose Spanish then he/she can view this site in Spanish. How we can do this? or how we can choose a particular language resource file???
use this code
protected override void InitializeCulture()
{
Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-US"); //'en-US' these values are may be in your session and you can use those
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");//'en-US' these values are may be in your session and you can use those
base.InitializeCulture();
}
I had this same question when i started developing multilingual sites and i found those two articles as the best starting point:
http://www.codeproject.com/KB/aspnet/localization_websites.aspx
http://www.codeproject.com/KB/aspnet/LocalizedSamplePart2.aspx
you could try something like this:
string culture = "en-US"; //could come from anything (session, database, control, etc..)
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(culture);
Thread.CurrentThread.CurrentUICulture = new CultureInfo(culture);
I think it works!
you need to use localization for language and individual resource file. Now when your site is being access at client side you need to check the locale setting on client's machine his date/time setting and the Default language ... on the basis of this you can provide language that user wish...

Categories