Dec 10 2009

Loop through PagedDataSource without binding

I hate binding to data list because they add in a ton of extra code that is a bitch to clean up. I like handling and manipulating the raw data and outputting it exactly as I like. So, my dilemma with PagedDataSources is that you need to bind them to a data list to get the data (to the best of my knowledge).

Here’s how I got around it:

1. Fill up your PagedDataSource with data
2. Bind it to a data list (ex: theDataList)
3. In the Data List on the aspx page, pump all the data back to the .vb page into a function.
4. Create a literal on the .aspx page (ex: litOutput)
5. In the function that is used to marshal the data, append all the output to the literal on the aspx page (litOutput.Append(strOutput))
6. After the command to connect the PagedDataSourse to the data list (theDataList.DataSource = objDps / theDataList.DataBind()), make it not visible:
theDataList.Visible = False

BAM! You now have all your data in the literal and the data list with all it’s crappy ass <br/>’s and <span>’s are no where to be found =)

.: Adam


Jan 12 2009

ASP.NET File.Delete with a Wildcard

I wanted to delete all files within a directory that have a certain string in it, but File.Delete doesn’t allow wildcards. So, I wrote up this little tid-bit that cleared up that problem =)

Dim files() As String = Directory.GetFiles(Server.MapPath(”/Directory/”), “*” strMatchingString “.*”)
Dim strFile As String = “”

For Each strFile In files
File.Delete(strFile)
Next

Cheers!

.: Adam


Aug 3 2008

Simple ASP.NET (VB) Email Validator

I needed one, and after scouring the net, I found this little bad boy:

Dim Expression As New System.Text.RegularExpressions.Regex("\S+@\S+\.\S+")
If Expression.IsMatch(strEmail) Then
	' Email is valid
Else
	' Email is not valid
End If

Volia!

.: Adam


Aug 1 2008

Fucking Nulls…. i swear! (Literally =)

Man, .net pisses me off when it comes to null values. I like the fact that I can test for them, but to have to account for them? lame.

Probably due to me coding at 5 in the morning than stoopid .net, but I implemented a new regex in a very commonly used function, and everything started throwing, "can’t parse null" errors. I was also working on a couple other areas of the site, so I wasn’t sure exactly what I did that broked everything. I wound up just saying, "fuck it" and going to bed.

First thing this morning, I throw a "If Not strValue Is Nothing Then" wrapper around my RegEx, and bam! All better.

That phrase doesn’t even make sense. Use of double-negatives in a stoopid order is stoopid. =)

If Not strValue Is Nothing Then
	strValue = System.Text.RegularExpressions.Regex.Replace(strValue, "RedExHere", String.Empty, RegexOptions.IgnoreCase)
End If

.: Adam


Jun 13 2008

Send Mail Function for VB.NET (ASP.NET)

For some reason, I wasn’t able to figure this simple little process out on my own with the help of Google. Everything I found was way over complicated. This is short, sweet, and works =)

 Public Shared Sub SendMail(ByVal fromaddress As String, ByVal toaddress As String, ByVal body As String, ByVal subject As String)
    Dim mailServer As String = "smtp.mailserver.com"
    Dim message As MailMessage = New MailMessage(fromaddress, toaddress, subject, body)
    Dim mailClient As SmtpClient = New SmtpClient

    message.IsBodyHtml = True
    mailClient.Host = mailServer
    mailClient.Send(message)
    message.Dispose()
End Sub

BAM! Thanks Joe!

.: Adam


May 12 2008

Trick: Prevent Image Caching of Dynamic Images

For the longest time I’ve been struggling with an issue of browsers caching dynamic images that have the same name. Here’s my use case:

A user has a profile photo on their profile photo that’s called MyProfilePhoto.jpg. The user uploads a new image for their profile photo. When they load their profile page, the browser sees the request for MyProfilePhoto.jpg and just pulls from cache. But in reality, the image has changed. This causes the user to re-upload the photo and get super frustrated. The solution seems to be stupidly simple: Append a random querystring value.

So my new image source value is something like: MyProfilePhoto.jpg?r=1234

This causes the image to be reloaded every time the page is loaded. Another way that I’ve thought about attacking this and making it a little more controlled is to store a random value to the database when a new image is uploaded and just append that value to the querysting. This will ensure that the new image is always loaded, and that it will pull from cache until the image changes.

I’m just lazy, and don’t want to add more fields into my user tables =)

You can see this in effect on my profile page on bodymod.org. Just view the source of my profile image.

.: Adam


Apr 10 2008

Subtracting Dates in .NET

This may be simple for a lot of .NET developers out there, but for a person like me (coming from classic asp), this was a little tricky.

Problem, I need to know the # of days between 2 dates.

In ASP, I used to use the DateDiff function, and it worked (most of the time). But it’s pretty convoluted and a pain to remember. From just winging it, I’ve come up with this for .NET:

Dim arrThisSplitDate As Array
Dim strThisDate As String = ""
Dim intDaysDifference As Integer

arrThisSplitDate = Split(CDate(strThisPremiumEndDate), "/")

strThisDate = DateSerial(arrThisSplitDate(2), arrThisSplitDate(1), arrThisSplitDate(0))

iintDaysDifference = DateTime.Today.Date.Subtract(strThisDate).Days

This will return you an integer value for the difference in days.

.word.


Mar 24 2008

Want to enable .NET caching from a prompt?

Here’s the command to issue at a command prompt to enable database caching for a MS SQL 2005 server:

aspnet_regsql -S [servername] -U [username] -d [databasename] -ed -et -t [tablename]

Here’s some variables to throw into your Page Directives:

<%@ OutputCache Duration=”20″ VaryByParam=”none” VaryByCustom=”browser” SqlDependency=”CommandNotification” %>


Mar 11 2008

.NET format Time

Here’s a great article on formatting Time in asp.net

check it!

From Site:

If you have read any DateTime format string documentation, you will know that the .NET platform has two different styles of DateTime format string:

2-a. Standard Format String

This is basically built in short hand for custom format string. You pass in the one character string to denote which custom format you want.

i.e.
now.ToString(”d”); // “09/27/2006″
now.ToString(”D”); // “Tuesday, 27 September 2006″
now.ToString(”G”); // “09/27/2006 14:15:39″

All of the format string syntax I discussed in “.NET Format String 101″ is invalid here. Also, if you call now.ToString(), it is basically calling now.ToString(”G”);

I have included my own table mapping Standard Format String to Custom Format string in part 2-c below. MSDN actually has a pretty good table that describe what each item does, and DateTime.ToString() has a pretty good code example that shows what each format string specifier do. Also if you just want samples, MSDN has a “Standard Date Time Format String Output example” here. Because documentation is so good. I won’t go into this too much. :)
2-b. Custom Format String

Custom format string gives you the flexibility to build your own formatting. When using a single character format string specifier, you will need to prepend it with a “%”, otherwise it will be interpreted as a Standard Format String. Here are the basics for building your own string:

DateTime now = new DateTime(2006, 9, 07, 15, 06, 01, 08, DateTimeKind.Local);

now.ToString(); //”09/27/2006 15:06:01″

Year

now.ToString(”%y”); //”6″

now.ToString(”yy”); //”06″

now.ToString(”yyy”); //”2006″

now.ToString(”yyyy”); //”2006″

Month

now.ToString(”%M”); //”9″

now.ToString(”MM”); //”09″

now.ToString(”MMM”); //”Sep”

now.ToString(”MMMM”); //”September”

Day

now.ToString(”%d”); //”7″

now.ToString(”dd”); //”07″

now.ToString(”ddd”); //”Thu”

now.ToString(”dddd”); //”Thursday”

Hour

now.ToString(”%h”); //”3″

now.ToString(”hh”); //”03″

now.ToString(”hhh”); //”03″

now.ToString(”hhhh”); //”03″

now.ToString(”%H”); //”15″

now.ToString(”HH”); //”15″

now.ToString(”HHH”); //”15″

now.ToString(”HHHH”); //”15″

Minutes

now.ToString(”%m”); //”3″

now.ToString(”mm”); //”03″

now.ToString(”mmm”); //”03″

now.ToString(”mmmm”); //”03″

Seconds

now.ToString(”%s”); //”1″

now.ToString(”ss”); //”01″

now.ToString(”sss”); //”01″

now.ToString(”ssss”); //”01″

Milliseconds

now.ToString(”%f”); //”0″

now.ToString(”ff”); //”00″

now.ToString(”fff”); //”008″

now.ToString(”ffff”); //”0080″

now.ToString(”%F”); //”"

now.ToString(”FF”); //”"

now.ToString(”FFF”); //”008″

now.ToString(”FFFF”); //”008″

Kind

now.ToString(”%K”); //”-07:00″

now.ToString(”KK”); //”-07:00-07:00″

now.ToString(”KKK”); //”-07:00-07:00-07:00″

now.ToString(”KKKK”); //”-07:00-07:00-07:00-07:00″

// Note: The multiple K were just read as multiple instances of the

// single K

DateTime unspecified = new DateTime(now.Ticks, DateTimeKind.Unspecified);

unspecified.ToString(”%K”); //”"

DateTime utc = new DateTime(now.Ticks, DateTimeKind.Utc);

utc.ToString(”%K”); //”Z”

TimeZone

now.ToString(”%z”); //”-7″

now.ToString(”zz”); //”-07″

now.ToString(”zzz”); //”-07:00″

now.ToString(”zzzz”); //”-07:00″

Other

now.ToString(”%g”); //”A.D.”

now.ToString(”gg”); //”A.D.”

now.ToString(”ggg”); //”A.D.”

now.ToString(”gggg”); //”A.D.”

now.ToString(”%t”); //”P”

now.ToString(”tt”); //”PM”

now.ToString(”ttt”); //”PM”

now.ToString(”tttt”); //”PM”

2-c. Additional Resources

Now that you understand what Standard and Custom format strings are, here is a table of Standard Format String to Custom Format String mapping:

Year Month Day Patterns:
d = “MM/dd/yyyy”
D = “dddd, dd MMMM yyyy”
M or m = “MMMM dd”
Y or y = “yyyy MMMM”

Time Patterns:
t = “HH:mm”
T = “HH:mm:ss”

Year Month Day and Time without Time Zones:
f = “dddd, dd MMMM yyyy HH:mm”
F = “dddd, dd MMMM yyyy HH:mm:ss”
g = “MM/dd/yyyy HH:mm”
G = “MM/dd/yyyy HH:mm:ss”

Year Month Day and Time with Time Zones:
o = “yyyy’-'MM’-'dd’T'HH’:'mm’:’ss.fffffffK”
R or r = “ddd, dd MMM yyyy HH’:'mm’:’ss ‘GMT’”
s = “yyyy’-'MM’-'dd’T'HH’:'mm’:’ss”
u = “yyyy’-'MM’-'dd HH’:'mm’:’ss’Z'”
U = “dddd, dd MMMM yyyy HH:mm:ss”

All other single characters will throw an exception.


Jan 9 2008

IIS 6 Page Compression

While looking into ASP.NET caching techniques, I ran across this little gem on IIS page compression using gzip.

IIS 6 has a built-in capability of compressing pages and / or content through gzip before sending it to the requesting client to cut down on bandwidth usage and overall network performance.

It’s also a smart process. First, there’s two types of compression that it will do. If it’s a static file (no dynamic content), it’ll zip up the file and store it in a temp space to send every time the page is requested. This way the CPU overhead is very minimal because it only has to compress the page once. The other is for dynamic pages. For these, it’ll compress the page as requested on the fly. This has a higher CPU usage, but worth it overall.

On top of that, it also checks the users browser for gzip compatibility before it even compresses the file. If it’s compatible (IE, Firefox, etc), it’ll send the compressed version. If the browser can’t handle compressed content, it’ll send the non-compressed version. Rock!

The downer is that it’s not very easy to setup (kinda). Meaning that there’s no checkbox anywhere to enable this and configure it. The guy over at AngryHacker.com (article above), wrote a great batch file that enables it and sets it up in one quick swoop. Make sure to save the BAT file in C:\Inetpub\AdminScripts

IISreset.exe /stop 

cscript adsutil.vbs set w3svc/filters/compression/parameters/HcDoDynamicCompression true
cscript adsutil.vbs set w3svc/filters/compression/parameters/HcDoStaticCompression true
cscript.exe adsutil.vbs set W3Svc/Filters/Compression/GZIP/HcFileExtensions "htm" "html" "txt" "ppt" "xls" "xml" "pdf" "xslt" "doc" "xsl" "htc" "js" "css"
cscript.exe adsutil.vbs set W3Svc/Filters/Compression/DEFLATE/HcFileExtensions "htm" "html" "txt" "ppt" "xls" "xml" "pdf" "xslt" "doc" "xsl" "htc" "js" "css"
cscript.exe adsutil.vbs set W3Svc/Filters/Compression/GZIP/HcScriptFileExtensions "asp" "dll" "exe" "aspx" "asmx" "ashx"
cscript.exe adsutil.vbs set W3Svc/Filters/Compression/DEFLATE/HcScriptFileExtensions "asp" "dll" "exe" "aspx" "asmx"
cscript.exe adsutil.vbs set W3Svc/Filters/Compression/GZIP/HcDynamicCompressionLevel "9"
cscript.exe adsutil.vbs set W3Svc/Filters/Compression/DEFLATE/HcDynamicCompressionLevel "9" 

IISreset.exe /restart

If you’re not familiar with IIS, this script will stop your web server while it implements this and then start it back up once it’s done. Also, the default compression level is 0 (0-10), and this script sets it to 9. I have mine set at 9 and didn’t really notice much difference in CPU utilization.

Good stuff eh?