tag:blogger.com,1999:blog-141932362818335952024-02-07T06:21:17.392-08:00Code SamplesHouse 9http://www.blogger.com/profile/08045832658861127427noreply@blogger.comBlogger20125tag:blogger.com,1999:blog-14193236281833595.post-46895178098958997052010-03-23T08:32:00.000-07:002010-03-23T08:45:24.452-07:00sorting rails view with will_paginate pluginThis solution for sorting data on rails index actions does NOT use ajax. Sometimes sorting with ajax is nice but often it is not actually as user friendly; breaking the browser back button, etc...<div><br /></div><div>Disclaimer 1: this code is probably using all kinds of ruby anti-patterns :) - but it is a very simple implementation and so I just went with it...</div><div><br /></div><div>Disclaimer 2: the title of the post might be a little miss leading as you can use this with or without the <a href="http://wiki.github.com/mislav/will_paginate/">will_paginate</a> plugin. In my case I am using it with the <a href="http://wiki.github.com/mislav/will_paginate/">will_paginate</a> plugin - and I highly recommend it!</div><div><br /></div><div>put this file in your rails lib directory /lib/sort_index.rb</div><div><script src="http://gist.github.com/341278.js?file=sort_index.rb"></script></div><div><br /></div><div>in your controller code, set up the SortIndex::Config (you can have more than one if you have multiple actions that need to support sorting</div><div><script src="http://gist.github.com/341290.js?file=sort_index_controller_usage.rb"></script></div><div><br /></div><div>then in your view code render your table headers using the sort object</div><div><script src="http://gist.github.com/341295.js?file=sort_index_view_usage.html.erb"></script></div><div><br /></div><div>Does not support the following:</div><div><ul><li>additional attributes on the anchor tags</li><li>additional attributes on the table header tags</li><li>additional query string parameters - might add this later, would be nice for search results</li></ul></div>House 9http://www.blogger.com/profile/08045832658861127427noreply@blogger.com0tag:blogger.com,1999:blog-14193236281833595.post-87863946312138657672010-01-06T10:03:00.000-08:002010-01-06T10:10:08.689-08:00Ruby Http Get with Net::HTTP<script src="http://gist.github.com/270459.js"></script><br />Resources<br /><ul><li><a href="http://ruby-doc.org/stdlib/libdoc/net/http/rdoc/classes/Net/HTTP.html">Net::HTTP ruby docs</a></li><li><a href="http://stackoverflow.com/questions/1252210/parametrized-get-request-in-ruby">Stackoverflow post</a></li></ul><br /><br /><div style="display:none"><br />require 'net/http'<br />require 'uri'<br /> <br />def get_html_content(requested_url)<br /> url = URI.parse(requested_url)<br /> full_path = (url.query.blank?) ? url.path : "#{url.path}?#{url.query}"<br /> the_request = Net::HTTP::Get.new(full_path)<br /> <br /> the_response = Net::HTTP.start(url.host, url.port) { |http|<br /> http.request(the_request)<br /> }<br /> <br /> raise "Response was not 200, response was #{the_response.code}" if the_response.code != "200"<br /> return the_response.body <br />end <br /> <br /># this will fail with ArgumentError: HTTP request path is empty<br />s = get_html_content("http://www.google.com")<br /># these should be fine<br />s = get_html_content("http://www.google.com/") <br />s = get_html_content("http://github.com/search?q=http")<br /># above code does not handle redirects but raises exception for non-200 <br />s = get_html_content("http://www.yahoo.com/") # http 302<br /></div>House 9http://www.blogger.com/profile/08045832658861127427noreply@blogger.com2tag:blogger.com,1999:blog-14193236281833595.post-36250959066814730582010-01-06T09:56:00.000-08:002010-01-06T10:02:09.714-08:00Ruby Regex to remove script tags<script src="http://gist.github.com/270463.js"></script><br />Resources<br /><ul><li><a href="http://rubular.com/">Rubular</a></li><li><a href="http://jamesmckay.net/2008/05/how-to-match-any-character-including-newlines-in-a-javascript-regular-expression/">Match any character in RegEx</a></li><li><a href="http://ruby-doc.org/core/classes/String.html#M000817">Ruby String gsub</a></li></ul>House 9http://www.blogger.com/profile/08045832658861127427noreply@blogger.com0tag:blogger.com,1999:blog-14193236281833595.post-8200729326240601792009-09-25T07:58:00.000-07:002009-10-07T07:30:43.632-07:00Attribute "target" exists, but can not be used for this element.These days I am all about valid xhtml and was surprised to receive this validation error when using the target attribute on an anchor tag.<div style="font-style: italic;"><blockquote style="background-color: yellow;">Attribute "target" exists, but can not be used for this element.</blockquote></div><br /><script src="http://gist.github.com/193604.js"></script><br /><div>I found a nice work around that does not involve window.open, using jquery we can hack the attribute on 'after' the dom has loaded.</div><br /><script src="http://gist.github.com/193608.js"></script><br /><div><br /><div>Now instead of target='_blank' you can just use class='target-blank', if the browser does not support javascript it will not open in a new window but the link will still work - and we have our valid xhtml.</div><br />Resources<br /><ul><li><a href="http://www.cre8asiteforums.com/forums/index.php?showtopic=58559">cre8asiteforums</a></li><li><a href="http://validator.w3.org/#validate_by_input+with_options">W3C Markup Validation Service</a></li><li><a href="http://jquery.com/">JQuery</a></li></ul></div>House 9http://www.blogger.com/profile/08045832658861127427noreply@blogger.com2tag:blogger.com,1999:blog-14193236281833595.post-90822525365942417352009-08-21T13:09:00.000-07:002009-08-21T14:06:22.504-07:00Ajax error handling with ruby on rails and jquery<p>This sample is just a slight modification of this post '<a href="http://www.railsfire.com/article/handling-ajax-errors-and-displaying-friendly-error-messages-users">Handling AJAX errors and displaying friendly error messages to users</a>'. Basically I wanted to maintain the existing rails error handling for non-ajax pages and then have good handling for errors in both development and production mode; i.e. get errors in the browser when in development mode and show a nice message when in production mode.</p><p>Modify /app/controllers/application.rb; add the rescue_from macro and the handler_exception method</p><br /><script src="http://gist.github.com/172342.js"></script><p>Then add a global javascript method for presenting the errors; most likely in application.js</p><script src="http://gist.github.com/172345.js"></script><p>Then a sample usage, jquery making an ajax post to a rails controller action</p><script src="http://gist.github.com/172347.js"></script><p>in development mode the error message is returned in an easier to read view in the firebug console and an alert message is presented that has a truncated version of the error</p><div><img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgRbZ5nRxqqJeEwvT7oXHCkqOO_W-4tmy9Iwbs7SX4h4N13xVcv6rcA9yeIX1VRVoOGm-IJsYJOdfZeDUzxB1-8h0Q2HzyXb7LDJl5b_jSxU006fzogL9-8Lq_BArcnCuBqTdye2BNIQ6g/s800/ajax_error_development.png" alt="dev mode" /></div><p>in production mode just a friendly error message.</p><div><img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhdntgk8oLSRbE441BzZ6ePCfxAq12CEJKn6fRkX8OUdBEJfW6pJU1TBesoXIbICr5BZE0WytbkWzmN_s27WQUdaVHkvXvsIGUnVhIcNRlktVxoX8ge6Dc0sNTy33JU-iUaTMAc1_jvnkU/s800/screen-shot-002.png" alt="production mode" /></div><p>Resources</p><ul><li><a href="http://www.railsfire.com/article/handling-ajax-errors-and-displaying-friendly-error-messages-users">Handling AJAX errors and displaying friendly error messages to users</a></li><li>Rails source code <a href="http://api.rubyonrails.org/classes/ActionController/Rescue.html">rescue.rb</a></li><li>Rails views source on your install lib/action_controller/templates/rescues</li><li><a href="http://docs.jquery.com/Ajax/jQuery.ajax">jquery ajax</a></li></ul>House 9http://www.blogger.com/profile/08045832658861127427noreply@blogger.com0tag:blogger.com,1999:blog-14193236281833595.post-85810828066054334332009-08-04T13:54:00.000-07:002009-08-04T14:00:30.373-07:00Get list of MSSQL jobs that are currently runningThe following sql statement will return information about the currently executing MSSQL jobs.<div>Run it against the msdb database</div><div><br /></div><div> <div><span class="Apple-style-span" style="font-family:Arial;font-size:100%;"><span class="Apple-style-span" style=" white-space: pre;font-size:13px;"><br /></span></span></div></div><br /><script src="http://gist.github.com/161536.js"></script><br /><div><br />Resources<br /><ul><li><a href="http://msdn.microsoft.com/en-us/library/ms186722.aspx">MSDN: sp_help_job</a></li><li><a href="http://www.sqlteam.com/article/controlling-jobs-in-transact-sql">Controlling Jobs in Transact-SQL</a></li></ul></div>House 9http://www.blogger.com/profile/08045832658861127427noreply@blogger.com0tag:blogger.com,1999:blog-14193236281833595.post-18094408870575196472009-04-23T21:31:00.000-07:002009-04-23T22:05:33.171-07:00PGError: ERROR: invalid byte sequence for encoding "UTF8": 0xa7 (ActiveRecord::StatementInvalid)Working on a rails application and have decided to make the switch from MySql to <a href="http://www.postgresql.org/">Postgresql</a>; ran into a few minor issues along the way and one really annoying and unexpected issue<br /><br /><blockquote><span style="font-style:italic; background-color:yellow;">PGError: ERROR: invalid byte sequence for encoding "UTF8": 0xa7 (ActiveRecord::StatementInvalid)<br />HINT: This error can also happen if the byte sequence does not match the encoding expected by the server, which is controlled by "client_encoding".</span><br /></blockquote><br />The above error was being generated when I was trying to save model objects that had their string and text attributes assigned from data that had been scrapped using http with <a href="http://scrubyt.org/">scRUBYt</a>. After searching on Google the only 'work-around' I found was to use base64 encode and decode when reading and writing to these model attributes / database columns<br /><br />Given the following migration<br /><script src="http://gist.github.com/100947.js"></script><br />Our model before and then after applying the work-around<br /><script src="http://gist.github.com/100943.js"></script><br /><br />Resources<div><ul><li><a href="http://groups.google.com/group/rubyonrails-talk/browse_thread/thread/aa02ee4750670d06/f2d5c89dafae30a1?lnk=gst&q=postgresql+base64">String encoding / Importing Feeds</a></li><li><a href="http://www.ruby-forum.com/topic/146059">override AR default attribute accessors</a><br /></li></ul><br /></div>House 9http://www.blogger.com/profile/08045832658861127427noreply@blogger.com1tag:blogger.com,1999:blog-14193236281833595.post-46201609854377463222009-04-09T11:51:00.000-07:002009-04-09T12:46:46.057-07:00UPDATE: NAnt build with TFS changeset as revision numberthis is a small revision to a previous post <a href="http://house9-code-samples.blogspot.com/2008/04/nant-build-with-tfs-changeset-as.html">NAnt build with TFS changeset as revision number</a><br /><br />apparently there is a limitation on the size of the number used in each segment of a .net assembly version so this is a slight update to the c# code that gets the latest changeset from TFS - changes start at "if(latestChangsetId > 65534)"<br /><br /><textarea class="csharp" name="code" rows="10" cols="80"><br />public static void ScriptMain(Project project) <br />{<br /> project.Log(Level.Info, "Connect to " + project.Properties["tfs.server"]);<br /> TeamFoundationServer tfs = new TeamFoundationServer(project.Properties["tfs.server"]);<br /><br /> // Get a reference to Version Control. <br /> Type type = typeof(VersionControlServer);<br /> VersionControlServer versionControl = (VersionControlServer)tfs.GetService(type);<br /><br /> project.Log(Level.Info, "get changesetId for " + project.Properties["tfs.fullpath"]);<br /> IEnumerable changeSets = versionControl.QueryHistory(project.Properties["tfs.fullpath"], VersionSpec.Latest, 0, RecursionType.Full, null, null, null, 1, true, false);<br /> int latestChangesetId = 0;<br /><br /> // there is only one<br /> foreach(Changeset c in changeSets)<br /> {<br /> latestChangesetId = c.ChangesetId;<br /> } <br /> <br /> string revision = String.Empty;<br /> if(latestChangsetId > 65534)<br /> {<br /> // use the last 4 numbers only<br /> revision = latestChangesetId.ToString().Substring(latestChangesetId.ToString().Length - 4, 4);<br /> }<br /> else<br /> {<br /> revision = latestChangesetId.ToString();<br /> }<br /><br /> project.Log(Level.Info, "ChangesetId is " + latestChangesetId.ToString());<br /> project.Log(Level.Info, "Revision will be " + revision);<br /> <br /> project.Properties["project.version.revision"] = revision;<br />}<br /></textarea><br /><br />see also <a href="http://michaelsync.net/2007/01/12/assemblyversion-buildno-limitation">AssemblyVersion - BuildNo Limitation </a>House 9http://www.blogger.com/profile/08045832658861127427noreply@blogger.com0tag:blogger.com,1999:blog-14193236281833595.post-30645369103744030472009-03-26T09:15:00.001-07:002009-03-26T09:24:44.837-07:00Get Filenames and Database names from MSSQLI was doing some clean up on one of our database servers; we have many databases created with backup/restore for testing purposes I was checking for the largest ldf files and making sure those databases were in simple mode and then shirking the data files, there were a few files I could not match to the databases because the mdf and ldf file names were different from the actual database file name - found the following queries using a few google searches<div><br /></div><br /><div><br /><script src="http://gist.github.com/86181.js"></script><br /></div><br /><div><br /><script src="http://gist.github.com/86182.js"></script><br /></div>House 9http://www.blogger.com/profile/08045832658861127427noreply@blogger.com0tag:blogger.com,1999:blog-14193236281833595.post-51075918911615124612009-02-16T14:57:00.000-08:002009-02-16T15:06:58.415-08:00use jquery to disable a button when clicked<a href="http://jquery.com/">jquery</a> is such a great javascript library, the more I use it the more I like it<div><br /></div><div><script src="http://gist.github.com/65438.js"></script></div><br /><div><br />NOTE: the above code snippets are untested - cut, pasted and modified from real code that was tested (and worked!)<br /></div><br /><div> <br /></div>House 9http://www.blogger.com/profile/08045832658861127427noreply@blogger.com0tag:blogger.com,1999:blog-14193236281833595.post-77660448183185956542008-11-01T08:33:00.000-07:002008-11-01T08:52:27.697-07:00Calling rake tasks from another rake taskThis turns out to be pretty straight forward, but was not obvious<br /><br /><textarea class="ruby" name="code" rows="10" cols="60"><br /> Rake::Task['task_name'].execute<br /></textarea><br /><br />A rake task to rebuild the development database<br /><textarea class="ruby" name="code" rows="10" cols="60"><br />desc 'drop, create and rebuild development db'<br />task(:rebuild_development_db) do<br /> puts "drop the db"<br /> Rake::Task['db:drop'].execute <br /> puts "create the db"<br /> Rake::Task['db:create'].execute<br /> puts "run the migrations"<br /> Rake::Task['db:migrate'].execute<br /> # do other stuff...<br />end<br /></textarea><br /><br />Resources<br /><ul><li><a href="http://www.railsenvy.com/2007/6/11/ruby-on-rails-rake-tutorial">http://www.railsenvy.com/2007/6/11/ruby-on-rails-rake-tutorial</a></li><li><a href="http://pastie.org/153991">Pastie code sample Rake calling Rake</a><br /></li></ul>House 9http://www.blogger.com/profile/08045832658861127427noreply@blogger.com2tag:blogger.com,1999:blog-14193236281833595.post-30084019564564410502008-05-18T07:54:00.001-07:002008-05-18T08:02:30.372-07:00MSSQL drop and re-add constraintsOne of the guys at work hooked me up with this code - quite useful if you want to do a bunch of data inserts but don't want to worry about the order you apply the inserts because of foreign key constraints<br /><br /><span style="font-weight:bold;">Before performing data actions:</span><br /><textarea class="sql" name="code" rows="10" cols="60"><br />-- generate these and run<br />SELECT<br />'ALTER TABLE ' + so.NAME + ' NOCHECK CONSTRAINT ALL'<br />FROM sysobjects so<br />WHERE xtype = 'u'<br /></textarea><br /><br /><span style="font-weight:bold;">After performing data actions:</span><br /><textarea class="sql" name="code" rows="10" cols="60"><br />-- generate these and run<br />SELECT<br />'ALTER TABLE ' + so.NAME + ' CHECK CONSTRAINT ALL'<br />FROM sysobjects so<br />WHERE xtype = 'u'<br /></textarea><br /><br />Thanks to ET for this code bit!House 9http://www.blogger.com/profile/08045832658861127427noreply@blogger.com0tag:blogger.com,1999:blog-14193236281833595.post-28548495429784073392008-05-10T13:25:00.000-07:002008-05-10T13:29:38.977-07:00Rolling Over Rails production.log fileJust came across this on a rails forum (post by Freezzo), rails production.log files can grow very large - but no chron job required - this is very handy.<br /><br /><br /><textarea class="ruby" name="code" rows="10" cols="60"><br />config.logger = Logger.new("#{RAILS_ROOT}/log/#{ENV['RAILS_ENV']}.log", 'daily')<br /></textarea><br /><br />where 'daily' can be 'daily' to 'weekly', 'monthly', '5mb', etc...House 9http://www.blogger.com/profile/08045832658861127427noreply@blogger.com0tag:blogger.com,1999:blog-14193236281833595.post-28158082174194731782008-04-20T15:08:00.001-07:002008-04-20T16:03:18.917-07:00NAnt build with TFS changeset as revision numberThis code sample is a <a href="http://nant.sourceforge.net/">nant</a> script that <br /><ul><br /><li>deletes the CommonAssembly.cs file (linked to all projects)</li><br /><li>uses the nant <a href="http://nant.sourceforge.net/release/latest/help/tasks/asminfo.html">asminfo</a> task to recreate the CommonAssembly.cs file, but after we query TFS for the changeset (revision) number which is used in the version number</li><br /><li>build the solution in release mode using the ide.exe (there are other - better ways, but this one works)</li><br /><li>xcopy files to C:\temp\{app} and clean up all the source files</li><br /></ul><br />basically I just put together a few bits that I found on other blogs (should have saved the urls - doh!), most were related to using svn for source control and then I added in the code block for the c# stuff to query TFS.<br /><br />A quick note about the linked CommonAssembly.cs file, visual studio has an option when you are adding an existing file to a project to select 'linked', click the arrow on the 'Add' button when you select your existing file<br /><br />what this script does not do - get latest from TFS, I usually do that part manually or from ccnet<br /><textarea class="xml" name="code" rows="10" cols="80"><br /><project name="YourApp" default="do-build" xmlns="http://nant.sf.net/release/0.85-rc4/nant.xsd"><br /> <!-- Version settings --><br /> <property name="project.config" value="release" /><br /> <property name="project.version.major" value="1" /><br /> <property name="project.version.minor" value="0" /><br /> <property name="project.version.build" value="0" /><br /> <property name="tfs.server" value="http://yourTFSserver:8080/" /><br /> <property name="tfs.fullpath" value="$/yourTeamProject/someDirectory/andSoOn/" /><br /> <property name="company" value="${project::get-name()}"/><br /> <property name="project" value="${project::get-name()}"/><br /> <property name="copyright" value="${company}, ${datetime::get-year(datetime::now())}"/><br /> <property name="temp-target-dir" value="C:\temp\yourApplication"/><br /><br /> <!-- the public target --><br /> <target name="do-build" depends="version, compile-release, copy-to-temp-dir"/><br /><br /> <target name="compile-release"><br /> <!-- delete the previous log files --><br /> <delete file="clean_log.txt" failonerror="false"></delete><br /> <delete file="compile_log.txt" failonerror="false"></delete><br /> <!-- clean --><br /> <echo message="Clean bins" /><br /> <exec program="c:\program files\microsoft visual studio 9.0\common7\ide\devenv.exe" workingdir="."><br /> <arg file="YourSolutionFileNameHere.sln" /><br /> <arg value="/out" /><br /> <arg value="clean_log.txt" /><br /> <arg value="/clean" /><br /> <arg value="${project.config}" /><br /> </exec><br /> <!-- build --><br /> <echo message="Build for ${project.config}" /><br /> <exec program="c:\program files\microsoft visual studio 9.0\common7\ide\devenv.exe" workingdir="."><br /> <arg file="YourSolutionFileNameHere.sln" /><br /> <arg value="/out" /><br /> <arg value="compile_log.txt" /><br /> <arg value="/rebuild" /><br /> <arg value="${project.config}" /><br /> </exec><br /> </target><br /> <br /> <target name="version"><br /> <property name="project.version.revision" value="0"/><br /> <!-- this block get the changesetid for this 'solution' and sets project.version.revision --><br /> <script language="C#"><br /> <references><br /> <include name="C:\someDirectoryWhereYouHaveThisDll\Microsoft.TeamFoundation.Client.dll" /><br /> <include name="C:\someDirectoryWhereYouHaveThisDll\TeamFoundation\Microsoft.TeamFoundation.VersionControl.Client.dll" /><br /> </references><br /> <imports><br /> <import namespace="Microsoft.TeamFoundation.Client" /><br /> <import namespace="Microsoft.TeamFoundation.VersionControl.Client" /><br /> </imports><br /> <code><br /> <![CDATA[<br /> public static void ScriptMain(Project project) <br /> {<br /> // see c# code sample in next section...<br /> }<br /> ]]><br /> </code><br /> </script><br /> <br /> <property name="project.version.full" value="${project.version.major}.${project.version.minor}.${project.version.build}.${project.version.revision}"/><br /><br /> <echo message="MARKING THIS BUILD AS VERSION ${project.version.full}" /><br /> <delete file="CommonAssemblyInfo.cs" failonerror="false"/><br /> <asminfo output="CommonAssemblyInfo.cs" language="CSharp"><br /> <imports><br /> <import namespace="System" /><br /> <import namespace="System.Reflection" /><br /> <import namespace="System.Runtime.InteropServices" /><br /> </imports><br /> <attributes><br /> <attribute type="ComVisibleAttribute" value="false" /><br /> <attribute type="AssemblyVersionAttribute" value="${project.version.full}" /><br /> <attribute type="AssemblyFileVersionAttribute" value="${project.version.full}" /><br /> <attribute type="AssemblyCopyrightAttribute" value="${copyright}" /><br /> <attribute type="AssemblyProductAttribute" value="${project}" /><br /> <attribute type="AssemblyCompanyAttribute" value="${company}" /><br /> <attribute type="AssemblyConfigurationAttribute" value="${project.config}" /><br /> <attribute type="AssemblyInformationalVersionAttribute" value="${project.version.full}" /><br /> </attributes><br /> <references><br /> <include name="System.dll" /><br /> </references><br /> </asminfo><br /> </target><br /><br /> <target name="copy-to-temp-dir"><br /> <mkdir dir="${temp-target-dir}" /><br /> <exec program="xcopy" verbose="true"><br /> <arg value=".\YourWebProjectDirectory" /><br /> <arg value="${temp-target-dir}" /><br /> <arg line="/e /r /y /q" /><br /> </exec><br /><br /> <delete><br /> <!-- probably a better way to do this? --><br /> <fileset basedir="${temp-target-dir}"><br /> <include name="*.cs" /><br /> <include name="*/*.cs" /><br /> <include name="*.csproj*" /><br /> <include name="*/*.otherfiletypes" /><br /> </fileset><br /> </delete><br /> <br /> <!-- fix up the web.config --><br /> <echo message="update the configuration ${temp-target-dir}\web.config" /><br /> <xmlpoke <br /> file="${temp-target-dir}\web.config"<br /> xpath="/ns:configuration/ns:system.web/ns:customErrors/@mode"<br /> value="On"<br /> ><br /> <namespaces><br /> <namespace prefix="ns" uri="http://schemas.microsoft.com/.NetConfiguration/v2.0" /><br /> </namespaces><br /> </xmlpoke> <br /> </target> <br /><br /></project><br /></textarea><br /><br />the c# bit that goes in the nant script block above<br /><textarea class="csharp" name="code" rows="10" cols="80"><br />public static void ScriptMain(Project project) <br />{<br /> project.Log(Level.Info, "Connect to " + project.Properties["tfs.server"]);<br /> TeamFoundationServer tfs = new TeamFoundationServer(project.Properties["tfs.server"]);<br /><br /> // Get a reference to Version Control. <br /> Type type = typeof(VersionControlServer);<br /> VersionControlServer versionControl = (VersionControlServer)tfs.GetService(type);<br /><br /> project.Log(Level.Info, "get changesetId for " + project.Properties["tfs.fullpath"]);<br /> IEnumerable changeSets = versionControl.QueryHistory(project.Properties["tfs.fullpath"], VersionSpec.Latest, 0, RecursionType.Full, null, null, null, 1, true, false);<br /> int latestChangesetId = 0;<br /><br /> // there is only one<br /> foreach(Changeset c in changeSets)<br /> {<br /> latestChangesetId = c.ChangesetId;<br /> } <br /><br /> project.Log(Level.Info, "ChangesetId is " + latestChangesetId.ToString());<br /> project.Properties["project.version.revision"] = latestChangesetId.ToString();<br />}<br /></textarea><br /><br />nant is awesome!House 9http://www.blogger.com/profile/08045832658861127427noreply@blogger.com1tag:blogger.com,1999:blog-14193236281833595.post-37215453241792557872008-02-16T09:05:00.000-08:002008-02-16T10:35:50.530-08:00Rhino.Mocks - the basicsStarted using Rhino.Mocks recently (Awesome!!!) - just wanted to list a few of the basics; the official Rhino Mocks Documentation is very good and available <a href="http://www.ayende.com/Wiki/(S(0asrslmlg1jh5355jtljowre))/Rhino+Mocks+Documentation.ashx">here</a>. These examples are a bit rough, they have not been compiled; there may be typos.<br /><br />using<pre class="c-sharp" name="code">using Rhino.Mocks;</pre><br /><br />The mock repository<br /><textarea class="c-sharp" name="code" rows="10" cols="60"><br />// use the mock repository to create the mocked objects<br />MockRepository mocks = new Rhino.Mocks.MockRepository();<br />// example<br />System.Object someObject = mocks.CreateMock<System.Object>();<br />// set up the behaviour you want from calls to your mocked object <br />Rhino.Mocks.Expect.Call(someObject.Equals(someParameter)).Return(false);<br />// then don't forget<br />mocks.ReplayAll();<br />// now do stuff that calls your mocked object Equals method<br />...<br /></textarea><br /><br />Mock a call to the db<br /><textarea class="c-sharp" name="code" rows="10" cols="60"><br />// create our mocked repository object - IProductRepository, the real one calls the db<br />IProductRepository repository = mocks.CreateMock<IProductRepository>();<br />// tell rhino.mocks when we call the method GetProduct with the argument 33 to return null<br />Rhino.Mocks.Expect.Call(repository.GetProduct(33)).Return(null);<br />// get the mocking ready<br />mocks.ReplayAll();<br />// pass our mock to our product service layer<br />ProductService service = new ProductService(repository);<br />// service.GetProduct makes a call to the mocked repository.GetProduct which will return null<br />IProduct product = service.GetProduct(33);<br />// should be null<br />Assert.IsNull(product);<br /></textarea><br /><br />Ignore any arguments<br /><textarea class="c-sharp" name="code" rows="10" cols="60"><br />// any call to GetProduct will return null no matter the value of the arg<br />Rhino.Mocks.Expect.Call(repository.GetProduct(null)).Return(null).IgnoreArguments();<br /></textarea><br /><br />mock a method that returns void<br /><textarea class="c-sharp" name="code" rows="10" cols="60"><br />IProduct product = new Product("003092", "Sierra Nevada", 6.49);<br />// this void call will handle our product 003092<br />Rhino.Mocks.Expect.Call(delegate { repository.Save(product); });<br />// this void call will handle any argument<br />Rhino.Mocks.Expect.Call(delegate { repository.Save(null); }).IgnoreArguments();<br /></textarea><br /><br />Handle multiple calls to the same method<br /><textarea class="c-sharp" name="code" rows="10" cols="60"><br />IProduct product = new Product("003092", "Sierra Nevada", 6.49);<br />// note the .Repeat.Any()<br />Rhino.Mocks.Expect.Call(repository.GetProduct("003092")).Return(product).Repeat.Any();<br />// send the mock to our product service object<br />ProductService service = new ProductService(repository);<br />// find by sku calls GetProduct on the mocked Product repository<br />IProduct beer = service.FindBySku("003092");<br />// find decent beer calls GetProduct on the mocked Product repository also<br />IProduct decentBeer = service.FindDecentBeer();<br /></textarea><br /><br />Partial Mock<br /><textarea class="c-sharp" name="code" rows="10" cols="60"><br />// create a partial mock with constructor args (our product repository again)<br />IProductService service = mocks.PartialMock<IProductService>(repository);<br />// our test case data<br />IUser loggedOnUser = new User("John", "Doe", CustomerType.Gold);<br />// mock product service calls to GetLoggedOnUser<br />Rhino.Mocks.Expect.Call(service.GetLoggedOnUser()).Return(loggedOnUser);<br />// get the mocking ready<br />mocks.ReplayAll();<br />// now GetDiscount is not a mocked method but it does call the mocked GetLoggedOnUser method<br />decimal discount = service.GetDiscount();<br />// assert the result<br />Assert.AreSame(44.4M, discount, "Gold customer discount not correct?");<br />// NOTE: this will not work (compile) unless the mocked method GetLoggedOnUser is public<br /></textarea>House 9http://www.blogger.com/profile/08045832658861127427noreply@blogger.com5tag:blogger.com,1999:blog-14193236281833595.post-32540764771426304942007-10-18T19:17:00.000-07:002007-10-18T19:43:16.698-07:00Rails RJS and newline charactersok this one really got me, I was generating a javascript alert from the server via an rjs file, i.e.<br /><br /><blockquote style="BORDER-RIGHT: 1px dashed; PADDING-RIGHT: 5px; BORDER-TOP: 1px dashed; PADDING-LEFT: 5px; BACKGROUND: #ffffff; LEFT: 65px; PADDING-BOTTOM: 5px; BORDER-LEFT: 1px dashed; WIDTH: 360px; PADDING-TOP: 5px; BORDER-BOTTOM: 1px dashed; POSITION: relative"><p style="BACKGROUND: #ffffff; WIDTH: 100%"><em><span style="color:#009900;"># rjs render a javascript alert on the client</span></em><br /><span style="color:#3333ff;">page<span style="color:#000000;">.alert</span> '<span style="color:#990000;">Errors\nError 1\nError 2</span>'</span></p></blockquote>and it kept on printing my error message as Errors<span style="color:#ff0000;">\n</span>Error message 1<span style="color:#ff0000;">\n</span>Error message2 - note that the newline characters were being escaped and rendered literally<br /><br />I found this <a href="http://www.agmweb.ca/blog/andy/1937/">informative post</a> which lead me to change my code from using single quotes to using double quotes - nasty.<br /><br /><blockquote style="BORDER-RIGHT: 1px dashed; PADDING-RIGHT: 5px; BORDER-TOP: 1px dashed; PADDING-LEFT: 5px; BACKGROUND: #ffffff; LEFT: 65px; PADDING-BOTTOM: 5px; BORDER-LEFT: 1px dashed; WIDTH: 460px; PADDING-TOP: 5px; BORDER-BOTTOM: 1px dashed; POSITION: relative"><p style="BACKGROUND: #ffffff; WIDTH: 100%; HEIGHT: 54px"><em><span style="color:#009900;"># this one will output the newlines in the javascript alert message</span></em><br /><span style="color:#3333ff;">page<span style="color:#000000;">.alert</span> "<span style="color:#990000;">Errors\nError 1\nError 2"</span></span></p></blockquote><br /><br />here is the final code, looping through each error on the model object (product in this case) and outputing a newline on the javascript alert for each error<br /><br /><br /><blockquote style="BORDER-RIGHT: 1px dashed; PADDING-RIGHT: 5px; BORDER-TOP: 1px dashed; PADDING-LEFT: 5px; BACKGROUND: #ffffff; LEFT: 65px; PADDING-BOTTOM: 5px; BORDER-LEFT: 1px dashed; WIDTH: 481px; PADDING-TOP: 5px; BORDER-BOTTOM: 1px dashed; POSITION: relative; HEIGHT: 301px"><p><em><span style="color:#009900;"># rjs file</span></em><br /><span style="color:#3333ff;">page</span>.alert <span style="color:#3333ff;">"</span><span style="color:#cc0000;">#{get_message_for_show_server_error}</span><span style="color:#3333ff;">"</span><br /></p><p><em><span style="color:#009900;"># helper file<br /></span></em><span style="color:#993399;">def</span> get_message_for_show_server_error<br /><span style="color:#ffffff;">__</span>s = "<span style="color:#cc0000;">Errors </span>"<br /><span style="color:#ffffff;">__</span><span style="color:#3333ff;">@product</span>.errors.full_messages.each <span style="color:#993399;">do</span> error<br /><span style="color:#ffffff;">____</span>s = s + "<span style="color:#cc0000;">\n</span>" + error.to_s<br /><span style="color:#993399;"><span style="color:#ffffff;">__</span>end</span></p><p><span style="color:#3333ff;"><span style="color:#ffffff;">__</span>return</span> s<br /><span style="color:#993399;">end</span><br /><br /></p><p style="BACKGROUND: #ffffff; WIDTH: 100%"></p></blockquote><br /><p></p><p></p>House 9http://www.blogger.com/profile/08045832658861127427noreply@blogger.com0tag:blogger.com,1999:blog-14193236281833595.post-81597052932472595632007-09-01T10:37:00.000-07:002007-09-01T11:15:30.411-07:00Ruby Notes - part 1 - dynamic object creationI am starting to learn Ruby and Rails (just for fun) - took awhile to find a good example of creating an object at runtime given a string representing the objects name; finally came across this post <a href="http://www.ruby-forum.com/topic/96222">http://www.ruby-forum.com/topic/96222</a>;<br /><br />in theses 2 examples - given an ActiveRecord object 'Project' and a database table named 'projects', invoke the Project and execute some methods on it<br /><blockquote style="BORDER-RIGHT: 1px dashed; PADDING-RIGHT: 5px; BORDER-TOP: 1px dashed; PADDING-LEFT: 5px; BACKGROUND: #ffffff; LEFT: 65px; PADDING-BOTTOM: 5px; BORDER-LEFT: 1px dashed; WIDTH: 360px; PADDING-TOP: 5px; BORDER-BOTTOM: 1px dashed; POSITION: relative"><p style="BACKGROUND: #ffffff; WIDTH: 100%"><em><span style="color:#009900;"># using eval</span></em><br /><span style="color:#993399;">def</span> test_dynamic_invoke_with_eval<br /><span style="color:#ffffff;">__</span>object_name = <span style="color:#3333ff;">"Project"</span><br /><span style="color:#ffffff;">__</span>o = eval(object_name)<br /><br /><span style="color:#ffffff;">__</span>p <span style="color:#3333ff;">"object name is '"</span> + o.to_s + <span style="color:#3333ff;">"'"<br /></span><span style="color:#ffffff;">__</span>p <span style="color:#3333ff;">"object table name is '"</span> + o.table_name + <span style="color:#3333ff;">"'"<br /></span><span style="color:#993399;">end</span><br /><br /></p></blockquote><br /><br /><blockquote style="BORDER-RIGHT: 1px dashed; PADDING-RIGHT: 5px; BORDER-TOP: 1px dashed; PADDING-LEFT: 5px; BACKGROUND: #ffffff; LEFT: 65px; PADDING-BOTTOM: 5px; BORDER-LEFT: 1px dashed; WIDTH: 360px; PADDING-TOP: 5px; BORDER-BOTTOM: 1px dashed; POSITION: relative"><p style="BACKGROUND: #ffffff; WIDTH: 100%"><em><span style="color:#009900;"># using Object.const_get</span></em><br /><span style="color:#993399;">def</span> test_dynamic_invoke_with_object_const_get<br /><span style="color:#ffffff;">__</span>object_name = <span style="color:#3333ff;">"Project"</span><br /><span style="color:#ffffff;">__</span>o = Object.const_get(object_name)<br /><br /><span style="color:#ffffff;">__</span>p <span style="color:#3333ff;">"object name is '"</span> + o.to_s + <span style="color:#3333ff;">"'"<br /></span><span style="color:#ffffff;">__</span>p <span style="color:#3333ff;">"object table name is '"</span> + o.table_name + <span style="color:#3333ff;">"'"<br /></span><span style="color:#993399;">end</span></p></blockquote><br /><br />Check the ruby forum link above as well - the last entry posted by <em>'unknown (Guest)'</em>; this is probably the true ruby way to do it? extend the String object with a helper method so you can turn any string into an object? code from that post<br /><blockquote style="BORDER-RIGHT: 1px dashed; PADDING-RIGHT: 5px; BORDER-TOP: 1px dashed; PADDING-LEFT: 5px; BACKGROUND: #ffffff; LEFT: 65px; PADDING-BOTTOM: 5px; BORDER-LEFT: 1px dashed; WIDTH: 360px; PADDING-TOP: 5px; BORDER-BOTTOM: 1px dashed; POSITION: relative"><p style="BACKGROUND: #ffffff; WIDTH: 100%"><em><span style="color:#009900;"># extend String</span></em><br /><span style="color:#993399;">class</span> String<br /><span style="color:#993399;"><span style="color:#ffffff;">__</span>def </span>to_class<br /><span style="color:#ffffff;">_</span><span style="color:#ffffff;">__</span>Object.const_get(<span style="color:#3333ff;">self</span>)<br /><span style="color:#ffffff;">__</span><span style="color:#993399;">end</span><span style="color:#ffffff;">__</span><span style="color:#3333ff;"><br /></span><span style="color:#993399;">end</span></p></blockquote>House 9http://www.blogger.com/profile/08045832658861127427noreply@blogger.com2tag:blogger.com,1999:blog-14193236281833595.post-71995613440022040752007-02-11T12:09:00.000-08:002008-02-16T09:24:15.877-08:00A client side (javascript) confirm box with ASP.NETThe following code sample illustrates a client side (javascript) confirm box in use with an aspx button, this presents the end user with a dialog box asking ''are you sure you want to submit this form?', it gives the user two options 'Ok' and 'Cancel', clicking ok will submit the form, clicking cancel will not<br /><br />This sample code uses 4 variations;<br /><ul><li><span style="font-size:85%;"><strong>TestButton1</strong> - a standard html input type 'button', which submits the page using hand coded js</span></li><li><span style="font-size:85%;"><strong>TestButton2</strong> - a standard html input type 'submit', it has the default behaviour of submitting the form</span></li><li><span style="font-size:85%;"><strong>TestButton3</strong> - an asp:button with the OnClientClick (rendered as onclick) declared in the mark up</span></li><li><span style="font-size:85%;"><strong>TestButton4</strong> - an asp:button with the onclick defined in the code behind or c#</span><br /></li></ul><br /><div>The aspx page markup - JavaScriptConfirm.aspx</div><br /><br /><pre class="xml" name="code"><br /><%@ Page <br /> Language="C#" <br /> AutoEventWireup="true" <br /> CodeBehind="JavaScriptConfirm.aspx.cs" <br /> Inherits="SandboxOne.JavaScriptConfirm" <br />%><br /><!DOCTYPE...><br /><html><br /><head runat="server"><br /> <title>Javascript Confirm</title><br /> <script language="javascript" type="text/javascript"><br /> function AreYouSure()<br /> {<br /> return confirm('are you sure you want to submit this form?');<br /> }<br /> </script><br /></head><br /><body><br /><form id="form1" runat="server"><br /> <input id="TestButton1"<br /> type="button"<br /> onclick="if(AreYouSure()) { document.forms[0].submit(); }"<br /> value="A regular html 'button' button"<br /> /><br /> <input id="TestButton2"<br /> type="submit"<br /> onclick="return AreYouSure();"<br /> value="A regular html 'submit' button"<br /> /><br /> <asp:Button ID="TestButton3"<br /> OnClientClick="return AreYouSure();"<br /> OnClick="InvokeServerSideMethod"<br /> Text="A asp button"<br /> runat="server"<br /> /><br /> <asp:Button ID="TestButton4"<br /> OnClick="InvokeServerSideMethod"<br /> Text="A asp button c# wired OnClientClick"<br /> runat="server"<br /> /><br /></form><br /></body><br /></html><br /></pre><br />The c# 'code-behind'<br /><pre name="code" class="c-sharp"><br />public partial class JavaScriptConfirm : System.Web.UI.Page<br />{<br /> protected void Page_Load(object sender, EventArgs e)<br /> {<br /> // wire the client side onclick to TestButton4<br /> this.TestButton4.Attributes.Add("onclick", "return AreYouSure();");<br /><br /> if(Page.IsPostBack)<br /> {<br /> Response.Write<br /> (<br /> String.Format("Page_Load, IsPostBack: {0}<hr />", DateTime.Now.ToLongTimeString())<br /> );<br /> }<br /> }<br /><br /> // the server side 'event' kicked off when asp:button is clicked<br /> protected void InvokeServerSideMethod(object sender, EventArgs e)<br /> {<br /> Response.Write<br /> (<br /> String.Format("InvokeServerSideMethod, E: {0}<hr />", DateTime.Now.ToLongTimeString())<br /> );<br /> }<br />}<br /></pre><br /><div style="MARGIN: 0px 0px 15px"><br />The 'key' here is the return in the onclick method; the javascript confirm will return true if 'Ok' is clicked and false if 'Cancel' is clicked, we must return this value from our buttons onclick event so that the form will not generate an HTTP POST (or PostBack if you like)<br /><br />if you do not include the return statement in the onclick the form will post back regardless of which button is clicked 'Ok' or 'Cancel'; for instance you do NOT want to do this <pre name="code" class="html"> onclick="AreYouSure();" </pre>but instead do this <pre name="code" class="html"> onclick="return AreYouSure();" </pre><br /></div>House 9http://www.blogger.com/profile/08045832658861127427noreply@blogger.com0tag:blogger.com,1999:blog-14193236281833595.post-91204248850285995342007-02-11T09:05:00.000-08:002008-02-16T08:11:28.451-08:00Generate a Guid from MSSQLReally simple...<br /><div><br /><pre name="code" class="sql">SELECT NEWID()</pre><br /></div><br /><br />This returns a MSSQL datatype of uniqueidentifier<br />read more here - <a href="http://msdn2.microsoft.com/en-us/library/aa276822(SQL.80).aspx">http://msdn2.microsoft.com/en-us/library/aa276822(SQL.80).aspx</a>House 9http://www.blogger.com/profile/08045832658861127427noreply@blogger.com0tag:blogger.com,1999:blog-14193236281833595.post-89311274310640251362007-02-11T08:54:00.000-08:002007-02-11T08:54:01.954-08:00This blog is just for the code samplesmy real blog is at <a href="http://house9.blogspot.com/">http://house9.blogspot.com/</a><br /><br />there really is not anything that interesting there either...House 9http://www.blogger.com/profile/08045832658861127427noreply@blogger.com0