Daily Archives

Articles indexed Sunday June 3 2012

Page 7/14 | < Previous Page | 3 4 5 6 7 8 9 10 11 12 13 14  | Next Page >

  • Passing variables from SQL proceedure to PHP

    - by Sam Corbet
    I am trying to create an sql proceedure that will return the results back to the php page. I want to be able to call the procedure as follows from the php call procedure_name($var1) which will run this script: -- --------------------------------------------------------------------------------- -- pUIGetCliStmtGenFlag -- -- This procedure returns the status of the Trading Period: -- -- --------------------------------------------------------------------------------- drop procedure if exists pUIGetCliStmtGenFlag; delimiter // create procedure pUIGetCliStmtGenFlag( IN pTradingPeriodMonth DATE ) MODIFIES SQL DATA COMMENT 'Checks if the TP has been closed' begin SELECT trading_period_month, dt_end, amt_traded_system_ccy FROM ca_trading_period WHERE trading_period_month=$var1 -- If amt_traded_system_ccy is NULL give the TP an open status otherwise mark as closed IF amt_traded_system_ccy is NULL $tpstatus='open' ELSE $tpstatus='closed' end; // delimiter ; I then want to be able to use $tpstatus in the rest of the php script. I know this is simple but this is completely new to me and I cant find the correct method

    Read the article

  • CSS with Java Script

    - by Field
    I have been at this for a long time. I have a css div that is center on page. It floats on bottom. When I add content to div #menu i can not get it to shift right. I want to add full menu that float on the page. It have a live chat button coded. It just does not seem to work right #menu { background: url("grid2.gif") repeat scroll 0 0 transparent; margin:0 auto; border: 0px solid #888888; color: #FFFFFF; display: block; font-weight: bold; padding: 0px; position: fixed; align: right; bottom: 30px; width: 970px; } * html #menu { position: absolute; } #menu a:visited, #menu a { color: #000000; display: block; height: 20px; line-height: 20px; margin: 0 auto; text-align: center; text-decoration: none; } <div id="menu"><script language="JavaScript" src="/livehelp/js/status_image.php?base_url=/livehelp&l=adminlive&x=1&deptid=1&"></a></script></div>

    Read the article

  • Google Maps InfoBubble pixelOffset

    - by Sam
    I am trying to implement a custom infoBubble that has the box opening to the side of a marker. This has turned out to be harder than expected. Using the normal infoWindow you can use pixelOffset. See here for the documentation Using infoBubble this does not seem to be the case. Is there anyway of using pixelOffset in an infoBubble, or something that will do the same thing? I have found this very difficult to search for, as using a google search such as this returns no relevant results Google Search Below is all my resources I have been using. Example of infoBubble here. My JavaScript to setup the map and infoBubble here. And now my javascript here just in-case the jsfiddle link is broken. <script type="text/javascript"> $(document).ready(function () { init(); }); function init() { //Setup the map var googleMapOptions = { center: new google.maps.LatLng(53.5167, -1.1333), zoom: 13, mapTypeId: google.maps.MapTypeId.ROADMAP }; //Start the map var map = new google.maps.Map(document.getElementById("map_canvas"), googleMapOptions); var marker = new google.maps.Marker({ position: new google.maps.LatLng(53.5267, -1.1333), title: "Just a test" }); marker.setMap(map); infoBubble = new InfoBubble({ map: map, content: '<div class="phoneytext">Some label</div>', //position: new google.maps.LatLng(-35, 151), shadowStyle: 1, padding: '10px', //backgroundColor: 'rgb(57,57,57)', borderRadius: 5, minWidth: 200, arrowSize: 10, borderWidth: 1, borderColor: '#2c2c2c', disableAutoPan: true, hideCloseButton: false, arrowPosition: 7, backgroundClassName: 'phoney', pixelOffset: new google.maps.Size(130, 120), arrowStyle: 2 }); infoBubble.open(map, marker); } </script>

    Read the article

  • Infinite loop when using fscanf

    - by user1409641
    I wrote this simple program in C, because I'm studying FILES right now at University. I take a txt file with a list of the results of the last race so my program will show the data formatted as I want. Here's my code: /* Esercizio file Motogp */ #include <stdio.h> #define SIZE 20 int main () { int pos, punt, num; float kmh; char nome[SIZE+1], cognome[SIZE+1], moto[SIZE+1]; char naz[SIZE+1], nome_file[SIZE+1]; FILE *fp; printf ("Inserisci il nome del file da aprire: "); gets (nome_file); fp = fopen (nome_file, "r"); if (fopen == NULL) printf ("Errore nell' apertura del file %s\n", nome_file); else { while (fscanf (fp, "%d %d %d %s %s %s %s %.2f", &pos, &punt, &num, nome, cognome, naz, moto, &kmh) != EOF ) { printf ("Posizione di arrivo: %d\n", pos); printf ("Punteggio: %d\n", punt); printf ("Numero pilota: %d\n", num); printf ("Nome pilota: %s\n", nome); printf ("Cognome pilota: %s\n", cognome); printf ("Nazione: %s\n", naz); printf ("Moto: %s\n", moto); printf ("Media Kmh: %d\n\n", kmh); } } fclose(fp); return 0; } and there's my txt file: 1 25 99 Jorge LORENZO SPA Yamaha 164.4 2 20 26 Dani PEDROSA SPA Honda 164.1 3 16 4 Andrea DOVIZIOSO ITA Yamaha 163.8 4 13 1 Casey STONER AUS Honda 163.8 5 11 35 Cal CRUTCHLOW GBR Yamaha 163.6 6 10 19 Alvaro BAUTISTA SPA Honda 163.5 7 9 46 Valentino ROSSI ITA Ducati 163.3 8 8 6 Stefan BRADL GER Honda 162.9 9 7 69 Nicky HAYDEN USA Ducati 162.5 10 6 11 Ben SPIES USA Yamaha 162.3 11 5 8 Hector BARBERA SPA Ducati 162.1 12 4 17 Karel ABRAHAM CZE Ducati 160.9 13 3 41 Aleix ESPARGARO SPA ART 160.2 14 2 51 Michele PIRRO ITA FTR 160.1 15 1 14 Randy DE PUNIET FRA ART 160.0 16 0 77 James ELLISON GBR ART 159.9 17 0 54 Mattia PASINI ITA ART 159.4 18 0 68 Yonny HERNANDEZ COL BQR 159.4 19 0 9 Danilo PETRUCCI ITA Ioda 158.2 20 0 22 Ivan SILVA SPA BQR 158.2 When I run my program, it return me an infinite loop of the first one. Why? Is there another function to read those data?

    Read the article

  • Wrap words in tags, keep markup

    - by spacevillain
    For example I have a string with markup (from html node): hello, this is dog "h<em>e<strong>llo, thi</strong>s i</em><strong>s d</strong>og" What is the most correct way to find some words in it (let's say "hello" and "dog"), wrap them in a span (make a highlight) and save all the markup? Desired output is something like this (notice properly closed tags) <span class="highlight">h<em>e<strong>llo</strong></em></span><strong>,</strong> <em><strong>thi</strong>s<em> i</em><strong>s <span class="highlight"><strong>d</strong>og</span> Looks the same as it should: hello, this is dog

    Read the article

  • Refactoring code/consolidating functions (e.g. nested for-loop order)

    - by bmay2
    Just a little background: I'm making a program where a user inputs a skeleton text, two numbers (lower and upper limit), and a list of words. The outputs are a series of modifications on the skeleton text. Sample inputs: text = "Player # likes @." (replace # with inputted integers and @ with words in list) lower = 1 upper = 3 list = "apples, bananas, oranges" The user can choose to iterate over numbers first: Player 1 likes apples. Player 2 likes apples. Player 3 likes apples. Or words first: Player 1 likes apples. Player 1 likes bananas. Player 1 likes oranges. I chose to split these two methods of outputs by creating a different type of dictionary based on either number keys (integers inputted by the user) or word keys (from words in the inputted list) and then later iterating over the values in the dictionary. Here are the two types of dictionary creation: def numkey(dict): # {1: ['Player 1 likes apples', 'Player 1 likes...' ] } text, lower, upper, list = input_sort(dict) d = {} for num in range(lower,upper+1): l = [] for i in list: l.append(text.replace('#', str(num)).replace('@', i)) d[num] = l return d def wordkey(dict): # {'apples': ['Player 1 likes apples', 'Player 2 likes apples'..] } text, lower, upper, list = input_sort(dict) d = {} for i in list: l = [] for num in range(lower,upper+1): l.append(text.replace('#', str(num)).replace('@', i)) d[i] = l return d It's fine that I have two separate functions for creating different types of dictionaries but I see a lot of repetition between the two. Is there any way I could make one dictionary function and pass in different values to it that would change the order of the nested for loops to create the specific {key : value} pairs I'm looking for? I'm not sure how this would be done. Is there anything related to functional programming or other paradigms that might help with this? The question is a little abstract and more stylistic/design-oriented than anything.

    Read the article

  • ASP NET forms Authorization: how to reduce duration?

    - by eddo
    I've got a web page which is implementing cookie based ASPNET Forms Authentication. Once the user has logged in the page, he can edit some information using a form which is created using a partialview and returned to him as a dialog for editing. The action linked to the partial view is decorated as follows: [HttpGet] [OutputCache(Duration = 0, VaryByParam = "None")] [Authorize(Roles = "test")] public ActionResult changeTripInfo(int tripID, bool ovride=false) { ... } The problem i am experiencing is the latency between the request and the time when the dialog is shown to the user: time ranges between 800 and 1100 ms which is not justified by the complexity of the form. Investigating with Glimpse turns out that the time to process the AuthorizeAttribute (see snip) sums up to at least 650 ms which is troubling me. Looking at the Sql server log, the call which checks the user roles takes, as expected, virtually nothing (duration 0). How can I reduce this time? Am I missing some optimization?

    Read the article

  • In SQL How do I copy values from one table to another based on another field's value?

    - by Joshua1729
    Okay I have two tables VOUCHERT with the following fields ACTIVATIONCODE SERIALNUMBER VOUCHERDATADBID UNAVAILABLEAT UNAVAILABLEOPERATORDBID AVAILABLEAT AVAILABLEOPERATORDBID ACTIVATIONCODENEW EXT1 EXT2 EXT3 DENOMINATION -- I added this column into the table. and the second table is VOUCHERDATAT with the following fields VOUCHERDATADBID BATCHID VALUE CURRENCY VOUCHERGROUP EXPIRYDATE AGENT EXT1 EXT2 EXT3 What I want to do is copy the corresponding VALUE from VOUCHERDATAT and put it into DENOMINATION of VOUCHERT. The linking between the two is VOUCHERDATADBID. How do I go about it? It is not a 1:1 mapping. What I mean is there may be 1000 SERIALNUMBERS with a same VOUCHERDATADBID. And that VOUCHERDATADBID has only entry in VOUCHERDATAT, hence one value. Therefore, all serial numbers belonging to a certain VOUCHERDATADBID will have the same value. Will JOINS work? What type of JOIN should I use? Or is UPDATE table the way to go? Thanks for the help !!

    Read the article

  • Creating a custom module for Orchard

    - by Moran Monovich
    I created a custom module using this guide from Orchard documentation, but for some reason I can't see the fields in the content type when I want to create a new one. this is my model: public class CustomerPartRecord : ContentPartRecord { public virtual string FirstName { get; set; } public virtual string LastName { get; set; } public virtual int PhoneNumber { get; set; } public virtual string Address { get; set; } public virtual string Profession { get; set; } public virtual string ProDescription { get; set; } public virtual int Hours { get; set; } } public class CustomerPart : ContentPart<CustomerPartRecord> { [Required(ErrorMessage="you must enter your first name")] [StringLength(200)] public string FirstName { get { return Record.FirstName; } set { Record.FirstName = value; } } [Required(ErrorMessage = "you must enter your last name")] [StringLength(200)] public string LastName { get { return Record.LastName; } set { Record.LastName = value; } } [Required(ErrorMessage = "you must enter your phone number")] [DataType(DataType.PhoneNumber)] public int PhoneNumber { get { return Record.PhoneNumber; } set { Record.PhoneNumber = value; } } [StringLength(200)] public string Address { get { return Record.Address; } set { Record.Address = value; } } [Required(ErrorMessage = "you must enter your profession")] [StringLength(200)] public string Profession { get { return Record.Profession; } set { Record.Profession = value; } } [StringLength(500)] public string ProDescription { get { return Record.ProDescription; } set { Record.ProDescription = value; } } [Required(ErrorMessage = "you must enter your hours")] public int Hours { get { return Record.Hours; } set { Record.Hours = value; } } } this is the Handler: class CustomerHandler : ContentHandler { public CustomerHandler(IRepository<CustomerPartRecord> repository) { Filters.Add(StorageFilter.For(repository)); } } the Driver: class CustomerDriver : ContentPartDriver<CustomerPart> { protected override DriverResult Display(CustomerPart part, string displayType, dynamic shapeHelper) { return ContentShape("Parts_Customer", () => shapeHelper.Parts_BankCustomer( FirstName: part.FirstName, LastName: part.LastName, PhoneNumber: part.PhoneNumber, Address: part.Address, Profession: part.Profession, ProDescription: part.ProDescription, Hours: part.Hours)); } //GET protected override DriverResult Editor(CustomerPart part, dynamic shapeHelper) { return ContentShape("Parts_Customer", () => shapeHelper.EditorTemplate( TemplateName:"Parts/Customer", Model: part, Prefix: Prefix)); } //POST protected override DriverResult Editor(CustomerPart part, IUpdateModel updater, dynamic shapeHelper) { updater.TryUpdateModel(part, Prefix, null, null); return Editor(part, shapeHelper); } the migration: public class Migrations : DataMigrationImpl { public int Create() { // Creating table CustomerPartRecord SchemaBuilder.CreateTable("CustomerPartRecord", table => table .ContentPartRecord() .Column("FirstName", DbType.String) .Column("LastName", DbType.String) .Column("PhoneNumber", DbType.Int32) .Column("Address", DbType.String) .Column("Profession", DbType.String) .Column("ProDescription", DbType.String) .Column("Hours", DbType.Int32) ); return 1; } public int UpdateFrom1() { ContentDefinitionManager.AlterPartDefinition("CustomerPart", builder => builder.Attachable()); return 2; } public int UpdateFrom2() { ContentDefinitionManager.AlterTypeDefinition("Customer", cfg => cfg .WithPart("CommonPart") .WithPart("RoutePart") .WithPart("BodyPart") .WithPart("CustomerPart") .WithPart("CommentsPart") .WithPart("TagsPart") .WithPart("LocalizationPart") .Creatable() .Indexed()); return 3; } } Can someone please tell me if I am missing something?

    Read the article

  • Issue reading in a cell from Excel with Apache POI

    - by Nick
    I am trying to use Apache POI to read in old (pre-2007 and XLS) Excel files. My program goes to the end of the rows and iterates back up until it finds something that's not either null or empty. Then it iterates back up a few times and grabs those cells. This program works just fine reading in XLSX and XLS files made in Office 2010. I get the following error message: Exception in thread "main" java.lang.NumberFormatException: empty String at sun.misc.FloatingDecimal.readJavaFormatString(Unknown Source) at java.lang.Double.parseDouble(Unknown Source) at the line: num = Double.parseDouble(str); from the code: str = cell.toString(); if (str != "" || str != null) { System.out.println("Cell is a string"); num = Double.parseDouble(str); } else { System.out.println("Cell is numeric."); num = cell.getNumericCellValue(); } where the cell is the last cell in the document that's not empty or null. When I try to print the first cell that's not empty or null, it prints nothing, so I think I'm not accessing it correctly.

    Read the article

  • android: tesseract force close

    - by Vishnu Mohan G
    I tried the tesseract tutorial here and get the following error: 06-03 01:18:52.626: E/AndroidRuntime(15103): FATAL EXCEPTION: main 06-03 01:18:52.626: E/AndroidRuntime(15103): java.lang.ExceptionInInitializerError 06-03 01:18:52.626: E/AndroidRuntime(15103): at o.c.r.LetsTryOCrActivity.onCreate(LetsTryOCrActivity.java:28) 06-03 01:18:52.626: E/AndroidRuntime(15103): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047) 06-03 01:18:52.626: E/AndroidRuntime(15103): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1722) 06-03 01:18:52.626: E/AndroidRuntime(15103): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1784) 06-03 01:18:52.626: E/AndroidRuntime(15103): at android.app.ActivityThread.access$1500(ActivityThread.java:123) 06-03 01:18:52.626: E/AndroidRuntime(15103): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:939) 06-03 01:18:52.626: E/AndroidRuntime(15103): at android.os.Handler.dispatchMessage(Handler.java:99) 06-03 01:18:52.626: E/AndroidRuntime(15103): at android.os.Looper.loop(Looper.java:130) 06-03 01:18:52.626: E/AndroidRuntime(15103): at android.app.ActivityThread.main(ActivityThread.java:3835) 06-03 01:18:52.626: E/AndroidRuntime(15103): at java.lang.reflect.Method.invokeNative(Native Method) 06-03 01:18:52.626: E/AndroidRuntime(15103): at java.lang.reflect.Method.invoke(Method.java:507) 06-03 01:18:52.626: E/AndroidRuntime(15103): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:847) 06-03 01:18:52.626: E/AndroidRuntime(15103): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:605) 06-03 01:18:52.626: E/AndroidRuntime(15103): at dalvik.system.NativeStart.main(Native Method) 06-03 01:18:52.626: E/AndroidRuntime(15103): Caused by: java.lang.UnsatisfiedLinkError: Couldn't load lept: findLibrary returned null 06-03 01:18:52.626: E/AndroidRuntime(15103): at java.lang.Runtime.loadLibrary(Runtime.java:429) 06-03 01:18:52.626: E/AndroidRuntime(15103): at java.lang.System.loadLibrary(System.java:554) 06-03 01:18:52.626: E/AndroidRuntime(15103): at com.googlecode.tesseract.android.TessBaseAPI.(TessBaseAPI.java:42) 06-03 01:18:52.626: E/AndroidRuntime(15103): ... 14 more Please help me solve this. thanks in Advance!.

    Read the article

  • Spring security oauth2 provider to secure non-spring api

    - by user1241320
    I'm trying to set up an oauth 2.0 provider that should "secure" our restful api using spring-security-oauth. Being a 'spring fan' i thought it could be the quicker solution. main point is this restful thingie is not a spring based webapp. boss says the oauth provider should be a separate application, but i'm starting to doubt that. (got this impression by reading spring-security-oauth) i'm also new here so haven't really got my hands into this other (jersey-powered) restul api (core of our business). any help/hint will be much appreciated.

    Read the article

  • Row selection based on subtable data in MySQL

    - by Felthragar
    I've been struggling with this selection for a while now, I've been searching around StackOverflow and tried a bunch of stuff but nothing that helps me with my particular issue. Maybe I'm just missing something obvious. I have two tables: Measurements, MeasurementFlags "Measurements" contain measurements from a device, and each measurement can have properties/attributes attached to them (commonly known as "flags") to signify that the measurement in question is special in some way or another (for instance, one flag may signify a test or calibration measurement). Note: One record per flag! Right, so a record from the "Measurements" table can theoreticly have an unlimited amount of MeasurementFlags attached to it, or it can have none. Now, I need to select records from "Measurements", that have an attached "MeasurementFlag" valued "X", but it must also NOT have a flag valued "Y" attached to it. We're talking about a fairly large database with hundreds of millions of rows, which is why I'm trying to keep all of this logic within one query. Splitting it up would create too many queries, however if it's not possible to do in one query I guess I don't have a choise. Thanks in advance.

    Read the article

  • Alternative to pjax/djax and ajaxy

    - by elluca
    I was evaluating jQuery plugins to make a Drupal 7 site using AJAX everywhere. I have been using ajaxy. But it does not seem to be very actively maintained. Two possible solutions I have found are pjax and djax. What are your experiences with those plugins? What other plugins do you know that do similar functionality? Very important features are SEO friendliness (preferably using pushState so no hash is being used. Hashes are used as a fallback for not supported browsers.). And also has to be very flexible since it has to wirk with Drupal's HTML structure.

    Read the article

  • ASP.NET MVC Validation Complete

    - by Ricardo Peres
    OK, so let’s talk about validation. Most people are probably familiar with the out of the box validation attributes that MVC knows about, from the System.ComponentModel.DataAnnotations namespace, such as EnumDataTypeAttribute, RequiredAttribute, StringLengthAttribute, RangeAttribute, RegularExpressionAttribute and CompareAttribute from the System.Web.Mvc namespace. All of these validators inherit from ValidationAttribute and perform server as well as client-side validation. In order to use them, you must include the JavaScript files MicrosoftMvcValidation.js, jquery.validate.js or jquery.validate.unobtrusive.js, depending on whether you want to use Microsoft’s own library or jQuery. No significant difference exists, but jQuery is more extensible. You can also create your own attribute by inheriting from ValidationAttribute, but, if you want to have client-side behavior, you must also implement IClientValidatable (all of the out of the box validation attributes implement it) and supply your own JavaScript validation function that mimics its server-side counterpart. Of course, you must reference the JavaScript file where the declaration function is. Let’s see an example, validating even numbers. First, the validation attribute: 1: [Serializable] 2: [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)] 3: public class IsEvenAttribute : ValidationAttribute, IClientValidatable 4: { 5: protected override ValidationResult IsValid(Object value, ValidationContext validationContext) 6: { 7: Int32 v = Convert.ToInt32(value); 8:  9: if (v % 2 == 0) 10: { 11: return (ValidationResult.Success); 12: } 13: else 14: { 15: return (new ValidationResult("Value is not even")); 16: } 17: } 18:  19: #region IClientValidatable Members 20:  21: public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context) 22: { 23: yield return (new ModelClientValidationRule() { ValidationType = "iseven", ErrorMessage = "Value is not even" }); 24: } 25:  26: #endregion 27: } The iseven validation function is declared like this in JavaScript, using jQuery validation: 1: jQuery.validator.addMethod('iseven', function (value, element, params) 2: { 3: return (true); 4: return ((parseInt(value) % 2) == 0); 5: }); 6:  7: jQuery.validator.unobtrusive.adapters.add('iseven', [], function (options) 8: { 9: options.rules['iseven'] = options.params; 10: options.messages['iseven'] = options.message; 11: }); Do keep in mind that this is a simple example, for example, we are not using parameters, which may be required for some more advanced scenarios. As a side note, if you implement a custom validator that also requires a JavaScript function, you’ll probably want them together. One way to achieve this is by including the JavaScript file as an embedded resource on the same assembly where the custom attribute is declared. You do this by having its Build Action set as Embedded Resource inside Visual Studio: Then you have to declare an attribute at assembly level, perhaps in the AssemblyInfo.cs file: 1: [assembly: WebResource("SomeNamespace.IsEven.js", "text/javascript")] In your views, if you want to include a JavaScript file from an embedded resource you can use this code: 1: public static class UrlExtensions 2: { 3: private static readonly MethodInfo getResourceUrlMethod = typeof(AssemblyResourceLoader).GetMethod("GetWebResourceUrlInternal", BindingFlags.NonPublic | BindingFlags.Static); 4:  5: public static IHtmlString Resource<TType>(this UrlHelper url, String resourceName) 6: { 7: return (Resource(url, typeof(TType).Assembly.FullName, resourceName)); 8: } 9:  10: public static IHtmlString Resource(this UrlHelper url, String assemblyName, String resourceName) 11: { 12: String resourceUrl = getResourceUrlMethod.Invoke(null, new Object[] { Assembly.Load(assemblyName), resourceName, false, false, null }).ToString(); 13: return (new HtmlString(resourceUrl)); 14: } 15: } And on the view: 1: <script src="<%: this.Url.Resource("SomeAssembly", "SomeNamespace.IsEven.js") %>" type="text/javascript"></script> Then there’s the CustomValidationAttribute. It allows externalizing your validation logic to another class, so you have to tell which type and method to use. The method can be static as well as instance, if it is instance, the class cannot be abstract and must have a public parameterless constructor. It can be applied to a property as well as a class. It does not, however, support client-side validation. Let’s see an example declaration: 1: [CustomValidation(typeof(ProductValidator), "OnValidateName")] 2: public String Name 3: { 4: get; 5: set; 6: } The validation method needs this signature: 1: public static ValidationResult OnValidateName(String name) 2: { 3: if ((String.IsNullOrWhiteSpace(name) == false) && (name.Length <= 50)) 4: { 5: return (ValidationResult.Success); 6: } 7: else 8: { 9: return (new ValidationResult(String.Format("The name has an invalid value: {0}", name), new String[] { "Name" })); 10: } 11: } Note that it can be either static or instance and it must return a ValidationResult-derived class. ValidationResult.Success is null, so any non-null value is considered a validation error. The single method argument must match the property type to which the attribute is attached to or the class, in case it is applied to a class: 1: [CustomValidation(typeof(ProductValidator), "OnValidateProduct")] 2: public class Product 3: { 4: } The signature must thus be: 1: public static ValidationResult OnValidateProduct(Product product) 2: { 3: } Continuing with attribute-based validation, another possibility is RemoteAttribute. This allows specifying a controller and an action method just for performing the validation of a property or set of properties. This works in a client-side AJAX way and it can be very useful. Let’s see an example, starting with the attribute declaration and proceeding to the action method implementation: 1: [Remote("Validate", "Validation")] 2: public String Username 3: { 4: get; 5: set; 6: } The controller action method must contain an argument that can be bound to the property: 1: public ActionResult Validate(String username) 2: { 3: return (this.Json(true, JsonRequestBehavior.AllowGet)); 4: } If in your result JSON object you include a string instead of the true value, it will consider it as an error, and the validation will fail. This string will be displayed as the error message, if you have included it in your view. You can also use the remote validation approach for validating your entire entity, by including all of its properties as included fields in the attribute and having an action method that receives an entity instead of a single property: 1: [Remote("Validate", "Validation", AdditionalFields = "Price")] 2: public String Name 3: { 4: get; 5: set; 6: } 7:  8: public Decimal Price 9: { 10: get; 11: set; 12: } The action method will then be: 1: public ActionResult Validate(Product product) 2: { 3: return (this.Json("Product is not valid", JsonRequestBehavior.AllowGet)); 4: } Only the property to which the attribute is applied and the additional properties referenced by the AdditionalFields will be populated in the entity instance received by the validation method. The same rule previously stated applies, if you return anything other than true, it will be used as the validation error message for the entity. The remote validation is triggered automatically, but you can also call it explicitly. In the next example, I am causing the full entity validation, see the call to serialize(): 1: function validate() 2: { 3: var form = $('form'); 4: var data = form.serialize(); 5: var url = '<%: this.Url.Action("Validation", "Validate") %>'; 6:  7: var result = $.ajax 8: ( 9: { 10: type: 'POST', 11: url: url, 12: data: data, 13: async: false 14: } 15: ).responseText; 16:  17: if (result) 18: { 19: //error 20: } 21: } Finally, by implementing IValidatableObject, you can implement your validation logic on the object itself, that is, you make it self-validatable. This will only work server-side, that is, the ModelState.IsValid property will be set to false on the controller’s action method if the validation in unsuccessful. Let’s see how to implement it: 1: public class Product : IValidatableObject 2: { 3: public String Name 4: { 5: get; 6: set; 7: } 8:  9: public Decimal Price 10: { 11: get; 12: set; 13: } 14:  15: #region IValidatableObject Members 16: 17: public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) 18: { 19: if ((String.IsNullOrWhiteSpace(this.Name) == true) || (this.Name.Length > 50)) 20: { 21: yield return (new ValidationResult(String.Format("The name has an invalid value: {0}", this.Name), new String[] { "Name" })); 22: } 23: 24: if ((this.Price <= 0) || (this.Price > 100)) 25: { 26: yield return (new ValidationResult(String.Format("The price has an invalid value: {0}", this.Price), new String[] { "Price" })); 27: } 28: } 29: 30: #endregion 31: } The errors returned will be matched against the model properties through the MemberNames property of the ValidationResult class and will be displayed in their proper labels, if present on the view. On the controller action method you can check for model validity by looking at ModelState.IsValid and you can get actual error messages and related properties by examining all of the entries in the ModelState dictionary: 1: Dictionary<String, String> errors = new Dictionary<String, String>(); 2:  3: foreach (KeyValuePair<String, ModelState> keyValue in this.ModelState) 4: { 5: String key = keyValue.Key; 6: ModelState modelState = keyValue.Value; 7:  8: foreach (ModelError error in modelState.Errors) 9: { 10: errors[key] = error.ErrorMessage; 11: } 12: } And these are the ways to perform date validation in ASP.NET MVC. Don’t forget to use them!

    Read the article

  • Why is my server performance degrading to the point of stopping, periodically?

    - by Pascal Aschwanden
    So, once in a while, I see in firebug that a request takes over 15 or even 60 seconds to respond and sometimes never. Here is what I've ruled out: It's not the CPU, cuz every time I check the Server load its less then 6 for all 3 numbers It's not the memory, because thats fairly low too, less the 50% It's not the I/O anymore, because I've seen the graphs that Joyent sent back to me when I requested them, and they show less then 3MB of I/O (mostly all read). It's not the SQL performance - I've profiled every last SQL command that runs, and they're all (99.9% of them anyway) running in less then 30ms, most run in less then 5ms. Oh and I've been profiling all the script execution times, and even the when the problem occurs, the script always manages to finish in 50ms or less (that's 1 / 20th of a second ). Now, I do run alot of ajax calls. 1 every 2 seconds per user and I have 300 DAU+. But, even if all 300 are playing simultaneously, thats still only 150 calls per second max. The only other thing I can think of is that one of my neighbors is funky. The problem is highly intermittent. 99% of the time it works perfectly and there's excellent performance. but 99%+ is not good enough. Eventually the performance gets so bad I have to restart the server, at which point everything is fine again. I've done this about 4 times now. Any ideas? Note: this is on joyent, vps, intro package 256mb of ram with bursting. here are the mysql dump info: Traffic ø per hour Received 18 MiB 29 MiB Sent 134 MiB 221 MiB Total 151 MiB 251 MiB Connections ø per hour % max. concurrent connections 5 --- --- Failed attempts 0 0.00 0.00% Aborted 0 0.00 0.00% Total 9,418 15.59 k 100.00%

    Read the article

  • My dedicated server keeps getting very slow that it fails to load the application

    - by server
    I have an application running on Windows Server 2008, running IIS 7.5, SQL Server 2008, 4GB RAM from brinkster. The problem is, every couple of days I get the same 10,000 calls that the system is very slow, and its not operating properly, then after 30 minutes of that it just fails to load. I try to access the server from the remote desktop connection but I can't access it. The only way it I can get it working again is to call the support at brinkster and have them do a manual reboot of the server. After that it works well for some time, and the it re-crashes after some time. Support over there, are not helping a lot.

    Read the article

  • Can't Allow Specific Port in Windows Firewall Advanced Security - Windows 2008

    - by Jody
    In the Outbound Rules, I set up a rule to allow outbound connection from port 26. But, it doesn't work. However, if I allow "all port" for this rule, this will work, but then all ports will be allowed too. What is the reason? Is there any conflicting rule? I need to fix this as soon as possible. -Edit to add : I'm trying to allow email access to mail server outside (port 26). The thing is, even if I telnet using port 26, it will not work, unless I allow "all ports". Specific port will not do.

    Read the article

  • mysql 5.0.23 vs 5.5 performance benefits and upgrade issues?

    - by WarDoGG
    I have been told that mysql 5.5 has a significant performance boost compared to 5.0 Our server handles a lot of data (around 30 million records processed per 5-10 seconds) and requires every drop of performance boost we can give. Will it be beneficial if we upgrade from 5.0.23 to mysql 5.5? Also, we have lots of database indexes setup on the tables and I've been told that sometimes the indexes become corrupt after a version upgrade and they have to be rebuilt. Is this true?

    Read the article

  • gzip compression good or bad?

    - by WarDoGG
    I have a server that currently does a lot of processing in my application and the target users are those who have a very good internet connection. The output that is sent from the server is always text/html and we do not use any media (audio/video) only images (static site images like logo,etc). We are experiencing severe performance issues and I wonder if turning off gzip/mod_deflate on the server so that the server would avoid compressing the output. Will this cause an improvement in performance?

    Read the article

  • Backup Exec job completed with exceptions: RWS_AttachToDLE

    - by HannesFostie
    2 of this weekend's jobs completed with exceptions, and mention "RWS_AttachToDLE". I get the feeling the job did in fact complete without missing data, but I would like to be 100% sure (and can't verify the backup myself right now - colleague is out of the office and the backup in question is a bit of a black box for me, it works but I am not familiar with its inner workings). Also, how can I prevent this from happening? Google didn't prove to be very helpful, and experts exchange seem to have changed their system so that you can't simply scroll down to see the answers to a particular question ;-)

    Read the article

  • Troubleshooting mailserver (Postfix, Dovecot) on Ubuntu Server 9.10?

    - by Christoffer
    I have configured a mail server with Postfix and Dovecot on Ubuntu Server 9.10. I followed the guidelines here (using Maildir): https://help.ubuntu.com/community/Postfix https://help.ubuntu.com/community/Dovecot The tests seemed alright so I connected it to GMail which is able to connect and fetch e-mails. But since there's no e-mail in the Maildir/ directory I can't decide if the problem is Postfix or Dovecot. And I am totally new to mailservers so I don't know where to start troubleshooting. So, I want to start by testing Dovecot. How can I create a fake "Hello World"-email directly on the server (using a text editor) so that I can try to fetch it with GMail? If Dovecot is alright, where do I start looking for errors in Postfix? Thank you for your time. Christoffer

    Read the article

  • What does 'Can't sync file './database_name/…frm' to disk (Errcode: 28)' mean?

    - by cool_cs
    I am getting this error message whenever I try to create a new index or a new table in my mysql server. Does anyone know what the reason is? This is the ouput after I run df -a Filesystem Size Used Avail Use% Mounted on /dev/sda2 13G 7.3G 4.5G 63% / /dev/sda1 251M 27M 212M 12% /boot tmpfs 3.9G 0 3.9G 0% /dev/shm 10.156.248.29:/vol/pharos_pnxd_data_01/env_empty_sbid_27133_qdcprod 30G 30G 32K 100% /app

    Read the article

  • Can't get any SMART or temperature data from HDDs

    - by Regs
    I have a PC with recently installed Gigabyte GA-X79-UD5 MB. I've encountered some weird problem with getting SMART data or temperature for HDDs. Every single tool I've tried in Windows 7 just can't get any data (HDTune, AIDA64...). I was suspecting that SMART feature is disabled in BIOS but it's seems like there is no such option in BIOS settings. I've even tried to update BIOS but still no luck. Same issue with both controllers on that MB (Intel and Marvell). It seems unlikely that both controllers end up with exact same issue. Both controllers are working in AHCI mode. Is there anythig that can interfere with getting SMART ant temp data from HDDs? Or is there any way to check that it's actuall MB issue? Is it even possible that it is hardware issue since all HDDs seems to work normal despite the fact that I can't get any temperature or SMART data from it.

    Read the article

  • postfix relay access denied from some IPs

    - by Caballero
    This is driving me nuts. I have Postfix/Dovecot set up on Centos 6 VPS for my emails. I can send and receive emails without any problems on my outlook (home broadband), on my Android phone (3G connection), however when I set up exactly the same email account on Outlook at my friends house I'm getting bouncebacks when I'm trying to send email (receiving works fine): 554 5.7.1 : Relay access denied Now if it wasn't working at all I'd understand, but why is it working on several internet connections, but not everywhere? Can someone shed some light on this? Where should I look for the problem?

    Read the article

< Previous Page | 3 4 5 6 7 8 9 10 11 12 13 14  | Next Page >