KeyLimeTie Blog
Often, I have the need to randomize what's presented to the user. For a test taking application I wrote, each student's test questions had to be randomized (helps prevent cheating). For a community website I built, the website's homepage sponsors had to be randomized each time the page was displayed. I've seen people try to solve this all kinds of ways, but there's one VERY simply way to do it...use SQL Server GUIDs.
Let's say you have a table of Sponsors with a SponsorID (int, identity, primary key) and a SponsorImage (varchar(50)).

And you have the following sponsor data:

To get the data returned in a randomized order, run the following query:
SELECT *, NEWID() AS RandomNum
FROM Sponsors
ORDER BY RandomNum

As you can see, the GUID is auto-generated and when sorted upon gives a different sort order for the sponsors. Could it be any easier?
Lately, I've been spending a lot of time in Visual Studio 2005. A cool new feature is code snippets. They are reusable, task-oriented blocks of code available in the code editor. They are available to download online, you can search for new ones through Visual Studio 2005 or you can create your own. Just yesterday, I came across this link:
http://msdn.microsoft.com/vstudio/downloads/codesnippets/default.aspxMicrosoft published dozens of code snippets that install into VS 2005. Check them out.
Ever have the need to allow people to download files but don't want them to know the physical location? It's actually pretty easy...just put your files in a location not accessible to the web and stream them back to the user:
1private void SendFileToUser(string strFileFullPath)
2{
3 FileStream objFile = null;
4 BinaryReader objBR = null;
5 try
6 {
7 objFile = new FileStream(strFileFullPath, FileMode.Open);
8 //Clear and change the response headers
9 Response.Clear();
10 Response.Charset = "";
11 Response.AddHeader("Content-disposition",
12 "attachment; filename=" +
13 Path.GetFileName(strFileFullPath));
14 //Stream the file down
15 objBR = new BinaryReader(objFile);
16 for (long l = 0; l < objFile.Length; l++)
17 {
18 Response.OutputStream.WriteByte(objBR.ReadByte());
19 }
20 objBR.Close();
21 }
22 catch (Exception ex)
23 {
24 throw new Exception("Exception: " + ex.Message);
25 }
26 finally
27 {
28 objBR = null;
29 objFile = null;
30 }
31}
Looking to automate your web testing? Create your own Windows forms robot to test your website (and continue to test as you add more and more features!). Here's a basic example to get you started today:
BE SURE TO CHECK OUT PART 2 OF THIS ARTICLE WHERE FRAMES ARE INVOLVEDDownload code1. Create a new Windows Forms application and add in the "Microsoft Internet Controls" COM Component (shdocvw.dll).2. Add a "Search" textbox, a couple of radio buttons, a web browser and a "Go" button. On click of the "Go" button, add the following code:1privatevoid cmdGo_Click(object sender, System.EventArgs e)
2{
3//Navigate to the page4 Object objNull = null;
5 WebBrowser.Navigate("http://www.google.com", ref objNull, ref objNull, ref objNull, ref objNull);
6 mbSearching = true;
7}3. Handle the web browser's "DocumentComplete" event like s1privatevoid WebBrowser_DocumentComplete(object sender, AxSHDocVw.DWebBrowserEvents2_DocumentCompleteEvent e)
2{
3//If we're not searching, exit4if (!mbSearching)
5return;
67 HTMLDocument myDoc = null;
8try9 {
10//Get the web browser document11 myDoc = new HTMLDocumentClass();
12 myDoc = (HTMLDocument) WebBrowser.Document;
1314//Find the textbox15 HTMLInputElement objTextBox = (HTMLInputElement) myDoc.all.item("q", 0);
16 objTextBox.value = txtSearchFor.Text;
1718//Click the selected button19string strBtn = (rdoClickSearch.Checked ? "btnG" : "btnI");
20 HTMLInputElement btnSearch = (HTMLInputElement) myDoc.all.item(strBtn, 0);
21 btnSearch.click();
22 }
23catch (Exception ex)
24 {
25 MessageBox.Show("Error:" + ex.Message);
26 }
27finally28 {
29//Release memory30 myDoc = null;
31 }
3233//Clear "searching" flag34 mbSearching = false;
35}Some example screenshots
Yeah yeah yeah...I know...I need to get this done!
I finally published this article...
see:
http://www.brianpautsch.com/ShowItem48.aspx(I created a new entry so that RSS subscribers would see the new article.)
Looking for a simple class to encrypt/decrypt strings such as passwords? Use this one...it's about as easy as it gets. And be sure to add a plain text phrase in your web.config (key="EncryptionKey") or hard code it in the app to make it impossible to find.
1using System;
2using System.Configuration;
3using System.Security.Cryptography;
4using System.Text;
5
6namespace com.BrianPautsch
7{
8 public class Cryptology
9 {
10 #region Encrypt
11 public static string Encrypt(string strPlainText)
12 {
13 TripleDESCryptoServiceProvider objDES =
new TripleDESCryptoServiceProvider();
14 MD5CryptoServiceProvider objMD5 =
new MD5CryptoServiceProvider();
15 string strKey =
ConfigurationSettings.AppSettings["EncryptionKey"].ToString();
16 objDES.Key = objMD5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(strKey));
17 objDES.Mode = CipherMode.ECB;
18 ICryptoTransform objDESEncrypt = objDES.CreateEncryptor();
19 byte[] arrBuffer = ASCIIEncoding.ASCII.GetBytes(strPlainText);
20 return Convert.ToBase64String(objDESEncrypt.TransformFinalBlock(
arrBuffer, 0, arrBuffer.Length));
21 }
22 #endregion
23 #region Decrypt
24 public static string Decrypt(string strBase64Text)
25 {
26 TripleDESCryptoServiceProvider objDES =
new TripleDESCryptoServiceProvider();
27 MD5CryptoServiceProvider objMD5 =
new MD5CryptoServiceProvider();
28 string strKey =
ConfigurationSettings.AppSettings["EncryptionKey"].ToString();
29 objDES.Key = objMD5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(strKey));
30 objDES.Mode = CipherMode.ECB;
31 ICryptoTransform objDESEncrypt = objDES.CreateDecryptor();
32 byte[] arrBuffer = Convert.FromBase64String(strBase64Text);
33 return ASCIIEncoding.ASCII.GetString(objDESEncrypt.TransformFinalBlock(
arrBuffer, 0, arrBuffer.Length));
34 }
35 #endregion
36 }
37}
In a recent project I was working on, I needed to hide DataGrid columns in a table where the columns are dynamically generated. I thought I might be able to do it after binding to the DataGrid or during the DataBinding event, but no luck. It turns out you have to hide the cells in each row (including the header and footer) during the DataGrid's ItemDataBound event. By the way, in my example, I have an 'Edit' column in the first columns always...so remember that when you implement this solution.
1//Private constants/variables
2private const int mintNumColsToShow = 4;
3private int mintColCt = 0;
4
5//In some method...get data and bind to DataGrid
6objDataSvc = new DataSvc();
7DataTable objDT = null;
8objDT = objDataSvc.GetData();
9mintColCt = objDT.Columns.Count;
10dgResults.DataSource = objDT;
11dgResults.DataBind();
12
13//DataGrid's ItemDataBound event
14private void dgResults_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
15{
16 //Only show first n columns (including 'Edit')
17 if (mintColCt > mintNumColsToShow)
18 {
19 for (int intCt = mintNumColsToShow + 1; intCt <= mintColCt; intCt++)
20 {
21 e.Item.Cells[intCt].Visible = false;
22 }
23 }
24}
There are a lot of industries that need to show their data results based on proximity to a specified zip code. Some include car dealers, real estate agencies, job listers, etc. A few of my customers have asked for this capability and instead of buying a boxed solution and subscribing to a zip code list, I decided to build it myself, maintain it myself and bill each customer for usage. Actually, it's not that difficult. Once you figure out some of the radius and distance calculations and where to get current zip code data from, it's as simple as creating a few SQL Server User Defined Functions and a service to periodcially update your database.
Download codeSample House Search Application
DatabaseAt a minimum, you'll need a database with zip codes and their latitude and longitude coordinates. My example includes a database with all of the zip codes for Illinois along with the City, State, Latitude and Longitude.
FunctionsRadiusFunc : Accepts @ZipCode (zip code) and @Miles (distance from zip code in miles) and returns the Maximum Latitudes and Longitudes for the radius of the zip code.
DistanceFunc : Accepts Latitudes and Longitudes for two zip codes and returns their distance Miles.
Stored ProceduresspHouses_GetNearZipcode: Accepts @ZipCode (zip code) and @Miles (distance from zip code in miles) and returns the houses listed in the radius.
Default.aspxDefault.aspx: Simple example where the user enters in a zip code, selects a distance from zip code radius and clicks enter to get results. Results are then bound to a repeater.
Default.aspx.csDefault.aspx.cs : Nothing special about this code...the real logic for zip code searching is in the database!