Search Results

Search found 85 results on 4 pages for 'currentculture'.

Page 1/4 | 1 2 3 4  | Next Page >

  • Can CultureInfo.CurrentCulture differ per application pool?

    - by Peter
    I'm having trouble with CultureInfo in our ASP.NET web application. Our web application returns a different culture, depending on which application pool it is in. In application pool A, it is en-US, but in application pool B, it's nl-BE. I'd like it to be nl-BE, but can't find where to change this (IIS6 by the way). I'm not even sure if this can be changed on an app-pool level. I'm checking with CultureInfo.CurrentCulture.Name. Is it possible to change this for an application pool? Or what else could influence this? In the regional settings of the server, we have selected 'Dutch (Belgium)', which translates to nl-BE, I believe. So where could this application pool be getting the en-US?

    Read the article

  • Why Does Thread.CurrentThread.CurrentCulture Change between Page Rendering and HttpModule.PostReques

    - by Chad
    I'm creating an HttpModule that needs to know the value of Thread.CurrentThread.CurrentCulture as set in an MVC application. That value is currently being set by the BaseController, but when my HttpModule.PostRequestHandlerExecute() method fires, it reverts to what the Culture was prior to page rendering. I have duplicated this by creating a simple web app with these steps: Module.PreRequestHandlerExecute: Set culture to A Page_Load: Culture is currently A. Set culture to B Module.PostRequestHandlerExecute: Current thread culture is A. I expected it to be B but it was changed between page rendering and PostRequestHandlerExecute Any idea why .Net changes this value or how I could get around it? The thread is the same, so something in .Net must be explicitly reverting the culture.

    Read the article

  • ASP.NET Setting Culture with InitializeCulture

    - by Helen
    I have a website with three domains .com, .de and .it Each domain needs to default to the local language/culture of the country. I have created a base page and added an InitializeCulture Protected Overrides Sub InitializeCulture() Dim url As System.Uri = Request.Url Dim hostname As String = url.Host.ToString() Dim SelectedLanguage As String If HttpContext.Current.Profile("PreferredCulture").ToString Is Nothing Then Select Case hostname Case "www.domain.de" SelectedLanguage = "de" Thread.CurrentThread.CurrentUICulture = New CultureInfo(SelectedLanguage) Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(SelectedLanguage) Case "www.domain.it" SelectedLanguage = "it" Thread.CurrentThread.CurrentUICulture = New CultureInfo(SelectedLanguage) Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(SelectedLanguage) Case Else SelectedLanguage = "en" Thread.CurrentThread.CurrentUICulture = New CultureInfo(SelectedLanguage) Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(SelectedLanguage) End Select End If End Sub This is fine. The problem now occurs because we also want three language selection buttons on the home page so that the user can override the domain language. So on my Default.asp.vb we have three button events like this... Protected Sub langEnglish_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles langEnglish.Click Dim SelectedLanguage As String = "en" 'Save selected user language in profile HttpContext.Current.Profile.SetPropertyValue("PreferredCulture", SelectedLanguage) 'Force re-initialization of the page to fire InitializeCulture() Context.Server.Transfer(Context.Request.Path) End Sub But of course the InititalizeCulture then overrides whatever button selection has been made. Is there any way that the InitialCulture can check whether a button click has occurred and if so skip the routine? Any advice would be greatly appreciated, thanks.

    Read the article

  • int.Parse of "8" fails. int.Parse always requires CultureInfo.InvariantCulture?

    - by Henrik Carlsson
    We develop an established software which works fine on all known computers except one. The problem is to parse strings that begin with "8". It seems like "8" in the beginning of a string is a reserved character. Parsing: int.Parse("8") -> Exception message: Input string was not in a correct format. int.Parse("80") -> 0 int.Parse("88") -> 8 int.Parse("8100") -> 100 CurrentCulture: sv-SE CurrentUICulture: en-US The problem is solved using int.Parse("8", CultureInfo.InvariantCulture). However, it would be nice to know the source of the problem. Question: Why do we get this behaviour of "8" if we don't specify invariant culture? Additional information: I did send a small program to my client achieve the result above: private int ParseInt(string s) { int parsedInt = -1000; try { parsedInt = int.Parse(s); textBoxMessage.Text = "Success: " + parsedInt; } catch (Exception ex) { textBoxMessage.Text = string.Format("Error parsing string: '{0}'", s) + Environment.NewLine + "Exception message: " + ex.Message; } textBoxMessage.Text += Environment.NewLine + Environment.NewLine + "CurrentCulture: " + Thread.CurrentThread.CurrentCulture.Name + "\r\n" + "CurrentUICulture: " + Thread.CurrentThread.CurrentUICulture.Name + "\r\n"; return parsedInt; }

    Read the article

  • How to honor/inherit user's language settings in WinForm app

    - by msorens
    I have worked with globalization settings in the past but not within the .NET environment, which is the topic of this question. What I am seeing is most certainly due to knowledge I have yet to learn so I would appreciate illumination on the following. Setup: My default language setting is English (en-us specifically). I added a second language (Danish) on my development system (WinXP) and then opened the language bar so I could select either at will. I selected Danish on the language bar then opened Notepad and found the language reverted to English on the language bar. I understand that the language setting is per application, so it seemed that Notepad set the default back to English. (I found that strange since Windows and thus Notepad is used all over the world.) Closing Notepad returned the setting on the language bar to Danish. I then launched my open custom WinForm application--which I know does not set the language--and it also reverted from English to Danish when opened, then back to Danish when terminated! Question #1A: How do I get my WinForm application upon launch to inherit the current setting of the language bar? My experiment seems to indicate that each application starts with the system default and requires the user to manually change it once the app is running--this would seem to be a major inconvenience for anyone that wants to work with more than one language! Question #1B: If one must, in fact, set the language manually in a multi-language scenario, how do I change my default system language (e.g. to Danish) so I can test my app's launch in another language? I added a display of the current language in my application for this next experiment. Specifically I set a MouseEnter handler on a label that set its tooltip to CultureInfo.CurrentCulture.Name so each time I mouse over I thought I should see the current language setting. Since setting the language before I launch my app did not work, I launched it then set the language to Danish. I found that some things (like typing in a TextBox) did honor this Danish setting. But mousing over the instrumented label still showed en-us! Question #2A: Why does CultureInfo.CurrentCulture.Name not reflect the change from my language bar while other parts of my app seem to recognize the change? (Trying CultureInfo.CurrentUICulture.Name produced the same result.) Question #2B: Is there an event that fires upon changes on the language bar so I could recognize within my app when the language setting changes?

    Read the article

  • Why does release mode affect on Thread.CurrentThread.CurrentCulture?

    - by satispunk
    Hi I have ASP .NET application. I set culture in Application_Begin request: System.Threading.Thread.CurrentThread.CurrentCulture = myCulture; System.Threading.Thread.CurrentThread.CurrentUICulture = myCulture; When I get current culture from page, it is myCulture in debug mode and it is "en-GB" in release mode. I don't understand why Release mode affects on Thread.CurrentThread.CurrentCulture I use VS2010 and .NET 4.0 Thanks

    Read the article

  • Best way to parse float?

    - by boris callens
    What is the best way to parse a float in CSharp? I know about TryParse, but what I'm particularly wondering about is dots, commas etc. I'm having problems with my website. On my dev server, the ',' is for decimals, the '.' for separator. On the prod server though, it is the other way round. How can I best capture this?

    Read the article

  • Do we affect multiple users in ASP.NET when we set the Thread CurrentCulture/CurentUICulture?

    - by Nikolay
    When we set the CurrentCulture and/or CurrentUICulture we do this on the current thread like this: Thread.CurrentThread.CurrentCulture = new CultureInfo("en-GB"); Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-GB"); Doest this mean we could affect the culture settings of multiple users of our web application as their requests may reuse the threads from pool? I am working on an ASP.NET MVC application where each user may have own culture setting specified in his/her account data. When the user logs in, the culture setting is retrieved from the database and has to be set as current culture. My worry is that setting the current culture on the current thread may affect another user request reusing this thread. I am even more concerned reading this: ASP.NET not only uses a thread pool, but may switch threads during request processing.

    Read the article

  • .NET Properties - Use Private Set or ReadOnly Property?

    - by tgxiii
    In what situation should I use a Private Set on a property versus making it a ReadOnly property? Take into consideration the two very simplistic examples below. First example: Public Class Person Private _name As String Public Property Name As String Get Return _name End Get Private Set(ByVal value As String) _name = value End Set End Property Public Sub WorkOnName() Dim txtInfo As TextInfo = _ Threading.Thread.CurrentThread.CurrentCulture.TextInfo Me.Name = txtInfo.ToTitleCase(Me.Name) End Sub End Class // ---------- public class Person { private string _name; public string Name { get { return _name; } private set { _name = value; } } public void WorkOnName() { TextInfo txtInfo = System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo; this.Name = txtInfo.ToTitleCase(this.Name); } } Second example: Public Class AnotherPerson Private _name As String Public ReadOnly Property Name As String Get Return _name End Get End Property Public Sub WorkOnName() Dim txtInfo As TextInfo = _ Threading.Thread.CurrentThread.CurrentCulture.TextInfo _name = txtInfo.ToTitleCase(_name) End Sub End Class // --------------- public class AnotherPerson { private string _name; public string Name { get { return _name; } } public void WorkOnName() { TextInfo txtInfo = System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo; _name = txtInfo.ToTitleCase(_name); } } They both yield the same results. Is this a situation where there's no right and wrong, and it's just a matter of preference?

    Read the article

  • StreamWriter appends random data

    - by void
    Hi I'm seeing odd behaviour using the StreamWriter class writing extra data to a file using this code: public void WriteToCSV(string filename) { StreamWriter streamWriter = null; try { streamWriter = new StreamWriter(filename); Log.Info("Writing CSV report header information ... "); streamWriter.WriteLine("\"{0}\",\"{1}\",\"{2}\",\"{3}\"", ((int)CSVRecordType.Header).ToString("D2", CultureInfo.CurrentCulture), m_InputFilename, m_LoadStartDate, m_LoadEndDate); int recordCount = 0; if (SummarySection) { Log.Info("Writing CSV report summary section ... "); foreach (KeyValuePair<KeyValuePair<LoadStatus, string>, CategoryResult> categoryResult in m_DataLoadResult.DataLoadResults) { streamWriter.WriteLine("\"{0}\",\"{1}\",\"{2}\",\"{3}\"", ((int)CSVRecordType.Summary).ToString("D2", CultureInfo.CurrentCulture), categoryResult.Value.StatusString, categoryResult.Value.Count.ToString(CultureInfo.CurrentCulture), categoryResult.Value.Category); recordCount++; } } Log.Info("Writing CSV report cases section ... "); foreach (KeyValuePair<KeyValuePair<LoadStatus, string>, CategoryResult> categoryResult in m_DataLoadResult.DataLoadResults) { foreach (CaseLoadResult result in categoryResult.Value.CaseLoadResults) { if ((LoadStatus.Success == result.Status && SuccessCases) || (LoadStatus.Warnings == result.Status && WarningCases) || (LoadStatus.Failure == result.Status && FailureCases) || (LoadStatus.NotProcessed == result.Status && NotProcessedCases)) { streamWriter.Write("\"{0}\",\"{1}\",\"{2}\",\"{3}\",\"{4}\"", ((int)CSVRecordType.Result).ToString("D2", CultureInfo.CurrentCulture), result.Status, result.UniqueId, result.Category, result.ClassicReference); if (RawResponse) { streamWriter.Write(",\"{0}\"", result.ResponseXml); } streamWriter.WriteLine(); recordCount++; } } } streamWriter.WriteLine("\"{0}\",\"{1}\"", ((int)CSVRecordType.Count).ToString("D2", CultureInfo.CurrentCulture), recordCount); Log.Info("CSV report written to '{0}'", fileName); } catch (IOException execption) { string errorMessage = string.Format(CultureInfo.CurrentCulture, "Unable to write XML report to '{0}'", fileName); Log.Error(errorMessage); Log.Error(exception.Message); throw new MyException(errorMessage, exception); } finally { if (null != streamWriter) { streamWriter.Close(); } } } The file produced contains a set of records on each line 0 to N, for example: [Record Zero] [Record One] ... [Record N] However the file produced either contains nulls or incomplete records from further up the file appended to the end. For example: [Record Zero] [Record One] ... [Record N] [Lots of nulls] or [Record Zero] [Record One] ... [Record N] [Half complete records] This also happens in separate pieces of code that also use the StreamWriter class. Furthermore, the files produced all have sizes that are multiples of 1024. I've been unable to reproduce this behaviour on any other machine and have tried recreating the environment. Previous versions of the application didn't exhibite this behaviour despite having the same code for the methods in question. EDIT: Added extra code.

    Read the article

  • Passing multiple simple POST Values to ASP.NET Web API

    - by Rick Strahl
    A few weeks backs I posted a blog post  about what does and doesn't work with ASP.NET Web API when it comes to POSTing data to a Web API controller. One of the features that doesn't work out of the box - somewhat unexpectedly -  is the ability to map POST form variables to simple parameters of a Web API method. For example imagine you have this form and you want to post this data to a Web API end point like this via AJAX: <form> Name: <input type="name" name="name" value="Rick" /> Value: <input type="value" name="value" value="12" /> Entered: <input type="entered" name="entered" value="12/01/2011" /> <input type="button" id="btnSend" value="Send" /> </form> <script type="text/javascript"> $("#btnSend").click( function() { $.post("samples/PostMultipleSimpleValues?action=kazam", $("form").serialize(), function (result) { alert(result); }); }); </script> or you might do this more explicitly by creating a simple client map and specifying the POST values directly by hand:$.post("samples/PostMultipleSimpleValues?action=kazam", { name: "Rick", value: 1, entered: "12/01/2012" }, $("form").serialize(), function (result) { alert(result); }); On the wire this generates a simple POST request with Url Encoded values in the content:POST /AspNetWebApi/samples/PostMultipleSimpleValues?action=kazam HTTP/1.1 Host: localhost User-Agent: Mozilla/5.0 (Windows NT 6.2; WOW64; rv:15.0) Gecko/20100101 Firefox/15.0.1 Accept: application/json Connection: keep-alive Content-Type: application/x-www-form-urlencoded; charset=UTF-8 X-Requested-With: XMLHttpRequest Referer: http://localhost/AspNetWebApi/FormPostTest.html Content-Length: 41 Pragma: no-cache Cache-Control: no-cachename=Rick&value=12&entered=12%2F10%2F2011 Seems simple enough, right? We are basically posting 3 form variables and 1 query string value to the server. Unfortunately Web API can't handle request out of the box. If I create a method like this:[HttpPost] public string PostMultipleSimpleValues(string name, int value, DateTime entered, string action = null) { return string.Format("Name: {0}, Value: {1}, Date: {2}, Action: {3}", name, value, entered, action); }You'll find that you get an HTTP 404 error and { "Message": "No HTTP resource was found that matches the request URI…"} Yes, it's possible to pass multiple POST parameters of course, but Web API expects you to use Model Binding for this - mapping the post parameters to a strongly typed .NET object, not to single parameters. Alternately you can also accept a FormDataCollection parameter on your API method to get a name value collection of all POSTed values. If you're using JSON only, using the dynamic JObject/JValue objects might also work. ModelBinding is fine in many use cases, but can quickly become overkill if you only need to pass a couple of simple parameters to many methods. Especially in applications with many, many AJAX callbacks the 'parameter mapping type' per method signature can lead to serious class pollution in a project very quickly. Simple POST variables are also commonly used in AJAX applications to pass data to the server, even in many complex public APIs. So this is not an uncommon use case, and - maybe more so a behavior that I would have expected Web API to support natively. The question "Why aren't my POST parameters mapping to Web API method parameters" is already a frequent one… So this is something that I think is fairly important, but unfortunately missing in the base Web API installation. Creating a Custom Parameter Binder Luckily Web API is greatly extensible and there's a way to create a custom Parameter Binding to provide this functionality! Although this solution took me a long while to find and then only with the help of some folks Microsoft (thanks Hong Mei!!!), it's not difficult to hook up in your own projects. It requires one small class and a GlobalConfiguration hookup. Web API parameter bindings allow you to intercept processing of individual parameters - they deal with mapping parameters to the signature as well as converting the parameters to the actual values that are returned. Here's the implementation of the SimplePostVariableParameterBinding class:public class SimplePostVariableParameterBinding : HttpParameterBinding { private const string MultipleBodyParameters = "MultipleBodyParameters"; public SimplePostVariableParameterBinding(HttpParameterDescriptor descriptor) : base(descriptor) { } /// <summary> /// Check for simple binding parameters in POST data. Bind POST /// data as well as query string data /// </summary> public override Task ExecuteBindingAsync(ModelMetadataProvider metadataProvider, HttpActionContext actionContext, CancellationToken cancellationToken) { // Body can only be read once, so read and cache it NameValueCollection col = TryReadBody(actionContext.Request); string stringValue = null; if (col != null) stringValue = col[Descriptor.ParameterName]; // try reading query string if we have no POST/PUT match if (stringValue == null) { var query = actionContext.Request.GetQueryNameValuePairs(); if (query != null) { var matches = query.Where(kv => kv.Key.ToLower() == Descriptor.ParameterName.ToLower()); if (matches.Count() > 0) stringValue = matches.First().Value; } } object value = StringToType(stringValue); // Set the binding result here SetValue(actionContext, value); // now, we can return a completed task with no result TaskCompletionSource<AsyncVoid> tcs = new TaskCompletionSource<AsyncVoid>(); tcs.SetResult(default(AsyncVoid)); return tcs.Task; } private object StringToType(string stringValue) { object value = null; if (stringValue == null) value = null; else if (Descriptor.ParameterType == typeof(string)) value = stringValue; else if (Descriptor.ParameterType == typeof(int)) value = int.Parse(stringValue, CultureInfo.CurrentCulture); else if (Descriptor.ParameterType == typeof(Int32)) value = Int32.Parse(stringValue, CultureInfo.CurrentCulture); else if (Descriptor.ParameterType == typeof(Int64)) value = Int64.Parse(stringValue, CultureInfo.CurrentCulture); else if (Descriptor.ParameterType == typeof(decimal)) value = decimal.Parse(stringValue, CultureInfo.CurrentCulture); else if (Descriptor.ParameterType == typeof(double)) value = double.Parse(stringValue, CultureInfo.CurrentCulture); else if (Descriptor.ParameterType == typeof(DateTime)) value = DateTime.Parse(stringValue, CultureInfo.CurrentCulture); else if (Descriptor.ParameterType == typeof(bool)) { value = false; if (stringValue == "true" || stringValue == "on" || stringValue == "1") value = true; } else value = stringValue; return value; } /// <summary> /// Read and cache the request body /// </summary> /// <param name="request"></param> /// <returns></returns> private NameValueCollection TryReadBody(HttpRequestMessage request) { object result = null; // try to read out of cache first if (!request.Properties.TryGetValue(MultipleBodyParameters, out result)) { // parsing the string like firstname=Hongmei&lastname=Ge result = request.Content.ReadAsFormDataAsync().Result; request.Properties.Add(MultipleBodyParameters, result); } return result as NameValueCollection; } private struct AsyncVoid { } }   The ExecuteBindingAsync method is fired for each parameter that is mapped and sent for conversion. This custom binding is fired only if the incoming parameter is a simple type (that gets defined later when I hook up the binding), so this binding never fires on complex types or if the first type is not a simple type. For the first parameter of a request the Binding first reads the request body into a NameValueCollection and caches that in the request.Properties collection. The request body can only be read once, so the first parameter request reads it and then caches it. Subsequent parameters then use the cached POST value collection. Once the form collection is available the value of the parameter is read, and the value is translated into the target type requested by the Descriptor. SetValue writes out the value to be mapped. Once you have the ParameterBinding in place, the binding has to be assigned. This is done along with all other Web API configuration tasks at application startup in global.asax's Application_Start:GlobalConfiguration.Configuration.ParameterBindingRules .Insert(0, (HttpParameterDescriptor descriptor) => { var supportedMethods = descriptor.ActionDescriptor.SupportedHttpMethods; // Only apply this binder on POST and PUT operations if (supportedMethods.Contains(HttpMethod.Post) || supportedMethods.Contains(HttpMethod.Put)) { var supportedTypes = new Type[] { typeof(string), typeof(int), typeof(decimal), typeof(double), typeof(bool), typeof(DateTime) }; if (supportedTypes.Where(typ => typ == descriptor.ParameterType).Count() > 0) return new SimplePostVariableParameterBinding(descriptor); } // let the default bindings do their work return null; });   The ParameterBindingRules.Insert method takes a delegate that checks which type of requests it should handle. The logic here checks whether the request is POST or PUT and whether the parameter type is a simple type that is supported. Web API calls this delegate once for each method signature it tries to map and the delegate returns null to indicate it's not handling this parameter, or it returns a new parameter binding instance - in this case the SimplePostVariableParameterBinding. Once the parameter binding and this hook up code is in place, you can now pass simple POST values to methods with simple parameters. The examples I showed above should now work in addition to the standard bindings. Summary Clearly this is not easy to discover. I spent quite a bit of time digging through the Web API source trying to figure this out on my own without much luck. It took Hong Mei at Micrsoft to provide a base example as I asked around so I can't take credit for this solution :-). But once you know where to look, Web API is brilliantly extensible to make it relatively easy to customize the parameter behavior. I'm very stoked that this got resolved  - in the last two months I've had two customers with projects that decided not to use Web API in AJAX heavy SPA applications because this POST variable mapping wasn't available. This might actually change their mind to still switch back and take advantage of the many great features in Web API. I too frequently use plain POST variables for communicating with server AJAX handlers and while I could have worked around this (with untyped JObject or the Form collection mostly), having proper POST to parameter mapping makes things much easier. I said this in my last post on POST data and say it again here: I think POST to method parameter mapping should have been shipped in the box with Web API, because without knowing about this limitation the expectation is that simple POST variables map to parameters just like query string values do. I hope Microsoft considers including this type of functionality natively in the next version of Web API natively or at least as a built-in HttpParameterBinding that can be just added. This is especially true, since this binding doesn't affect existing bindings. Resources SimplePostVariableParameterBinding Source on GitHub Global.asax hookup source Mapping URL Encoded Post Values in  ASP.NET Web API© Rick Strahl, West Wind Technologies, 2005-2012Posted in Web Api  AJAX   Tweet !function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs"); (function() { var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true; po.src = 'https://apis.google.com/js/plusone.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s); })();

    Read the article

  • asp.net multiligual website culture settings

    - by Hemant Kothiyal
    Hi, In asp.net multilingual website in english Uk and swedish, i have three rsources file 1. en-GB.resx 2. sv-SE.resx 3. Culture neutral file. I have create one base class and all pages is inherited from that class. There i write following lines to set UICULTURE and culture 1. Thread.CurrentThread.CurrentUICulture = CultureInfo.CurrentUICulture.Name; 2. Thread.CurrentThread.CurrentCulture = CultureInfo.CurrentCulture.Name; Question: Suppose my browser language is Swedish(sv-SE) then this code will run because it find CurrentUICulture and CurrentCulture values as sv-SE. Now if suppose browser language is Swedish(sv) only, in that case values will be set as CurrentUICulture = sv; and CurrentCulture = sv-SE Now the problem is that user can able to view all text in Culture neutral resource file that i kept as english while all decimal saperators, currency and other will be appear in swedish. It looks confusing to usr. What would be right approach. I am thinking following solution. Please correct me? 1. i can create extra resource file for sv also. 2. I check value of CurrentUICulture in base class and if it is sv then replace it with sv-SE Please correct me which one is right approach or Is there any other good way of doing?

    Read the article

  • Setting thread culture to default

    - by synergetic
    In silverlight application I have MyTexts.resx (for english) and MyTexts.ja-JP.resx (for japanese) resource files. Before loading a page I can set current culture to japanese as following: Thread.CurrentThread.CurrentCulture = new CultureInfo("ja-JP"); Thread.CurrentThread.CurrentUICulture = new CultureInfo("ja-JP"); But sometimes I need to reset culture to default. How can I do that? The following wouldn't work: Thread.CurrentThread.CurrentCulture = new CultureInfo("default"); OR Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");

    Read the article

  • handle null values for string when implementing IXmlSerializable interface

    - by user208081
    I have the following class that implements IXmlSerializable. When implementing WriteXml(), I need to handle the case where the string members of this class may be null values. What is the best way of handling this? Currently, I am using the default constructor in which all the string properties are initialized to empty string values. This way, when WriteXml() is called, the string will not be null. One other way I could do this is check using String.IsNullOrEmpty before writing each string in xml. Any suggestions on how I can improve this code? using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml.Serialization; using System.Globalization; namespace TCS.Common.InformationObjects { public sealed class FaxSender : IXmlSerializable { #region Public Constants private const string DEFAULT_CLASS_NAME = "FaxSender"; #endregion Public Constants #region Public Properties public string Name { get; set; } public string Organization { get; set; } public string PhoneNumber { get; set; } public string FaxNumber { get; set; } public string EmailAddress { get; set; } #endregion Public Properties #region Public Methods #region Constructors public FaxSender() { Name = String.Empty; Organization = String.Empty; PhoneNumber = String.Empty; FaxNumber = String.Empty; EmailAddress = String.Empty; } public FaxSender(string name, string organization, string phoneNumber, string faxNumber, string emailAddress) { Name = name; Organization = organization; PhoneNumber = phoneNumber; FaxNumber = faxNumber; EmailAddress = emailAddress; } #endregion Constructors #region IXmlSerializable Members public System.Xml.Schema.XmlSchema GetSchema() { throw new NotImplementedException(); } public void ReadXml(System.Xml.XmlReader reader) { throw new NotImplementedException(); } public void WriteXml(System.Xml.XmlWriter xmlWriter) { try { // <sender> xmlWriter.WriteStartElement("sender"); // Write the name of the sender as an element. xmlWriter.WriteElementString("name", this.Name.ToString(CultureInfo.CurrentCulture)); // Write the organization of the sender as an element. xmlWriter.WriteElementString("organization", this.Organization.ToString(CultureInfo.CurrentCulture)); // Write the phone number of the sender as an element. xmlWriter.WriteElementString("phone_number", this.PhoneNumber.ToString(CultureInfo.CurrentCulture)); // Write the fax number of the sender as an element. xmlWriter.WriteElementString("fax_number", this.FaxNumber.ToString(CultureInfo.CurrentCulture)); // Write the email address of the sender as an element. xmlWriter.WriteElementString("email_address", this.EmailAddress.ToString(CultureInfo.CurrentCulture)); // </sender> xmlWriter.WriteEndElement(); } catch { // Rethrow any exceptions. throw; } } #endregion IXmlSerializable Members #endregion Public Methods } }

    Read the article

  • Getting current culture day names in .NET

    - by cxfx
    Is it possible to get the CurrentCulture's weekdays from DateTimeFormatInfo, but returning Monday as first day of the week instead of Sunday. And, if the current culture isn't English (i.e. the ISO code isn't "en") then leave it as default. By default CultureInfo.CurrentCulture.DateTimeFormat.DayNames returns: [0]: "Sunday" [1]: "Monday" [2]: "Tuesday" [3]: "Wednesday" [4]: "Thursday" [5]: "Friday" [6]: "Saturday" But I need: [0]: "Monday" [1]: "Tuesday" [2]: "Wednesday" [3]: "Thursday" [4]: "Friday" [5]: "Saturday" [6]: "Sunday"

    Read the article

  • RIA Services Repository Save does not work!?

    - by Savvas Sopiadis
    Hello everybody! Doing my first SL4 MVVM RIA based application and i ran into the following situation: updating a record (EF4,NO-POCOS!!) in the SL-client seems to take place, but values in the dbms are unchanged. Debugging with Fiddler the message on save is (amongst others): EntityActions.nil? b9http://schemas.microsoft.com/2003/10/Serialization/Arrays^HasMemberChanges?^Id?^ Operation?Update I assume that this says only: hey! the dbms should do an update on this record, AND nothing more! Is that right?! I 'm using a generic repository like this: public class Repository<T> : IRepository<T> where T : class { IObjectSet<T> _objectSet; IObjectContext _objectContext; public Repository(IObjectContext objectContext) { this._objectContext = objectContext; _objectSet = objectContext.CreateObjectSet<T>(); } public IQueryable<T> AsQueryable() { return _objectSet; } public IEnumerable<T> GetAll() { return _objectSet.ToList(); } public IEnumerable<T> Find(Expression<Func<T, bool>> where) { return _objectSet.Where(where); } public T Single(Expression<Func<T, bool>> where) { return _objectSet.Single(where); } public T First(Expression<Func<T, bool>> where) { return _objectSet.First(where); } public void Delete(T entity) { _objectSet.DeleteObject(entity); } public void Add(T entity) { _objectSet.AddObject(entity); } public void Attach(T entity) { _objectSet.Attach(entity); } public void Save() { _objectContext.SaveChanges(); } } The DomainService Update Method is the following: [Update] public void UpdateCulture(Culture currentCulture) { if (currentCulture.EntityState == System.Data.EntityState.Detached) { this.cultureRepository.Attach(currentCulture); } this.cultureRepository.Save(); } I know that the currentCulture-Entity is detached. What confuses me (amongst other things) is this: is the _objectContext still alive? (which means it "will be"??? aware of the changes made to record, so simply calling Attach() and then Save() should be enough!?!?) What am i missing? Development Environment: VS2010RC - Entity Framework 4 (no POCOs) Thanks in advance

    Read the article

  • Convert.ToDateTime causes FormatException on afternoon date/time values

    - by Sam
    We have an application parsing date/time values in the following format: 2009-10-10 09:19:12.124 2009-10-10 12:13:14.852 2009-10-10 13:00:00 2009-10-10 15:23:32.022 One particular server all of the sudden (today) started failing to parse any times 13:00:00 or later. This particular client has five servers and only one has the problem. We have dozens of other clients with a total of hundreds of servers without the problem. System.FormatException: String was not recognized as a valid DateTime. at System.DateTimeParse.Parse(String s, DateTimeFormatInfo dtfi, DateTimeStyles styles) at System.DateTime.Parse(String s, IFormatProvider provider) at System.Convert.ToDateTime(String value, IFormatProvider provider) at System.String.System.IConvertible.ToDateTime(IFormatProvider provider) at System.Convert.ToDateTime(Object value) I ran a test using DateTime.Parse(s, CultureInfo.CurrentCulture) comapred to DateTime.Parse(s, CultureInfo.InvariantCulture) and the problem only shows up with CurrentCulture. However, CurrentCulture is "en-US" just like all the other servers and there's nothing different that I can find in regional or language settings. Has anyone seen this before? Suggestions related to what I can look into? EDIT: Thank you for the answers so far. However, I'm looking for suggestions on what configuration to look into that could have caused this to suddenly change behavior and stop working when it's worked for years and works on hundreds of other servers. I've already changed it for the next version, but I'm looking for a configuration change to fix this in the interim for the current installation.

    Read the article

  • Change CulturalInfo after button click

    - by Bart
    i have multilingual asp.net site. there is masterpage and default.aspx in masterpage i put two buttons one to click when i want to change the language to english, second for polish. I want to change the language after click on these buttons (and all changes should appear automatically on the page) here is a code for both: protected void EnglishButton_Click(object sender, ImageClickEventArgs e) { string selectedLanguage = "en-US"; //Sets the cookie that is to be used by InitializeCulture() in content page HttpCookie cookie = new HttpCookie("CultureInfo"); cookie.Value = selectedLanguage; Response.Cookies.Add(cookie); Server.Transfer(Request.Path); } protected void PolishButton_Click(object sender, ImageClickEventArgs e) { string selectedLanguage = "pl-PL"; //Sets the cookie that is to be used by InitializeCulture() in content page HttpCookie cookie = new HttpCookie("CultureInfo"); cookie.Value = selectedLanguage; Response.Cookies.Add(cookie); Server.Transfer(Request.Path); } in default.aspx.cs i have InitializeCulture(): protected override void InitializeCulture() { HttpCookie cookie = Request.Cookies["CultureInfo"]; // if there is some value in cookie if (cookie != null && cookie.Value != null) { Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(cookie.Value); Thread.CurrentThread.CurrentUICulture = new CultureInfo(cookie.Value); } else // if none value has been sent by cookie, set default language { Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("pl-PL"); Thread.CurrentThread.CurrentUICulture = new CultureInfo("pl-PL"); } base.InitializeCulture(); } i added resource files and in one label i show actual culture: Welcome.Text = "Culture: " + System.Globalization.CultureInfo.CurrentCulture.ToString(); the problem is that when i run this app and click e.g. english button (default language is polish), there is no effect. if i click it second time or press F5, the changes are applies and in the label is Culture: en-US. the same happens if i want to change language back to polish (it works after second click (or one click and refresh)). What am i doing wrong?

    Read the article

  • Application hangs after changing language From “En-Us” to any global language in control panel

    - by user1764824
    I created a WinForms application using C#. When I try to change the culture info, my application gets hanged. Microsoft.Win32.SystemEvents.UserPreferenceChanged += new Microsoft.Win32.UserPreferenceChangedEventHandler(SystemEvents_UserPreferenceChanged); void SystemEvents_UserPreferenceChanged(object sender, Microsoft.Win32.UserPreferenceChangedEventArgs e) { if (!PreviousInstance()) { CultureInfo ObjCulture = new CultureInfo(CultureInfo.InvariantCulture.IetfLanguageTag, false); Thread.CurrentThread.CurrentCulture = ObjCulture; Application.CurrentCulture = ObjCulture; } } public void INIT() { CultureInfo objCultureInfo = null; try { objCultureInfo = new CultureInfo("en-US", false); objCultureInfo.NumberFormat.NumberDecimalSeparator = "."; objCultureInfo.NumberFormat.NegativeSign = "-"; objCultureInfo.NumberFormat.NumberNegativePattern = 1; //1 stands for -100. Application.CurrentCulture = objCultureInfo; } } After Changing Language ... My Application gets Hanged and i cant Debug anything When i Try to Evaluate things This Event Called only once.. But if try in a small application it comes every time when Language is changed... ... Nothing shown in Eventviewer either. How can I solve this problem? ..

    Read the article

  • [ASP.NET] Change CulturalInfo after button click

    - by Bart
    Hello, i have multilingual asp.net site. there is masterpage and default.aspx in masterpage i put two buttons one to click when i want to change the language to english, second for polish. I want to change the language after click on these buttons (and all changes should appear automatically on the page) here is a code for both: protected void EnglishButton_Click(object sender, ImageClickEventArgs e) { string selectedLanguage = "en-US"; //Sets the cookie that is to be used by InitializeCulture() in content page HttpCookie cookie = new HttpCookie("CultureInfo"); cookie.Value = selectedLanguage; Response.Cookies.Add(cookie); Server.Transfer(Request.Path); } protected void PolishButton_Click(object sender, ImageClickEventArgs e) { string selectedLanguage = "pl-PL"; //Sets the cookie that is to be used by InitializeCulture() in content page HttpCookie cookie = new HttpCookie("CultureInfo"); cookie.Value = selectedLanguage; Response.Cookies.Add(cookie); Server.Transfer(Request.Path); } in default.aspx.cs i have InitializeCulture(): protected override void InitializeCulture() { HttpCookie cookie = Request.Cookies["CultureInfo"]; // if there is some value in cookie if (cookie != null && cookie.Value != null) { Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(cookie.Value); Thread.CurrentThread.CurrentUICulture = new CultureInfo(cookie.Value); } else // if none value has been sent by cookie, set default language { Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("pl-PL"); Thread.CurrentThread.CurrentUICulture = new CultureInfo("pl-PL"); } base.InitializeCulture(); } i added resource files and in one label i show actual culture: Welcome.Text = "Culture: " + System.Globalization.CultureInfo.CurrentCulture.ToString(); the problem is that when i run this app and click e.g. english button (default language is polish), there is no effect. if i click it second time or press F5, the changes are applies and in the label is Culture: en-US. the same happens if i want to change language back to polish (it works after second click (or one click and refresh)). What am i doing wrong? Regards, Bart

    Read the article

  • SpeechSynthesizer Exception - Please Help

    - by Chris
    Hi. I have the following code: private List<VoiceInfo> GetInstalledVoices(SpeechSynthesizer synthesizer) { CultureInfo currentCulture = CultureInfo.CurrentCulture; var listOfVoiceInfo = from voice in synthesizer.GetInstalledVoices(currentCulture) select voice.VoiceInfo; return listOfVoiceInfo.ToList<VoiceInfo>(); } I then call the code from the following code snippet: var synthesizer = new SpeechSynthesizer(); var installedVoices = GetInstalledVoices(synthesizer); VoiceInfo voice = null; if (installedVoices != null && installedVoices.Count > 0) { voice = installedVoices.FirstOrDefault(); } if (voice != null) { synthesizer.SelectVoice(voice.Name); } The line of code that selects the voice throws the following exception: "Cannot set voice. No matching voice is installed or the voice was disabled." This is being done from within an ASP.NET web application - running on Windows Server 2003 R2. When I run this from within Visual Studio 2008 - everything works fine. I created a simple Console app to perform the same action - then ran it from the Windows Server 2003 machine - and it worked fine. I even modified the code in the Console app to loop through each of the installed voices and select the voice. No problems. However, when doing the same from within the web application, I get the same error. I am beating my head against a wall on this one. ANY help on this would be greatly appreciated. Thanks. Chris

    Read the article

  • Parsing a DateTime containing milliseconds fails for certain cultures. Why?

    - by dradovic
    I'm trying to parse a string containing milliseconds like this: string s = "11.05.2010 15:03:08.7718687"; // culture: de-CH DateTime d = DateTime.Parse(s); // works However, for example under the de-DE locale, the decimal separator is a comma (not a dot). So the example becomes: string s = "11.05.2010 15:03:08,7718687"; // culture: de-DE (note the comma) DateTime d = DateTime.Parse(s); // throws a FormatException It is weird to me that DateTime.Parse(s) should throw a FormatException now as it is supposed to use the CultureInfo.CurrentCulture to do the parsing. Even passing the CurrentCulture as an argument explicitly does not help neither. Does anybody have an idea why this does not work? Doesn't parsing take the NumberFormatInfo.NumberDecimalSeparator into account?

    Read the article

1 2 3 4  | Next Page >