Search Results

Search found 145 results on 6 pages for 'tryparse'.

Page 2/6 | < Previous Page | 1 2 3 4 5 6  | Next Page >

  • How to use jQuery Date Range Picker plugin in asp.net

    - by alaa9jo
    I stepped by this page: http://www.filamentgroup.com/lab/date_range_picker_using_jquery_ui_16_and_jquery_ui_css_framework/ and let me tell you,this is one of the best and coolest daterangepicker in the web in my opinion,they did a great job with extending the original jQuery UI DatePicker.Of course I made enhancements to the original plugin (fixed few bugs) and added a new option (Clear) to clear the textbox. In this article I well use that updated plugin and show you how to use it in asp.net..you will definitely like it. So,What do I need? 1- jQuery library : you can use 1.3.2 or 1.4.2 which is the latest version so far,in my article I will use the latest version. 2- jQuery UI library (1.8): As I mentioned earlier,daterangepicker plugin is based on the original jQuery UI DatePicker so that library should be included into your page. 3- jQuery DateRangePicker plugin : you can go to the author page or use the modified one (it's included in the attachment),in this article I will use the modified one. 4- Visual Studio 2005 or later : very funny :D,in my article I will use VS 2008. Note: in the attachment,I included all CSS and JS files so don't worry. How to use it? First thing,you will have to include all of the CSS and JS files into your page like this: <script src="Scripts/jquery-1.4.2.min.js" type="text/javascript"></script> <script src="Scripts/jquery-ui-1.8.custom.min.js" type="text/javascript"></script> <script src="Scripts/daterangepicker.jQuery.js" type="text/javascript"></script> <link href="CSS/redmond/jquery-ui-1.8.custom.css" rel="stylesheet" type="text/css" /> <link href="CSS/ui.daterangepicker.css" rel="stylesheet" type="text/css" /> <style type="text/css"> .ui-daterangepicker { font-size: 10px; } </style> Then add this html: <asp:TextBox ID="TextBox1" runat="server" Font-Size="10px"></asp:TextBox><asp:Button ID="SubmitButton" runat="server" Text="Submit" OnClick="SubmitButton_Click" /> <span>First Date:</span><asp:Label ID="FirstDate" runat="server"></asp:Label> <span>Second Date:</span><asp:Label ID="SecondDate" runat="server"></asp:Label> As you can see,it includes TextBox1 which we are going to attach the daterangepicker to it,2 labels to show you later on by code on how to read the date from the textbox and set it to the labels Now we have to attach the daterangepicker to the textbox by using jQuery (Note:visit the author's website for more info on daterangerpicker's options and how to use them): <script type="text/javascript"> $(function() { $("#<%= TextBox1.ClientID %>").attr("readonly", "readonly"); $("#<%= TextBox1.ClientID %>").attr("unselectable", "on"); $("#<%= TextBox1.ClientID %>").daterangepicker({ presetRanges: [], arrows: true, dateFormat: 'd M, yy', clearValue: '', datepickerOptions: { changeMonth: true, changeYear: true} }); }); </script> Finally,add this C# code: protected void SubmitButton_Click(object sender, EventArgs e) { if (TextBox1.Text.Trim().Length == 0) { return; } string selectedDate = TextBox1.Text; if (selectedDate.Contains("-")) { DateTime startDate; DateTime endDate; string[] splittedDates = selectedDate.Split("-".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); if (splittedDates.Count() == 2 && DateTime.TryParse(splittedDates[0], out startDate) && DateTime.TryParse(splittedDates[1], out endDate)) { FirstDate.Text = startDate.ToShortDateString(); SecondDate.Text = endDate.ToShortDateString(); } else { //maybe the client has modified/altered the input i.e. hacking tools } } else { DateTime selectedDateObj; if (DateTime.TryParse(selectedDate, out selectedDateObj)) { FirstDate.Text = selectedDateObj.ToShortDateString(); SecondDate.Text = string.Empty; } else { //maybe the client has modified/altered the input i.e. hacking tools } } } This is the way on how to read from the textbox,That's it!. FAQ: 1-Why did you add this code?: <style type="text/css"> .ui-daterangepicker { font-size: 10px; } </style> A:For two reasons: 1)To show the Daterangepicker in a smaller size because it's original size is huge 2)To show you how to control the size of it. 2- Can I change the theme? A: yes you can,you will notice that I'm using Redmond theme which you will find it in jQuery UI website,visit their website and download a different theme,you may also have to make modifications to the css of daterangepicker,it's all yours. 3- Why did you add a font size to the textbox? A: To make the design look better,try to remove it and see by your self. 4- Can I register the script at codebehind? A: yes you can 5- I see you have added these two lines,what they do? $("#<%= TextBox1.ClientID %>").attr("readonly", "readonly"); $("#<%= TextBox1.ClientID %>").attr("unselectable", "on"); A:The first line will make the textbox not editable by the user,the second will block the blinking typing cursor from appearing if the user clicked on the textbox,you will notice that both lines are necessary to be used together,you can't just use one of them...for logical reasons of course. Finally,I hope everyone liked the article and as always,your feedbacks are always welcomed and if anyone have any suggestions or made any modifications that might be useful for anyone else then please post it at at the author's website and post a reference to your post here.

    Read the article

  • Error "E_UNEXPECTED(0x8000FFFF)" when using CDec/CInt/IsNumeric

    - by Marc vB
    I have encountered a strange problem, which I could solve but don't understand why it did occur. I have build a DLL with COM enabled. In this DLL I have classes that did use the functions CInt, CDec and IsNumeric. If I test these classes from a .NET application then it works ok. But when I called/run these classes from a Win32 application (with COM) then I did get an "E_UNEXPECTED(0x8000FFFF)" error. After some debugging I found out that the problem would go away if I: - replaced IsNumeric with Integer.TryParse or Decimal.TryParse - replaced CInt with Integer.Parse - replaced CDec with Decimal.Parse Can anyone explain this? Again, I could solve it by doing this but I would like to know why.

    Read the article

  • Convert String value format of YYYYMMDDHHMMSS to C# DateTime

    - by SARAVAN
    I have a need to convert a string value in the form "YYYYMMDDHHMMSS" to a DateTime. But not sure on how, may be a DateTime.Tryparse can be used to make this happen. Or is there any other way to do it. I can do this using some string operations to take "YYYYMMDD" alone, convert to a datetime and then add HH, MM, SS separately to that DateTime. But is there any DateTime.TryParse() methods that I can use in one line to convert a "YYYYMMDDHHMMSS" format string value to a DateTime value?

    Read the article

  • How can i use listDictionary?

    - by Phsika
    i can fill my listdictinary but, if running error returns to me in " foreach (string ky in ld.Keys)"(invalid operation Exception was unhandled) Error Detail : After creating a pointer to the list of sample collection has been changed. C# ListDictionary ld = new ListDictionary(); foreach (DataColumn dc in dTable.Columns) { MessageBox.Show(dTable.Rows[0][dc].ToString()); ld.Add(dc.ColumnName, dTable.Rows[0][dc].ToString()); } foreach (string ky in ld.Keys) if (int.TryParse(ld[ky].ToString(), out QuantityInt)) ld[ky] = "integer"; else if(double.TryParse(ld[ky].ToString(), out QuantityDouble)) ld[ky]="double"; else ld[ky]="nvarchar";

    Read the article

  • Specification

    Generally saying Specification is a predicate that determines if an object does or does not satisfy some criteria. By using Specifications you could easily recombine business logic together using boolean logic.Have you ever thought that bool TryParse(string s, out int result) is pattern?

    Read the article

  • claimsResponse Always Return Null

    - by Chirag Pandya
    hello i have a following code in asp.net. i have used DotNetOpenAuth.dll for openID. the code is under protected void openidValidator_ServerValidate(object source, ServerValidateEventArgs args) { // This catches common typos that result in an invalid OpenID Identifier. args.IsValid = Identifier.IsValid(args.Value); } protected void loginButton_Click(object sender, EventArgs e) { if (!this.Page.IsValid) { return; // don't login if custom validation failed. } try { using (OpenIdRelyingParty openid = this.createRelyingParty()) { IAuthenticationRequest request = openid.CreateRequest(this.openIdBox.Text); // This is where you would add any OpenID extensions you wanted // to include in the authentication request. ClaimsRequest objClmRequest = new ClaimsRequest(); objClmRequest.Email = DemandLevel.Request; objClmRequest.Country = DemandLevel.Request; request.AddExtension(objClmRequest); // Send your visitor to their Provider for authentication. request.RedirectToProvider(); } } catch (ProtocolException ex) { this.openidValidator.Text = ex.Message; this.openidValidator.IsValid = false; } } protected void Page_Load(object sender, EventArgs e) { this.openIdBox.Focus(); if (Request.QueryString["clearAssociations"] == "1") { Application.Remove("DotNetOpenAuth.OpenId.RelyingParty.OpenIdRelyingParty.ApplicationStore"); UriBuilder builder = new UriBuilder(Request.Url); builder.Query = null; Response.Redirect(builder.Uri.AbsoluteUri); } OpenIdRelyingParty openid = this.createRelyingParty(); var response = openid.GetResponse(); if (response != null) { switch (response.Status) { case AuthenticationStatus.Authenticated: // This is where you would look for any OpenID extension responses included // in the authentication assertion. var claimsResponse = response.GetExtension<ClaimsResponse>(); State.ProfileFields = claimsResponse; // Store off the "friendly" username to display -- NOT for username lookup State.FriendlyLoginName = response.FriendlyIdentifierForDisplay; // Use FormsAuthentication to tell ASP.NET that the user is now logged in, // with the OpenID Claimed Identifier as their username. FormsAuthentication.RedirectFromLoginPage(response.ClaimedIdentifier, false); break; case AuthenticationStatus.Canceled: this.loginCanceledLabel.Visible = true; break; case AuthenticationStatus.Failed: this.loginFailedLabel.Visible = true; break; // We don't need to handle SetupRequired because we're not setting // IAuthenticationRequest.Mode to immediate mode. ////case AuthenticationStatus.SetupRequired: //// break; } } } private OpenIdRelyingParty createRelyingParty() { OpenIdRelyingParty openid = new OpenIdRelyingParty(); int minsha, maxsha, minversion; if (int.TryParse(Request.QueryString["minsha"], out minsha)) { openid.SecuritySettings.MinimumHashBitLength = minsha; } if (int.TryParse(Request.QueryString["maxsha"], out maxsha)) { openid.SecuritySettings.MaximumHashBitLength = maxsha; } if (int.TryParse(Request.QueryString["minversion"], out minversion)) { switch (minversion) { case 1: openid.SecuritySettings.MinimumRequiredOpenIdVersion = ProtocolVersion.V10; break; case 2: openid.SecuritySettings.MinimumRequiredOpenIdVersion = ProtocolVersion.V20; break; default: throw new ArgumentOutOfRangeException("minversion"); } } return openid; } for above code i am always getting var claimsResponse = response.GetExtension<ClaimsResponse>(); i am always getting claimsResponse= null. what is the reason why it happen. is there any requirement which is required for openid like domain validation for RelyingParty?? please give me answer as soon as possible.

    Read the article

  • It&rsquo;s ok to throw System.Exception&hellip;

    - by Chris Skardon
    No. No it’s not. It’s not just me saying that, it’s the Microsoft guidelines: http://msdn.microsoft.com/en-us/library/ms229007.aspx  Do not throw System.Exception or System.SystemException. Also – as important: Do not catch System.Exception or System.SystemException in framework code, unless you intend to re-throw.. Throwing: Always, always try to pick the most specific exception type you can, if the parameter you have received in your method is null, throw an ArgumentNullException, value received greater than expected? ArgumentOutOfRangeException. For example: public void ArgChecker(int theInt, string theString) { if (theInt < 0) throw new ArgumentOutOfRangeException("theInt", theInt, "theInt needs to be greater than zero."); if (theString == null) throw new ArgumentNullException("theString"); if (theString.Length == 0) throw new ArgumentException("theString needs to have content.", "theString"); } Why do we want to do this? It’s a lot of extra code when compared with a simple: public void ArgChecker(int theInt, string theString) { if (theInt < 0 || string.IsNullOrWhiteSpace(theString)) throw new Exception("The parameters were invalid."); } It all comes down to a couple of things; the catching of the exceptions, and the information you are passing back to the calling code. Catching: Ok, so let’s go with introduction level Exception handling, taught by many-a-university: You do all your work in a try clause, and catch anything wrong in the catch clause. So this tends to give us code like this: try { /* All the shizzle */ } catch { /* Deal with errors */ } But of course, we can improve on that by catching the exception so we can report on it: try { } catch(Exception ex) { /* Log that 'ex' occurred? */ } Now we’re at the point where people tend to go: Brilliant, I’ve got exception handling nailed, what next??? and code gets littered with the catch(Exception ex) nastiness. Why is it nasty? Let’s imagine for a moment our code is throwing an ArgumentNullException which we’re catching in the catch block and logging. Ok, the log entry has been made, so we can debug the code right? We’ve got all the info… What about an OutOfMemoryException – what can we do with that? That’s right, not a lot, chances are you can’t even log it (you are out of memory after all), but you’ve caught it – and as such - have hidden it. So, as part of this, there are two things you can do one, is the rethrow method: try { /* code */ } catch (Exception ex) { //Log throw; } Note, it’s not catch (Exception ex) { throw ex; } as that will wipe all your important stack trace information. This does get your exception to continue, and is the only reason you would catch Exception (anywhere other than a global catch-all) in your code. The other preferred method is to catch the exceptions you can deal with. It may not matter that the string I’m passing in is null, and I can cope with it like this: try{ DoSomething(myString); } catch(ArgumentNullException){} And that’s fine, it means that any exceptions I can’t deal with (OutOfMemory for example) will be propagated out to other code that can deal with it. Of course, this is horribly messy, no one wants try / catch blocks everywhere and that’s why Microsoft added the ‘Try’ methods to the framework, and it’s a strategy we should continue. If I try: int i = (int) "one"; I will get an InvalidCastException which means I need the try / catch block, but I could mitigate this using the ‘TryParse’ method: int i; if(!Int32.TryParse("one", out i)) return; Similarly, in the ‘DoSomething’ example, it might be beneficial to have a ‘TryDoSomething’ that returns a boolean value indicating the success of continuing. Obviously this isn’t practical in every case, so use the ol’ common sense approach. Onwards Yer thanks Chris, I’m looking forward to writing tonnes of new code. Fear not, that is where helpers come into it… (but that’s the next post)

    Read the article

  • Best way to load application settings

    - by enzom83
    A simple way to keep the settings of a Java application is represented by a text file with ".properties" extension containing the identifier of each setting associated with a specific value (this value may be a number, string, date, etc..). C# uses a similar approach, but the text file must be named "App.config". In both cases, in source code you must initialize a specific class for reading settings: this class has a method that returns the value (as string) associated with the specified setting identifier. // Java example Properties config = new Properties(); config.load(...); String valueStr = config.getProperty("listening-port"); // ... // C# example NameValueCollection setting = ConfigurationManager.AppSettings; string valueStr = setting["listening-port"]; // ... In both cases we should parse strings loaded from the configuration file and assign the ??converted values to the related typed objects (parsing errors could occur during this phase). After the parsing step, we must check that the setting values ??belong to a specific domain of validity: for example, the maximum size of a queue should be a positive value, some values ??may be related (example: min < max), and so on. Suppose that the application should load the settings as soon as it starts: in other words, the first operation performed by the application is to load the settings. Any invalid values for the settings ??must be replaced automatically with default values??: if this happens to a group of related settings, those settings are all set with default values. The easiest way to perform these operations is to create a method that first parses all the settings, then checks the loaded values ??and finally sets any default values??. However maintenance is difficult if you use this approach: as the number of settings increases while developing the application, it becomes increasingly difficult to update the code. In order to solve this problem, I had thought of using the Template Method pattern, as follows. public abstract class Setting { protected abstract bool TryParseValues(); protected abstract bool CheckValues(); public abstract void SetDefaultValues(); /// <summary> /// Template Method /// </summary> public bool TrySetValuesOrDefault() { if (!TryParseValues() || !CheckValues()) { // parsing error or domain error SetDefaultValues(); return false; } return true; } } public class RangeSetting : Setting { private string minStr, maxStr; private byte min, max; public RangeSetting(string minStr, maxStr) { this.minStr = minStr; this.maxStr = maxStr; } protected override bool TryParseValues() { return (byte.TryParse(minStr, out min) && byte.TryParse(maxStr, out max)); } protected override bool CheckValues() { return (0 < min && min < max); } public override void SetDefaultValues() { min = 5; max = 10; } } The problem is that in this way we need to create a new class for each setting, even for a single value. Are there other solutions to this kind of problem? In summary: Easy maintenance: for example, the addition of one or more parameters. Extensibility: a first version of the application could read a single configuration file, but later versions may give the possibility of a multi-user setup (admin sets up a basic configuration, users can set only certain settings, etc..). Object oriented design.

    Read the article

  • How can I use Convert.ChangeType to convert string into numerics with group separator?

    - by Loic
    Hello, I want to make a generic string to numeric converter, and provide it as a string extension, so I wrote the following code: public static bool TryParse<T>( this string text, out T result, IFormatProvider formatProvider ) where T : struct try { result = (T)Convert.ChangeType( text, typeof( T ), formatProvider ); return true; } catch(... I call it like this: int value; var ok = "123".TryParse(out value, NumberFormatInfo.CurrentInfo) It works fine until I want to use a group separator: As I live in France, where the thousand separator is a space and the decimal separator is a comma, the string "1 234 567,89" should be equals to 1234567.89 (in Invariant culture). But, the function crashes! When a try to perform a non generic conversion, like double.Parse(...), I can use an overload which accepts a NumberStyles parameter. I specify NumberStyles.Number and this time it works! So, the questions are : Why the parsing does not respect my NumberFormatInfo (where the NumberGroupSeparator is well specified to a space, as I specified in my OS) How could I make work the generic version with Convert.ChangeTime, as it has no overload wich accepts a NumberStyles parameter ?

    Read the article

  • Converting string to a simple type

    - by zespri
    .Net framework contains a great class named Convert that allows conversion between simple types, DateTime type and String type. Also the class support conversion of the types implementing IConvertible interface. The class has been implemented in the very first version of .Net framework. There were a few things in the first .Net framework that were not done quite right. For example .Parse methods on simple types would throw an exception if the string couldn't be parsed and there would be no way to check if exception is going to be thrown in advance. A future version of .Net Framework removed this deficiency by introducing the TryParse method that resolved this problem. The Convert class dates back to time of the old Parse method, so the ChangeType method on this class in implemented old style - if conversion can't be performed an exception is thrown. Take a look at the following code: public static T ConvertString<T>(string s, T @default) { try { return (T)Convert.ChangeType(s, typeof(T), CultureInfo.InvariantCulture); } catch (Exception) { return @default; } } This code basically does what I want. However I would pretty much like to avoid the ugly try/catch here. I'm sure, that similar to TryParse, there is a modern method of rewriting this code without the catch-all. Could you suggest one?

    Read the article

  • How to match a period in Regex coming from Firefox browser?

    - by Dr. Zim
    I have the following C# code which should match a quantity / $ price string like "4/$3.99". It works all day long until we use it against a string returned from Firefox Browser. 77.77 becomes 77 (dropping the .77 cents). var matches = Regex.Match(_priceText, @"^\s?((?<qty>\d+)\s?/)?\s?[$]?\s?(?<price>[0-9]?\.?[0-9]?[0-9]?)"); if( matches.Success) { if (!Decimal.TryParse(matches.Groups["price"].Value, out this._price)) this._price = 0.0m; if (!Int32.TryParse(matches.Groups["qty"].Value, out this._qty)) this._qty = (this._price > 0 ? 1 : 0); else if (this._price > 0 && this._qty == 0) this._qty = 1; } Any idea why the period wouldn't match coming from a Firefox string, but the C# string matches? There isn't any special about the Firefox we used. It's a plain Jane 1252 code page download right off the Firefox site. The computer's local settings are unaltered North American, etc. We have two different computers showing the same effects. It's Firefox 3.6.4, nothing fancy or beta.

    Read the article

  • Monitoring ASP.NET Application

    - by imran_ku07
        Introduction:          There are times when you may need to monitor your ASP.NET application's CPU and memory consumption, so that you can fine-tune your ASP.NET application(whether Web Form, MVC or WebMatrix). Also, sometimes you may need to see all the exceptions(and their details) of your application raising, whether they are handled or not. If you are creating an ASP.NET application in .NET Framework 4.0, then you can easily monitor your application's CPU or memory consumption and see how many exceptions your application raising. In this article I will show you how you can do this.       Description:           With .NET Framework 4.0, you can turn on the monitoring of CPU and memory consumption by setting AppDomain.MonitoringEnabled property to true. Also, in .NET Framework 4.0, you can register a callback method to AppDomain.FirstChanceException event to monitor the exceptions being thrown within your application's AppDomain. Turning on the monitoring and registering a callback method will add some additional overhead to your application, which will hurt your application performance. So it is better to turn on these features only if you have following properties in web.config file,   <add key="AppDomainMonitoringEnabled" value="true"/> <add key="FirstChanceExceptionMonitoringEnabled" value="true"/>             In case if you wonder what does FirstChanceException mean. It simply means the first notification of an exception raised by your application. Even CLR invokes this notification before the catch block that handles the exception. Now just update global.asax.cs file as,   string _item = "__RequestExceptionKey"; protected void Application_Start() { SetupMonitoring(); } private void SetupMonitoring() { bool appDomainMonitoringEnabled, firstChanceExceptionMonitoringEnabled; bool.TryParse(ConfigurationManager.AppSettings["AppDomainMonitoringEnabled"], out appDomainMonitoringEnabled); bool.TryParse(ConfigurationManager.AppSettings["FirstChanceExceptionMonitoringEnabled"], out firstChanceExceptionMonitoringEnabled); if (appDomainMonitoringEnabled) { AppDomain.MonitoringIsEnabled = true; } if (firstChanceExceptionMonitoringEnabled) { AppDomain.CurrentDomain.FirstChanceException += (object source, FirstChanceExceptionEventArgs e) => { if (HttpContext.Current == null)// If no context available, ignore it return; if (HttpContext.Current.Items[_item] == null) HttpContext.Current.Items[_item] = new RequestException { Exceptions = new List<Exception>() }; (HttpContext.Current.Items[_item] as RequestException).Exceptions.Add(e.Exception); }; } } protected void Application_EndRequest() { if (Context.Items[_item] != null) { //Only add the request if atleast one exception is raised var reqExc = Context.Items[_item] as RequestException; reqExc.Url = Request.Url.AbsoluteUri; Application.Lock(); if (Application["AllExc"] == null) Application["AllExc"] = new List<RequestException>(); (Application["AllExc"] as List<RequestException>).Add(reqExc); Application.UnLock(); } }               Now browse to Monitoring.cshtml file, you will see the following screen,                            The above screen shows you the total bytes allocated, total bytes in use and CPU usage of your application. The above screen also shows you all the exceptions raised by your application which is very helpful for you. I have uploaded a sample project on github at here. You can find Monitoring.cshtml file on this sample project. You can use this approach in ASP.NET MVC, ASP.NET WebForm and WebMatrix application.       Summary:          This is very important for administrators/developers to manage and administer their web application after deploying to production server. This article will help administrators/developers to see the memory and CPU usage of their web application. This will also help administrators/developers to see all the exceptions your application is throwing whether they are swallowed or not. Hopefully you will enjoy this article too.   SyntaxHighlighter.all()

    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

  • String to DateTime in C# to save in SQL server

    - by Ashwani K
    Hello All: I am an issue while converting "March 16-17" to DateTime and saving it to SQL server. "March 16-17" as it looks, read as March 16 to March 17, which in my case is invalid, but C# DateTime.TryParse() is treating "March 16 -17" as March 16, 2017 which is wrong, and saving the data in SQL server. SQL server treats "March 16-17" as invalid. So, can some body tell me how to use SQL server datetime validation in C#. Thanks Ashwani

    Read the article

  • which version of the code below is right?

    - by TheVillageIdiot
    Hi I found this function in a utilities code file: Version 1: public static bool IsValidLong(string strLong) { bool result = true; try { long tmp = long.Parse(strLong); } catch (Exception ex) { result = false; } return result; } I want to replace this (and validators for other types) with following: Version 2: public static bool IsValidLong(string strLong) { long l; return long.TryParse(strLong, out l); } which version is better and why?

    Read the article

  • DataGridView validating old value insted of new value.

    - by Scott Chamberlain
    I have a DataGridView that is bound to a DataTable, it has a column that is a double and the values need to be between 0 and 1. Here is my code private void dgvImpRDP_InfinityRDPLogin_CellValidating(object sender, DataGridViewCellValidatingEventArgs e) { if (e.ColumnIndex == dtxtPercentageOfUsersAllowed.Index) { double percentage; if(dgvImpRDP_InfinityRDPLogin[e.ColumnIndex, e.RowIndex].Value.GetType() == typeof(double)) percentage = (double)dgvImpRDP_InfinityRDPLogin[e.ColumnIndex, e.RowIndex].Value; else if (!double.TryParse(dgvImpRDP_InfinityRDPLogin[e.ColumnIndex, e.RowIndex].Value.ToString(), out percentage)) { e.Cancel = true; dgvImpRDP_InfinityRDPLogin[e.ColumnIndex, e.RowIndex].ErrorText = "The value must be between 0 and 1"; return; } if (percentage < 0 || percentage > 1) { e.Cancel = true; dgvImpRDP_InfinityRDPLogin[e.ColumnIndex, e.RowIndex].ErrorText = "The value must be between 0 and 1"; } } } However my issue when dgvImpRDP_InfinityRDPLogin_CellValidating fires dgvImpRDP_InfinityRDPLogin[e.ColumnIndex, e.RowIndex].Value will contain the old value before the edit, not the new value. For example lets say the old value was .1 and I enter 3. The above code runs when you exit the cell and dgvImpRDP_InfinityRDPLogin[e.ColumnIndex, e.RowIndex].Value will be .1 for that run, the code validates and writes 3 the data to the DataTable. I click on it a second time, try to leave, and this time it behaves like it should, it raises the error icon for the cell and prevents me from leaving. I try to enter the correct value (say .7) but the the Value will still be 3 and there is now no way out of the cell because it is locked due to the error and my validation code will never push the new value. Any recommendations would be greatly appreciated. EDIT -- New version of the code based off of Stuart's suggestion and mimicking the style the MSDN article uses. Still behaves the same. private void dgvImpRDP_InfinityRDPLogin_CellValidating(object sender, DataGridViewCellValidatingEventArgs e) { if (e.ColumnIndex == dtxtPercentageOfUsersAllowed.Index) { dgvImpRDP_InfinityRDPLogin[e.ColumnIndex, e.RowIndex].ErrorText = String.Empty; double percentage; if (!double.TryParse(dgvImpRDP_InfinityRDPLogin[e.ColumnIndex, e.RowIndex].FormattedValue.ToString(), out percentage) || percentage < 0 || percentage > 1) { e.Cancel = true; dgvImpRDP_InfinityRDPLogin[e.ColumnIndex, e.RowIndex].ErrorText = "The value must be between 0 and 1"; return; } } }

    Read the article

  • C#: Object having two constructors: how to limit which properties are set together?

    - by Dr. Zim
    Say you have a Price object that accepts either an (int quantity, decimal price) or a string containing "4/$3.99". Is there a way to limit which properties can be set together? Feel free to correct me in my logic below. The Test: A and B are equal to each other, but the C example should not be allowed. Thus the question How to enforce that all three parameters are not invoked as in the C example? AdPrice A = new AdPrice { priceText = "4/$3.99"}; // Valid AdPrice B = new AdPrice { qty = 4, price = 3.99m}; // Valid AdPrice C = new AdPrice { qty = 4, priceText = "2/$1.99", price = 3.99m};// Not The class: public class AdPrice { private int _qty; private decimal _price; private string _priceText; The constructors: public AdPrice () : this( qty: 0, price: 0.0m) {} // Default Constructor public AdPrice (int qty = 0, decimal price = 0.0m) { // Numbers only this.qty = qty; this.price = price; } public AdPrice (string priceText = "0/$0.00") { // String only this.priceText = priceText; } The Methods: private void SetPriceValues() { var matches = Regex.Match(_priceText, @"^\s?((?<qty>\d+)\s?/)?\s?[$]?\s?(?<price>[0-9]?\.?[0-9]?[0-9]?)"); if( matches.Success) { if (!Decimal.TryParse(matches.Groups["price"].Value, out this._price)) this._price = 0.0m; if (!Int32.TryParse(matches.Groups["qty"].Value, out this._qty)) this._qty = (this._price > 0 ? 1 : 0); else if (this._price > 0 && this._qty == 0) this._qty = 1; } } private void SetPriceString() { this._priceText = (this._qty > 1 ? this._qty.ToString() + '/' : "") + String.Format("{0:C}",this.price); } The Accessors: public int qty { get { return this._qty; } set { this._qty = value; this.SetPriceString(); } } public decimal price { get { return this._price; } set { this._price = value; this.SetPriceString(); } } public string priceText { get { return this._priceText; } set { this._priceText = value; this.SetPriceValues(); } } }

    Read the article

  • C# Performance on Errors

    - by pm_2
    It would appear that catching an error is slower that performing a check prior to the error (for example a TryParse). The related questions that prompt this observation are here and here. Can anyone tell me why this is so - why is it more costly to catch an error that to perform one or many checks of the data to prevent the error?

    Read the article

  • What useful minor features of C# 4.0 can you list?

    - by sashaeve
    C# 4.0 has a lot of new major features such as dynamic type, covariance and contravariance, named arguments etc. But C# 4.0 contains new minor (but useful) changes such as TryParse method for TimeSpan, Enum, Guid data types, String.IsNullOrWhiteSpace, System.IO.Stream.CopyTo etc. What other minor and useful features of C# 4.0 can you list?

    Read the article

  • Dynamic Type to do away with Reflection

    - by Rick Strahl
    The dynamic type in C# 4.0 is a welcome addition to the language. One thing I’ve been doing a lot with it is to remove explicit Reflection code that’s often necessary when you ‘dynamically’ need to walk and object hierarchy. In the past I’ve had a number of ReflectionUtils that used string based expressions to walk an object hierarchy. With the introduction of dynamic much of the ReflectionUtils code can be removed for cleaner code that runs considerably faster to boot. The old Way - Reflection Here’s a really contrived example, but assume for a second, you’d want to dynamically retrieve a Page.Request.Url.AbsoluteUrl based on a Page instance in an ASP.NET Web Page request. The strongly typed version looks like this: string path = Page.Request.Url.AbsolutePath; Now assume for a second that Page wasn’t available as a strongly typed instance and all you had was an object reference to start with and you couldn’t cast it (right I said this was contrived :-)) If you’re using raw Reflection code to retrieve this you’d end up writing 3 sets of Reflection calls using GetValue(). Here’s some internal code I use to retrieve Property values as part of ReflectionUtils: /// <summary> /// Retrieve a property value from an object dynamically. This is a simple version /// that uses Reflection calls directly. It doesn't support indexers. /// </summary> /// <param name="instance">Object to make the call on</param> /// <param name="property">Property to retrieve</param> /// <returns>Object - cast to proper type</returns> public static object GetProperty(object instance, string property) { return instance.GetType().GetProperty(property, ReflectionUtils.MemberAccess).GetValue(instance, null); } If you want more control over properties and support both fields and properties as well as array indexers a little more work is required: /// <summary> /// Parses Properties and Fields including Array and Collection references. /// Used internally for the 'Ex' Reflection methods. /// </summary> /// <param name="Parent"></param> /// <param name="Property"></param> /// <returns></returns> private static object GetPropertyInternal(object Parent, string Property) { if (Property == "this" || Property == "me") return Parent; object result = null; string pureProperty = Property; string indexes = null; bool isArrayOrCollection = false; // Deal with Array Property if (Property.IndexOf("[") > -1) { pureProperty = Property.Substring(0, Property.IndexOf("[")); indexes = Property.Substring(Property.IndexOf("[")); isArrayOrCollection = true; } // Get the member MemberInfo member = Parent.GetType().GetMember(pureProperty, ReflectionUtils.MemberAccess)[0]; if (member.MemberType == MemberTypes.Property) result = ((PropertyInfo)member).GetValue(Parent, null); else result = ((FieldInfo)member).GetValue(Parent); if (isArrayOrCollection) { indexes = indexes.Replace("[", string.Empty).Replace("]", string.Empty); if (result is Array) { int Index = -1; int.TryParse(indexes, out Index); result = CallMethod(result, "GetValue", Index); } else if (result is ICollection) { if (indexes.StartsWith("\"")) { // String Index indexes = indexes.Trim('\"'); result = CallMethod(result, "get_Item", indexes); } else { // assume numeric index int index = -1; int.TryParse(indexes, out index); result = CallMethod(result, "get_Item", index); } } } return result; } /// <summary> /// Returns a property or field value using a base object and sub members including . syntax. /// For example, you can access: oCustomer.oData.Company with (this,"oCustomer.oData.Company") /// This method also supports indexers in the Property value such as: /// Customer.DataSet.Tables["Customers"].Rows[0] /// </summary> /// <param name="Parent">Parent object to 'start' parsing from. Typically this will be the Page.</param> /// <param name="Property">The property to retrieve. Example: 'Customer.Entity.Company'</param> /// <returns></returns> public static object GetPropertyEx(object Parent, string Property) { Type type = Parent.GetType(); int at = Property.IndexOf("."); if (at < 0) { // Complex parse of the property return GetPropertyInternal(Parent, Property); } // Walk the . syntax - split into current object (Main) and further parsed objects (Subs) string main = Property.Substring(0, at); string subs = Property.Substring(at + 1); // Retrieve the next . section of the property object sub = GetPropertyInternal(Parent, main); // Now go parse the left over sections return GetPropertyEx(sub, subs); } As you can see there’s a fair bit of code involved into retrieving a property or field value reliably especially if you want to support array indexer syntax. This method is then used by a variety of routines to retrieve individual properties including one called GetPropertyEx() which can walk the dot syntax hierarchy easily. Anyway with ReflectionUtils I can  retrieve Page.Request.Url.AbsolutePath using code like this: string url = ReflectionUtils.GetPropertyEx(Page, "Request.Url.AbsolutePath") as string; This works fine, but is bulky to write and of course requires that I use my custom routines. It’s also quite slow as the code in GetPropertyEx does all sorts of string parsing to figure out which members to walk in the hierarchy. Enter dynamic – way easier! .NET 4.0’s dynamic type makes the above really easy. The following code is all that it takes: object objPage = Page; // force to object for contrivance :) dynamic page = objPage; // convert to dynamic from untyped object string scriptUrl = page.Request.Url.AbsolutePath; The dynamic type assignment in the first two lines turns the strongly typed Page object into a dynamic. The first assignment is just part of the contrived example to force the strongly typed Page reference into an untyped value to demonstrate the dynamic member access. The next line then just creates the dynamic type from the Page reference which allows you to access any public properties and methods easily. It also lets you access any child properties as dynamic types so when you look at Intellisense you’ll see something like this when typing Request.: In other words any dynamic value access on an object returns another dynamic object which is what allows the walking of the hierarchy chain. Note also that the result value doesn’t have to be explicitly cast as string in the code above – the compiler is perfectly happy without the cast in this case inferring the target type based on the type being assigned to. The dynamic conversion automatically handles the cast when making the final assignment which is nice making for natural syntnax that looks *exactly* like the fully typed syntax, but is completely dynamic. Note that you can also use indexers in the same natural syntax so the following also works on the dynamic page instance: string scriptUrl = page.Request.ServerVariables["SCRIPT_NAME"]; The dynamic type is going to make a lot of Reflection code go away as it’s simply so much nicer to be able to use natural syntax to write out code that previously required nasty Reflection syntax. Another interesting thing about the dynamic type is that it actually works considerably faster than Reflection. Check out the following methods that check performance: void Reflection() { Stopwatch stop = new Stopwatch(); stop.Start(); for (int i = 0; i < reps; i++) { // string url = ReflectionUtils.GetProperty(Page,"Title") as string;// "Request.Url.AbsolutePath") as string; string url = Page.GetType().GetProperty("Title", ReflectionUtils.MemberAccess).GetValue(Page, null) as string; } stop.Stop(); Response.Write("Reflection: " + stop.ElapsedMilliseconds.ToString()); } void Dynamic() { Stopwatch stop = new Stopwatch(); stop.Start(); dynamic page = Page; for (int i = 0; i < reps; i++) { string url = page.Title; //Request.Url.AbsolutePath; } stop.Stop(); Response.Write("Dynamic: " + stop.ElapsedMilliseconds.ToString()); } The dynamic code runs in 4-5 milliseconds while the Reflection code runs around 200+ milliseconds! There’s a bit of overhead in the first dynamic object call but subsequent calls are blazing fast and performance is actually much better than manual Reflection. Dynamic is definitely a huge win-win situation when you need dynamic access to objects at runtime.© Rick Strahl, West Wind Technologies, 2005-2010Posted in .NET  CSharp  

    Read the article

< Previous Page | 1 2 3 4 5 6  | Next Page >