tips

There are 47 entries for the tag tips

Better Git with PowerShell

I’m usually not one to resort to puns in my blog titles, but I couldn’t resist. Git it? Git it? Sorry. Ever since we introduced PowerShell into NuGet, I’ve become a big fan. I think it’s great, yet I’ve heard from so many other developers that they have no time to try it out. That it’s “on their list” and they really want to learn it, but they just don’t have the time. But here’s the dirty little secret about PowerShell. This might get me banned from the PowerShell junkie secret meet-ups (complete with secret handshake) for leaking...

Presentation Tips Learned From My (Many) Mistakes

One aspect of my job that I love is being able to go in front of other developers, my peers, and give presentations on the technologies that my team and I build. I’m very fortunate to be able to do so, especially given the intense stage fright I used to have. But over time, through giving multiple presentations, the stage fright has subsided to mere abject horror levels. Even so, I’m still nowhere near the numbers of much more polished and experienced speakers such as my cohort, Scott Hanselman. Always looking for the silver lining, I’ve...

Copying Files Over Remote Desktop

Here’s a handy tip I just recently learned from the new intern on our team (see, you can learn something from anyone on any given day). I’ve long known you could access your local drives from a remote machine. For example, start up a remote desktop dialog. Then expand the dialog by clicking on Options, then check the Local Resources tab. Make sure Clipboard is checked, and then hit the More… button. Now you can select a local disk to be shared with the remote machine. For example, in...

VS2008 Web Server Here Shell Extension

UPDATE: Updated the registry settings per James Curran’s comment. Thanks James! One of the most useful registry hacks I use on a regular basis is one Robert McLaws wrote, the “ASP.NET 2.0 Web Server Here” Shell Extension. This shell extension adds a right click menu on any folder that will start WebDev.WebServer.exe (aka Cassini) pointing to that directory. I recently had to repave my work machine and I couldn’t find the .reg file I created that would recreate this shell extension. When I brought up Robert’s page, I noticed that the settings he has are out...

Visual Studio Smart Tag Expansion Tip

I used to find the smart tag really annoying in Visual Studio because it is such a small target to hit with the mouse. Silly me, trying to expand a smart tag with a mouse.   When you highlight the tag with your mouse, it tells you that the keyboard combination of ALT + SHIFT + F10 will expand the menu. What it doesn’t tell you is that there’s a two key combination that will also expand it. I learned this one from Karen Liu of the C# IDE team who also happens to have a blog...

Blocking Direct Access To Views in ASP.NET MVC

UPDATE: I improved this based on some feedback in my comments. With ASP.NET MVC it is possible for someone to try and navigate directly to a .aspx view. In general, this only leaves them with an ugly error message as Views typically need ViewData in order to work. However, one approach that I think will easily work is to create a Web.config file in the root of your Views directory that contains the following. We need to do more testing on our side to make sure there's no pathological case in doing this, but so far in my personal testing, it seems to...

The Most Useful .NET Utility Classes Developers Tend To Reinvent Rather Than Reuse

System.IO.Path How often do you see code like this to create a file path? public string GetFullPath(string fileName) { string folder = ConfigurationManager.AppSettings["somefolder"]; return folder + fileName; } Code like this drives me crazy because it is so prone to error. For example, when you set the folder setting, you have to remember to make sure it ends with a slash. Having too many things to remember makes this setup fragile. Sure, you write some code to ensure that the folder has an ending slash, but I’d rather let someone write that code. For example, Microsoft. The .NET framework is definitely huge so it can...

Databinding Tips: Nesting Eval Statements

Maybe this is obvious, but it wasn’t obvious to me. I’m binding some data in a repeater that has the following output based on two numeric columns in my database. It doesn’t matter why or what the data represents. It’s just two pieces of data with some formatting: 42, (123) Basically these are two measurements. Initially, I would databind this like so: <%# Eval("First") %>, (<%# Eval("Second") %>) The problem with this is that if the first field is null, I’m left with this output. , (123) Ok, easy enough to fix using a format string: <%# Eval("First", "{0}, ") %>(<%# Eval("Second") %>) But now I’ve learned that...

Thread Safety Via Read Only Collections

UPDATE: Made some corrections to the discussion of ReadOnlyCollection’s interface implementations near the bottom. Thanks to Thomas Freudenberg and Damien Guard for pointing out the discrepancy. In a recent post I warned against needlessly using double check locking for static members such as a Singleton. By using a static initializer, the creation of your Singleton member is thread safe. However the story does not end there. One common scenario I often run into is having what is effectively a Singleton collection. For example, suppose you want to expose a collection of all fifty states. This should never change, so you might...

Gain Control Of Your Control State

Some people think the ViewState is the spawn of the devil. Not one to be afraid of being in bed with the devil, I feel a tad bit less negative towards it, as it can be very useful. Still, it has its share of disadvantages. It sure can get bloated. Not only that, but disabling ViewState can wreack havock with the functionality of many controls. This is why ASP.NET 2.0 introduces the control state. The basic idea is that there is some state that should be considered the data for the control, while other state is necessary for the control to function. For example,...

Dashes Vs Underscores In URLs

I used to think the choice of using dashes vs underscores to separate words in an URL was simply a matter of personal preference. Nothing more than a religious choice. Personally, I preferred underscores because I felt dashes intruded upon the words while underscores stayed at the bottom out of the way. So much so I had originally made that the default URL scheme in Subtext for friendly URLs and was using that myself. It wasn’t till recently that I learned this debate has already been resolved. Years ago. I wouldn’t say resolved really. Just that, there appears to be a really good reason to choose...

Quick CSS Optimization Tip

When you see the following in your CSS div { margin-top: 10px; margin-right: 20px; margin-bottom: 10px; margin-left: 20px; } It makes sense to convert it to this. div { margin: 10px 20px; } It’s cleaner and takes up less space. There are a lot of ways you can optimize your CSS in this way. I'm not talking about compression, but optimization. Today, The Daily Blog Tips site linked to a website called CleanCSS that can perform many of these optimizations for you. For example, feed it the above CSS and it will make that conversion. Very nice! Technorati tags: CSS, Tips

Improve Your Blog's Reach With These 20 Essential Web Utilities

You’ve spent hours setting up your blog on your favorite blog platform just right. Good for you! So how do you maintain your blog so that it remains at the top of its game? It turns out, there are a large number of free web utilities useful for improving your blog’s effectiveness outside of your blog engine. Tools 4 Argentina - Some Rights Reserved Everytime I come across one of these useful utilities, I bookmark it to my Blog Utilities folder. This folder is my blogger utility belt, full of tools to meet every need when composing blog posts or optimizing my...

Custom Configuration Sections in 3 Easy Steps

Are you tired of seeing your configuration settings as an endless list of key value pairs? <add key="key0" value="value0" /> <add key="key1" value="value1" /> <add key="key2" value="value2" /> ... Would you rather see something more like this? <MySetting fileName="c:\temp" password="pencil" someOtherSetting="value" /> Join the club. Not only is the first approach prone to typos (AppSettings["tire"] or AppSettings["tier] anyone?), too many of these things all bunched together can cause your eyes to glaze over. It is a lot easier to manage when settings are grouped in logical bunches. A while back Craig Andera solved this problem with the Last Configuration Section Handler he’d ever need. This basically...

Start++ Is All That And Then Some

Update: I have an even better startlet for stopping and starting services in my comments. If you’re running Vista, run, don’t walk, and go download and install Start++ (thanks to Omar Shahine for turning me on to this). Make it the first thing you do. Many thanks to Brandon Paddock who developed this nice little tool. He describes the tool in this post. I have a message for Start++ from the Start menu. “You complete me!”. Ok, terribly corny jokes aside, it’s the little things that save me lots of time in the long run. For example, starting and stopping SQL server is kind...

ASP.NET Tip - Use The Label Control Correctly

Scott Watermasysk has a great set of Quick Tips for ASP.NET on his blog. And this is only part one! I’m Looking forward to seeing the subsequent posts of this series. However, I disagree slightly with his tip to Never use the ASP.NET Label control. I would rephrase it to: Never use the ASP.NET Label control when a Literal would do. The problem is not the Label control. The problem is treating the Label control as if it was merely a Literal control. The Label control has a specific usage, to be a label for a form input. For example, check out this screenshot of...

[Tip Jar] Unit Test Events With Anonymous Delegates

Here we are already looking ahead to learn about the language features of C# 3.0 and I am still finding new ways to make my code better with good “old fashioned” C# 2.0. Like many people, I tend to fall into certain habits of writing code. For example, today I was writing a unit test to test the source of a particular event. I wanted to make sure that the event is raised and that the event arguments were set properly. Here’s the test I started off with (some details changed for brevity) which reflects how I would do this in the old days. private bool eventRaised...

Using WebServer.WebDev For Unit Tests

Last night a unit test saved my life (with apologies). Ok, maybe not my life, but the act of writing some unit tests did save me the embarrasment of an obscure bug which was sure to hit when I least expected it.  It is cases like this that made me into such a big fan of writing automated unit tests. Not too long ago I wrote a C# Akismet API for Subtext. In writing the code, I followed design principles focused on making the API as testable as possible. For example, I applied Inversion of Control (IOC) by having the AkismetClient constructor take...

Tip Jar: Concatenating A Delimited String

Update: I also wrote a more generic version using anonymous delegates for .NET 2.0 as a followup to this post. Here’s one for the tip jar. Every now and then I find myself concatening a bunch of values together to create a delimited string.  In fact, I find myself in that very position on a current project. In my case, I am looping through a collection of objects concatenating together three separate strings, each for a different property of the object (long story). Usually when building such a string, I will append the delimiter to the end of the string I am...

Register Custom Controls In Web.config

This one is probably old news to many of you, but I just recently ran across it. Every time I want to add a new control to a new page, I get annoyed because I have to remember that annoying syntax for registering a control. Let’s see...how does it go again? Do I have to add a TagName attribute? No, that’s for user controls. Hmmm, forget it, I’ll just dynamically add it! Well in the interest of reducing future angst, here are two examples of the syntax, one for a custom control and one for a user...

Tip For Managing Remote VMWare Server

Quick tip for you if you need to remotely connect to a server with VMWare Server installed in order to manage the virtual server.  VMWare Server Console doesn’t work correctly if you Remote Desktop or Terminal in. You have to physically be at the machine or Remote Desktop into the Console session. The symptoms I ran into was that I could not open a virtual machine, and when I tried to create a new one, I got an “Invalid Handle” error. Technorati Tags: Tips

Tivo For Your Registry

Ever prolific Jon Galloway has released another tool on our tools site.  When we started the tools site, I talked some trash to spur some friendly competition between the two of us.  Let’s just say Jon is kicking my arse so hard my relatives in Korea can’t sit down. His latest RegmonToRegfile tool works with yet another SysInternals tool, Regmon. Winternals (maker of Sysinternal) released many fantastic tools for managing and spelunking your system. So great, in fact, that Robb feels he owes them his child in gratitude. Kudos to Microsoft for snatching up Mark Russinovich and Winternals Software. Regmon is essentially a Tivo...

Power Tools For Disk Defragmenting

Disk Defragmenter For the most part, the Disk Defragmenter application (located at %SystemRoot%\system32\dfrg.msc) that comes with Windows XP does a decent enough job of defragmenting a hard drive for most users. But if you’re a developer, you are not like most users, often dealing with very large files and installing and uninstalling applications like there’s no tomorrow.  For you, there are a couple of other free utilities you should have in your utility belt. Recently I noticed my hard drive grinding a lot.  After defragmenting my drive, I clicked on the View Report button this time (I normally never do this out of hurriedness). This brings...

Change The Display Of A Type In The Debugger

Keyvan Nayyeri has a great tip for how to control the display of a type in the various debugger windows using a DebuggerTypeProxy attribute.  His post includes screenshots with this in use. This is an attribute you can apply to a class, assembly, or struct to specify another class to examine within a debugger window.  You still get access to the raw view of the original type, just in case some other developer plays a practical joke on you by specifying a DebuggerTypeProxy that displays the value of every field as being 42. Tags: .NET, C#, Debugging, Visual Studio.NET, Tips

Optical Character Recognition On The Cheap

Jon Galloway combines Timesnapper (Tivo for geeks) with the OCR abilities of Microsoft Office Document Imaging (OCR you didn’t realize you owned) and never forgets anything ever again. Tags: OCR, Tips

Another Marginally Useful Tool - BatchConcat

UPDATE: In one comment, szeryf points out something I didn’t know and invalidates the need for the tool I wrote. This is why I post this stuff, so someone can tell me about a better way! Thanks szeryf! I’ve updated the post to point out the better technique. Based on my recent spate of posts, you can probably guess that I am working on improving a particular build process.  In this situation, I have a pre-build step to concatenate a bunch of files into a single file.  I tried to do this with a simple command like so: FOR %%A in (*.sql)...

Fun Iterating PagedCollections With Generics and Iterators

Oh boy are you in for a roller coaster ride now! Let me start with a question, How do you iterate through a large collection of data without loading the entire collection into memory? The following scenario probably sounds quite familiar to you. You have a lot of data to present to the user. Rather than slapping all of the data onto a page, you display one page of data at a time. One technique for this approach is to define an interface for paged collections like so... /// <summary> /// Base interface for paged collections. /// </summary> public interface IPagedCollection { ///...

How To Get The Calling Method And Type

Here are a couple of useful methods for getting information about the caller of a method. The first returns the calling method of the current method. The second returns the type of the caller. Both of these methods require declaring the System.Diagnostics namespace. private static MethodBase GetCallingMethod() { return new StackFrame(2, false).GetMethod(); } private static Type GetCallingType() { return new StackFrame(2, false).GetMethod().DeclaringType; } Pop Quiz! Why didn’t I apply the principle of code re-use and implement the second method like so? public static Type GetCallingType() { return GetCallingMethod().DeclaringType; } A virtual cigar and the admiration of your peers to the first person to answer...

Bulletproof Sql Change Scripts Using INFORMATION_SCHEMA Views

Working as a team against a common database schema can be a real challenge. Some teams prefer to have their local code connect to a centralized database, but this approach can create many headaches. If I make a schema change to a shared database, but am not ready to check in my code, that can break the site for another developer. For a project like Subtext, it is just not feasible to have a central database. Instead, I prefer to work on a local copy of the database and propagate changes via versioned change scripts. That way, when I...

[SQL] Create a Job to Backup and FTP Your Database

In two earlier posts I presented a couple of SQL stored procedures that I promised to tie together. The first procedure generates a random time of day and the second can be used to FTP a file from within SQL Server. Well in this post I put these two together to create a stored procedure for creating a database job that will take a nightly backup of a database and FTP it to another location. I hope this isn’t terribly anti-climactic for you. This script is perfect for a quick and dirty backup plan for a database. If you are...

[SQL] Stored Procedure To FTP Files From SQL Server

This is another useful Sql Server Stored Procedure I found on the net written by Nigel Rivett. The procedure uses the xp_cmdshell extended stored procedure to shell out an FTP command. You can use this procedure to ftp a file from one place to another. Of course, you will need to make sure that your command runs in the proper security context. I made some very slight modifications in my own version of this procedure. I changed some of the parameters to be of type nvarchar instead of varchar for my international friends. I also changed the name to suit...

[SQL] Stored ProcedureTo Generate Random Time of Day

Here is a function that will generate a random time of day. Later I will show why I am posting this particular query and how I am using it. It comes in useful when trying create random scheduled jobs in SQL Server. I made use of a technique for generating random dates via Jon Galloway. Parameter DataType ...

Database Maintenance Of Your Blog

Lately I have been spending a little bit of time performing maintenance tasks on my blog’s SQL Server. I noticed that OdeToCode’s Scott Allen was in the same mood. In looking to free up some database space, he took the somewhat drastic step of deleting all referrals and urls before a certain date. Since he doesn’t care about this data, it isn’t really all that drastic. But it makes a data packrat like me shudder. I wanted to free up some space as well so I created an approach that frees up a lot of space, but keeps the data...

Dynamic WHERE and ORDER BY Without Dynamic SQL

My friend Jeremy (no blog) pointed me to these two useful articles on how to perform dynamic WHERE clauses and ORDER BY clauses without using dynamic SQL. These were written long ago, but I had never thought to use COALESCE in this way. Very cool! I will post them here so I can find them later. Implementing a Dynamic WHERE Clause Dynamic ORDER BY UPDATE: This technique may not be as performant as hoped for. Marty in the comments noted that he saw table scans in using COALESCE in this way. Jeremy...

Connecting to Terminal Services When All Active Sessions are Used

UPDATE: If you are using Windows Server 2008, the switch is /admin not /console. See this post for details. We use Remote Desktop (Terminal Services) to remotely manage a Windows 2003 server that is not part of our domain. Recently we ran into the two user limit for remote desktop connections, which barred anyone from connecting. Jon discovered a neat little trick that got us in. He ran the following command from the command line: mstsc -console It turns out that mstsc.exe is the remote desktop connection application. The -console flag specifies that we want to connect to the console session of...

Sql Query Analyzer Template Parameters

I’m not sure if this is common knowledge, but you can place template parameters in your SQL scripts and evaluate them within query analyzer. I think I learned this one a long time ago from a former fantastic SysAdmin, turned DBA, turned Developer, Tyler. Here’s an example of a short script that makes use of a template variable. SELECT * FROM <tableName, varchar(32), 'MyTable'> Paste that into SQL Query Analyzer and hit CTRL+SHIFT+M. A dialog to replace the template parameters will pop up like so Just fill in the values and hit return and you’re ready to run the...

Threading Tips: Never Lock a Value Type. Never Lock "This".

UPDATE: As a commenter pointed out, the original code example did not properly demonstrate the problem with locking on the this keyword within a normal method. I have corrected this example and wrote a better example that demonstrates that this problem still exists even in a “normal” method. Take a look at this code: private bool isDisposed = false; //... code... ~MyClass() { lock(isDisposed) { if(!isDisposed) { //Do Stuff... ...

Beware of @@Identity Theft in SQL Server

In T-SQL, you can use the @@IDENTITY keyword to obtain the value of the identity column when you insert a new record. For example, the following query inserts a record into an imaginary table and returns a result set containing the ID of the inserted column. INSERT INTO SomeTable     SELECT Value1, Value2     SELECT @@IDENTITY -- LAST INSERTED IDENTITY VALUE There's the potential for a subtle bug here. Suppose later on, a coworker realizes that any time a record is inserted into [SomeTable] a record should also be inserted into the table [SomeTableAudit]. The simplest solution would be to add a trigger...

SQL TIP: Prefixing Stored Procedure With "sp_" Gives Your SP a Bad Name

Found this interesting article via Hassan Voyeau that details the performance penalty when naming your stored procedure with an sp_ prefix in a database other than the master database. Personally, I hate adding extraneous and unecessary prefixes and suffixes to names. Sometimes they’re useful and necessary, like when programming in Fortran 77. But I hate naming tables with a tbl prefix and stored procs with an sp prefix (I’m forced to at my current position). Sql Enterprise Manager does a nice job of separating tables from stored procedures when they are being displayed. I’m never going to get the fact confused...

SQL TIP: Connection To SQL via Windows Authentication over VPN

I’m posting this great tip so I can find it later and for your benefit. [Via Julia Lerman Blog - Don’t Be Iffy...] Technorati Tags: SQL, Tips

Using a Regular Expression to Match HTML

UPDATE: There was a big mistake in the above expression. Unfortunately .TEXT (trying to be helpful) munged the code I posted and uppercased some characters. I’m using FireFox to post so that I don’t get the helpful text editor. Also, the above didn’t take into account multi-line html tags. That’s been corrected now. You’ll have to use the SingleLine RegexOption for it to work. I just love regular expressions. I mean look at the sample below. </?\w+((\s+\w+(\s*=\s*(?:".*?"|'.*?'|[^'">\s]+))?)+\s*|\s*)/?> What’s not to like? Ok I admit, I was a bit intimidated by regular expressions when I first started off as a developer. All I...

SQL TIP: Selecting Random Selection Of Rows From A Database Table

I found a nice tip for selecting random rows from within a SQL Server 2000 database. Well actually, pseudorandom. Since my undergraduate thesis was on the topic of pseudorandom number generation, I might as well be precise. For some reason, my non-geek friends find it awfully funny when I mention pseudorandom numbers. I digress. In order to select 10 records from some table at random, try this: SELECT TOP 10 * FROM someTable ORDER By NEWID()   Now for my homework, I should find out just how random this is. There's a whole slew of statistical tests I can run to...

Microsoft Sql Server 2000 Best Practices Analyzer 1.0

Microsoft just released the the Microsoft Sql Server 2000 Best Practices Analyzer 1.0. It's basically FxCop for SQL Server. Very cool. Technorati Tags: SQL, Tips

SQL TIP: Auto Increment in an UPDATE statement.

I needed to create a temp table in SQL with a column that contained an incrementing integer, without making that column an identity. For example, suppose I want to select record from a table of users, but add a column that contains an incrementing counter. The data in the table should look like so: counter UserID ...

TIP: More on Exceptions and Serialization

I just left to do some thinking where I get my best thinking done. While washing my hands, I realized I should mention a few issues with my previous recommendation. Adding the SerializableAttribute to a class indicates to .NET that the class may be automatically serialized via reflection. When the class is being serialized, .NET uses reflection to obtain the values of every private, protected, and public member. What this means for your exception class, is that any properties it exposes should themselves be serializable. Should .NET attempt to serialize your class, and your class contains a member that cannot be...

TIP: Decorate Custom Exception Classes With the Serializable Attribute

When writing a custom Exception class, don’t forget to mark the class as Serializable? Why? If the exception is ever used in a remoting context, exceptions on the server are serialized and remoted back to the client proxy. The proxy then throws the exception on the client. By default, .NET types are not serializable. But by adding a simple Serializable attribute decoration on your class, .NET is able to serialize your exception. [Serializable] public class MyException : Exception { // Custom Code } Technorati Tags: Tips

Practice safe DateTime manipulation

What is the proper way to add three hours to a DateTime for the PST timezone? Is it this? DateTime d = DateTime.Parse("Oct 26, 2003 12:00:00 AM");d = d.AddHours(3.0); A valiant attempt, but wrong. Instead try this: DateTime d = DateTime.Parse("Oct 26, 2003 12:00:00 AM"); d = d.ToUniversalTime().AddHours(3.0).ToLocalTime(); // displays 10/26/2003 02:00:00 AM which is correct! Console.WriteLine(d); Why all the rigamarole of converting to universal time and back to local time? A little thing we like to call Daylight savings time. Without the conversion, adding three hours would have set the time to 3:00 AM which would be wrong. Realizing this probably would have saved me from many...