Rotating content with JQuery, JTemplates & AJAX

May 30th, 2010 David Veksler No comments

The following JavaScript is used here to rotate the featured product every 30 seconds. I will leave the implementation of the JSON-emitting REST api for another post.

<script src="/Javascript/jquery-latest.min.js" type="text/javascript"><!--mce:0--></script>
<script src="/Javascript/jquery-jtemplates.js" type="text/javascript"><!--mce:1--></script>    
 
<script type="text/javascript"><!--mce:2--></script>
<div id="FeaturedProduct" class="outerbox"></div>
<textarea id="productTemplate" style="display: none;"> 
&lt;div class="outerbox"&gt;
&lt;div class="box featured"&gt;
&lt;h2 &gt;
			Featured&lt;/h2&gt;
&lt;div class="item"&gt;
&lt;div class="bord-se"&gt;
&lt;div class="bord-ne"&gt;
&lt;div class="bord-s"&gt;
						&lt;a href="/store/Product.aspx?ProductId={$T.ProductId}&amp;utm_source=Homepage&amp;utm_medium=FeaturedProd&amp;utm_term=Widget&amp;utm_campaign=Featured_Widget" mce_href="/store/Product.aspx?ProductId={$T.ProductId}&amp;utm_source=Homepage&amp;utm_medium=FeaturedProd&amp;utm_term=Widget&amp;utm_campaign=Featured_Widget" id="A1"&gt;
							&lt;img class="FeaturedProduct" src="{$T.ThumbnailUrl}" mce_src="{$T.ThumbnailUrl}" alt="featured" style="border-width:0px;" mce_style="border-width: 0px;" /&gt;
						&lt;/a&gt;
					&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;h4&gt;
			&lt;a href="/store/Product.aspx?ProductId={$T.ProductId}&amp;utm_source=Homepage&amp;utm_medium=FeaturedProd&amp;utm_term=Widget&amp;utm_campaign=Featured_Widget" mce_href="/store/Product.aspx?ProductId={$T.ProductId}&amp;utm_source=Homepage&amp;utm_medium=FeaturedProd&amp;utm_term=Widget&amp;utm_campaign=Featured_Widget"&gt;{$T.Name}&lt;/a&gt;&lt;/h4&gt;
 
			&lt;span&gt;Author: &lt;/span&gt;
			&lt;a href="/store/search.aspx?m={$T.AuthorId}" mce_href="/store/search.aspx?m={$T.AuthorId}"&gt;{$T.Author}&lt;/a&gt; 
			&lt;span class="Price"&gt;
				${$T.Price}&lt;/span&gt; 
 
            {$T.Summary}				
 
			&lt;a class="more" href="/store/New-Products-C52.aspx" mce_href="/store/New-Products-C52.aspx"&gt;view all…&lt;/a&gt;
 
&lt;/div&gt;
&lt;/div&gt;
 
</textarea>

Categories: code Tags: , , ,

AES encryption strategies with .Net

April 11th, 2010 David Veksler No comments

I did a presentation last week on AES encryption techniques in .Net.

I’ll post some details here later, but for now, I’ve uploaded a zip file with the project code.

Here’s the key bit:

 
            string key = "1234567891123456";
            string secret = @"Sometimes I sing Shania Twain's ""I Feel Like A Woman!"" in the shower.";
 
            Console.WriteLine("basic:");
            EncryptString(key, secret);
            Console.ReadKey();
 
            Console.WriteLine("salt the secret:");
            // good when there are multiple machines but a dynamic global shared secret (for example, Profile Create Date or User ID)
            string secret2 = secret + " ###" + DateTime.Now.Millisecond;
            EncryptString(key, secret2);
 
            secret2 = secret + " ###" + DateTime.Now.Millisecond;
            EncryptString(key, secret2);
 
            Console.ReadKey();
 
            Console.WriteLine("salt the key:"); 
            // good when the same machine encrypts/decrepts
            string uniqueMachineIdentifier = MachineId.GetProcessorID();
            Console.WriteLine("MachineId: " + uniqueMachineIdentifier);
            EncryptString(key + uniqueMachineIdentifier, secret);
            Console.ReadKey();
 
            Console.WriteLine("SHA1 hash the passphrase with a salt:"); 
            // note: talk about why hashing is good
            SHA1 sha = new SHA1CryptoServiceProvider();
            // This is one implementation of the abstract class SHA1.
            string password = "this is my user password and/or userid";
            byte[] saltedKey = Encoding.Default.GetBytes(key + password);
 
            byte[] result = sha.ComputeHash(saltedKey);
            EncryptString(Convert.ToBase64String(result), secret);
            Console.ReadKey();

Categories: code Tags: , ,

Using the MySql ADO.Net adapter

April 11th, 2010 David Veksler No comments
public DataSet ExecuteQuery(string commandText)
        {
            DataSet ds = new DataSet();
            using (var connection = new MySqlConnection(connString))
            {
                connection.Open();
                var command = connection.CreateCommand();
                command.CommandText = commandText;
                using (var data = new MySqlDataAdapter { SelectCommand = command })
                {
                    data.Fill(ds);
                    connection.Close();
                }
            }
            return ds;
        }

Categories: code Tags:

.Net Graphics: drawing text on a bitmap

April 1st, 2010 David Veksler No comments

I use this code here.

Graphics backgroundGraphics;
backgroundImage = (Bitmap)Image.FromFile(AppDomain.CurrentDomain.BaseDirectory + "\\images\\Header.jpg");
backgroundGraphics = Graphics.FromImage(backgroundImage);
var font = new Font("Perpetua Titling MT", 24F, FontStyle.Regular);
backgroundGraphics.DrawString(authorname.ToUpper(), font, new SolidBrush(Color.FromArgb(100, 0, 0, 0)), 10, 5);

Now save – or output to the browser:

backgroundImage.Save(context.Response.OutputStream, ImageFormat.Jpeg);

Categories: code Tags: ,

Response.Redirect and 302 and 301 status codes

March 8th, 2010 David Veksler No comments

If you use Response.Redirect to direct users to a new location, you should be aware that it issues a status code of 302, which means that “the resource resides temporarily under a different URI.” If you intend to communicate that the resource has permanently changed locations, you should not use Response.Redirect. This is important for search engines and other crawlers that might need to know the definitive url.

To send a 301 redirect:

Response.Status = "301 Moved Permanently";
Response.StatusCode = 301;
Response.AddHeader("Location", url);
Response.End();

Update: ASP.Net 4.0 ads a Response.RedirectPermanent() method.

Categories: code Tags:

Set the admin color scheme for all WordPress users

March 6th, 2010 David Veksler No comments
INSERT INTO wp_usermeta
(
user_id,
meta_key,
meta_value
)
(
SELECT
id,
'admin_color',
'classic'
FROM wp_users
WHERE id  NOT  IN (SELECT user_Id FROM wp_usermeta WHERE meta_key = 'admin_color')
)
 
UPDATE wp_usermeta SET meta_value = 'classic' WHERE meta_key = 'admin_color'

Categories: code Tags: ,

Bulk update post slugs in a WordPress blog

March 6th, 2010 David Veksler 1 comment

The following PHP script updates missing post slugs (permalinks) in a WordPress blogs, or reformats them according to your needs:
Read more…

Categories: code Tags: , ,

Delete smart quotes and fix latin1>utf8 encoding issues in WordPress

March 4th, 2010 David Veksler No comments

If you use wptexturize, smart quotes will mess you up. This is a quick and dirty fix.
Read more…

Categories: code Tags:

SQL script to migrate from Movable Type to WordPress

March 2nd, 2010 David Veksler No comments

While trying to migrate a large blog from Movable Type to WordPress, I found the built-in export and import functionality unable to handle volume of content on the blog or to properly preserve the primary keys needed for permalinks.

With assistance from Alvaro on the MisesDev list, we came up with the following MySql SQL script to import the entries directly from the Movable Type (5.01) database to WordPress (2.9.2). What would take many hours otherwise can be done in a minute or two. This is especially important if you don’t want to lose data during the time it takes to migrate the blog, as the script can be run immediately before the switch. This script also includes additional stuff like IP addresses and url-friendly names.
Read more…

Categories: code Tags: , ,

Luhn algorithm validation via a CustomValidator control

February 8th, 2010 David Veksler No comments
The Luhn algorithm is a checksum used for credit cards and many other identifying numbers as a basic integrity validation check.  It’s useful for credit card forms because it avoids unneeded transaction attempts when card numbers are mis-typed.
It’s easy to add an account # Luhn checksum validation control to credit card forms in ASP.Net:
  • Add this method to your business logic.
  • Add a <asp:CustomValidator  … /> control with the error message, target control, etc.
  • Add and wire up a void ServerValidation method:
void ServerValidation(object source, ServerValidateEventArgs args) {
// use a RequiredFieldValidator to check for an empty value
 if (txtCardNum.Text == string.Empty) args.IsValid = true;
 args.IsValid = IsCreditCardValid(this.txtCardNum.Text);
}
 
protected override void OnInit(EventArgs e)    {
 base.OnInit(e);
 valLunCode.ServerValidate += ServerValidation;
}
  • (Optional:) For client-side code, use a Javascript version from here.

Categories: code Tags: , , , ,