Multiple Languages - Language files OR Langages Database? - localization

I'm developing a website from scratch. It supposed to be a multi-lang website.
My question is, how should I do that?
Manage language files or manage language database tables?
I'm using MySQL, it you need to know.

You can do either way, it is a choice of opinion. I prefer files, because from my sight they are easier to translate and because of that you can even let other people without so much technical know-how do the translation of the files :)

i recommend using a file "StringManager Class"
public static final String stringManagerBinFile = "/StringManager_en.data";
public static final int ABOUT = 0;
public static final int ACCOUNT = 1;
public static final int PASS = 2;
public static final int CONTACT = 3;
......
public static String getData (int header) {
//Load string from stringManagerBinFile, if user change language, you might be change stringManagerBinFile PATH
}
In your code you can use:
String about = getData(ABOUT);
//repaint your GUI

Related

Load Tests, trying to generate random names but getting same names for many virtual users

I'm using Visual Studio Performance Tests. I want to generate a random name before each of my requests. I'm using this WebTestRequestPlugin for that:
using System;
using System.ComponentModel;
using System.Linq;
using Microsoft.VisualStudio.TestTools.WebTesting;
namespace TransCEND.Tests.Performance.Plugins
{
public class RandomStringContextParameterWebRequestPlugin : WebTestRequestPlugin
{
[Description("Name of the Context Paramter that will sotre the random string.")]
[DefaultValue("RandomString")]
public string ContextParameter { get; set; }
[Description("Length of the random string.")]
[DefaultValue(10)]
public int Length { get; set; }
[Description("Prefix for the random string.")]
[DefaultValue("")]
public string Prefix { get; set; }
private readonly string _chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
private Random _random = new Random();
public RandomStringContextParameterWebRequestPlugin()
{
ContextParameter = "RandomString";
Prefix = "";
Length = 10;
}
public override void PreRequestDataBinding(object sender, PreRequestDataBindingEventArgs e)
{
e.WebTest.Context[ContextParameter] = CreateNewRandomString();
base.PreRequestDataBinding(sender, e);
}
private string CreateNewRandomString()
{
var randomString = new string(Enumerable.Repeat(_chars, Length).Select(s => s[_random.Next(s.Length)]).ToArray()).ToLower();
return $"{Prefix}{randomString}";
}
}
}
My problem is that when I start a load test with multiple virtual users, the preRequest code runs for the first few users immediately, rewriting the RandomName context parameter on every run. So when my requests are actually running, they are using the same random name, causing a conflict in my back-end code.
My question is how can I generate random names for each of my requests even when the user load is high?
I think the problem is that the standard random number routines are not thread safe. Thus each virtual user (VU) gets the same random seed value and hence the same random numbers. See here and here for fuller explanations.
The code for CreateNewRandomString is not shown in the question but it probably uses the basic C# random number code which has the problem described above. The solution is to use a safer random number. This question provides some ideas on better random number generators.
I have used code based on the following in several performance tests:
public static class RandomNumber
{
private static Random rand = new Random(DateTime.Now.Millisecond);
private static object randLock = new object();
/// <summary>
/// Generate a random number.
/// </summary>
/// <param name="maxPlus1">1 more than the maximum value wanted.</param>
/// <returns>Value between 0 and maxPlus1-1 inclusive. Ie 0 .le. returned value .lt. maxPlus1</returns>
public static int Next(int maxPlus1)
{
int result;
lock (randLock)
{
result = rand.Next(maxPlus1);
}
return result;
}
}
It should be simple to add a string creation method to the above code, something that generates the wanted string within a lock{ ... } statement.
The part of the question that states "rewriting the RandomName context parameter on every run. So when my requests are actually running, they are using the same random name" is misunderstanding what is happening. Each VU gets its own set of CPs, it is just that the random numbers are the same.

Constructor not created in proxy class with Add Service Reference

I have created a web service with ServiceStack which returns List<SyncUserDTO>.
It has more properties, but I simplified it to one field, Timestamp.
[DataContract]
public class SyncUserDTO
{
public SyncUserDTO()
{
Timestamp = new TimestampDTO();
}
[DataMember(Order = 1)]
public TimestampDTO Timestamp { get; set; }
}
[DataContract]
public class TimestampDTO
{
[DataMember]
public bool DataValid { get; set; }
[DataMember]
public DateTime? Value { get; set; }
}
The service seems to work perfectly (with other tests), but when I create a client console application and Add Service Reference, the SyncUserDTO does not have the constructor, meaning this doesn't work:
static void SendUsersServiceReference()
{
var users = new List<SyncUserDTO>();
for (var i = 0; i < 5; i++)
{
var user = new SyncUserDTO();
user.Timestamp.Value = DateTime.Now; // NullReferenceException,
user.Timestamp.DataValid = true; // as Timestamp is null
}
}
When pressing F12 on SyncUserDTO, I can't seem to find any Constructor method in Reference.cs, explaining why the above doesn't work.
But why is the constructor not created in my proxy classes in the client application?
I need to do the "construction" myself in the client, and then it works:
var user = new SyncUserDTO() { Timestamp = new TimestampDTO() };
Of cause, I don't want the people who consumes my service to have to create this themselves. They should really note care about the underlying TimestampDTO. The constructor should do this.
Btw, I searched Google and SO for terms like "Constructor not created in proxy class with Add Service Reference" with and without "ServiceStack", no results to aid me in this quest...
Pps. Demis (ServiceStack), if you're reading this, yes SOAP is on the way out, REST is the new black - but I want to support both, which it seems like ServiceStack does, which is really great. I love ServiceStack :D
try to instanciate your property by the time you are going to access it, I know that´s a workaround but it could be convenient in your scenario.
private TimestampDTO _timestamp;
public TimestampDTO Timestamp
{
get
{
if(_timestamp==null) _timestamp=new TimestampDTO();
return _timestamp;
}
set
{
_Timestamp=value;
}
}
This is my solution (for now):
I created a new service method in my service, where the client gets a new UserDTO complete with all fields. This way, the constructor is run on the server. I bet I have quite a performance hit this way, but it doesn't matter that much (now...).
Service DTO's:
[DataContract]
public class ReturnNewEmptyUser : IReturn<ReturnNewEmptyUserResponse> {}
[DataContract]
public class ReturnNewEmptyUserResponse
{
[DataMember]
public SyncUserDTO User { get; set; }
}
The Service:
public class SyncService : Service
{
public ReturnNewEmptyUserResponse Any(ReturnNewEmptyUser request)
{
var user = new ReturnNewEmptyUserResponse { User = new SyncUserDTO() };
return user;
}
}
On the client:
static void SendUsersServiceReference()
{
var webservice = new ServiceReference1.SyncReplyClient();
var users = new List<User>();
for (var i = 0; i < 5; i++)
{
var userResponse = webservice.ReturnNewEmptyUser(new ReturnNewEmptyUser());
var user = userResponse.User;
user.Timestamp.Value = DateTime.Now;
user.Timestamp.DataValid = true;
// Continue with field population...
users.Add(user);
}
// Send users with webservice method
// ...
}
We're wondering if it is a bad way to expose the fields this way. It is nice, because the client can use autocomplete and know exactly the types used - but is it better to force the client to create an XML/JSON in a specific format.
This should be in another question - this question I guess has been answered: Add service reference/proxy classes does not contain methods (incl. constructors for types), only types. If you really need the constructor, have it run and then exposed on the server and then consume it from the client. Like a factory-thing, as Adam wrote here: Class constructor (from C# web service) won't auto-implement properties in C# MVC
Btw - is there any security issues with this design? User is logged in via url-credentials (should probably be header authentication), only a few systems has access to it.
A proxy class does not keep implementation details, like a constructor. It is just a DTO. This can only be done if you share the classes, through a shared project.
Think about that servicestack is just telling the client which properties it needs, and their type.. the implementation is up to the client.

Easiest way of porting html table data to readable document

Ok,
For the past 6 months i've been struggeling to build a system that allows user input in form of big sexy textareas(with loads of support for tables,list etc). Pretty much enables the user to input data as if it were word. However when wanting to export all this data I haven't been able to find a working solution...
My first step was to try and find a reporting software that did support raw HTML from the data source and render it as normal html, worked perfectly except that the keep together function is awful, either data is split in half(tables,lists etc) which I dont want. Or report always skips to the next page to avoid this, ending up in 15+ empty pages within the final document.
So Im looking for some kind of tip/direction to what would be the best solution to export my data into a readable document(pdf or word pref).
What I got is the following data breakdown, where data is often raw html.
-Period
--Unit
---Group
----Question
-----Data
What would be the best choice? Trying to render html to pdf or rtf? I need tips :(
And also sometimes the data is 2-3 pages long with mixed tables lists and plain text.
I would suggest that you try to keep this in the browser, and add a print stylesheet to the HTML to make it render one way on the screen and another way on paper. Adding a print stylesheet to your HTML is as easy as this:
<link rel="stylesheet" media="print" href="print.css">
You should be able to parse the input it with something like Html Agility Pack and transform it (i.e. with XSLT) to whatever output format you want.
Another option is to write HTML to the browser, but with Content-Type set to a Microsoft Word-specific variant (there are several to choose from, depending on the version of Word you're targeting) should make the browser ask if the user wants to open the page with Microsoft Word. With Word 2007 and newer you can also write Office Open XML Word directly, since it's XML-based.
The content-types you can use are:
application/msword
For binary Microsoft Word files, but should also work for HTML.
application/vnd.openxmlformats-officedocument.wordprocessingml.document
For the newer "Office Open XML" formats of Word 2007 and newer.
A solution you could use is to run an application on the server using System.Diagnostics.Process that will convert the site and save it as a PDF document.
You could use wkhtmltopdf which is an open source console program that can convert from HTML to PDF or image.
The installer for windows can be obtained from wkhtmltox-0.10.0_rc2 Windows Installer (i368).
After installing wkhtmltopdf you can copy the files in the installation folder inside your solution. You can use a setup like this in the solution:
The converted pdf's will be saved to the pdf folder.
And here is code for doing the conversion:
var wkhtmltopdfLocation = Server.MapPath("~/wkhtmltopdf/") + "wkhtmltopdf.exe";
var htmlUrl = #"http://stackoverflow.com/q/7384558/750216";
var pdfSaveLocation = "\"" + Server.MapPath("~/wkhtmltopdf/pdf/") + "question.pdf\"";
var process = new Process();
process.StartInfo.UseShellExecute = false;
process.StartInfo.CreateNoWindow = true;
process.StartInfo.FileName = wkhtmltopdfLocation;
process.StartInfo.Arguments = htmlUrl + " " + pdfSaveLocation;
process.Start();
process.WaitForExit();
The htmlUrl is the location of the page you need to convert to pdf. It is set to this stackoverflow page. :)
Its a general question, but two things come to mind the Visitor Pattern and Changing the Mime Type.
Visitor Pattern
You can have two seperate rendering techniques. This would be up to your implementation.
MIME Type
When the request is made write date out in the Response etc
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Charset = "utf-16";
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("windows-1250");
HttpContext.Current.Response.AddHeader("content-disposition", string.Format("attachment; filename={0}.doc", filename));
HttpContext.Current.Response.ContentType = "application/msword";
HttpContext.Current.Response.Write("-Period");
HttpContext.Current.Response.Write("/n");
HttpContext.Current.Response.Write("--Unit");
HttpContext.Current.Response.Write("/n");
HttpContext.Current.Response.Write("---Group");
HttpContext.Current.Response.Write("/n");
HttpContext.Current.Response.Write("----Question");
HttpContext.Current.Response.Write("/n");
HttpContext.Current.Response.Write("-----Data");
HttpContext.Current.Response.Write("/n");
HttpContext.Current.Response.End();
Here is another option, use print screens (Although it doesnt take care of scrolling, I think you should be able to build this in). This example can be expanded to meet the needs of your business, although it is a hack of sorts. You pass it a URL it generates an image.
Call like this
protected void Page_Load(object sender, EventArgs e)
{
int screenWidth = Convert.ToInt32(Request["ScreenWidth"]);
int screenHeight = Convert.ToInt32(Request["ScreenHeight"]);
string url = Request["Url"].ToString();
string bitmapName = Request["BitmapName"].ToString();
WebURLToImage webUrlToImage = new WebURLToImage()
{
Url = url,
BrowserHeight = screenHeight,
BrowserWidth = screenWidth,
ImageHeight = 0,
ImageWidth = 0
};
webUrlToImage.GenerateBitmapForUrl();
webUrlToImage.GeneratedImage.Save(Server.MapPath("~") + #"Images\" +bitmapName + ".bmp");
}
Generate an image from a webpage.
using System;
using System.Drawing;
using System.Windows.Forms;
using System.Threading;
using System.IO;
public class WebURLToImage
{
public string Url { get; set; }
public Bitmap GeneratedImage { get; private set; }
public int ImageWidth { get; set; }
public int ImageHeight { get; set; }
public int BrowserWidth { get; set; }
public int BrowserHeight { get; set; }
public Bitmap GenerateBitmapForUrl()
{
ThreadStart threadStart = new ThreadStart(ImageGenerator);
Thread thread = new Thread(threadStart);
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
thread.Join();
return GeneratedImage;
}
private void ImageGenerator()
{
WebBrowser webBrowser = new WebBrowser();
webBrowser.ScrollBarsEnabled = false;
webBrowser.Navigate(Url);
webBrowser.DocumentCompleted += new
WebBrowserDocumentCompletedEventHandler(webBrowser_DocumentCompleted);
while (webBrowser.ReadyState != WebBrowserReadyState.Complete)
Application.DoEvents();
webBrowser.Dispose();
}
void webBrowser_DocumentCompleted(object sender,
WebBrowserDocumentCompletedEventArgs e)
{
WebBrowser webBrowser = (WebBrowser)sender;
webBrowser.ClientSize = new Size(BrowserWidth, this.BrowserHeight);
webBrowser.ScrollBarsEnabled = false;
GeneratedImage = new Bitmap(webBrowser.Bounds.Width, webBrowser.Bounds.Height);
webBrowser.BringToFront();
webBrowser.DrawToBitmap(GeneratedImage, webBrowser.Bounds);
if (ImageHeight != 0 && ImageWidth != 0)
GeneratedImage =
(Bitmap)GeneratedImage.GetThumbnailImage(ImageWidth, ImageHeight,
null, IntPtr.Zero);
}
}

Using Persistent Store in BlackBerry

I am developing a BlackBerry application. I want to store the details of multiple users in my mobile. I have to store data like username, first name, last name ,email id ,phone number for each user. Can any one please provide me a sample code for persistent store using which I can store all this data in a vector and retrieve later.
This link should answer most of what you need to know - http://www.miamicoder.com/post/2010/04/13/How-to-Save-BlackBerry-Application-Settings-in-the-Persistent-Store.aspx.
Below is some code from one of my projects.
public class PreferencesStore
{
// Not a real key, replace it with your own.
private static long m_lTabulaRectaKey = 0l;
public static Vector getTabulaRectas()
{
Vector vecTabulaRectas = new Vector();
PersistentObject poObject = PersistentStore.getPersistentObject(m_lTabulaRectaKey);
if(poObject.getContents() != null)
{
vecTabulaRectas = (Vector)poObject.getContents();
}
return vecTabulaRectas;
}
public static void addTabulaRecta(TabulaRecta a_oTabulaRecta)
{
Vector vecTabulaRectas = getTabulaRectas();
vecTabulaRectas.addElement(a_oTabulaRecta);
PersistentObject poObject = PersistentStore.getPersistentObject(m_lTabulaRectaKey);
poObject.setContents(vecTabulaRectas);
poObject.commit();
}
}

Correct way to create and store utility/manager classes in asp.net mvc

How should I create application wide utility/manager classes that read settings from the database?
Should I use static classes e.g.
public static class ThemeHelper
{
private static string themeDirectory { get; private set; }
static ThemeHelper()
{
// read from the database
themeDirectory = "blue-theme";
}
public static string ResolveViewPath(string viewName)
{
string path = string.Format("~/themes/{0}/{1}.aspx", themeDirectory, viewName);
// check if file exists...
// if not, use default
return path;
}
}
or a static instance of a normal class, which is stored in the HttpApplicationState for example?
Or should I use dependency injection library (like Ninject)?
Static classes and methods are okay for this kind of scenario. Pay attention however to static variables - their value will be shared between all clients of the same web application.
If you wish to cache the result but distinguish between clients (sessions), you can drop it to the Session collection.

Resources