<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>AkillesBlog &#187; programming</title>
	<atom:link href="http://blog.akilles.org/tag/programming/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.akilles.org</link>
	<description>Talk on programming, computers, electronics, web etc</description>
	<lastBuildDate>Sun, 13 Jun 2010 02:42:55 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Caching of PHP scripts with query strings</title>
		<link>http://blog.akilles.org/2009/01/10/caching-of-php-scripts-with-query-strings/</link>
		<comments>http://blog.akilles.org/2009/01/10/caching-of-php-scripts-with-query-strings/#comments</comments>
		<pubDate>Sat, 10 Jan 2009 19:41:01 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Software]]></category>
		<category><![CDATA[caching]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[url rewrite]]></category>

		<guid isPermaLink="false">http://blog.akilles.org/?p=66</guid>
		<description><![CDATA[Trying to decrease bandwith usage and page loading time, I&#8217;ve enabled caching on some of my web pages recently. Caching can be done in many ways, and with PHP-scripts running on Apache, I have the choice of enabling caching in either .htaccess-files, in the HTML-header or in the HTTP header. I think sending HTTP headers [...]]]></description>
			<content:encoded><![CDATA[<p>Trying to decrease bandwith usage and page loading time, I&#8217;ve enabled caching on some of my web pages recently. Caching can be done in many ways, and with PHP-scripts running on Apache, I have the choice of enabling caching in either .htaccess-files, in the HTML-header or in the HTTP header. I think sending HTTP headers from PHP gives the best control, having all programatically possibilities for conditional caching and headers.</p>
<p>For basic caching of a generated PHP-page I find the &#8220;Expires&#8221; / &#8220;max-age&#8221; HTTP headers the most convenient to use;</p>
<pre name="code" class="php">

//Cache for 15 minutes:
$maxage = 60*15;
header (&quot;Cache-Control: max-age=$maxage&quot;);
header ('Expires: ' . gmstrftime(&quot;%a, %d %b %Y %H:%M:%S GMT&quot;, time() + $maxage));
</pre>
<p>With this method, the page will be loaded from the user&#8217;s browser-cache instead of from my server until $maxage seconds have passed. After that, a new visit to the page will be freshly loaded from my server to the browser&#8217;s cache again, and will live there for another $maxage seconds. This <strong>works well with</strong> URLs such as </p>
<ul>
<li>http://www.example.com/index.php</li>
<li>http://www.example.com/index.html</li>
<li>http://www.example.com/</li>
<li>http://www.example.com/pages/frontpage/</li>
</ul>
<p><strong>but not with</strong> URLs containing query strings:</p>
<p>http://www.example.com/index.php<em>?page=frontpage&#038;itemcount=10</em></p>
<p><script type="text/javascript"><!--
google_ad_client = "pub-0426298800349415";
google_ad_slot = "0902617621";
google_ad_width = 468;
google_ad_height = 60;
//--></script>
<script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
</p>
<h2>The problem with query strings</h2>
<p>If the URL to the page in question contains a query string (starting with the question mark in this URL: http://www.example.com/index.php?page=frontpage&#038;itemcount=10), the HTTP standard says that the browser never should cache that page. Using standard-compliant browsers like Opera, you&#8217;ll have to <strong>get rid of that query string</strong> to enable caching of such pages.</p>
<p>I long scratched my head over this, but was after a while enlightened by <a href="http://www.thinkvitamin.com/features/webapps/serving-javascript-fast">Cal Henderson&#8217;s post</a>:</p>
<blockquote><p>
According the letter of the HTTP caching specification, user agents should never cache URLs with query strings. While Internet Explorer and Firefox ignore this, Opera and Safari don’t &#8211; to make sure all user agents can cache your resources, we need to keep query strings out of their URLs.
</p></blockquote>
<h2>Getting rid of the query string &#8211; URL rewriting</h2>
<p><script type="text/javascript"><!--
google_ad_client = "pub-0426298800349415";
google_ad_slot = "0902617621";
google_ad_width = 468;
google_ad_height = 60;
//--></script>
<script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
</p>
<p>URL rewriting can be used to <em>tricking</em> the browser into believing we&#8217;re browsing an ordinary page without query strings. URL rewriting means that the user and the user&#8217;s browser enters and sees an URL like http://www.example.com/frontpage.asdf, while the Apache web server internally translates this to, let&#8217;s say, http://www.example.com/index.php?page=frontpage, running your index.php script with the right GET parameters.</p>
<p>Using Apache, this is as easy as writing some RewriteRules in a .htaccess-file, for instance:<br />
<code><br />
RewriteEngine On</p>
<p>#do not rewrite requests for /index.php:<br />
RewriteRule	^index.php$	-			[L]</p>
<p>#rewrite /frontpage.asdf, /photos.asdf<br />
#to /index.php?page=frontpage etc:<br />
RewriteRule	^(.*?).asdf$	/index.php?page=$1	[QSA,L]<br />
</code></p>
<p>More tips and tricks about URL rewriting can be read <a href="http://www.askapache.com/htaccess/mod_rewrite-tips-and-tricks.html">here</a> and many other places. Google it!</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.akilles.org/2009/01/10/caching-of-php-scripts-with-query-strings/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Ruby on Rails: Experimenting with ActiveScaffold</title>
		<link>http://blog.akilles.org/2008/04/17/ruby-on-rails-experimenting-with-activescaffold/</link>
		<comments>http://blog.akilles.org/2008/04/17/ruby-on-rails-experimenting-with-activescaffold/#comments</comments>
		<pubDate>Thu, 17 Apr 2008 01:00:58 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[programming]]></category>
		<category><![CDATA[ActiveScaffold]]></category>
		<category><![CDATA[rails]]></category>
		<category><![CDATA[scaffolding]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://blog.akilles.org/?p=61</guid>
		<description><![CDATA[Introduction
Here I will set up a sample Ruby on Rails application with the ActiveScaffold scaffolding plugin. I will first give the basic instructions to a default setup (as found on ActiveScaffold&#8217;s site, only with my field names and values), and will then make some tweaks and override some of the default configuration. It&#8217;s all very [...]]]></description>
			<content:encoded><![CDATA[<h3>Introduction</h3>
<p>Here I will set up a sample Ruby on Rails application with the ActiveScaffold scaffolding plugin. I will first give the <strong><a href="#basic">basic instructions to a default setup</a></strong> (as found on ActiveScaffold&#8217;s site, only with my field names and values), and will then make some <strong><a href="#overrides">tweaks and override</a></strong> some of the default configuration. It&#8217;s all very basic, but it can be a help for those trying out ActiveScaffold for their first time.</p>
<p><strong>The case we&#8217;re working on:</strong> create a list of <em>Equipment</em>, i.e. electronic gadgets you&#8217;re planning to buy. We want to register title, price, an url to the product page of a webstore, an image url, some description and whether it&#8217;s in the webstore&#8217;s stock. Aditionally, we would like to <em>calculate</em> the registered price into another currency. All of this is to be shown in a sortable, searchable list.</p>
<p>It will be <strong><a href="http://blog.akilles.org/wp-content/uploads/2008/04/equipment.png">looking like this</a></strong> when we&#8217;re done.</p>
<p>After some years developing and experimenting with PHP, I&#8217;ve become curious of Ruby on Rails and what it has to offer in ease and &#8220;speedy&#8221; development. I&#8217;m for the time being an absolute rookie in RoR, but I&#8217;ve had a look on some resources on the net and have tried making a few very basic &#8220;test&#8221; applications.</p>
<p>Having limited experience regarding web development <em>frameworks</em>, it takes a few scratches on the head to get the <a href="http://betterexplained.com/articles/intermediate-rails-understanding-models-views-and-controllers/">concept of MVC</a> and knowing what does what (M=model, V=view, C=controller) and what calls what. Generating a scaffold and investigating the different files helps grasping the concept after a while.</p>
<p>The first time I saw the result of a scaffold-generation, I was convinced that this kind of development was something to look further into. However, after having seen samples of other scaffold generators, the default one seems a little <em>static</em> and cumersome to override: It seems like the default scaffolding generator is meant for running once, and then hardcode-editing the scaffold-generated code. Then, if you for some reason have to rescaffold, you must reimplement the changes. Also, the result is rather static without &#8220;fancy stuff&#8221; like Ajax.</p>
<p>Therefore, I had to test out the ActiveScaffold scaffolding plugin. It&#8217;s very easily installed, quickly up and running (a getting-started-tutorial on their site is estimated to 2 minutes from scratch), produces a smooth Ajax&#8217;ed design and is very easily to override and configure.</p>
<p>Remember, though, that I&#8217;m quite new to RoR, so I haven&#8217;t a broad basis of comparison, and there may be better practices for what I&#8217;m doing here. If so, please tell me! <img src='http://blog.akilles.org/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<h3>Assumptions</h3>
<p>I think the majority of the steps in this tutorial should work with most versions (except the scaffolding, which is different in rails v. >= 2), but here&#8217;s what I&#8217;ve used:</p>
<ul>
<li>Rails 1.2.6 <em>(yes, I know, it&#8217;s time to upgrade&#8230;)</em></li>
<li>Ruby 1.8.6</li>
<li>ActiveScaffold rev. 739</li>
</ul>
<p><strong>I assume you have</strong> a working rails-application, set up with connection to an existing database and accessible through a web browser before starting off.</p>
<p><div class="adsense_post"><script type="text/javascript"><!--
google_ad_client = "pub-0426298800349415";
google_ad_slot = "9481476571";
google_ad_width = 336;
google_ad_height = 280;
//--></script>
<script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
</div></p>
<p><a name="basic"><br />
<h3>Basic setup</h3>
<p></a></p>
<p>The first thing we&#8217;re gonna do, is <strong>create a new table</strong> in the database to which the application connects. I created a table called <em>equipment</em> like this in my MySql database:</p>
<pre name="code" class="sql">

CREATE TABLE equipment (
  id int(10) unsigned NOT NULL auto_increment,
  title varchar(255) NOT NULL,
  descr text NOT NULL,
  price float NOT NULL,
  updated timestamp NOT NULL
    default CURRENT_TIMESTAMP
    on update CURRENT_TIMESTAMP,
  url varchar(255) NOT NULL,
  imgurl varchar(255) NOT NULL,
  instock tinyint(1) NOT NULL default '1',
  PRIMARY KEY  (id)
) ;
</pre>
<p>Then, let the generator scripts <strong>make the appropriate files</strong> we&#8217;ll be working on. 4 types of files are created, but we&#8217;re only interested in 3 of these; the <em>model</em>, <em>controller</em> and <em>helper</em> files, not the <em>view</em> files. However, we&#8217;ll just delete the view files afterwards&#8230;<br />
Open up a terminal window, and cd to your rails application root folder. Then run<br />
<code>./script/generate scaffold Equipment</code></p>
<p>Now, <strong>delete</strong> the unnecessary views files (not only unnecessary; they also override the ActiveScaffold which we&#8217;ll put to work later on, so <strong>follow this step!</strong>):<br />
<code>rm -R app/views/equipment/</code></p>
<p>Now it&#8217;s about time to <strong>install</strong> the ActiveScaffold plugin:<br />
<em>([Parts of] the following few steps are borrowed from ActiveScaffold&#8217;s <a href="http://activescaffold.com/">website</a>)</em><br />
<code>./script/plugin install http://activescaffold.googlecode.com/svn/tags/active_scaffold</code></p>
<p>When the plugin has been downloaded and installed, you need to <strong>update</strong> a few of your files.<br />
Add this to the <em>head</em>-section of your <em>app/views/layouts/equipment.rhtml</em> file:</p>
<pre name="code" class="ruby">

  &lt;%= javascript_include_tag :defaults %&gt;
  &lt;%= active_scaffold_includes %&gt;
</pre>
<p>It should then look something like this:</p>
<pre name="code" class="ruby">

&lt;!DOCTYPE html PUBLIC &quot;-//W3C//DTD XHTML 1.0 Transitional//EN&quot;
       &quot;http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd&quot;&gt;

&lt;html xmlns=&quot;http://www.w3.org/1999/xhtml&quot; xml:lang=&quot;en&quot; lang=&quot;en&quot;&gt;
&lt;head&gt;
  &lt;meta http-equiv=&quot;content-type&quot; content=&quot;text/html;charset=UTF-8&quot; /&gt;
  &lt;title&gt;as test&lt;/title&gt;
  &lt;%= javascript_include_tag :defaults %&gt;
  &lt;%= active_scaffold_includes %&gt;
&lt;/head&gt;
&lt;body&gt;

&lt;p style=&quot;color: green&quot;&gt;&lt;%= flash[:notice] %&gt;&lt;/p&gt;

&lt;%= yield  %&gt;

&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>Then, <strong>edit</strong> your <em>app/controllers/equipment_controller.rb</em>, so that it looks similar to this:</p>
<pre name="code" class="ruby">

class EquipmentController &lt; ApplicationController
  @equipment_pages, @equipment = paginate :equipment, :per_page =&gt; 10
  layout &quot;equipment&quot;
  active_scaffold :equipment
end
</pre>
<p>Also, quote from <a href="http://activescaffold.com/tutorials/getting-started">http://activescaffold.com/tutorials/getting-started</a>:</p>
<blockquote><p>3a. Make sure that you don’t have AjaxScaffold installed in your project. Since ActiveScaffold evolved out of AjaxScaffold they share some common method names and are incompatible with each other.</p></blockquote>
<p>Then you&#8217;re <strong>done</strong> with basic setup. Now browse to http://your-rails-app-root/Equipment, and hopefully you&#8217;ll see the magnificent Ajax&#8217;ed layout created by ActiveScaffold. Isn&#8217;t it wonderful?</p>
<p>If you, like me, are running Rails on Apache/FastCGI, you may have to restart your Apache httpd-server every now and then (I don&#8217;t know of any other methods of killing/restarting the rails fastCGI-scripts being run by apache. If you know; please tell me!). When testing new stuff and/or when getting errors, I always restart apache to see if the problem still persists.</p>
<p>Up to now, we&#8217;ve basically dealt with initial setup covered by ActiveScaffold&#8217;s own <a href="http://activescaffold.com/tutorials/getting-started">Getting Started-tutorial</a>. Now it&#8217;s time to tweak the config to our needs.</p>
<p><div class="adsense_post"><script type="text/javascript"><!--
google_ad_client = "pub-0426298800349415";
google_ad_slot = "8602966591";
google_ad_output = "textlink";
google_ad_format = "ref_text";
google_cpa_choice = "";
//--></script>
<script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
</div></p>
<p><a name="overrides"><br />
<h3>Tweaking and overriding default ActiveScaffold config</h3>
<p></a></p>
<p>I&#8217;m over all very satisfied with the looks and functionality of the initial output, especially when considering it almost takes no time at all. However, since ActiveScaffold can&#8217;t know how I plan to view my data, there are some overrides to be done. Datafields are overridden very smoothly by creating small methods with designated names in the right classes.</p>
<p>Anyways, here&#8217;s what I&#8217;m gonna do:</p>
<ul>
<li>Show the <strong>image</strong> pointed to by <em>imgurl</em> instead of the url itself.</li>
<li>Put the image inside an <em>&lt;a href&#8230;&gt;</em>-tag, so that the image <strong>links to the url</strong> in the <em>url</em>-field.</li>
<li>Create/include a <strong>virtual column</strong> that shows the price in <strong>a foreign currency</strong> as well as in USD.</li>
<li><strong>Format</strong> the two price-columns with <em>sprintf</em></li>
<li><strong>Reorder</strong> the columns</li>
<li><strong>Exclude</strong> the <em>descr</em>-column from list view</li>
<li>Tweak the output of the boolean field <em>instock</em></li>
<li>Apply a <strong>default sorting</strong> of the rows in the list view</li>
</ul>
<p>This may sound as a lot of work, but fact is it&#8217;s quite easily implemented.</p>
<p>First a note on the two price-columns: I live in Norway, and am sometimes interested in monitoring prices in some US webshops. Therefore, I register the USD price in the <em>price</em>-field in the database, while I calculate what this will cost me in NOK (Norwegian kroner) based on the current exchange rate. Since most of you probably are not from Norway, I called NOK the foreign currency.</p>
<p>First, place a floating point number (for instance 4.99 &#8211; the actual rate on 2008-Apr-15, the lowest rate in 25 years!) as the only line in a file placed here (though customized for your rails-path!):<br />
<em>/usr/local/www/rails/as/myincludes/nok_usd_rate.txt</em></p>
<p>We want a global variable (<em>yeah, I know everyone&#8217;s not found of that</em>) to hold the exchange rate, read from a file in the event of page loading. I do this so that I won&#8217;t have to read the file over for each record.</p>
<p>Edit the <em>app/controllers/application.rb</em>-file, so that it looks like this:</p>
<pre name="code" class="ruby">

# Filters added to this controller apply to all controllers in the application.
# Likewise, all the methods added will be available for all controllers.

class ApplicationController &lt; ActionController::Base
  def setmyglobalvar
    # reads exchange rate from file: UPDATE TO YOUR PATH!
    contents = File.read('/usr/local/www/rails/as/myincludes/nok_usd_rate.txt')
    # converts to NOK and includes 25% &quot;mva&quot; (=Norwegian VAT). Stores in global var:
    $myglobalvar= contents.to_f * 1.25
  end

  # Pick a unique cookie name to distinguish our session data from others'
  session :session_key =&gt; '_testapp_session_id'

  before_filter :setmyglobalvar
end
</pre>
<p>Here, we have defined a method, and calls this by the <em>before_filter</em>-statement.</p>
<p>Next, we must extend our record-model so that it includes the field to be used as a virtual column. Edit <em>app/models/equipment.rb</em> to look like this:</p>
<pre name="code" class="ruby">

class Equipment &lt; ActiveRecord::Base
  def price_nok
    # $myglobalvar is set in controllers/application_controller,
    # and contains exchange rate incl VAT:
    # self.price references the price-
    # field from current database record.
    self.price * $myglobalvar
  end
end
</pre>
<p>Then we must tell the controller to include this new field as a (virtual) column.<br />
At the same time, we reorder the columns and apply a default sorting for the list view.<br />
Note that we only alter the columns of the <em>list</em> action and not of any other actions (<em>list</em> is an action, so is <em>new</em>, <em>edit</em>, <em>show</em> etc). Altering the columns of <em>edit</em> or <em>new</em> can result in an error on record edit or creation attempts.<br />
Note also that only the columns listed in <em>config.list.columns</em> will be shown in the list view.<br />
Here it goes &#8211; <em>app/controllers/equipment_controller.rb</em>:</p>
<pre name="code" class="ruby">

class EquipmentController &lt; ApplicationController
  @equipment_pages, @equipment = paginate :equipment, :per_page =&gt; 10
  layout &quot;equipment&quot;

  active_scaffold :equipment do |config|
    list.sorting = {:price =&gt; 'DESC'}
    config.list.columns = [:imgurl, :instock, :price, :price_nok, :title, :updated]
  end
end
</pre>
<p>Then, at last, we alter the way some of the columns are shown. This is done in <em>app/helpers/equipment_helper.rb</em>, by creating methods with name <em>columnname_column</em>. All output within the method will be printed in the respective table cell (td) for each record of that column. Here is the contents of that file:</p>
<pre name="code" class="ruby">

module EquipmentHelper
  def imgurl_column(record)
    '&lt;a href=&quot;'+record.url+'&quot;&gt;' + image_tag(record.imgurl, :alt =&gt; &quot;Image&quot;) + '&lt;/a&gt;'
  end
  def url_column(record)
    '&lt;b&gt;&lt;a href=&quot;'+record.url+'&quot;&gt;[ link ]&lt;/a&gt;&lt;/b&gt;'
  end
  def instock_column(record)
    if record.instock
      image_tag(&quot;/img/yes.png&quot;, :alt =&gt; &quot;yes!&quot;)
    else
      image_tag(&quot;/img/no.png&quot;, :alt =&gt; &quot;no, sadly!&quot;)
    end
  end
  def price_column(record)
    # http://railsmanual.org/module/ActionView::Helpers::NumberHelper
    number_to_currency(record.price)
  end
  def price_nok_column(record)
    number_to_currency(record.price_nok, :unit =&gt; &quot;NOK &quot;, :delimiter =&gt; &quot; &quot;, :separator =&gt; &quot;,&quot;)
  end
  def descr_column(record)
    # for the show action, where we want to show the description as well.
    record.descr.gsub(&quot;\n&quot;, &quot;&lt;br /&gt;&quot;)
  end
end
</pre>
<h5>Custom stylesheet</h5>
<p>If you want to apply your own css-formatting, don&#8217;t edit the default stylesheets, because they may be overwritten. Instead, include this <strong>as the very last line</strong> in the <em>head</em>-section of <em>app/views/layouts/equipment.rhtml</em>:</p>
<pre name="code" class="ruby">

  &lt;%= stylesheet_link_tag 'active_scaffold_overrides' %&gt;
</pre>
<p>Then, add your css rules in the stylesheet <em>public/stylesheets/active_scaffold_overrides.css</em>! For instance:</p>
<pre name="code" class="css">

.price_nok-column
{
        font-weight: bold;
}
</pre>
<hr />
<p><a name="links"><br />
<h3>Links</h3>
<p></a></p>
<ul>
<li><a href="http://betterexplained.com/articles/intermediate-rails-understanding-models-views-and-controllers/">MVC-concept @ betterexplained.com</a></li>
</ul>
<p><div class="adsense_post"><script type="text/javascript"><!--
google_ad_client = "pub-0426298800349415";
google_ad_slot = "9481476571";
google_ad_width = 336;
google_ad_height = 280;
//--></script>
<script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
</div></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.akilles.org/2008/04/17/ruby-on-rails-experimenting-with-activescaffold/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Escaping backslash character in C# .NET MySQL-queries</title>
		<link>http://blog.akilles.org/2008/03/12/escaping-backslash-character-in-c-net-mysql-queries/</link>
		<comments>http://blog.akilles.org/2008/03/12/escaping-backslash-character-in-c-net-mysql-queries/#comments</comments>
		<pubDate>Wed, 12 Mar 2008 00:20:01 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[programming]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[escapecharacters]]></category>
		<category><![CDATA[MySQL]]></category>

		<guid isPermaLink="false">http://blog.akilles.org/2008/03/12/escaping-backslash-character-in-c-net-mysql-queries/</guid>
		<description><![CDATA[Using escape-sequences like \t or \n is one thing, but escaping the escapecharacter (often &#8216;\&#8217;) can sometimes be a pain&#8230; This is especially true when the string you&#8217;re escaping is about to be processed by several succeeding processes, like: 1) a compiler, 2) a regex-engine, 3) a database, &#8230; , etc.
Anyways, I&#8217;ve experimented some with [...]]]></description>
			<content:encoded><![CDATA[<p>Using escape-sequences like \t or \n is one thing, but escaping the escapecharacter (often &#8216;\&#8217;) can sometimes be a pain&#8230; This is especially true when the string you&#8217;re escaping is about to be processed by several succeeding processes, like: 1) a compiler, 2) a regex-engine, 3) a database, &#8230; , etc.</p>
<p>Anyways, I&#8217;ve experimented some with MySql-queries from within C# .NET, using Windows paths (containing backslashes as path separators) in the WHERE-clauses. We have a query of one of the forms:</p>
<p><strong>case 1: = operator</strong></p>
<pre name="code" class="c#">
querystring1 =
  &quot;SELECT a,b,path FROM table &quot; +
  &quot;WHERE path = '&quot; + patharg1 + &quot;';&quot;;
</pre>
<p><em>or</em></p>
<p><strong>case 2: LIKE operator</strong></p>
<pre name="code" class="c#">
querystring2 =
  &quot;SELECT a,b,path FROM table &quot; +
  &quot;WHERE path LIKE '&quot; + patharg2 + &quot;';&quot;;
</pre>
<p>Here is what I&#8217;ve found out:</p>
<p><strong>case 1: = operator</strong><br />
Use <strong>4</strong> backslashes for each backslash in the saved record you&#8217;re matching against. You could do:</p>
<pre name="code" class="c#">
patharg1 =
  patharg1.Replace(&quot;\\&quot;, &quot;\\\\&quot;);
</pre>
<p>(The 2 backslashes in the first replace-argument is for escaping the backslash within the compiler.)</p>
<p><strong>case 1: LIKE operator</strong><br />
Use <strong>8</strong>(!) backslashes for each backslash in the saved record you&#8217;re matching against. You could do:</p>
<pre name="code" class="c#">
patharg2 =
  patharg2.Replace(&quot;\\&quot;, &quot;\\\\\\\\&quot;);
</pre>
<p>(The 2 backslashes in the first replace-argument is for escaping the backslash within the compiler.)</p>
<p>The two cases could then look like this:</p>
<p><strong>case 1:</strong></p>
<pre name="code" class="c#">
querystring1 =
  &quot;SELECT a,b,path FROM table &quot; +
  &quot;WHERE path = 'c:\\\\some\\\\path.txt';&quot;;
</pre>
<p><strong>case 2:</strong></p>
<pre name="code" class="c#">
querystring2 =
  &quot;SELECT a,b,path FROM table &quot; +
  &quot;WHERE path LIKE 'c:\\\\\\\\some\\\\\\\\path.txt';&quot;;
</pre>
<p>The above is if you put the querystring into, for instance, a MySqlCommand&#8217;s CommandText.</p>
<p>However, if you use datasets and run something like</p>
<pre name="code" class="c#">
dataTable.Select(filterExpression)
</pre>
<p>where dataTable is a DataTable instance and filterExpression is a string, you must <strong>not</strong> escape the backslash more than for a usual string (you&#8217;ll just write &#8220;\\&#8221; or @&#8221;\&#8221;, because some kind of escape of the backslash is <em>always</em> necessary for the compiler).</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.akilles.org/2008/03/12/escaping-backslash-character-in-c-net-mysql-queries/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Note to self: C# and logical shortcircuiting</title>
		<link>http://blog.akilles.org/2008/03/10/note-to-self-c-and-logical-shortcircuiting/</link>
		<comments>http://blog.akilles.org/2008/03/10/note-to-self-c-and-logical-shortcircuiting/#comments</comments>
		<pubDate>Mon, 10 Mar 2008 17:44:22 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[programming]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://blog.akilles.org/2008/03/10/note-to-self-c-and-logical-shortcircuiting/</guid>
		<description><![CDATA[C# (.NET) do short-circuit logical expressions; i.e.:
1)

(A &#124;&#124; B)

==> If A is true, then only A is evaluated.
2)

(C &#38;&#38; D)

==> If C is false, then only C is evaluated.
This means that, provided that A is true, expression 1 is true even though B would throw an exception if evaluated.
An example use of expression 2:


if ((filename [...]]]></description>
			<content:encoded><![CDATA[<p>C# (.NET) <strong>do</strong> short-circuit logical expressions; i.e.:</p>
<p>1)</p>
<pre name="code" class="csharp">
(A || B)
</pre>
<p>==> If A is true, then only A is evaluated.</p>
<p>2)</p>
<pre name="code" class="csharp">
(C &amp;&amp; D)
</pre>
<p>==> If C is false, then only C is evaluated.</p>
<p>This means that, provided that A is true, expression 1 is true even though B would throw an exception if evaluated.</p>
<p>An example use of expression 2:</p>
<pre name="code" class="csharp">

if ((filename != &quot;&quot;) &amp;&amp; (new FileInfo(filename).Exists))
	//file exists
</pre>
<p>If filename == &#8220;&#8221;, the Exists-statement would throw an exception. However, since the first expression (&#8230;!=&#8230;) is false, the Exists-statement is never evaluated, and the exception doesn&#8217;t occur.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.akilles.org/2008/03/10/note-to-self-c-and-logical-shortcircuiting/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
